github.com/CanonicalLtd/go-sqlite3@v1.6.0/sqlite3-binding.c (about)

     1  #ifndef USE_LIBSQLITE3
     2  /******************************************************************************
     3  ** This file is an amalgamation of many separate C source files from SQLite
     4  ** version 3.21.0.  By combining all the individual C code files into this
     5  ** single large file, the entire code can be compiled as a single translation
     6  ** unit.  This allows many compilers to do optimizations that would not be
     7  ** possible if the files were compiled separately.  Performance improvements
     8  ** of 5% or more are commonly seen when SQLite is compiled as a single
     9  ** translation unit.
    10  **
    11  ** This file is all you need to compile SQLite.  To use SQLite in other
    12  ** programs, you need this file and the "sqlite3.h" header file that defines
    13  ** the programming interface to the SQLite library.  (If you do not have
    14  ** the "sqlite3.h" header file at hand, you will find a copy embedded within
    15  ** the text of this file.  Search for "Begin file sqlite3.h" to find the start
    16  ** of the embedded sqlite3.h header file.) Additional code files may be needed
    17  ** if you want a wrapper to interface SQLite with your choice of programming
    18  ** language. The code for the "sqlite3" command-line shell is also in a
    19  ** separate file. This file contains only code for the core SQLite library.
    20  */
    21  #define SQLITE_CORE 1
    22  #define SQLITE_AMALGAMATION 1
    23  #ifndef SQLITE_PRIVATE
    24  # define SQLITE_PRIVATE static
    25  #endif
    26  /************** Begin file ctime.c *******************************************/
    27  /*
    28  ** 2010 February 23
    29  **
    30  ** The author disclaims copyright to this source code.  In place of
    31  ** a legal notice, here is a blessing:
    32  **
    33  **    May you do good and not evil.
    34  **    May you find forgiveness for yourself and forgive others.
    35  **    May you share freely, never taking more than you give.
    36  **
    37  *************************************************************************
    38  **
    39  ** This file implements routines used to report what compile-time options
    40  ** SQLite was built with.
    41  */
    42  
    43  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
    44  
    45  /*
    46  ** Include the configuration header output by 'configure' if we're using the
    47  ** autoconf-based build
    48  */
    49  #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
    50  #include "config.h"
    51  #define SQLITECONFIG_H 1
    52  #endif
    53  
    54  /* These macros are provided to "stringify" the value of the define
    55  ** for those options in which the value is meaningful. */
    56  #define CTIMEOPT_VAL_(opt) #opt
    57  #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
    58  
    59  /*
    60  ** An array of names of all compile-time options.  This array should 
    61  ** be sorted A-Z.
    62  **
    63  ** This array looks large, but in a typical installation actually uses
    64  ** only a handful of compile-time options, so most times this array is usually
    65  ** rather short and uses little memory space.
    66  */
    67  static const char * const sqlite3azCompileOpt[] = {
    68  
    69  /* 
    70  ** BEGIN CODE GENERATED BY tool/mkctime.tcl 
    71  */
    72  #if SQLITE_32BIT_ROWID
    73    "32BIT_ROWID",
    74  #endif
    75  #if SQLITE_4_BYTE_ALIGNED_MALLOC
    76    "4_BYTE_ALIGNED_MALLOC",
    77  #endif
    78  #if SQLITE_64BIT_STATS
    79    "64BIT_STATS",
    80  #endif
    81  #if SQLITE_ALLOW_COVERING_INDEX_SCAN
    82    "ALLOW_COVERING_INDEX_SCAN",
    83  #endif
    84  #if SQLITE_ALLOW_URI_AUTHORITY
    85    "ALLOW_URI_AUTHORITY",
    86  #endif
    87  #ifdef SQLITE_BITMASK_TYPE
    88    "BITMASK_TYPE=" CTIMEOPT_VAL(SQLITE_BITMASK_TYPE),
    89  #endif
    90  #if SQLITE_BUG_COMPATIBLE_20160819
    91    "BUG_COMPATIBLE_20160819",
    92  #endif
    93  #if SQLITE_CASE_SENSITIVE_LIKE
    94    "CASE_SENSITIVE_LIKE",
    95  #endif
    96  #if SQLITE_CHECK_PAGES
    97    "CHECK_PAGES",
    98  #endif
    99  #if defined(__clang__) && defined(__clang_major__)
   100    "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
   101                      CTIMEOPT_VAL(__clang_minor__) "."
   102                      CTIMEOPT_VAL(__clang_patchlevel__),
   103  #elif defined(_MSC_VER)
   104    "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
   105  #elif defined(__GNUC__) && defined(__VERSION__)
   106    "COMPILER=gcc-" __VERSION__,
   107  #endif
   108  #if SQLITE_COVERAGE_TEST
   109    "COVERAGE_TEST",
   110  #endif
   111  #if SQLITE_DEBUG
   112    "DEBUG",
   113  #endif
   114  #if SQLITE_DEFAULT_AUTOMATIC_INDEX
   115    "DEFAULT_AUTOMATIC_INDEX",
   116  #endif
   117  #if SQLITE_DEFAULT_AUTOVACUUM
   118    "DEFAULT_AUTOVACUUM",
   119  #endif
   120  #ifdef SQLITE_DEFAULT_CACHE_SIZE
   121    "DEFAULT_CACHE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_CACHE_SIZE),
   122  #endif
   123  #if SQLITE_DEFAULT_CKPTFULLFSYNC
   124    "DEFAULT_CKPTFULLFSYNC",
   125  #endif
   126  #ifdef SQLITE_DEFAULT_FILE_FORMAT
   127    "DEFAULT_FILE_FORMAT=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_FORMAT),
   128  #endif
   129  #ifdef SQLITE_DEFAULT_FILE_PERMISSIONS
   130    "DEFAULT_FILE_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_PERMISSIONS),
   131  #endif
   132  #if SQLITE_DEFAULT_FOREIGN_KEYS
   133    "DEFAULT_FOREIGN_KEYS",
   134  #endif
   135  #ifdef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
   136    "DEFAULT_JOURNAL_SIZE_LIMIT=" CTIMEOPT_VAL(SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT),
   137  #endif
   138  #ifdef SQLITE_DEFAULT_LOCKING_MODE
   139    "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
   140  #endif
   141  #ifdef SQLITE_DEFAULT_LOOKASIDE
   142    "DEFAULT_LOOKASIDE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOOKASIDE),
   143  #endif
   144  #if SQLITE_DEFAULT_MEMSTATUS
   145    "DEFAULT_MEMSTATUS",
   146  #endif
   147  #ifdef SQLITE_DEFAULT_MMAP_SIZE
   148    "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
   149  #endif
   150  #ifdef SQLITE_DEFAULT_PAGE_SIZE
   151    "DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_PAGE_SIZE),
   152  #endif
   153  #ifdef SQLITE_DEFAULT_PCACHE_INITSZ
   154    "DEFAULT_PCACHE_INITSZ=" CTIMEOPT_VAL(SQLITE_DEFAULT_PCACHE_INITSZ),
   155  #endif
   156  #ifdef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
   157    "DEFAULT_PROXYDIR_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_PROXYDIR_PERMISSIONS),
   158  #endif
   159  #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
   160    "DEFAULT_RECURSIVE_TRIGGERS",
   161  #endif
   162  #ifdef SQLITE_DEFAULT_ROWEST
   163    "DEFAULT_ROWEST=" CTIMEOPT_VAL(SQLITE_DEFAULT_ROWEST),
   164  #endif
   165  #ifdef SQLITE_DEFAULT_SECTOR_SIZE
   166    "DEFAULT_SECTOR_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_SECTOR_SIZE),
   167  #endif
   168  #ifdef SQLITE_DEFAULT_SYNCHRONOUS
   169    "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS),
   170  #endif
   171  #ifdef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
   172    "DEFAULT_WAL_AUTOCHECKPOINT=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_AUTOCHECKPOINT),
   173  #endif
   174  #ifdef SQLITE_DEFAULT_WAL_SYNCHRONOUS
   175    "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS),
   176  #endif
   177  #ifdef SQLITE_DEFAULT_WORKER_THREADS
   178    "DEFAULT_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WORKER_THREADS),
   179  #endif
   180  #if SQLITE_DIRECT_OVERFLOW_READ
   181    "DIRECT_OVERFLOW_READ",
   182  #endif
   183  #if SQLITE_DISABLE_DIRSYNC
   184    "DISABLE_DIRSYNC",
   185  #endif
   186  #if SQLITE_DISABLE_FTS3_UNICODE
   187    "DISABLE_FTS3_UNICODE",
   188  #endif
   189  #if SQLITE_DISABLE_FTS4_DEFERRED
   190    "DISABLE_FTS4_DEFERRED",
   191  #endif
   192  #if SQLITE_DISABLE_INTRINSIC
   193    "DISABLE_INTRINSIC",
   194  #endif
   195  #if SQLITE_DISABLE_LFS
   196    "DISABLE_LFS",
   197  #endif
   198  #if SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
   199    "DISABLE_PAGECACHE_OVERFLOW_STATS",
   200  #endif
   201  #if SQLITE_DISABLE_SKIPAHEAD_DISTINCT
   202    "DISABLE_SKIPAHEAD_DISTINCT",
   203  #endif
   204  #ifdef SQLITE_ENABLE_8_3_NAMES
   205    "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
   206  #endif
   207  #if SQLITE_ENABLE_API_ARMOR
   208    "ENABLE_API_ARMOR",
   209  #endif
   210  #if SQLITE_ENABLE_ATOMIC_WRITE
   211    "ENABLE_ATOMIC_WRITE",
   212  #endif
   213  #if SQLITE_ENABLE_BATCH_ATOMIC_WRITE
   214    "ENABLE_BATCH_ATOMIC_WRITE",
   215  #endif
   216  #if SQLITE_ENABLE_CEROD
   217    "ENABLE_CEROD",
   218  #endif
   219  #if SQLITE_ENABLE_COLUMN_METADATA
   220    "ENABLE_COLUMN_METADATA",
   221  #endif
   222  #if SQLITE_ENABLE_COLUMN_USED_MASK
   223    "ENABLE_COLUMN_USED_MASK",
   224  #endif
   225  #if SQLITE_ENABLE_COSTMULT
   226    "ENABLE_COSTMULT",
   227  #endif
   228  #if SQLITE_ENABLE_CURSOR_HINTS
   229    "ENABLE_CURSOR_HINTS",
   230  #endif
   231  #if SQLITE_ENABLE_DBSTAT_VTAB
   232    "ENABLE_DBSTAT_VTAB",
   233  #endif
   234  #if SQLITE_ENABLE_EXPENSIVE_ASSERT
   235    "ENABLE_EXPENSIVE_ASSERT",
   236  #endif
   237  #if SQLITE_ENABLE_FTS1
   238    "ENABLE_FTS1",
   239  #endif
   240  #if SQLITE_ENABLE_FTS2
   241    "ENABLE_FTS2",
   242  #endif
   243  #if SQLITE_ENABLE_FTS3
   244    "ENABLE_FTS3",
   245  #endif
   246  #if SQLITE_ENABLE_FTS3_PARENTHESIS
   247    "ENABLE_FTS3_PARENTHESIS",
   248  #endif
   249  #if SQLITE_ENABLE_FTS3_TOKENIZER
   250    "ENABLE_FTS3_TOKENIZER",
   251  #endif
   252  #if SQLITE_ENABLE_FTS4
   253    "ENABLE_FTS4",
   254  #endif
   255  #if SQLITE_ENABLE_FTS5
   256    "ENABLE_FTS5",
   257  #endif
   258  #if SQLITE_ENABLE_HIDDEN_COLUMNS
   259    "ENABLE_HIDDEN_COLUMNS",
   260  #endif
   261  #if SQLITE_ENABLE_ICU
   262    "ENABLE_ICU",
   263  #endif
   264  #if SQLITE_ENABLE_IOTRACE
   265    "ENABLE_IOTRACE",
   266  #endif
   267  #if SQLITE_ENABLE_JSON1
   268    "ENABLE_JSON1",
   269  #endif
   270  #if SQLITE_ENABLE_LOAD_EXTENSION
   271    "ENABLE_LOAD_EXTENSION",
   272  #endif
   273  #ifdef SQLITE_ENABLE_LOCKING_STYLE
   274    "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
   275  #endif
   276  #if SQLITE_ENABLE_MEMORY_MANAGEMENT
   277    "ENABLE_MEMORY_MANAGEMENT",
   278  #endif
   279  #if SQLITE_ENABLE_MEMSYS3
   280    "ENABLE_MEMSYS3",
   281  #endif
   282  #if SQLITE_ENABLE_MEMSYS5
   283    "ENABLE_MEMSYS5",
   284  #endif
   285  #if SQLITE_ENABLE_MULTIPLEX
   286    "ENABLE_MULTIPLEX",
   287  #endif
   288  #if SQLITE_ENABLE_NULL_TRIM
   289    "ENABLE_NULL_TRIM",
   290  #endif
   291  #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
   292    "ENABLE_OVERSIZE_CELL_CHECK",
   293  #endif
   294  #if SQLITE_ENABLE_PREUPDATE_HOOK
   295    "ENABLE_PREUPDATE_HOOK",
   296  #endif
   297  #if SQLITE_ENABLE_QPSG
   298    "ENABLE_QPSG",
   299  #endif
   300  #if SQLITE_ENABLE_RBU
   301    "ENABLE_RBU",
   302  #endif
   303  #if SQLITE_ENABLE_RTREE
   304    "ENABLE_RTREE",
   305  #endif
   306  #if SQLITE_ENABLE_SELECTTRACE
   307    "ENABLE_SELECTTRACE",
   308  #endif
   309  #if SQLITE_ENABLE_SESSION
   310    "ENABLE_SESSION",
   311  #endif
   312  #if SQLITE_ENABLE_SNAPSHOT
   313    "ENABLE_SNAPSHOT",
   314  #endif
   315  #if SQLITE_ENABLE_SQLLOG
   316    "ENABLE_SQLLOG",
   317  #endif
   318  #if defined(SQLITE_ENABLE_STAT4)
   319    "ENABLE_STAT4",
   320  #elif defined(SQLITE_ENABLE_STAT3)
   321    "ENABLE_STAT3",
   322  #endif
   323  #if SQLITE_ENABLE_STMTVTAB
   324    "ENABLE_STMTVTAB",
   325  #endif
   326  #if SQLITE_ENABLE_STMT_SCANSTATUS
   327    "ENABLE_STMT_SCANSTATUS",
   328  #endif
   329  #if SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
   330    "ENABLE_UNKNOWN_SQL_FUNCTION",
   331  #endif
   332  #if SQLITE_ENABLE_UNLOCK_NOTIFY
   333    "ENABLE_UNLOCK_NOTIFY",
   334  #endif
   335  #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
   336    "ENABLE_UPDATE_DELETE_LIMIT",
   337  #endif
   338  #if SQLITE_ENABLE_URI_00_ERROR
   339    "ENABLE_URI_00_ERROR",
   340  #endif
   341  #if SQLITE_ENABLE_VFSTRACE
   342    "ENABLE_VFSTRACE",
   343  #endif
   344  #if SQLITE_ENABLE_WHERETRACE
   345    "ENABLE_WHERETRACE",
   346  #endif
   347  #if SQLITE_ENABLE_ZIPVFS
   348    "ENABLE_ZIPVFS",
   349  #endif
   350  #if SQLITE_EXPLAIN_ESTIMATED_ROWS
   351    "EXPLAIN_ESTIMATED_ROWS",
   352  #endif
   353  #if SQLITE_EXTRA_IFNULLROW
   354    "EXTRA_IFNULLROW",
   355  #endif
   356  #ifdef SQLITE_EXTRA_INIT
   357    "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT),
   358  #endif
   359  #ifdef SQLITE_EXTRA_SHUTDOWN
   360    "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN),
   361  #endif
   362  #ifdef SQLITE_FTS3_MAX_EXPR_DEPTH
   363    "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH),
   364  #endif
   365  #if SQLITE_FTS5_ENABLE_TEST_MI
   366    "FTS5_ENABLE_TEST_MI",
   367  #endif
   368  #if SQLITE_FTS5_NO_WITHOUT_ROWID
   369    "FTS5_NO_WITHOUT_ROWID",
   370  #endif
   371  #if SQLITE_HAS_CODEC
   372    "HAS_CODEC",
   373  #endif
   374  #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
   375    "HAVE_ISNAN",
   376  #endif
   377  #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   378    "HOMEGROWN_RECURSIVE_MUTEX",
   379  #endif
   380  #if SQLITE_IGNORE_AFP_LOCK_ERRORS
   381    "IGNORE_AFP_LOCK_ERRORS",
   382  #endif
   383  #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   384    "IGNORE_FLOCK_LOCK_ERRORS",
   385  #endif
   386  #if SQLITE_INLINE_MEMCPY
   387    "INLINE_MEMCPY",
   388  #endif
   389  #if SQLITE_INT64_TYPE
   390    "INT64_TYPE",
   391  #endif
   392  #ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX
   393    "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX),
   394  #endif
   395  #if SQLITE_LIKE_DOESNT_MATCH_BLOBS
   396    "LIKE_DOESNT_MATCH_BLOBS",
   397  #endif
   398  #if SQLITE_LOCK_TRACE
   399    "LOCK_TRACE",
   400  #endif
   401  #if SQLITE_LOG_CACHE_SPILL
   402    "LOG_CACHE_SPILL",
   403  #endif
   404  #ifdef SQLITE_MALLOC_SOFT_LIMIT
   405    "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT),
   406  #endif
   407  #ifdef SQLITE_MAX_ATTACHED
   408    "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED),
   409  #endif
   410  #ifdef SQLITE_MAX_COLUMN
   411    "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN),
   412  #endif
   413  #ifdef SQLITE_MAX_COMPOUND_SELECT
   414    "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT),
   415  #endif
   416  #ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE
   417    "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE),
   418  #endif
   419  #ifdef SQLITE_MAX_EXPR_DEPTH
   420    "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH),
   421  #endif
   422  #ifdef SQLITE_MAX_FUNCTION_ARG
   423    "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG),
   424  #endif
   425  #ifdef SQLITE_MAX_LENGTH
   426    "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH),
   427  #endif
   428  #ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH
   429    "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH),
   430  #endif
   431  #ifdef SQLITE_MAX_MEMORY
   432    "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY),
   433  #endif
   434  #ifdef SQLITE_MAX_MMAP_SIZE
   435    "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
   436  #endif
   437  #ifdef SQLITE_MAX_MMAP_SIZE_
   438    "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_),
   439  #endif
   440  #ifdef SQLITE_MAX_PAGE_COUNT
   441    "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),
   442  #endif
   443  #ifdef SQLITE_MAX_PAGE_SIZE
   444    "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),
   445  #endif
   446  #ifdef SQLITE_MAX_SCHEMA_RETRY
   447    "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
   448  #endif
   449  #ifdef SQLITE_MAX_SQL_LENGTH
   450    "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),
   451  #endif
   452  #ifdef SQLITE_MAX_TRIGGER_DEPTH
   453    "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH),
   454  #endif
   455  #ifdef SQLITE_MAX_VARIABLE_NUMBER
   456    "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER),
   457  #endif
   458  #ifdef SQLITE_MAX_VDBE_OP
   459    "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP),
   460  #endif
   461  #ifdef SQLITE_MAX_WORKER_THREADS
   462    "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS),
   463  #endif
   464  #if SQLITE_MEMDEBUG
   465    "MEMDEBUG",
   466  #endif
   467  #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
   468    "MIXED_ENDIAN_64BIT_FLOAT",
   469  #endif
   470  #if SQLITE_MMAP_READWRITE
   471    "MMAP_READWRITE",
   472  #endif
   473  #if SQLITE_MUTEX_NOOP
   474    "MUTEX_NOOP",
   475  #endif
   476  #if SQLITE_MUTEX_NREF
   477    "MUTEX_NREF",
   478  #endif
   479  #if SQLITE_MUTEX_OMIT
   480    "MUTEX_OMIT",
   481  #endif
   482  #if SQLITE_MUTEX_PTHREADS
   483    "MUTEX_PTHREADS",
   484  #endif
   485  #if SQLITE_MUTEX_W32
   486    "MUTEX_W32",
   487  #endif
   488  #if SQLITE_NEED_ERR_NAME
   489    "NEED_ERR_NAME",
   490  #endif
   491  #if SQLITE_NOINLINE
   492    "NOINLINE",
   493  #endif
   494  #if SQLITE_NO_SYNC
   495    "NO_SYNC",
   496  #endif
   497  #if SQLITE_OMIT_ALTERTABLE
   498    "OMIT_ALTERTABLE",
   499  #endif
   500  #if SQLITE_OMIT_ANALYZE
   501    "OMIT_ANALYZE",
   502  #endif
   503  #if SQLITE_OMIT_ATTACH
   504    "OMIT_ATTACH",
   505  #endif
   506  #if SQLITE_OMIT_AUTHORIZATION
   507    "OMIT_AUTHORIZATION",
   508  #endif
   509  #if SQLITE_OMIT_AUTOINCREMENT
   510    "OMIT_AUTOINCREMENT",
   511  #endif
   512  #if SQLITE_OMIT_AUTOINIT
   513    "OMIT_AUTOINIT",
   514  #endif
   515  #if SQLITE_OMIT_AUTOMATIC_INDEX
   516    "OMIT_AUTOMATIC_INDEX",
   517  #endif
   518  #if SQLITE_OMIT_AUTORESET
   519    "OMIT_AUTORESET",
   520  #endif
   521  #if SQLITE_OMIT_AUTOVACUUM
   522    "OMIT_AUTOVACUUM",
   523  #endif
   524  #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
   525    "OMIT_BETWEEN_OPTIMIZATION",
   526  #endif
   527  #if SQLITE_OMIT_BLOB_LITERAL
   528    "OMIT_BLOB_LITERAL",
   529  #endif
   530  #if SQLITE_OMIT_BTREECOUNT
   531    "OMIT_BTREECOUNT",
   532  #endif
   533  #if SQLITE_OMIT_CAST
   534    "OMIT_CAST",
   535  #endif
   536  #if SQLITE_OMIT_CHECK
   537    "OMIT_CHECK",
   538  #endif
   539  #if SQLITE_OMIT_COMPLETE
   540    "OMIT_COMPLETE",
   541  #endif
   542  #if SQLITE_OMIT_COMPOUND_SELECT
   543    "OMIT_COMPOUND_SELECT",
   544  #endif
   545  #if SQLITE_OMIT_CONFLICT_CLAUSE
   546    "OMIT_CONFLICT_CLAUSE",
   547  #endif
   548  #if SQLITE_OMIT_CTE
   549    "OMIT_CTE",
   550  #endif
   551  #if SQLITE_OMIT_DATETIME_FUNCS
   552    "OMIT_DATETIME_FUNCS",
   553  #endif
   554  #if SQLITE_OMIT_DECLTYPE
   555    "OMIT_DECLTYPE",
   556  #endif
   557  #if SQLITE_OMIT_DEPRECATED
   558    "OMIT_DEPRECATED",
   559  #endif
   560  #if SQLITE_OMIT_DISKIO
   561    "OMIT_DISKIO",
   562  #endif
   563  #if SQLITE_OMIT_EXPLAIN
   564    "OMIT_EXPLAIN",
   565  #endif
   566  #if SQLITE_OMIT_FLAG_PRAGMAS
   567    "OMIT_FLAG_PRAGMAS",
   568  #endif
   569  #if SQLITE_OMIT_FLOATING_POINT
   570    "OMIT_FLOATING_POINT",
   571  #endif
   572  #if SQLITE_OMIT_FOREIGN_KEY
   573    "OMIT_FOREIGN_KEY",
   574  #endif
   575  #if SQLITE_OMIT_GET_TABLE
   576    "OMIT_GET_TABLE",
   577  #endif
   578  #if SQLITE_OMIT_HEX_INTEGER
   579    "OMIT_HEX_INTEGER",
   580  #endif
   581  #if SQLITE_OMIT_INCRBLOB
   582    "OMIT_INCRBLOB",
   583  #endif
   584  #if SQLITE_OMIT_INTEGRITY_CHECK
   585    "OMIT_INTEGRITY_CHECK",
   586  #endif
   587  #if SQLITE_OMIT_LIKE_OPTIMIZATION
   588    "OMIT_LIKE_OPTIMIZATION",
   589  #endif
   590  #if SQLITE_OMIT_LOAD_EXTENSION
   591    "OMIT_LOAD_EXTENSION",
   592  #endif
   593  #if SQLITE_OMIT_LOCALTIME
   594    "OMIT_LOCALTIME",
   595  #endif
   596  #if SQLITE_OMIT_LOOKASIDE
   597    "OMIT_LOOKASIDE",
   598  #endif
   599  #if SQLITE_OMIT_MEMORYDB
   600    "OMIT_MEMORYDB",
   601  #endif
   602  #if SQLITE_OMIT_OR_OPTIMIZATION
   603    "OMIT_OR_OPTIMIZATION",
   604  #endif
   605  #if SQLITE_OMIT_PAGER_PRAGMAS
   606    "OMIT_PAGER_PRAGMAS",
   607  #endif
   608  #if SQLITE_OMIT_PARSER_TRACE
   609    "OMIT_PARSER_TRACE",
   610  #endif
   611  #if SQLITE_OMIT_POPEN
   612    "OMIT_POPEN",
   613  #endif
   614  #if SQLITE_OMIT_PRAGMA
   615    "OMIT_PRAGMA",
   616  #endif
   617  #if SQLITE_OMIT_PROGRESS_CALLBACK
   618    "OMIT_PROGRESS_CALLBACK",
   619  #endif
   620  #if SQLITE_OMIT_QUICKBALANCE
   621    "OMIT_QUICKBALANCE",
   622  #endif
   623  #if SQLITE_OMIT_REINDEX
   624    "OMIT_REINDEX",
   625  #endif
   626  #if SQLITE_OMIT_SCHEMA_PRAGMAS
   627    "OMIT_SCHEMA_PRAGMAS",
   628  #endif
   629  #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
   630    "OMIT_SCHEMA_VERSION_PRAGMAS",
   631  #endif
   632  #if SQLITE_OMIT_SHARED_CACHE
   633    "OMIT_SHARED_CACHE",
   634  #endif
   635  #if SQLITE_OMIT_SHUTDOWN_DIRECTORIES
   636    "OMIT_SHUTDOWN_DIRECTORIES",
   637  #endif
   638  #if SQLITE_OMIT_SUBQUERY
   639    "OMIT_SUBQUERY",
   640  #endif
   641  #if SQLITE_OMIT_TCL_VARIABLE
   642    "OMIT_TCL_VARIABLE",
   643  #endif
   644  #if SQLITE_OMIT_TEMPDB
   645    "OMIT_TEMPDB",
   646  #endif
   647  #if SQLITE_OMIT_TEST_CONTROL
   648    "OMIT_TEST_CONTROL",
   649  #endif
   650  #if SQLITE_OMIT_TRACE
   651    "OMIT_TRACE",
   652  #endif
   653  #if SQLITE_OMIT_TRIGGER
   654    "OMIT_TRIGGER",
   655  #endif
   656  #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
   657    "OMIT_TRUNCATE_OPTIMIZATION",
   658  #endif
   659  #if SQLITE_OMIT_UTF16
   660    "OMIT_UTF16",
   661  #endif
   662  #if SQLITE_OMIT_VACUUM
   663    "OMIT_VACUUM",
   664  #endif
   665  #if SQLITE_OMIT_VIEW
   666    "OMIT_VIEW",
   667  #endif
   668  #if SQLITE_OMIT_VIRTUALTABLE
   669    "OMIT_VIRTUALTABLE",
   670  #endif
   671  #if SQLITE_OMIT_WAL
   672    "OMIT_WAL",
   673  #endif
   674  #if SQLITE_OMIT_WSD
   675    "OMIT_WSD",
   676  #endif
   677  #if SQLITE_OMIT_XFER_OPT
   678    "OMIT_XFER_OPT",
   679  #endif
   680  #if SQLITE_PCACHE_SEPARATE_HEADER
   681    "PCACHE_SEPARATE_HEADER",
   682  #endif
   683  #if SQLITE_PERFORMANCE_TRACE
   684    "PERFORMANCE_TRACE",
   685  #endif
   686  #if SQLITE_POWERSAFE_OVERWRITE
   687    "POWERSAFE_OVERWRITE",
   688  #endif
   689  #if SQLITE_PREFER_PROXY_LOCKING
   690    "PREFER_PROXY_LOCKING",
   691  #endif
   692  #if SQLITE_PROXY_DEBUG
   693    "PROXY_DEBUG",
   694  #endif
   695  #if SQLITE_REVERSE_UNORDERED_SELECTS
   696    "REVERSE_UNORDERED_SELECTS",
   697  #endif
   698  #if SQLITE_RTREE_INT_ONLY
   699    "RTREE_INT_ONLY",
   700  #endif
   701  #if SQLITE_SECURE_DELETE
   702    "SECURE_DELETE",
   703  #endif
   704  #if SQLITE_SMALL_STACK
   705    "SMALL_STACK",
   706  #endif
   707  #ifdef SQLITE_SORTER_PMASZ
   708    "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ),
   709  #endif
   710  #if SQLITE_SOUNDEX
   711    "SOUNDEX",
   712  #endif
   713  #ifdef SQLITE_STAT4_SAMPLES
   714    "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES),
   715  #endif
   716  #ifdef SQLITE_STMTJRNL_SPILL
   717    "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL),
   718  #endif
   719  #if SQLITE_SUBSTR_COMPATIBILITY
   720    "SUBSTR_COMPATIBILITY",
   721  #endif
   722  #if SQLITE_SYSTEM_MALLOC
   723    "SYSTEM_MALLOC",
   724  #endif
   725  #if SQLITE_TCL
   726    "TCL",
   727  #endif
   728  #ifdef SQLITE_TEMP_STORE
   729    "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
   730  #endif
   731  #if SQLITE_TEST
   732    "TEST",
   733  #endif
   734  #if defined(SQLITE_THREADSAFE)
   735    "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
   736  #elif defined(THREADSAFE)
   737    "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE),
   738  #else
   739    "THREADSAFE=1",
   740  #endif
   741  #if SQLITE_UNLINK_AFTER_CLOSE
   742    "UNLINK_AFTER_CLOSE",
   743  #endif
   744  #if SQLITE_UNTESTABLE
   745    "UNTESTABLE",
   746  #endif
   747  #if SQLITE_USER_AUTHENTICATION
   748    "USER_AUTHENTICATION",
   749  #endif
   750  #if SQLITE_USE_ALLOCA
   751    "USE_ALLOCA",
   752  #endif
   753  #if SQLITE_USE_FCNTL_TRACE
   754    "USE_FCNTL_TRACE",
   755  #endif
   756  #if SQLITE_USE_URI
   757    "USE_URI",
   758  #endif
   759  #if SQLITE_VDBE_COVERAGE
   760    "VDBE_COVERAGE",
   761  #endif
   762  #if SQLITE_WIN32_MALLOC
   763    "WIN32_MALLOC",
   764  #endif
   765  #if SQLITE_ZERO_MALLOC
   766    "ZERO_MALLOC",
   767  #endif
   768  /* 
   769  ** END CODE GENERATED BY tool/mkctime.tcl 
   770  */
   771  };
   772  
   773  SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){
   774    *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]);
   775    return (const char**)sqlite3azCompileOpt;
   776  }
   777  
   778  #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   779  
   780  /************** End of ctime.c ***********************************************/
   781  /************** Begin file sqliteInt.h ***************************************/
   782  /*
   783  ** 2001 September 15
   784  **
   785  ** The author disclaims copyright to this source code.  In place of
   786  ** a legal notice, here is a blessing:
   787  **
   788  **    May you do good and not evil.
   789  **    May you find forgiveness for yourself and forgive others.
   790  **    May you share freely, never taking more than you give.
   791  **
   792  *************************************************************************
   793  ** Internal interface definitions for SQLite.
   794  **
   795  */
   796  #ifndef SQLITEINT_H
   797  #define SQLITEINT_H
   798  
   799  /* Special Comments:
   800  **
   801  ** Some comments have special meaning to the tools that measure test
   802  ** coverage:
   803  **
   804  **    NO_TEST                     - The branches on this line are not
   805  **                                  measured by branch coverage.  This is
   806  **                                  used on lines of code that actually
   807  **                                  implement parts of coverage testing.
   808  **
   809  **    OPTIMIZATION-IF-TRUE        - This branch is allowed to alway be false
   810  **                                  and the correct answer is still obtained,
   811  **                                  though perhaps more slowly.
   812  **
   813  **    OPTIMIZATION-IF-FALSE       - This branch is allowed to alway be true
   814  **                                  and the correct answer is still obtained,
   815  **                                  though perhaps more slowly.
   816  **
   817  **    PREVENTS-HARMLESS-OVERREAD  - This branch prevents a buffer overread
   818  **                                  that would be harmless and undetectable
   819  **                                  if it did occur.  
   820  **
   821  ** In all cases, the special comment must be enclosed in the usual
   822  ** slash-asterisk...asterisk-slash comment marks, with no spaces between the 
   823  ** asterisks and the comment text.
   824  */
   825  
   826  /*
   827  ** Make sure the Tcl calling convention macro is defined.  This macro is
   828  ** only used by test code and Tcl integration code.
   829  */
   830  #ifndef SQLITE_TCLAPI
   831  #  define SQLITE_TCLAPI
   832  #endif
   833  
   834  /*
   835  ** Include the header file used to customize the compiler options for MSVC.
   836  ** This should be done first so that it can successfully prevent spurious
   837  ** compiler warnings due to subsequent content in this file and other files
   838  ** that are included by this file.
   839  */
   840  /************** Include msvc.h in the middle of sqliteInt.h ******************/
   841  /************** Begin file msvc.h ********************************************/
   842  /*
   843  ** 2015 January 12
   844  **
   845  ** The author disclaims copyright to this source code.  In place of
   846  ** a legal notice, here is a blessing:
   847  **
   848  **    May you do good and not evil.
   849  **    May you find forgiveness for yourself and forgive others.
   850  **    May you share freely, never taking more than you give.
   851  **
   852  ******************************************************************************
   853  **
   854  ** This file contains code that is specific to MSVC.
   855  */
   856  #ifndef SQLITE_MSVC_H
   857  #define SQLITE_MSVC_H
   858  
   859  #if defined(_MSC_VER)
   860  #pragma warning(disable : 4054)
   861  #pragma warning(disable : 4055)
   862  #pragma warning(disable : 4100)
   863  #pragma warning(disable : 4127)
   864  #pragma warning(disable : 4130)
   865  #pragma warning(disable : 4152)
   866  #pragma warning(disable : 4189)
   867  #pragma warning(disable : 4206)
   868  #pragma warning(disable : 4210)
   869  #pragma warning(disable : 4232)
   870  #pragma warning(disable : 4244)
   871  #pragma warning(disable : 4305)
   872  #pragma warning(disable : 4306)
   873  #pragma warning(disable : 4702)
   874  #pragma warning(disable : 4706)
   875  #endif /* defined(_MSC_VER) */
   876  
   877  #endif /* SQLITE_MSVC_H */
   878  
   879  /************** End of msvc.h ************************************************/
   880  /************** Continuing where we left off in sqliteInt.h ******************/
   881  
   882  /*
   883  ** Special setup for VxWorks
   884  */
   885  /************** Include vxworks.h in the middle of sqliteInt.h ***************/
   886  /************** Begin file vxworks.h *****************************************/
   887  /*
   888  ** 2015-03-02
   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 Wind River's VxWorks
   900  */
   901  #if defined(__RTP__) || defined(_WRS_KERNEL)
   902  /* This is VxWorks.  Set up things specially for that OS
   903  */
   904  #include <vxWorks.h>
   905  #include <pthread.h>  /* amalgamator: dontcache */
   906  #define OS_VXWORKS 1
   907  #define SQLITE_OS_OTHER 0
   908  #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
   909  #define SQLITE_OMIT_LOAD_EXTENSION 1
   910  #define SQLITE_ENABLE_LOCKING_STYLE 0
   911  #define HAVE_UTIME 1
   912  #else
   913  /* This is not VxWorks. */
   914  #define OS_VXWORKS 0
   915  #define HAVE_FCHOWN 1
   916  #define HAVE_READLINK 1
   917  #define HAVE_LSTAT 1
   918  #endif /* defined(_WRS_KERNEL) */
   919  
   920  /************** End of vxworks.h *********************************************/
   921  /************** Continuing where we left off in sqliteInt.h ******************/
   922  
   923  /*
   924  ** These #defines should enable >2GB file support on POSIX if the
   925  ** underlying operating system supports it.  If the OS lacks
   926  ** large file support, or if the OS is windows, these should be no-ops.
   927  **
   928  ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
   929  ** system #includes.  Hence, this block of code must be the very first
   930  ** code in all source files.
   931  **
   932  ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
   933  ** on the compiler command line.  This is necessary if you are compiling
   934  ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
   935  ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
   936  ** without this option, LFS is enable.  But LFS does not exist in the kernel
   937  ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
   938  ** portability you should omit LFS.
   939  **
   940  ** The previous paragraph was written in 2005.  (This paragraph is written
   941  ** on 2008-11-28.) These days, all Linux kernels support large files, so
   942  ** you should probably leave LFS enabled.  But some embedded platforms might
   943  ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
   944  **
   945  ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
   946  */
   947  #ifndef SQLITE_DISABLE_LFS
   948  # define _LARGE_FILE       1
   949  # ifndef _FILE_OFFSET_BITS
   950  #   define _FILE_OFFSET_BITS 64
   951  # endif
   952  # define _LARGEFILE_SOURCE 1
   953  #endif
   954  
   955  /* The GCC_VERSION and MSVC_VERSION macros are used to
   956  ** conditionally include optimizations for each of these compilers.  A
   957  ** value of 0 means that compiler is not being used.  The
   958  ** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
   959  ** optimizations, and hence set all compiler macros to 0
   960  **
   961  ** There was once also a CLANG_VERSION macro.  However, we learn that the
   962  ** version numbers in clang are for "marketing" only and are inconsistent
   963  ** and unreliable.  Fortunately, all versions of clang also recognize the
   964  ** gcc version numbers and have reasonable settings for gcc version numbers,
   965  ** so the GCC_VERSION macro will be set to a correct non-zero value even
   966  ** when compiling with clang.
   967  */
   968  #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
   969  # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
   970  #else
   971  # define GCC_VERSION 0
   972  #endif
   973  #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
   974  # define MSVC_VERSION _MSC_VER
   975  #else
   976  # define MSVC_VERSION 0
   977  #endif
   978  
   979  /* Needed for various definitions... */
   980  #if defined(__GNUC__) && !defined(_GNU_SOURCE)
   981  # define _GNU_SOURCE
   982  #endif
   983  
   984  #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
   985  # define _BSD_SOURCE
   986  #endif
   987  
   988  /*
   989  ** For MinGW, check to see if we can include the header file containing its
   990  ** version information, among other things.  Normally, this internal MinGW
   991  ** header file would [only] be included automatically by other MinGW header
   992  ** files; however, the contained version information is now required by this
   993  ** header file to work around binary compatibility issues (see below) and
   994  ** this is the only known way to reliably obtain it.  This entire #if block
   995  ** would be completely unnecessary if there was any other way of detecting
   996  ** MinGW via their preprocessor (e.g. if they customized their GCC to define
   997  ** some MinGW-specific macros).  When compiling for MinGW, either the
   998  ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
   999  ** defined; otherwise, detection of conditions specific to MinGW will be
  1000  ** disabled.
  1001  */
  1002  #if defined(_HAVE_MINGW_H)
  1003  # include "mingw.h"
  1004  #elif defined(_HAVE__MINGW_H)
  1005  # include "_mingw.h"
  1006  #endif
  1007  
  1008  /*
  1009  ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
  1010  ** define is required to maintain binary compatibility with the MSVC runtime
  1011  ** library in use (e.g. for Windows XP).
  1012  */
  1013  #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
  1014      defined(_WIN32) && !defined(_WIN64) && \
  1015      defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
  1016      defined(__MSVCRT__)
  1017  # define _USE_32BIT_TIME_T
  1018  #endif
  1019  
  1020  /* The public SQLite interface.  The _FILE_OFFSET_BITS macro must appear
  1021  ** first in QNX.  Also, the _USE_32BIT_TIME_T macro must appear first for
  1022  ** MinGW.
  1023  */
  1024  /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  1025  /************** Begin file sqlite3.h *****************************************/
  1026  /*
  1027  ** 2001-09-15
  1028  **
  1029  ** The author disclaims copyright to this source code.  In place of
  1030  ** a legal notice, here is a blessing:
  1031  **
  1032  **    May you do good and not evil.
  1033  **    May you find forgiveness for yourself and forgive others.
  1034  **    May you share freely, never taking more than you give.
  1035  **
  1036  *************************************************************************
  1037  ** This header file defines the interface that the SQLite library
  1038  ** presents to client programs.  If a C-function, structure, datatype,
  1039  ** or constant definition does not appear in this file, then it is
  1040  ** not a published API of SQLite, is subject to change without
  1041  ** notice, and should not be referenced by programs that use SQLite.
  1042  **
  1043  ** Some of the definitions that are in this file are marked as
  1044  ** "experimental".  Experimental interfaces are normally new
  1045  ** features recently added to SQLite.  We do not anticipate changes
  1046  ** to experimental interfaces but reserve the right to make minor changes
  1047  ** if experience from use "in the wild" suggest such changes are prudent.
  1048  **
  1049  ** The official C-language API documentation for SQLite is derived
  1050  ** from comments in this file.  This file is the authoritative source
  1051  ** on how SQLite interfaces are supposed to operate.
  1052  **
  1053  ** The name of this file under configuration management is "sqlite.h.in".
  1054  ** The makefile makes some minor changes to this file (such as inserting
  1055  ** the version number) and changes its name to "sqlite3.h" as
  1056  ** part of the build process.
  1057  */
  1058  #ifndef SQLITE3_H
  1059  #define SQLITE3_H
  1060  #include <stdarg.h>     /* Needed for the definition of va_list */
  1061  
  1062  /*
  1063  ** Make sure we can call this stuff from C++.
  1064  */
  1065  #if 0
  1066  extern "C" {
  1067  #endif
  1068  
  1069  
  1070  /*
  1071  ** Provide the ability to override linkage features of the interface.
  1072  */
  1073  #ifndef SQLITE_EXTERN
  1074  # define SQLITE_EXTERN extern
  1075  #endif
  1076  #ifndef SQLITE_API
  1077  # define SQLITE_API
  1078  #endif
  1079  #ifndef SQLITE_CDECL
  1080  # define SQLITE_CDECL
  1081  #endif
  1082  #ifndef SQLITE_APICALL
  1083  # define SQLITE_APICALL
  1084  #endif
  1085  #ifndef SQLITE_STDCALL
  1086  # define SQLITE_STDCALL SQLITE_APICALL
  1087  #endif
  1088  #ifndef SQLITE_CALLBACK
  1089  # define SQLITE_CALLBACK
  1090  #endif
  1091  #ifndef SQLITE_SYSAPI
  1092  # define SQLITE_SYSAPI
  1093  #endif
  1094  
  1095  /*
  1096  ** These no-op macros are used in front of interfaces to mark those
  1097  ** interfaces as either deprecated or experimental.  New applications
  1098  ** should not use deprecated interfaces - they are supported for backwards
  1099  ** compatibility only.  Application writers should be aware that
  1100  ** experimental interfaces are subject to change in point releases.
  1101  **
  1102  ** These macros used to resolve to various kinds of compiler magic that
  1103  ** would generate warning messages when they were used.  But that
  1104  ** compiler magic ended up generating such a flurry of bug reports
  1105  ** that we have taken it all out and gone back to using simple
  1106  ** noop macros.
  1107  */
  1108  #define SQLITE_DEPRECATED
  1109  #define SQLITE_EXPERIMENTAL
  1110  
  1111  /*
  1112  ** Ensure these symbols were not defined by some previous header file.
  1113  */
  1114  #ifdef SQLITE_VERSION
  1115  # undef SQLITE_VERSION
  1116  #endif
  1117  #ifdef SQLITE_VERSION_NUMBER
  1118  # undef SQLITE_VERSION_NUMBER
  1119  #endif
  1120  
  1121  /*
  1122  ** CAPI3REF: Compile-Time Library Version Numbers
  1123  **
  1124  ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  1125  ** evaluates to a string literal that is the SQLite version in the
  1126  ** format "X.Y.Z" where X is the major version number (always 3 for
  1127  ** SQLite3) and Y is the minor version number and Z is the release number.)^
  1128  ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  1129  ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  1130  ** numbers used in [SQLITE_VERSION].)^
  1131  ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  1132  ** be larger than the release from which it is derived.  Either Y will
  1133  ** be held constant and Z will be incremented or else Y will be incremented
  1134  ** and Z will be reset to zero.
  1135  **
  1136  ** Since [version 3.6.18] ([dateof:3.6.18]), 
  1137  ** SQLite source code has been stored in the
  1138  ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  1139  ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
  1140  ** a string which identifies a particular check-in of SQLite
  1141  ** within its configuration management system.  ^The SQLITE_SOURCE_ID
  1142  ** string contains the date and time of the check-in (UTC) and a SHA1
  1143  ** or SHA3-256 hash of the entire source tree.  If the source code has
  1144  ** been edited in any way since it was last checked in, then the last
  1145  ** four hexadecimal digits of the hash may be modified.
  1146  **
  1147  ** See also: [sqlite3_libversion()],
  1148  ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  1149  ** [sqlite_version()] and [sqlite_source_id()].
  1150  */
  1151  #define SQLITE_VERSION        "3.21.0"
  1152  #define SQLITE_VERSION_NUMBER 3021000
  1153  #define SQLITE_SOURCE_ID      "2017-10-24 18:55:49 1a584e499906b5c87ec7d43d4abce641fdf017c42125b083109bc77c4de48827"
  1154  
  1155  /*
  1156  ** CAPI3REF: Run-Time Library Version Numbers
  1157  ** KEYWORDS: sqlite3_version sqlite3_sourceid
  1158  **
  1159  ** These interfaces provide the same information as the [SQLITE_VERSION],
  1160  ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  1161  ** but are associated with the library instead of the header file.  ^(Cautious
  1162  ** programmers might include assert() statements in their application to
  1163  ** verify that values returned by these interfaces match the macros in
  1164  ** the header, and thus ensure that the application is
  1165  ** compiled with matching library and header files.
  1166  **
  1167  ** <blockquote><pre>
  1168  ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  1169  ** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );
  1170  ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  1171  ** </pre></blockquote>)^
  1172  **
  1173  ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  1174  ** macro.  ^The sqlite3_libversion() function returns a pointer to the
  1175  ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
  1176  ** function is provided for use in DLLs since DLL users usually do not have
  1177  ** direct access to string constants within the DLL.  ^The
  1178  ** sqlite3_libversion_number() function returns an integer equal to
  1179  ** [SQLITE_VERSION_NUMBER].  ^(The sqlite3_sourceid() function returns 
  1180  ** a pointer to a string constant whose value is the same as the 
  1181  ** [SQLITE_SOURCE_ID] C preprocessor macro.  Except if SQLite is built
  1182  ** using an edited copy of [the amalgamation], then the last four characters
  1183  ** of the hash might be different from [SQLITE_SOURCE_ID].)^
  1184  **
  1185  ** See also: [sqlite_version()] and [sqlite_source_id()].
  1186  */
  1187  SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  1188  SQLITE_API const char *sqlite3_libversion(void);
  1189  SQLITE_API const char *sqlite3_sourceid(void);
  1190  SQLITE_API int sqlite3_libversion_number(void);
  1191  
  1192  /*
  1193  ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  1194  **
  1195  ** ^The sqlite3_compileoption_used() function returns 0 or 1 
  1196  ** indicating whether the specified option was defined at 
  1197  ** compile time.  ^The SQLITE_ prefix may be omitted from the 
  1198  ** option name passed to sqlite3_compileoption_used().  
  1199  **
  1200  ** ^The sqlite3_compileoption_get() function allows iterating
  1201  ** over the list of options that were defined at compile time by
  1202  ** returning the N-th compile time option string.  ^If N is out of range,
  1203  ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
  1204  ** prefix is omitted from any strings returned by 
  1205  ** sqlite3_compileoption_get().
  1206  **
  1207  ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  1208  ** and sqlite3_compileoption_get() may be omitted by specifying the 
  1209  ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  1210  **
  1211  ** See also: SQL functions [sqlite_compileoption_used()] and
  1212  ** [sqlite_compileoption_get()] and the [compile_options pragma].
  1213  */
  1214  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  1215  SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
  1216  SQLITE_API const char *sqlite3_compileoption_get(int N);
  1217  #endif
  1218  
  1219  /*
  1220  ** CAPI3REF: Test To See If The Library Is Threadsafe
  1221  **
  1222  ** ^The sqlite3_threadsafe() function returns zero if and only if
  1223  ** SQLite was compiled with mutexing code omitted due to the
  1224  ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  1225  **
  1226  ** SQLite can be compiled with or without mutexes.  When
  1227  ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  1228  ** are enabled and SQLite is threadsafe.  When the
  1229  ** [SQLITE_THREADSAFE] macro is 0, 
  1230  ** the mutexes are omitted.  Without the mutexes, it is not safe
  1231  ** to use SQLite concurrently from more than one thread.
  1232  **
  1233  ** Enabling mutexes incurs a measurable performance penalty.
  1234  ** So if speed is of utmost importance, it makes sense to disable
  1235  ** the mutexes.  But for maximum safety, mutexes should be enabled.
  1236  ** ^The default behavior is for mutexes to be enabled.
  1237  **
  1238  ** This interface can be used by an application to make sure that the
  1239  ** version of SQLite that it is linking against was compiled with
  1240  ** the desired setting of the [SQLITE_THREADSAFE] macro.
  1241  **
  1242  ** This interface only reports on the compile-time mutex setting
  1243  ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
  1244  ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  1245  ** can be fully or partially disabled using a call to [sqlite3_config()]
  1246  ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  1247  ** or [SQLITE_CONFIG_SERIALIZED].  ^(The return value of the
  1248  ** sqlite3_threadsafe() function shows only the compile-time setting of
  1249  ** thread safety, not any run-time changes to that setting made by
  1250  ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  1251  ** is unchanged by calls to sqlite3_config().)^
  1252  **
  1253  ** See the [threading mode] documentation for additional information.
  1254  */
  1255  SQLITE_API int sqlite3_threadsafe(void);
  1256  
  1257  /*
  1258  ** CAPI3REF: Database Connection Handle
  1259  ** KEYWORDS: {database connection} {database connections}
  1260  **
  1261  ** Each open SQLite database is represented by a pointer to an instance of
  1262  ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
  1263  ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
  1264  ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  1265  ** and [sqlite3_close_v2()] are its destructors.  There are many other
  1266  ** interfaces (such as
  1267  ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  1268  ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  1269  ** sqlite3 object.
  1270  */
  1271  typedef struct sqlite3 sqlite3;
  1272  
  1273  /*
  1274  ** CAPI3REF: 64-Bit Integer Types
  1275  ** KEYWORDS: sqlite_int64 sqlite_uint64
  1276  **
  1277  ** Because there is no cross-platform way to specify 64-bit integer types
  1278  ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  1279  **
  1280  ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  1281  ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  1282  ** compatibility only.
  1283  **
  1284  ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  1285  ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
  1286  ** sqlite3_uint64 and sqlite_uint64 types can store integer values 
  1287  ** between 0 and +18446744073709551615 inclusive.
  1288  */
  1289  #ifdef SQLITE_INT64_TYPE
  1290    typedef SQLITE_INT64_TYPE sqlite_int64;
  1291  # ifdef SQLITE_UINT64_TYPE
  1292      typedef SQLITE_UINT64_TYPE sqlite_uint64;
  1293  # else  
  1294      typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  1295  # endif
  1296  #elif defined(_MSC_VER) || defined(__BORLANDC__)
  1297    typedef __int64 sqlite_int64;
  1298    typedef unsigned __int64 sqlite_uint64;
  1299  #else
  1300    typedef long long int sqlite_int64;
  1301    typedef unsigned long long int sqlite_uint64;
  1302  #endif
  1303  typedef sqlite_int64 sqlite3_int64;
  1304  typedef sqlite_uint64 sqlite3_uint64;
  1305  
  1306  /*
  1307  ** If compiling for a processor that lacks floating point support,
  1308  ** substitute integer for floating-point.
  1309  */
  1310  #ifdef SQLITE_OMIT_FLOATING_POINT
  1311  # define double sqlite3_int64
  1312  #endif
  1313  
  1314  /*
  1315  ** CAPI3REF: Closing A Database Connection
  1316  ** DESTRUCTOR: sqlite3
  1317  **
  1318  ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  1319  ** for the [sqlite3] object.
  1320  ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
  1321  ** the [sqlite3] object is successfully destroyed and all associated
  1322  ** resources are deallocated.
  1323  **
  1324  ** ^If the database connection is associated with unfinalized prepared
  1325  ** statements or unfinished sqlite3_backup objects then sqlite3_close()
  1326  ** will leave the database connection open and return [SQLITE_BUSY].
  1327  ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
  1328  ** and/or unfinished sqlite3_backups, then the database connection becomes
  1329  ** an unusable "zombie" which will automatically be deallocated when the
  1330  ** last prepared statement is finalized or the last sqlite3_backup is
  1331  ** finished.  The sqlite3_close_v2() interface is intended for use with
  1332  ** host languages that are garbage collected, and where the order in which
  1333  ** destructors are called is arbitrary.
  1334  **
  1335  ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
  1336  ** [sqlite3_blob_close | close] all [BLOB handles], and 
  1337  ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  1338  ** with the [sqlite3] object prior to attempting to close the object.  ^If
  1339  ** sqlite3_close_v2() is called on a [database connection] that still has
  1340  ** outstanding [prepared statements], [BLOB handles], and/or
  1341  ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
  1342  ** of resources is deferred until all [prepared statements], [BLOB handles],
  1343  ** and [sqlite3_backup] objects are also destroyed.
  1344  **
  1345  ** ^If an [sqlite3] object is destroyed while a transaction is open,
  1346  ** the transaction is automatically rolled back.
  1347  **
  1348  ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  1349  ** must be either a NULL
  1350  ** pointer or an [sqlite3] object pointer obtained
  1351  ** from [sqlite3_open()], [sqlite3_open16()], or
  1352  ** [sqlite3_open_v2()], and not previously closed.
  1353  ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  1354  ** argument is a harmless no-op.
  1355  */
  1356  SQLITE_API int sqlite3_close(sqlite3*);
  1357  SQLITE_API int sqlite3_close_v2(sqlite3*);
  1358  
  1359  /*
  1360  ** The type for a callback function.
  1361  ** This is legacy and deprecated.  It is included for historical
  1362  ** compatibility and is not documented.
  1363  */
  1364  typedef int (*sqlite3_callback)(void*,int,char**, char**);
  1365  
  1366  /*
  1367  ** CAPI3REF: One-Step Query Execution Interface
  1368  ** METHOD: sqlite3
  1369  **
  1370  ** The sqlite3_exec() interface is a convenience wrapper around
  1371  ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  1372  ** that allows an application to run multiple statements of SQL
  1373  ** without having to use a lot of C code. 
  1374  **
  1375  ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  1376  ** semicolon-separate SQL statements passed into its 2nd argument,
  1377  ** in the context of the [database connection] passed in as its 1st
  1378  ** argument.  ^If the callback function of the 3rd argument to
  1379  ** sqlite3_exec() is not NULL, then it is invoked for each result row
  1380  ** coming out of the evaluated SQL statements.  ^The 4th argument to
  1381  ** sqlite3_exec() is relayed through to the 1st argument of each
  1382  ** callback invocation.  ^If the callback pointer to sqlite3_exec()
  1383  ** is NULL, then no callback is ever invoked and result rows are
  1384  ** ignored.
  1385  **
  1386  ** ^If an error occurs while evaluating the SQL statements passed into
  1387  ** sqlite3_exec(), then execution of the current statement stops and
  1388  ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
  1389  ** is not NULL then any error message is written into memory obtained
  1390  ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  1391  ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  1392  ** on error message strings returned through the 5th parameter of
  1393  ** sqlite3_exec() after the error message string is no longer needed.
  1394  ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  1395  ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  1396  ** NULL before returning.
  1397  **
  1398  ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  1399  ** routine returns SQLITE_ABORT without invoking the callback again and
  1400  ** without running any subsequent SQL statements.
  1401  **
  1402  ** ^The 2nd argument to the sqlite3_exec() callback function is the
  1403  ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
  1404  ** callback is an array of pointers to strings obtained as if from
  1405  ** [sqlite3_column_text()], one for each column.  ^If an element of a
  1406  ** result row is NULL then the corresponding string pointer for the
  1407  ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
  1408  ** sqlite3_exec() callback is an array of pointers to strings where each
  1409  ** entry represents the name of corresponding result column as obtained
  1410  ** from [sqlite3_column_name()].
  1411  **
  1412  ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  1413  ** to an empty string, or a pointer that contains only whitespace and/or 
  1414  ** SQL comments, then no SQL statements are evaluated and the database
  1415  ** is not changed.
  1416  **
  1417  ** Restrictions:
  1418  **
  1419  ** <ul>
  1420  ** <li> The application must ensure that the 1st parameter to sqlite3_exec()
  1421  **      is a valid and open [database connection].
  1422  ** <li> The application must not close the [database connection] specified by
  1423  **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  1424  ** <li> The application must not modify the SQL statement text passed into
  1425  **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  1426  ** </ul>
  1427  */
  1428  SQLITE_API int sqlite3_exec(
  1429    sqlite3*,                                  /* An open database */
  1430    const char *sql,                           /* SQL to be evaluated */
  1431    int (*callback)(void*,int,char**,char**),  /* Callback function */
  1432    void *,                                    /* 1st argument to callback */
  1433    char **errmsg                              /* Error msg written here */
  1434  );
  1435  
  1436  /*
  1437  ** CAPI3REF: Result Codes
  1438  ** KEYWORDS: {result code definitions}
  1439  **
  1440  ** Many SQLite functions return an integer result code from the set shown
  1441  ** here in order to indicate success or failure.
  1442  **
  1443  ** New error codes may be added in future versions of SQLite.
  1444  **
  1445  ** See also: [extended result code definitions]
  1446  */
  1447  #define SQLITE_OK           0   /* Successful result */
  1448  /* beginning-of-error-codes */
  1449  #define SQLITE_ERROR        1   /* Generic error */
  1450  #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
  1451  #define SQLITE_PERM         3   /* Access permission denied */
  1452  #define SQLITE_ABORT        4   /* Callback routine requested an abort */
  1453  #define SQLITE_BUSY         5   /* The database file is locked */
  1454  #define SQLITE_LOCKED       6   /* A table in the database is locked */
  1455  #define SQLITE_NOMEM        7   /* A malloc() failed */
  1456  #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
  1457  #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
  1458  #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
  1459  #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
  1460  #define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
  1461  #define SQLITE_FULL        13   /* Insertion failed because database is full */
  1462  #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
  1463  #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
  1464  #define SQLITE_EMPTY       16   /* Internal use only */
  1465  #define SQLITE_SCHEMA      17   /* The database schema changed */
  1466  #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
  1467  #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
  1468  #define SQLITE_MISMATCH    20   /* Data type mismatch */
  1469  #define SQLITE_MISUSE      21   /* Library used incorrectly */
  1470  #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
  1471  #define SQLITE_AUTH        23   /* Authorization denied */
  1472  #define SQLITE_FORMAT      24   /* Not used */
  1473  #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
  1474  #define SQLITE_NOTADB      26   /* File opened that is not a database file */
  1475  #define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */
  1476  #define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
  1477  #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
  1478  #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
  1479  /* end-of-error-codes */
  1480  
  1481  /*
  1482  ** CAPI3REF: Extended Result Codes
  1483  ** KEYWORDS: {extended result code definitions}
  1484  **
  1485  ** In its default configuration, SQLite API routines return one of 30 integer
  1486  ** [result codes].  However, experience has shown that many of
  1487  ** these result codes are too coarse-grained.  They do not provide as
  1488  ** much information about problems as programmers might like.  In an effort to
  1489  ** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
  1490  ** and later) include
  1491  ** support for additional result codes that provide more detailed information
  1492  ** about errors. These [extended result codes] are enabled or disabled
  1493  ** on a per database connection basis using the
  1494  ** [sqlite3_extended_result_codes()] API.  Or, the extended code for
  1495  ** the most recent error can be obtained using
  1496  ** [sqlite3_extended_errcode()].
  1497  */
  1498  #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
  1499  #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
  1500  #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
  1501  #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
  1502  #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
  1503  #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
  1504  #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
  1505  #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
  1506  #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
  1507  #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
  1508  #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
  1509  #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
  1510  #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
  1511  #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  1512  #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
  1513  #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
  1514  #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
  1515  #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
  1516  #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
  1517  #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
  1518  #define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
  1519  #define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
  1520  #define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
  1521  #define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))
  1522  #define SQLITE_IOERR_GETTEMPPATH       (SQLITE_IOERR | (25<<8))
  1523  #define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))
  1524  #define SQLITE_IOERR_VNODE             (SQLITE_IOERR | (27<<8))
  1525  #define SQLITE_IOERR_AUTH              (SQLITE_IOERR | (28<<8))
  1526  #define SQLITE_IOERR_BEGIN_ATOMIC      (SQLITE_IOERR | (29<<8))
  1527  #define SQLITE_IOERR_COMMIT_ATOMIC     (SQLITE_IOERR | (30<<8))
  1528  #define SQLITE_IOERR_ROLLBACK_ATOMIC   (SQLITE_IOERR | (31<<8))
  1529  #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
  1530  #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
  1531  #define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
  1532  #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
  1533  #define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
  1534  #define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
  1535  #define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
  1536  #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
  1537  #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
  1538  #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
  1539  #define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
  1540  #define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))
  1541  #define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
  1542  #define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))
  1543  #define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))
  1544  #define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))
  1545  #define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))
  1546  #define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
  1547  #define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
  1548  #define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
  1549  #define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
  1550  #define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
  1551  #define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
  1552  #define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
  1553  #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  1554  #define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
  1555  #define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))
  1556  #define SQLITE_OK_LOAD_PERMANENTLY     (SQLITE_OK | (1<<8))
  1557  
  1558  /*
  1559  ** CAPI3REF: Flags For File Open Operations
  1560  **
  1561  ** These bit values are intended for use in the
  1562  ** 3rd parameter to the [sqlite3_open_v2()] interface and
  1563  ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  1564  */
  1565  #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
  1566  #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
  1567  #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
  1568  #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
  1569  #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
  1570  #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
  1571  #define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
  1572  #define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
  1573  #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
  1574  #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
  1575  #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
  1576  #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
  1577  #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
  1578  #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
  1579  #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
  1580  #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
  1581  #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
  1582  #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
  1583  #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
  1584  #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
  1585  
  1586  /* Reserved:                         0x00F00000 */
  1587  
  1588  /*
  1589  ** CAPI3REF: Device Characteristics
  1590  **
  1591  ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  1592  ** object returns an integer which is a vector of these
  1593  ** bit values expressing I/O characteristics of the mass storage
  1594  ** device that holds the file that the [sqlite3_io_methods]
  1595  ** refers to.
  1596  **
  1597  ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1598  ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
  1599  ** mean that writes of blocks that are nnn bytes in size and
  1600  ** are aligned to an address which is an integer multiple of
  1601  ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
  1602  ** that when data is appended to a file, the data is appended
  1603  ** first then the size of the file is extended, never the other
  1604  ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
  1605  ** information is written to disk in the same order as calls
  1606  ** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  1607  ** after reboot following a crash or power loss, the only bytes in a
  1608  ** file that were written at the application level might have changed
  1609  ** and that adjacent bytes, even bytes within the same sector are
  1610  ** guaranteed to be unchanged.  The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  1611  ** flag indicates that a file cannot be deleted when open.  The
  1612  ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
  1613  ** read-only media and cannot be changed even by processes with
  1614  ** elevated privileges.
  1615  **
  1616  ** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying
  1617  ** filesystem supports doing multiple write operations atomically when those
  1618  ** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and
  1619  ** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].
  1620  */
  1621  #define SQLITE_IOCAP_ATOMIC                 0x00000001
  1622  #define SQLITE_IOCAP_ATOMIC512              0x00000002
  1623  #define SQLITE_IOCAP_ATOMIC1K               0x00000004
  1624  #define SQLITE_IOCAP_ATOMIC2K               0x00000008
  1625  #define SQLITE_IOCAP_ATOMIC4K               0x00000010
  1626  #define SQLITE_IOCAP_ATOMIC8K               0x00000020
  1627  #define SQLITE_IOCAP_ATOMIC16K              0x00000040
  1628  #define SQLITE_IOCAP_ATOMIC32K              0x00000080
  1629  #define SQLITE_IOCAP_ATOMIC64K              0x00000100
  1630  #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
  1631  #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
  1632  #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
  1633  #define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
  1634  #define SQLITE_IOCAP_IMMUTABLE              0x00002000
  1635  #define SQLITE_IOCAP_BATCH_ATOMIC           0x00004000
  1636  
  1637  /*
  1638  ** CAPI3REF: File Locking Levels
  1639  **
  1640  ** SQLite uses one of these integer values as the second
  1641  ** argument to calls it makes to the xLock() and xUnlock() methods
  1642  ** of an [sqlite3_io_methods] object.
  1643  */
  1644  #define SQLITE_LOCK_NONE          0
  1645  #define SQLITE_LOCK_SHARED        1
  1646  #define SQLITE_LOCK_RESERVED      2
  1647  #define SQLITE_LOCK_PENDING       3
  1648  #define SQLITE_LOCK_EXCLUSIVE     4
  1649  
  1650  /*
  1651  ** CAPI3REF: Synchronization Type Flags
  1652  **
  1653  ** When SQLite invokes the xSync() method of an
  1654  ** [sqlite3_io_methods] object it uses a combination of
  1655  ** these integer values as the second argument.
  1656  **
  1657  ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  1658  ** sync operation only needs to flush data to mass storage.  Inode
  1659  ** information need not be flushed. If the lower four bits of the flag
  1660  ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  1661  ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  1662  ** to use Mac OS X style fullsync instead of fsync().
  1663  **
  1664  ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  1665  ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  1666  ** settings.  The [synchronous pragma] determines when calls to the
  1667  ** xSync VFS method occur and applies uniformly across all platforms.
  1668  ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  1669  ** energetic or rigorous or forceful the sync operations are and
  1670  ** only make a difference on Mac OSX for the default SQLite code.
  1671  ** (Third-party VFS implementations might also make the distinction
  1672  ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  1673  ** operating systems natively supported by SQLite, only Mac OSX
  1674  ** cares about the difference.)
  1675  */
  1676  #define SQLITE_SYNC_NORMAL        0x00002
  1677  #define SQLITE_SYNC_FULL          0x00003
  1678  #define SQLITE_SYNC_DATAONLY      0x00010
  1679  
  1680  /*
  1681  ** CAPI3REF: OS Interface Open File Handle
  1682  **
  1683  ** An [sqlite3_file] object represents an open file in the 
  1684  ** [sqlite3_vfs | OS interface layer].  Individual OS interface
  1685  ** implementations will
  1686  ** want to subclass this object by appending additional fields
  1687  ** for their own use.  The pMethods entry is a pointer to an
  1688  ** [sqlite3_io_methods] object that defines methods for performing
  1689  ** I/O operations on the open file.
  1690  */
  1691  typedef struct sqlite3_file sqlite3_file;
  1692  struct sqlite3_file {
  1693    const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
  1694  };
  1695  
  1696  /*
  1697  ** CAPI3REF: OS Interface File Virtual Methods Object
  1698  **
  1699  ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  1700  ** [sqlite3_file] object (or, more commonly, a subclass of the
  1701  ** [sqlite3_file] object) with a pointer to an instance of this object.
  1702  ** This object defines the methods used to perform various operations
  1703  ** against the open file represented by the [sqlite3_file] object.
  1704  **
  1705  ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element 
  1706  ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  1707  ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
  1708  ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  1709  ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  1710  ** to NULL.
  1711  **
  1712  ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  1713  ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
  1714  ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
  1715  ** flag may be ORed in to indicate that only the data of the file
  1716  ** and not its inode needs to be synced.
  1717  **
  1718  ** The integer values to xLock() and xUnlock() are one of
  1719  ** <ul>
  1720  ** <li> [SQLITE_LOCK_NONE],
  1721  ** <li> [SQLITE_LOCK_SHARED],
  1722  ** <li> [SQLITE_LOCK_RESERVED],
  1723  ** <li> [SQLITE_LOCK_PENDING], or
  1724  ** <li> [SQLITE_LOCK_EXCLUSIVE].
  1725  ** </ul>
  1726  ** xLock() increases the lock. xUnlock() decreases the lock.
  1727  ** The xCheckReservedLock() method checks whether any database connection,
  1728  ** either in this process or in some other process, is holding a RESERVED,
  1729  ** PENDING, or EXCLUSIVE lock on the file.  It returns true
  1730  ** if such a lock exists and false otherwise.
  1731  **
  1732  ** The xFileControl() method is a generic interface that allows custom
  1733  ** VFS implementations to directly control an open file using the
  1734  ** [sqlite3_file_control()] interface.  The second "op" argument is an
  1735  ** integer opcode.  The third argument is a generic pointer intended to
  1736  ** point to a structure that may contain arguments or space in which to
  1737  ** write return values.  Potential uses for xFileControl() might be
  1738  ** functions to enable blocking locks with timeouts, to change the
  1739  ** locking strategy (for example to use dot-file locks), to inquire
  1740  ** about the status of a lock, or to break stale locks.  The SQLite
  1741  ** core reserves all opcodes less than 100 for its own use.
  1742  ** A [file control opcodes | list of opcodes] less than 100 is available.
  1743  ** Applications that define a custom xFileControl method should use opcodes
  1744  ** greater than 100 to avoid conflicts.  VFS implementations should
  1745  ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  1746  ** recognize.
  1747  **
  1748  ** The xSectorSize() method returns the sector size of the
  1749  ** device that underlies the file.  The sector size is the
  1750  ** minimum write that can be performed without disturbing
  1751  ** other bytes in the file.  The xDeviceCharacteristics()
  1752  ** method returns a bit vector describing behaviors of the
  1753  ** underlying device:
  1754  **
  1755  ** <ul>
  1756  ** <li> [SQLITE_IOCAP_ATOMIC]
  1757  ** <li> [SQLITE_IOCAP_ATOMIC512]
  1758  ** <li> [SQLITE_IOCAP_ATOMIC1K]
  1759  ** <li> [SQLITE_IOCAP_ATOMIC2K]
  1760  ** <li> [SQLITE_IOCAP_ATOMIC4K]
  1761  ** <li> [SQLITE_IOCAP_ATOMIC8K]
  1762  ** <li> [SQLITE_IOCAP_ATOMIC16K]
  1763  ** <li> [SQLITE_IOCAP_ATOMIC32K]
  1764  ** <li> [SQLITE_IOCAP_ATOMIC64K]
  1765  ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  1766  ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  1767  ** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
  1768  ** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
  1769  ** <li> [SQLITE_IOCAP_IMMUTABLE]
  1770  ** <li> [SQLITE_IOCAP_BATCH_ATOMIC]
  1771  ** </ul>
  1772  **
  1773  ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1774  ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
  1775  ** mean that writes of blocks that are nnn bytes in size and
  1776  ** are aligned to an address which is an integer multiple of
  1777  ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
  1778  ** that when data is appended to a file, the data is appended
  1779  ** first then the size of the file is extended, never the other
  1780  ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
  1781  ** information is written to disk in the same order as calls
  1782  ** to xWrite().
  1783  **
  1784  ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  1785  ** in the unread portions of the buffer with zeros.  A VFS that
  1786  ** fails to zero-fill short reads might seem to work.  However,
  1787  ** failure to zero-fill short reads will eventually lead to
  1788  ** database corruption.
  1789  */
  1790  typedef struct sqlite3_io_methods sqlite3_io_methods;
  1791  struct sqlite3_io_methods {
  1792    int iVersion;
  1793    int (*xClose)(sqlite3_file*);
  1794    int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  1795    int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  1796    int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  1797    int (*xSync)(sqlite3_file*, int flags);
  1798    int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  1799    int (*xLock)(sqlite3_file*, int);
  1800    int (*xUnlock)(sqlite3_file*, int);
  1801    int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  1802    int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  1803    int (*xSectorSize)(sqlite3_file*);
  1804    int (*xDeviceCharacteristics)(sqlite3_file*);
  1805    /* Methods above are valid for version 1 */
  1806    int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  1807    int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  1808    void (*xShmBarrier)(sqlite3_file*);
  1809    int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  1810    /* Methods above are valid for version 2 */
  1811    int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  1812    int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  1813    /* Methods above are valid for version 3 */
  1814    /* Additional methods may be added in future releases */
  1815  };
  1816  
  1817  /*
  1818  ** CAPI3REF: Standard File Control Opcodes
  1819  ** KEYWORDS: {file control opcodes} {file control opcode}
  1820  **
  1821  ** These integer constants are opcodes for the xFileControl method
  1822  ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  1823  ** interface.
  1824  **
  1825  ** <ul>
  1826  ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
  1827  ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
  1828  ** opcode causes the xFileControl method to write the current state of
  1829  ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  1830  ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  1831  ** into an integer that the pArg argument points to. This capability
  1832  ** is used during testing and is only available when the SQLITE_TEST
  1833  ** compile-time option is used.
  1834  **
  1835  ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  1836  ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  1837  ** layer a hint of how large the database file will grow to be during the
  1838  ** current transaction.  This hint is not guaranteed to be accurate but it
  1839  ** is often close.  The underlying VFS might choose to preallocate database
  1840  ** file space based on this hint in order to help writes to the database
  1841  ** file run faster.
  1842  **
  1843  ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  1844  ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  1845  ** extends and truncates the database file in chunks of a size specified
  1846  ** by the user. The fourth argument to [sqlite3_file_control()] should 
  1847  ** point to an integer (type int) containing the new chunk-size to use
  1848  ** for the nominated database. Allocating database file space in large
  1849  ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  1850  ** improve performance on some systems.
  1851  **
  1852  ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  1853  ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  1854  ** to the [sqlite3_file] object associated with a particular database
  1855  ** connection.  See also [SQLITE_FCNTL_JOURNAL_POINTER].
  1856  **
  1857  ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
  1858  ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
  1859  ** to the [sqlite3_file] object associated with the journal file (either
  1860  ** the [rollback journal] or the [write-ahead log]) for a particular database
  1861  ** connection.  See also [SQLITE_FCNTL_FILE_POINTER].
  1862  **
  1863  ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  1864  ** No longer in use.
  1865  **
  1866  ** <li>[[SQLITE_FCNTL_SYNC]]
  1867  ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
  1868  ** sent to the VFS immediately before the xSync method is invoked on a
  1869  ** database file descriptor. Or, if the xSync method is not invoked 
  1870  ** because the user has configured SQLite with 
  1871  ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place 
  1872  ** of the xSync method. In most cases, the pointer argument passed with
  1873  ** this file-control is NULL. However, if the database file is being synced
  1874  ** as part of a multi-database commit, the argument points to a nul-terminated
  1875  ** string containing the transactions master-journal file name. VFSes that 
  1876  ** do not need this signal should silently ignore this opcode. Applications 
  1877  ** should not call [sqlite3_file_control()] with this opcode as doing so may 
  1878  ** disrupt the operation of the specialized VFSes that do require it.  
  1879  **
  1880  ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
  1881  ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
  1882  ** and sent to the VFS after a transaction has been committed immediately
  1883  ** but before the database is unlocked. VFSes that do not need this signal
  1884  ** should silently ignore this opcode. Applications should not call
  1885  ** [sqlite3_file_control()] with this opcode as doing so may disrupt the 
  1886  ** operation of the specialized VFSes that do require it.  
  1887  **
  1888  ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  1889  ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  1890  ** retry counts and intervals for certain disk I/O operations for the
  1891  ** windows [VFS] in order to provide robustness in the presence of
  1892  ** anti-virus programs.  By default, the windows VFS will retry file read,
  1893  ** file write, and file delete operations up to 10 times, with a delay
  1894  ** of 25 milliseconds before the first retry and with the delay increasing
  1895  ** by an additional 25 milliseconds with each subsequent retry.  This
  1896  ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  1897  ** to be adjusted.  The values are changed for all database connections
  1898  ** within the same process.  The argument is a pointer to an array of two
  1899  ** integers where the first integer is the new retry count and the second
  1900  ** integer is the delay.  If either integer is negative, then the setting
  1901  ** is not changed but instead the prior value of that setting is written
  1902  ** into the array entry, allowing the current retry settings to be
  1903  ** interrogated.  The zDbName parameter is ignored.
  1904  **
  1905  ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  1906  ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  1907  ** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
  1908  ** write ahead log and shared memory files used for transaction control
  1909  ** are automatically deleted when the latest connection to the database
  1910  ** closes.  Setting persistent WAL mode causes those files to persist after
  1911  ** close.  Persisting the files is useful when other processes that do not
  1912  ** have write permission on the directory containing the database file want
  1913  ** to read the database file, as the WAL and shared memory files must exist
  1914  ** in order for the database to be readable.  The fourth parameter to
  1915  ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1916  ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  1917  ** WAL mode.  If the integer is -1, then it is overwritten with the current
  1918  ** WAL persistence setting.
  1919  **
  1920  ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  1921  ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  1922  ** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
  1923  ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  1924  ** xDeviceCharacteristics methods. The fourth parameter to
  1925  ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1926  ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  1927  ** mode.  If the integer is -1, then it is overwritten with the current
  1928  ** zero-damage mode setting.
  1929  **
  1930  ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  1931  ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  1932  ** a write transaction to indicate that, unless it is rolled back for some
  1933  ** reason, the entire database file will be overwritten by the current 
  1934  ** transaction. This is used by VACUUM operations.
  1935  **
  1936  ** <li>[[SQLITE_FCNTL_VFSNAME]]
  1937  ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  1938  ** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
  1939  ** final bottom-level VFS are written into memory obtained from 
  1940  ** [sqlite3_malloc()] and the result is stored in the char* variable
  1941  ** that the fourth parameter of [sqlite3_file_control()] points to.
  1942  ** The caller is responsible for freeing the memory when done.  As with
  1943  ** all file-control actions, there is no guarantee that this will actually
  1944  ** do anything.  Callers should initialize the char* variable to a NULL
  1945  ** pointer in case this file-control is not implemented.  This file-control
  1946  ** is intended for diagnostic use only.
  1947  **
  1948  ** <li>[[SQLITE_FCNTL_VFS_POINTER]]
  1949  ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
  1950  ** [VFSes] currently in use.  ^(The argument X in
  1951  ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
  1952  ** of type "[sqlite3_vfs] **".  This opcodes will set *X
  1953  ** to a pointer to the top-level VFS.)^
  1954  ** ^When there are multiple VFS shims in the stack, this opcode finds the
  1955  ** upper-most shim only.
  1956  **
  1957  ** <li>[[SQLITE_FCNTL_PRAGMA]]
  1958  ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] 
  1959  ** file control is sent to the open [sqlite3_file] object corresponding
  1960  ** to the database file to which the pragma statement refers. ^The argument
  1961  ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  1962  ** pointers to strings (char**) in which the second element of the array
  1963  ** is the name of the pragma and the third element is the argument to the
  1964  ** pragma or NULL if the pragma has no argument.  ^The handler for an
  1965  ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  1966  ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  1967  ** or the equivalent and that string will become the result of the pragma or
  1968  ** the error message if the pragma fails. ^If the
  1969  ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal 
  1970  ** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
  1971  ** file control returns [SQLITE_OK], then the parser assumes that the
  1972  ** VFS has handled the PRAGMA itself and the parser generates a no-op
  1973  ** prepared statement if result string is NULL, or that returns a copy
  1974  ** of the result string if the string is non-NULL.
  1975  ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  1976  ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  1977  ** that the VFS encountered an error while handling the [PRAGMA] and the
  1978  ** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
  1979  ** file control occurs at the beginning of pragma statement analysis and so
  1980  ** it is able to override built-in [PRAGMA] statements.
  1981  **
  1982  ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  1983  ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  1984  ** file-control may be invoked by SQLite on the database file handle
  1985  ** shortly after it is opened in order to provide a custom VFS with access
  1986  ** to the connections busy-handler callback. The argument is of type (void **)
  1987  ** - an array of two (void *) values. The first (void *) actually points
  1988  ** to a function of type (int (*)(void *)). In order to invoke the connections
  1989  ** busy-handler, this function should be invoked with the second (void *) in
  1990  ** the array as the only argument. If it returns non-zero, then the operation
  1991  ** should be retried. If it returns zero, the custom VFS should abandon the
  1992  ** current operation.
  1993  **
  1994  ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  1995  ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  1996  ** to have SQLite generate a
  1997  ** temporary filename using the same algorithm that is followed to generate
  1998  ** temporary filenames for TEMP tables and other internal uses.  The
  1999  ** argument should be a char** which will be filled with the filename
  2000  ** written into memory obtained from [sqlite3_malloc()].  The caller should
  2001  ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  2002  **
  2003  ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  2004  ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  2005  ** maximum number of bytes that will be used for memory-mapped I/O.
  2006  ** The argument is a pointer to a value of type sqlite3_int64 that
  2007  ** is an advisory maximum number of bytes in the file to memory map.  The
  2008  ** pointer is overwritten with the old value.  The limit is not changed if
  2009  ** the value originally pointed to is negative, and so the current limit 
  2010  ** can be queried by passing in a pointer to a negative number.  This
  2011  ** file-control is used internally to implement [PRAGMA mmap_size].
  2012  **
  2013  ** <li>[[SQLITE_FCNTL_TRACE]]
  2014  ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
  2015  ** to the VFS about what the higher layers of the SQLite stack are doing.
  2016  ** This file control is used by some VFS activity tracing [shims].
  2017  ** The argument is a zero-terminated string.  Higher layers in the
  2018  ** SQLite stack may generate instances of this file control if
  2019  ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
  2020  **
  2021  ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
  2022  ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
  2023  ** pointer to an integer and it writes a boolean into that integer depending
  2024  ** on whether or not the file has been renamed, moved, or deleted since it
  2025  ** was first opened.
  2026  **
  2027  ** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
  2028  ** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
  2029  ** underlying native file handle associated with a file handle.  This file
  2030  ** control interprets its argument as a pointer to a native file handle and
  2031  ** writes the resulting value there.
  2032  **
  2033  ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
  2034  ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging.  This
  2035  ** opcode causes the xFileControl method to swap the file handle with the one
  2036  ** pointed to by the pArg argument.  This capability is used during testing
  2037  ** and only needs to be supported when SQLITE_TEST is defined.
  2038  **
  2039  ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
  2040  ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
  2041  ** be advantageous to block on the next WAL lock if the lock is not immediately
  2042  ** available.  The WAL subsystem issues this signal during rare
  2043  ** circumstances in order to fix a problem with priority inversion.
  2044  ** Applications should <em>not</em> use this file-control.
  2045  **
  2046  ** <li>[[SQLITE_FCNTL_ZIPVFS]]
  2047  ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
  2048  ** VFS should return SQLITE_NOTFOUND for this opcode.
  2049  **
  2050  ** <li>[[SQLITE_FCNTL_RBU]]
  2051  ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
  2052  ** the RBU extension only.  All other VFS should return SQLITE_NOTFOUND for
  2053  ** this opcode.  
  2054  **
  2055  ** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
  2056  ** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
  2057  ** the file descriptor is placed in "batch write mode", which
  2058  ** means all subsequent write operations will be deferred and done
  2059  ** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].  Systems
  2060  ** that do not support batch atomic writes will return SQLITE_NOTFOUND.
  2061  ** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to
  2062  ** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or
  2063  ** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make
  2064  ** no VFS interface calls on the same [sqlite3_file] file descriptor
  2065  ** except for calls to the xWrite method and the xFileControl method
  2066  ** with [SQLITE_FCNTL_SIZE_HINT].
  2067  **
  2068  ** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
  2069  ** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
  2070  ** operations since the previous successful call to 
  2071  ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
  2072  ** This file control returns [SQLITE_OK] if and only if the writes were
  2073  ** all performed successfully and have been committed to persistent storage.
  2074  ** ^Regardless of whether or not it is successful, this file control takes
  2075  ** the file descriptor out of batch write mode so that all subsequent
  2076  ** write operations are independent.
  2077  ** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without
  2078  ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
  2079  **
  2080  ** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
  2081  ** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
  2082  ** operations since the previous successful call to 
  2083  ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
  2084  ** ^This file control takes the file descriptor out of batch write mode
  2085  ** so that all subsequent write operations are independent.
  2086  ** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without
  2087  ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
  2088  ** </ul>
  2089  */
  2090  #define SQLITE_FCNTL_LOCKSTATE               1
  2091  #define SQLITE_FCNTL_GET_LOCKPROXYFILE       2
  2092  #define SQLITE_FCNTL_SET_LOCKPROXYFILE       3
  2093  #define SQLITE_FCNTL_LAST_ERRNO              4
  2094  #define SQLITE_FCNTL_SIZE_HINT               5
  2095  #define SQLITE_FCNTL_CHUNK_SIZE              6
  2096  #define SQLITE_FCNTL_FILE_POINTER            7
  2097  #define SQLITE_FCNTL_SYNC_OMITTED            8
  2098  #define SQLITE_FCNTL_WIN32_AV_RETRY          9
  2099  #define SQLITE_FCNTL_PERSIST_WAL            10
  2100  #define SQLITE_FCNTL_OVERWRITE              11
  2101  #define SQLITE_FCNTL_VFSNAME                12
  2102  #define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
  2103  #define SQLITE_FCNTL_PRAGMA                 14
  2104  #define SQLITE_FCNTL_BUSYHANDLER            15
  2105  #define SQLITE_FCNTL_TEMPFILENAME           16
  2106  #define SQLITE_FCNTL_MMAP_SIZE              18
  2107  #define SQLITE_FCNTL_TRACE                  19
  2108  #define SQLITE_FCNTL_HAS_MOVED              20
  2109  #define SQLITE_FCNTL_SYNC                   21
  2110  #define SQLITE_FCNTL_COMMIT_PHASETWO        22
  2111  #define SQLITE_FCNTL_WIN32_SET_HANDLE       23
  2112  #define SQLITE_FCNTL_WAL_BLOCK              24
  2113  #define SQLITE_FCNTL_ZIPVFS                 25
  2114  #define SQLITE_FCNTL_RBU                    26
  2115  #define SQLITE_FCNTL_VFS_POINTER            27
  2116  #define SQLITE_FCNTL_JOURNAL_POINTER        28
  2117  #define SQLITE_FCNTL_WIN32_GET_HANDLE       29
  2118  #define SQLITE_FCNTL_PDB                    30
  2119  #define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE     31
  2120  #define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE    32
  2121  #define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE  33
  2122  
  2123  /* deprecated names */
  2124  #define SQLITE_GET_LOCKPROXYFILE      SQLITE_FCNTL_GET_LOCKPROXYFILE
  2125  #define SQLITE_SET_LOCKPROXYFILE      SQLITE_FCNTL_SET_LOCKPROXYFILE
  2126  #define SQLITE_LAST_ERRNO             SQLITE_FCNTL_LAST_ERRNO
  2127  
  2128  
  2129  /*
  2130  ** CAPI3REF: Mutex Handle
  2131  **
  2132  ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  2133  ** abstract type for a mutex object.  The SQLite core never looks
  2134  ** at the internal representation of an [sqlite3_mutex].  It only
  2135  ** deals with pointers to the [sqlite3_mutex] object.
  2136  **
  2137  ** Mutexes are created using [sqlite3_mutex_alloc()].
  2138  */
  2139  typedef struct sqlite3_mutex sqlite3_mutex;
  2140  
  2141  /*
  2142  ** CAPI3REF: Loadable Extension Thunk
  2143  **
  2144  ** A pointer to the opaque sqlite3_api_routines structure is passed as
  2145  ** the third parameter to entry points of [loadable extensions].  This
  2146  ** structure must be typedefed in order to work around compiler warnings
  2147  ** on some platforms.
  2148  */
  2149  typedef struct sqlite3_api_routines sqlite3_api_routines;
  2150  
  2151  /*
  2152  ** CAPI3REF: OS Interface Object
  2153  **
  2154  ** An instance of the sqlite3_vfs object defines the interface between
  2155  ** the SQLite core and the underlying operating system.  The "vfs"
  2156  ** in the name of the object stands for "virtual file system".  See
  2157  ** the [VFS | VFS documentation] for further information.
  2158  **
  2159  ** The value of the iVersion field is initially 1 but may be larger in
  2160  ** future versions of SQLite.  Additional fields may be appended to this
  2161  ** object when the iVersion value is increased.  Note that the structure
  2162  ** of the sqlite3_vfs object changes in the transaction between
  2163  ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  2164  ** modified.
  2165  **
  2166  ** The szOsFile field is the size of the subclassed [sqlite3_file]
  2167  ** structure used by this VFS.  mxPathname is the maximum length of
  2168  ** a pathname in this VFS.
  2169  **
  2170  ** Registered sqlite3_vfs objects are kept on a linked list formed by
  2171  ** the pNext pointer.  The [sqlite3_vfs_register()]
  2172  ** and [sqlite3_vfs_unregister()] interfaces manage this list
  2173  ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
  2174  ** searches the list.  Neither the application code nor the VFS
  2175  ** implementation should use the pNext pointer.
  2176  **
  2177  ** The pNext field is the only field in the sqlite3_vfs
  2178  ** structure that SQLite will ever modify.  SQLite will only access
  2179  ** or modify this field while holding a particular static mutex.
  2180  ** The application should never modify anything within the sqlite3_vfs
  2181  ** object once the object has been registered.
  2182  **
  2183  ** The zName field holds the name of the VFS module.  The name must
  2184  ** be unique across all VFS modules.
  2185  **
  2186  ** [[sqlite3_vfs.xOpen]]
  2187  ** ^SQLite guarantees that the zFilename parameter to xOpen
  2188  ** is either a NULL pointer or string obtained
  2189  ** from xFullPathname() with an optional suffix added.
  2190  ** ^If a suffix is added to the zFilename parameter, it will
  2191  ** consist of a single "-" character followed by no more than
  2192  ** 11 alphanumeric and/or "-" characters.
  2193  ** ^SQLite further guarantees that
  2194  ** the string will be valid and unchanged until xClose() is
  2195  ** called. Because of the previous sentence,
  2196  ** the [sqlite3_file] can safely store a pointer to the
  2197  ** filename if it needs to remember the filename for some reason.
  2198  ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  2199  ** must invent its own temporary name for the file.  ^Whenever the 
  2200  ** xFilename parameter is NULL it will also be the case that the
  2201  ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  2202  **
  2203  ** The flags argument to xOpen() includes all bits set in
  2204  ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
  2205  ** or [sqlite3_open16()] is used, then flags includes at least
  2206  ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
  2207  ** If xOpen() opens a file read-only then it sets *pOutFlags to
  2208  ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
  2209  **
  2210  ** ^(SQLite will also add one of the following flags to the xOpen()
  2211  ** call, depending on the object being opened:
  2212  **
  2213  ** <ul>
  2214  ** <li>  [SQLITE_OPEN_MAIN_DB]
  2215  ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
  2216  ** <li>  [SQLITE_OPEN_TEMP_DB]
  2217  ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
  2218  ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
  2219  ** <li>  [SQLITE_OPEN_SUBJOURNAL]
  2220  ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
  2221  ** <li>  [SQLITE_OPEN_WAL]
  2222  ** </ul>)^
  2223  **
  2224  ** The file I/O implementation can use the object type flags to
  2225  ** change the way it deals with files.  For example, an application
  2226  ** that does not care about crash recovery or rollback might make
  2227  ** the open of a journal file a no-op.  Writes to this journal would
  2228  ** also be no-ops, and any attempt to read the journal would return
  2229  ** SQLITE_IOERR.  Or the implementation might recognize that a database
  2230  ** file will be doing page-aligned sector reads and writes in a random
  2231  ** order and set up its I/O subsystem accordingly.
  2232  **
  2233  ** SQLite might also add one of the following flags to the xOpen method:
  2234  **
  2235  ** <ul>
  2236  ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  2237  ** <li> [SQLITE_OPEN_EXCLUSIVE]
  2238  ** </ul>
  2239  **
  2240  ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  2241  ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
  2242  ** will be set for TEMP databases and their journals, transient
  2243  ** databases, and subjournals.
  2244  **
  2245  ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  2246  ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  2247  ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  2248  ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
  2249  ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  2250  ** be created, and that it is an error if it already exists.
  2251  ** It is <i>not</i> used to indicate the file should be opened 
  2252  ** for exclusive access.
  2253  **
  2254  ** ^At least szOsFile bytes of memory are allocated by SQLite
  2255  ** to hold the  [sqlite3_file] structure passed as the third
  2256  ** argument to xOpen.  The xOpen method does not have to
  2257  ** allocate the structure; it should just fill it in.  Note that
  2258  ** the xOpen method must set the sqlite3_file.pMethods to either
  2259  ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
  2260  ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
  2261  ** element will be valid after xOpen returns regardless of the success
  2262  ** or failure of the xOpen call.
  2263  **
  2264  ** [[sqlite3_vfs.xAccess]]
  2265  ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  2266  ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  2267  ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  2268  ** to test whether a file is at least readable.   The file can be a
  2269  ** directory.
  2270  **
  2271  ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  2272  ** output buffer xFullPathname.  The exact size of the output buffer
  2273  ** is also passed as a parameter to both  methods. If the output buffer
  2274  ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  2275  ** handled as a fatal error by SQLite, vfs implementations should endeavor
  2276  ** to prevent this by setting mxPathname to a sufficiently large value.
  2277  **
  2278  ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  2279  ** interfaces are not strictly a part of the filesystem, but they are
  2280  ** included in the VFS structure for completeness.
  2281  ** The xRandomness() function attempts to return nBytes bytes
  2282  ** of good-quality randomness into zOut.  The return value is
  2283  ** the actual number of bytes of randomness obtained.
  2284  ** The xSleep() method causes the calling thread to sleep for at
  2285  ** least the number of microseconds given.  ^The xCurrentTime()
  2286  ** method returns a Julian Day Number for the current date and time as
  2287  ** a floating point value.
  2288  ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  2289  ** Day Number multiplied by 86400000 (the number of milliseconds in 
  2290  ** a 24-hour day).  
  2291  ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  2292  ** date and time if that method is available (if iVersion is 2 or 
  2293  ** greater and the function pointer is not NULL) and will fall back
  2294  ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  2295  **
  2296  ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  2297  ** are not used by the SQLite core.  These optional interfaces are provided
  2298  ** by some VFSes to facilitate testing of the VFS code. By overriding 
  2299  ** system calls with functions under its control, a test program can
  2300  ** simulate faults and error conditions that would otherwise be difficult
  2301  ** or impossible to induce.  The set of system calls that can be overridden
  2302  ** varies from one VFS to another, and from one version of the same VFS to the
  2303  ** next.  Applications that use these interfaces must be prepared for any
  2304  ** or all of these interfaces to be NULL or for their behavior to change
  2305  ** from one release to the next.  Applications must not attempt to access
  2306  ** any of these methods if the iVersion of the VFS is less than 3.
  2307  */
  2308  typedef struct sqlite3_vfs sqlite3_vfs;
  2309  typedef void (*sqlite3_syscall_ptr)(void);
  2310  struct sqlite3_vfs {
  2311    int iVersion;            /* Structure version number (currently 3) */
  2312    int szOsFile;            /* Size of subclassed sqlite3_file */
  2313    int mxPathname;          /* Maximum file pathname length */
  2314    sqlite3_vfs *pNext;      /* Next registered VFS */
  2315    const char *zName;       /* Name of this virtual file system */
  2316    void *pAppData;          /* Pointer to application-specific data */
  2317    int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  2318                 int flags, int *pOutFlags);
  2319    int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  2320    int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  2321    int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  2322    void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  2323    void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  2324    void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  2325    void (*xDlClose)(sqlite3_vfs*, void*);
  2326    int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  2327    int (*xSleep)(sqlite3_vfs*, int microseconds);
  2328    int (*xCurrentTime)(sqlite3_vfs*, double*);
  2329    int (*xGetLastError)(sqlite3_vfs*, int, char *);
  2330    /*
  2331    ** The methods above are in version 1 of the sqlite_vfs object
  2332    ** definition.  Those that follow are added in version 2 or later
  2333    */
  2334    int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  2335    /*
  2336    ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  2337    ** Those below are for version 3 and greater.
  2338    */
  2339    int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  2340    sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  2341    const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  2342    /*
  2343    ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  2344    ** New fields may be appended in future versions.  The iVersion
  2345    ** value will increment whenever this happens. 
  2346    */
  2347  };
  2348  
  2349  /*
  2350  ** CAPI3REF: Flags for the xAccess VFS method
  2351  **
  2352  ** These integer constants can be used as the third parameter to
  2353  ** the xAccess method of an [sqlite3_vfs] object.  They determine
  2354  ** what kind of permissions the xAccess method is looking for.
  2355  ** With SQLITE_ACCESS_EXISTS, the xAccess method
  2356  ** simply checks whether the file exists.
  2357  ** With SQLITE_ACCESS_READWRITE, the xAccess method
  2358  ** checks whether the named directory is both readable and writable
  2359  ** (in other words, if files can be added, removed, and renamed within
  2360  ** the directory).
  2361  ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  2362  ** [temp_store_directory pragma], though this could change in a future
  2363  ** release of SQLite.
  2364  ** With SQLITE_ACCESS_READ, the xAccess method
  2365  ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
  2366  ** currently unused, though it might be used in a future release of
  2367  ** SQLite.
  2368  */
  2369  #define SQLITE_ACCESS_EXISTS    0
  2370  #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
  2371  #define SQLITE_ACCESS_READ      2   /* Unused */
  2372  
  2373  /*
  2374  ** CAPI3REF: Flags for the xShmLock VFS method
  2375  **
  2376  ** These integer constants define the various locking operations
  2377  ** allowed by the xShmLock method of [sqlite3_io_methods].  The
  2378  ** following are the only legal combinations of flags to the
  2379  ** xShmLock method:
  2380  **
  2381  ** <ul>
  2382  ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  2383  ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  2384  ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  2385  ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  2386  ** </ul>
  2387  **
  2388  ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  2389  ** was given on the corresponding lock.  
  2390  **
  2391  ** The xShmLock method can transition between unlocked and SHARED or
  2392  ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
  2393  ** and EXCLUSIVE.
  2394  */
  2395  #define SQLITE_SHM_UNLOCK       1
  2396  #define SQLITE_SHM_LOCK         2
  2397  #define SQLITE_SHM_SHARED       4
  2398  #define SQLITE_SHM_EXCLUSIVE    8
  2399  
  2400  /*
  2401  ** CAPI3REF: Maximum xShmLock index
  2402  **
  2403  ** The xShmLock method on [sqlite3_io_methods] may use values
  2404  ** between 0 and this upper bound as its "offset" argument.
  2405  ** The SQLite core will never attempt to acquire or release a
  2406  ** lock outside of this range
  2407  */
  2408  #define SQLITE_SHM_NLOCK        8
  2409  
  2410  
  2411  /*
  2412  ** CAPI3REF: Initialize The SQLite Library
  2413  **
  2414  ** ^The sqlite3_initialize() routine initializes the
  2415  ** SQLite library.  ^The sqlite3_shutdown() routine
  2416  ** deallocates any resources that were allocated by sqlite3_initialize().
  2417  ** These routines are designed to aid in process initialization and
  2418  ** shutdown on embedded systems.  Workstation applications using
  2419  ** SQLite normally do not need to invoke either of these routines.
  2420  **
  2421  ** A call to sqlite3_initialize() is an "effective" call if it is
  2422  ** the first time sqlite3_initialize() is invoked during the lifetime of
  2423  ** the process, or if it is the first time sqlite3_initialize() is invoked
  2424  ** following a call to sqlite3_shutdown().  ^(Only an effective call
  2425  ** of sqlite3_initialize() does any initialization.  All other calls
  2426  ** are harmless no-ops.)^
  2427  **
  2428  ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  2429  ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
  2430  ** an effective call to sqlite3_shutdown() does any deinitialization.
  2431  ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  2432  **
  2433  ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  2434  ** is not.  The sqlite3_shutdown() interface must only be called from a
  2435  ** single thread.  All open [database connections] must be closed and all
  2436  ** other SQLite resources must be deallocated prior to invoking
  2437  ** sqlite3_shutdown().
  2438  **
  2439  ** Among other things, ^sqlite3_initialize() will invoke
  2440  ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
  2441  ** will invoke sqlite3_os_end().
  2442  **
  2443  ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  2444  ** ^If for some reason, sqlite3_initialize() is unable to initialize
  2445  ** the library (perhaps it is unable to allocate a needed resource such
  2446  ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  2447  **
  2448  ** ^The sqlite3_initialize() routine is called internally by many other
  2449  ** SQLite interfaces so that an application usually does not need to
  2450  ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
  2451  ** calls sqlite3_initialize() so the SQLite library will be automatically
  2452  ** initialized when [sqlite3_open()] is called if it has not be initialized
  2453  ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  2454  ** compile-time option, then the automatic calls to sqlite3_initialize()
  2455  ** are omitted and the application must call sqlite3_initialize() directly
  2456  ** prior to using any other SQLite interface.  For maximum portability,
  2457  ** it is recommended that applications always invoke sqlite3_initialize()
  2458  ** directly prior to using any other SQLite interface.  Future releases
  2459  ** of SQLite may require this.  In other words, the behavior exhibited
  2460  ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  2461  ** default behavior in some future release of SQLite.
  2462  **
  2463  ** The sqlite3_os_init() routine does operating-system specific
  2464  ** initialization of the SQLite library.  The sqlite3_os_end()
  2465  ** routine undoes the effect of sqlite3_os_init().  Typical tasks
  2466  ** performed by these routines include allocation or deallocation
  2467  ** of static resources, initialization of global variables,
  2468  ** setting up a default [sqlite3_vfs] module, or setting up
  2469  ** a default configuration using [sqlite3_config()].
  2470  **
  2471  ** The application should never invoke either sqlite3_os_init()
  2472  ** or sqlite3_os_end() directly.  The application should only invoke
  2473  ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
  2474  ** interface is called automatically by sqlite3_initialize() and
  2475  ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
  2476  ** implementations for sqlite3_os_init() and sqlite3_os_end()
  2477  ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  2478  ** When [custom builds | built for other platforms]
  2479  ** (using the [SQLITE_OS_OTHER=1] compile-time
  2480  ** option) the application must supply a suitable implementation for
  2481  ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
  2482  ** implementation of sqlite3_os_init() or sqlite3_os_end()
  2483  ** must return [SQLITE_OK] on success and some other [error code] upon
  2484  ** failure.
  2485  */
  2486  SQLITE_API int sqlite3_initialize(void);
  2487  SQLITE_API int sqlite3_shutdown(void);
  2488  SQLITE_API int sqlite3_os_init(void);
  2489  SQLITE_API int sqlite3_os_end(void);
  2490  
  2491  /*
  2492  ** CAPI3REF: Configuring The SQLite Library
  2493  **
  2494  ** The sqlite3_config() interface is used to make global configuration
  2495  ** changes to SQLite in order to tune SQLite to the specific needs of
  2496  ** the application.  The default configuration is recommended for most
  2497  ** applications and so this routine is usually not necessary.  It is
  2498  ** provided to support rare applications with unusual needs.
  2499  **
  2500  ** <b>The sqlite3_config() interface is not threadsafe. The application
  2501  ** must ensure that no other SQLite interfaces are invoked by other
  2502  ** threads while sqlite3_config() is running.</b>
  2503  **
  2504  ** The sqlite3_config() interface
  2505  ** may only be invoked prior to library initialization using
  2506  ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  2507  ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  2508  ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  2509  ** Note, however, that ^sqlite3_config() can be called as part of the
  2510  ** implementation of an application-defined [sqlite3_os_init()].
  2511  **
  2512  ** The first argument to sqlite3_config() is an integer
  2513  ** [configuration option] that determines
  2514  ** what property of SQLite is to be configured.  Subsequent arguments
  2515  ** vary depending on the [configuration option]
  2516  ** in the first argument.
  2517  **
  2518  ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  2519  ** ^If the option is unknown or SQLite is unable to set the option
  2520  ** then this routine returns a non-zero [error code].
  2521  */
  2522  SQLITE_API int sqlite3_config(int, ...);
  2523  
  2524  /*
  2525  ** CAPI3REF: Configure database connections
  2526  ** METHOD: sqlite3
  2527  **
  2528  ** The sqlite3_db_config() interface is used to make configuration
  2529  ** changes to a [database connection].  The interface is similar to
  2530  ** [sqlite3_config()] except that the changes apply to a single
  2531  ** [database connection] (specified in the first argument).
  2532  **
  2533  ** The second argument to sqlite3_db_config(D,V,...)  is the
  2534  ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code 
  2535  ** that indicates what aspect of the [database connection] is being configured.
  2536  ** Subsequent arguments vary depending on the configuration verb.
  2537  **
  2538  ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  2539  ** the call is considered successful.
  2540  */
  2541  SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  2542  
  2543  /*
  2544  ** CAPI3REF: Memory Allocation Routines
  2545  **
  2546  ** An instance of this object defines the interface between SQLite
  2547  ** and low-level memory allocation routines.
  2548  **
  2549  ** This object is used in only one place in the SQLite interface.
  2550  ** A pointer to an instance of this object is the argument to
  2551  ** [sqlite3_config()] when the configuration option is
  2552  ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
  2553  ** By creating an instance of this object
  2554  ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  2555  ** during configuration, an application can specify an alternative
  2556  ** memory allocation subsystem for SQLite to use for all of its
  2557  ** dynamic memory needs.
  2558  **
  2559  ** Note that SQLite comes with several [built-in memory allocators]
  2560  ** that are perfectly adequate for the overwhelming majority of applications
  2561  ** and that this object is only useful to a tiny minority of applications
  2562  ** with specialized memory allocation requirements.  This object is
  2563  ** also used during testing of SQLite in order to specify an alternative
  2564  ** memory allocator that simulates memory out-of-memory conditions in
  2565  ** order to verify that SQLite recovers gracefully from such
  2566  ** conditions.
  2567  **
  2568  ** The xMalloc, xRealloc, and xFree methods must work like the
  2569  ** malloc(), realloc() and free() functions from the standard C library.
  2570  ** ^SQLite guarantees that the second argument to
  2571  ** xRealloc is always a value returned by a prior call to xRoundup.
  2572  **
  2573  ** xSize should return the allocated size of a memory allocation
  2574  ** previously obtained from xMalloc or xRealloc.  The allocated size
  2575  ** is always at least as big as the requested size but may be larger.
  2576  **
  2577  ** The xRoundup method returns what would be the allocated size of
  2578  ** a memory allocation given a particular requested size.  Most memory
  2579  ** allocators round up memory allocations at least to the next multiple
  2580  ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
  2581  ** Every memory allocation request coming in through [sqlite3_malloc()]
  2582  ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
  2583  ** that causes the corresponding memory allocation to fail.
  2584  **
  2585  ** The xInit method initializes the memory allocator.  For example,
  2586  ** it might allocate any require mutexes or initialize internal data
  2587  ** structures.  The xShutdown method is invoked (indirectly) by
  2588  ** [sqlite3_shutdown()] and should deallocate any resources acquired
  2589  ** by xInit.  The pAppData pointer is used as the only parameter to
  2590  ** xInit and xShutdown.
  2591  **
  2592  ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  2593  ** the xInit method, so the xInit method need not be threadsafe.  The
  2594  ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  2595  ** not need to be threadsafe either.  For all other methods, SQLite
  2596  ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  2597  ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  2598  ** it is by default) and so the methods are automatically serialized.
  2599  ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  2600  ** methods must be threadsafe or else make their own arrangements for
  2601  ** serialization.
  2602  **
  2603  ** SQLite will never invoke xInit() more than once without an intervening
  2604  ** call to xShutdown().
  2605  */
  2606  typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  2607  struct sqlite3_mem_methods {
  2608    void *(*xMalloc)(int);         /* Memory allocation function */
  2609    void (*xFree)(void*);          /* Free a prior allocation */
  2610    void *(*xRealloc)(void*,int);  /* Resize an allocation */
  2611    int (*xSize)(void*);           /* Return the size of an allocation */
  2612    int (*xRoundup)(int);          /* Round up request size to allocation size */
  2613    int (*xInit)(void*);           /* Initialize the memory allocator */
  2614    void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
  2615    void *pAppData;                /* Argument to xInit() and xShutdown() */
  2616  };
  2617  
  2618  /*
  2619  ** CAPI3REF: Configuration Options
  2620  ** KEYWORDS: {configuration option}
  2621  **
  2622  ** These constants are the available integer configuration options that
  2623  ** can be passed as the first argument to the [sqlite3_config()] interface.
  2624  **
  2625  ** New configuration options may be added in future releases of SQLite.
  2626  ** Existing configuration options might be discontinued.  Applications
  2627  ** should check the return code from [sqlite3_config()] to make sure that
  2628  ** the call worked.  The [sqlite3_config()] interface will return a
  2629  ** non-zero [error code] if a discontinued or unsupported configuration option
  2630  ** is invoked.
  2631  **
  2632  ** <dl>
  2633  ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  2634  ** <dd>There are no arguments to this option.  ^This option sets the
  2635  ** [threading mode] to Single-thread.  In other words, it disables
  2636  ** all mutexing and puts SQLite into a mode where it can only be used
  2637  ** by a single thread.   ^If SQLite is compiled with
  2638  ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2639  ** it is not possible to change the [threading mode] from its default
  2640  ** value of Single-thread and so [sqlite3_config()] will return 
  2641  ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  2642  ** configuration option.</dd>
  2643  **
  2644  ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  2645  ** <dd>There are no arguments to this option.  ^This option sets the
  2646  ** [threading mode] to Multi-thread.  In other words, it disables
  2647  ** mutexing on [database connection] and [prepared statement] objects.
  2648  ** The application is responsible for serializing access to
  2649  ** [database connections] and [prepared statements].  But other mutexes
  2650  ** are enabled so that SQLite will be safe to use in a multi-threaded
  2651  ** environment as long as no two threads attempt to use the same
  2652  ** [database connection] at the same time.  ^If SQLite is compiled with
  2653  ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2654  ** it is not possible to set the Multi-thread [threading mode] and
  2655  ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  2656  ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  2657  **
  2658  ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  2659  ** <dd>There are no arguments to this option.  ^This option sets the
  2660  ** [threading mode] to Serialized. In other words, this option enables
  2661  ** all mutexes including the recursive
  2662  ** mutexes on [database connection] and [prepared statement] objects.
  2663  ** In this mode (which is the default when SQLite is compiled with
  2664  ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  2665  ** to [database connections] and [prepared statements] so that the
  2666  ** application is free to use the same [database connection] or the
  2667  ** same [prepared statement] in different threads at the same time.
  2668  ** ^If SQLite is compiled with
  2669  ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2670  ** it is not possible to set the Serialized [threading mode] and
  2671  ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  2672  ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  2673  **
  2674  ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  2675  ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is 
  2676  ** a pointer to an instance of the [sqlite3_mem_methods] structure.
  2677  ** The argument specifies
  2678  ** alternative low-level memory allocation routines to be used in place of
  2679  ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  2680  ** its own private copy of the content of the [sqlite3_mem_methods] structure
  2681  ** before the [sqlite3_config()] call returns.</dd>
  2682  **
  2683  ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  2684  ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
  2685  ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
  2686  ** The [sqlite3_mem_methods]
  2687  ** structure is filled with the currently defined memory allocation routines.)^
  2688  ** This option can be used to overload the default memory allocation
  2689  ** routines with a wrapper that simulations memory allocation failure or
  2690  ** tracks memory usage, for example. </dd>
  2691  **
  2692  ** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>
  2693  ** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of
  2694  ** type int, interpreted as a boolean, which if true provides a hint to
  2695  ** SQLite that it should avoid large memory allocations if possible.
  2696  ** SQLite will run faster if it is free to make large memory allocations,
  2697  ** but some application might prefer to run slower in exchange for
  2698  ** guarantees about memory fragmentation that are possible if large
  2699  ** allocations are avoided.  This hint is normally off.
  2700  ** </dd>
  2701  **
  2702  ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  2703  ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
  2704  ** interpreted as a boolean, which enables or disables the collection of
  2705  ** memory allocation statistics. ^(When memory allocation statistics are
  2706  ** disabled, the following SQLite interfaces become non-operational:
  2707  **   <ul>
  2708  **   <li> [sqlite3_memory_used()]
  2709  **   <li> [sqlite3_memory_highwater()]
  2710  **   <li> [sqlite3_soft_heap_limit64()]
  2711  **   <li> [sqlite3_status64()]
  2712  **   </ul>)^
  2713  ** ^Memory allocation statistics are enabled by default unless SQLite is
  2714  ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  2715  ** allocation statistics are disabled by default.
  2716  ** </dd>
  2717  **
  2718  ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  2719  ** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used.
  2720  ** </dd>
  2721  **
  2722  ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  2723  ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
  2724  ** that SQLite can use for the database page cache with the default page
  2725  ** cache implementation.  
  2726  ** This configuration option is a no-op if an application-define page
  2727  ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
  2728  ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
  2729  ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
  2730  ** and the number of cache lines (N).
  2731  ** The sz argument should be the size of the largest database page
  2732  ** (a power of two between 512 and 65536) plus some extra bytes for each
  2733  ** page header.  ^The number of extra bytes needed by the page header
  2734  ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
  2735  ** ^It is harmless, apart from the wasted memory,
  2736  ** for the sz parameter to be larger than necessary.  The pMem
  2737  ** argument must be either a NULL pointer or a pointer to an 8-byte
  2738  ** aligned block of memory of at least sz*N bytes, otherwise
  2739  ** subsequent behavior is undefined.
  2740  ** ^When pMem is not NULL, SQLite will strive to use the memory provided
  2741  ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
  2742  ** a page cache line is larger than sz bytes or if all of the pMem buffer
  2743  ** is exhausted.
  2744  ** ^If pMem is NULL and N is non-zero, then each database connection
  2745  ** does an initial bulk allocation for page cache memory
  2746  ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
  2747  ** of -1024*N bytes if N is negative, . ^If additional
  2748  ** page cache memory is needed beyond what is provided by the initial
  2749  ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
  2750  ** additional cache line. </dd>
  2751  **
  2752  ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  2753  ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer 
  2754  ** that SQLite will use for all of its dynamic memory allocation needs
  2755  ** beyond those provided for by [SQLITE_CONFIG_PAGECACHE].
  2756  ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
  2757  ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
  2758  ** [SQLITE_ERROR] if invoked otherwise.
  2759  ** ^There are three arguments to SQLITE_CONFIG_HEAP:
  2760  ** An 8-byte aligned pointer to the memory,
  2761  ** the number of bytes in the memory buffer, and the minimum allocation size.
  2762  ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  2763  ** to using its default memory allocator (the system malloc() implementation),
  2764  ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
  2765  ** memory pointer is not NULL then the alternative memory
  2766  ** allocator is engaged to handle all of SQLites memory allocation needs.
  2767  ** The first pointer (the memory pointer) must be aligned to an 8-byte
  2768  ** boundary or subsequent behavior of SQLite will be undefined.
  2769  ** The minimum allocation size is capped at 2**12. Reasonable values
  2770  ** for the minimum allocation size are 2**5 through 2**8.</dd>
  2771  **
  2772  ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  2773  ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
  2774  ** pointer to an instance of the [sqlite3_mutex_methods] structure.
  2775  ** The argument specifies alternative low-level mutex routines to be used
  2776  ** in place the mutex routines built into SQLite.)^  ^SQLite makes a copy of
  2777  ** the content of the [sqlite3_mutex_methods] structure before the call to
  2778  ** [sqlite3_config()] returns. ^If SQLite is compiled with
  2779  ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2780  ** the entire mutexing subsystem is omitted from the build and hence calls to
  2781  ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  2782  ** return [SQLITE_ERROR].</dd>
  2783  **
  2784  ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  2785  ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
  2786  ** is a pointer to an instance of the [sqlite3_mutex_methods] structure.  The
  2787  ** [sqlite3_mutex_methods]
  2788  ** structure is filled with the currently defined mutex routines.)^
  2789  ** This option can be used to overload the default mutex allocation
  2790  ** routines with a wrapper used to track mutex usage for performance
  2791  ** profiling or testing, for example.   ^If SQLite is compiled with
  2792  ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2793  ** the entire mutexing subsystem is omitted from the build and hence calls to
  2794  ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  2795  ** return [SQLITE_ERROR].</dd>
  2796  **
  2797  ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  2798  ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
  2799  ** the default size of lookaside memory on each [database connection].
  2800  ** The first argument is the
  2801  ** size of each lookaside buffer slot and the second is the number of
  2802  ** slots allocated to each database connection.)^  ^(SQLITE_CONFIG_LOOKASIDE
  2803  ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  2804  ** option to [sqlite3_db_config()] can be used to change the lookaside
  2805  ** configuration on individual connections.)^ </dd>
  2806  **
  2807  ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  2808  ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is 
  2809  ** a pointer to an [sqlite3_pcache_methods2] object.  This object specifies
  2810  ** the interface to a custom page cache implementation.)^
  2811  ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
  2812  **
  2813  ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  2814  ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
  2815  ** is a pointer to an [sqlite3_pcache_methods2] object.  SQLite copies of
  2816  ** the current page cache implementation into that object.)^ </dd>
  2817  **
  2818  ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  2819  ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  2820  ** global [error log].
  2821  ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  2822  ** function with a call signature of void(*)(void*,int,const char*), 
  2823  ** and a pointer to void. ^If the function pointer is not NULL, it is
  2824  ** invoked by [sqlite3_log()] to process each logging event.  ^If the
  2825  ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  2826  ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  2827  ** passed through as the first parameter to the application-defined logger
  2828  ** function whenever that function is invoked.  ^The second parameter to
  2829  ** the logger function is a copy of the first parameter to the corresponding
  2830  ** [sqlite3_log()] call and is intended to be a [result code] or an
  2831  ** [extended result code].  ^The third parameter passed to the logger is
  2832  ** log message after formatting via [sqlite3_snprintf()].
  2833  ** The SQLite logging interface is not reentrant; the logger function
  2834  ** supplied by the application must not invoke any SQLite interface.
  2835  ** In a multi-threaded application, the application-defined logger
  2836  ** function must be threadsafe. </dd>
  2837  **
  2838  ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  2839  ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
  2840  ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
  2841  ** then URI handling is globally disabled.)^ ^If URI handling is globally
  2842  ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
  2843  ** [sqlite3_open16()] or
  2844  ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  2845  ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  2846  ** connection is opened. ^If it is globally disabled, filenames are
  2847  ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  2848  ** database connection is opened. ^(By default, URI handling is globally
  2849  ** disabled. The default value may be changed by compiling with the
  2850  ** [SQLITE_USE_URI] symbol defined.)^
  2851  **
  2852  ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  2853  ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
  2854  ** argument which is interpreted as a boolean in order to enable or disable
  2855  ** the use of covering indices for full table scans in the query optimizer.
  2856  ** ^The default setting is determined
  2857  ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  2858  ** if that compile-time option is omitted.
  2859  ** The ability to disable the use of covering indices for full table scans
  2860  ** is because some incorrectly coded legacy applications might malfunction
  2861  ** when the optimization is enabled.  Providing the ability to
  2862  ** disable the optimization allows the older, buggy application code to work
  2863  ** without change even with newer versions of SQLite.
  2864  **
  2865  ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  2866  ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  2867  ** <dd> These options are obsolete and should not be used by new code.
  2868  ** They are retained for backwards compatibility but are now no-ops.
  2869  ** </dd>
  2870  **
  2871  ** [[SQLITE_CONFIG_SQLLOG]]
  2872  ** <dt>SQLITE_CONFIG_SQLLOG
  2873  ** <dd>This option is only available if sqlite is compiled with the
  2874  ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  2875  ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  2876  ** The second should be of type (void*). The callback is invoked by the library
  2877  ** in three separate circumstances, identified by the value passed as the
  2878  ** fourth parameter. If the fourth parameter is 0, then the database connection
  2879  ** passed as the second argument has just been opened. The third argument
  2880  ** points to a buffer containing the name of the main database file. If the
  2881  ** fourth parameter is 1, then the SQL statement that the third parameter
  2882  ** points to has just been executed. Or, if the fourth parameter is 2, then
  2883  ** the connection being passed as the second parameter is being closed. The
  2884  ** third parameter is passed NULL In this case.  An example of using this
  2885  ** configuration option can be seen in the "test_sqllog.c" source file in
  2886  ** the canonical SQLite source tree.</dd>
  2887  **
  2888  ** [[SQLITE_CONFIG_MMAP_SIZE]]
  2889  ** <dt>SQLITE_CONFIG_MMAP_SIZE
  2890  ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  2891  ** that are the default mmap size limit (the default setting for
  2892  ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  2893  ** ^The default setting can be overridden by each database connection using
  2894  ** either the [PRAGMA mmap_size] command, or by using the
  2895  ** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size
  2896  ** will be silently truncated if necessary so that it does not exceed the
  2897  ** compile-time maximum mmap size set by the
  2898  ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  2899  ** ^If either argument to this option is negative, then that argument is
  2900  ** changed to its compile-time default.
  2901  **
  2902  ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
  2903  ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
  2904  ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
  2905  ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
  2906  ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
  2907  ** that specifies the maximum size of the created heap.
  2908  **
  2909  ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
  2910  ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
  2911  ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
  2912  ** is a pointer to an integer and writes into that integer the number of extra
  2913  ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
  2914  ** The amount of extra space required can change depending on the compiler,
  2915  ** target platform, and SQLite version.
  2916  **
  2917  ** [[SQLITE_CONFIG_PMASZ]]
  2918  ** <dt>SQLITE_CONFIG_PMASZ
  2919  ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
  2920  ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
  2921  ** sorter to that integer.  The default minimum PMA Size is set by the
  2922  ** [SQLITE_SORTER_PMASZ] compile-time option.  New threads are launched
  2923  ** to help with sort operations when multithreaded sorting
  2924  ** is enabled (using the [PRAGMA threads] command) and the amount of content
  2925  ** to be sorted exceeds the page size times the minimum of the
  2926  ** [PRAGMA cache_size] setting and this value.
  2927  **
  2928  ** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
  2929  ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
  2930  ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
  2931  ** becomes the [statement journal] spill-to-disk threshold.  
  2932  ** [Statement journals] are held in memory until their size (in bytes)
  2933  ** exceeds this threshold, at which point they are written to disk.
  2934  ** Or if the threshold is -1, statement journals are always held
  2935  ** exclusively in memory.
  2936  ** Since many statement journals never become large, setting the spill
  2937  ** threshold to a value such as 64KiB can greatly reduce the amount of
  2938  ** I/O required to support statement rollback.
  2939  ** The default value for this setting is controlled by the
  2940  ** [SQLITE_STMTJRNL_SPILL] compile-time option.
  2941  ** </dl>
  2942  */
  2943  #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
  2944  #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
  2945  #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
  2946  #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
  2947  #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
  2948  #define SQLITE_CONFIG_SCRATCH       6  /* No longer used */
  2949  #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
  2950  #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
  2951  #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
  2952  #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
  2953  #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
  2954  /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
  2955  #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
  2956  #define SQLITE_CONFIG_PCACHE       14  /* no-op */
  2957  #define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
  2958  #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
  2959  #define SQLITE_CONFIG_URI          17  /* int */
  2960  #define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
  2961  #define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
  2962  #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
  2963  #define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
  2964  #define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */
  2965  #define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
  2966  #define SQLITE_CONFIG_PCACHE_HDRSZ        24  /* int *psz */
  2967  #define SQLITE_CONFIG_PMASZ               25  /* unsigned int szPma */
  2968  #define SQLITE_CONFIG_STMTJRNL_SPILL      26  /* int nByte */
  2969  #define SQLITE_CONFIG_SMALL_MALLOC        27  /* boolean */
  2970  
  2971  /*
  2972  ** CAPI3REF: Database Connection Configuration Options
  2973  **
  2974  ** These constants are the available integer configuration options that
  2975  ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  2976  **
  2977  ** New configuration options may be added in future releases of SQLite.
  2978  ** Existing configuration options might be discontinued.  Applications
  2979  ** should check the return code from [sqlite3_db_config()] to make sure that
  2980  ** the call worked.  ^The [sqlite3_db_config()] interface will return a
  2981  ** non-zero [error code] if a discontinued or unsupported configuration option
  2982  ** is invoked.
  2983  **
  2984  ** <dl>
  2985  ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  2986  ** <dd> ^This option takes three additional arguments that determine the 
  2987  ** [lookaside memory allocator] configuration for the [database connection].
  2988  ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  2989  ** pointer to a memory buffer to use for lookaside memory.
  2990  ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  2991  ** may be NULL in which case SQLite will allocate the
  2992  ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  2993  ** size of each lookaside buffer slot.  ^The third argument is the number of
  2994  ** slots.  The size of the buffer in the first argument must be greater than
  2995  ** or equal to the product of the second and third arguments.  The buffer
  2996  ** must be aligned to an 8-byte boundary.  ^If the second argument to
  2997  ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  2998  ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
  2999  ** configuration for a database connection can only be changed when that
  3000  ** connection is not currently using lookaside memory, or in other words
  3001  ** when the "current value" returned by
  3002  ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  3003  ** Any attempt to change the lookaside memory configuration when lookaside
  3004  ** memory is in use leaves the configuration unchanged and returns 
  3005  ** [SQLITE_BUSY].)^</dd>
  3006  **
  3007  ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  3008  ** <dd> ^This option is used to enable or disable the enforcement of
  3009  ** [foreign key constraints].  There should be two additional arguments.
  3010  ** The first argument is an integer which is 0 to disable FK enforcement,
  3011  ** positive to enable FK enforcement or negative to leave FK enforcement
  3012  ** unchanged.  The second parameter is a pointer to an integer into which
  3013  ** is written 0 or 1 to indicate whether FK enforcement is off or on
  3014  ** following this call.  The second parameter may be a NULL pointer, in
  3015  ** which case the FK enforcement setting is not reported back. </dd>
  3016  **
  3017  ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  3018  ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  3019  ** There should be two additional arguments.
  3020  ** The first argument is an integer which is 0 to disable triggers,
  3021  ** positive to enable triggers or negative to leave the setting unchanged.
  3022  ** The second parameter is a pointer to an integer into which
  3023  ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  3024  ** following this call.  The second parameter may be a NULL pointer, in
  3025  ** which case the trigger setting is not reported back. </dd>
  3026  **
  3027  ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
  3028  ** <dd> ^This option is used to enable or disable the two-argument
  3029  ** version of the [fts3_tokenizer()] function which is part of the
  3030  ** [FTS3] full-text search engine extension.
  3031  ** There should be two additional arguments.
  3032  ** The first argument is an integer which is 0 to disable fts3_tokenizer() or
  3033  ** positive to enable fts3_tokenizer() or negative to leave the setting
  3034  ** unchanged.
  3035  ** The second parameter is a pointer to an integer into which
  3036  ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
  3037  ** following this call.  The second parameter may be a NULL pointer, in
  3038  ** which case the new setting is not reported back. </dd>
  3039  **
  3040  ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
  3041  ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
  3042  ** interface independently of the [load_extension()] SQL function.
  3043  ** The [sqlite3_enable_load_extension()] API enables or disables both the
  3044  ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
  3045  ** There should be two additional arguments.
  3046  ** When the first argument to this interface is 1, then only the C-API is
  3047  ** enabled and the SQL function remains disabled.  If the first argument to
  3048  ** this interface is 0, then both the C-API and the SQL function are disabled.
  3049  ** If the first argument is -1, then no changes are made to state of either the
  3050  ** C-API or the SQL function.
  3051  ** The second parameter is a pointer to an integer into which
  3052  ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
  3053  ** is disabled or enabled following this call.  The second parameter may
  3054  ** be a NULL pointer, in which case the new setting is not reported back.
  3055  ** </dd>
  3056  **
  3057  ** <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
  3058  ** <dd> ^This option is used to change the name of the "main" database
  3059  ** schema.  ^The sole argument is a pointer to a constant UTF8 string
  3060  ** which will become the new schema name in place of "main".  ^SQLite
  3061  ** does not make a copy of the new main schema name string, so the application
  3062  ** must ensure that the argument passed into this DBCONFIG option is unchanged
  3063  ** until after the database connection closes.
  3064  ** </dd>
  3065  **
  3066  ** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
  3067  ** <dd> Usually, when a database in wal mode is closed or detached from a 
  3068  ** database handle, SQLite checks if this will mean that there are now no 
  3069  ** connections at all to the database. If so, it performs a checkpoint 
  3070  ** operation before closing the connection. This option may be used to
  3071  ** override this behaviour. The first parameter passed to this operation
  3072  ** is an integer - non-zero to disable checkpoints-on-close, or zero (the
  3073  ** default) to enable them. The second parameter is a pointer to an integer
  3074  ** into which is written 0 or 1 to indicate whether checkpoints-on-close
  3075  ** have been disabled - 0 if they are not disabled, 1 if they are.
  3076  ** </dd>
  3077  **
  3078  ** <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>
  3079  ** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates
  3080  ** the [query planner stability guarantee] (QPSG).  When the QPSG is active,
  3081  ** a single SQL query statement will always use the same algorithm regardless
  3082  ** of values of [bound parameters].)^ The QPSG disables some query optimizations
  3083  ** that look at the values of bound parameters, which can make some queries
  3084  ** slower.  But the QPSG has the advantage of more predictable behavior.  With
  3085  ** the QPSG active, SQLite will always use the same query plan in the field as
  3086  ** was used during testing in the lab.
  3087  ** </dd>
  3088  **
  3089  ** </dl>
  3090  */
  3091  #define SQLITE_DBCONFIG_MAINDBNAME            1000 /* const char* */
  3092  #define SQLITE_DBCONFIG_LOOKASIDE             1001 /* void* int int */
  3093  #define SQLITE_DBCONFIG_ENABLE_FKEY           1002 /* int int* */
  3094  #define SQLITE_DBCONFIG_ENABLE_TRIGGER        1003 /* int int* */
  3095  #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
  3096  #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
  3097  #define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      1006 /* int int* */
  3098  #define SQLITE_DBCONFIG_ENABLE_QPSG           1007 /* int int* */
  3099  
  3100  
  3101  /*
  3102  ** CAPI3REF: Enable Or Disable Extended Result Codes
  3103  ** METHOD: sqlite3
  3104  **
  3105  ** ^The sqlite3_extended_result_codes() routine enables or disables the
  3106  ** [extended result codes] feature of SQLite. ^The extended result
  3107  ** codes are disabled by default for historical compatibility.
  3108  */
  3109  SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  3110  
  3111  /*
  3112  ** CAPI3REF: Last Insert Rowid
  3113  ** METHOD: sqlite3
  3114  **
  3115  ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
  3116  ** has a unique 64-bit signed
  3117  ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  3118  ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  3119  ** names are not also used by explicitly declared columns. ^If
  3120  ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  3121  ** is another alias for the rowid.
  3122  **
  3123  ** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
  3124  ** the most recent successful [INSERT] into a rowid table or [virtual table]
  3125  ** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
  3126  ** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred 
  3127  ** on the database connection D, then sqlite3_last_insert_rowid(D) returns 
  3128  ** zero.
  3129  **
  3130  ** As well as being set automatically as rows are inserted into database
  3131  ** tables, the value returned by this function may be set explicitly by
  3132  ** [sqlite3_set_last_insert_rowid()]
  3133  **
  3134  ** Some virtual table implementations may INSERT rows into rowid tables as
  3135  ** part of committing a transaction (e.g. to flush data accumulated in memory
  3136  ** to disk). In this case subsequent calls to this function return the rowid
  3137  ** associated with these internal INSERT operations, which leads to 
  3138  ** unintuitive results. Virtual table implementations that do write to rowid
  3139  ** tables in this way can avoid this problem by restoring the original 
  3140  ** rowid value using [sqlite3_set_last_insert_rowid()] before returning 
  3141  ** control to the user.
  3142  **
  3143  ** ^(If an [INSERT] occurs within a trigger then this routine will 
  3144  ** return the [rowid] of the inserted row as long as the trigger is 
  3145  ** running. Once the trigger program ends, the value returned 
  3146  ** by this routine reverts to what it was before the trigger was fired.)^
  3147  **
  3148  ** ^An [INSERT] that fails due to a constraint violation is not a
  3149  ** successful [INSERT] and does not change the value returned by this
  3150  ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  3151  ** and INSERT OR ABORT make no changes to the return value of this
  3152  ** routine when their insertion fails.  ^(When INSERT OR REPLACE
  3153  ** encounters a constraint violation, it does not fail.  The
  3154  ** INSERT continues to completion after deleting rows that caused
  3155  ** the constraint problem so INSERT OR REPLACE will always change
  3156  ** the return value of this interface.)^
  3157  **
  3158  ** ^For the purposes of this routine, an [INSERT] is considered to
  3159  ** be successful even if it is subsequently rolled back.
  3160  **
  3161  ** This function is accessible to SQL statements via the
  3162  ** [last_insert_rowid() SQL function].
  3163  **
  3164  ** If a separate thread performs a new [INSERT] on the same
  3165  ** database connection while the [sqlite3_last_insert_rowid()]
  3166  ** function is running and thus changes the last insert [rowid],
  3167  ** then the value returned by [sqlite3_last_insert_rowid()] is
  3168  ** unpredictable and might not equal either the old or the new
  3169  ** last insert [rowid].
  3170  */
  3171  SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  3172  
  3173  /*
  3174  ** CAPI3REF: Set the Last Insert Rowid value.
  3175  ** METHOD: sqlite3
  3176  **
  3177  ** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
  3178  ** set the value returned by calling sqlite3_last_insert_rowid(D) to R 
  3179  ** without inserting a row into the database.
  3180  */
  3181  SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
  3182  
  3183  /*
  3184  ** CAPI3REF: Count The Number Of Rows Modified
  3185  ** METHOD: sqlite3
  3186  **
  3187  ** ^This function returns the number of rows modified, inserted or
  3188  ** deleted by the most recently completed INSERT, UPDATE or DELETE
  3189  ** statement on the database connection specified by the only parameter.
  3190  ** ^Executing any other type of SQL statement does not modify the value
  3191  ** returned by this function.
  3192  **
  3193  ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
  3194  ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers], 
  3195  ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
  3196  ** 
  3197  ** Changes to a view that are intercepted by 
  3198  ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value 
  3199  ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or 
  3200  ** DELETE statement run on a view is always zero. Only changes made to real 
  3201  ** tables are counted.
  3202  **
  3203  ** Things are more complicated if the sqlite3_changes() function is
  3204  ** executed while a trigger program is running. This may happen if the
  3205  ** program uses the [changes() SQL function], or if some other callback
  3206  ** function invokes sqlite3_changes() directly. Essentially:
  3207  ** 
  3208  ** <ul>
  3209  **   <li> ^(Before entering a trigger program the value returned by
  3210  **        sqlite3_changes() function is saved. After the trigger program 
  3211  **        has finished, the original value is restored.)^
  3212  ** 
  3213  **   <li> ^(Within a trigger program each INSERT, UPDATE and DELETE 
  3214  **        statement sets the value returned by sqlite3_changes() 
  3215  **        upon completion as normal. Of course, this value will not include 
  3216  **        any changes performed by sub-triggers, as the sqlite3_changes() 
  3217  **        value will be saved and restored after each sub-trigger has run.)^
  3218  ** </ul>
  3219  ** 
  3220  ** ^This means that if the changes() SQL function (or similar) is used
  3221  ** by the first INSERT, UPDATE or DELETE statement within a trigger, it 
  3222  ** returns the value as set when the calling statement began executing.
  3223  ** ^If it is used by the second or subsequent such statement within a trigger 
  3224  ** program, the value returned reflects the number of rows modified by the 
  3225  ** previous INSERT, UPDATE or DELETE statement within the same trigger.
  3226  **
  3227  ** See also the [sqlite3_total_changes()] interface, the
  3228  ** [count_changes pragma], and the [changes() SQL function].
  3229  **
  3230  ** If a separate thread makes changes on the same database connection
  3231  ** while [sqlite3_changes()] is running then the value returned
  3232  ** is unpredictable and not meaningful.
  3233  */
  3234  SQLITE_API int sqlite3_changes(sqlite3*);
  3235  
  3236  /*
  3237  ** CAPI3REF: Total Number Of Rows Modified
  3238  ** METHOD: sqlite3
  3239  **
  3240  ** ^This function returns the total number of rows inserted, modified or
  3241  ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
  3242  ** since the database connection was opened, including those executed as
  3243  ** part of trigger programs. ^Executing any other type of SQL statement
  3244  ** does not affect the value returned by sqlite3_total_changes().
  3245  ** 
  3246  ** ^Changes made as part of [foreign key actions] are included in the
  3247  ** count, but those made as part of REPLACE constraint resolution are
  3248  ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers 
  3249  ** are not counted.
  3250  ** 
  3251  ** See also the [sqlite3_changes()] interface, the
  3252  ** [count_changes pragma], and the [total_changes() SQL function].
  3253  **
  3254  ** If a separate thread makes changes on the same database connection
  3255  ** while [sqlite3_total_changes()] is running then the value
  3256  ** returned is unpredictable and not meaningful.
  3257  */
  3258  SQLITE_API int sqlite3_total_changes(sqlite3*);
  3259  
  3260  /*
  3261  ** CAPI3REF: Interrupt A Long-Running Query
  3262  ** METHOD: sqlite3
  3263  **
  3264  ** ^This function causes any pending database operation to abort and
  3265  ** return at its earliest opportunity. This routine is typically
  3266  ** called in response to a user action such as pressing "Cancel"
  3267  ** or Ctrl-C where the user wants a long query operation to halt
  3268  ** immediately.
  3269  **
  3270  ** ^It is safe to call this routine from a thread different from the
  3271  ** thread that is currently running the database operation.  But it
  3272  ** is not safe to call this routine with a [database connection] that
  3273  ** is closed or might close before sqlite3_interrupt() returns.
  3274  **
  3275  ** ^If an SQL operation is very nearly finished at the time when
  3276  ** sqlite3_interrupt() is called, then it might not have an opportunity
  3277  ** to be interrupted and might continue to completion.
  3278  **
  3279  ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  3280  ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  3281  ** that is inside an explicit transaction, then the entire transaction
  3282  ** will be rolled back automatically.
  3283  **
  3284  ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  3285  ** SQL statements on [database connection] D complete.  ^Any new SQL statements
  3286  ** that are started after the sqlite3_interrupt() call and before the 
  3287  ** running statements reaches zero are interrupted as if they had been
  3288  ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
  3289  ** that are started after the running statement count reaches zero are
  3290  ** not effected by the sqlite3_interrupt().
  3291  ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  3292  ** SQL statements is a no-op and has no effect on SQL statements
  3293  ** that are started after the sqlite3_interrupt() call returns.
  3294  */
  3295  SQLITE_API void sqlite3_interrupt(sqlite3*);
  3296  
  3297  /*
  3298  ** CAPI3REF: Determine If An SQL Statement Is Complete
  3299  **
  3300  ** These routines are useful during command-line input to determine if the
  3301  ** currently entered text seems to form a complete SQL statement or
  3302  ** if additional input is needed before sending the text into
  3303  ** SQLite for parsing.  ^These routines return 1 if the input string
  3304  ** appears to be a complete SQL statement.  ^A statement is judged to be
  3305  ** complete if it ends with a semicolon token and is not a prefix of a
  3306  ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
  3307  ** string literals or quoted identifier names or comments are not
  3308  ** independent tokens (they are part of the token in which they are
  3309  ** embedded) and thus do not count as a statement terminator.  ^Whitespace
  3310  ** and comments that follow the final semicolon are ignored.
  3311  **
  3312  ** ^These routines return 0 if the statement is incomplete.  ^If a
  3313  ** memory allocation fails, then SQLITE_NOMEM is returned.
  3314  **
  3315  ** ^These routines do not parse the SQL statements thus
  3316  ** will not detect syntactically incorrect SQL.
  3317  **
  3318  ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
  3319  ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  3320  ** automatically by sqlite3_complete16().  If that initialization fails,
  3321  ** then the return value from sqlite3_complete16() will be non-zero
  3322  ** regardless of whether or not the input SQL is complete.)^
  3323  **
  3324  ** The input to [sqlite3_complete()] must be a zero-terminated
  3325  ** UTF-8 string.
  3326  **
  3327  ** The input to [sqlite3_complete16()] must be a zero-terminated
  3328  ** UTF-16 string in native byte order.
  3329  */
  3330  SQLITE_API int sqlite3_complete(const char *sql);
  3331  SQLITE_API int sqlite3_complete16(const void *sql);
  3332  
  3333  /*
  3334  ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  3335  ** KEYWORDS: {busy-handler callback} {busy handler}
  3336  ** METHOD: sqlite3
  3337  **
  3338  ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
  3339  ** that might be invoked with argument P whenever
  3340  ** an attempt is made to access a database table associated with
  3341  ** [database connection] D when another thread
  3342  ** or process has the table locked.
  3343  ** The sqlite3_busy_handler() interface is used to implement
  3344  ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
  3345  **
  3346  ** ^If the busy callback is NULL, then [SQLITE_BUSY]
  3347  ** is returned immediately upon encountering the lock.  ^If the busy callback
  3348  ** is not NULL, then the callback might be invoked with two arguments.
  3349  **
  3350  ** ^The first argument to the busy handler is a copy of the void* pointer which
  3351  ** is the third argument to sqlite3_busy_handler().  ^The second argument to
  3352  ** the busy handler callback is the number of times that the busy handler has
  3353  ** been invoked previously for the same locking event.  ^If the
  3354  ** busy callback returns 0, then no additional attempts are made to
  3355  ** access the database and [SQLITE_BUSY] is returned
  3356  ** to the application.
  3357  ** ^If the callback returns non-zero, then another attempt
  3358  ** is made to access the database and the cycle repeats.
  3359  **
  3360  ** The presence of a busy handler does not guarantee that it will be invoked
  3361  ** when there is lock contention. ^If SQLite determines that invoking the busy
  3362  ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  3363  ** to the application instead of invoking the 
  3364  ** busy handler.
  3365  ** Consider a scenario where one process is holding a read lock that
  3366  ** it is trying to promote to a reserved lock and
  3367  ** a second process is holding a reserved lock that it is trying
  3368  ** to promote to an exclusive lock.  The first process cannot proceed
  3369  ** because it is blocked by the second and the second process cannot
  3370  ** proceed because it is blocked by the first.  If both processes
  3371  ** invoke the busy handlers, neither will make any progress.  Therefore,
  3372  ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  3373  ** will induce the first process to release its read lock and allow
  3374  ** the second process to proceed.
  3375  **
  3376  ** ^The default busy callback is NULL.
  3377  **
  3378  ** ^(There can only be a single busy handler defined for each
  3379  ** [database connection].  Setting a new busy handler clears any
  3380  ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
  3381  ** or evaluating [PRAGMA busy_timeout=N] will change the
  3382  ** busy handler and thus clear any previously set busy handler.
  3383  **
  3384  ** The busy callback should not take any actions which modify the
  3385  ** database connection that invoked the busy handler.  In other words,
  3386  ** the busy handler is not reentrant.  Any such actions
  3387  ** result in undefined behavior.
  3388  ** 
  3389  ** A busy handler must not close the database connection
  3390  ** or [prepared statement] that invoked the busy handler.
  3391  */
  3392  SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
  3393  
  3394  /*
  3395  ** CAPI3REF: Set A Busy Timeout
  3396  ** METHOD: sqlite3
  3397  **
  3398  ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  3399  ** for a specified amount of time when a table is locked.  ^The handler
  3400  ** will sleep multiple times until at least "ms" milliseconds of sleeping
  3401  ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
  3402  ** the handler returns 0 which causes [sqlite3_step()] to return
  3403  ** [SQLITE_BUSY].
  3404  **
  3405  ** ^Calling this routine with an argument less than or equal to zero
  3406  ** turns off all busy handlers.
  3407  **
  3408  ** ^(There can only be a single busy handler for a particular
  3409  ** [database connection] at any given moment.  If another busy handler
  3410  ** was defined  (using [sqlite3_busy_handler()]) prior to calling
  3411  ** this routine, that other busy handler is cleared.)^
  3412  **
  3413  ** See also:  [PRAGMA busy_timeout]
  3414  */
  3415  SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  3416  
  3417  /*
  3418  ** CAPI3REF: Convenience Routines For Running Queries
  3419  ** METHOD: sqlite3
  3420  **
  3421  ** This is a legacy interface that is preserved for backwards compatibility.
  3422  ** Use of this interface is not recommended.
  3423  **
  3424  ** Definition: A <b>result table</b> is memory data structure created by the
  3425  ** [sqlite3_get_table()] interface.  A result table records the
  3426  ** complete query results from one or more queries.
  3427  **
  3428  ** The table conceptually has a number of rows and columns.  But
  3429  ** these numbers are not part of the result table itself.  These
  3430  ** numbers are obtained separately.  Let N be the number of rows
  3431  ** and M be the number of columns.
  3432  **
  3433  ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  3434  ** There are (N+1)*M elements in the array.  The first M pointers point
  3435  ** to zero-terminated strings that  contain the names of the columns.
  3436  ** The remaining entries all point to query results.  NULL values result
  3437  ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
  3438  ** string representation as returned by [sqlite3_column_text()].
  3439  **
  3440  ** A result table might consist of one or more memory allocations.
  3441  ** It is not safe to pass a result table directly to [sqlite3_free()].
  3442  ** A result table should be deallocated using [sqlite3_free_table()].
  3443  **
  3444  ** ^(As an example of the result table format, suppose a query result
  3445  ** is as follows:
  3446  **
  3447  ** <blockquote><pre>
  3448  **        Name        | Age
  3449  **        -----------------------
  3450  **        Alice       | 43
  3451  **        Bob         | 28
  3452  **        Cindy       | 21
  3453  ** </pre></blockquote>
  3454  **
  3455  ** There are two column (M==2) and three rows (N==3).  Thus the
  3456  ** result table has 8 entries.  Suppose the result table is stored
  3457  ** in an array names azResult.  Then azResult holds this content:
  3458  **
  3459  ** <blockquote><pre>
  3460  **        azResult&#91;0] = "Name";
  3461  **        azResult&#91;1] = "Age";
  3462  **        azResult&#91;2] = "Alice";
  3463  **        azResult&#91;3] = "43";
  3464  **        azResult&#91;4] = "Bob";
  3465  **        azResult&#91;5] = "28";
  3466  **        azResult&#91;6] = "Cindy";
  3467  **        azResult&#91;7] = "21";
  3468  ** </pre></blockquote>)^
  3469  **
  3470  ** ^The sqlite3_get_table() function evaluates one or more
  3471  ** semicolon-separated SQL statements in the zero-terminated UTF-8
  3472  ** string of its 2nd parameter and returns a result table to the
  3473  ** pointer given in its 3rd parameter.
  3474  **
  3475  ** After the application has finished with the result from sqlite3_get_table(),
  3476  ** it must pass the result table pointer to sqlite3_free_table() in order to
  3477  ** release the memory that was malloced.  Because of the way the
  3478  ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  3479  ** function must not try to call [sqlite3_free()] directly.  Only
  3480  ** [sqlite3_free_table()] is able to release the memory properly and safely.
  3481  **
  3482  ** The sqlite3_get_table() interface is implemented as a wrapper around
  3483  ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
  3484  ** to any internal data structures of SQLite.  It uses only the public
  3485  ** interface defined here.  As a consequence, errors that occur in the
  3486  ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  3487  ** reflected in subsequent calls to [sqlite3_errcode()] or
  3488  ** [sqlite3_errmsg()].
  3489  */
  3490  SQLITE_API int sqlite3_get_table(
  3491    sqlite3 *db,          /* An open database */
  3492    const char *zSql,     /* SQL to be evaluated */
  3493    char ***pazResult,    /* Results of the query */
  3494    int *pnRow,           /* Number of result rows written here */
  3495    int *pnColumn,        /* Number of result columns written here */
  3496    char **pzErrmsg       /* Error msg written here */
  3497  );
  3498  SQLITE_API void sqlite3_free_table(char **result);
  3499  
  3500  /*
  3501  ** CAPI3REF: Formatted String Printing Functions
  3502  **
  3503  ** These routines are work-alikes of the "printf()" family of functions
  3504  ** from the standard C library.
  3505  ** These routines understand most of the common K&R formatting options,
  3506  ** plus some additional non-standard formats, detailed below.
  3507  ** Note that some of the more obscure formatting options from recent
  3508  ** C-library standards are omitted from this implementation.
  3509  **
  3510  ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  3511  ** results into memory obtained from [sqlite3_malloc()].
  3512  ** The strings returned by these two routines should be
  3513  ** released by [sqlite3_free()].  ^Both routines return a
  3514  ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  3515  ** memory to hold the resulting string.
  3516  **
  3517  ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  3518  ** the standard C library.  The result is written into the
  3519  ** buffer supplied as the second parameter whose size is given by
  3520  ** the first parameter. Note that the order of the
  3521  ** first two parameters is reversed from snprintf().)^  This is an
  3522  ** historical accident that cannot be fixed without breaking
  3523  ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
  3524  ** returns a pointer to its buffer instead of the number of
  3525  ** characters actually written into the buffer.)^  We admit that
  3526  ** the number of characters written would be a more useful return
  3527  ** value but we cannot change the implementation of sqlite3_snprintf()
  3528  ** now without breaking compatibility.
  3529  **
  3530  ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  3531  ** guarantees that the buffer is always zero-terminated.  ^The first
  3532  ** parameter "n" is the total size of the buffer, including space for
  3533  ** the zero terminator.  So the longest string that can be completely
  3534  ** written will be n-1 characters.
  3535  **
  3536  ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  3537  **
  3538  ** These routines all implement some additional formatting
  3539  ** options that are useful for constructing SQL statements.
  3540  ** All of the usual printf() formatting options apply.  In addition, there
  3541  ** is are "%q", "%Q", "%w" and "%z" options.
  3542  **
  3543  ** ^(The %q option works like %s in that it substitutes a nul-terminated
  3544  ** string from the argument list.  But %q also doubles every '\'' character.
  3545  ** %q is designed for use inside a string literal.)^  By doubling each '\''
  3546  ** character it escapes that character and allows it to be inserted into
  3547  ** the string.
  3548  **
  3549  ** For example, assume the string variable zText contains text as follows:
  3550  **
  3551  ** <blockquote><pre>
  3552  **  char *zText = "It's a happy day!";
  3553  ** </pre></blockquote>
  3554  **
  3555  ** One can use this text in an SQL statement as follows:
  3556  **
  3557  ** <blockquote><pre>
  3558  **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  3559  **  sqlite3_exec(db, zSQL, 0, 0, 0);
  3560  **  sqlite3_free(zSQL);
  3561  ** </pre></blockquote>
  3562  **
  3563  ** Because the %q format string is used, the '\'' character in zText
  3564  ** is escaped and the SQL generated is as follows:
  3565  **
  3566  ** <blockquote><pre>
  3567  **  INSERT INTO table1 VALUES('It''s a happy day!')
  3568  ** </pre></blockquote>
  3569  **
  3570  ** This is correct.  Had we used %s instead of %q, the generated SQL
  3571  ** would have looked like this:
  3572  **
  3573  ** <blockquote><pre>
  3574  **  INSERT INTO table1 VALUES('It's a happy day!');
  3575  ** </pre></blockquote>
  3576  **
  3577  ** This second example is an SQL syntax error.  As a general rule you should
  3578  ** always use %q instead of %s when inserting text into a string literal.
  3579  **
  3580  ** ^(The %Q option works like %q except it also adds single quotes around
  3581  ** the outside of the total string.  Additionally, if the parameter in the
  3582  ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  3583  ** single quotes).)^  So, for example, one could say:
  3584  **
  3585  ** <blockquote><pre>
  3586  **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  3587  **  sqlite3_exec(db, zSQL, 0, 0, 0);
  3588  **  sqlite3_free(zSQL);
  3589  ** </pre></blockquote>
  3590  **
  3591  ** The code above will render a correct SQL statement in the zSQL
  3592  ** variable even if the zText variable is a NULL pointer.
  3593  **
  3594  ** ^(The "%w" formatting option is like "%q" except that it expects to
  3595  ** be contained within double-quotes instead of single quotes, and it
  3596  ** escapes the double-quote character instead of the single-quote
  3597  ** character.)^  The "%w" formatting option is intended for safely inserting
  3598  ** table and column names into a constructed SQL statement.
  3599  **
  3600  ** ^(The "%z" formatting option works like "%s" but with the
  3601  ** addition that after the string has been read and copied into
  3602  ** the result, [sqlite3_free()] is called on the input string.)^
  3603  */
  3604  SQLITE_API char *sqlite3_mprintf(const char*,...);
  3605  SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  3606  SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  3607  SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  3608  
  3609  /*
  3610  ** CAPI3REF: Memory Allocation Subsystem
  3611  **
  3612  ** The SQLite core uses these three routines for all of its own
  3613  ** internal memory allocation needs. "Core" in the previous sentence
  3614  ** does not include operating-system specific VFS implementation.  The
  3615  ** Windows VFS uses native malloc() and free() for some operations.
  3616  **
  3617  ** ^The sqlite3_malloc() routine returns a pointer to a block
  3618  ** of memory at least N bytes in length, where N is the parameter.
  3619  ** ^If sqlite3_malloc() is unable to obtain sufficient free
  3620  ** memory, it returns a NULL pointer.  ^If the parameter N to
  3621  ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  3622  ** a NULL pointer.
  3623  **
  3624  ** ^The sqlite3_malloc64(N) routine works just like
  3625  ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
  3626  ** of a signed 32-bit integer.
  3627  **
  3628  ** ^Calling sqlite3_free() with a pointer previously returned
  3629  ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  3630  ** that it might be reused.  ^The sqlite3_free() routine is
  3631  ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
  3632  ** to sqlite3_free() is harmless.  After being freed, memory
  3633  ** should neither be read nor written.  Even reading previously freed
  3634  ** memory might result in a segmentation fault or other severe error.
  3635  ** Memory corruption, a segmentation fault, or other severe error
  3636  ** might result if sqlite3_free() is called with a non-NULL pointer that
  3637  ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  3638  **
  3639  ** ^The sqlite3_realloc(X,N) interface attempts to resize a
  3640  ** prior memory allocation X to be at least N bytes.
  3641  ** ^If the X parameter to sqlite3_realloc(X,N)
  3642  ** is a NULL pointer then its behavior is identical to calling
  3643  ** sqlite3_malloc(N).
  3644  ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
  3645  ** negative then the behavior is exactly the same as calling
  3646  ** sqlite3_free(X).
  3647  ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
  3648  ** of at least N bytes in size or NULL if insufficient memory is available.
  3649  ** ^If M is the size of the prior allocation, then min(N,M) bytes
  3650  ** of the prior allocation are copied into the beginning of buffer returned
  3651  ** by sqlite3_realloc(X,N) and the prior allocation is freed.
  3652  ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
  3653  ** prior allocation is not freed.
  3654  **
  3655  ** ^The sqlite3_realloc64(X,N) interfaces works the same as
  3656  ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
  3657  ** of a 32-bit signed integer.
  3658  **
  3659  ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
  3660  ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
  3661  ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
  3662  ** ^The value returned by sqlite3_msize(X) might be larger than the number
  3663  ** of bytes requested when X was allocated.  ^If X is a NULL pointer then
  3664  ** sqlite3_msize(X) returns zero.  If X points to something that is not
  3665  ** the beginning of memory allocation, or if it points to a formerly
  3666  ** valid memory allocation that has now been freed, then the behavior
  3667  ** of sqlite3_msize(X) is undefined and possibly harmful.
  3668  **
  3669  ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
  3670  ** sqlite3_malloc64(), and sqlite3_realloc64()
  3671  ** is always aligned to at least an 8 byte boundary, or to a
  3672  ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  3673  ** option is used.
  3674  **
  3675  ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  3676  ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  3677  ** implementation of these routines to be omitted.  That capability
  3678  ** is no longer provided.  Only built-in memory allocators can be used.
  3679  **
  3680  ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  3681  ** the system malloc() and free() directly when converting
  3682  ** filenames between the UTF-8 encoding used by SQLite
  3683  ** and whatever filename encoding is used by the particular Windows
  3684  ** installation.  Memory allocation errors were detected, but
  3685  ** they were reported back as [SQLITE_CANTOPEN] or
  3686  ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  3687  **
  3688  ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  3689  ** must be either NULL or else pointers obtained from a prior
  3690  ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  3691  ** not yet been released.
  3692  **
  3693  ** The application must not read or write any part of
  3694  ** a block of memory after it has been released using
  3695  ** [sqlite3_free()] or [sqlite3_realloc()].
  3696  */
  3697  SQLITE_API void *sqlite3_malloc(int);
  3698  SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
  3699  SQLITE_API void *sqlite3_realloc(void*, int);
  3700  SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
  3701  SQLITE_API void sqlite3_free(void*);
  3702  SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
  3703  
  3704  /*
  3705  ** CAPI3REF: Memory Allocator Statistics
  3706  **
  3707  ** SQLite provides these two interfaces for reporting on the status
  3708  ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  3709  ** routines, which form the built-in memory allocation subsystem.
  3710  **
  3711  ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  3712  ** of memory currently outstanding (malloced but not freed).
  3713  ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  3714  ** value of [sqlite3_memory_used()] since the high-water mark
  3715  ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
  3716  ** [sqlite3_memory_highwater()] include any overhead
  3717  ** added by SQLite in its implementation of [sqlite3_malloc()],
  3718  ** but not overhead added by the any underlying system library
  3719  ** routines that [sqlite3_malloc()] may call.
  3720  **
  3721  ** ^The memory high-water mark is reset to the current value of
  3722  ** [sqlite3_memory_used()] if and only if the parameter to
  3723  ** [sqlite3_memory_highwater()] is true.  ^The value returned
  3724  ** by [sqlite3_memory_highwater(1)] is the high-water mark
  3725  ** prior to the reset.
  3726  */
  3727  SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  3728  SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  3729  
  3730  /*
  3731  ** CAPI3REF: Pseudo-Random Number Generator
  3732  **
  3733  ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  3734  ** select random [ROWID | ROWIDs] when inserting new records into a table that
  3735  ** already uses the largest possible [ROWID].  The PRNG is also used for
  3736  ** the build-in random() and randomblob() SQL functions.  This interface allows
  3737  ** applications to access the same PRNG for other purposes.
  3738  **
  3739  ** ^A call to this routine stores N bytes of randomness into buffer P.
  3740  ** ^The P parameter can be a NULL pointer.
  3741  **
  3742  ** ^If this routine has not been previously called or if the previous
  3743  ** call had N less than one or a NULL pointer for P, then the PRNG is
  3744  ** seeded using randomness obtained from the xRandomness method of
  3745  ** the default [sqlite3_vfs] object.
  3746  ** ^If the previous call to this routine had an N of 1 or more and a
  3747  ** non-NULL P then the pseudo-randomness is generated
  3748  ** internally and without recourse to the [sqlite3_vfs] xRandomness
  3749  ** method.
  3750  */
  3751  SQLITE_API void sqlite3_randomness(int N, void *P);
  3752  
  3753  /*
  3754  ** CAPI3REF: Compile-Time Authorization Callbacks
  3755  ** METHOD: sqlite3
  3756  ** KEYWORDS: {authorizer callback}
  3757  **
  3758  ** ^This routine registers an authorizer callback with a particular
  3759  ** [database connection], supplied in the first argument.
  3760  ** ^The authorizer callback is invoked as SQL statements are being compiled
  3761  ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  3762  ** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()],
  3763  ** and [sqlite3_prepare16_v3()].  ^At various
  3764  ** points during the compilation process, as logic is being created
  3765  ** to perform various actions, the authorizer callback is invoked to
  3766  ** see if those actions are allowed.  ^The authorizer callback should
  3767  ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  3768  ** specific action but allow the SQL statement to continue to be
  3769  ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  3770  ** rejected with an error.  ^If the authorizer callback returns
  3771  ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  3772  ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  3773  ** the authorizer will fail with an error message.
  3774  **
  3775  ** When the callback returns [SQLITE_OK], that means the operation
  3776  ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
  3777  ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  3778  ** authorizer will fail with an error message explaining that
  3779  ** access is denied. 
  3780  **
  3781  ** ^The first parameter to the authorizer callback is a copy of the third
  3782  ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  3783  ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  3784  ** the particular action to be authorized. ^The third through sixth parameters
  3785  ** to the callback are either NULL pointers or zero-terminated strings
  3786  ** that contain additional details about the action to be authorized.
  3787  ** Applications must always be prepared to encounter a NULL pointer in any
  3788  ** of the third through the sixth parameters of the authorization callback.
  3789  **
  3790  ** ^If the action code is [SQLITE_READ]
  3791  ** and the callback returns [SQLITE_IGNORE] then the
  3792  ** [prepared statement] statement is constructed to substitute
  3793  ** a NULL value in place of the table column that would have
  3794  ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
  3795  ** return can be used to deny an untrusted user access to individual
  3796  ** columns of a table.
  3797  ** ^When a table is referenced by a [SELECT] but no column values are
  3798  ** extracted from that table (for example in a query like
  3799  ** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback
  3800  ** is invoked once for that table with a column name that is an empty string.
  3801  ** ^If the action code is [SQLITE_DELETE] and the callback returns
  3802  ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  3803  ** [truncate optimization] is disabled and all rows are deleted individually.
  3804  **
  3805  ** An authorizer is used when [sqlite3_prepare | preparing]
  3806  ** SQL statements from an untrusted source, to ensure that the SQL statements
  3807  ** do not try to access data they are not allowed to see, or that they do not
  3808  ** try to execute malicious statements that damage the database.  For
  3809  ** example, an application may allow a user to enter arbitrary
  3810  ** SQL queries for evaluation by a database.  But the application does
  3811  ** not want the user to be able to make arbitrary changes to the
  3812  ** database.  An authorizer could then be put in place while the
  3813  ** user-entered SQL is being [sqlite3_prepare | prepared] that
  3814  ** disallows everything except [SELECT] statements.
  3815  **
  3816  ** Applications that need to process SQL from untrusted sources
  3817  ** might also consider lowering resource limits using [sqlite3_limit()]
  3818  ** and limiting database size using the [max_page_count] [PRAGMA]
  3819  ** in addition to using an authorizer.
  3820  **
  3821  ** ^(Only a single authorizer can be in place on a database connection
  3822  ** at a time.  Each call to sqlite3_set_authorizer overrides the
  3823  ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
  3824  ** The authorizer is disabled by default.
  3825  **
  3826  ** The authorizer callback must not do anything that will modify
  3827  ** the database connection that invoked the authorizer callback.
  3828  ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  3829  ** database connections for the meaning of "modify" in this paragraph.
  3830  **
  3831  ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  3832  ** statement might be re-prepared during [sqlite3_step()] due to a 
  3833  ** schema change.  Hence, the application should ensure that the
  3834  ** correct authorizer callback remains in place during the [sqlite3_step()].
  3835  **
  3836  ** ^Note that the authorizer callback is invoked only during
  3837  ** [sqlite3_prepare()] or its variants.  Authorization is not
  3838  ** performed during statement evaluation in [sqlite3_step()], unless
  3839  ** as stated in the previous paragraph, sqlite3_step() invokes
  3840  ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  3841  */
  3842  SQLITE_API int sqlite3_set_authorizer(
  3843    sqlite3*,
  3844    int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  3845    void *pUserData
  3846  );
  3847  
  3848  /*
  3849  ** CAPI3REF: Authorizer Return Codes
  3850  **
  3851  ** The [sqlite3_set_authorizer | authorizer callback function] must
  3852  ** return either [SQLITE_OK] or one of these two constants in order
  3853  ** to signal SQLite whether or not the action is permitted.  See the
  3854  ** [sqlite3_set_authorizer | authorizer documentation] for additional
  3855  ** information.
  3856  **
  3857  ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
  3858  ** returned from the [sqlite3_vtab_on_conflict()] interface.
  3859  */
  3860  #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
  3861  #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
  3862  
  3863  /*
  3864  ** CAPI3REF: Authorizer Action Codes
  3865  **
  3866  ** The [sqlite3_set_authorizer()] interface registers a callback function
  3867  ** that is invoked to authorize certain SQL statement actions.  The
  3868  ** second parameter to the callback is an integer code that specifies
  3869  ** what action is being authorized.  These are the integer action codes that
  3870  ** the authorizer callback may be passed.
  3871  **
  3872  ** These action code values signify what kind of operation is to be
  3873  ** authorized.  The 3rd and 4th parameters to the authorization
  3874  ** callback function will be parameters or NULL depending on which of these
  3875  ** codes is used as the second parameter.  ^(The 5th parameter to the
  3876  ** authorizer callback is the name of the database ("main", "temp",
  3877  ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
  3878  ** is the name of the inner-most trigger or view that is responsible for
  3879  ** the access attempt or NULL if this access attempt is directly from
  3880  ** top-level SQL code.
  3881  */
  3882  /******************************************* 3rd ************ 4th ***********/
  3883  #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
  3884  #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
  3885  #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
  3886  #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
  3887  #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
  3888  #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
  3889  #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
  3890  #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
  3891  #define SQLITE_DELETE                9   /* Table Name      NULL            */
  3892  #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
  3893  #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
  3894  #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
  3895  #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
  3896  #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
  3897  #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
  3898  #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
  3899  #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
  3900  #define SQLITE_INSERT               18   /* Table Name      NULL            */
  3901  #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
  3902  #define SQLITE_READ                 20   /* Table Name      Column Name     */
  3903  #define SQLITE_SELECT               21   /* NULL            NULL            */
  3904  #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
  3905  #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
  3906  #define SQLITE_ATTACH               24   /* Filename        NULL            */
  3907  #define SQLITE_DETACH               25   /* Database Name   NULL            */
  3908  #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
  3909  #define SQLITE_REINDEX              27   /* Index Name      NULL            */
  3910  #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
  3911  #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
  3912  #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
  3913  #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
  3914  #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
  3915  #define SQLITE_COPY                  0   /* No longer used */
  3916  #define SQLITE_RECURSIVE            33   /* NULL            NULL            */
  3917  
  3918  /*
  3919  ** CAPI3REF: Tracing And Profiling Functions
  3920  ** METHOD: sqlite3
  3921  **
  3922  ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
  3923  ** instead of the routines described here.
  3924  **
  3925  ** These routines register callback functions that can be used for
  3926  ** tracing and profiling the execution of SQL statements.
  3927  **
  3928  ** ^The callback function registered by sqlite3_trace() is invoked at
  3929  ** various times when an SQL statement is being run by [sqlite3_step()].
  3930  ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  3931  ** SQL statement text as the statement first begins executing.
  3932  ** ^(Additional sqlite3_trace() callbacks might occur
  3933  ** as each triggered subprogram is entered.  The callbacks for triggers
  3934  ** contain a UTF-8 SQL comment that identifies the trigger.)^
  3935  **
  3936  ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  3937  ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  3938  **
  3939  ** ^The callback function registered by sqlite3_profile() is invoked
  3940  ** as each SQL statement finishes.  ^The profile callback contains
  3941  ** the original statement text and an estimate of wall-clock time
  3942  ** of how long that statement took to run.  ^The profile callback
  3943  ** time is in units of nanoseconds, however the current implementation
  3944  ** is only capable of millisecond resolution so the six least significant
  3945  ** digits in the time are meaningless.  Future versions of SQLite
  3946  ** might provide greater resolution on the profiler callback.  The
  3947  ** sqlite3_profile() function is considered experimental and is
  3948  ** subject to change in future versions of SQLite.
  3949  */
  3950  SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
  3951     void(*xTrace)(void*,const char*), void*);
  3952  SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
  3953     void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  3954  
  3955  /*
  3956  ** CAPI3REF: SQL Trace Event Codes
  3957  ** KEYWORDS: SQLITE_TRACE
  3958  **
  3959  ** These constants identify classes of events that can be monitored
  3960  ** using the [sqlite3_trace_v2()] tracing logic.  The third argument
  3961  ** to [sqlite3_trace_v2()] is an OR-ed combination of one or more of
  3962  ** the following constants.  ^The first argument to the trace callback
  3963  ** is one of the following constants.
  3964  **
  3965  ** New tracing constants may be added in future releases.
  3966  **
  3967  ** ^A trace callback has four arguments: xCallback(T,C,P,X).
  3968  ** ^The T argument is one of the integer type codes above.
  3969  ** ^The C argument is a copy of the context pointer passed in as the
  3970  ** fourth argument to [sqlite3_trace_v2()].
  3971  ** The P and X arguments are pointers whose meanings depend on T.
  3972  **
  3973  ** <dl>
  3974  ** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
  3975  ** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
  3976  ** first begins running and possibly at other times during the
  3977  ** execution of the prepared statement, such as at the start of each
  3978  ** trigger subprogram. ^The P argument is a pointer to the
  3979  ** [prepared statement]. ^The X argument is a pointer to a string which
  3980  ** is the unexpanded SQL text of the prepared statement or an SQL comment 
  3981  ** that indicates the invocation of a trigger.  ^The callback can compute
  3982  ** the same text that would have been returned by the legacy [sqlite3_trace()]
  3983  ** interface by using the X argument when X begins with "--" and invoking
  3984  ** [sqlite3_expanded_sql(P)] otherwise.
  3985  **
  3986  ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
  3987  ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
  3988  ** information as is provided by the [sqlite3_profile()] callback.
  3989  ** ^The P argument is a pointer to the [prepared statement] and the
  3990  ** X argument points to a 64-bit integer which is the estimated of
  3991  ** the number of nanosecond that the prepared statement took to run.
  3992  ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
  3993  **
  3994  ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
  3995  ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
  3996  ** statement generates a single row of result.  
  3997  ** ^The P argument is a pointer to the [prepared statement] and the
  3998  ** X argument is unused.
  3999  **
  4000  ** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
  4001  ** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
  4002  ** connection closes.
  4003  ** ^The P argument is a pointer to the [database connection] object
  4004  ** and the X argument is unused.
  4005  ** </dl>
  4006  */
  4007  #define SQLITE_TRACE_STMT       0x01
  4008  #define SQLITE_TRACE_PROFILE    0x02
  4009  #define SQLITE_TRACE_ROW        0x04
  4010  #define SQLITE_TRACE_CLOSE      0x08
  4011  
  4012  /*
  4013  ** CAPI3REF: SQL Trace Hook
  4014  ** METHOD: sqlite3
  4015  **
  4016  ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
  4017  ** function X against [database connection] D, using property mask M
  4018  ** and context pointer P.  ^If the X callback is
  4019  ** NULL or if the M mask is zero, then tracing is disabled.  The
  4020  ** M argument should be the bitwise OR-ed combination of
  4021  ** zero or more [SQLITE_TRACE] constants.
  4022  **
  4023  ** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides 
  4024  ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
  4025  **
  4026  ** ^The X callback is invoked whenever any of the events identified by 
  4027  ** mask M occur.  ^The integer return value from the callback is currently
  4028  ** ignored, though this may change in future releases.  Callback
  4029  ** implementations should return zero to ensure future compatibility.
  4030  **
  4031  ** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
  4032  ** ^The T argument is one of the [SQLITE_TRACE]
  4033  ** constants to indicate why the callback was invoked.
  4034  ** ^The C argument is a copy of the context pointer.
  4035  ** The P and X arguments are pointers whose meanings depend on T.
  4036  **
  4037  ** The sqlite3_trace_v2() interface is intended to replace the legacy
  4038  ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
  4039  ** are deprecated.
  4040  */
  4041  SQLITE_API int sqlite3_trace_v2(
  4042    sqlite3*,
  4043    unsigned uMask,
  4044    int(*xCallback)(unsigned,void*,void*,void*),
  4045    void *pCtx
  4046  );
  4047  
  4048  /*
  4049  ** CAPI3REF: Query Progress Callbacks
  4050  ** METHOD: sqlite3
  4051  **
  4052  ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  4053  ** function X to be invoked periodically during long running calls to
  4054  ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  4055  ** database connection D.  An example use for this
  4056  ** interface is to keep a GUI updated during a large query.
  4057  **
  4058  ** ^The parameter P is passed through as the only parameter to the 
  4059  ** callback function X.  ^The parameter N is the approximate number of 
  4060  ** [virtual machine instructions] that are evaluated between successive
  4061  ** invocations of the callback X.  ^If N is less than one then the progress
  4062  ** handler is disabled.
  4063  **
  4064  ** ^Only a single progress handler may be defined at one time per
  4065  ** [database connection]; setting a new progress handler cancels the
  4066  ** old one.  ^Setting parameter X to NULL disables the progress handler.
  4067  ** ^The progress handler is also disabled by setting N to a value less
  4068  ** than 1.
  4069  **
  4070  ** ^If the progress callback returns non-zero, the operation is
  4071  ** interrupted.  This feature can be used to implement a
  4072  ** "Cancel" button on a GUI progress dialog box.
  4073  **
  4074  ** The progress handler callback must not do anything that will modify
  4075  ** the database connection that invoked the progress handler.
  4076  ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  4077  ** database connections for the meaning of "modify" in this paragraph.
  4078  **
  4079  */
  4080  SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  4081  
  4082  /*
  4083  ** CAPI3REF: Opening A New Database Connection
  4084  ** CONSTRUCTOR: sqlite3
  4085  **
  4086  ** ^These routines open an SQLite database file as specified by the 
  4087  ** filename argument. ^The filename argument is interpreted as UTF-8 for
  4088  ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  4089  ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  4090  ** returned in *ppDb, even if an error occurs.  The only exception is that
  4091  ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  4092  ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  4093  ** object.)^ ^(If the database is opened (and/or created) successfully, then
  4094  ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
  4095  ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  4096  ** an English language description of the error following a failure of any
  4097  ** of the sqlite3_open() routines.
  4098  **
  4099  ** ^The default encoding will be UTF-8 for databases created using
  4100  ** sqlite3_open() or sqlite3_open_v2().  ^The default encoding for databases
  4101  ** created using sqlite3_open16() will be UTF-16 in the native byte order.
  4102  **
  4103  ** Whether or not an error occurs when it is opened, resources
  4104  ** associated with the [database connection] handle should be released by
  4105  ** passing it to [sqlite3_close()] when it is no longer required.
  4106  **
  4107  ** The sqlite3_open_v2() interface works like sqlite3_open()
  4108  ** except that it accepts two additional parameters for additional control
  4109  ** over the new database connection.  ^(The flags parameter to
  4110  ** sqlite3_open_v2() can take one of
  4111  ** the following three values, optionally combined with the 
  4112  ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  4113  ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  4114  **
  4115  ** <dl>
  4116  ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  4117  ** <dd>The database is opened in read-only mode.  If the database does not
  4118  ** already exist, an error is returned.</dd>)^
  4119  **
  4120  ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  4121  ** <dd>The database is opened for reading and writing if possible, or reading
  4122  ** only if the file is write protected by the operating system.  In either
  4123  ** case the database must already exist, otherwise an error is returned.</dd>)^
  4124  **
  4125  ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  4126  ** <dd>The database is opened for reading and writing, and is created if
  4127  ** it does not already exist. This is the behavior that is always used for
  4128  ** sqlite3_open() and sqlite3_open16().</dd>)^
  4129  ** </dl>
  4130  **
  4131  ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  4132  ** combinations shown above optionally combined with other
  4133  ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  4134  ** then the behavior is undefined.
  4135  **
  4136  ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  4137  ** opens in the multi-thread [threading mode] as long as the single-thread
  4138  ** mode has not been set at compile-time or start-time.  ^If the
  4139  ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  4140  ** in the serialized [threading mode] unless single-thread was
  4141  ** previously selected at compile-time or start-time.
  4142  ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  4143  ** eligible to use [shared cache mode], regardless of whether or not shared
  4144  ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
  4145  ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  4146  ** participate in [shared cache mode] even if it is enabled.
  4147  **
  4148  ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  4149  ** [sqlite3_vfs] object that defines the operating system interface that
  4150  ** the new database connection should use.  ^If the fourth parameter is
  4151  ** a NULL pointer then the default [sqlite3_vfs] object is used.
  4152  **
  4153  ** ^If the filename is ":memory:", then a private, temporary in-memory database
  4154  ** is created for the connection.  ^This in-memory database will vanish when
  4155  ** the database connection is closed.  Future versions of SQLite might
  4156  ** make use of additional special filenames that begin with the ":" character.
  4157  ** It is recommended that when a database filename actually does begin with
  4158  ** a ":" character you should prefix the filename with a pathname such as
  4159  ** "./" to avoid ambiguity.
  4160  **
  4161  ** ^If the filename is an empty string, then a private, temporary
  4162  ** on-disk database will be created.  ^This private database will be
  4163  ** automatically deleted as soon as the database connection is closed.
  4164  **
  4165  ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  4166  **
  4167  ** ^If [URI filename] interpretation is enabled, and the filename argument
  4168  ** begins with "file:", then the filename is interpreted as a URI. ^URI
  4169  ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  4170  ** set in the third argument to sqlite3_open_v2(), or if it has
  4171  ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  4172  ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  4173  ** URI filename interpretation is turned off
  4174  ** by default, but future releases of SQLite might enable URI filename
  4175  ** interpretation by default.  See "[URI filenames]" for additional
  4176  ** information.
  4177  **
  4178  ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  4179  ** authority, then it must be either an empty string or the string 
  4180  ** "localhost". ^If the authority is not an empty string or "localhost", an 
  4181  ** error is returned to the caller. ^The fragment component of a URI, if 
  4182  ** present, is ignored.
  4183  **
  4184  ** ^SQLite uses the path component of the URI as the name of the disk file
  4185  ** which contains the database. ^If the path begins with a '/' character, 
  4186  ** then it is interpreted as an absolute path. ^If the path does not begin 
  4187  ** with a '/' (meaning that the authority section is omitted from the URI)
  4188  ** then the path is interpreted as a relative path. 
  4189  ** ^(On windows, the first component of an absolute path 
  4190  ** is a drive specification (e.g. "C:").)^
  4191  **
  4192  ** [[core URI query parameters]]
  4193  ** The query component of a URI may contain parameters that are interpreted
  4194  ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  4195  ** SQLite and its built-in [VFSes] interpret the
  4196  ** following query parameters:
  4197  **
  4198  ** <ul>
  4199  **   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  4200  **     a VFS object that provides the operating system interface that should
  4201  **     be used to access the database file on disk. ^If this option is set to
  4202  **     an empty string the default VFS object is used. ^Specifying an unknown
  4203  **     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  4204  **     present, then the VFS specified by the option takes precedence over
  4205  **     the value passed as the fourth parameter to sqlite3_open_v2().
  4206  **
  4207  **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  4208  **     "rwc", or "memory". Attempting to set it to any other value is
  4209  **     an error)^. 
  4210  **     ^If "ro" is specified, then the database is opened for read-only 
  4211  **     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the 
  4212  **     third argument to sqlite3_open_v2(). ^If the mode option is set to 
  4213  **     "rw", then the database is opened for read-write (but not create) 
  4214  **     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had 
  4215  **     been set. ^Value "rwc" is equivalent to setting both 
  4216  **     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
  4217  **     set to "memory" then a pure [in-memory database] that never reads
  4218  **     or writes from disk is used. ^It is an error to specify a value for
  4219  **     the mode parameter that is less restrictive than that specified by
  4220  **     the flags passed in the third parameter to sqlite3_open_v2().
  4221  **
  4222  **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  4223  **     "private". ^Setting it to "shared" is equivalent to setting the
  4224  **     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  4225  **     sqlite3_open_v2(). ^Setting the cache parameter to "private" is 
  4226  **     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  4227  **     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  4228  **     a URI filename, its value overrides any behavior requested by setting
  4229  **     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  4230  **
  4231  **  <li> <b>psow</b>: ^The psow parameter indicates whether or not the
  4232  **     [powersafe overwrite] property does or does not apply to the
  4233  **     storage media on which the database file resides.
  4234  **
  4235  **  <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
  4236  **     which if set disables file locking in rollback journal modes.  This
  4237  **     is useful for accessing a database on a filesystem that does not
  4238  **     support locking.  Caution:  Database corruption might result if two
  4239  **     or more processes write to the same database and any one of those
  4240  **     processes uses nolock=1.
  4241  **
  4242  **  <li> <b>immutable</b>: ^The immutable parameter is a boolean query
  4243  **     parameter that indicates that the database file is stored on
  4244  **     read-only media.  ^When immutable is set, SQLite assumes that the
  4245  **     database file cannot be changed, even by a process with higher
  4246  **     privilege, and so the database is opened read-only and all locking
  4247  **     and change detection is disabled.  Caution: Setting the immutable
  4248  **     property on a database file that does in fact change can result
  4249  **     in incorrect query results and/or [SQLITE_CORRUPT] errors.
  4250  **     See also: [SQLITE_IOCAP_IMMUTABLE].
  4251  **       
  4252  ** </ul>
  4253  **
  4254  ** ^Specifying an unknown parameter in the query component of a URI is not an
  4255  ** error.  Future versions of SQLite might understand additional query
  4256  ** parameters.  See "[query parameters with special meaning to SQLite]" for
  4257  ** additional information.
  4258  **
  4259  ** [[URI filename examples]] <h3>URI filename examples</h3>
  4260  **
  4261  ** <table border="1" align=center cellpadding=5>
  4262  ** <tr><th> URI filenames <th> Results
  4263  ** <tr><td> file:data.db <td> 
  4264  **          Open the file "data.db" in the current directory.
  4265  ** <tr><td> file:/home/fred/data.db<br>
  4266  **          file:///home/fred/data.db <br> 
  4267  **          file://localhost/home/fred/data.db <br> <td> 
  4268  **          Open the database file "/home/fred/data.db".
  4269  ** <tr><td> file://darkstar/home/fred/data.db <td> 
  4270  **          An error. "darkstar" is not a recognized authority.
  4271  ** <tr><td style="white-space:nowrap"> 
  4272  **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  4273  **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
  4274  **          C:. Note that the %20 escaping in this example is not strictly 
  4275  **          necessary - space characters can be used literally
  4276  **          in URI filenames.
  4277  ** <tr><td> file:data.db?mode=ro&cache=private <td> 
  4278  **          Open file "data.db" in the current directory for read-only access.
  4279  **          Regardless of whether or not shared-cache mode is enabled by
  4280  **          default, use a private cache.
  4281  ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
  4282  **          Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
  4283  **          that uses dot-files in place of posix advisory locking.
  4284  ** <tr><td> file:data.db?mode=readonly <td> 
  4285  **          An error. "readonly" is not a valid option for the "mode" parameter.
  4286  ** </table>
  4287  **
  4288  ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  4289  ** query components of a URI. A hexadecimal escape sequence consists of a
  4290  ** percent sign - "%" - followed by exactly two hexadecimal digits 
  4291  ** specifying an octet value. ^Before the path or query components of a
  4292  ** URI filename are interpreted, they are encoded using UTF-8 and all 
  4293  ** hexadecimal escape sequences replaced by a single byte containing the
  4294  ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  4295  ** the results are undefined.
  4296  **
  4297  ** <b>Note to Windows users:</b>  The encoding used for the filename argument
  4298  ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  4299  ** codepage is currently defined.  Filenames containing international
  4300  ** characters must be converted to UTF-8 prior to passing them into
  4301  ** sqlite3_open() or sqlite3_open_v2().
  4302  **
  4303  ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
  4304  ** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
  4305  ** features that require the use of temporary files may fail.
  4306  **
  4307  ** See also: [sqlite3_temp_directory]
  4308  */
  4309  SQLITE_API int sqlite3_open(
  4310    const char *filename,   /* Database filename (UTF-8) */
  4311    sqlite3 **ppDb          /* OUT: SQLite db handle */
  4312  );
  4313  SQLITE_API int sqlite3_open16(
  4314    const void *filename,   /* Database filename (UTF-16) */
  4315    sqlite3 **ppDb          /* OUT: SQLite db handle */
  4316  );
  4317  SQLITE_API int sqlite3_open_v2(
  4318    const char *filename,   /* Database filename (UTF-8) */
  4319    sqlite3 **ppDb,         /* OUT: SQLite db handle */
  4320    int flags,              /* Flags */
  4321    const char *zVfs        /* Name of VFS module to use */
  4322  );
  4323  
  4324  /*
  4325  ** CAPI3REF: Obtain Values For URI Parameters
  4326  **
  4327  ** These are utility routines, useful to VFS implementations, that check
  4328  ** to see if a database file was a URI that contained a specific query 
  4329  ** parameter, and if so obtains the value of that query parameter.
  4330  **
  4331  ** If F is the database filename pointer passed into the xOpen() method of 
  4332  ** a VFS implementation when the flags parameter to xOpen() has one or 
  4333  ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  4334  ** P is the name of the query parameter, then
  4335  ** sqlite3_uri_parameter(F,P) returns the value of the P
  4336  ** parameter if it exists or a NULL pointer if P does not appear as a 
  4337  ** query parameter on F.  If P is a query parameter of F
  4338  ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  4339  ** a pointer to an empty string.
  4340  **
  4341  ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  4342  ** parameter and returns true (1) or false (0) according to the value
  4343  ** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  4344  ** value of query parameter P is one of "yes", "true", or "on" in any
  4345  ** case or if the value begins with a non-zero number.  The 
  4346  ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  4347  ** query parameter P is one of "no", "false", or "off" in any case or
  4348  ** if the value begins with a numeric zero.  If P is not a query
  4349  ** parameter on F or if the value of P is does not match any of the
  4350  ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  4351  **
  4352  ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  4353  ** 64-bit signed integer and returns that integer, or D if P does not
  4354  ** exist.  If the value of P is something other than an integer, then
  4355  ** zero is returned.
  4356  ** 
  4357  ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  4358  ** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
  4359  ** is not a database file pathname pointer that SQLite passed into the xOpen
  4360  ** VFS method, then the behavior of this routine is undefined and probably
  4361  ** undesirable.
  4362  */
  4363  SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  4364  SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  4365  SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  4366  
  4367  
  4368  /*
  4369  ** CAPI3REF: Error Codes And Messages
  4370  ** METHOD: sqlite3
  4371  **
  4372  ** ^If the most recent sqlite3_* API call associated with 
  4373  ** [database connection] D failed, then the sqlite3_errcode(D) interface
  4374  ** returns the numeric [result code] or [extended result code] for that
  4375  ** API call.
  4376  ** If the most recent API call was successful,
  4377  ** then the return value from sqlite3_errcode() is undefined.
  4378  ** ^The sqlite3_extended_errcode()
  4379  ** interface is the same except that it always returns the 
  4380  ** [extended result code] even when extended result codes are
  4381  ** disabled.
  4382  **
  4383  ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  4384  ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  4385  ** ^(Memory to hold the error message string is managed internally.
  4386  ** The application does not need to worry about freeing the result.
  4387  ** However, the error string might be overwritten or deallocated by
  4388  ** subsequent calls to other SQLite interface functions.)^
  4389  **
  4390  ** ^The sqlite3_errstr() interface returns the English-language text
  4391  ** that describes the [result code], as UTF-8.
  4392  ** ^(Memory to hold the error message string is managed internally
  4393  ** and must not be freed by the application)^.
  4394  **
  4395  ** When the serialized [threading mode] is in use, it might be the
  4396  ** case that a second error occurs on a separate thread in between
  4397  ** the time of the first error and the call to these interfaces.
  4398  ** When that happens, the second error will be reported since these
  4399  ** interfaces always report the most recent result.  To avoid
  4400  ** this, each thread can obtain exclusive use of the [database connection] D
  4401  ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  4402  ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  4403  ** all calls to the interfaces listed here are completed.
  4404  **
  4405  ** If an interface fails with SQLITE_MISUSE, that means the interface
  4406  ** was invoked incorrectly by the application.  In that case, the
  4407  ** error code and message may or may not be set.
  4408  */
  4409  SQLITE_API int sqlite3_errcode(sqlite3 *db);
  4410  SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  4411  SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  4412  SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  4413  SQLITE_API const char *sqlite3_errstr(int);
  4414  
  4415  /*
  4416  ** CAPI3REF: Prepared Statement Object
  4417  ** KEYWORDS: {prepared statement} {prepared statements}
  4418  **
  4419  ** An instance of this object represents a single SQL statement that
  4420  ** has been compiled into binary form and is ready to be evaluated.
  4421  **
  4422  ** Think of each SQL statement as a separate computer program.  The
  4423  ** original SQL text is source code.  A prepared statement object 
  4424  ** is the compiled object code.  All SQL must be converted into a
  4425  ** prepared statement before it can be run.
  4426  **
  4427  ** The life-cycle of a prepared statement object usually goes like this:
  4428  **
  4429  ** <ol>
  4430  ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
  4431  ** <li> Bind values to [parameters] using the sqlite3_bind_*()
  4432  **      interfaces.
  4433  ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  4434  ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
  4435  **      to step 2.  Do this zero or more times.
  4436  ** <li> Destroy the object using [sqlite3_finalize()].
  4437  ** </ol>
  4438  */
  4439  typedef struct sqlite3_stmt sqlite3_stmt;
  4440  
  4441  /*
  4442  ** CAPI3REF: Run-time Limits
  4443  ** METHOD: sqlite3
  4444  **
  4445  ** ^(This interface allows the size of various constructs to be limited
  4446  ** on a connection by connection basis.  The first parameter is the
  4447  ** [database connection] whose limit is to be set or queried.  The
  4448  ** second parameter is one of the [limit categories] that define a
  4449  ** class of constructs to be size limited.  The third parameter is the
  4450  ** new limit for that construct.)^
  4451  **
  4452  ** ^If the new limit is a negative number, the limit is unchanged.
  4453  ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a 
  4454  ** [limits | hard upper bound]
  4455  ** set at compile-time by a C preprocessor macro called
  4456  ** [limits | SQLITE_MAX_<i>NAME</i>].
  4457  ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  4458  ** ^Attempts to increase a limit above its hard upper bound are
  4459  ** silently truncated to the hard upper bound.
  4460  **
  4461  ** ^Regardless of whether or not the limit was changed, the 
  4462  ** [sqlite3_limit()] interface returns the prior value of the limit.
  4463  ** ^Hence, to find the current value of a limit without changing it,
  4464  ** simply invoke this interface with the third parameter set to -1.
  4465  **
  4466  ** Run-time limits are intended for use in applications that manage
  4467  ** both their own internal database and also databases that are controlled
  4468  ** by untrusted external sources.  An example application might be a
  4469  ** web browser that has its own databases for storing history and
  4470  ** separate databases controlled by JavaScript applications downloaded
  4471  ** off the Internet.  The internal databases can be given the
  4472  ** large, default limits.  Databases managed by external sources can
  4473  ** be given much smaller limits designed to prevent a denial of service
  4474  ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
  4475  ** interface to further control untrusted SQL.  The size of the database
  4476  ** created by an untrusted script can be contained using the
  4477  ** [max_page_count] [PRAGMA].
  4478  **
  4479  ** New run-time limit categories may be added in future releases.
  4480  */
  4481  SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  4482  
  4483  /*
  4484  ** CAPI3REF: Run-Time Limit Categories
  4485  ** KEYWORDS: {limit category} {*limit categories}
  4486  **
  4487  ** These constants define various performance limits
  4488  ** that can be lowered at run-time using [sqlite3_limit()].
  4489  ** The synopsis of the meanings of the various limits is shown below.
  4490  ** Additional information is available at [limits | Limits in SQLite].
  4491  **
  4492  ** <dl>
  4493  ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  4494  ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  4495  **
  4496  ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  4497  ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  4498  **
  4499  ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  4500  ** <dd>The maximum number of columns in a table definition or in the
  4501  ** result set of a [SELECT] or the maximum number of columns in an index
  4502  ** or in an ORDER BY or GROUP BY clause.</dd>)^
  4503  **
  4504  ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  4505  ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  4506  **
  4507  ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  4508  ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  4509  **
  4510  ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  4511  ** <dd>The maximum number of instructions in a virtual machine program
  4512  ** used to implement an SQL statement.  If [sqlite3_prepare_v2()] or
  4513  ** the equivalent tries to allocate space for more than this many opcodes
  4514  ** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^
  4515  **
  4516  ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  4517  ** <dd>The maximum number of arguments on a function.</dd>)^
  4518  **
  4519  ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  4520  ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  4521  **
  4522  ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  4523  ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  4524  ** <dd>The maximum length of the pattern argument to the [LIKE] or
  4525  ** [GLOB] operators.</dd>)^
  4526  **
  4527  ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  4528  ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  4529  ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  4530  **
  4531  ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  4532  ** <dd>The maximum depth of recursion for triggers.</dd>)^
  4533  **
  4534  ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
  4535  ** <dd>The maximum number of auxiliary worker threads that a single
  4536  ** [prepared statement] may start.</dd>)^
  4537  ** </dl>
  4538  */
  4539  #define SQLITE_LIMIT_LENGTH                    0
  4540  #define SQLITE_LIMIT_SQL_LENGTH                1
  4541  #define SQLITE_LIMIT_COLUMN                    2
  4542  #define SQLITE_LIMIT_EXPR_DEPTH                3
  4543  #define SQLITE_LIMIT_COMPOUND_SELECT           4
  4544  #define SQLITE_LIMIT_VDBE_OP                   5
  4545  #define SQLITE_LIMIT_FUNCTION_ARG              6
  4546  #define SQLITE_LIMIT_ATTACHED                  7
  4547  #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
  4548  #define SQLITE_LIMIT_VARIABLE_NUMBER           9
  4549  #define SQLITE_LIMIT_TRIGGER_DEPTH            10
  4550  #define SQLITE_LIMIT_WORKER_THREADS           11
  4551  
  4552  /*
  4553  ** CAPI3REF: Prepare Flags
  4554  **
  4555  ** These constants define various flags that can be passed into
  4556  ** "prepFlags" parameter of the [sqlite3_prepare_v3()] and
  4557  ** [sqlite3_prepare16_v3()] interfaces.
  4558  **
  4559  ** New flags may be added in future releases of SQLite.
  4560  **
  4561  ** <dl>
  4562  ** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt>
  4563  ** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner
  4564  ** that the prepared statement will be retained for a long time and
  4565  ** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]
  4566  ** and [sqlite3_prepare16_v3()] assume that the prepared statement will 
  4567  ** be used just once or at most a few times and then destroyed using
  4568  ** [sqlite3_finalize()] relatively soon. The current implementation acts
  4569  ** on this hint by avoiding the use of [lookaside memory] so as not to
  4570  ** deplete the limited store of lookaside memory. Future versions of
  4571  ** SQLite may act on this hint differently.
  4572  ** </dl>
  4573  */
  4574  #define SQLITE_PREPARE_PERSISTENT              0x01
  4575  
  4576  /*
  4577  ** CAPI3REF: Compiling An SQL Statement
  4578  ** KEYWORDS: {SQL statement compiler}
  4579  ** METHOD: sqlite3
  4580  ** CONSTRUCTOR: sqlite3_stmt
  4581  **
  4582  ** To execute an SQL statement, it must first be compiled into a byte-code
  4583  ** program using one of these routines.  Or, in other words, these routines
  4584  ** are constructors for the [prepared statement] object.
  4585  **
  4586  ** The preferred routine to use is [sqlite3_prepare_v2()].  The
  4587  ** [sqlite3_prepare()] interface is legacy and should be avoided.
  4588  ** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used
  4589  ** for special purposes.
  4590  **
  4591  ** The use of the UTF-8 interfaces is preferred, as SQLite currently
  4592  ** does all parsing using UTF-8.  The UTF-16 interfaces are provided
  4593  ** as a convenience.  The UTF-16 interfaces work by converting the
  4594  ** input text into UTF-8, then invoking the corresponding UTF-8 interface.
  4595  **
  4596  ** The first argument, "db", is a [database connection] obtained from a
  4597  ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  4598  ** [sqlite3_open16()].  The database connection must not have been closed.
  4599  **
  4600  ** The second argument, "zSql", is the statement to be compiled, encoded
  4601  ** as either UTF-8 or UTF-16.  The sqlite3_prepare(), sqlite3_prepare_v2(),
  4602  ** and sqlite3_prepare_v3()
  4603  ** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),
  4604  ** and sqlite3_prepare16_v3() use UTF-16.
  4605  **
  4606  ** ^If the nByte argument is negative, then zSql is read up to the
  4607  ** first zero terminator. ^If nByte is positive, then it is the
  4608  ** number of bytes read from zSql.  ^If nByte is zero, then no prepared
  4609  ** statement is generated.
  4610  ** If the caller knows that the supplied string is nul-terminated, then
  4611  ** there is a small performance advantage to passing an nByte parameter that
  4612  ** is the number of bytes in the input string <i>including</i>
  4613  ** the nul-terminator.
  4614  **
  4615  ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  4616  ** past the end of the first SQL statement in zSql.  These routines only
  4617  ** compile the first statement in zSql, so *pzTail is left pointing to
  4618  ** what remains uncompiled.
  4619  **
  4620  ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  4621  ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
  4622  ** to NULL.  ^If the input text contains no SQL (if the input is an empty
  4623  ** string or a comment) then *ppStmt is set to NULL.
  4624  ** The calling procedure is responsible for deleting the compiled
  4625  ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  4626  ** ppStmt may not be NULL.
  4627  **
  4628  ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  4629  ** otherwise an [error code] is returned.
  4630  **
  4631  ** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),
  4632  ** and sqlite3_prepare16_v3() interfaces are recommended for all new programs.
  4633  ** The older interfaces (sqlite3_prepare() and sqlite3_prepare16())
  4634  ** are retained for backwards compatibility, but their use is discouraged.
  4635  ** ^In the "vX" interfaces, the prepared statement
  4636  ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  4637  ** original SQL text. This causes the [sqlite3_step()] interface to
  4638  ** behave differently in three ways:
  4639  **
  4640  ** <ol>
  4641  ** <li>
  4642  ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  4643  ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  4644  ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  4645  ** retries will occur before sqlite3_step() gives up and returns an error.
  4646  ** </li>
  4647  **
  4648  ** <li>
  4649  ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  4650  ** [error codes] or [extended error codes].  ^The legacy behavior was that
  4651  ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  4652  ** and the application would have to make a second call to [sqlite3_reset()]
  4653  ** in order to find the underlying cause of the problem. With the "v2" prepare
  4654  ** interfaces, the underlying reason for the error is returned immediately.
  4655  ** </li>
  4656  **
  4657  ** <li>
  4658  ** ^If the specific value bound to [parameter | host parameter] in the 
  4659  ** WHERE clause might influence the choice of query plan for a statement,
  4660  ** then the statement will be automatically recompiled, as if there had been 
  4661  ** a schema change, on the first  [sqlite3_step()] call following any change
  4662  ** to the [sqlite3_bind_text | bindings] of that [parameter]. 
  4663  ** ^The specific value of WHERE-clause [parameter] might influence the 
  4664  ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  4665  ** or [GLOB] operator or if the parameter is compared to an indexed column
  4666  ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  4667  ** </li>
  4668  **
  4669  ** <p>^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having
  4670  ** the extra prepFlags parameter, which is a bit array consisting of zero or
  4671  ** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags.  ^The
  4672  ** sqlite3_prepare_v2() interface works exactly the same as
  4673  ** sqlite3_prepare_v3() with a zero prepFlags parameter.
  4674  ** </ol>
  4675  */
  4676  SQLITE_API int sqlite3_prepare(
  4677    sqlite3 *db,            /* Database handle */
  4678    const char *zSql,       /* SQL statement, UTF-8 encoded */
  4679    int nByte,              /* Maximum length of zSql in bytes. */
  4680    sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  4681    const char **pzTail     /* OUT: Pointer to unused portion of zSql */
  4682  );
  4683  SQLITE_API int sqlite3_prepare_v2(
  4684    sqlite3 *db,            /* Database handle */
  4685    const char *zSql,       /* SQL statement, UTF-8 encoded */
  4686    int nByte,              /* Maximum length of zSql in bytes. */
  4687    sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  4688    const char **pzTail     /* OUT: Pointer to unused portion of zSql */
  4689  );
  4690  SQLITE_API int sqlite3_prepare_v3(
  4691    sqlite3 *db,            /* Database handle */
  4692    const char *zSql,       /* SQL statement, UTF-8 encoded */
  4693    int nByte,              /* Maximum length of zSql in bytes. */
  4694    unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
  4695    sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  4696    const char **pzTail     /* OUT: Pointer to unused portion of zSql */
  4697  );
  4698  SQLITE_API int sqlite3_prepare16(
  4699    sqlite3 *db,            /* Database handle */
  4700    const void *zSql,       /* SQL statement, UTF-16 encoded */
  4701    int nByte,              /* Maximum length of zSql in bytes. */
  4702    sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  4703    const void **pzTail     /* OUT: Pointer to unused portion of zSql */
  4704  );
  4705  SQLITE_API int sqlite3_prepare16_v2(
  4706    sqlite3 *db,            /* Database handle */
  4707    const void *zSql,       /* SQL statement, UTF-16 encoded */
  4708    int nByte,              /* Maximum length of zSql in bytes. */
  4709    sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  4710    const void **pzTail     /* OUT: Pointer to unused portion of zSql */
  4711  );
  4712  SQLITE_API int sqlite3_prepare16_v3(
  4713    sqlite3 *db,            /* Database handle */
  4714    const void *zSql,       /* SQL statement, UTF-16 encoded */
  4715    int nByte,              /* Maximum length of zSql in bytes. */
  4716    unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
  4717    sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  4718    const void **pzTail     /* OUT: Pointer to unused portion of zSql */
  4719  );
  4720  
  4721  /*
  4722  ** CAPI3REF: Retrieving Statement SQL
  4723  ** METHOD: sqlite3_stmt
  4724  **
  4725  ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
  4726  ** SQL text used to create [prepared statement] P if P was
  4727  ** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],
  4728  ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
  4729  ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
  4730  ** string containing the SQL text of prepared statement P with
  4731  ** [bound parameters] expanded.
  4732  **
  4733  ** ^(For example, if a prepared statement is created using the SQL
  4734  ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
  4735  ** and parameter :xyz is unbound, then sqlite3_sql() will return
  4736  ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
  4737  ** will return "SELECT 2345,NULL".)^
  4738  **
  4739  ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
  4740  ** is available to hold the result, or if the result would exceed the
  4741  ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
  4742  **
  4743  ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
  4744  ** bound parameter expansions.  ^The [SQLITE_OMIT_TRACE] compile-time
  4745  ** option causes sqlite3_expanded_sql() to always return NULL.
  4746  **
  4747  ** ^The string returned by sqlite3_sql(P) is managed by SQLite and is
  4748  ** automatically freed when the prepared statement is finalized.
  4749  ** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
  4750  ** is obtained from [sqlite3_malloc()] and must be free by the application
  4751  ** by passing it to [sqlite3_free()].
  4752  */
  4753  SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  4754  SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
  4755  
  4756  /*
  4757  ** CAPI3REF: Determine If An SQL Statement Writes The Database
  4758  ** METHOD: sqlite3_stmt
  4759  **
  4760  ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  4761  ** and only if the [prepared statement] X makes no direct changes to
  4762  ** the content of the database file.
  4763  **
  4764  ** Note that [application-defined SQL functions] or
  4765  ** [virtual tables] might change the database indirectly as a side effect.  
  4766  ** ^(For example, if an application defines a function "eval()" that 
  4767  ** calls [sqlite3_exec()], then the following SQL statement would
  4768  ** change the database file through side-effects:
  4769  **
  4770  ** <blockquote><pre>
  4771  **    SELECT eval('DELETE FROM t1') FROM t2;
  4772  ** </pre></blockquote>
  4773  **
  4774  ** But because the [SELECT] statement does not change the database file
  4775  ** directly, sqlite3_stmt_readonly() would still return true.)^
  4776  **
  4777  ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  4778  ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  4779  ** since the statements themselves do not actually modify the database but
  4780  ** rather they control the timing of when other statements modify the 
  4781  ** database.  ^The [ATTACH] and [DETACH] statements also cause
  4782  ** sqlite3_stmt_readonly() to return true since, while those statements
  4783  ** change the configuration of a database connection, they do not make 
  4784  ** changes to the content of the database files on disk.
  4785  ** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
  4786  ** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
  4787  ** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
  4788  ** sqlite3_stmt_readonly() returns false for those commands.
  4789  */
  4790  SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  4791  
  4792  /*
  4793  ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  4794  ** METHOD: sqlite3_stmt
  4795  **
  4796  ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  4797  ** [prepared statement] S has been stepped at least once using 
  4798  ** [sqlite3_step(S)] but has neither run to completion (returned
  4799  ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
  4800  ** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
  4801  ** interface returns false if S is a NULL pointer.  If S is not a 
  4802  ** NULL pointer and is not a pointer to a valid [prepared statement]
  4803  ** object, then the behavior is undefined and probably undesirable.
  4804  **
  4805  ** This interface can be used in combination [sqlite3_next_stmt()]
  4806  ** to locate all prepared statements associated with a database 
  4807  ** connection that are in need of being reset.  This can be used,
  4808  ** for example, in diagnostic routines to search for prepared 
  4809  ** statements that are holding a transaction open.
  4810  */
  4811  SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  4812  
  4813  /*
  4814  ** CAPI3REF: Dynamically Typed Value Object
  4815  ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  4816  **
  4817  ** SQLite uses the sqlite3_value object to represent all values
  4818  ** that can be stored in a database table. SQLite uses dynamic typing
  4819  ** for the values it stores.  ^Values stored in sqlite3_value objects
  4820  ** can be integers, floating point values, strings, BLOBs, or NULL.
  4821  **
  4822  ** An sqlite3_value object may be either "protected" or "unprotected".
  4823  ** Some interfaces require a protected sqlite3_value.  Other interfaces
  4824  ** will accept either a protected or an unprotected sqlite3_value.
  4825  ** Every interface that accepts sqlite3_value arguments specifies
  4826  ** whether or not it requires a protected sqlite3_value.  The
  4827  ** [sqlite3_value_dup()] interface can be used to construct a new 
  4828  ** protected sqlite3_value from an unprotected sqlite3_value.
  4829  **
  4830  ** The terms "protected" and "unprotected" refer to whether or not
  4831  ** a mutex is held.  An internal mutex is held for a protected
  4832  ** sqlite3_value object but no mutex is held for an unprotected
  4833  ** sqlite3_value object.  If SQLite is compiled to be single-threaded
  4834  ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  4835  ** or if SQLite is run in one of reduced mutex modes 
  4836  ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  4837  ** then there is no distinction between protected and unprotected
  4838  ** sqlite3_value objects and they can be used interchangeably.  However,
  4839  ** for maximum code portability it is recommended that applications
  4840  ** still make the distinction between protected and unprotected
  4841  ** sqlite3_value objects even when not strictly required.
  4842  **
  4843  ** ^The sqlite3_value objects that are passed as parameters into the
  4844  ** implementation of [application-defined SQL functions] are protected.
  4845  ** ^The sqlite3_value object returned by
  4846  ** [sqlite3_column_value()] is unprotected.
  4847  ** Unprotected sqlite3_value objects may only be used as arguments
  4848  ** to [sqlite3_result_value()], [sqlite3_bind_value()], and
  4849  ** [sqlite3_value_dup()].
  4850  ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  4851  ** interfaces require protected sqlite3_value objects.
  4852  */
  4853  typedef struct sqlite3_value sqlite3_value;
  4854  
  4855  /*
  4856  ** CAPI3REF: SQL Function Context Object
  4857  **
  4858  ** The context in which an SQL function executes is stored in an
  4859  ** sqlite3_context object.  ^A pointer to an sqlite3_context object
  4860  ** is always first parameter to [application-defined SQL functions].
  4861  ** The application-defined SQL function implementation will pass this
  4862  ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  4863  ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  4864  ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  4865  ** and/or [sqlite3_set_auxdata()].
  4866  */
  4867  typedef struct sqlite3_context sqlite3_context;
  4868  
  4869  /*
  4870  ** CAPI3REF: Binding Values To Prepared Statements
  4871  ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  4872  ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  4873  ** METHOD: sqlite3_stmt
  4874  **
  4875  ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  4876  ** literals may be replaced by a [parameter] that matches one of following
  4877  ** templates:
  4878  **
  4879  ** <ul>
  4880  ** <li>  ?
  4881  ** <li>  ?NNN
  4882  ** <li>  :VVV
  4883  ** <li>  @VVV
  4884  ** <li>  $VVV
  4885  ** </ul>
  4886  **
  4887  ** In the templates above, NNN represents an integer literal,
  4888  ** and VVV represents an alphanumeric identifier.)^  ^The values of these
  4889  ** parameters (also called "host parameter names" or "SQL parameters")
  4890  ** can be set using the sqlite3_bind_*() routines defined here.
  4891  **
  4892  ** ^The first argument to the sqlite3_bind_*() routines is always
  4893  ** a pointer to the [sqlite3_stmt] object returned from
  4894  ** [sqlite3_prepare_v2()] or its variants.
  4895  **
  4896  ** ^The second argument is the index of the SQL parameter to be set.
  4897  ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
  4898  ** SQL parameter is used more than once, second and subsequent
  4899  ** occurrences have the same index as the first occurrence.
  4900  ** ^The index for named parameters can be looked up using the
  4901  ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
  4902  ** for "?NNN" parameters is the value of NNN.
  4903  ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  4904  ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  4905  **
  4906  ** ^The third argument is the value to bind to the parameter.
  4907  ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  4908  ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  4909  ** is ignored and the end result is the same as sqlite3_bind_null().
  4910  **
  4911  ** ^(In those routines that have a fourth argument, its value is the
  4912  ** number of bytes in the parameter.  To be clear: the value is the
  4913  ** number of <u>bytes</u> in the value, not the number of characters.)^
  4914  ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  4915  ** is negative, then the length of the string is
  4916  ** the number of bytes up to the first zero terminator.
  4917  ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  4918  ** the behavior is undefined.
  4919  ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  4920  ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
  4921  ** that parameter must be the byte offset
  4922  ** where the NUL terminator would occur assuming the string were NUL
  4923  ** terminated.  If any NUL characters occur at byte offsets less than 
  4924  ** the value of the fourth parameter then the resulting string value will
  4925  ** contain embedded NULs.  The result of expressions involving strings
  4926  ** with embedded NULs is undefined.
  4927  **
  4928  ** ^The fifth argument to the BLOB and string binding interfaces
  4929  ** is a destructor used to dispose of the BLOB or
  4930  ** string after SQLite has finished with it.  ^The destructor is called
  4931  ** to dispose of the BLOB or string even if the call to bind API fails.
  4932  ** ^If the fifth argument is
  4933  ** the special value [SQLITE_STATIC], then SQLite assumes that the
  4934  ** information is in static, unmanaged space and does not need to be freed.
  4935  ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  4936  ** SQLite makes its own private copy of the data immediately, before
  4937  ** the sqlite3_bind_*() routine returns.
  4938  **
  4939  ** ^The sixth argument to sqlite3_bind_text64() must be one of
  4940  ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
  4941  ** to specify the encoding of the text in the third parameter.  If
  4942  ** the sixth argument to sqlite3_bind_text64() is not one of the
  4943  ** allowed values shown above, or if the text encoding is different
  4944  ** from the encoding specified by the sixth parameter, then the behavior
  4945  ** is undefined.
  4946  **
  4947  ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  4948  ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
  4949  ** (just an integer to hold its size) while it is being processed.
  4950  ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  4951  ** content is later written using
  4952  ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  4953  ** ^A negative value for the zeroblob results in a zero-length BLOB.
  4954  **
  4955  ** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in
  4956  ** [prepared statement] S to have an SQL value of NULL, but to also be
  4957  ** associated with the pointer P of type T.  ^D is either a NULL pointer or
  4958  ** a pointer to a destructor function for P. ^SQLite will invoke the
  4959  ** destructor D with a single argument of P when it is finished using
  4960  ** P.  The T parameter should be a static string, preferably a string
  4961  ** literal. The sqlite3_bind_pointer() routine is part of the
  4962  ** [pointer passing interface] added for SQLite 3.20.0.
  4963  **
  4964  ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  4965  ** for the [prepared statement] or with a prepared statement for which
  4966  ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  4967  ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
  4968  ** routine is passed a [prepared statement] that has been finalized, the
  4969  ** result is undefined and probably harmful.
  4970  **
  4971  ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  4972  ** ^Unbound parameters are interpreted as NULL.
  4973  **
  4974  ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  4975  ** [error code] if anything goes wrong.
  4976  ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
  4977  ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
  4978  ** [SQLITE_MAX_LENGTH].
  4979  ** ^[SQLITE_RANGE] is returned if the parameter
  4980  ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
  4981  **
  4982  ** See also: [sqlite3_bind_parameter_count()],
  4983  ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  4984  */
  4985  SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  4986  SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
  4987                          void(*)(void*));
  4988  SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  4989  SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  4990  SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  4991  SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  4992  SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
  4993  SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  4994  SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
  4995                           void(*)(void*), unsigned char encoding);
  4996  SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  4997  SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));
  4998  SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  4999  SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
  5000  
  5001  /*
  5002  ** CAPI3REF: Number Of SQL Parameters
  5003  ** METHOD: sqlite3_stmt
  5004  **
  5005  ** ^This routine can be used to find the number of [SQL parameters]
  5006  ** in a [prepared statement].  SQL parameters are tokens of the
  5007  ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  5008  ** placeholders for values that are [sqlite3_bind_blob | bound]
  5009  ** to the parameters at a later time.
  5010  **
  5011  ** ^(This routine actually returns the index of the largest (rightmost)
  5012  ** parameter. For all forms except ?NNN, this will correspond to the
  5013  ** number of unique parameters.  If parameters of the ?NNN form are used,
  5014  ** there may be gaps in the list.)^
  5015  **
  5016  ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  5017  ** [sqlite3_bind_parameter_name()], and
  5018  ** [sqlite3_bind_parameter_index()].
  5019  */
  5020  SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  5021  
  5022  /*
  5023  ** CAPI3REF: Name Of A Host Parameter
  5024  ** METHOD: sqlite3_stmt
  5025  **
  5026  ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  5027  ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  5028  ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  5029  ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  5030  ** respectively.
  5031  ** In other words, the initial ":" or "$" or "@" or "?"
  5032  ** is included as part of the name.)^
  5033  ** ^Parameters of the form "?" without a following integer have no name
  5034  ** and are referred to as "nameless" or "anonymous parameters".
  5035  **
  5036  ** ^The first host parameter has an index of 1, not 0.
  5037  **
  5038  ** ^If the value N is out of range or if the N-th parameter is
  5039  ** nameless, then NULL is returned.  ^The returned string is
  5040  ** always in UTF-8 encoding even if the named parameter was
  5041  ** originally specified as UTF-16 in [sqlite3_prepare16()],
  5042  ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
  5043  **
  5044  ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  5045  ** [sqlite3_bind_parameter_count()], and
  5046  ** [sqlite3_bind_parameter_index()].
  5047  */
  5048  SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  5049  
  5050  /*
  5051  ** CAPI3REF: Index Of A Parameter With A Given Name
  5052  ** METHOD: sqlite3_stmt
  5053  **
  5054  ** ^Return the index of an SQL parameter given its name.  ^The
  5055  ** index value returned is suitable for use as the second
  5056  ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
  5057  ** is returned if no matching parameter is found.  ^The parameter
  5058  ** name must be given in UTF-8 even if the original statement
  5059  ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or
  5060  ** [sqlite3_prepare16_v3()].
  5061  **
  5062  ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  5063  ** [sqlite3_bind_parameter_count()], and
  5064  ** [sqlite3_bind_parameter_name()].
  5065  */
  5066  SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  5067  
  5068  /*
  5069  ** CAPI3REF: Reset All Bindings On A Prepared Statement
  5070  ** METHOD: sqlite3_stmt
  5071  **
  5072  ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  5073  ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  5074  ** ^Use this routine to reset all host parameters to NULL.
  5075  */
  5076  SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  5077  
  5078  /*
  5079  ** CAPI3REF: Number Of Columns In A Result Set
  5080  ** METHOD: sqlite3_stmt
  5081  **
  5082  ** ^Return the number of columns in the result set returned by the
  5083  ** [prepared statement]. ^If this routine returns 0, that means the 
  5084  ** [prepared statement] returns no data (for example an [UPDATE]).
  5085  ** ^However, just because this routine returns a positive number does not
  5086  ** mean that one or more rows of data will be returned.  ^A SELECT statement
  5087  ** will always have a positive sqlite3_column_count() but depending on the
  5088  ** WHERE clause constraints and the table content, it might return no rows.
  5089  **
  5090  ** See also: [sqlite3_data_count()]
  5091  */
  5092  SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  5093  
  5094  /*
  5095  ** CAPI3REF: Column Names In A Result Set
  5096  ** METHOD: sqlite3_stmt
  5097  **
  5098  ** ^These routines return the name assigned to a particular column
  5099  ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
  5100  ** interface returns a pointer to a zero-terminated UTF-8 string
  5101  ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  5102  ** UTF-16 string.  ^The first parameter is the [prepared statement]
  5103  ** that implements the [SELECT] statement. ^The second parameter is the
  5104  ** column number.  ^The leftmost column is number 0.
  5105  **
  5106  ** ^The returned string pointer is valid until either the [prepared statement]
  5107  ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  5108  ** reprepared by the first call to [sqlite3_step()] for a particular run
  5109  ** or until the next call to
  5110  ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  5111  **
  5112  ** ^If sqlite3_malloc() fails during the processing of either routine
  5113  ** (for example during a conversion from UTF-8 to UTF-16) then a
  5114  ** NULL pointer is returned.
  5115  **
  5116  ** ^The name of a result column is the value of the "AS" clause for
  5117  ** that column, if there is an AS clause.  If there is no AS clause
  5118  ** then the name of the column is unspecified and may change from
  5119  ** one release of SQLite to the next.
  5120  */
  5121  SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  5122  SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  5123  
  5124  /*
  5125  ** CAPI3REF: Source Of Data In A Query Result
  5126  ** METHOD: sqlite3_stmt
  5127  **
  5128  ** ^These routines provide a means to determine the database, table, and
  5129  ** table column that is the origin of a particular result column in
  5130  ** [SELECT] statement.
  5131  ** ^The name of the database or table or column can be returned as
  5132  ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
  5133  ** the database name, the _table_ routines return the table name, and
  5134  ** the origin_ routines return the column name.
  5135  ** ^The returned string is valid until the [prepared statement] is destroyed
  5136  ** using [sqlite3_finalize()] or until the statement is automatically
  5137  ** reprepared by the first call to [sqlite3_step()] for a particular run
  5138  ** or until the same information is requested
  5139  ** again in a different encoding.
  5140  **
  5141  ** ^The names returned are the original un-aliased names of the
  5142  ** database, table, and column.
  5143  **
  5144  ** ^The first argument to these interfaces is a [prepared statement].
  5145  ** ^These functions return information about the Nth result column returned by
  5146  ** the statement, where N is the second function argument.
  5147  ** ^The left-most column is column 0 for these routines.
  5148  **
  5149  ** ^If the Nth column returned by the statement is an expression or
  5150  ** subquery and is not a column value, then all of these functions return
  5151  ** NULL.  ^These routine might also return NULL if a memory allocation error
  5152  ** occurs.  ^Otherwise, they return the name of the attached database, table,
  5153  ** or column that query result column was extracted from.
  5154  **
  5155  ** ^As with all other SQLite APIs, those whose names end with "16" return
  5156  ** UTF-16 encoded strings and the other functions return UTF-8.
  5157  **
  5158  ** ^These APIs are only available if the library was compiled with the
  5159  ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  5160  **
  5161  ** If two or more threads call one or more of these routines against the same
  5162  ** prepared statement and column at the same time then the results are
  5163  ** undefined.
  5164  **
  5165  ** If two or more threads call one or more
  5166  ** [sqlite3_column_database_name | column metadata interfaces]
  5167  ** for the same [prepared statement] and result column
  5168  ** at the same time then the results are undefined.
  5169  */
  5170  SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  5171  SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  5172  SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  5173  SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  5174  SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  5175  SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  5176  
  5177  /*
  5178  ** CAPI3REF: Declared Datatype Of A Query Result
  5179  ** METHOD: sqlite3_stmt
  5180  **
  5181  ** ^(The first parameter is a [prepared statement].
  5182  ** If this statement is a [SELECT] statement and the Nth column of the
  5183  ** returned result set of that [SELECT] is a table column (not an
  5184  ** expression or subquery) then the declared type of the table
  5185  ** column is returned.)^  ^If the Nth column of the result set is an
  5186  ** expression or subquery, then a NULL pointer is returned.
  5187  ** ^The returned string is always UTF-8 encoded.
  5188  **
  5189  ** ^(For example, given the database schema:
  5190  **
  5191  ** CREATE TABLE t1(c1 VARIANT);
  5192  **
  5193  ** and the following statement to be compiled:
  5194  **
  5195  ** SELECT c1 + 1, c1 FROM t1;
  5196  **
  5197  ** this routine would return the string "VARIANT" for the second result
  5198  ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  5199  **
  5200  ** ^SQLite uses dynamic run-time typing.  ^So just because a column
  5201  ** is declared to contain a particular type does not mean that the
  5202  ** data stored in that column is of the declared type.  SQLite is
  5203  ** strongly typed, but the typing is dynamic not static.  ^Type
  5204  ** is associated with individual values, not with the containers
  5205  ** used to hold those values.
  5206  */
  5207  SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  5208  SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  5209  
  5210  /*
  5211  ** CAPI3REF: Evaluate An SQL Statement
  5212  ** METHOD: sqlite3_stmt
  5213  **
  5214  ** After a [prepared statement] has been prepared using any of
  5215  ** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()],
  5216  ** or [sqlite3_prepare16_v3()] or one of the legacy
  5217  ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  5218  ** must be called one or more times to evaluate the statement.
  5219  **
  5220  ** The details of the behavior of the sqlite3_step() interface depend
  5221  ** on whether the statement was prepared using the newer "vX" interfaces
  5222  ** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()],
  5223  ** [sqlite3_prepare16_v2()] or the older legacy
  5224  ** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
  5225  ** new "vX" interface is recommended for new applications but the legacy
  5226  ** interface will continue to be supported.
  5227  **
  5228  ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  5229  ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  5230  ** ^With the "v2" interface, any of the other [result codes] or
  5231  ** [extended result codes] might be returned as well.
  5232  **
  5233  ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  5234  ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
  5235  ** or occurs outside of an explicit transaction, then you can retry the
  5236  ** statement.  If the statement is not a [COMMIT] and occurs within an
  5237  ** explicit transaction then you should rollback the transaction before
  5238  ** continuing.
  5239  **
  5240  ** ^[SQLITE_DONE] means that the statement has finished executing
  5241  ** successfully.  sqlite3_step() should not be called again on this virtual
  5242  ** machine without first calling [sqlite3_reset()] to reset the virtual
  5243  ** machine back to its initial state.
  5244  **
  5245  ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  5246  ** is returned each time a new row of data is ready for processing by the
  5247  ** caller. The values may be accessed using the [column access functions].
  5248  ** sqlite3_step() is called again to retrieve the next row of data.
  5249  **
  5250  ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  5251  ** violation) has occurred.  sqlite3_step() should not be called again on
  5252  ** the VM. More information may be found by calling [sqlite3_errmsg()].
  5253  ** ^With the legacy interface, a more specific error code (for example,
  5254  ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  5255  ** can be obtained by calling [sqlite3_reset()] on the
  5256  ** [prepared statement].  ^In the "v2" interface,
  5257  ** the more specific error code is returned directly by sqlite3_step().
  5258  **
  5259  ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  5260  ** Perhaps it was called on a [prepared statement] that has
  5261  ** already been [sqlite3_finalize | finalized] or on one that had
  5262  ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
  5263  ** be the case that the same database connection is being used by two or
  5264  ** more threads at the same moment in time.
  5265  **
  5266  ** For all versions of SQLite up to and including 3.6.23.1, a call to
  5267  ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  5268  ** other than [SQLITE_ROW] before any subsequent invocation of
  5269  ** sqlite3_step().  Failure to reset the prepared statement using 
  5270  ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  5271  ** sqlite3_step().  But after [version 3.6.23.1] ([dateof:3.6.23.1],
  5272  ** sqlite3_step() began
  5273  ** calling [sqlite3_reset()] automatically in this circumstance rather
  5274  ** than returning [SQLITE_MISUSE].  This is not considered a compatibility
  5275  ** break because any application that ever receives an SQLITE_MISUSE error
  5276  ** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
  5277  ** can be used to restore the legacy behavior.
  5278  **
  5279  ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  5280  ** API always returns a generic error code, [SQLITE_ERROR], following any
  5281  ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
  5282  ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  5283  ** specific [error codes] that better describes the error.
  5284  ** We admit that this is a goofy design.  The problem has been fixed
  5285  ** with the "v2" interface.  If you prepare all of your SQL statements
  5286  ** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()]
  5287  ** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead
  5288  ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  5289  ** then the more specific [error codes] are returned directly
  5290  ** by sqlite3_step().  The use of the "vX" interfaces is recommended.
  5291  */
  5292  SQLITE_API int sqlite3_step(sqlite3_stmt*);
  5293  
  5294  /*
  5295  ** CAPI3REF: Number of columns in a result set
  5296  ** METHOD: sqlite3_stmt
  5297  **
  5298  ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  5299  ** current row of the result set of [prepared statement] P.
  5300  ** ^If prepared statement P does not have results ready to return
  5301  ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  5302  ** interfaces) then sqlite3_data_count(P) returns 0.
  5303  ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  5304  ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  5305  ** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
  5306  ** will return non-zero if previous call to [sqlite3_step](P) returned
  5307  ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  5308  ** where it always returns zero since each step of that multi-step
  5309  ** pragma returns 0 columns of data.
  5310  **
  5311  ** See also: [sqlite3_column_count()]
  5312  */
  5313  SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  5314  
  5315  /*
  5316  ** CAPI3REF: Fundamental Datatypes
  5317  ** KEYWORDS: SQLITE_TEXT
  5318  **
  5319  ** ^(Every value in SQLite has one of five fundamental datatypes:
  5320  **
  5321  ** <ul>
  5322  ** <li> 64-bit signed integer
  5323  ** <li> 64-bit IEEE floating point number
  5324  ** <li> string
  5325  ** <li> BLOB
  5326  ** <li> NULL
  5327  ** </ul>)^
  5328  **
  5329  ** These constants are codes for each of those types.
  5330  **
  5331  ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  5332  ** for a completely different meaning.  Software that links against both
  5333  ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  5334  ** SQLITE_TEXT.
  5335  */
  5336  #define SQLITE_INTEGER  1
  5337  #define SQLITE_FLOAT    2
  5338  #define SQLITE_BLOB     4
  5339  #define SQLITE_NULL     5
  5340  #ifdef SQLITE_TEXT
  5341  # undef SQLITE_TEXT
  5342  #else
  5343  # define SQLITE_TEXT     3
  5344  #endif
  5345  #define SQLITE3_TEXT     3
  5346  
  5347  /*
  5348  ** CAPI3REF: Result Values From A Query
  5349  ** KEYWORDS: {column access functions}
  5350  ** METHOD: sqlite3_stmt
  5351  **
  5352  ** <b>Summary:</b>
  5353  ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
  5354  ** <tr><td><b>sqlite3_column_blob</b><td>&rarr;<td>BLOB result
  5355  ** <tr><td><b>sqlite3_column_double</b><td>&rarr;<td>REAL result
  5356  ** <tr><td><b>sqlite3_column_int</b><td>&rarr;<td>32-bit INTEGER result
  5357  ** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result
  5358  ** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result
  5359  ** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result
  5360  ** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an 
  5361  ** [sqlite3_value|unprotected sqlite3_value] object.
  5362  ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
  5363  ** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB
  5364  ** or a UTF-8 TEXT result in bytes
  5365  ** <tr><td><b>sqlite3_column_bytes16&nbsp;&nbsp;</b>
  5366  ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
  5367  ** TEXT in bytes
  5368  ** <tr><td><b>sqlite3_column_type</b><td>&rarr;<td>Default
  5369  ** datatype of the result
  5370  ** </table></blockquote>
  5371  **
  5372  ** <b>Details:</b>
  5373  **
  5374  ** ^These routines return information about a single column of the current
  5375  ** result row of a query.  ^In every case the first argument is a pointer
  5376  ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  5377  ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  5378  ** and the second argument is the index of the column for which information
  5379  ** should be returned. ^The leftmost column of the result set has the index 0.
  5380  ** ^The number of columns in the result can be determined using
  5381  ** [sqlite3_column_count()].
  5382  **
  5383  ** If the SQL statement does not currently point to a valid row, or if the
  5384  ** column index is out of range, the result is undefined.
  5385  ** These routines may only be called when the most recent call to
  5386  ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  5387  ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  5388  ** If any of these routines are called after [sqlite3_reset()] or
  5389  ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  5390  ** something other than [SQLITE_ROW], the results are undefined.
  5391  ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  5392  ** are called from a different thread while any of these routines
  5393  ** are pending, then the results are undefined.
  5394  **
  5395  ** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16)
  5396  ** each return the value of a result column in a specific data format.  If
  5397  ** the result column is not initially in the requested format (for example,
  5398  ** if the query returns an integer but the sqlite3_column_text() interface
  5399  ** is used to extract the value) then an automatic type conversion is performed.
  5400  **
  5401  ** ^The sqlite3_column_type() routine returns the
  5402  ** [SQLITE_INTEGER | datatype code] for the initial data type
  5403  ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
  5404  ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].
  5405  ** The return value of sqlite3_column_type() can be used to decide which
  5406  ** of the first six interface should be used to extract the column value.
  5407  ** The value returned by sqlite3_column_type() is only meaningful if no
  5408  ** automatic type conversions have occurred for the value in question.  
  5409  ** After a type conversion, the result of calling sqlite3_column_type()
  5410  ** is undefined, though harmless.  Future
  5411  ** versions of SQLite may change the behavior of sqlite3_column_type()
  5412  ** following a type conversion.
  5413  **
  5414  ** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()
  5415  ** or sqlite3_column_bytes16() interfaces can be used to determine the size
  5416  ** of that BLOB or string.
  5417  **
  5418  ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  5419  ** routine returns the number of bytes in that BLOB or string.
  5420  ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  5421  ** the string to UTF-8 and then returns the number of bytes.
  5422  ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  5423  ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  5424  ** the number of bytes in that string.
  5425  ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  5426  **
  5427  ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  5428  ** routine returns the number of bytes in that BLOB or string.
  5429  ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  5430  ** the string to UTF-16 and then returns the number of bytes.
  5431  ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  5432  ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  5433  ** the number of bytes in that string.
  5434  ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  5435  **
  5436  ** ^The values returned by [sqlite3_column_bytes()] and 
  5437  ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  5438  ** of the string.  ^For clarity: the values returned by
  5439  ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  5440  ** bytes in the string, not the number of characters.
  5441  **
  5442  ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  5443  ** even empty strings, are always zero-terminated.  ^The return
  5444  ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  5445  **
  5446  ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
  5447  ** [unprotected sqlite3_value] object.  In a multithreaded environment,
  5448  ** an unprotected sqlite3_value object may only be used safely with
  5449  ** [sqlite3_bind_value()] and [sqlite3_result_value()].
  5450  ** If the [unprotected sqlite3_value] object returned by
  5451  ** [sqlite3_column_value()] is used in any other way, including calls
  5452  ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  5453  ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
  5454  ** Hence, the sqlite3_column_value() interface
  5455  ** is normally only useful within the implementation of 
  5456  ** [application-defined SQL functions] or [virtual tables], not within
  5457  ** top-level application code.
  5458  **
  5459  ** The these routines may attempt to convert the datatype of the result.
  5460  ** ^For example, if the internal representation is FLOAT and a text result
  5461  ** is requested, [sqlite3_snprintf()] is used internally to perform the
  5462  ** conversion automatically.  ^(The following table details the conversions
  5463  ** that are applied:
  5464  **
  5465  ** <blockquote>
  5466  ** <table border="1">
  5467  ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
  5468  **
  5469  ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
  5470  ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
  5471  ** <tr><td>  NULL    <td>   TEXT    <td> Result is a NULL pointer
  5472  ** <tr><td>  NULL    <td>   BLOB    <td> Result is a NULL pointer
  5473  ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
  5474  ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
  5475  ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
  5476  ** <tr><td>  FLOAT   <td> INTEGER   <td> [CAST] to INTEGER
  5477  ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
  5478  ** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB
  5479  ** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER
  5480  ** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL
  5481  ** <tr><td>  TEXT    <td>   BLOB    <td> No change
  5482  ** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER
  5483  ** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL
  5484  ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
  5485  ** </table>
  5486  ** </blockquote>)^
  5487  **
  5488  ** Note that when type conversions occur, pointers returned by prior
  5489  ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  5490  ** sqlite3_column_text16() may be invalidated.
  5491  ** Type conversions and pointer invalidations might occur
  5492  ** in the following cases:
  5493  **
  5494  ** <ul>
  5495  ** <li> The initial content is a BLOB and sqlite3_column_text() or
  5496  **      sqlite3_column_text16() is called.  A zero-terminator might
  5497  **      need to be added to the string.</li>
  5498  ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  5499  **      sqlite3_column_text16() is called.  The content must be converted
  5500  **      to UTF-16.</li>
  5501  ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  5502  **      sqlite3_column_text() is called.  The content must be converted
  5503  **      to UTF-8.</li>
  5504  ** </ul>
  5505  **
  5506  ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  5507  ** not invalidate a prior pointer, though of course the content of the buffer
  5508  ** that the prior pointer references will have been modified.  Other kinds
  5509  ** of conversion are done in place when it is possible, but sometimes they
  5510  ** are not possible and in those cases prior pointers are invalidated.
  5511  **
  5512  ** The safest policy is to invoke these routines
  5513  ** in one of the following ways:
  5514  **
  5515  ** <ul>
  5516  **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  5517  **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  5518  **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  5519  ** </ul>
  5520  **
  5521  ** In other words, you should call sqlite3_column_text(),
  5522  ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  5523  ** into the desired format, then invoke sqlite3_column_bytes() or
  5524  ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
  5525  ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  5526  ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  5527  ** with calls to sqlite3_column_bytes().
  5528  **
  5529  ** ^The pointers returned are valid until a type conversion occurs as
  5530  ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  5531  ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
  5532  ** and BLOBs is freed automatically.  Do not pass the pointers returned
  5533  ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  5534  ** [sqlite3_free()].
  5535  **
  5536  ** ^(If a memory allocation error occurs during the evaluation of any
  5537  ** of these routines, a default value is returned.  The default value
  5538  ** is either the integer 0, the floating point number 0.0, or a NULL
  5539  ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
  5540  ** [SQLITE_NOMEM].)^
  5541  */
  5542  SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  5543  SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  5544  SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  5545  SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  5546  SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  5547  SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  5548  SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  5549  SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  5550  SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  5551  SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  5552  
  5553  /*
  5554  ** CAPI3REF: Destroy A Prepared Statement Object
  5555  ** DESTRUCTOR: sqlite3_stmt
  5556  **
  5557  ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  5558  ** ^If the most recent evaluation of the statement encountered no errors
  5559  ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  5560  ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
  5561  ** sqlite3_finalize(S) returns the appropriate [error code] or
  5562  ** [extended error code].
  5563  **
  5564  ** ^The sqlite3_finalize(S) routine can be called at any point during
  5565  ** the life cycle of [prepared statement] S:
  5566  ** before statement S is ever evaluated, after
  5567  ** one or more calls to [sqlite3_reset()], or after any call
  5568  ** to [sqlite3_step()] regardless of whether or not the statement has
  5569  ** completed execution.
  5570  **
  5571  ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  5572  **
  5573  ** The application must finalize every [prepared statement] in order to avoid
  5574  ** resource leaks.  It is a grievous error for the application to try to use
  5575  ** a prepared statement after it has been finalized.  Any use of a prepared
  5576  ** statement after it has been finalized can result in undefined and
  5577  ** undesirable behavior such as segfaults and heap corruption.
  5578  */
  5579  SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  5580  
  5581  /*
  5582  ** CAPI3REF: Reset A Prepared Statement Object
  5583  ** METHOD: sqlite3_stmt
  5584  **
  5585  ** The sqlite3_reset() function is called to reset a [prepared statement]
  5586  ** object back to its initial state, ready to be re-executed.
  5587  ** ^Any SQL statement variables that had values bound to them using
  5588  ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  5589  ** Use [sqlite3_clear_bindings()] to reset the bindings.
  5590  **
  5591  ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  5592  ** back to the beginning of its program.
  5593  **
  5594  ** ^If the most recent call to [sqlite3_step(S)] for the
  5595  ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  5596  ** or if [sqlite3_step(S)] has never before been called on S,
  5597  ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  5598  **
  5599  ** ^If the most recent call to [sqlite3_step(S)] for the
  5600  ** [prepared statement] S indicated an error, then
  5601  ** [sqlite3_reset(S)] returns an appropriate [error code].
  5602  **
  5603  ** ^The [sqlite3_reset(S)] interface does not change the values
  5604  ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  5605  */
  5606  SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  5607  
  5608  /*
  5609  ** CAPI3REF: Create Or Redefine SQL Functions
  5610  ** KEYWORDS: {function creation routines}
  5611  ** KEYWORDS: {application-defined SQL function}
  5612  ** KEYWORDS: {application-defined SQL functions}
  5613  ** METHOD: sqlite3
  5614  **
  5615  ** ^These functions (collectively known as "function creation routines")
  5616  ** are used to add SQL functions or aggregates or to redefine the behavior
  5617  ** of existing SQL functions or aggregates.  The only differences between
  5618  ** these routines are the text encoding expected for
  5619  ** the second parameter (the name of the function being created)
  5620  ** and the presence or absence of a destructor callback for
  5621  ** the application data pointer.
  5622  **
  5623  ** ^The first parameter is the [database connection] to which the SQL
  5624  ** function is to be added.  ^If an application uses more than one database
  5625  ** connection then application-defined SQL functions must be added
  5626  ** to each database connection separately.
  5627  **
  5628  ** ^The second parameter is the name of the SQL function to be created or
  5629  ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
  5630  ** representation, exclusive of the zero-terminator.  ^Note that the name
  5631  ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  
  5632  ** ^Any attempt to create a function with a longer name
  5633  ** will result in [SQLITE_MISUSE] being returned.
  5634  **
  5635  ** ^The third parameter (nArg)
  5636  ** is the number of arguments that the SQL function or
  5637  ** aggregate takes. ^If this parameter is -1, then the SQL function or
  5638  ** aggregate may take any number of arguments between 0 and the limit
  5639  ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
  5640  ** parameter is less than -1 or greater than 127 then the behavior is
  5641  ** undefined.
  5642  **
  5643  ** ^The fourth parameter, eTextRep, specifies what
  5644  ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  5645  ** its parameters.  The application should set this parameter to
  5646  ** [SQLITE_UTF16LE] if the function implementation invokes 
  5647  ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
  5648  ** implementation invokes [sqlite3_value_text16be()] on an input, or
  5649  ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
  5650  ** otherwise.  ^The same SQL function may be registered multiple times using
  5651  ** different preferred text encodings, with different implementations for
  5652  ** each encoding.
  5653  ** ^When multiple implementations of the same function are available, SQLite
  5654  ** will pick the one that involves the least amount of data conversion.
  5655  **
  5656  ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
  5657  ** to signal that the function will always return the same result given
  5658  ** the same inputs within a single SQL statement.  Most SQL functions are
  5659  ** deterministic.  The built-in [random()] SQL function is an example of a
  5660  ** function that is not deterministic.  The SQLite query planner is able to
  5661  ** perform additional optimizations on deterministic functions, so use
  5662  ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
  5663  **
  5664  ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
  5665  ** function can gain access to this pointer using [sqlite3_user_data()].)^
  5666  **
  5667  ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  5668  ** pointers to C-language functions that implement the SQL function or
  5669  ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  5670  ** callback only; NULL pointers must be passed as the xStep and xFinal
  5671  ** parameters. ^An aggregate SQL function requires an implementation of xStep
  5672  ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  5673  ** SQL function or aggregate, pass NULL pointers for all three function
  5674  ** callbacks.
  5675  **
  5676  ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  5677  ** then it is destructor for the application data pointer. 
  5678  ** The destructor is invoked when the function is deleted, either by being
  5679  ** overloaded or when the database connection closes.)^
  5680  ** ^The destructor is also invoked if the call to
  5681  ** sqlite3_create_function_v2() fails.
  5682  ** ^When the destructor callback of the tenth parameter is invoked, it
  5683  ** is passed a single argument which is a copy of the application data 
  5684  ** pointer which was the fifth parameter to sqlite3_create_function_v2().
  5685  **
  5686  ** ^It is permitted to register multiple implementations of the same
  5687  ** functions with the same name but with either differing numbers of
  5688  ** arguments or differing preferred text encodings.  ^SQLite will use
  5689  ** the implementation that most closely matches the way in which the
  5690  ** SQL function is used.  ^A function implementation with a non-negative
  5691  ** nArg parameter is a better match than a function implementation with
  5692  ** a negative nArg.  ^A function where the preferred text encoding
  5693  ** matches the database encoding is a better
  5694  ** match than a function where the encoding is different.  
  5695  ** ^A function where the encoding difference is between UTF16le and UTF16be
  5696  ** is a closer match than a function where the encoding difference is
  5697  ** between UTF8 and UTF16.
  5698  **
  5699  ** ^Built-in functions may be overloaded by new application-defined functions.
  5700  **
  5701  ** ^An application-defined function is permitted to call other
  5702  ** SQLite interfaces.  However, such calls must not
  5703  ** close the database connection nor finalize or reset the prepared
  5704  ** statement in which the function is running.
  5705  */
  5706  SQLITE_API int sqlite3_create_function(
  5707    sqlite3 *db,
  5708    const char *zFunctionName,
  5709    int nArg,
  5710    int eTextRep,
  5711    void *pApp,
  5712    void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5713    void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5714    void (*xFinal)(sqlite3_context*)
  5715  );
  5716  SQLITE_API int sqlite3_create_function16(
  5717    sqlite3 *db,
  5718    const void *zFunctionName,
  5719    int nArg,
  5720    int eTextRep,
  5721    void *pApp,
  5722    void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5723    void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5724    void (*xFinal)(sqlite3_context*)
  5725  );
  5726  SQLITE_API int sqlite3_create_function_v2(
  5727    sqlite3 *db,
  5728    const char *zFunctionName,
  5729    int nArg,
  5730    int eTextRep,
  5731    void *pApp,
  5732    void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5733    void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5734    void (*xFinal)(sqlite3_context*),
  5735    void(*xDestroy)(void*)
  5736  );
  5737  
  5738  /*
  5739  ** CAPI3REF: Text Encodings
  5740  **
  5741  ** These constant define integer codes that represent the various
  5742  ** text encodings supported by SQLite.
  5743  */
  5744  #define SQLITE_UTF8           1    /* IMP: R-37514-35566 */
  5745  #define SQLITE_UTF16LE        2    /* IMP: R-03371-37637 */
  5746  #define SQLITE_UTF16BE        3    /* IMP: R-51971-34154 */
  5747  #define SQLITE_UTF16          4    /* Use native byte order */
  5748  #define SQLITE_ANY            5    /* Deprecated */
  5749  #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
  5750  
  5751  /*
  5752  ** CAPI3REF: Function Flags
  5753  **
  5754  ** These constants may be ORed together with the 
  5755  ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
  5756  ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
  5757  ** [sqlite3_create_function_v2()].
  5758  */
  5759  #define SQLITE_DETERMINISTIC    0x800
  5760  
  5761  /*
  5762  ** CAPI3REF: Deprecated Functions
  5763  ** DEPRECATED
  5764  **
  5765  ** These functions are [deprecated].  In order to maintain
  5766  ** backwards compatibility with older code, these functions continue 
  5767  ** to be supported.  However, new applications should avoid
  5768  ** the use of these functions.  To encourage programmers to avoid
  5769  ** these functions, we will not explain what they do.
  5770  */
  5771  #ifndef SQLITE_OMIT_DEPRECATED
  5772  SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  5773  SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  5774  SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  5775  SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  5776  SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  5777  SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  5778                        void*,sqlite3_int64);
  5779  #endif
  5780  
  5781  /*
  5782  ** CAPI3REF: Obtaining SQL Values
  5783  ** METHOD: sqlite3_value
  5784  **
  5785  ** <b>Summary:</b>
  5786  ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
  5787  ** <tr><td><b>sqlite3_value_blob</b><td>&rarr;<td>BLOB value
  5788  ** <tr><td><b>sqlite3_value_double</b><td>&rarr;<td>REAL value
  5789  ** <tr><td><b>sqlite3_value_int</b><td>&rarr;<td>32-bit INTEGER value
  5790  ** <tr><td><b>sqlite3_value_int64</b><td>&rarr;<td>64-bit INTEGER value
  5791  ** <tr><td><b>sqlite3_value_pointer</b><td>&rarr;<td>Pointer value
  5792  ** <tr><td><b>sqlite3_value_text</b><td>&rarr;<td>UTF-8 TEXT value
  5793  ** <tr><td><b>sqlite3_value_text16</b><td>&rarr;<td>UTF-16 TEXT value in
  5794  ** the native byteorder
  5795  ** <tr><td><b>sqlite3_value_text16be</b><td>&rarr;<td>UTF-16be TEXT value
  5796  ** <tr><td><b>sqlite3_value_text16le</b><td>&rarr;<td>UTF-16le TEXT value
  5797  ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
  5798  ** <tr><td><b>sqlite3_value_bytes</b><td>&rarr;<td>Size of a BLOB
  5799  ** or a UTF-8 TEXT in bytes
  5800  ** <tr><td><b>sqlite3_value_bytes16&nbsp;&nbsp;</b>
  5801  ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
  5802  ** TEXT in bytes
  5803  ** <tr><td><b>sqlite3_value_type</b><td>&rarr;<td>Default
  5804  ** datatype of the value
  5805  ** <tr><td><b>sqlite3_value_numeric_type&nbsp;&nbsp;</b>
  5806  ** <td>&rarr;&nbsp;&nbsp;<td>Best numeric datatype of the value
  5807  ** </table></blockquote>
  5808  **
  5809  ** <b>Details:</b>
  5810  **
  5811  ** These routines extract type, size, and content information from
  5812  ** [protected sqlite3_value] objects.  Protected sqlite3_value objects
  5813  ** are used to pass parameter information into implementation of
  5814  ** [application-defined SQL functions] and [virtual tables].
  5815  **
  5816  ** These routines work only with [protected sqlite3_value] objects.
  5817  ** Any attempt to use these routines on an [unprotected sqlite3_value]
  5818  ** is not threadsafe.
  5819  **
  5820  ** ^These routines work just like the corresponding [column access functions]
  5821  ** except that these routines take a single [protected sqlite3_value] object
  5822  ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  5823  **
  5824  ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  5825  ** in the native byte-order of the host machine.  ^The
  5826  ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  5827  ** extract UTF-16 strings as big-endian and little-endian respectively.
  5828  **
  5829  ** ^If [sqlite3_value] object V was initialized 
  5830  ** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]
  5831  ** and if X and Y are strings that compare equal according to strcmp(X,Y),
  5832  ** then sqlite3_value_pointer(V,Y) will return the pointer P.  ^Otherwise,
  5833  ** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer() 
  5834  ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
  5835  **
  5836  ** ^(The sqlite3_value_type(V) interface returns the
  5837  ** [SQLITE_INTEGER | datatype code] for the initial datatype of the
  5838  ** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER],
  5839  ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^
  5840  ** Other interfaces might change the datatype for an sqlite3_value object.
  5841  ** For example, if the datatype is initially SQLITE_INTEGER and
  5842  ** sqlite3_value_text(V) is called to extract a text value for that
  5843  ** integer, then subsequent calls to sqlite3_value_type(V) might return
  5844  ** SQLITE_TEXT.  Whether or not a persistent internal datatype conversion
  5845  ** occurs is undefined and may change from one release of SQLite to the next.
  5846  **
  5847  ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  5848  ** numeric affinity to the value.  This means that an attempt is
  5849  ** made to convert the value to an integer or floating point.  If
  5850  ** such a conversion is possible without loss of information (in other
  5851  ** words, if the value is a string that looks like a number)
  5852  ** then the conversion is performed.  Otherwise no conversion occurs.
  5853  ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  5854  **
  5855  ** Please pay particular attention to the fact that the pointer returned
  5856  ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  5857  ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  5858  ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  5859  ** or [sqlite3_value_text16()].
  5860  **
  5861  ** These routines must be called from the same thread as
  5862  ** the SQL function that supplied the [sqlite3_value*] parameters.
  5863  */
  5864  SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  5865  SQLITE_API double sqlite3_value_double(sqlite3_value*);
  5866  SQLITE_API int sqlite3_value_int(sqlite3_value*);
  5867  SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  5868  SQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*);
  5869  SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  5870  SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  5871  SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  5872  SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  5873  SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  5874  SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  5875  SQLITE_API int sqlite3_value_type(sqlite3_value*);
  5876  SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  5877  
  5878  /*
  5879  ** CAPI3REF: Finding The Subtype Of SQL Values
  5880  ** METHOD: sqlite3_value
  5881  **
  5882  ** The sqlite3_value_subtype(V) function returns the subtype for
  5883  ** an [application-defined SQL function] argument V.  The subtype
  5884  ** information can be used to pass a limited amount of context from
  5885  ** one SQL function to another.  Use the [sqlite3_result_subtype()]
  5886  ** routine to set the subtype for the return value of an SQL function.
  5887  */
  5888  SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
  5889  
  5890  /*
  5891  ** CAPI3REF: Copy And Free SQL Values
  5892  ** METHOD: sqlite3_value
  5893  **
  5894  ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
  5895  ** object D and returns a pointer to that copy.  ^The [sqlite3_value] returned
  5896  ** is a [protected sqlite3_value] object even if the input is not.
  5897  ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
  5898  ** memory allocation fails.
  5899  **
  5900  ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
  5901  ** previously obtained from [sqlite3_value_dup()].  ^If V is a NULL pointer
  5902  ** then sqlite3_value_free(V) is a harmless no-op.
  5903  */
  5904  SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
  5905  SQLITE_API void sqlite3_value_free(sqlite3_value*);
  5906  
  5907  /*
  5908  ** CAPI3REF: Obtain Aggregate Function Context
  5909  ** METHOD: sqlite3_context
  5910  **
  5911  ** Implementations of aggregate SQL functions use this
  5912  ** routine to allocate memory for storing their state.
  5913  **
  5914  ** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
  5915  ** for a particular aggregate function, SQLite
  5916  ** allocates N of memory, zeroes out that memory, and returns a pointer
  5917  ** to the new memory. ^On second and subsequent calls to
  5918  ** sqlite3_aggregate_context() for the same aggregate function instance,
  5919  ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
  5920  ** called once for each invocation of the xStep callback and then one
  5921  ** last time when the xFinal callback is invoked.  ^(When no rows match
  5922  ** an aggregate query, the xStep() callback of the aggregate function
  5923  ** implementation is never called and xFinal() is called exactly once.
  5924  ** In those cases, sqlite3_aggregate_context() might be called for the
  5925  ** first time from within xFinal().)^
  5926  **
  5927  ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer 
  5928  ** when first called if N is less than or equal to zero or if a memory
  5929  ** allocate error occurs.
  5930  **
  5931  ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  5932  ** determined by the N parameter on first successful call.  Changing the
  5933  ** value of N in subsequent call to sqlite3_aggregate_context() within
  5934  ** the same aggregate function instance will not resize the memory
  5935  ** allocation.)^  Within the xFinal callback, it is customary to set
  5936  ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no 
  5937  ** pointless memory allocations occur.
  5938  **
  5939  ** ^SQLite automatically frees the memory allocated by 
  5940  ** sqlite3_aggregate_context() when the aggregate query concludes.
  5941  **
  5942  ** The first parameter must be a copy of the
  5943  ** [sqlite3_context | SQL function context] that is the first parameter
  5944  ** to the xStep or xFinal callback routine that implements the aggregate
  5945  ** function.
  5946  **
  5947  ** This routine must be called from the same thread in which
  5948  ** the aggregate SQL function is running.
  5949  */
  5950  SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  5951  
  5952  /*
  5953  ** CAPI3REF: User Data For Functions
  5954  ** METHOD: sqlite3_context
  5955  **
  5956  ** ^The sqlite3_user_data() interface returns a copy of
  5957  ** the pointer that was the pUserData parameter (the 5th parameter)
  5958  ** of the [sqlite3_create_function()]
  5959  ** and [sqlite3_create_function16()] routines that originally
  5960  ** registered the application defined function.
  5961  **
  5962  ** This routine must be called from the same thread in which
  5963  ** the application-defined function is running.
  5964  */
  5965  SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  5966  
  5967  /*
  5968  ** CAPI3REF: Database Connection For Functions
  5969  ** METHOD: sqlite3_context
  5970  **
  5971  ** ^The sqlite3_context_db_handle() interface returns a copy of
  5972  ** the pointer to the [database connection] (the 1st parameter)
  5973  ** of the [sqlite3_create_function()]
  5974  ** and [sqlite3_create_function16()] routines that originally
  5975  ** registered the application defined function.
  5976  */
  5977  SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  5978  
  5979  /*
  5980  ** CAPI3REF: Function Auxiliary Data
  5981  ** METHOD: sqlite3_context
  5982  **
  5983  ** These functions may be used by (non-aggregate) SQL functions to
  5984  ** associate metadata with argument values. If the same value is passed to
  5985  ** multiple invocations of the same SQL function during query execution, under
  5986  ** some circumstances the associated metadata may be preserved.  An example
  5987  ** of where this might be useful is in a regular-expression matching
  5988  ** function. The compiled version of the regular expression can be stored as
  5989  ** metadata associated with the pattern string.  
  5990  ** Then as long as the pattern string remains the same,
  5991  ** the compiled regular expression can be reused on multiple
  5992  ** invocations of the same function.
  5993  **
  5994  ** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata
  5995  ** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
  5996  ** value to the application-defined function.  ^N is zero for the left-most
  5997  ** function argument.  ^If there is no metadata
  5998  ** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
  5999  ** returns a NULL pointer.
  6000  **
  6001  ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  6002  ** argument of the application-defined function.  ^Subsequent
  6003  ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  6004  ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  6005  ** NULL if the metadata has been discarded.
  6006  ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  6007  ** SQLite will invoke the destructor function X with parameter P exactly
  6008  ** once, when the metadata is discarded.
  6009  ** SQLite is free to discard the metadata at any time, including: <ul>
  6010  ** <li> ^(when the corresponding function parameter changes)^, or
  6011  ** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  6012  **      SQL statement)^, or
  6013  ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
  6014  **       parameter)^, or
  6015  ** <li> ^(during the original sqlite3_set_auxdata() call when a memory 
  6016  **      allocation error occurs.)^ </ul>
  6017  **
  6018  ** Note the last bullet in particular.  The destructor X in 
  6019  ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  6020  ** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()
  6021  ** should be called near the end of the function implementation and the
  6022  ** function implementation should not make any use of P after
  6023  ** sqlite3_set_auxdata() has been called.
  6024  **
  6025  ** ^(In practice, metadata is preserved between function calls for
  6026  ** function parameters that are compile-time constants, including literal
  6027  ** values and [parameters] and expressions composed from the same.)^
  6028  **
  6029  ** The value of the N parameter to these interfaces should be non-negative.
  6030  ** Future enhancements may make use of negative N values to define new
  6031  ** kinds of function caching behavior.
  6032  **
  6033  ** These routines must be called from the same thread in which
  6034  ** the SQL function is running.
  6035  */
  6036  SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  6037  SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  6038  
  6039  
  6040  /*
  6041  ** CAPI3REF: Constants Defining Special Destructor Behavior
  6042  **
  6043  ** These are special values for the destructor that is passed in as the
  6044  ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
  6045  ** argument is SQLITE_STATIC, it means that the content pointer is constant
  6046  ** and will never change.  It does not need to be destroyed.  ^The
  6047  ** SQLITE_TRANSIENT value means that the content will likely change in
  6048  ** the near future and that SQLite should make its own private copy of
  6049  ** the content before returning.
  6050  **
  6051  ** The typedef is necessary to work around problems in certain
  6052  ** C++ compilers.
  6053  */
  6054  typedef void (*sqlite3_destructor_type)(void*);
  6055  #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
  6056  #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
  6057  
  6058  /*
  6059  ** CAPI3REF: Setting The Result Of An SQL Function
  6060  ** METHOD: sqlite3_context
  6061  **
  6062  ** These routines are used by the xFunc or xFinal callbacks that
  6063  ** implement SQL functions and aggregates.  See
  6064  ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  6065  ** for additional information.
  6066  **
  6067  ** These functions work very much like the [parameter binding] family of
  6068  ** functions used to bind values to host parameters in prepared statements.
  6069  ** Refer to the [SQL parameter] documentation for additional information.
  6070  **
  6071  ** ^The sqlite3_result_blob() interface sets the result from
  6072  ** an application-defined function to be the BLOB whose content is pointed
  6073  ** to by the second parameter and which is N bytes long where N is the
  6074  ** third parameter.
  6075  **
  6076  ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
  6077  ** interfaces set the result of the application-defined function to be
  6078  ** a BLOB containing all zero bytes and N bytes in size.
  6079  **
  6080  ** ^The sqlite3_result_double() interface sets the result from
  6081  ** an application-defined function to be a floating point value specified
  6082  ** by its 2nd argument.
  6083  **
  6084  ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  6085  ** cause the implemented SQL function to throw an exception.
  6086  ** ^SQLite uses the string pointed to by the
  6087  ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  6088  ** as the text of an error message.  ^SQLite interprets the error
  6089  ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  6090  ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  6091  ** byte order.  ^If the third parameter to sqlite3_result_error()
  6092  ** or sqlite3_result_error16() is negative then SQLite takes as the error
  6093  ** message all text up through the first zero character.
  6094  ** ^If the third parameter to sqlite3_result_error() or
  6095  ** sqlite3_result_error16() is non-negative then SQLite takes that many
  6096  ** bytes (not characters) from the 2nd parameter as the error message.
  6097  ** ^The sqlite3_result_error() and sqlite3_result_error16()
  6098  ** routines make a private copy of the error message text before
  6099  ** they return.  Hence, the calling function can deallocate or
  6100  ** modify the text after they return without harm.
  6101  ** ^The sqlite3_result_error_code() function changes the error code
  6102  ** returned by SQLite as a result of an error in a function.  ^By default,
  6103  ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
  6104  ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  6105  **
  6106  ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  6107  ** error indicating that a string or BLOB is too long to represent.
  6108  **
  6109  ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  6110  ** error indicating that a memory allocation failed.
  6111  **
  6112  ** ^The sqlite3_result_int() interface sets the return value
  6113  ** of the application-defined function to be the 32-bit signed integer
  6114  ** value given in the 2nd argument.
  6115  ** ^The sqlite3_result_int64() interface sets the return value
  6116  ** of the application-defined function to be the 64-bit signed integer
  6117  ** value given in the 2nd argument.
  6118  **
  6119  ** ^The sqlite3_result_null() interface sets the return value
  6120  ** of the application-defined function to be NULL.
  6121  **
  6122  ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  6123  ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  6124  ** set the return value of the application-defined function to be
  6125  ** a text string which is represented as UTF-8, UTF-16 native byte order,
  6126  ** UTF-16 little endian, or UTF-16 big endian, respectively.
  6127  ** ^The sqlite3_result_text64() interface sets the return value of an
  6128  ** application-defined function to be a text string in an encoding
  6129  ** specified by the fifth (and last) parameter, which must be one
  6130  ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
  6131  ** ^SQLite takes the text result from the application from
  6132  ** the 2nd parameter of the sqlite3_result_text* interfaces.
  6133  ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  6134  ** is negative, then SQLite takes result text from the 2nd parameter
  6135  ** through the first zero character.
  6136  ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  6137  ** is non-negative, then as many bytes (not characters) of the text
  6138  ** pointed to by the 2nd parameter are taken as the application-defined
  6139  ** function result.  If the 3rd parameter is non-negative, then it
  6140  ** must be the byte offset into the string where the NUL terminator would
  6141  ** appear if the string where NUL terminated.  If any NUL characters occur
  6142  ** in the string at a byte offset that is less than the value of the 3rd
  6143  ** parameter, then the resulting string will contain embedded NULs and the
  6144  ** result of expressions operating on strings with embedded NULs is undefined.
  6145  ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  6146  ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  6147  ** function as the destructor on the text or BLOB result when it has
  6148  ** finished using that result.
  6149  ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  6150  ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  6151  ** assumes that the text or BLOB result is in constant space and does not
  6152  ** copy the content of the parameter nor call a destructor on the content
  6153  ** when it has finished using that result.
  6154  ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  6155  ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  6156  ** then SQLite makes a copy of the result into space obtained
  6157  ** from [sqlite3_malloc()] before it returns.
  6158  **
  6159  ** ^The sqlite3_result_value() interface sets the result of
  6160  ** the application-defined function to be a copy of the
  6161  ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
  6162  ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  6163  ** so that the [sqlite3_value] specified in the parameter may change or
  6164  ** be deallocated after sqlite3_result_value() returns without harm.
  6165  ** ^A [protected sqlite3_value] object may always be used where an
  6166  ** [unprotected sqlite3_value] object is required, so either
  6167  ** kind of [sqlite3_value] object can be used with this interface.
  6168  **
  6169  ** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an
  6170  ** SQL NULL value, just like [sqlite3_result_null(C)], except that it
  6171  ** also associates the host-language pointer P or type T with that 
  6172  ** NULL value such that the pointer can be retrieved within an
  6173  ** [application-defined SQL function] using [sqlite3_value_pointer()].
  6174  ** ^If the D parameter is not NULL, then it is a pointer to a destructor
  6175  ** for the P parameter.  ^SQLite invokes D with P as its only argument
  6176  ** when SQLite is finished with P.  The T parameter should be a static
  6177  ** string and preferably a string literal. The sqlite3_result_pointer()
  6178  ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
  6179  **
  6180  ** If these routines are called from within the different thread
  6181  ** than the one containing the application-defined function that received
  6182  ** the [sqlite3_context] pointer, the results are undefined.
  6183  */
  6184  SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  6185  SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
  6186                             sqlite3_uint64,void(*)(void*));
  6187  SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  6188  SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  6189  SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  6190  SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  6191  SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  6192  SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  6193  SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  6194  SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  6195  SQLITE_API void sqlite3_result_null(sqlite3_context*);
  6196  SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  6197  SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
  6198                             void(*)(void*), unsigned char encoding);
  6199  SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  6200  SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  6201  SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  6202  SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  6203  SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*));
  6204  SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  6205  SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
  6206  
  6207  
  6208  /*
  6209  ** CAPI3REF: Setting The Subtype Of An SQL Function
  6210  ** METHOD: sqlite3_context
  6211  **
  6212  ** The sqlite3_result_subtype(C,T) function causes the subtype of
  6213  ** the result from the [application-defined SQL function] with 
  6214  ** [sqlite3_context] C to be the value T.  Only the lower 8 bits 
  6215  ** of the subtype T are preserved in current versions of SQLite;
  6216  ** higher order bits are discarded.
  6217  ** The number of subtype bytes preserved by SQLite might increase
  6218  ** in future releases of SQLite.
  6219  */
  6220  SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
  6221  
  6222  /*
  6223  ** CAPI3REF: Define New Collating Sequences
  6224  ** METHOD: sqlite3
  6225  **
  6226  ** ^These functions add, remove, or modify a [collation] associated
  6227  ** with the [database connection] specified as the first argument.
  6228  **
  6229  ** ^The name of the collation is a UTF-8 string
  6230  ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  6231  ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  6232  ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  6233  ** considered to be the same name.
  6234  **
  6235  ** ^(The third argument (eTextRep) must be one of the constants:
  6236  ** <ul>
  6237  ** <li> [SQLITE_UTF8],
  6238  ** <li> [SQLITE_UTF16LE],
  6239  ** <li> [SQLITE_UTF16BE],
  6240  ** <li> [SQLITE_UTF16], or
  6241  ** <li> [SQLITE_UTF16_ALIGNED].
  6242  ** </ul>)^
  6243  ** ^The eTextRep argument determines the encoding of strings passed
  6244  ** to the collating function callback, xCallback.
  6245  ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  6246  ** force strings to be UTF16 with native byte order.
  6247  ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  6248  ** on an even byte address.
  6249  **
  6250  ** ^The fourth argument, pArg, is an application data pointer that is passed
  6251  ** through as the first argument to the collating function callback.
  6252  **
  6253  ** ^The fifth argument, xCallback, is a pointer to the collating function.
  6254  ** ^Multiple collating functions can be registered using the same name but
  6255  ** with different eTextRep parameters and SQLite will use whichever
  6256  ** function requires the least amount of data transformation.
  6257  ** ^If the xCallback argument is NULL then the collating function is
  6258  ** deleted.  ^When all collating functions having the same name are deleted,
  6259  ** that collation is no longer usable.
  6260  **
  6261  ** ^The collating function callback is invoked with a copy of the pArg 
  6262  ** application data pointer and with two strings in the encoding specified
  6263  ** by the eTextRep argument.  The collating function must return an
  6264  ** integer that is negative, zero, or positive
  6265  ** if the first string is less than, equal to, or greater than the second,
  6266  ** respectively.  A collating function must always return the same answer
  6267  ** given the same inputs.  If two or more collating functions are registered
  6268  ** to the same collation name (using different eTextRep values) then all
  6269  ** must give an equivalent answer when invoked with equivalent strings.
  6270  ** The collating function must obey the following properties for all
  6271  ** strings A, B, and C:
  6272  **
  6273  ** <ol>
  6274  ** <li> If A==B then B==A.
  6275  ** <li> If A==B and B==C then A==C.
  6276  ** <li> If A&lt;B THEN B&gt;A.
  6277  ** <li> If A&lt;B and B&lt;C then A&lt;C.
  6278  ** </ol>
  6279  **
  6280  ** If a collating function fails any of the above constraints and that
  6281  ** collating function is  registered and used, then the behavior of SQLite
  6282  ** is undefined.
  6283  **
  6284  ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  6285  ** with the addition that the xDestroy callback is invoked on pArg when
  6286  ** the collating function is deleted.
  6287  ** ^Collating functions are deleted when they are overridden by later
  6288  ** calls to the collation creation functions or when the
  6289  ** [database connection] is closed using [sqlite3_close()].
  6290  **
  6291  ** ^The xDestroy callback is <u>not</u> called if the 
  6292  ** sqlite3_create_collation_v2() function fails.  Applications that invoke
  6293  ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should 
  6294  ** check the return code and dispose of the application data pointer
  6295  ** themselves rather than expecting SQLite to deal with it for them.
  6296  ** This is different from every other SQLite interface.  The inconsistency 
  6297  ** is unfortunate but cannot be changed without breaking backwards 
  6298  ** compatibility.
  6299  **
  6300  ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  6301  */
  6302  SQLITE_API int sqlite3_create_collation(
  6303    sqlite3*, 
  6304    const char *zName, 
  6305    int eTextRep, 
  6306    void *pArg,
  6307    int(*xCompare)(void*,int,const void*,int,const void*)
  6308  );
  6309  SQLITE_API int sqlite3_create_collation_v2(
  6310    sqlite3*, 
  6311    const char *zName, 
  6312    int eTextRep, 
  6313    void *pArg,
  6314    int(*xCompare)(void*,int,const void*,int,const void*),
  6315    void(*xDestroy)(void*)
  6316  );
  6317  SQLITE_API int sqlite3_create_collation16(
  6318    sqlite3*, 
  6319    const void *zName,
  6320    int eTextRep, 
  6321    void *pArg,
  6322    int(*xCompare)(void*,int,const void*,int,const void*)
  6323  );
  6324  
  6325  /*
  6326  ** CAPI3REF: Collation Needed Callbacks
  6327  ** METHOD: sqlite3
  6328  **
  6329  ** ^To avoid having to register all collation sequences before a database
  6330  ** can be used, a single callback function may be registered with the
  6331  ** [database connection] to be invoked whenever an undefined collation
  6332  ** sequence is required.
  6333  **
  6334  ** ^If the function is registered using the sqlite3_collation_needed() API,
  6335  ** then it is passed the names of undefined collation sequences as strings
  6336  ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  6337  ** the names are passed as UTF-16 in machine native byte order.
  6338  ** ^A call to either function replaces the existing collation-needed callback.
  6339  **
  6340  ** ^(When the callback is invoked, the first argument passed is a copy
  6341  ** of the second argument to sqlite3_collation_needed() or
  6342  ** sqlite3_collation_needed16().  The second argument is the database
  6343  ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  6344  ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  6345  ** sequence function required.  The fourth parameter is the name of the
  6346  ** required collation sequence.)^
  6347  **
  6348  ** The callback function should register the desired collation using
  6349  ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  6350  ** [sqlite3_create_collation_v2()].
  6351  */
  6352  SQLITE_API int sqlite3_collation_needed(
  6353    sqlite3*, 
  6354    void*, 
  6355    void(*)(void*,sqlite3*,int eTextRep,const char*)
  6356  );
  6357  SQLITE_API int sqlite3_collation_needed16(
  6358    sqlite3*, 
  6359    void*,
  6360    void(*)(void*,sqlite3*,int eTextRep,const void*)
  6361  );
  6362  
  6363  #ifdef SQLITE_HAS_CODEC
  6364  /*
  6365  ** Specify the key for an encrypted database.  This routine should be
  6366  ** called right after sqlite3_open().
  6367  **
  6368  ** The code to implement this API is not available in the public release
  6369  ** of SQLite.
  6370  */
  6371  SQLITE_API int sqlite3_key(
  6372    sqlite3 *db,                   /* Database to be rekeyed */
  6373    const void *pKey, int nKey     /* The key */
  6374  );
  6375  SQLITE_API int sqlite3_key_v2(
  6376    sqlite3 *db,                   /* Database to be rekeyed */
  6377    const char *zDbName,           /* Name of the database */
  6378    const void *pKey, int nKey     /* The key */
  6379  );
  6380  
  6381  /*
  6382  ** Change the key on an open database.  If the current database is not
  6383  ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
  6384  ** database is decrypted.
  6385  **
  6386  ** The code to implement this API is not available in the public release
  6387  ** of SQLite.
  6388  */
  6389  SQLITE_API int sqlite3_rekey(
  6390    sqlite3 *db,                   /* Database to be rekeyed */
  6391    const void *pKey, int nKey     /* The new key */
  6392  );
  6393  SQLITE_API int sqlite3_rekey_v2(
  6394    sqlite3 *db,                   /* Database to be rekeyed */
  6395    const char *zDbName,           /* Name of the database */
  6396    const void *pKey, int nKey     /* The new key */
  6397  );
  6398  
  6399  /*
  6400  ** Specify the activation key for a SEE database.  Unless 
  6401  ** activated, none of the SEE routines will work.
  6402  */
  6403  SQLITE_API void sqlite3_activate_see(
  6404    const char *zPassPhrase        /* Activation phrase */
  6405  );
  6406  #endif
  6407  
  6408  #ifdef SQLITE_ENABLE_CEROD
  6409  /*
  6410  ** Specify the activation key for a CEROD database.  Unless 
  6411  ** activated, none of the CEROD routines will work.
  6412  */
  6413  SQLITE_API void sqlite3_activate_cerod(
  6414    const char *zPassPhrase        /* Activation phrase */
  6415  );
  6416  #endif
  6417  
  6418  /*
  6419  ** CAPI3REF: Suspend Execution For A Short Time
  6420  **
  6421  ** The sqlite3_sleep() function causes the current thread to suspend execution
  6422  ** for at least a number of milliseconds specified in its parameter.
  6423  **
  6424  ** If the operating system does not support sleep requests with
  6425  ** millisecond time resolution, then the time will be rounded up to
  6426  ** the nearest second. The number of milliseconds of sleep actually
  6427  ** requested from the operating system is returned.
  6428  **
  6429  ** ^SQLite implements this interface by calling the xSleep()
  6430  ** method of the default [sqlite3_vfs] object.  If the xSleep() method
  6431  ** of the default VFS is not implemented correctly, or not implemented at
  6432  ** all, then the behavior of sqlite3_sleep() may deviate from the description
  6433  ** in the previous paragraphs.
  6434  */
  6435  SQLITE_API int sqlite3_sleep(int);
  6436  
  6437  /*
  6438  ** CAPI3REF: Name Of The Folder Holding Temporary Files
  6439  **
  6440  ** ^(If this global variable is made to point to a string which is
  6441  ** the name of a folder (a.k.a. directory), then all temporary files
  6442  ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  6443  ** will be placed in that directory.)^  ^If this variable
  6444  ** is a NULL pointer, then SQLite performs a search for an appropriate
  6445  ** temporary file directory.
  6446  **
  6447  ** Applications are strongly discouraged from using this global variable.
  6448  ** It is required to set a temporary folder on Windows Runtime (WinRT).
  6449  ** But for all other platforms, it is highly recommended that applications
  6450  ** neither read nor write this variable.  This global variable is a relic
  6451  ** that exists for backwards compatibility of legacy applications and should
  6452  ** be avoided in new projects.
  6453  **
  6454  ** It is not safe to read or modify this variable in more than one
  6455  ** thread at a time.  It is not safe to read or modify this variable
  6456  ** if a [database connection] is being used at the same time in a separate
  6457  ** thread.
  6458  ** It is intended that this variable be set once
  6459  ** as part of process initialization and before any SQLite interface
  6460  ** routines have been called and that this variable remain unchanged
  6461  ** thereafter.
  6462  **
  6463  ** ^The [temp_store_directory pragma] may modify this variable and cause
  6464  ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
  6465  ** the [temp_store_directory pragma] always assumes that any string
  6466  ** that this variable points to is held in memory obtained from 
  6467  ** [sqlite3_malloc] and the pragma may attempt to free that memory
  6468  ** using [sqlite3_free].
  6469  ** Hence, if this variable is modified directly, either it should be
  6470  ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  6471  ** or else the use of the [temp_store_directory pragma] should be avoided.
  6472  ** Except when requested by the [temp_store_directory pragma], SQLite
  6473  ** does not free the memory that sqlite3_temp_directory points to.  If
  6474  ** the application wants that memory to be freed, it must do
  6475  ** so itself, taking care to only do so after all [database connection]
  6476  ** objects have been destroyed.
  6477  **
  6478  ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
  6479  ** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
  6480  ** features that require the use of temporary files may fail.  Here is an
  6481  ** example of how to do this using C++ with the Windows Runtime:
  6482  **
  6483  ** <blockquote><pre>
  6484  ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  6485  ** &nbsp;     TemporaryFolder->Path->Data();
  6486  ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  6487  ** memset(zPathBuf, 0, sizeof(zPathBuf));
  6488  ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  6489  ** &nbsp;     NULL, NULL);
  6490  ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  6491  ** </pre></blockquote>
  6492  */
  6493  SQLITE_API char *sqlite3_temp_directory;
  6494  
  6495  /*
  6496  ** CAPI3REF: Name Of The Folder Holding Database Files
  6497  **
  6498  ** ^(If this global variable is made to point to a string which is
  6499  ** the name of a folder (a.k.a. directory), then all database files
  6500  ** specified with a relative pathname and created or accessed by
  6501  ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  6502  ** to be relative to that directory.)^ ^If this variable is a NULL
  6503  ** pointer, then SQLite assumes that all database files specified
  6504  ** with a relative pathname are relative to the current directory
  6505  ** for the process.  Only the windows VFS makes use of this global
  6506  ** variable; it is ignored by the unix VFS.
  6507  **
  6508  ** Changing the value of this variable while a database connection is
  6509  ** open can result in a corrupt database.
  6510  **
  6511  ** It is not safe to read or modify this variable in more than one
  6512  ** thread at a time.  It is not safe to read or modify this variable
  6513  ** if a [database connection] is being used at the same time in a separate
  6514  ** thread.
  6515  ** It is intended that this variable be set once
  6516  ** as part of process initialization and before any SQLite interface
  6517  ** routines have been called and that this variable remain unchanged
  6518  ** thereafter.
  6519  **
  6520  ** ^The [data_store_directory pragma] may modify this variable and cause
  6521  ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
  6522  ** the [data_store_directory pragma] always assumes that any string
  6523  ** that this variable points to is held in memory obtained from 
  6524  ** [sqlite3_malloc] and the pragma may attempt to free that memory
  6525  ** using [sqlite3_free].
  6526  ** Hence, if this variable is modified directly, either it should be
  6527  ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  6528  ** or else the use of the [data_store_directory pragma] should be avoided.
  6529  */
  6530  SQLITE_API char *sqlite3_data_directory;
  6531  
  6532  /*
  6533  ** CAPI3REF: Test For Auto-Commit Mode
  6534  ** KEYWORDS: {autocommit mode}
  6535  ** METHOD: sqlite3
  6536  **
  6537  ** ^The sqlite3_get_autocommit() interface returns non-zero or
  6538  ** zero if the given database connection is or is not in autocommit mode,
  6539  ** respectively.  ^Autocommit mode is on by default.
  6540  ** ^Autocommit mode is disabled by a [BEGIN] statement.
  6541  ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  6542  **
  6543  ** If certain kinds of errors occur on a statement within a multi-statement
  6544  ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  6545  ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  6546  ** transaction might be rolled back automatically.  The only way to
  6547  ** find out whether SQLite automatically rolled back the transaction after
  6548  ** an error is to use this function.
  6549  **
  6550  ** If another thread changes the autocommit status of the database
  6551  ** connection while this routine is running, then the return value
  6552  ** is undefined.
  6553  */
  6554  SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  6555  
  6556  /*
  6557  ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  6558  ** METHOD: sqlite3_stmt
  6559  **
  6560  ** ^The sqlite3_db_handle interface returns the [database connection] handle
  6561  ** to which a [prepared statement] belongs.  ^The [database connection]
  6562  ** returned by sqlite3_db_handle is the same [database connection]
  6563  ** that was the first argument
  6564  ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  6565  ** create the statement in the first place.
  6566  */
  6567  SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  6568  
  6569  /*
  6570  ** CAPI3REF: Return The Filename For A Database Connection
  6571  ** METHOD: sqlite3
  6572  **
  6573  ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  6574  ** associated with database N of connection D.  ^The main database file
  6575  ** has the name "main".  If there is no attached database N on the database
  6576  ** connection D, or if database N is a temporary or in-memory database, then
  6577  ** a NULL pointer is returned.
  6578  **
  6579  ** ^The filename returned by this function is the output of the
  6580  ** xFullPathname method of the [VFS].  ^In other words, the filename
  6581  ** will be an absolute pathname, even if the filename used
  6582  ** to open the database originally was a URI or relative pathname.
  6583  */
  6584  SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  6585  
  6586  /*
  6587  ** CAPI3REF: Determine if a database is read-only
  6588  ** METHOD: sqlite3
  6589  **
  6590  ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  6591  ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  6592  ** the name of a database on connection D.
  6593  */
  6594  SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  6595  
  6596  /*
  6597  ** CAPI3REF: Find the next prepared statement
  6598  ** METHOD: sqlite3
  6599  **
  6600  ** ^This interface returns a pointer to the next [prepared statement] after
  6601  ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
  6602  ** then this interface returns a pointer to the first prepared statement
  6603  ** associated with the database connection pDb.  ^If no prepared statement
  6604  ** satisfies the conditions of this routine, it returns NULL.
  6605  **
  6606  ** The [database connection] pointer D in a call to
  6607  ** [sqlite3_next_stmt(D,S)] must refer to an open database
  6608  ** connection and in particular must not be a NULL pointer.
  6609  */
  6610  SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  6611  
  6612  /*
  6613  ** CAPI3REF: Commit And Rollback Notification Callbacks
  6614  ** METHOD: sqlite3
  6615  **
  6616  ** ^The sqlite3_commit_hook() interface registers a callback
  6617  ** function to be invoked whenever a transaction is [COMMIT | committed].
  6618  ** ^Any callback set by a previous call to sqlite3_commit_hook()
  6619  ** for the same database connection is overridden.
  6620  ** ^The sqlite3_rollback_hook() interface registers a callback
  6621  ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  6622  ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  6623  ** for the same database connection is overridden.
  6624  ** ^The pArg argument is passed through to the callback.
  6625  ** ^If the callback on a commit hook function returns non-zero,
  6626  ** then the commit is converted into a rollback.
  6627  **
  6628  ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  6629  ** return the P argument from the previous call of the same function
  6630  ** on the same [database connection] D, or NULL for
  6631  ** the first call for each function on D.
  6632  **
  6633  ** The commit and rollback hook callbacks are not reentrant.
  6634  ** The callback implementation must not do anything that will modify
  6635  ** the database connection that invoked the callback.  Any actions
  6636  ** to modify the database connection must be deferred until after the
  6637  ** completion of the [sqlite3_step()] call that triggered the commit
  6638  ** or rollback hook in the first place.
  6639  ** Note that running any other SQL statements, including SELECT statements,
  6640  ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  6641  ** the database connections for the meaning of "modify" in this paragraph.
  6642  **
  6643  ** ^Registering a NULL function disables the callback.
  6644  **
  6645  ** ^When the commit hook callback routine returns zero, the [COMMIT]
  6646  ** operation is allowed to continue normally.  ^If the commit hook
  6647  ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  6648  ** ^The rollback hook is invoked on a rollback that results from a commit
  6649  ** hook returning non-zero, just as it would be with any other rollback.
  6650  **
  6651  ** ^For the purposes of this API, a transaction is said to have been
  6652  ** rolled back if an explicit "ROLLBACK" statement is executed, or
  6653  ** an error or constraint causes an implicit rollback to occur.
  6654  ** ^The rollback callback is not invoked if a transaction is
  6655  ** automatically rolled back because the database connection is closed.
  6656  **
  6657  ** See also the [sqlite3_update_hook()] interface.
  6658  */
  6659  SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  6660  SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  6661  
  6662  /*
  6663  ** CAPI3REF: Data Change Notification Callbacks
  6664  ** METHOD: sqlite3
  6665  **
  6666  ** ^The sqlite3_update_hook() interface registers a callback function
  6667  ** with the [database connection] identified by the first argument
  6668  ** to be invoked whenever a row is updated, inserted or deleted in
  6669  ** a [rowid table].
  6670  ** ^Any callback set by a previous call to this function
  6671  ** for the same database connection is overridden.
  6672  **
  6673  ** ^The second argument is a pointer to the function to invoke when a
  6674  ** row is updated, inserted or deleted in a rowid table.
  6675  ** ^The first argument to the callback is a copy of the third argument
  6676  ** to sqlite3_update_hook().
  6677  ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  6678  ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  6679  ** to be invoked.
  6680  ** ^The third and fourth arguments to the callback contain pointers to the
  6681  ** database and table name containing the affected row.
  6682  ** ^The final callback parameter is the [rowid] of the row.
  6683  ** ^In the case of an update, this is the [rowid] after the update takes place.
  6684  **
  6685  ** ^(The update hook is not invoked when internal system tables are
  6686  ** modified (i.e. sqlite_master and sqlite_sequence).)^
  6687  ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
  6688  **
  6689  ** ^In the current implementation, the update hook
  6690  ** is not invoked when conflicting rows are deleted because of an
  6691  ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
  6692  ** invoked when rows are deleted using the [truncate optimization].
  6693  ** The exceptions defined in this paragraph might change in a future
  6694  ** release of SQLite.
  6695  **
  6696  ** The update hook implementation must not do anything that will modify
  6697  ** the database connection that invoked the update hook.  Any actions
  6698  ** to modify the database connection must be deferred until after the
  6699  ** completion of the [sqlite3_step()] call that triggered the update hook.
  6700  ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  6701  ** database connections for the meaning of "modify" in this paragraph.
  6702  **
  6703  ** ^The sqlite3_update_hook(D,C,P) function
  6704  ** returns the P argument from the previous call
  6705  ** on the same [database connection] D, or NULL for
  6706  ** the first call on D.
  6707  **
  6708  ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
  6709  ** and [sqlite3_preupdate_hook()] interfaces.
  6710  */
  6711  SQLITE_API void *sqlite3_update_hook(
  6712    sqlite3*, 
  6713    void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  6714    void*
  6715  );
  6716  
  6717  /*
  6718  ** CAPI3REF: Enable Or Disable Shared Pager Cache
  6719  **
  6720  ** ^(This routine enables or disables the sharing of the database cache
  6721  ** and schema data structures between [database connection | connections]
  6722  ** to the same database. Sharing is enabled if the argument is true
  6723  ** and disabled if the argument is false.)^
  6724  **
  6725  ** ^Cache sharing is enabled and disabled for an entire process.
  6726  ** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]). 
  6727  ** In prior versions of SQLite,
  6728  ** sharing was enabled or disabled for each thread separately.
  6729  **
  6730  ** ^(The cache sharing mode set by this interface effects all subsequent
  6731  ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  6732  ** Existing database connections continue use the sharing mode
  6733  ** that was in effect at the time they were opened.)^
  6734  **
  6735  ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  6736  ** successfully.  An [error code] is returned otherwise.)^
  6737  **
  6738  ** ^Shared cache is disabled by default. But this might change in
  6739  ** future releases of SQLite.  Applications that care about shared
  6740  ** cache setting should set it explicitly.
  6741  **
  6742  ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
  6743  ** and will always return SQLITE_MISUSE. On those systems, 
  6744  ** shared cache mode should be enabled per-database connection via 
  6745  ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
  6746  **
  6747  ** This interface is threadsafe on processors where writing a
  6748  ** 32-bit integer is atomic.
  6749  **
  6750  ** See Also:  [SQLite Shared-Cache Mode]
  6751  */
  6752  SQLITE_API int sqlite3_enable_shared_cache(int);
  6753  
  6754  /*
  6755  ** CAPI3REF: Attempt To Free Heap Memory
  6756  **
  6757  ** ^The sqlite3_release_memory() interface attempts to free N bytes
  6758  ** of heap memory by deallocating non-essential memory allocations
  6759  ** held by the database library.   Memory used to cache database
  6760  ** pages to improve performance is an example of non-essential memory.
  6761  ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  6762  ** which might be more or less than the amount requested.
  6763  ** ^The sqlite3_release_memory() routine is a no-op returning zero
  6764  ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  6765  **
  6766  ** See also: [sqlite3_db_release_memory()]
  6767  */
  6768  SQLITE_API int sqlite3_release_memory(int);
  6769  
  6770  /*
  6771  ** CAPI3REF: Free Memory Used By A Database Connection
  6772  ** METHOD: sqlite3
  6773  **
  6774  ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  6775  ** memory as possible from database connection D. Unlike the
  6776  ** [sqlite3_release_memory()] interface, this interface is in effect even
  6777  ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  6778  ** omitted.
  6779  **
  6780  ** See also: [sqlite3_release_memory()]
  6781  */
  6782  SQLITE_API int sqlite3_db_release_memory(sqlite3*);
  6783  
  6784  /*
  6785  ** CAPI3REF: Impose A Limit On Heap Size
  6786  **
  6787  ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  6788  ** soft limit on the amount of heap memory that may be allocated by SQLite.
  6789  ** ^SQLite strives to keep heap memory utilization below the soft heap
  6790  ** limit by reducing the number of pages held in the page cache
  6791  ** as heap memory usages approaches the limit.
  6792  ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  6793  ** below the limit, it will exceed the limit rather than generate
  6794  ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit 
  6795  ** is advisory only.
  6796  **
  6797  ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  6798  ** the soft heap limit prior to the call, or negative in the case of an
  6799  ** error.  ^If the argument N is negative
  6800  ** then no change is made to the soft heap limit.  Hence, the current
  6801  ** size of the soft heap limit can be determined by invoking
  6802  ** sqlite3_soft_heap_limit64() with a negative argument.
  6803  **
  6804  ** ^If the argument N is zero then the soft heap limit is disabled.
  6805  **
  6806  ** ^(The soft heap limit is not enforced in the current implementation
  6807  ** if one or more of following conditions are true:
  6808  **
  6809  ** <ul>
  6810  ** <li> The soft heap limit is set to zero.
  6811  ** <li> Memory accounting is disabled using a combination of the
  6812  **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  6813  **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  6814  ** <li> An alternative page cache implementation is specified using
  6815  **      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  6816  ** <li> The page cache allocates from its own memory pool supplied
  6817  **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  6818  **      from the heap.
  6819  ** </ul>)^
  6820  **
  6821  ** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]), 
  6822  ** the soft heap limit is enforced
  6823  ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  6824  ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  6825  ** the soft heap limit is enforced on every memory allocation.  Without
  6826  ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  6827  ** when memory is allocated by the page cache.  Testing suggests that because
  6828  ** the page cache is the predominate memory user in SQLite, most
  6829  ** applications will achieve adequate soft heap limit enforcement without
  6830  ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  6831  **
  6832  ** The circumstances under which SQLite will enforce the soft heap limit may
  6833  ** changes in future releases of SQLite.
  6834  */
  6835  SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  6836  
  6837  /*
  6838  ** CAPI3REF: Deprecated Soft Heap Limit Interface
  6839  ** DEPRECATED
  6840  **
  6841  ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  6842  ** interface.  This routine is provided for historical compatibility
  6843  ** only.  All new applications should use the
  6844  ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  6845  */
  6846  SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  6847  
  6848  
  6849  /*
  6850  ** CAPI3REF: Extract Metadata About A Column Of A Table
  6851  ** METHOD: sqlite3
  6852  **
  6853  ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
  6854  ** information about column C of table T in database D
  6855  ** on [database connection] X.)^  ^The sqlite3_table_column_metadata()
  6856  ** interface returns SQLITE_OK and fills in the non-NULL pointers in
  6857  ** the final five arguments with appropriate values if the specified
  6858  ** column exists.  ^The sqlite3_table_column_metadata() interface returns
  6859  ** SQLITE_ERROR and if the specified column does not exist.
  6860  ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
  6861  ** NULL pointer, then this routine simply checks for the existence of the
  6862  ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
  6863  ** does not.  If the table name parameter T in a call to
  6864  ** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is
  6865  ** undefined behavior.
  6866  **
  6867  ** ^The column is identified by the second, third and fourth parameters to
  6868  ** this function. ^(The second parameter is either the name of the database
  6869  ** (i.e. "main", "temp", or an attached database) containing the specified
  6870  ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
  6871  ** for the table using the same algorithm used by the database engine to
  6872  ** resolve unqualified table references.
  6873  **
  6874  ** ^The third and fourth parameters to this function are the table and column
  6875  ** name of the desired column, respectively.
  6876  **
  6877  ** ^Metadata is returned by writing to the memory locations passed as the 5th
  6878  ** and subsequent parameters to this function. ^Any of these arguments may be
  6879  ** NULL, in which case the corresponding element of metadata is omitted.
  6880  **
  6881  ** ^(<blockquote>
  6882  ** <table border="1">
  6883  ** <tr><th> Parameter <th> Output<br>Type <th>  Description
  6884  **
  6885  ** <tr><td> 5th <td> const char* <td> Data type
  6886  ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  6887  ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
  6888  ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
  6889  ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
  6890  ** </table>
  6891  ** </blockquote>)^
  6892  **
  6893  ** ^The memory pointed to by the character pointers returned for the
  6894  ** declaration type and collation sequence is valid until the next
  6895  ** call to any SQLite API function.
  6896  **
  6897  ** ^If the specified table is actually a view, an [error code] is returned.
  6898  **
  6899  ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table 
  6900  ** is not a [WITHOUT ROWID] table and an
  6901  ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  6902  ** parameters are set for the explicitly declared column. ^(If there is no
  6903  ** [INTEGER PRIMARY KEY] column, then the outputs
  6904  ** for the [rowid] are set as follows:
  6905  **
  6906  ** <pre>
  6907  **     data type: "INTEGER"
  6908  **     collation sequence: "BINARY"
  6909  **     not null: 0
  6910  **     primary key: 1
  6911  **     auto increment: 0
  6912  ** </pre>)^
  6913  **
  6914  ** ^This function causes all database schemas to be read from disk and
  6915  ** parsed, if that has not already been done, and returns an error if
  6916  ** any errors are encountered while loading the schema.
  6917  */
  6918  SQLITE_API int sqlite3_table_column_metadata(
  6919    sqlite3 *db,                /* Connection handle */
  6920    const char *zDbName,        /* Database name or NULL */
  6921    const char *zTableName,     /* Table name */
  6922    const char *zColumnName,    /* Column name */
  6923    char const **pzDataType,    /* OUTPUT: Declared data type */
  6924    char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
  6925    int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
  6926    int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
  6927    int *pAutoinc               /* OUTPUT: True if column is auto-increment */
  6928  );
  6929  
  6930  /*
  6931  ** CAPI3REF: Load An Extension
  6932  ** METHOD: sqlite3
  6933  **
  6934  ** ^This interface loads an SQLite extension library from the named file.
  6935  **
  6936  ** ^The sqlite3_load_extension() interface attempts to load an
  6937  ** [SQLite extension] library contained in the file zFile.  If
  6938  ** the file cannot be loaded directly, attempts are made to load
  6939  ** with various operating-system specific extensions added.
  6940  ** So for example, if "samplelib" cannot be loaded, then names like
  6941  ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  6942  ** be tried also.
  6943  **
  6944  ** ^The entry point is zProc.
  6945  ** ^(zProc may be 0, in which case SQLite will try to come up with an
  6946  ** entry point name on its own.  It first tries "sqlite3_extension_init".
  6947  ** If that does not work, it constructs a name "sqlite3_X_init" where the
  6948  ** X is consists of the lower-case equivalent of all ASCII alphabetic
  6949  ** characters in the filename from the last "/" to the first following
  6950  ** "." and omitting any initial "lib".)^
  6951  ** ^The sqlite3_load_extension() interface returns
  6952  ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  6953  ** ^If an error occurs and pzErrMsg is not 0, then the
  6954  ** [sqlite3_load_extension()] interface shall attempt to
  6955  ** fill *pzErrMsg with error message text stored in memory
  6956  ** obtained from [sqlite3_malloc()]. The calling function
  6957  ** should free this memory by calling [sqlite3_free()].
  6958  **
  6959  ** ^Extension loading must be enabled using
  6960  ** [sqlite3_enable_load_extension()] or
  6961  ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
  6962  ** prior to calling this API,
  6963  ** otherwise an error will be returned.
  6964  **
  6965  ** <b>Security warning:</b> It is recommended that the 
  6966  ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
  6967  ** interface.  The use of the [sqlite3_enable_load_extension()] interface
  6968  ** should be avoided.  This will keep the SQL function [load_extension()]
  6969  ** disabled and prevent SQL injections from giving attackers
  6970  ** access to extension loading capabilities.
  6971  **
  6972  ** See also the [load_extension() SQL function].
  6973  */
  6974  SQLITE_API int sqlite3_load_extension(
  6975    sqlite3 *db,          /* Load the extension into this database connection */
  6976    const char *zFile,    /* Name of the shared library containing extension */
  6977    const char *zProc,    /* Entry point.  Derived from zFile if 0 */
  6978    char **pzErrMsg       /* Put error message here if not 0 */
  6979  );
  6980  
  6981  /*
  6982  ** CAPI3REF: Enable Or Disable Extension Loading
  6983  ** METHOD: sqlite3
  6984  **
  6985  ** ^So as not to open security holes in older applications that are
  6986  ** unprepared to deal with [extension loading], and as a means of disabling
  6987  ** [extension loading] while evaluating user-entered SQL, the following API
  6988  ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  6989  **
  6990  ** ^Extension loading is off by default.
  6991  ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  6992  ** to turn extension loading on and call it with onoff==0 to turn
  6993  ** it back off again.
  6994  **
  6995  ** ^This interface enables or disables both the C-API
  6996  ** [sqlite3_load_extension()] and the SQL function [load_extension()].
  6997  ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
  6998  ** to enable or disable only the C-API.)^
  6999  **
  7000  ** <b>Security warning:</b> It is recommended that extension loading
  7001  ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
  7002  ** rather than this interface, so the [load_extension()] SQL function
  7003  ** remains disabled. This will prevent SQL injections from giving attackers
  7004  ** access to extension loading capabilities.
  7005  */
  7006  SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  7007  
  7008  /*
  7009  ** CAPI3REF: Automatically Load Statically Linked Extensions
  7010  **
  7011  ** ^This interface causes the xEntryPoint() function to be invoked for
  7012  ** each new [database connection] that is created.  The idea here is that
  7013  ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  7014  ** that is to be automatically loaded into all new database connections.
  7015  **
  7016  ** ^(Even though the function prototype shows that xEntryPoint() takes
  7017  ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  7018  ** arguments and expects an integer result as if the signature of the
  7019  ** entry point where as follows:
  7020  **
  7021  ** <blockquote><pre>
  7022  ** &nbsp;  int xEntryPoint(
  7023  ** &nbsp;    sqlite3 *db,
  7024  ** &nbsp;    const char **pzErrMsg,
  7025  ** &nbsp;    const struct sqlite3_api_routines *pThunk
  7026  ** &nbsp;  );
  7027  ** </pre></blockquote>)^
  7028  **
  7029  ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  7030  ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  7031  ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
  7032  ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
  7033  ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
  7034  ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  7035  ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  7036  **
  7037  ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  7038  ** on the list of automatic extensions is a harmless no-op. ^No entry point
  7039  ** will be called more than once for each database connection that is opened.
  7040  **
  7041  ** See also: [sqlite3_reset_auto_extension()]
  7042  ** and [sqlite3_cancel_auto_extension()]
  7043  */
  7044  SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
  7045  
  7046  /*
  7047  ** CAPI3REF: Cancel Automatic Extension Loading
  7048  **
  7049  ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  7050  ** initialization routine X that was registered using a prior call to
  7051  ** [sqlite3_auto_extension(X)].  ^The [sqlite3_cancel_auto_extension(X)]
  7052  ** routine returns 1 if initialization routine X was successfully 
  7053  ** unregistered and it returns 0 if X was not on the list of initialization
  7054  ** routines.
  7055  */
  7056  SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
  7057  
  7058  /*
  7059  ** CAPI3REF: Reset Automatic Extension Loading
  7060  **
  7061  ** ^This interface disables all automatic extensions previously
  7062  ** registered using [sqlite3_auto_extension()].
  7063  */
  7064  SQLITE_API void sqlite3_reset_auto_extension(void);
  7065  
  7066  /*
  7067  ** The interface to the virtual-table mechanism is currently considered
  7068  ** to be experimental.  The interface might change in incompatible ways.
  7069  ** If this is a problem for you, do not use the interface at this time.
  7070  **
  7071  ** When the virtual-table mechanism stabilizes, we will declare the
  7072  ** interface fixed, support it indefinitely, and remove this comment.
  7073  */
  7074  
  7075  /*
  7076  ** Structures used by the virtual table interface
  7077  */
  7078  typedef struct sqlite3_vtab sqlite3_vtab;
  7079  typedef struct sqlite3_index_info sqlite3_index_info;
  7080  typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  7081  typedef struct sqlite3_module sqlite3_module;
  7082  
  7083  /*
  7084  ** CAPI3REF: Virtual Table Object
  7085  ** KEYWORDS: sqlite3_module {virtual table module}
  7086  **
  7087  ** This structure, sometimes called a "virtual table module", 
  7088  ** defines the implementation of a [virtual tables].  
  7089  ** This structure consists mostly of methods for the module.
  7090  **
  7091  ** ^A virtual table module is created by filling in a persistent
  7092  ** instance of this structure and passing a pointer to that instance
  7093  ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  7094  ** ^The registration remains valid until it is replaced by a different
  7095  ** module or until the [database connection] closes.  The content
  7096  ** of this structure must not change while it is registered with
  7097  ** any database connection.
  7098  */
  7099  struct sqlite3_module {
  7100    int iVersion;
  7101    int (*xCreate)(sqlite3*, void *pAux,
  7102                 int argc, const char *const*argv,
  7103                 sqlite3_vtab **ppVTab, char**);
  7104    int (*xConnect)(sqlite3*, void *pAux,
  7105                 int argc, const char *const*argv,
  7106                 sqlite3_vtab **ppVTab, char**);
  7107    int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  7108    int (*xDisconnect)(sqlite3_vtab *pVTab);
  7109    int (*xDestroy)(sqlite3_vtab *pVTab);
  7110    int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  7111    int (*xClose)(sqlite3_vtab_cursor*);
  7112    int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  7113                  int argc, sqlite3_value **argv);
  7114    int (*xNext)(sqlite3_vtab_cursor*);
  7115    int (*xEof)(sqlite3_vtab_cursor*);
  7116    int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  7117    int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  7118    int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  7119    int (*xBegin)(sqlite3_vtab *pVTab);
  7120    int (*xSync)(sqlite3_vtab *pVTab);
  7121    int (*xCommit)(sqlite3_vtab *pVTab);
  7122    int (*xRollback)(sqlite3_vtab *pVTab);
  7123    int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  7124                         void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  7125                         void **ppArg);
  7126    int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  7127    /* The methods above are in version 1 of the sqlite_module object. Those 
  7128    ** below are for version 2 and greater. */
  7129    int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  7130    int (*xRelease)(sqlite3_vtab *pVTab, int);
  7131    int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  7132  };
  7133  
  7134  /*
  7135  ** CAPI3REF: Virtual Table Indexing Information
  7136  ** KEYWORDS: sqlite3_index_info
  7137  **
  7138  ** The sqlite3_index_info structure and its substructures is used as part
  7139  ** of the [virtual table] interface to
  7140  ** pass information into and receive the reply from the [xBestIndex]
  7141  ** method of a [virtual table module].  The fields under **Inputs** are the
  7142  ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
  7143  ** results into the **Outputs** fields.
  7144  **
  7145  ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  7146  **
  7147  ** <blockquote>column OP expr</blockquote>
  7148  **
  7149  ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
  7150  ** stored in aConstraint[].op using one of the
  7151  ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  7152  ** ^(The index of the column is stored in
  7153  ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
  7154  ** expr on the right-hand side can be evaluated (and thus the constraint
  7155  ** is usable) and false if it cannot.)^
  7156  **
  7157  ** ^The optimizer automatically inverts terms of the form "expr OP column"
  7158  ** and makes other simplifications to the WHERE clause in an attempt to
  7159  ** get as many WHERE clause terms into the form shown above as possible.
  7160  ** ^The aConstraint[] array only reports WHERE clause terms that are
  7161  ** relevant to the particular virtual table being queried.
  7162  **
  7163  ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  7164  ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  7165  **
  7166  ** The colUsed field indicates which columns of the virtual table may be
  7167  ** required by the current scan. Virtual table columns are numbered from
  7168  ** zero in the order in which they appear within the CREATE TABLE statement
  7169  ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
  7170  ** the corresponding bit is set within the colUsed mask if the column may be
  7171  ** required by SQLite. If the table has at least 64 columns and any column
  7172  ** to the right of the first 63 is required, then bit 63 of colUsed is also
  7173  ** set. In other words, column iCol may be required if the expression
  7174  ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to 
  7175  ** non-zero.
  7176  **
  7177  ** The [xBestIndex] method must fill aConstraintUsage[] with information
  7178  ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
  7179  ** the right-hand side of the corresponding aConstraint[] is evaluated
  7180  ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
  7181  ** is true, then the constraint is assumed to be fully handled by the
  7182  ** virtual table and is not checked again by SQLite.)^
  7183  **
  7184  ** ^The idxNum and idxPtr values are recorded and passed into the
  7185  ** [xFilter] method.
  7186  ** ^[sqlite3_free()] is used to free idxPtr if and only if
  7187  ** needToFreeIdxPtr is true.
  7188  **
  7189  ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  7190  ** the correct order to satisfy the ORDER BY clause so that no separate
  7191  ** sorting step is required.
  7192  **
  7193  ** ^The estimatedCost value is an estimate of the cost of a particular
  7194  ** strategy. A cost of N indicates that the cost of the strategy is similar
  7195  ** to a linear scan of an SQLite table with N rows. A cost of log(N) 
  7196  ** indicates that the expense of the operation is similar to that of a
  7197  ** binary search on a unique indexed field of an SQLite table with N rows.
  7198  **
  7199  ** ^The estimatedRows value is an estimate of the number of rows that
  7200  ** will be returned by the strategy.
  7201  **
  7202  ** The xBestIndex method may optionally populate the idxFlags field with a 
  7203  ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
  7204  ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
  7205  ** assumes that the strategy may visit at most one row. 
  7206  **
  7207  ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
  7208  ** SQLite also assumes that if a call to the xUpdate() method is made as
  7209  ** part of the same statement to delete or update a virtual table row and the
  7210  ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
  7211  ** any database changes. In other words, if the xUpdate() returns
  7212  ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
  7213  ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
  7214  ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
  7215  ** the xUpdate method are automatically rolled back by SQLite.
  7216  **
  7217  ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
  7218  ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]). 
  7219  ** If a virtual table extension is
  7220  ** used with an SQLite version earlier than 3.8.2, the results of attempting 
  7221  ** to read or write the estimatedRows field are undefined (but are likely 
  7222  ** to included crashing the application). The estimatedRows field should
  7223  ** therefore only be used if [sqlite3_libversion_number()] returns a
  7224  ** value greater than or equal to 3008002. Similarly, the idxFlags field
  7225  ** was added for [version 3.9.0] ([dateof:3.9.0]). 
  7226  ** It may therefore only be used if
  7227  ** sqlite3_libversion_number() returns a value greater than or equal to
  7228  ** 3009000.
  7229  */
  7230  struct sqlite3_index_info {
  7231    /* Inputs */
  7232    int nConstraint;           /* Number of entries in aConstraint */
  7233    struct sqlite3_index_constraint {
  7234       int iColumn;              /* Column constrained.  -1 for ROWID */
  7235       unsigned char op;         /* Constraint operator */
  7236       unsigned char usable;     /* True if this constraint is usable */
  7237       int iTermOffset;          /* Used internally - xBestIndex should ignore */
  7238    } *aConstraint;            /* Table of WHERE clause constraints */
  7239    int nOrderBy;              /* Number of terms in the ORDER BY clause */
  7240    struct sqlite3_index_orderby {
  7241       int iColumn;              /* Column number */
  7242       unsigned char desc;       /* True for DESC.  False for ASC. */
  7243    } *aOrderBy;               /* The ORDER BY clause */
  7244    /* Outputs */
  7245    struct sqlite3_index_constraint_usage {
  7246      int argvIndex;           /* if >0, constraint is part of argv to xFilter */
  7247      unsigned char omit;      /* Do not code a test for this constraint */
  7248    } *aConstraintUsage;
  7249    int idxNum;                /* Number used to identify the index */
  7250    char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
  7251    int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
  7252    int orderByConsumed;       /* True if output is already ordered */
  7253    double estimatedCost;           /* Estimated cost of using this index */
  7254    /* Fields below are only available in SQLite 3.8.2 and later */
  7255    sqlite3_int64 estimatedRows;    /* Estimated number of rows returned */
  7256    /* Fields below are only available in SQLite 3.9.0 and later */
  7257    int idxFlags;              /* Mask of SQLITE_INDEX_SCAN_* flags */
  7258    /* Fields below are only available in SQLite 3.10.0 and later */
  7259    sqlite3_uint64 colUsed;    /* Input: Mask of columns used by statement */
  7260  };
  7261  
  7262  /*
  7263  ** CAPI3REF: Virtual Table Scan Flags
  7264  */
  7265  #define SQLITE_INDEX_SCAN_UNIQUE      1     /* Scan visits at most 1 row */
  7266  
  7267  /*
  7268  ** CAPI3REF: Virtual Table Constraint Operator Codes
  7269  **
  7270  ** These macros defined the allowed values for the
  7271  ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
  7272  ** an operator that is part of a constraint term in the wHERE clause of
  7273  ** a query that uses a [virtual table].
  7274  */
  7275  #define SQLITE_INDEX_CONSTRAINT_EQ         2
  7276  #define SQLITE_INDEX_CONSTRAINT_GT         4
  7277  #define SQLITE_INDEX_CONSTRAINT_LE         8
  7278  #define SQLITE_INDEX_CONSTRAINT_LT        16
  7279  #define SQLITE_INDEX_CONSTRAINT_GE        32
  7280  #define SQLITE_INDEX_CONSTRAINT_MATCH     64
  7281  #define SQLITE_INDEX_CONSTRAINT_LIKE      65
  7282  #define SQLITE_INDEX_CONSTRAINT_GLOB      66
  7283  #define SQLITE_INDEX_CONSTRAINT_REGEXP    67
  7284  #define SQLITE_INDEX_CONSTRAINT_NE        68
  7285  #define SQLITE_INDEX_CONSTRAINT_ISNOT     69
  7286  #define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70
  7287  #define SQLITE_INDEX_CONSTRAINT_ISNULL    71
  7288  #define SQLITE_INDEX_CONSTRAINT_IS        72
  7289  
  7290  /*
  7291  ** CAPI3REF: Register A Virtual Table Implementation
  7292  ** METHOD: sqlite3
  7293  **
  7294  ** ^These routines are used to register a new [virtual table module] name.
  7295  ** ^Module names must be registered before
  7296  ** creating a new [virtual table] using the module and before using a
  7297  ** preexisting [virtual table] for the module.
  7298  **
  7299  ** ^The module name is registered on the [database connection] specified
  7300  ** by the first parameter.  ^The name of the module is given by the 
  7301  ** second parameter.  ^The third parameter is a pointer to
  7302  ** the implementation of the [virtual table module].   ^The fourth
  7303  ** parameter is an arbitrary client data pointer that is passed through
  7304  ** into the [xCreate] and [xConnect] methods of the virtual table module
  7305  ** when a new virtual table is be being created or reinitialized.
  7306  **
  7307  ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  7308  ** is a pointer to a destructor for the pClientData.  ^SQLite will
  7309  ** invoke the destructor function (if it is not NULL) when SQLite
  7310  ** no longer needs the pClientData pointer.  ^The destructor will also
  7311  ** be invoked if the call to sqlite3_create_module_v2() fails.
  7312  ** ^The sqlite3_create_module()
  7313  ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  7314  ** destructor.
  7315  */
  7316  SQLITE_API int sqlite3_create_module(
  7317    sqlite3 *db,               /* SQLite connection to register module with */
  7318    const char *zName,         /* Name of the module */
  7319    const sqlite3_module *p,   /* Methods for the module */
  7320    void *pClientData          /* Client data for xCreate/xConnect */
  7321  );
  7322  SQLITE_API int sqlite3_create_module_v2(
  7323    sqlite3 *db,               /* SQLite connection to register module with */
  7324    const char *zName,         /* Name of the module */
  7325    const sqlite3_module *p,   /* Methods for the module */
  7326    void *pClientData,         /* Client data for xCreate/xConnect */
  7327    void(*xDestroy)(void*)     /* Module destructor function */
  7328  );
  7329  
  7330  /*
  7331  ** CAPI3REF: Virtual Table Instance Object
  7332  ** KEYWORDS: sqlite3_vtab
  7333  **
  7334  ** Every [virtual table module] implementation uses a subclass
  7335  ** of this object to describe a particular instance
  7336  ** of the [virtual table].  Each subclass will
  7337  ** be tailored to the specific needs of the module implementation.
  7338  ** The purpose of this superclass is to define certain fields that are
  7339  ** common to all module implementations.
  7340  **
  7341  ** ^Virtual tables methods can set an error message by assigning a
  7342  ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
  7343  ** take care that any prior string is freed by a call to [sqlite3_free()]
  7344  ** prior to assigning a new string to zErrMsg.  ^After the error message
  7345  ** is delivered up to the client application, the string will be automatically
  7346  ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  7347  */
  7348  struct sqlite3_vtab {
  7349    const sqlite3_module *pModule;  /* The module for this virtual table */
  7350    int nRef;                       /* Number of open cursors */
  7351    char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
  7352    /* Virtual table implementations will typically add additional fields */
  7353  };
  7354  
  7355  /*
  7356  ** CAPI3REF: Virtual Table Cursor Object
  7357  ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  7358  **
  7359  ** Every [virtual table module] implementation uses a subclass of the
  7360  ** following structure to describe cursors that point into the
  7361  ** [virtual table] and are used
  7362  ** to loop through the virtual table.  Cursors are created using the
  7363  ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  7364  ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
  7365  ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  7366  ** of the module.  Each module implementation will define
  7367  ** the content of a cursor structure to suit its own needs.
  7368  **
  7369  ** This superclass exists in order to define fields of the cursor that
  7370  ** are common to all implementations.
  7371  */
  7372  struct sqlite3_vtab_cursor {
  7373    sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
  7374    /* Virtual table implementations will typically add additional fields */
  7375  };
  7376  
  7377  /*
  7378  ** CAPI3REF: Declare The Schema Of A Virtual Table
  7379  **
  7380  ** ^The [xCreate] and [xConnect] methods of a
  7381  ** [virtual table module] call this interface
  7382  ** to declare the format (the names and datatypes of the columns) of
  7383  ** the virtual tables they implement.
  7384  */
  7385  SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  7386  
  7387  /*
  7388  ** CAPI3REF: Overload A Function For A Virtual Table
  7389  ** METHOD: sqlite3
  7390  **
  7391  ** ^(Virtual tables can provide alternative implementations of functions
  7392  ** using the [xFindFunction] method of the [virtual table module].  
  7393  ** But global versions of those functions
  7394  ** must exist in order to be overloaded.)^
  7395  **
  7396  ** ^(This API makes sure a global version of a function with a particular
  7397  ** name and number of parameters exists.  If no such function exists
  7398  ** before this API is called, a new function is created.)^  ^The implementation
  7399  ** of the new function always causes an exception to be thrown.  So
  7400  ** the new function is not good for anything by itself.  Its only
  7401  ** purpose is to be a placeholder function that can be overloaded
  7402  ** by a [virtual table].
  7403  */
  7404  SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  7405  
  7406  /*
  7407  ** The interface to the virtual-table mechanism defined above (back up
  7408  ** to a comment remarkably similar to this one) is currently considered
  7409  ** to be experimental.  The interface might change in incompatible ways.
  7410  ** If this is a problem for you, do not use the interface at this time.
  7411  **
  7412  ** When the virtual-table mechanism stabilizes, we will declare the
  7413  ** interface fixed, support it indefinitely, and remove this comment.
  7414  */
  7415  
  7416  /*
  7417  ** CAPI3REF: A Handle To An Open BLOB
  7418  ** KEYWORDS: {BLOB handle} {BLOB handles}
  7419  **
  7420  ** An instance of this object represents an open BLOB on which
  7421  ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  7422  ** ^Objects of this type are created by [sqlite3_blob_open()]
  7423  ** and destroyed by [sqlite3_blob_close()].
  7424  ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  7425  ** can be used to read or write small subsections of the BLOB.
  7426  ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  7427  */
  7428  typedef struct sqlite3_blob sqlite3_blob;
  7429  
  7430  /*
  7431  ** CAPI3REF: Open A BLOB For Incremental I/O
  7432  ** METHOD: sqlite3
  7433  ** CONSTRUCTOR: sqlite3_blob
  7434  **
  7435  ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  7436  ** in row iRow, column zColumn, table zTable in database zDb;
  7437  ** in other words, the same BLOB that would be selected by:
  7438  **
  7439  ** <pre>
  7440  **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  7441  ** </pre>)^
  7442  **
  7443  ** ^(Parameter zDb is not the filename that contains the database, but 
  7444  ** rather the symbolic name of the database. For attached databases, this is
  7445  ** the name that appears after the AS keyword in the [ATTACH] statement.
  7446  ** For the main database file, the database name is "main". For TEMP
  7447  ** tables, the database name is "temp".)^
  7448  **
  7449  ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  7450  ** and write access. ^If the flags parameter is zero, the BLOB is opened for
  7451  ** read-only access.
  7452  **
  7453  ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
  7454  ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
  7455  ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
  7456  ** the API is not misused, it is always safe to call [sqlite3_blob_close()] 
  7457  ** on *ppBlob after this function it returns.
  7458  **
  7459  ** This function fails with SQLITE_ERROR if any of the following are true:
  7460  ** <ul>
  7461  **   <li> ^(Database zDb does not exist)^, 
  7462  **   <li> ^(Table zTable does not exist within database zDb)^, 
  7463  **   <li> ^(Table zTable is a WITHOUT ROWID table)^, 
  7464  **   <li> ^(Column zColumn does not exist)^,
  7465  **   <li> ^(Row iRow is not present in the table)^,
  7466  **   <li> ^(The specified column of row iRow contains a value that is not
  7467  **         a TEXT or BLOB value)^,
  7468  **   <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE 
  7469  **         constraint and the blob is being opened for read/write access)^,
  7470  **   <li> ^([foreign key constraints | Foreign key constraints] are enabled, 
  7471  **         column zColumn is part of a [child key] definition and the blob is
  7472  **         being opened for read/write access)^.
  7473  ** </ul>
  7474  **
  7475  ** ^Unless it returns SQLITE_MISUSE, this function sets the 
  7476  ** [database connection] error code and message accessible via 
  7477  ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. 
  7478  **
  7479  ** A BLOB referenced by sqlite3_blob_open() may be read using the
  7480  ** [sqlite3_blob_read()] interface and modified by using
  7481  ** [sqlite3_blob_write()].  The [BLOB handle] can be moved to a
  7482  ** different row of the same table using the [sqlite3_blob_reopen()]
  7483  ** interface.  However, the column, table, or database of a [BLOB handle]
  7484  ** cannot be changed after the [BLOB handle] is opened.
  7485  **
  7486  ** ^(If the row that a BLOB handle points to is modified by an
  7487  ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  7488  ** then the BLOB handle is marked as "expired".
  7489  ** This is true if any column of the row is changed, even a column
  7490  ** other than the one the BLOB handle is open on.)^
  7491  ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  7492  ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  7493  ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  7494  ** rolled back by the expiration of the BLOB.  Such changes will eventually
  7495  ** commit if the transaction continues to completion.)^
  7496  **
  7497  ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  7498  ** the opened blob.  ^The size of a blob may not be changed by this
  7499  ** interface.  Use the [UPDATE] SQL command to change the size of a
  7500  ** blob.
  7501  **
  7502  ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  7503  ** and the built-in [zeroblob] SQL function may be used to create a 
  7504  ** zero-filled blob to read or write using the incremental-blob interface.
  7505  **
  7506  ** To avoid a resource leak, every open [BLOB handle] should eventually
  7507  ** be released by a call to [sqlite3_blob_close()].
  7508  **
  7509  ** See also: [sqlite3_blob_close()],
  7510  ** [sqlite3_blob_reopen()], [sqlite3_blob_read()],
  7511  ** [sqlite3_blob_bytes()], [sqlite3_blob_write()].
  7512  */
  7513  SQLITE_API int sqlite3_blob_open(
  7514    sqlite3*,
  7515    const char *zDb,
  7516    const char *zTable,
  7517    const char *zColumn,
  7518    sqlite3_int64 iRow,
  7519    int flags,
  7520    sqlite3_blob **ppBlob
  7521  );
  7522  
  7523  /*
  7524  ** CAPI3REF: Move a BLOB Handle to a New Row
  7525  ** METHOD: sqlite3_blob
  7526  **
  7527  ** ^This function is used to move an existing [BLOB handle] so that it points
  7528  ** to a different row of the same database table. ^The new row is identified
  7529  ** by the rowid value passed as the second argument. Only the row can be
  7530  ** changed. ^The database, table and column on which the blob handle is open
  7531  ** remain the same. Moving an existing [BLOB handle] to a new row is
  7532  ** faster than closing the existing handle and opening a new one.
  7533  **
  7534  ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  7535  ** it must exist and there must be either a blob or text value stored in
  7536  ** the nominated column.)^ ^If the new row is not present in the table, or if
  7537  ** it does not contain a blob or text value, or if another error occurs, an
  7538  ** SQLite error code is returned and the blob handle is considered aborted.
  7539  ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  7540  ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  7541  ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  7542  ** always returns zero.
  7543  **
  7544  ** ^This function sets the database handle error code and message.
  7545  */
  7546  SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  7547  
  7548  /*
  7549  ** CAPI3REF: Close A BLOB Handle
  7550  ** DESTRUCTOR: sqlite3_blob
  7551  **
  7552  ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
  7553  ** unconditionally.  Even if this routine returns an error code, the 
  7554  ** handle is still closed.)^
  7555  **
  7556  ** ^If the blob handle being closed was opened for read-write access, and if
  7557  ** the database is in auto-commit mode and there are no other open read-write
  7558  ** blob handles or active write statements, the current transaction is
  7559  ** committed. ^If an error occurs while committing the transaction, an error
  7560  ** code is returned and the transaction rolled back.
  7561  **
  7562  ** Calling this function with an argument that is not a NULL pointer or an
  7563  ** open blob handle results in undefined behaviour. ^Calling this routine 
  7564  ** with a null pointer (such as would be returned by a failed call to 
  7565  ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
  7566  ** is passed a valid open blob handle, the values returned by the 
  7567  ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
  7568  */
  7569  SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  7570  
  7571  /*
  7572  ** CAPI3REF: Return The Size Of An Open BLOB
  7573  ** METHOD: sqlite3_blob
  7574  **
  7575  ** ^Returns the size in bytes of the BLOB accessible via the 
  7576  ** successfully opened [BLOB handle] in its only argument.  ^The
  7577  ** incremental blob I/O routines can only read or overwriting existing
  7578  ** blob content; they cannot change the size of a blob.
  7579  **
  7580  ** This routine only works on a [BLOB handle] which has been created
  7581  ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7582  ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
  7583  ** to this routine results in undefined and probably undesirable behavior.
  7584  */
  7585  SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  7586  
  7587  /*
  7588  ** CAPI3REF: Read Data From A BLOB Incrementally
  7589  ** METHOD: sqlite3_blob
  7590  **
  7591  ** ^(This function is used to read data from an open [BLOB handle] into a
  7592  ** caller-supplied buffer. N bytes of data are copied into buffer Z
  7593  ** from the open BLOB, starting at offset iOffset.)^
  7594  **
  7595  ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  7596  ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
  7597  ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  7598  ** ^The size of the blob (and hence the maximum value of N+iOffset)
  7599  ** can be determined using the [sqlite3_blob_bytes()] interface.
  7600  **
  7601  ** ^An attempt to read from an expired [BLOB handle] fails with an
  7602  ** error code of [SQLITE_ABORT].
  7603  **
  7604  ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  7605  ** Otherwise, an [error code] or an [extended error code] is returned.)^
  7606  **
  7607  ** This routine only works on a [BLOB handle] which has been created
  7608  ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7609  ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
  7610  ** to this routine results in undefined and probably undesirable behavior.
  7611  **
  7612  ** See also: [sqlite3_blob_write()].
  7613  */
  7614  SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  7615  
  7616  /*
  7617  ** CAPI3REF: Write Data Into A BLOB Incrementally
  7618  ** METHOD: sqlite3_blob
  7619  **
  7620  ** ^(This function is used to write data into an open [BLOB handle] from a
  7621  ** caller-supplied buffer. N bytes of data are copied from the buffer Z
  7622  ** into the open BLOB, starting at offset iOffset.)^
  7623  **
  7624  ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  7625  ** Otherwise, an  [error code] or an [extended error code] is returned.)^
  7626  ** ^Unless SQLITE_MISUSE is returned, this function sets the 
  7627  ** [database connection] error code and message accessible via 
  7628  ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. 
  7629  **
  7630  ** ^If the [BLOB handle] passed as the first argument was not opened for
  7631  ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  7632  ** this function returns [SQLITE_READONLY].
  7633  **
  7634  ** This function may only modify the contents of the BLOB; it is
  7635  ** not possible to increase the size of a BLOB using this API.
  7636  ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  7637  ** [SQLITE_ERROR] is returned and no data is written. The size of the 
  7638  ** BLOB (and hence the maximum value of N+iOffset) can be determined 
  7639  ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less 
  7640  ** than zero [SQLITE_ERROR] is returned and no data is written.
  7641  **
  7642  ** ^An attempt to write to an expired [BLOB handle] fails with an
  7643  ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
  7644  ** before the [BLOB handle] expired are not rolled back by the
  7645  ** expiration of the handle, though of course those changes might
  7646  ** have been overwritten by the statement that expired the BLOB handle
  7647  ** or by other independent statements.
  7648  **
  7649  ** This routine only works on a [BLOB handle] which has been created
  7650  ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7651  ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
  7652  ** to this routine results in undefined and probably undesirable behavior.
  7653  **
  7654  ** See also: [sqlite3_blob_read()].
  7655  */
  7656  SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  7657  
  7658  /*
  7659  ** CAPI3REF: Virtual File System Objects
  7660  **
  7661  ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  7662  ** that SQLite uses to interact
  7663  ** with the underlying operating system.  Most SQLite builds come with a
  7664  ** single default VFS that is appropriate for the host computer.
  7665  ** New VFSes can be registered and existing VFSes can be unregistered.
  7666  ** The following interfaces are provided.
  7667  **
  7668  ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  7669  ** ^Names are case sensitive.
  7670  ** ^Names are zero-terminated UTF-8 strings.
  7671  ** ^If there is no match, a NULL pointer is returned.
  7672  ** ^If zVfsName is NULL then the default VFS is returned.
  7673  **
  7674  ** ^New VFSes are registered with sqlite3_vfs_register().
  7675  ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  7676  ** ^The same VFS can be registered multiple times without injury.
  7677  ** ^To make an existing VFS into the default VFS, register it again
  7678  ** with the makeDflt flag set.  If two different VFSes with the
  7679  ** same name are registered, the behavior is undefined.  If a
  7680  ** VFS is registered with a name that is NULL or an empty string,
  7681  ** then the behavior is undefined.
  7682  **
  7683  ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  7684  ** ^(If the default VFS is unregistered, another VFS is chosen as
  7685  ** the default.  The choice for the new VFS is arbitrary.)^
  7686  */
  7687  SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  7688  SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  7689  SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  7690  
  7691  /*
  7692  ** CAPI3REF: Mutexes
  7693  **
  7694  ** The SQLite core uses these routines for thread
  7695  ** synchronization. Though they are intended for internal
  7696  ** use by SQLite, code that links against SQLite is
  7697  ** permitted to use any of these routines.
  7698  **
  7699  ** The SQLite source code contains multiple implementations
  7700  ** of these mutex routines.  An appropriate implementation
  7701  ** is selected automatically at compile-time.  The following
  7702  ** implementations are available in the SQLite core:
  7703  **
  7704  ** <ul>
  7705  ** <li>   SQLITE_MUTEX_PTHREADS
  7706  ** <li>   SQLITE_MUTEX_W32
  7707  ** <li>   SQLITE_MUTEX_NOOP
  7708  ** </ul>
  7709  **
  7710  ** The SQLITE_MUTEX_NOOP implementation is a set of routines
  7711  ** that does no real locking and is appropriate for use in
  7712  ** a single-threaded application.  The SQLITE_MUTEX_PTHREADS and
  7713  ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  7714  ** and Windows.
  7715  **
  7716  ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  7717  ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  7718  ** implementation is included with the library. In this case the
  7719  ** application must supply a custom mutex implementation using the
  7720  ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  7721  ** before calling sqlite3_initialize() or any other public sqlite3_
  7722  ** function that calls sqlite3_initialize().
  7723  **
  7724  ** ^The sqlite3_mutex_alloc() routine allocates a new
  7725  ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
  7726  ** routine returns NULL if it is unable to allocate the requested
  7727  ** mutex.  The argument to sqlite3_mutex_alloc() must one of these
  7728  ** integer constants:
  7729  **
  7730  ** <ul>
  7731  ** <li>  SQLITE_MUTEX_FAST
  7732  ** <li>  SQLITE_MUTEX_RECURSIVE
  7733  ** <li>  SQLITE_MUTEX_STATIC_MASTER
  7734  ** <li>  SQLITE_MUTEX_STATIC_MEM
  7735  ** <li>  SQLITE_MUTEX_STATIC_OPEN
  7736  ** <li>  SQLITE_MUTEX_STATIC_PRNG
  7737  ** <li>  SQLITE_MUTEX_STATIC_LRU
  7738  ** <li>  SQLITE_MUTEX_STATIC_PMEM
  7739  ** <li>  SQLITE_MUTEX_STATIC_APP1
  7740  ** <li>  SQLITE_MUTEX_STATIC_APP2
  7741  ** <li>  SQLITE_MUTEX_STATIC_APP3
  7742  ** <li>  SQLITE_MUTEX_STATIC_VFS1
  7743  ** <li>  SQLITE_MUTEX_STATIC_VFS2
  7744  ** <li>  SQLITE_MUTEX_STATIC_VFS3
  7745  ** </ul>
  7746  **
  7747  ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  7748  ** cause sqlite3_mutex_alloc() to create
  7749  ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  7750  ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  7751  ** The mutex implementation does not need to make a distinction
  7752  ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  7753  ** not want to.  SQLite will only request a recursive mutex in
  7754  ** cases where it really needs one.  If a faster non-recursive mutex
  7755  ** implementation is available on the host platform, the mutex subsystem
  7756  ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  7757  **
  7758  ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  7759  ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  7760  ** a pointer to a static preexisting mutex.  ^Nine static mutexes are
  7761  ** used by the current version of SQLite.  Future versions of SQLite
  7762  ** may add additional static mutexes.  Static mutexes are for internal
  7763  ** use by SQLite only.  Applications that use SQLite mutexes should
  7764  ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  7765  ** SQLITE_MUTEX_RECURSIVE.
  7766  **
  7767  ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  7768  ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  7769  ** returns a different mutex on every call.  ^For the static
  7770  ** mutex types, the same mutex is returned on every call that has
  7771  ** the same type number.
  7772  **
  7773  ** ^The sqlite3_mutex_free() routine deallocates a previously
  7774  ** allocated dynamic mutex.  Attempting to deallocate a static
  7775  ** mutex results in undefined behavior.
  7776  **
  7777  ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  7778  ** to enter a mutex.  ^If another thread is already within the mutex,
  7779  ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  7780  ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  7781  ** upon successful entry.  ^(Mutexes created using
  7782  ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  7783  ** In such cases, the
  7784  ** mutex must be exited an equal number of times before another thread
  7785  ** can enter.)^  If the same thread tries to enter any mutex other
  7786  ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
  7787  **
  7788  ** ^(Some systems (for example, Windows 95) do not support the operation
  7789  ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
  7790  ** will always return SQLITE_BUSY. The SQLite core only ever uses
  7791  ** sqlite3_mutex_try() as an optimization so this is acceptable 
  7792  ** behavior.)^
  7793  **
  7794  ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  7795  ** previously entered by the same thread.   The behavior
  7796  ** is undefined if the mutex is not currently entered by the
  7797  ** calling thread or is not currently allocated.
  7798  **
  7799  ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  7800  ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  7801  ** behave as no-ops.
  7802  **
  7803  ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  7804  */
  7805  SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  7806  SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  7807  SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  7808  SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  7809  SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  7810  
  7811  /*
  7812  ** CAPI3REF: Mutex Methods Object
  7813  **
  7814  ** An instance of this structure defines the low-level routines
  7815  ** used to allocate and use mutexes.
  7816  **
  7817  ** Usually, the default mutex implementations provided by SQLite are
  7818  ** sufficient, however the application has the option of substituting a custom
  7819  ** implementation for specialized deployments or systems for which SQLite
  7820  ** does not provide a suitable implementation. In this case, the application
  7821  ** creates and populates an instance of this structure to pass
  7822  ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  7823  ** Additionally, an instance of this structure can be used as an
  7824  ** output variable when querying the system for the current mutex
  7825  ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  7826  **
  7827  ** ^The xMutexInit method defined by this structure is invoked as
  7828  ** part of system initialization by the sqlite3_initialize() function.
  7829  ** ^The xMutexInit routine is called by SQLite exactly once for each
  7830  ** effective call to [sqlite3_initialize()].
  7831  **
  7832  ** ^The xMutexEnd method defined by this structure is invoked as
  7833  ** part of system shutdown by the sqlite3_shutdown() function. The
  7834  ** implementation of this method is expected to release all outstanding
  7835  ** resources obtained by the mutex methods implementation, especially
  7836  ** those obtained by the xMutexInit method.  ^The xMutexEnd()
  7837  ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  7838  **
  7839  ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  7840  ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  7841  ** xMutexNotheld) implement the following interfaces (respectively):
  7842  **
  7843  ** <ul>
  7844  **   <li>  [sqlite3_mutex_alloc()] </li>
  7845  **   <li>  [sqlite3_mutex_free()] </li>
  7846  **   <li>  [sqlite3_mutex_enter()] </li>
  7847  **   <li>  [sqlite3_mutex_try()] </li>
  7848  **   <li>  [sqlite3_mutex_leave()] </li>
  7849  **   <li>  [sqlite3_mutex_held()] </li>
  7850  **   <li>  [sqlite3_mutex_notheld()] </li>
  7851  ** </ul>)^
  7852  **
  7853  ** The only difference is that the public sqlite3_XXX functions enumerated
  7854  ** above silently ignore any invocations that pass a NULL pointer instead
  7855  ** of a valid mutex handle. The implementations of the methods defined
  7856  ** by this structure are not required to handle this case, the results
  7857  ** of passing a NULL pointer instead of a valid mutex handle are undefined
  7858  ** (i.e. it is acceptable to provide an implementation that segfaults if
  7859  ** it is passed a NULL pointer).
  7860  **
  7861  ** The xMutexInit() method must be threadsafe.  It must be harmless to
  7862  ** invoke xMutexInit() multiple times within the same process and without
  7863  ** intervening calls to xMutexEnd().  Second and subsequent calls to
  7864  ** xMutexInit() must be no-ops.
  7865  **
  7866  ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  7867  ** and its associates).  Similarly, xMutexAlloc() must not use SQLite memory
  7868  ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
  7869  ** memory allocation for a fast or recursive mutex.
  7870  **
  7871  ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  7872  ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  7873  ** If xMutexInit fails in any way, it is expected to clean up after itself
  7874  ** prior to returning.
  7875  */
  7876  typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  7877  struct sqlite3_mutex_methods {
  7878    int (*xMutexInit)(void);
  7879    int (*xMutexEnd)(void);
  7880    sqlite3_mutex *(*xMutexAlloc)(int);
  7881    void (*xMutexFree)(sqlite3_mutex *);
  7882    void (*xMutexEnter)(sqlite3_mutex *);
  7883    int (*xMutexTry)(sqlite3_mutex *);
  7884    void (*xMutexLeave)(sqlite3_mutex *);
  7885    int (*xMutexHeld)(sqlite3_mutex *);
  7886    int (*xMutexNotheld)(sqlite3_mutex *);
  7887  };
  7888  
  7889  /*
  7890  ** CAPI3REF: Mutex Verification Routines
  7891  **
  7892  ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  7893  ** are intended for use inside assert() statements.  The SQLite core
  7894  ** never uses these routines except inside an assert() and applications
  7895  ** are advised to follow the lead of the core.  The SQLite core only
  7896  ** provides implementations for these routines when it is compiled
  7897  ** with the SQLITE_DEBUG flag.  External mutex implementations
  7898  ** are only required to provide these routines if SQLITE_DEBUG is
  7899  ** defined and if NDEBUG is not defined.
  7900  **
  7901  ** These routines should return true if the mutex in their argument
  7902  ** is held or not held, respectively, by the calling thread.
  7903  **
  7904  ** The implementation is not required to provide versions of these
  7905  ** routines that actually work. If the implementation does not provide working
  7906  ** versions of these routines, it should at least provide stubs that always
  7907  ** return true so that one does not get spurious assertion failures.
  7908  **
  7909  ** If the argument to sqlite3_mutex_held() is a NULL pointer then
  7910  ** the routine should return 1.   This seems counter-intuitive since
  7911  ** clearly the mutex cannot be held if it does not exist.  But
  7912  ** the reason the mutex does not exist is because the build is not
  7913  ** using mutexes.  And we do not want the assert() containing the
  7914  ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  7915  ** the appropriate thing to do.  The sqlite3_mutex_notheld()
  7916  ** interface should also return 1 when given a NULL pointer.
  7917  */
  7918  #ifndef NDEBUG
  7919  SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  7920  SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  7921  #endif
  7922  
  7923  /*
  7924  ** CAPI3REF: Mutex Types
  7925  **
  7926  ** The [sqlite3_mutex_alloc()] interface takes a single argument
  7927  ** which is one of these integer constants.
  7928  **
  7929  ** The set of static mutexes may change from one SQLite release to the
  7930  ** next.  Applications that override the built-in mutex logic must be
  7931  ** prepared to accommodate additional static mutexes.
  7932  */
  7933  #define SQLITE_MUTEX_FAST             0
  7934  #define SQLITE_MUTEX_RECURSIVE        1
  7935  #define SQLITE_MUTEX_STATIC_MASTER    2
  7936  #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
  7937  #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
  7938  #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
  7939  #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_randomness() */
  7940  #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
  7941  #define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
  7942  #define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
  7943  #define SQLITE_MUTEX_STATIC_APP1      8  /* For use by application */
  7944  #define SQLITE_MUTEX_STATIC_APP2      9  /* For use by application */
  7945  #define SQLITE_MUTEX_STATIC_APP3     10  /* For use by application */
  7946  #define SQLITE_MUTEX_STATIC_VFS1     11  /* For use by built-in VFS */
  7947  #define SQLITE_MUTEX_STATIC_VFS2     12  /* For use by extension VFS */
  7948  #define SQLITE_MUTEX_STATIC_VFS3     13  /* For use by application VFS */
  7949  
  7950  /*
  7951  ** CAPI3REF: Retrieve the mutex for a database connection
  7952  ** METHOD: sqlite3
  7953  **
  7954  ** ^This interface returns a pointer the [sqlite3_mutex] object that 
  7955  ** serializes access to the [database connection] given in the argument
  7956  ** when the [threading mode] is Serialized.
  7957  ** ^If the [threading mode] is Single-thread or Multi-thread then this
  7958  ** routine returns a NULL pointer.
  7959  */
  7960  SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  7961  
  7962  /*
  7963  ** CAPI3REF: Low-Level Control Of Database Files
  7964  ** METHOD: sqlite3
  7965  **
  7966  ** ^The [sqlite3_file_control()] interface makes a direct call to the
  7967  ** xFileControl method for the [sqlite3_io_methods] object associated
  7968  ** with a particular database identified by the second argument. ^The
  7969  ** name of the database is "main" for the main database or "temp" for the
  7970  ** TEMP database, or the name that appears after the AS keyword for
  7971  ** databases that are added using the [ATTACH] SQL command.
  7972  ** ^A NULL pointer can be used in place of "main" to refer to the
  7973  ** main database file.
  7974  ** ^The third and fourth parameters to this routine
  7975  ** are passed directly through to the second and third parameters of
  7976  ** the xFileControl method.  ^The return value of the xFileControl
  7977  ** method becomes the return value of this routine.
  7978  **
  7979  ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
  7980  ** a pointer to the underlying [sqlite3_file] object to be written into
  7981  ** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
  7982  ** case is a short-circuit path which does not actually invoke the
  7983  ** underlying sqlite3_io_methods.xFileControl method.
  7984  **
  7985  ** ^If the second parameter (zDbName) does not match the name of any
  7986  ** open database file, then SQLITE_ERROR is returned.  ^This error
  7987  ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  7988  ** or [sqlite3_errmsg()].  The underlying xFileControl method might
  7989  ** also return SQLITE_ERROR.  There is no way to distinguish between
  7990  ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  7991  ** xFileControl method.
  7992  **
  7993  ** See also: [SQLITE_FCNTL_LOCKSTATE]
  7994  */
  7995  SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  7996  
  7997  /*
  7998  ** CAPI3REF: Testing Interface
  7999  **
  8000  ** ^The sqlite3_test_control() interface is used to read out internal
  8001  ** state of SQLite and to inject faults into SQLite for testing
  8002  ** purposes.  ^The first parameter is an operation code that determines
  8003  ** the number, meaning, and operation of all subsequent parameters.
  8004  **
  8005  ** This interface is not for use by applications.  It exists solely
  8006  ** for verifying the correct operation of the SQLite library.  Depending
  8007  ** on how the SQLite library is compiled, this interface might not exist.
  8008  **
  8009  ** The details of the operation codes, their meanings, the parameters
  8010  ** they take, and what they do are all subject to change without notice.
  8011  ** Unlike most of the SQLite API, this function is not guaranteed to
  8012  ** operate consistently from one release to the next.
  8013  */
  8014  SQLITE_API int sqlite3_test_control(int op, ...);
  8015  
  8016  /*
  8017  ** CAPI3REF: Testing Interface Operation Codes
  8018  **
  8019  ** These constants are the valid operation code parameters used
  8020  ** as the first argument to [sqlite3_test_control()].
  8021  **
  8022  ** These parameters and their meanings are subject to change
  8023  ** without notice.  These values are for testing purposes only.
  8024  ** Applications should not use any of these parameters or the
  8025  ** [sqlite3_test_control()] interface.
  8026  */
  8027  #define SQLITE_TESTCTRL_FIRST                    5
  8028  #define SQLITE_TESTCTRL_PRNG_SAVE                5
  8029  #define SQLITE_TESTCTRL_PRNG_RESTORE             6
  8030  #define SQLITE_TESTCTRL_PRNG_RESET               7
  8031  #define SQLITE_TESTCTRL_BITVEC_TEST              8
  8032  #define SQLITE_TESTCTRL_FAULT_INSTALL            9
  8033  #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
  8034  #define SQLITE_TESTCTRL_PENDING_BYTE            11
  8035  #define SQLITE_TESTCTRL_ASSERT                  12
  8036  #define SQLITE_TESTCTRL_ALWAYS                  13
  8037  #define SQLITE_TESTCTRL_RESERVE                 14
  8038  #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
  8039  #define SQLITE_TESTCTRL_ISKEYWORD               16
  8040  #define SQLITE_TESTCTRL_SCRATCHMALLOC           17  /* NOT USED */
  8041  #define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
  8042  #define SQLITE_TESTCTRL_EXPLAIN_STMT            19  /* NOT USED */
  8043  #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD    19
  8044  #define SQLITE_TESTCTRL_NEVER_CORRUPT           20
  8045  #define SQLITE_TESTCTRL_VDBE_COVERAGE           21
  8046  #define SQLITE_TESTCTRL_BYTEORDER               22
  8047  #define SQLITE_TESTCTRL_ISINIT                  23
  8048  #define SQLITE_TESTCTRL_SORTER_MMAP             24
  8049  #define SQLITE_TESTCTRL_IMPOSTER                25
  8050  #define SQLITE_TESTCTRL_LAST                    25
  8051  
  8052  /*
  8053  ** CAPI3REF: SQLite Runtime Status
  8054  **
  8055  ** ^These interfaces are used to retrieve runtime status information
  8056  ** about the performance of SQLite, and optionally to reset various
  8057  ** highwater marks.  ^The first argument is an integer code for
  8058  ** the specific parameter to measure.  ^(Recognized integer codes
  8059  ** are of the form [status parameters | SQLITE_STATUS_...].)^
  8060  ** ^The current value of the parameter is returned into *pCurrent.
  8061  ** ^The highest recorded value is returned in *pHighwater.  ^If the
  8062  ** resetFlag is true, then the highest record value is reset after
  8063  ** *pHighwater is written.  ^(Some parameters do not record the highest
  8064  ** value.  For those parameters
  8065  ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  8066  ** ^(Other parameters record only the highwater mark and not the current
  8067  ** value.  For these latter parameters nothing is written into *pCurrent.)^
  8068  **
  8069  ** ^The sqlite3_status() and sqlite3_status64() routines return
  8070  ** SQLITE_OK on success and a non-zero [error code] on failure.
  8071  **
  8072  ** If either the current value or the highwater mark is too large to
  8073  ** be represented by a 32-bit integer, then the values returned by
  8074  ** sqlite3_status() are undefined.
  8075  **
  8076  ** See also: [sqlite3_db_status()]
  8077  */
  8078  SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  8079  SQLITE_API int sqlite3_status64(
  8080    int op,
  8081    sqlite3_int64 *pCurrent,
  8082    sqlite3_int64 *pHighwater,
  8083    int resetFlag
  8084  );
  8085  
  8086  
  8087  /*
  8088  ** CAPI3REF: Status Parameters
  8089  ** KEYWORDS: {status parameters}
  8090  **
  8091  ** These integer constants designate various run-time status parameters
  8092  ** that can be returned by [sqlite3_status()].
  8093  **
  8094  ** <dl>
  8095  ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  8096  ** <dd>This parameter is the current amount of memory checked out
  8097  ** using [sqlite3_malloc()], either directly or indirectly.  The
  8098  ** figure includes calls made to [sqlite3_malloc()] by the application
  8099  ** and internal memory usage by the SQLite library.  Auxiliary page-cache
  8100  ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  8101  ** this parameter.  The amount returned is the sum of the allocation
  8102  ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  8103  **
  8104  ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  8105  ** <dd>This parameter records the largest memory allocation request
  8106  ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  8107  ** internal equivalents).  Only the value returned in the
  8108  ** *pHighwater parameter to [sqlite3_status()] is of interest.  
  8109  ** The value written into the *pCurrent parameter is undefined.</dd>)^
  8110  **
  8111  ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  8112  ** <dd>This parameter records the number of separate memory allocations
  8113  ** currently checked out.</dd>)^
  8114  **
  8115  ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  8116  ** <dd>This parameter returns the number of pages used out of the
  8117  ** [pagecache memory allocator] that was configured using 
  8118  ** [SQLITE_CONFIG_PAGECACHE].  The
  8119  ** value returned is in pages, not in bytes.</dd>)^
  8120  **
  8121  ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] 
  8122  ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  8123  ** <dd>This parameter returns the number of bytes of page cache
  8124  ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  8125  ** buffer and where forced to overflow to [sqlite3_malloc()].  The
  8126  ** returned value includes allocations that overflowed because they
  8127  ** where too large (they were larger than the "sz" parameter to
  8128  ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  8129  ** no space was left in the page cache.</dd>)^
  8130  **
  8131  ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  8132  ** <dd>This parameter records the largest memory allocation request
  8133  ** handed to [pagecache memory allocator].  Only the value returned in the
  8134  ** *pHighwater parameter to [sqlite3_status()] is of interest.  
  8135  ** The value written into the *pCurrent parameter is undefined.</dd>)^
  8136  **
  8137  ** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt>
  8138  ** <dd>No longer used.</dd>
  8139  **
  8140  ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  8141  ** <dd>No longer used.</dd>
  8142  **
  8143  ** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  8144  ** <dd>No longer used.</dd>
  8145  **
  8146  ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  8147  ** <dd>The *pHighwater parameter records the deepest parser stack. 
  8148  ** The *pCurrent value is undefined.  The *pHighwater value is only
  8149  ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  8150  ** </dl>
  8151  **
  8152  ** New status parameters may be added from time to time.
  8153  */
  8154  #define SQLITE_STATUS_MEMORY_USED          0
  8155  #define SQLITE_STATUS_PAGECACHE_USED       1
  8156  #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
  8157  #define SQLITE_STATUS_SCRATCH_USED         3  /* NOT USED */
  8158  #define SQLITE_STATUS_SCRATCH_OVERFLOW     4  /* NOT USED */
  8159  #define SQLITE_STATUS_MALLOC_SIZE          5
  8160  #define SQLITE_STATUS_PARSER_STACK         6
  8161  #define SQLITE_STATUS_PAGECACHE_SIZE       7
  8162  #define SQLITE_STATUS_SCRATCH_SIZE         8  /* NOT USED */
  8163  #define SQLITE_STATUS_MALLOC_COUNT         9
  8164  
  8165  /*
  8166  ** CAPI3REF: Database Connection Status
  8167  ** METHOD: sqlite3
  8168  **
  8169  ** ^This interface is used to retrieve runtime status information 
  8170  ** about a single [database connection].  ^The first argument is the
  8171  ** database connection object to be interrogated.  ^The second argument
  8172  ** is an integer constant, taken from the set of
  8173  ** [SQLITE_DBSTATUS options], that
  8174  ** determines the parameter to interrogate.  The set of 
  8175  ** [SQLITE_DBSTATUS options] is likely
  8176  ** to grow in future releases of SQLite.
  8177  **
  8178  ** ^The current value of the requested parameter is written into *pCur
  8179  ** and the highest instantaneous value is written into *pHiwtr.  ^If
  8180  ** the resetFlg is true, then the highest instantaneous value is
  8181  ** reset back down to the current value.
  8182  **
  8183  ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  8184  ** non-zero [error code] on failure.
  8185  **
  8186  ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  8187  */
  8188  SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  8189  
  8190  /*
  8191  ** CAPI3REF: Status Parameters for database connections
  8192  ** KEYWORDS: {SQLITE_DBSTATUS options}
  8193  **
  8194  ** These constants are the available integer "verbs" that can be passed as
  8195  ** the second argument to the [sqlite3_db_status()] interface.
  8196  **
  8197  ** New verbs may be added in future releases of SQLite. Existing verbs
  8198  ** might be discontinued. Applications should check the return code from
  8199  ** [sqlite3_db_status()] to make sure that the call worked.
  8200  ** The [sqlite3_db_status()] interface will return a non-zero error code
  8201  ** if a discontinued or unsupported verb is invoked.
  8202  **
  8203  ** <dl>
  8204  ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  8205  ** <dd>This parameter returns the number of lookaside memory slots currently
  8206  ** checked out.</dd>)^
  8207  **
  8208  ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  8209  ** <dd>This parameter returns the number malloc attempts that were 
  8210  ** satisfied using lookaside memory. Only the high-water value is meaningful;
  8211  ** the current value is always zero.)^
  8212  **
  8213  ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  8214  ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  8215  ** <dd>This parameter returns the number malloc attempts that might have
  8216  ** been satisfied using lookaside memory but failed due to the amount of
  8217  ** memory requested being larger than the lookaside slot size.
  8218  ** Only the high-water value is meaningful;
  8219  ** the current value is always zero.)^
  8220  **
  8221  ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  8222  ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  8223  ** <dd>This parameter returns the number malloc attempts that might have
  8224  ** been satisfied using lookaside memory but failed due to all lookaside
  8225  ** memory already being in use.
  8226  ** Only the high-water value is meaningful;
  8227  ** the current value is always zero.)^
  8228  **
  8229  ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  8230  ** <dd>This parameter returns the approximate number of bytes of heap
  8231  ** memory used by all pager caches associated with the database connection.)^
  8232  ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  8233  **
  8234  ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]] 
  8235  ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
  8236  ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
  8237  ** pager cache is shared between two or more connections the bytes of heap
  8238  ** memory used by that pager cache is divided evenly between the attached
  8239  ** connections.)^  In other words, if none of the pager caches associated
  8240  ** with the database connection are shared, this request returns the same
  8241  ** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
  8242  ** shared, the value returned by this call will be smaller than that returned
  8243  ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
  8244  ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
  8245  **
  8246  ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  8247  ** <dd>This parameter returns the approximate number of bytes of heap
  8248  ** memory used to store the schema for all databases associated
  8249  ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
  8250  ** ^The full amount of memory used by the schemas is reported, even if the
  8251  ** schema memory is shared with other database connections due to
  8252  ** [shared cache mode] being enabled.
  8253  ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  8254  **
  8255  ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  8256  ** <dd>This parameter returns the approximate number of bytes of heap
  8257  ** and lookaside memory used by all prepared statements associated with
  8258  ** the database connection.)^
  8259  ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  8260  ** </dd>
  8261  **
  8262  ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  8263  ** <dd>This parameter returns the number of pager cache hits that have
  8264  ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT 
  8265  ** is always 0.
  8266  ** </dd>
  8267  **
  8268  ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  8269  ** <dd>This parameter returns the number of pager cache misses that have
  8270  ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS 
  8271  ** is always 0.
  8272  ** </dd>
  8273  **
  8274  ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  8275  ** <dd>This parameter returns the number of dirty cache entries that have
  8276  ** been written to disk. Specifically, the number of pages written to the
  8277  ** wal file in wal mode databases, or the number of pages written to the
  8278  ** database file in rollback mode databases. Any pages written as part of
  8279  ** transaction rollback or database recovery operations are not included.
  8280  ** If an IO or other error occurs while writing a page to disk, the effect
  8281  ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  8282  ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  8283  ** </dd>
  8284  **
  8285  ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  8286  ** <dd>This parameter returns zero for the current value if and only if
  8287  ** all foreign key constraints (deferred or immediate) have been
  8288  ** resolved.)^  ^The highwater mark is always 0.
  8289  ** </dd>
  8290  ** </dl>
  8291  */
  8292  #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
  8293  #define SQLITE_DBSTATUS_CACHE_USED           1
  8294  #define SQLITE_DBSTATUS_SCHEMA_USED          2
  8295  #define SQLITE_DBSTATUS_STMT_USED            3
  8296  #define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
  8297  #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
  8298  #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
  8299  #define SQLITE_DBSTATUS_CACHE_HIT            7
  8300  #define SQLITE_DBSTATUS_CACHE_MISS           8
  8301  #define SQLITE_DBSTATUS_CACHE_WRITE          9
  8302  #define SQLITE_DBSTATUS_DEFERRED_FKS        10
  8303  #define SQLITE_DBSTATUS_CACHE_USED_SHARED   11
  8304  #define SQLITE_DBSTATUS_MAX                 11   /* Largest defined DBSTATUS */
  8305  
  8306  
  8307  /*
  8308  ** CAPI3REF: Prepared Statement Status
  8309  ** METHOD: sqlite3_stmt
  8310  **
  8311  ** ^(Each prepared statement maintains various
  8312  ** [SQLITE_STMTSTATUS counters] that measure the number
  8313  ** of times it has performed specific operations.)^  These counters can
  8314  ** be used to monitor the performance characteristics of the prepared
  8315  ** statements.  For example, if the number of table steps greatly exceeds
  8316  ** the number of table searches or result rows, that would tend to indicate
  8317  ** that the prepared statement is using a full table scan rather than
  8318  ** an index.  
  8319  **
  8320  ** ^(This interface is used to retrieve and reset counter values from
  8321  ** a [prepared statement].  The first argument is the prepared statement
  8322  ** object to be interrogated.  The second argument
  8323  ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  8324  ** to be interrogated.)^
  8325  ** ^The current value of the requested counter is returned.
  8326  ** ^If the resetFlg is true, then the counter is reset to zero after this
  8327  ** interface call returns.
  8328  **
  8329  ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  8330  */
  8331  SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  8332  
  8333  /*
  8334  ** CAPI3REF: Status Parameters for prepared statements
  8335  ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  8336  **
  8337  ** These preprocessor macros define integer codes that name counter
  8338  ** values associated with the [sqlite3_stmt_status()] interface.
  8339  ** The meanings of the various counters are as follows:
  8340  **
  8341  ** <dl>
  8342  ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  8343  ** <dd>^This is the number of times that SQLite has stepped forward in
  8344  ** a table as part of a full table scan.  Large numbers for this counter
  8345  ** may indicate opportunities for performance improvement through 
  8346  ** careful use of indices.</dd>
  8347  **
  8348  ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  8349  ** <dd>^This is the number of sort operations that have occurred.
  8350  ** A non-zero value in this counter may indicate an opportunity to
  8351  ** improvement performance through careful use of indices.</dd>
  8352  **
  8353  ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  8354  ** <dd>^This is the number of rows inserted into transient indices that
  8355  ** were created automatically in order to help joins run faster.
  8356  ** A non-zero value in this counter may indicate an opportunity to
  8357  ** improvement performance by adding permanent indices that do not
  8358  ** need to be reinitialized each time the statement is run.</dd>
  8359  **
  8360  ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  8361  ** <dd>^This is the number of virtual machine operations executed
  8362  ** by the prepared statement if that number is less than or equal
  8363  ** to 2147483647.  The number of virtual machine operations can be 
  8364  ** used as a proxy for the total work done by the prepared statement.
  8365  ** If the number of virtual machine operations exceeds 2147483647
  8366  ** then the value returned by this statement status code is undefined.
  8367  **
  8368  ** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>
  8369  ** <dd>^This is the number of times that the prepare statement has been
  8370  ** automatically regenerated due to schema changes or change to 
  8371  ** [bound parameters] that might affect the query plan.
  8372  **
  8373  ** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>
  8374  ** <dd>^This is the number of times that the prepared statement has
  8375  ** been run.  A single "run" for the purposes of this counter is one
  8376  ** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].
  8377  ** The counter is incremented on the first [sqlite3_step()] call of each
  8378  ** cycle.
  8379  **
  8380  ** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>
  8381  ** <dd>^This is the approximate number of bytes of heap memory
  8382  ** used to store the prepared statement.  ^This value is not actually
  8383  ** a counter, and so the resetFlg parameter to sqlite3_stmt_status()
  8384  ** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.
  8385  ** </dd>
  8386  ** </dl>
  8387  */
  8388  #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
  8389  #define SQLITE_STMTSTATUS_SORT              2
  8390  #define SQLITE_STMTSTATUS_AUTOINDEX         3
  8391  #define SQLITE_STMTSTATUS_VM_STEP           4
  8392  #define SQLITE_STMTSTATUS_REPREPARE         5
  8393  #define SQLITE_STMTSTATUS_RUN               6
  8394  #define SQLITE_STMTSTATUS_MEMUSED           99
  8395  
  8396  /*
  8397  ** CAPI3REF: Custom Page Cache Object
  8398  **
  8399  ** The sqlite3_pcache type is opaque.  It is implemented by
  8400  ** the pluggable module.  The SQLite core has no knowledge of
  8401  ** its size or internal structure and never deals with the
  8402  ** sqlite3_pcache object except by holding and passing pointers
  8403  ** to the object.
  8404  **
  8405  ** See [sqlite3_pcache_methods2] for additional information.
  8406  */
  8407  typedef struct sqlite3_pcache sqlite3_pcache;
  8408  
  8409  /*
  8410  ** CAPI3REF: Custom Page Cache Object
  8411  **
  8412  ** The sqlite3_pcache_page object represents a single page in the
  8413  ** page cache.  The page cache will allocate instances of this
  8414  ** object.  Various methods of the page cache use pointers to instances
  8415  ** of this object as parameters or as their return value.
  8416  **
  8417  ** See [sqlite3_pcache_methods2] for additional information.
  8418  */
  8419  typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  8420  struct sqlite3_pcache_page {
  8421    void *pBuf;        /* The content of the page */
  8422    void *pExtra;      /* Extra information associated with the page */
  8423  };
  8424  
  8425  /*
  8426  ** CAPI3REF: Application Defined Page Cache.
  8427  ** KEYWORDS: {page cache}
  8428  **
  8429  ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  8430  ** register an alternative page cache implementation by passing in an 
  8431  ** instance of the sqlite3_pcache_methods2 structure.)^
  8432  ** In many applications, most of the heap memory allocated by 
  8433  ** SQLite is used for the page cache.
  8434  ** By implementing a 
  8435  ** custom page cache using this API, an application can better control
  8436  ** the amount of memory consumed by SQLite, the way in which 
  8437  ** that memory is allocated and released, and the policies used to 
  8438  ** determine exactly which parts of a database file are cached and for 
  8439  ** how long.
  8440  **
  8441  ** The alternative page cache mechanism is an
  8442  ** extreme measure that is only needed by the most demanding applications.
  8443  ** The built-in page cache is recommended for most uses.
  8444  **
  8445  ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  8446  ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
  8447  ** the application may discard the parameter after the call to
  8448  ** [sqlite3_config()] returns.)^
  8449  **
  8450  ** [[the xInit() page cache method]]
  8451  ** ^(The xInit() method is called once for each effective 
  8452  ** call to [sqlite3_initialize()])^
  8453  ** (usually only once during the lifetime of the process). ^(The xInit()
  8454  ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  8455  ** The intent of the xInit() method is to set up global data structures 
  8456  ** required by the custom page cache implementation. 
  8457  ** ^(If the xInit() method is NULL, then the 
  8458  ** built-in default page cache is used instead of the application defined
  8459  ** page cache.)^
  8460  **
  8461  ** [[the xShutdown() page cache method]]
  8462  ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  8463  ** It can be used to clean up 
  8464  ** any outstanding resources before process shutdown, if required.
  8465  ** ^The xShutdown() method may be NULL.
  8466  **
  8467  ** ^SQLite automatically serializes calls to the xInit method,
  8468  ** so the xInit method need not be threadsafe.  ^The
  8469  ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  8470  ** not need to be threadsafe either.  All other methods must be threadsafe
  8471  ** in multithreaded applications.
  8472  **
  8473  ** ^SQLite will never invoke xInit() more than once without an intervening
  8474  ** call to xShutdown().
  8475  **
  8476  ** [[the xCreate() page cache methods]]
  8477  ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  8478  ** SQLite will typically create one cache instance for each open database file,
  8479  ** though this is not guaranteed. ^The
  8480  ** first parameter, szPage, is the size in bytes of the pages that must
  8481  ** be allocated by the cache.  ^szPage will always a power of two.  ^The
  8482  ** second parameter szExtra is a number of bytes of extra storage 
  8483  ** associated with each page cache entry.  ^The szExtra parameter will
  8484  ** a number less than 250.  SQLite will use the
  8485  ** extra szExtra bytes on each page to store metadata about the underlying
  8486  ** database page on disk.  The value passed into szExtra depends
  8487  ** on the SQLite version, the target platform, and how SQLite was compiled.
  8488  ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  8489  ** created will be used to cache database pages of a file stored on disk, or
  8490  ** false if it is used for an in-memory database. The cache implementation
  8491  ** does not have to do anything special based with the value of bPurgeable;
  8492  ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
  8493  ** never invoke xUnpin() except to deliberately delete a page.
  8494  ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  8495  ** false will always have the "discard" flag set to true.  
  8496  ** ^Hence, a cache created with bPurgeable false will
  8497  ** never contain any unpinned pages.
  8498  **
  8499  ** [[the xCachesize() page cache method]]
  8500  ** ^(The xCachesize() method may be called at any time by SQLite to set the
  8501  ** suggested maximum cache-size (number of pages stored by) the cache
  8502  ** instance passed as the first argument. This is the value configured using
  8503  ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
  8504  ** parameter, the implementation is not required to do anything with this
  8505  ** value; it is advisory only.
  8506  **
  8507  ** [[the xPagecount() page cache methods]]
  8508  ** The xPagecount() method must return the number of pages currently
  8509  ** stored in the cache, both pinned and unpinned.
  8510  ** 
  8511  ** [[the xFetch() page cache methods]]
  8512  ** The xFetch() method locates a page in the cache and returns a pointer to 
  8513  ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  8514  ** The pBuf element of the returned sqlite3_pcache_page object will be a
  8515  ** pointer to a buffer of szPage bytes used to store the content of a 
  8516  ** single database page.  The pExtra element of sqlite3_pcache_page will be
  8517  ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  8518  ** for each entry in the page cache.
  8519  **
  8520  ** The page to be fetched is determined by the key. ^The minimum key value
  8521  ** is 1.  After it has been retrieved using xFetch, the page is considered
  8522  ** to be "pinned".
  8523  **
  8524  ** If the requested page is already in the page cache, then the page cache
  8525  ** implementation must return a pointer to the page buffer with its content
  8526  ** intact.  If the requested page is not already in the cache, then the
  8527  ** cache implementation should use the value of the createFlag
  8528  ** parameter to help it determined what action to take:
  8529  **
  8530  ** <table border=1 width=85% align=center>
  8531  ** <tr><th> createFlag <th> Behavior when page is not already in cache
  8532  ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
  8533  ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  8534  **                 Otherwise return NULL.
  8535  ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
  8536  **                 NULL if allocating a new page is effectively impossible.
  8537  ** </table>
  8538  **
  8539  ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
  8540  ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  8541  ** failed.)^  In between the to xFetch() calls, SQLite may
  8542  ** attempt to unpin one or more cache pages by spilling the content of
  8543  ** pinned pages to disk and synching the operating system disk cache.
  8544  **
  8545  ** [[the xUnpin() page cache method]]
  8546  ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  8547  ** as its second argument.  If the third parameter, discard, is non-zero,
  8548  ** then the page must be evicted from the cache.
  8549  ** ^If the discard parameter is
  8550  ** zero, then the page may be discarded or retained at the discretion of
  8551  ** page cache implementation. ^The page cache implementation
  8552  ** may choose to evict unpinned pages at any time.
  8553  **
  8554  ** The cache must not perform any reference counting. A single 
  8555  ** call to xUnpin() unpins the page regardless of the number of prior calls 
  8556  ** to xFetch().
  8557  **
  8558  ** [[the xRekey() page cache methods]]
  8559  ** The xRekey() method is used to change the key value associated with the
  8560  ** page passed as the second argument. If the cache
  8561  ** previously contains an entry associated with newKey, it must be
  8562  ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  8563  ** to be pinned.
  8564  **
  8565  ** When SQLite calls the xTruncate() method, the cache must discard all
  8566  ** existing cache entries with page numbers (keys) greater than or equal
  8567  ** to the value of the iLimit parameter passed to xTruncate(). If any
  8568  ** of these pages are pinned, they are implicitly unpinned, meaning that
  8569  ** they can be safely discarded.
  8570  **
  8571  ** [[the xDestroy() page cache method]]
  8572  ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  8573  ** All resources associated with the specified cache should be freed. ^After
  8574  ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  8575  ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  8576  ** functions.
  8577  **
  8578  ** [[the xShrink() page cache method]]
  8579  ** ^SQLite invokes the xShrink() method when it wants the page cache to
  8580  ** free up as much of heap memory as possible.  The page cache implementation
  8581  ** is not obligated to free any memory, but well-behaved implementations should
  8582  ** do their best.
  8583  */
  8584  typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  8585  struct sqlite3_pcache_methods2 {
  8586    int iVersion;
  8587    void *pArg;
  8588    int (*xInit)(void*);
  8589    void (*xShutdown)(void*);
  8590    sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  8591    void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  8592    int (*xPagecount)(sqlite3_pcache*);
  8593    sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  8594    void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  8595    void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, 
  8596        unsigned oldKey, unsigned newKey);
  8597    void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  8598    void (*xDestroy)(sqlite3_pcache*);
  8599    void (*xShrink)(sqlite3_pcache*);
  8600  };
  8601  
  8602  /*
  8603  ** This is the obsolete pcache_methods object that has now been replaced
  8604  ** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
  8605  ** retained in the header file for backwards compatibility only.
  8606  */
  8607  typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  8608  struct sqlite3_pcache_methods {
  8609    void *pArg;
  8610    int (*xInit)(void*);
  8611    void (*xShutdown)(void*);
  8612    sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  8613    void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  8614    int (*xPagecount)(sqlite3_pcache*);
  8615    void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  8616    void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  8617    void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  8618    void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  8619    void (*xDestroy)(sqlite3_pcache*);
  8620  };
  8621  
  8622  
  8623  /*
  8624  ** CAPI3REF: Online Backup Object
  8625  **
  8626  ** The sqlite3_backup object records state information about an ongoing
  8627  ** online backup operation.  ^The sqlite3_backup object is created by
  8628  ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  8629  ** [sqlite3_backup_finish()].
  8630  **
  8631  ** See Also: [Using the SQLite Online Backup API]
  8632  */
  8633  typedef struct sqlite3_backup sqlite3_backup;
  8634  
  8635  /*
  8636  ** CAPI3REF: Online Backup API.
  8637  **
  8638  ** The backup API copies the content of one database into another.
  8639  ** It is useful either for creating backups of databases or
  8640  ** for copying in-memory databases to or from persistent files. 
  8641  **
  8642  ** See Also: [Using the SQLite Online Backup API]
  8643  **
  8644  ** ^SQLite holds a write transaction open on the destination database file
  8645  ** for the duration of the backup operation.
  8646  ** ^The source database is read-locked only while it is being read;
  8647  ** it is not locked continuously for the entire backup operation.
  8648  ** ^Thus, the backup may be performed on a live source database without
  8649  ** preventing other database connections from
  8650  ** reading or writing to the source database while the backup is underway.
  8651  ** 
  8652  ** ^(To perform a backup operation: 
  8653  **   <ol>
  8654  **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
  8655  **         backup, 
  8656  **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
  8657  **         the data between the two databases, and finally
  8658  **     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
  8659  **         associated with the backup operation. 
  8660  **   </ol>)^
  8661  ** There should be exactly one call to sqlite3_backup_finish() for each
  8662  ** successful call to sqlite3_backup_init().
  8663  **
  8664  ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  8665  **
  8666  ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
  8667  ** [database connection] associated with the destination database 
  8668  ** and the database name, respectively.
  8669  ** ^The database name is "main" for the main database, "temp" for the
  8670  ** temporary database, or the name specified after the AS keyword in
  8671  ** an [ATTACH] statement for an attached database.
  8672  ** ^The S and M arguments passed to 
  8673  ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  8674  ** and database name of the source database, respectively.
  8675  ** ^The source and destination [database connections] (parameters S and D)
  8676  ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  8677  ** an error.
  8678  **
  8679  ** ^A call to sqlite3_backup_init() will fail, returning NULL, if 
  8680  ** there is already a read or read-write transaction open on the 
  8681  ** destination database.
  8682  **
  8683  ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  8684  ** returned and an error code and error message are stored in the
  8685  ** destination [database connection] D.
  8686  ** ^The error code and message for the failed call to sqlite3_backup_init()
  8687  ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  8688  ** [sqlite3_errmsg16()] functions.
  8689  ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  8690  ** [sqlite3_backup] object.
  8691  ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  8692  ** sqlite3_backup_finish() functions to perform the specified backup 
  8693  ** operation.
  8694  **
  8695  ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  8696  **
  8697  ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
  8698  ** the source and destination databases specified by [sqlite3_backup] object B.
  8699  ** ^If N is negative, all remaining source pages are copied. 
  8700  ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  8701  ** are still more pages to be copied, then the function returns [SQLITE_OK].
  8702  ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  8703  ** from source to destination, then it returns [SQLITE_DONE].
  8704  ** ^If an error occurs while running sqlite3_backup_step(B,N),
  8705  ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  8706  ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  8707  ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  8708  ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  8709  **
  8710  ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  8711  ** <ol>
  8712  ** <li> the destination database was opened read-only, or
  8713  ** <li> the destination database is using write-ahead-log journaling
  8714  ** and the destination and source page sizes differ, or
  8715  ** <li> the destination database is an in-memory database and the
  8716  ** destination and source page sizes differ.
  8717  ** </ol>)^
  8718  **
  8719  ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  8720  ** the [sqlite3_busy_handler | busy-handler function]
  8721  ** is invoked (if one is specified). ^If the 
  8722  ** busy-handler returns non-zero before the lock is available, then 
  8723  ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  8724  ** sqlite3_backup_step() can be retried later. ^If the source
  8725  ** [database connection]
  8726  ** is being used to write to the source database when sqlite3_backup_step()
  8727  ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  8728  ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  8729  ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  8730  ** [SQLITE_READONLY] is returned, then 
  8731  ** there is no point in retrying the call to sqlite3_backup_step(). These 
  8732  ** errors are considered fatal.)^  The application must accept 
  8733  ** that the backup operation has failed and pass the backup operation handle 
  8734  ** to the sqlite3_backup_finish() to release associated resources.
  8735  **
  8736  ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  8737  ** on the destination file. ^The exclusive lock is not released until either 
  8738  ** sqlite3_backup_finish() is called or the backup operation is complete 
  8739  ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
  8740  ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  8741  ** lasts for the duration of the sqlite3_backup_step() call.
  8742  ** ^Because the source database is not locked between calls to
  8743  ** sqlite3_backup_step(), the source database may be modified mid-way
  8744  ** through the backup process.  ^If the source database is modified by an
  8745  ** external process or via a database connection other than the one being
  8746  ** used by the backup operation, then the backup will be automatically
  8747  ** restarted by the next call to sqlite3_backup_step(). ^If the source 
  8748  ** database is modified by the using the same database connection as is used
  8749  ** by the backup operation, then the backup database is automatically
  8750  ** updated at the same time.
  8751  **
  8752  ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  8753  **
  8754  ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
  8755  ** application wishes to abandon the backup operation, the application
  8756  ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  8757  ** ^The sqlite3_backup_finish() interfaces releases all
  8758  ** resources associated with the [sqlite3_backup] object. 
  8759  ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  8760  ** active write-transaction on the destination database is rolled back.
  8761  ** The [sqlite3_backup] object is invalid
  8762  ** and may not be used following a call to sqlite3_backup_finish().
  8763  **
  8764  ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  8765  ** sqlite3_backup_step() errors occurred, regardless or whether or not
  8766  ** sqlite3_backup_step() completed.
  8767  ** ^If an out-of-memory condition or IO error occurred during any prior
  8768  ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  8769  ** sqlite3_backup_finish() returns the corresponding [error code].
  8770  **
  8771  ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  8772  ** is not a permanent error and does not affect the return value of
  8773  ** sqlite3_backup_finish().
  8774  **
  8775  ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
  8776  ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  8777  **
  8778  ** ^The sqlite3_backup_remaining() routine returns the number of pages still
  8779  ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
  8780  ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
  8781  ** in the source database at the conclusion of the most recent
  8782  ** sqlite3_backup_step().
  8783  ** ^(The values returned by these functions are only updated by
  8784  ** sqlite3_backup_step(). If the source database is modified in a way that
  8785  ** changes the size of the source database or the number of pages remaining,
  8786  ** those changes are not reflected in the output of sqlite3_backup_pagecount()
  8787  ** and sqlite3_backup_remaining() until after the next
  8788  ** sqlite3_backup_step().)^
  8789  **
  8790  ** <b>Concurrent Usage of Database Handles</b>
  8791  **
  8792  ** ^The source [database connection] may be used by the application for other
  8793  ** purposes while a backup operation is underway or being initialized.
  8794  ** ^If SQLite is compiled and configured to support threadsafe database
  8795  ** connections, then the source database connection may be used concurrently
  8796  ** from within other threads.
  8797  **
  8798  ** However, the application must guarantee that the destination 
  8799  ** [database connection] is not passed to any other API (by any thread) after 
  8800  ** sqlite3_backup_init() is called and before the corresponding call to
  8801  ** sqlite3_backup_finish().  SQLite does not currently check to see
  8802  ** if the application incorrectly accesses the destination [database connection]
  8803  ** and so no error code is reported, but the operations may malfunction
  8804  ** nevertheless.  Use of the destination database connection while a
  8805  ** backup is in progress might also also cause a mutex deadlock.
  8806  **
  8807  ** If running in [shared cache mode], the application must
  8808  ** guarantee that the shared cache used by the destination database
  8809  ** is not accessed while the backup is running. In practice this means
  8810  ** that the application must guarantee that the disk file being 
  8811  ** backed up to is not accessed by any connection within the process,
  8812  ** not just the specific connection that was passed to sqlite3_backup_init().
  8813  **
  8814  ** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
  8815  ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  8816  ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  8817  ** APIs are not strictly speaking threadsafe. If they are invoked at the
  8818  ** same time as another thread is invoking sqlite3_backup_step() it is
  8819  ** possible that they return invalid values.
  8820  */
  8821  SQLITE_API sqlite3_backup *sqlite3_backup_init(
  8822    sqlite3 *pDest,                        /* Destination database handle */
  8823    const char *zDestName,                 /* Destination database name */
  8824    sqlite3 *pSource,                      /* Source database handle */
  8825    const char *zSourceName                /* Source database name */
  8826  );
  8827  SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  8828  SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  8829  SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  8830  SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  8831  
  8832  /*
  8833  ** CAPI3REF: Unlock Notification
  8834  ** METHOD: sqlite3
  8835  **
  8836  ** ^When running in shared-cache mode, a database operation may fail with
  8837  ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  8838  ** individual tables within the shared-cache cannot be obtained. See
  8839  ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
  8840  ** ^This API may be used to register a callback that SQLite will invoke 
  8841  ** when the connection currently holding the required lock relinquishes it.
  8842  ** ^This API is only available if the library was compiled with the
  8843  ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  8844  **
  8845  ** See Also: [Using the SQLite Unlock Notification Feature].
  8846  **
  8847  ** ^Shared-cache locks are released when a database connection concludes
  8848  ** its current transaction, either by committing it or rolling it back. 
  8849  **
  8850  ** ^When a connection (known as the blocked connection) fails to obtain a
  8851  ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  8852  ** identity of the database connection (the blocking connection) that
  8853  ** has locked the required resource is stored internally. ^After an 
  8854  ** application receives an SQLITE_LOCKED error, it may call the
  8855  ** sqlite3_unlock_notify() method with the blocked connection handle as 
  8856  ** the first argument to register for a callback that will be invoked
  8857  ** when the blocking connections current transaction is concluded. ^The
  8858  ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  8859  ** call that concludes the blocking connections transaction.
  8860  **
  8861  ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  8862  ** there is a chance that the blocking connection will have already
  8863  ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  8864  ** If this happens, then the specified callback is invoked immediately,
  8865  ** from within the call to sqlite3_unlock_notify().)^
  8866  **
  8867  ** ^If the blocked connection is attempting to obtain a write-lock on a
  8868  ** shared-cache table, and more than one other connection currently holds
  8869  ** a read-lock on the same table, then SQLite arbitrarily selects one of 
  8870  ** the other connections to use as the blocking connection.
  8871  **
  8872  ** ^(There may be at most one unlock-notify callback registered by a 
  8873  ** blocked connection. If sqlite3_unlock_notify() is called when the
  8874  ** blocked connection already has a registered unlock-notify callback,
  8875  ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  8876  ** called with a NULL pointer as its second argument, then any existing
  8877  ** unlock-notify callback is canceled. ^The blocked connections 
  8878  ** unlock-notify callback may also be canceled by closing the blocked
  8879  ** connection using [sqlite3_close()].
  8880  **
  8881  ** The unlock-notify callback is not reentrant. If an application invokes
  8882  ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  8883  ** crash or deadlock may be the result.
  8884  **
  8885  ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  8886  ** returns SQLITE_OK.
  8887  **
  8888  ** <b>Callback Invocation Details</b>
  8889  **
  8890  ** When an unlock-notify callback is registered, the application provides a 
  8891  ** single void* pointer that is passed to the callback when it is invoked.
  8892  ** However, the signature of the callback function allows SQLite to pass
  8893  ** it an array of void* context pointers. The first argument passed to
  8894  ** an unlock-notify callback is a pointer to an array of void* pointers,
  8895  ** and the second is the number of entries in the array.
  8896  **
  8897  ** When a blocking connections transaction is concluded, there may be
  8898  ** more than one blocked connection that has registered for an unlock-notify
  8899  ** callback. ^If two or more such blocked connections have specified the
  8900  ** same callback function, then instead of invoking the callback function
  8901  ** multiple times, it is invoked once with the set of void* context pointers
  8902  ** specified by the blocked connections bundled together into an array.
  8903  ** This gives the application an opportunity to prioritize any actions 
  8904  ** related to the set of unblocked database connections.
  8905  **
  8906  ** <b>Deadlock Detection</b>
  8907  **
  8908  ** Assuming that after registering for an unlock-notify callback a 
  8909  ** database waits for the callback to be issued before taking any further
  8910  ** action (a reasonable assumption), then using this API may cause the
  8911  ** application to deadlock. For example, if connection X is waiting for
  8912  ** connection Y's transaction to be concluded, and similarly connection
  8913  ** Y is waiting on connection X's transaction, then neither connection
  8914  ** will proceed and the system may remain deadlocked indefinitely.
  8915  **
  8916  ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  8917  ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  8918  ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  8919  ** unlock-notify callback is registered. The system is said to be in
  8920  ** a deadlocked state if connection A has registered for an unlock-notify
  8921  ** callback on the conclusion of connection B's transaction, and connection
  8922  ** B has itself registered for an unlock-notify callback when connection
  8923  ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  8924  ** the system is also considered to be deadlocked if connection B has
  8925  ** registered for an unlock-notify callback on the conclusion of connection
  8926  ** C's transaction, where connection C is waiting on connection A. ^Any
  8927  ** number of levels of indirection are allowed.
  8928  **
  8929  ** <b>The "DROP TABLE" Exception</b>
  8930  **
  8931  ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
  8932  ** always appropriate to call sqlite3_unlock_notify(). There is however,
  8933  ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  8934  ** SQLite checks if there are any currently executing SELECT statements
  8935  ** that belong to the same connection. If there are, SQLITE_LOCKED is
  8936  ** returned. In this case there is no "blocking connection", so invoking
  8937  ** sqlite3_unlock_notify() results in the unlock-notify callback being
  8938  ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  8939  ** or "DROP INDEX" query, an infinite loop might be the result.
  8940  **
  8941  ** One way around this problem is to check the extended error code returned
  8942  ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  8943  ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  8944  ** the special "DROP TABLE/INDEX" case, the extended error code is just 
  8945  ** SQLITE_LOCKED.)^
  8946  */
  8947  SQLITE_API int sqlite3_unlock_notify(
  8948    sqlite3 *pBlocked,                          /* Waiting connection */
  8949    void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
  8950    void *pNotifyArg                            /* Argument to pass to xNotify */
  8951  );
  8952  
  8953  
  8954  /*
  8955  ** CAPI3REF: String Comparison
  8956  **
  8957  ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  8958  ** and extensions to compare the contents of two buffers containing UTF-8
  8959  ** strings in a case-independent fashion, using the same definition of "case
  8960  ** independence" that SQLite uses internally when comparing identifiers.
  8961  */
  8962  SQLITE_API int sqlite3_stricmp(const char *, const char *);
  8963  SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  8964  
  8965  /*
  8966  ** CAPI3REF: String Globbing
  8967  *
  8968  ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
  8969  ** string X matches the [GLOB] pattern P.
  8970  ** ^The definition of [GLOB] pattern matching used in
  8971  ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  8972  ** SQL dialect understood by SQLite.  ^The [sqlite3_strglob(P,X)] function
  8973  ** is case sensitive.
  8974  **
  8975  ** Note that this routine returns zero on a match and non-zero if the strings
  8976  ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  8977  **
  8978  ** See also: [sqlite3_strlike()].
  8979  */
  8980  SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
  8981  
  8982  /*
  8983  ** CAPI3REF: String LIKE Matching
  8984  *
  8985  ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
  8986  ** string X matches the [LIKE] pattern P with escape character E.
  8987  ** ^The definition of [LIKE] pattern matching used in
  8988  ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
  8989  ** operator in the SQL dialect understood by SQLite.  ^For "X LIKE P" without
  8990  ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
  8991  ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
  8992  ** insensitive - equivalent upper and lower case ASCII characters match
  8993  ** one another.
  8994  **
  8995  ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
  8996  ** only ASCII characters are case folded.
  8997  **
  8998  ** Note that this routine returns zero on a match and non-zero if the strings
  8999  ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  9000  **
  9001  ** See also: [sqlite3_strglob()].
  9002  */
  9003  SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
  9004  
  9005  /*
  9006  ** CAPI3REF: Error Logging Interface
  9007  **
  9008  ** ^The [sqlite3_log()] interface writes a message into the [error log]
  9009  ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  9010  ** ^If logging is enabled, the zFormat string and subsequent arguments are
  9011  ** used with [sqlite3_snprintf()] to generate the final output string.
  9012  **
  9013  ** The sqlite3_log() interface is intended for use by extensions such as
  9014  ** virtual tables, collating functions, and SQL functions.  While there is
  9015  ** nothing to prevent an application from calling sqlite3_log(), doing so
  9016  ** is considered bad form.
  9017  **
  9018  ** The zFormat string must not be NULL.
  9019  **
  9020  ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  9021  ** will not use dynamically allocated memory.  The log message is stored in
  9022  ** a fixed-length buffer on the stack.  If the log message is longer than
  9023  ** a few hundred characters, it will be truncated to the length of the
  9024  ** buffer.
  9025  */
  9026  SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  9027  
  9028  /*
  9029  ** CAPI3REF: Write-Ahead Log Commit Hook
  9030  ** METHOD: sqlite3
  9031  **
  9032  ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  9033  ** is invoked each time data is committed to a database in wal mode.
  9034  **
  9035  ** ^(The callback is invoked by SQLite after the commit has taken place and 
  9036  ** the associated write-lock on the database released)^, so the implementation 
  9037  ** may read, write or [checkpoint] the database as required.
  9038  **
  9039  ** ^The first parameter passed to the callback function when it is invoked
  9040  ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  9041  ** registering the callback. ^The second is a copy of the database handle.
  9042  ** ^The third parameter is the name of the database that was written to -
  9043  ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  9044  ** is the number of pages currently in the write-ahead log file,
  9045  ** including those that were just committed.
  9046  **
  9047  ** The callback function should normally return [SQLITE_OK].  ^If an error
  9048  ** code is returned, that error will propagate back up through the
  9049  ** SQLite code base to cause the statement that provoked the callback
  9050  ** to report an error, though the commit will have still occurred. If the
  9051  ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  9052  ** that does not correspond to any valid SQLite error code, the results
  9053  ** are undefined.
  9054  **
  9055  ** A single database handle may have at most a single write-ahead log callback 
  9056  ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  9057  ** previously registered write-ahead log callback. ^Note that the
  9058  ** [sqlite3_wal_autocheckpoint()] interface and the
  9059  ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  9060  ** overwrite any prior [sqlite3_wal_hook()] settings.
  9061  */
  9062  SQLITE_API void *sqlite3_wal_hook(
  9063    sqlite3*, 
  9064    int(*)(void *,sqlite3*,const char*,int),
  9065    void*
  9066  );
  9067  
  9068  /*
  9069  ** CAPI3REF: Configure an auto-checkpoint
  9070  ** METHOD: sqlite3
  9071  **
  9072  ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  9073  ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  9074  ** to automatically [checkpoint]
  9075  ** after committing a transaction if there are N or
  9076  ** more frames in the [write-ahead log] file.  ^Passing zero or 
  9077  ** a negative value as the nFrame parameter disables automatic
  9078  ** checkpoints entirely.
  9079  **
  9080  ** ^The callback registered by this function replaces any existing callback
  9081  ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
  9082  ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  9083  ** configured by this function.
  9084  **
  9085  ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  9086  ** from SQL.
  9087  **
  9088  ** ^Checkpoints initiated by this mechanism are
  9089  ** [sqlite3_wal_checkpoint_v2|PASSIVE].
  9090  **
  9091  ** ^Every new [database connection] defaults to having the auto-checkpoint
  9092  ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  9093  ** pages.  The use of this interface
  9094  ** is only necessary if the default setting is found to be suboptimal
  9095  ** for a particular application.
  9096  */
  9097  SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  9098  
  9099  /*
  9100  ** CAPI3REF: Checkpoint a database
  9101  ** METHOD: sqlite3
  9102  **
  9103  ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
  9104  ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
  9105  **
  9106  ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the 
  9107  ** [write-ahead log] for database X on [database connection] D to be
  9108  ** transferred into the database file and for the write-ahead log to
  9109  ** be reset.  See the [checkpointing] documentation for addition
  9110  ** information.
  9111  **
  9112  ** This interface used to be the only way to cause a checkpoint to
  9113  ** occur.  But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
  9114  ** interface was added.  This interface is retained for backwards
  9115  ** compatibility and as a convenience for applications that need to manually
  9116  ** start a callback but which do not need the full power (and corresponding
  9117  ** complication) of [sqlite3_wal_checkpoint_v2()].
  9118  */
  9119  SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  9120  
  9121  /*
  9122  ** CAPI3REF: Checkpoint a database
  9123  ** METHOD: sqlite3
  9124  **
  9125  ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
  9126  ** operation on database X of [database connection] D in mode M.  Status
  9127  ** information is written back into integers pointed to by L and C.)^
  9128  ** ^(The M parameter must be a valid [checkpoint mode]:)^
  9129  **
  9130  ** <dl>
  9131  ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  9132  **   ^Checkpoint as many frames as possible without waiting for any database 
  9133  **   readers or writers to finish, then sync the database file if all frames 
  9134  **   in the log were checkpointed. ^The [busy-handler callback]
  9135  **   is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.  
  9136  **   ^On the other hand, passive mode might leave the checkpoint unfinished
  9137  **   if there are concurrent readers or writers.
  9138  **
  9139  ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  9140  **   ^This mode blocks (it invokes the
  9141  **   [sqlite3_busy_handler|busy-handler callback]) until there is no
  9142  **   database writer and all readers are reading from the most recent database
  9143  **   snapshot. ^It then checkpoints all frames in the log file and syncs the
  9144  **   database file. ^This mode blocks new database writers while it is pending,
  9145  **   but new database readers are allowed to continue unimpeded.
  9146  **
  9147  ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  9148  **   ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
  9149  **   that after checkpointing the log file it blocks (calls the 
  9150  **   [busy-handler callback])
  9151  **   until all readers are reading from the database file only. ^This ensures 
  9152  **   that the next writer will restart the log file from the beginning.
  9153  **   ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
  9154  **   database writer attempts while it is pending, but does not impede readers.
  9155  **
  9156  ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
  9157  **   ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
  9158  **   addition that it also truncates the log file to zero bytes just prior
  9159  **   to a successful return.
  9160  ** </dl>
  9161  **
  9162  ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
  9163  ** the log file or to -1 if the checkpoint could not run because
  9164  ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
  9165  ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
  9166  ** log file (including any that were already checkpointed before the function
  9167  ** was called) or to -1 if the checkpoint could not run due to an error or
  9168  ** because the database is not in WAL mode. ^Note that upon successful
  9169  ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
  9170  ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
  9171  **
  9172  ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
  9173  ** any other process is running a checkpoint operation at the same time, the 
  9174  ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a 
  9175  ** busy-handler configured, it will not be invoked in this case.
  9176  **
  9177  ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the 
  9178  ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
  9179  ** obtained immediately, and a busy-handler is configured, it is invoked and
  9180  ** the writer lock retried until either the busy-handler returns 0 or the lock
  9181  ** is successfully obtained. ^The busy-handler is also invoked while waiting for
  9182  ** database readers as described above. ^If the busy-handler returns 0 before
  9183  ** the writer lock is obtained or while waiting for database readers, the
  9184  ** checkpoint operation proceeds from that point in the same way as 
  9185  ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible 
  9186  ** without blocking any further. ^SQLITE_BUSY is returned in this case.
  9187  **
  9188  ** ^If parameter zDb is NULL or points to a zero length string, then the
  9189  ** specified operation is attempted on all WAL databases [attached] to 
  9190  ** [database connection] db.  In this case the
  9191  ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If 
  9192  ** an SQLITE_BUSY error is encountered when processing one or more of the 
  9193  ** attached WAL databases, the operation is still attempted on any remaining 
  9194  ** attached databases and SQLITE_BUSY is returned at the end. ^If any other 
  9195  ** error occurs while processing an attached database, processing is abandoned 
  9196  ** and the error code is returned to the caller immediately. ^If no error 
  9197  ** (SQLITE_BUSY or otherwise) is encountered while processing the attached 
  9198  ** databases, SQLITE_OK is returned.
  9199  **
  9200  ** ^If database zDb is the name of an attached database that is not in WAL
  9201  ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
  9202  ** zDb is not NULL (or a zero length string) and is not the name of any
  9203  ** attached database, SQLITE_ERROR is returned to the caller.
  9204  **
  9205  ** ^Unless it returns SQLITE_MISUSE,
  9206  ** the sqlite3_wal_checkpoint_v2() interface
  9207  ** sets the error information that is queried by
  9208  ** [sqlite3_errcode()] and [sqlite3_errmsg()].
  9209  **
  9210  ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
  9211  ** from SQL.
  9212  */
  9213  SQLITE_API int sqlite3_wal_checkpoint_v2(
  9214    sqlite3 *db,                    /* Database handle */
  9215    const char *zDb,                /* Name of attached database (or NULL) */
  9216    int eMode,                      /* SQLITE_CHECKPOINT_* value */
  9217    int *pnLog,                     /* OUT: Size of WAL log in frames */
  9218    int *pnCkpt                     /* OUT: Total number of frames checkpointed */
  9219  );
  9220  
  9221  /*
  9222  ** CAPI3REF: Checkpoint Mode Values
  9223  ** KEYWORDS: {checkpoint mode}
  9224  **
  9225  ** These constants define all valid values for the "checkpoint mode" passed
  9226  ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
  9227  ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
  9228  ** meaning of each of these checkpoint modes.
  9229  */
  9230  #define SQLITE_CHECKPOINT_PASSIVE  0  /* Do as much as possible w/o blocking */
  9231  #define SQLITE_CHECKPOINT_FULL     1  /* Wait for writers, then checkpoint */
  9232  #define SQLITE_CHECKPOINT_RESTART  2  /* Like FULL but wait for for readers */
  9233  #define SQLITE_CHECKPOINT_TRUNCATE 3  /* Like RESTART but also truncate WAL */
  9234  
  9235  /*
  9236  ** CAPI3REF: Virtual Table Interface Configuration
  9237  **
  9238  ** This function may be called by either the [xConnect] or [xCreate] method
  9239  ** of a [virtual table] implementation to configure
  9240  ** various facets of the virtual table interface.
  9241  **
  9242  ** If this interface is invoked outside the context of an xConnect or
  9243  ** xCreate virtual table method then the behavior is undefined.
  9244  **
  9245  ** At present, there is only one option that may be configured using
  9246  ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
  9247  ** may be added in the future.
  9248  */
  9249  SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
  9250  
  9251  /*
  9252  ** CAPI3REF: Virtual Table Configuration Options
  9253  **
  9254  ** These macros define the various options to the
  9255  ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  9256  ** can use to customize and optimize their behavior.
  9257  **
  9258  ** <dl>
  9259  ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  9260  ** <dd>Calls of the form
  9261  ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  9262  ** where X is an integer.  If X is zero, then the [virtual table] whose
  9263  ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  9264  ** support constraints.  In this configuration (which is the default) if
  9265  ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  9266  ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  9267  ** specified as part of the users SQL statement, regardless of the actual
  9268  ** ON CONFLICT mode specified.
  9269  **
  9270  ** If X is non-zero, then the virtual table implementation guarantees
  9271  ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  9272  ** any modifications to internal or persistent data structures have been made.
  9273  ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite 
  9274  ** is able to roll back a statement or database transaction, and abandon
  9275  ** or continue processing the current SQL statement as appropriate. 
  9276  ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  9277  ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  9278  ** had been ABORT.
  9279  **
  9280  ** Virtual table implementations that are required to handle OR REPLACE
  9281  ** must do so within the [xUpdate] method. If a call to the 
  9282  ** [sqlite3_vtab_on_conflict()] function indicates that the current ON 
  9283  ** CONFLICT policy is REPLACE, the virtual table implementation should 
  9284  ** silently replace the appropriate rows within the xUpdate callback and
  9285  ** return SQLITE_OK. Or, if this is not possible, it may return
  9286  ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT 
  9287  ** constraint handling.
  9288  ** </dl>
  9289  */
  9290  #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  9291  
  9292  /*
  9293  ** CAPI3REF: Determine The Virtual Table Conflict Policy
  9294  **
  9295  ** This function may only be called from within a call to the [xUpdate] method
  9296  ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  9297  ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  9298  ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  9299  ** of the SQL statement that triggered the call to the [xUpdate] method of the
  9300  ** [virtual table].
  9301  */
  9302  SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
  9303  
  9304  /*
  9305  ** CAPI3REF: Conflict resolution modes
  9306  ** KEYWORDS: {conflict resolution mode}
  9307  **
  9308  ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  9309  ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  9310  ** is for the SQL statement being evaluated.
  9311  **
  9312  ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  9313  ** return value from the [sqlite3_set_authorizer()] callback and that
  9314  ** [SQLITE_ABORT] is also a [result code].
  9315  */
  9316  #define SQLITE_ROLLBACK 1
  9317  /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  9318  #define SQLITE_FAIL     3
  9319  /* #define SQLITE_ABORT 4  // Also an error code */
  9320  #define SQLITE_REPLACE  5
  9321  
  9322  /*
  9323  ** CAPI3REF: Prepared Statement Scan Status Opcodes
  9324  ** KEYWORDS: {scanstatus options}
  9325  **
  9326  ** The following constants can be used for the T parameter to the
  9327  ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface.  Each constant designates a
  9328  ** different metric for sqlite3_stmt_scanstatus() to return.
  9329  **
  9330  ** When the value returned to V is a string, space to hold that string is
  9331  ** managed by the prepared statement S and will be automatically freed when
  9332  ** S is finalized.
  9333  **
  9334  ** <dl>
  9335  ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
  9336  ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
  9337  ** set to the total number of times that the X-th loop has run.</dd>
  9338  **
  9339  ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
  9340  ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
  9341  ** to the total number of rows examined by all iterations of the X-th loop.</dd>
  9342  **
  9343  ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
  9344  ** <dd>^The "double" variable pointed to by the T parameter will be set to the
  9345  ** query planner's estimate for the average number of rows output from each
  9346  ** iteration of the X-th loop.  If the query planner's estimates was accurate,
  9347  ** then this value will approximate the quotient NVISIT/NLOOP and the
  9348  ** product of this value for all prior loops with the same SELECTID will
  9349  ** be the NLOOP value for the current loop.
  9350  **
  9351  ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
  9352  ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  9353  ** to a zero-terminated UTF-8 string containing the name of the index or table
  9354  ** used for the X-th loop.
  9355  **
  9356  ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
  9357  ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  9358  ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
  9359  ** description for the X-th loop.
  9360  **
  9361  ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
  9362  ** <dd>^The "int" variable pointed to by the T parameter will be set to the
  9363  ** "select-id" for the X-th loop.  The select-id identifies which query or
  9364  ** subquery the loop is part of.  The main query has a select-id of zero.
  9365  ** The select-id is the same value as is output in the first column
  9366  ** of an [EXPLAIN QUERY PLAN] query.
  9367  ** </dl>
  9368  */
  9369  #define SQLITE_SCANSTAT_NLOOP    0
  9370  #define SQLITE_SCANSTAT_NVISIT   1
  9371  #define SQLITE_SCANSTAT_EST      2
  9372  #define SQLITE_SCANSTAT_NAME     3
  9373  #define SQLITE_SCANSTAT_EXPLAIN  4
  9374  #define SQLITE_SCANSTAT_SELECTID 5
  9375  
  9376  /*
  9377  ** CAPI3REF: Prepared Statement Scan Status
  9378  ** METHOD: sqlite3_stmt
  9379  **
  9380  ** This interface returns information about the predicted and measured
  9381  ** performance for pStmt.  Advanced applications can use this
  9382  ** interface to compare the predicted and the measured performance and
  9383  ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
  9384  **
  9385  ** Since this interface is expected to be rarely used, it is only
  9386  ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
  9387  ** compile-time option.
  9388  **
  9389  ** The "iScanStatusOp" parameter determines which status information to return.
  9390  ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
  9391  ** of this interface is undefined.
  9392  ** ^The requested measurement is written into a variable pointed to by
  9393  ** the "pOut" parameter.
  9394  ** Parameter "idx" identifies the specific loop to retrieve statistics for.
  9395  ** Loops are numbered starting from zero. ^If idx is out of range - less than
  9396  ** zero or greater than or equal to the total number of loops used to implement
  9397  ** the statement - a non-zero value is returned and the variable that pOut
  9398  ** points to is unchanged.
  9399  **
  9400  ** ^Statistics might not be available for all loops in all statements. ^In cases
  9401  ** where there exist loops with no available statistics, this function behaves
  9402  ** as if the loop did not exist - it returns non-zero and leave the variable
  9403  ** that pOut points to unchanged.
  9404  **
  9405  ** See also: [sqlite3_stmt_scanstatus_reset()]
  9406  */
  9407  SQLITE_API int sqlite3_stmt_scanstatus(
  9408    sqlite3_stmt *pStmt,      /* Prepared statement for which info desired */
  9409    int idx,                  /* Index of loop to report on */
  9410    int iScanStatusOp,        /* Information desired.  SQLITE_SCANSTAT_* */
  9411    void *pOut                /* Result written here */
  9412  );     
  9413  
  9414  /*
  9415  ** CAPI3REF: Zero Scan-Status Counters
  9416  ** METHOD: sqlite3_stmt
  9417  **
  9418  ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
  9419  **
  9420  ** This API is only available if the library is built with pre-processor
  9421  ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
  9422  */
  9423  SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
  9424  
  9425  /*
  9426  ** CAPI3REF: Flush caches to disk mid-transaction
  9427  **
  9428  ** ^If a write-transaction is open on [database connection] D when the
  9429  ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
  9430  ** pages in the pager-cache that are not currently in use are written out 
  9431  ** to disk. A dirty page may be in use if a database cursor created by an
  9432  ** active SQL statement is reading from it, or if it is page 1 of a database
  9433  ** file (page 1 is always "in use").  ^The [sqlite3_db_cacheflush(D)]
  9434  ** interface flushes caches for all schemas - "main", "temp", and
  9435  ** any [attached] databases.
  9436  **
  9437  ** ^If this function needs to obtain extra database locks before dirty pages 
  9438  ** can be flushed to disk, it does so. ^If those locks cannot be obtained 
  9439  ** immediately and there is a busy-handler callback configured, it is invoked
  9440  ** in the usual manner. ^If the required lock still cannot be obtained, then
  9441  ** the database is skipped and an attempt made to flush any dirty pages
  9442  ** belonging to the next (if any) database. ^If any databases are skipped
  9443  ** because locks cannot be obtained, but no other error occurs, this
  9444  ** function returns SQLITE_BUSY.
  9445  **
  9446  ** ^If any other error occurs while flushing dirty pages to disk (for
  9447  ** example an IO error or out-of-memory condition), then processing is
  9448  ** abandoned and an SQLite [error code] is returned to the caller immediately.
  9449  **
  9450  ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
  9451  **
  9452  ** ^This function does not set the database handle error code or message
  9453  ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
  9454  */
  9455  SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
  9456  
  9457  /*
  9458  ** CAPI3REF: The pre-update hook.
  9459  **
  9460  ** ^These interfaces are only available if SQLite is compiled using the
  9461  ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
  9462  **
  9463  ** ^The [sqlite3_preupdate_hook()] interface registers a callback function
  9464  ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
  9465  ** on a database table.
  9466  ** ^At most one preupdate hook may be registered at a time on a single
  9467  ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
  9468  ** the previous setting.
  9469  ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
  9470  ** with a NULL pointer as the second parameter.
  9471  ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
  9472  ** the first parameter to callbacks.
  9473  **
  9474  ** ^The preupdate hook only fires for changes to real database tables; the
  9475  ** preupdate hook is not invoked for changes to [virtual tables] or to
  9476  ** system tables like sqlite_master or sqlite_stat1.
  9477  **
  9478  ** ^The second parameter to the preupdate callback is a pointer to
  9479  ** the [database connection] that registered the preupdate hook.
  9480  ** ^The third parameter to the preupdate callback is one of the constants
  9481  ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
  9482  ** kind of update operation that is about to occur.
  9483  ** ^(The fourth parameter to the preupdate callback is the name of the
  9484  ** database within the database connection that is being modified.  This
  9485  ** will be "main" for the main database or "temp" for TEMP tables or 
  9486  ** the name given after the AS keyword in the [ATTACH] statement for attached
  9487  ** databases.)^
  9488  ** ^The fifth parameter to the preupdate callback is the name of the
  9489  ** table that is being modified.
  9490  **
  9491  ** For an UPDATE or DELETE operation on a [rowid table], the sixth
  9492  ** parameter passed to the preupdate callback is the initial [rowid] of the 
  9493  ** row being modified or deleted. For an INSERT operation on a rowid table,
  9494  ** or any operation on a WITHOUT ROWID table, the value of the sixth 
  9495  ** parameter is undefined. For an INSERT or UPDATE on a rowid table the
  9496  ** seventh parameter is the final rowid value of the row being inserted
  9497  ** or updated. The value of the seventh parameter passed to the callback
  9498  ** function is not defined for operations on WITHOUT ROWID tables, or for
  9499  ** INSERT operations on rowid tables.
  9500  **
  9501  ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
  9502  ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
  9503  ** provide additional information about a preupdate event. These routines
  9504  ** may only be called from within a preupdate callback.  Invoking any of
  9505  ** these routines from outside of a preupdate callback or with a
  9506  ** [database connection] pointer that is different from the one supplied
  9507  ** to the preupdate callback results in undefined and probably undesirable
  9508  ** behavior.
  9509  **
  9510  ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
  9511  ** in the row that is being inserted, updated, or deleted.
  9512  **
  9513  ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
  9514  ** a [protected sqlite3_value] that contains the value of the Nth column of
  9515  ** the table row before it is updated.  The N parameter must be between 0
  9516  ** and one less than the number of columns or the behavior will be
  9517  ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
  9518  ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
  9519  ** behavior is undefined.  The [sqlite3_value] that P points to
  9520  ** will be destroyed when the preupdate callback returns.
  9521  **
  9522  ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
  9523  ** a [protected sqlite3_value] that contains the value of the Nth column of
  9524  ** the table row after it is updated.  The N parameter must be between 0
  9525  ** and one less than the number of columns or the behavior will be
  9526  ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
  9527  ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
  9528  ** behavior is undefined.  The [sqlite3_value] that P points to
  9529  ** will be destroyed when the preupdate callback returns.
  9530  **
  9531  ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
  9532  ** callback was invoked as a result of a direct insert, update, or delete
  9533  ** operation; or 1 for inserts, updates, or deletes invoked by top-level 
  9534  ** triggers; or 2 for changes resulting from triggers called by top-level
  9535  ** triggers; and so forth.
  9536  **
  9537  ** See also:  [sqlite3_update_hook()]
  9538  */
  9539  #if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
  9540  SQLITE_API void *sqlite3_preupdate_hook(
  9541    sqlite3 *db,
  9542    void(*xPreUpdate)(
  9543      void *pCtx,                   /* Copy of third arg to preupdate_hook() */
  9544      sqlite3 *db,                  /* Database handle */
  9545      int op,                       /* SQLITE_UPDATE, DELETE or INSERT */
  9546      char const *zDb,              /* Database name */
  9547      char const *zName,            /* Table name */
  9548      sqlite3_int64 iKey1,          /* Rowid of row about to be deleted/updated */
  9549      sqlite3_int64 iKey2           /* New rowid value (for a rowid UPDATE) */
  9550    ),
  9551    void*
  9552  );
  9553  SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
  9554  SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
  9555  SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
  9556  SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
  9557  #endif
  9558  
  9559  /*
  9560  ** CAPI3REF: Low-level system error code
  9561  **
  9562  ** ^Attempt to return the underlying operating system error code or error
  9563  ** number that caused the most recent I/O error or failure to open a file.
  9564  ** The return value is OS-dependent.  For example, on unix systems, after
  9565  ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
  9566  ** called to get back the underlying "errno" that caused the problem, such
  9567  ** as ENOSPC, EAUTH, EISDIR, and so forth.  
  9568  */
  9569  SQLITE_API int sqlite3_system_errno(sqlite3*);
  9570  
  9571  /*
  9572  ** CAPI3REF: Database Snapshot
  9573  ** KEYWORDS: {snapshot} {sqlite3_snapshot}
  9574  ** EXPERIMENTAL
  9575  **
  9576  ** An instance of the snapshot object records the state of a [WAL mode]
  9577  ** database for some specific point in history.
  9578  **
  9579  ** In [WAL mode], multiple [database connections] that are open on the
  9580  ** same database file can each be reading a different historical version
  9581  ** of the database file.  When a [database connection] begins a read
  9582  ** transaction, that connection sees an unchanging copy of the database
  9583  ** as it existed for the point in time when the transaction first started.
  9584  ** Subsequent changes to the database from other connections are not seen
  9585  ** by the reader until a new read transaction is started.
  9586  **
  9587  ** The sqlite3_snapshot object records state information about an historical
  9588  ** version of the database file so that it is possible to later open a new read
  9589  ** transaction that sees that historical version of the database rather than
  9590  ** the most recent version.
  9591  **
  9592  ** The constructor for this object is [sqlite3_snapshot_get()].  The
  9593  ** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer
  9594  ** to an historical snapshot (if possible).  The destructor for 
  9595  ** sqlite3_snapshot objects is [sqlite3_snapshot_free()].
  9596  */
  9597  typedef struct sqlite3_snapshot {
  9598    unsigned char hidden[48];
  9599  } sqlite3_snapshot;
  9600  
  9601  /*
  9602  ** CAPI3REF: Record A Database Snapshot
  9603  ** EXPERIMENTAL
  9604  **
  9605  ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
  9606  ** new [sqlite3_snapshot] object that records the current state of
  9607  ** schema S in database connection D.  ^On success, the
  9608  ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
  9609  ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
  9610  ** If there is not already a read-transaction open on schema S when
  9611  ** this function is called, one is opened automatically. 
  9612  **
  9613  ** The following must be true for this function to succeed. If any of
  9614  ** the following statements are false when sqlite3_snapshot_get() is
  9615  ** called, SQLITE_ERROR is returned. The final value of *P is undefined
  9616  ** in this case. 
  9617  **
  9618  ** <ul>
  9619  **   <li> The database handle must be in [autocommit mode].
  9620  **
  9621  **   <li> Schema S of [database connection] D must be a [WAL mode] database.
  9622  **
  9623  **   <li> There must not be a write transaction open on schema S of database
  9624  **        connection D.
  9625  **
  9626  **   <li> One or more transactions must have been written to the current wal
  9627  **        file since it was created on disk (by any connection). This means
  9628  **        that a snapshot cannot be taken on a wal mode database with no wal 
  9629  **        file immediately after it is first opened. At least one transaction
  9630  **        must be written to it first.
  9631  ** </ul>
  9632  **
  9633  ** This function may also return SQLITE_NOMEM.  If it is called with the
  9634  ** database handle in autocommit mode but fails for some other reason, 
  9635  ** whether or not a read transaction is opened on schema S is undefined.
  9636  **
  9637  ** The [sqlite3_snapshot] object returned from a successful call to
  9638  ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
  9639  ** to avoid a memory leak.
  9640  **
  9641  ** The [sqlite3_snapshot_get()] interface is only available when the
  9642  ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  9643  */
  9644  SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
  9645    sqlite3 *db,
  9646    const char *zSchema,
  9647    sqlite3_snapshot **ppSnapshot
  9648  );
  9649  
  9650  /*
  9651  ** CAPI3REF: Start a read transaction on an historical snapshot
  9652  ** EXPERIMENTAL
  9653  **
  9654  ** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a
  9655  ** read transaction for schema S of
  9656  ** [database connection] D such that the read transaction
  9657  ** refers to historical [snapshot] P, rather than the most
  9658  ** recent change to the database.
  9659  ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
  9660  ** or an appropriate [error code] if it fails.
  9661  **
  9662  ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
  9663  ** the first operation following the [BEGIN] that takes the schema S
  9664  ** out of [autocommit mode].
  9665  ** ^In other words, schema S must not currently be in
  9666  ** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the
  9667  ** database connection D must be out of [autocommit mode].
  9668  ** ^A [snapshot] will fail to open if it has been overwritten by a
  9669  ** [checkpoint].
  9670  ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
  9671  ** database connection D does not know that the database file for
  9672  ** schema S is in [WAL mode].  A database connection might not know
  9673  ** that the database file is in [WAL mode] if there has been no prior
  9674  ** I/O on that database connection, or if the database entered [WAL mode] 
  9675  ** after the most recent I/O on the database connection.)^
  9676  ** (Hint: Run "[PRAGMA application_id]" against a newly opened
  9677  ** database connection in order to make it ready to use snapshots.)
  9678  **
  9679  ** The [sqlite3_snapshot_open()] interface is only available when the
  9680  ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  9681  */
  9682  SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
  9683    sqlite3 *db,
  9684    const char *zSchema,
  9685    sqlite3_snapshot *pSnapshot
  9686  );
  9687  
  9688  /*
  9689  ** CAPI3REF: Destroy a snapshot
  9690  ** EXPERIMENTAL
  9691  **
  9692  ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
  9693  ** The application must eventually free every [sqlite3_snapshot] object
  9694  ** using this routine to avoid a memory leak.
  9695  **
  9696  ** The [sqlite3_snapshot_free()] interface is only available when the
  9697  ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  9698  */
  9699  SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
  9700  
  9701  /*
  9702  ** CAPI3REF: Compare the ages of two snapshot handles.
  9703  ** EXPERIMENTAL
  9704  **
  9705  ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
  9706  ** of two valid snapshot handles. 
  9707  **
  9708  ** If the two snapshot handles are not associated with the same database 
  9709  ** file, the result of the comparison is undefined. 
  9710  **
  9711  ** Additionally, the result of the comparison is only valid if both of the
  9712  ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
  9713  ** last time the wal file was deleted. The wal file is deleted when the
  9714  ** database is changed back to rollback mode or when the number of database
  9715  ** clients drops to zero. If either snapshot handle was obtained before the 
  9716  ** wal file was last deleted, the value returned by this function 
  9717  ** is undefined.
  9718  **
  9719  ** Otherwise, this API returns a negative value if P1 refers to an older
  9720  ** snapshot than P2, zero if the two handles refer to the same database
  9721  ** snapshot, and a positive value if P1 is a newer snapshot than P2.
  9722  */
  9723  SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
  9724    sqlite3_snapshot *p1,
  9725    sqlite3_snapshot *p2
  9726  );
  9727  
  9728  /*
  9729  ** CAPI3REF: Recover snapshots from a wal file
  9730  ** EXPERIMENTAL
  9731  **
  9732  ** If all connections disconnect from a database file but do not perform
  9733  ** a checkpoint, the existing wal file is opened along with the database
  9734  ** file the next time the database is opened. At this point it is only
  9735  ** possible to successfully call sqlite3_snapshot_open() to open the most
  9736  ** recent snapshot of the database (the one at the head of the wal file),
  9737  ** even though the wal file may contain other valid snapshots for which
  9738  ** clients have sqlite3_snapshot handles.
  9739  **
  9740  ** This function attempts to scan the wal file associated with database zDb
  9741  ** of database handle db and make all valid snapshots available to
  9742  ** sqlite3_snapshot_open(). It is an error if there is already a read
  9743  ** transaction open on the database, or if the database is not a wal mode
  9744  ** database.
  9745  **
  9746  ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  9747  */
  9748  SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);
  9749  
  9750  /*
  9751  ** Undo the hack that converts floating point types to integer for
  9752  ** builds on processors without floating point support.
  9753  */
  9754  #ifdef SQLITE_OMIT_FLOATING_POINT
  9755  # undef double
  9756  #endif
  9757  
  9758  #if 0
  9759  }  /* End of the 'extern "C"' block */
  9760  #endif
  9761  #endif /* SQLITE3_H */
  9762  
  9763  /******** Begin file sqlite3rtree.h *********/
  9764  /*
  9765  ** 2010 August 30
  9766  **
  9767  ** The author disclaims copyright to this source code.  In place of
  9768  ** a legal notice, here is a blessing:
  9769  **
  9770  **    May you do good and not evil.
  9771  **    May you find forgiveness for yourself and forgive others.
  9772  **    May you share freely, never taking more than you give.
  9773  **
  9774  *************************************************************************
  9775  */
  9776  
  9777  #ifndef _SQLITE3RTREE_H_
  9778  #define _SQLITE3RTREE_H_
  9779  
  9780  
  9781  #if 0
  9782  extern "C" {
  9783  #endif
  9784  
  9785  typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  9786  typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
  9787  
  9788  /* The double-precision datatype used by RTree depends on the
  9789  ** SQLITE_RTREE_INT_ONLY compile-time option.
  9790  */
  9791  #ifdef SQLITE_RTREE_INT_ONLY
  9792    typedef sqlite3_int64 sqlite3_rtree_dbl;
  9793  #else
  9794    typedef double sqlite3_rtree_dbl;
  9795  #endif
  9796  
  9797  /*
  9798  ** Register a geometry callback named zGeom that can be used as part of an
  9799  ** R-Tree geometry query as follows:
  9800  **
  9801  **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  9802  */
  9803  SQLITE_API int sqlite3_rtree_geometry_callback(
  9804    sqlite3 *db,
  9805    const char *zGeom,
  9806    int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
  9807    void *pContext
  9808  );
  9809  
  9810  
  9811  /*
  9812  ** A pointer to a structure of the following type is passed as the first
  9813  ** argument to callbacks registered using rtree_geometry_callback().
  9814  */
  9815  struct sqlite3_rtree_geometry {
  9816    void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
  9817    int nParam;                     /* Size of array aParam[] */
  9818    sqlite3_rtree_dbl *aParam;      /* Parameters passed to SQL geom function */
  9819    void *pUser;                    /* Callback implementation user data */
  9820    void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
  9821  };
  9822  
  9823  /*
  9824  ** Register a 2nd-generation geometry callback named zScore that can be 
  9825  ** used as part of an R-Tree geometry query as follows:
  9826  **
  9827  **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
  9828  */
  9829  SQLITE_API int sqlite3_rtree_query_callback(
  9830    sqlite3 *db,
  9831    const char *zQueryFunc,
  9832    int (*xQueryFunc)(sqlite3_rtree_query_info*),
  9833    void *pContext,
  9834    void (*xDestructor)(void*)
  9835  );
  9836  
  9837  
  9838  /*
  9839  ** A pointer to a structure of the following type is passed as the 
  9840  ** argument to scored geometry callback registered using
  9841  ** sqlite3_rtree_query_callback().
  9842  **
  9843  ** Note that the first 5 fields of this structure are identical to
  9844  ** sqlite3_rtree_geometry.  This structure is a subclass of
  9845  ** sqlite3_rtree_geometry.
  9846  */
  9847  struct sqlite3_rtree_query_info {
  9848    void *pContext;                   /* pContext from when function registered */
  9849    int nParam;                       /* Number of function parameters */
  9850    sqlite3_rtree_dbl *aParam;        /* value of function parameters */
  9851    void *pUser;                      /* callback can use this, if desired */
  9852    void (*xDelUser)(void*);          /* function to free pUser */
  9853    sqlite3_rtree_dbl *aCoord;        /* Coordinates of node or entry to check */
  9854    unsigned int *anQueue;            /* Number of pending entries in the queue */
  9855    int nCoord;                       /* Number of coordinates */
  9856    int iLevel;                       /* Level of current node or entry */
  9857    int mxLevel;                      /* The largest iLevel value in the tree */
  9858    sqlite3_int64 iRowid;             /* Rowid for current entry */
  9859    sqlite3_rtree_dbl rParentScore;   /* Score of parent node */
  9860    int eParentWithin;                /* Visibility of parent node */
  9861    int eWithin;                      /* OUT: Visiblity */
  9862    sqlite3_rtree_dbl rScore;         /* OUT: Write the score here */
  9863    /* The following fields are only available in 3.8.11 and later */
  9864    sqlite3_value **apSqlParam;       /* Original SQL values of parameters */
  9865  };
  9866  
  9867  /*
  9868  ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
  9869  */
  9870  #define NOT_WITHIN       0   /* Object completely outside of query region */
  9871  #define PARTLY_WITHIN    1   /* Object partially overlaps query region */
  9872  #define FULLY_WITHIN     2   /* Object fully contained within query region */
  9873  
  9874  
  9875  #if 0
  9876  }  /* end of the 'extern "C"' block */
  9877  #endif
  9878  
  9879  #endif  /* ifndef _SQLITE3RTREE_H_ */
  9880  
  9881  /******** End of sqlite3rtree.h *********/
  9882  /******** Begin file sqlite3session.h *********/
  9883  
  9884  #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
  9885  #define __SQLITESESSION_H_ 1
  9886  
  9887  /*
  9888  ** Make sure we can call this stuff from C++.
  9889  */
  9890  #if 0
  9891  extern "C" {
  9892  #endif
  9893  
  9894  
  9895  /*
  9896  ** CAPI3REF: Session Object Handle
  9897  */
  9898  typedef struct sqlite3_session sqlite3_session;
  9899  
  9900  /*
  9901  ** CAPI3REF: Changeset Iterator Handle
  9902  */
  9903  typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
  9904  
  9905  /*
  9906  ** CAPI3REF: Create A New Session Object
  9907  **
  9908  ** Create a new session object attached to database handle db. If successful,
  9909  ** a pointer to the new object is written to *ppSession and SQLITE_OK is
  9910  ** returned. If an error occurs, *ppSession is set to NULL and an SQLite
  9911  ** error code (e.g. SQLITE_NOMEM) is returned.
  9912  **
  9913  ** It is possible to create multiple session objects attached to a single
  9914  ** database handle.
  9915  **
  9916  ** Session objects created using this function should be deleted using the
  9917  ** [sqlite3session_delete()] function before the database handle that they
  9918  ** are attached to is itself closed. If the database handle is closed before
  9919  ** the session object is deleted, then the results of calling any session
  9920  ** module function, including [sqlite3session_delete()] on the session object
  9921  ** are undefined.
  9922  **
  9923  ** Because the session module uses the [sqlite3_preupdate_hook()] API, it
  9924  ** is not possible for an application to register a pre-update hook on a
  9925  ** database handle that has one or more session objects attached. Nor is
  9926  ** it possible to create a session object attached to a database handle for
  9927  ** which a pre-update hook is already defined. The results of attempting 
  9928  ** either of these things are undefined.
  9929  **
  9930  ** The session object will be used to create changesets for tables in
  9931  ** database zDb, where zDb is either "main", or "temp", or the name of an
  9932  ** attached database. It is not an error if database zDb is not attached
  9933  ** to the database when the session object is created.
  9934  */
  9935  SQLITE_API int sqlite3session_create(
  9936    sqlite3 *db,                    /* Database handle */
  9937    const char *zDb,                /* Name of db (e.g. "main") */
  9938    sqlite3_session **ppSession     /* OUT: New session object */
  9939  );
  9940  
  9941  /*
  9942  ** CAPI3REF: Delete A Session Object
  9943  **
  9944  ** Delete a session object previously allocated using 
  9945  ** [sqlite3session_create()]. Once a session object has been deleted, the
  9946  ** results of attempting to use pSession with any other session module
  9947  ** function are undefined.
  9948  **
  9949  ** Session objects must be deleted before the database handle to which they
  9950  ** are attached is closed. Refer to the documentation for 
  9951  ** [sqlite3session_create()] for details.
  9952  */
  9953  SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
  9954  
  9955  
  9956  /*
  9957  ** CAPI3REF: Enable Or Disable A Session Object
  9958  **
  9959  ** Enable or disable the recording of changes by a session object. When
  9960  ** enabled, a session object records changes made to the database. When
  9961  ** disabled - it does not. A newly created session object is enabled.
  9962  ** Refer to the documentation for [sqlite3session_changeset()] for further
  9963  ** details regarding how enabling and disabling a session object affects
  9964  ** the eventual changesets.
  9965  **
  9966  ** Passing zero to this function disables the session. Passing a value
  9967  ** greater than zero enables it. Passing a value less than zero is a 
  9968  ** no-op, and may be used to query the current state of the session.
  9969  **
  9970  ** The return value indicates the final state of the session object: 0 if 
  9971  ** the session is disabled, or 1 if it is enabled.
  9972  */
  9973  SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
  9974  
  9975  /*
  9976  ** CAPI3REF: Set Or Clear the Indirect Change Flag
  9977  **
  9978  ** Each change recorded by a session object is marked as either direct or
  9979  ** indirect. A change is marked as indirect if either:
  9980  **
  9981  ** <ul>
  9982  **   <li> The session object "indirect" flag is set when the change is
  9983  **        made, or
  9984  **   <li> The change is made by an SQL trigger or foreign key action 
  9985  **        instead of directly as a result of a users SQL statement.
  9986  ** </ul>
  9987  **
  9988  ** If a single row is affected by more than one operation within a session,
  9989  ** then the change is considered indirect if all operations meet the criteria
  9990  ** for an indirect change above, or direct otherwise.
  9991  **
  9992  ** This function is used to set, clear or query the session object indirect
  9993  ** flag.  If the second argument passed to this function is zero, then the
  9994  ** indirect flag is cleared. If it is greater than zero, the indirect flag
  9995  ** is set. Passing a value less than zero does not modify the current value
  9996  ** of the indirect flag, and may be used to query the current state of the 
  9997  ** indirect flag for the specified session object.
  9998  **
  9999  ** The return value indicates the final state of the indirect flag: 0 if 
 10000  ** it is clear, or 1 if it is set.
 10001  */
 10002  SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
 10003  
 10004  /*
 10005  ** CAPI3REF: Attach A Table To A Session Object
 10006  **
 10007  ** If argument zTab is not NULL, then it is the name of a table to attach
 10008  ** to the session object passed as the first argument. All subsequent changes 
 10009  ** made to the table while the session object is enabled will be recorded. See 
 10010  ** documentation for [sqlite3session_changeset()] for further details.
 10011  **
 10012  ** Or, if argument zTab is NULL, then changes are recorded for all tables
 10013  ** in the database. If additional tables are added to the database (by 
 10014  ** executing "CREATE TABLE" statements) after this call is made, changes for 
 10015  ** the new tables are also recorded.
 10016  **
 10017  ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
 10018  ** defined as part of their CREATE TABLE statement. It does not matter if the 
 10019  ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
 10020  ** KEY may consist of a single column, or may be a composite key.
 10021  ** 
 10022  ** It is not an error if the named table does not exist in the database. Nor
 10023  ** is it an error if the named table does not have a PRIMARY KEY. However,
 10024  ** no changes will be recorded in either of these scenarios.
 10025  **
 10026  ** Changes are not recorded for individual rows that have NULL values stored
 10027  ** in one or more of their PRIMARY KEY columns.
 10028  **
 10029  ** SQLITE_OK is returned if the call completes without error. Or, if an error 
 10030  ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
 10031  */
 10032  SQLITE_API int sqlite3session_attach(
 10033    sqlite3_session *pSession,      /* Session object */
 10034    const char *zTab                /* Table name */
 10035  );
 10036  
 10037  /*
 10038  ** CAPI3REF: Set a table filter on a Session Object.
 10039  **
 10040  ** The second argument (xFilter) is the "filter callback". For changes to rows 
 10041  ** in tables that are not attached to the Session object, the filter is called
 10042  ** to determine whether changes to the table's rows should be tracked or not. 
 10043  ** If xFilter returns 0, changes is not tracked. Note that once a table is 
 10044  ** attached, xFilter will not be called again.
 10045  */
 10046  SQLITE_API void sqlite3session_table_filter(
 10047    sqlite3_session *pSession,      /* Session object */
 10048    int(*xFilter)(
 10049      void *pCtx,                   /* Copy of third arg to _filter_table() */
 10050      const char *zTab              /* Table name */
 10051    ),
 10052    void *pCtx                      /* First argument passed to xFilter */
 10053  );
 10054  
 10055  /*
 10056  ** CAPI3REF: Generate A Changeset From A Session Object
 10057  **
 10058  ** Obtain a changeset containing changes to the tables attached to the 
 10059  ** session object passed as the first argument. If successful, 
 10060  ** set *ppChangeset to point to a buffer containing the changeset 
 10061  ** and *pnChangeset to the size of the changeset in bytes before returning
 10062  ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
 10063  ** zero and return an SQLite error code.
 10064  **
 10065  ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
 10066  ** each representing a change to a single row of an attached table. An INSERT
 10067  ** change contains the values of each field of a new database row. A DELETE
 10068  ** contains the original values of each field of a deleted database row. An
 10069  ** UPDATE change contains the original values of each field of an updated
 10070  ** database row along with the updated values for each updated non-primary-key
 10071  ** column. It is not possible for an UPDATE change to represent a change that
 10072  ** modifies the values of primary key columns. If such a change is made, it
 10073  ** is represented in a changeset as a DELETE followed by an INSERT.
 10074  **
 10075  ** Changes are not recorded for rows that have NULL values stored in one or 
 10076  ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
 10077  ** no corresponding change is present in the changesets returned by this
 10078  ** function. If an existing row with one or more NULL values stored in
 10079  ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
 10080  ** only an INSERT is appears in the changeset. Similarly, if an existing row
 10081  ** with non-NULL PRIMARY KEY values is updated so that one or more of its
 10082  ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
 10083  ** DELETE change only.
 10084  **
 10085  ** The contents of a changeset may be traversed using an iterator created
 10086  ** using the [sqlite3changeset_start()] API. A changeset may be applied to
 10087  ** a database with a compatible schema using the [sqlite3changeset_apply()]
 10088  ** API.
 10089  **
 10090  ** Within a changeset generated by this function, all changes related to a
 10091  ** single table are grouped together. In other words, when iterating through
 10092  ** a changeset or when applying a changeset to a database, all changes related
 10093  ** to a single table are processed before moving on to the next table. Tables
 10094  ** are sorted in the same order in which they were attached (or auto-attached)
 10095  ** to the sqlite3_session object. The order in which the changes related to
 10096  ** a single table are stored is undefined.
 10097  **
 10098  ** Following a successful call to this function, it is the responsibility of
 10099  ** the caller to eventually free the buffer that *ppChangeset points to using
 10100  ** [sqlite3_free()].
 10101  **
 10102  ** <h3>Changeset Generation</h3>
 10103  **
 10104  ** Once a table has been attached to a session object, the session object
 10105  ** records the primary key values of all new rows inserted into the table.
 10106  ** It also records the original primary key and other column values of any
 10107  ** deleted or updated rows. For each unique primary key value, data is only
 10108  ** recorded once - the first time a row with said primary key is inserted,
 10109  ** updated or deleted in the lifetime of the session.
 10110  **
 10111  ** There is one exception to the previous paragraph: when a row is inserted,
 10112  ** updated or deleted, if one or more of its primary key columns contain a
 10113  ** NULL value, no record of the change is made.
 10114  **
 10115  ** The session object therefore accumulates two types of records - those
 10116  ** that consist of primary key values only (created when the user inserts
 10117  ** a new record) and those that consist of the primary key values and the
 10118  ** original values of other table columns (created when the users deletes
 10119  ** or updates a record).
 10120  **
 10121  ** When this function is called, the requested changeset is created using
 10122  ** both the accumulated records and the current contents of the database
 10123  ** file. Specifically:
 10124  **
 10125  ** <ul>
 10126  **   <li> For each record generated by an insert, the database is queried
 10127  **        for a row with a matching primary key. If one is found, an INSERT
 10128  **        change is added to the changeset. If no such row is found, no change 
 10129  **        is added to the changeset.
 10130  **
 10131  **   <li> For each record generated by an update or delete, the database is 
 10132  **        queried for a row with a matching primary key. If such a row is
 10133  **        found and one or more of the non-primary key fields have been
 10134  **        modified from their original values, an UPDATE change is added to 
 10135  **        the changeset. Or, if no such row is found in the table, a DELETE 
 10136  **        change is added to the changeset. If there is a row with a matching
 10137  **        primary key in the database, but all fields contain their original
 10138  **        values, no change is added to the changeset.
 10139  ** </ul>
 10140  **
 10141  ** This means, amongst other things, that if a row is inserted and then later
 10142  ** deleted while a session object is active, neither the insert nor the delete
 10143  ** will be present in the changeset. Or if a row is deleted and then later a 
 10144  ** row with the same primary key values inserted while a session object is
 10145  ** active, the resulting changeset will contain an UPDATE change instead of
 10146  ** a DELETE and an INSERT.
 10147  **
 10148  ** When a session object is disabled (see the [sqlite3session_enable()] API),
 10149  ** it does not accumulate records when rows are inserted, updated or deleted.
 10150  ** This may appear to have some counter-intuitive effects if a single row
 10151  ** is written to more than once during a session. For example, if a row
 10152  ** is inserted while a session object is enabled, then later deleted while 
 10153  ** the same session object is disabled, no INSERT record will appear in the
 10154  ** changeset, even though the delete took place while the session was disabled.
 10155  ** Or, if one field of a row is updated while a session is disabled, and 
 10156  ** another field of the same row is updated while the session is enabled, the
 10157  ** resulting changeset will contain an UPDATE change that updates both fields.
 10158  */
 10159  SQLITE_API int sqlite3session_changeset(
 10160    sqlite3_session *pSession,      /* Session object */
 10161    int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
 10162    void **ppChangeset              /* OUT: Buffer containing changeset */
 10163  );
 10164  
 10165  /*
 10166  ** CAPI3REF: Load The Difference Between Tables Into A Session 
 10167  **
 10168  ** If it is not already attached to the session object passed as the first
 10169  ** argument, this function attaches table zTbl in the same manner as the
 10170  ** [sqlite3session_attach()] function. If zTbl does not exist, or if it
 10171  ** does not have a primary key, this function is a no-op (but does not return
 10172  ** an error).
 10173  **
 10174  ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
 10175  ** attached to the same database handle as the session object that contains 
 10176  ** a table compatible with the table attached to the session by this function.
 10177  ** A table is considered compatible if it:
 10178  **
 10179  ** <ul>
 10180  **   <li> Has the same name,
 10181  **   <li> Has the same set of columns declared in the same order, and
 10182  **   <li> Has the same PRIMARY KEY definition.
 10183  ** </ul>
 10184  **
 10185  ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
 10186  ** are compatible but do not have any PRIMARY KEY columns, it is not an error
 10187  ** but no changes are added to the session object. As with other session
 10188  ** APIs, tables without PRIMARY KEYs are simply ignored.
 10189  **
 10190  ** This function adds a set of changes to the session object that could be
 10191  ** used to update the table in database zFrom (call this the "from-table") 
 10192  ** so that its content is the same as the table attached to the session 
 10193  ** object (call this the "to-table"). Specifically:
 10194  **
 10195  ** <ul>
 10196  **   <li> For each row (primary key) that exists in the to-table but not in 
 10197  **     the from-table, an INSERT record is added to the session object.
 10198  **
 10199  **   <li> For each row (primary key) that exists in the to-table but not in 
 10200  **     the from-table, a DELETE record is added to the session object.
 10201  **
 10202  **   <li> For each row (primary key) that exists in both tables, but features 
 10203  **     different non-PK values in each, an UPDATE record is added to the
 10204  **     session.  
 10205  ** </ul>
 10206  **
 10207  ** To clarify, if this function is called and then a changeset constructed
 10208  ** using [sqlite3session_changeset()], then after applying that changeset to 
 10209  ** database zFrom the contents of the two compatible tables would be 
 10210  ** identical.
 10211  **
 10212  ** It an error if database zFrom does not exist or does not contain the
 10213  ** required compatible table.
 10214  **
 10215  ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
 10216  ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
 10217  ** may be set to point to a buffer containing an English language error 
 10218  ** message. It is the responsibility of the caller to free this buffer using
 10219  ** sqlite3_free().
 10220  */
 10221  SQLITE_API int sqlite3session_diff(
 10222    sqlite3_session *pSession,
 10223    const char *zFromDb,
 10224    const char *zTbl,
 10225    char **pzErrMsg
 10226  );
 10227  
 10228  
 10229  /*
 10230  ** CAPI3REF: Generate A Patchset From A Session Object
 10231  **
 10232  ** The differences between a patchset and a changeset are that:
 10233  **
 10234  ** <ul>
 10235  **   <li> DELETE records consist of the primary key fields only. The 
 10236  **        original values of other fields are omitted.
 10237  **   <li> The original values of any modified fields are omitted from 
 10238  **        UPDATE records.
 10239  ** </ul>
 10240  **
 10241  ** A patchset blob may be used with up to date versions of all 
 10242  ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(), 
 10243  ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
 10244  ** attempting to use a patchset blob with old versions of the
 10245  ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error. 
 10246  **
 10247  ** Because the non-primary key "old.*" fields are omitted, no 
 10248  ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
 10249  ** is passed to the sqlite3changeset_apply() API. Other conflict types work
 10250  ** in the same way as for changesets.
 10251  **
 10252  ** Changes within a patchset are ordered in the same way as for changesets
 10253  ** generated by the sqlite3session_changeset() function (i.e. all changes for
 10254  ** a single table are grouped together, tables appear in the order in which
 10255  ** they were attached to the session object).
 10256  */
 10257  SQLITE_API int sqlite3session_patchset(
 10258    sqlite3_session *pSession,      /* Session object */
 10259    int *pnPatchset,                /* OUT: Size of buffer at *ppPatchset */
 10260    void **ppPatchset               /* OUT: Buffer containing patchset */
 10261  );
 10262  
 10263  /*
 10264  ** CAPI3REF: Test if a changeset has recorded any changes.
 10265  **
 10266  ** Return non-zero if no changes to attached tables have been recorded by 
 10267  ** the session object passed as the first argument. Otherwise, if one or 
 10268  ** more changes have been recorded, return zero.
 10269  **
 10270  ** Even if this function returns zero, it is possible that calling
 10271  ** [sqlite3session_changeset()] on the session handle may still return a
 10272  ** changeset that contains no changes. This can happen when a row in 
 10273  ** an attached table is modified and then later on the original values 
 10274  ** are restored. However, if this function returns non-zero, then it is
 10275  ** guaranteed that a call to sqlite3session_changeset() will return a 
 10276  ** changeset containing zero changes.
 10277  */
 10278  SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
 10279  
 10280  /*
 10281  ** CAPI3REF: Create An Iterator To Traverse A Changeset 
 10282  **
 10283  ** Create an iterator used to iterate through the contents of a changeset.
 10284  ** If successful, *pp is set to point to the iterator handle and SQLITE_OK
 10285  ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
 10286  ** SQLite error code is returned.
 10287  **
 10288  ** The following functions can be used to advance and query a changeset 
 10289  ** iterator created by this function:
 10290  **
 10291  ** <ul>
 10292  **   <li> [sqlite3changeset_next()]
 10293  **   <li> [sqlite3changeset_op()]
 10294  **   <li> [sqlite3changeset_new()]
 10295  **   <li> [sqlite3changeset_old()]
 10296  ** </ul>
 10297  **
 10298  ** It is the responsibility of the caller to eventually destroy the iterator
 10299  ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
 10300  ** changeset (pChangeset) must remain valid until after the iterator is
 10301  ** destroyed.
 10302  **
 10303  ** Assuming the changeset blob was created by one of the
 10304  ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
 10305  ** [sqlite3changeset_invert()] functions, all changes within the changeset 
 10306  ** that apply to a single table are grouped together. This means that when 
 10307  ** an application iterates through a changeset using an iterator created by 
 10308  ** this function, all changes that relate to a single table are visited 
 10309  ** consecutively. There is no chance that the iterator will visit a change 
 10310  ** the applies to table X, then one for table Y, and then later on visit 
 10311  ** another change for table X.
 10312  */
 10313  SQLITE_API int sqlite3changeset_start(
 10314    sqlite3_changeset_iter **pp,    /* OUT: New changeset iterator handle */
 10315    int nChangeset,                 /* Size of changeset blob in bytes */
 10316    void *pChangeset                /* Pointer to blob containing changeset */
 10317  );
 10318  
 10319  
 10320  /*
 10321  ** CAPI3REF: Advance A Changeset Iterator
 10322  **
 10323  ** This function may only be used with iterators created by function
 10324  ** [sqlite3changeset_start()]. If it is called on an iterator passed to
 10325  ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
 10326  ** is returned and the call has no effect.
 10327  **
 10328  ** Immediately after an iterator is created by sqlite3changeset_start(), it
 10329  ** does not point to any change in the changeset. Assuming the changeset
 10330  ** is not empty, the first call to this function advances the iterator to
 10331  ** point to the first change in the changeset. Each subsequent call advances
 10332  ** the iterator to point to the next change in the changeset (if any). If
 10333  ** no error occurs and the iterator points to a valid change after a call
 10334  ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned. 
 10335  ** Otherwise, if all changes in the changeset have already been visited,
 10336  ** SQLITE_DONE is returned.
 10337  **
 10338  ** If an error occurs, an SQLite error code is returned. Possible error 
 10339  ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or 
 10340  ** SQLITE_NOMEM.
 10341  */
 10342  SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
 10343  
 10344  /*
 10345  ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
 10346  **
 10347  ** The pIter argument passed to this function may either be an iterator
 10348  ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
 10349  ** created by [sqlite3changeset_start()]. In the latter case, the most recent
 10350  ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
 10351  ** is not the case, this function returns [SQLITE_MISUSE].
 10352  **
 10353  ** If argument pzTab is not NULL, then *pzTab is set to point to a
 10354  ** nul-terminated utf-8 encoded string containing the name of the table
 10355  ** affected by the current change. The buffer remains valid until either
 10356  ** sqlite3changeset_next() is called on the iterator or until the 
 10357  ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is 
 10358  ** set to the number of columns in the table affected by the change. If
 10359  ** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change
 10360  ** is an indirect change, or false (0) otherwise. See the documentation for
 10361  ** [sqlite3session_indirect()] for a description of direct and indirect
 10362  ** changes. Finally, if pOp is not NULL, then *pOp is set to one of 
 10363  ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the 
 10364  ** type of change that the iterator currently points to.
 10365  **
 10366  ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
 10367  ** SQLite error code is returned. The values of the output variables may not
 10368  ** be trusted in this case.
 10369  */
 10370  SQLITE_API int sqlite3changeset_op(
 10371    sqlite3_changeset_iter *pIter,  /* Iterator object */
 10372    const char **pzTab,             /* OUT: Pointer to table name */
 10373    int *pnCol,                     /* OUT: Number of columns in table */
 10374    int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */
 10375    int *pbIndirect                 /* OUT: True for an 'indirect' change */
 10376  );
 10377  
 10378  /*
 10379  ** CAPI3REF: Obtain The Primary Key Definition Of A Table
 10380  **
 10381  ** For each modified table, a changeset includes the following:
 10382  **
 10383  ** <ul>
 10384  **   <li> The number of columns in the table, and
 10385  **   <li> Which of those columns make up the tables PRIMARY KEY.
 10386  ** </ul>
 10387  **
 10388  ** This function is used to find which columns comprise the PRIMARY KEY of
 10389  ** the table modified by the change that iterator pIter currently points to.
 10390  ** If successful, *pabPK is set to point to an array of nCol entries, where
 10391  ** nCol is the number of columns in the table. Elements of *pabPK are set to
 10392  ** 0x01 if the corresponding column is part of the tables primary key, or
 10393  ** 0x00 if it is not.
 10394  **
 10395  ** If argument pnCol is not NULL, then *pnCol is set to the number of columns
 10396  ** in the table.
 10397  **
 10398  ** If this function is called when the iterator does not point to a valid
 10399  ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
 10400  ** SQLITE_OK is returned and the output variables populated as described
 10401  ** above.
 10402  */
 10403  SQLITE_API int sqlite3changeset_pk(
 10404    sqlite3_changeset_iter *pIter,  /* Iterator object */
 10405    unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */
 10406    int *pnCol                      /* OUT: Number of entries in output array */
 10407  );
 10408  
 10409  /*
 10410  ** CAPI3REF: Obtain old.* Values From A Changeset Iterator
 10411  **
 10412  ** The pIter argument passed to this function may either be an iterator
 10413  ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
 10414  ** created by [sqlite3changeset_start()]. In the latter case, the most recent
 10415  ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. 
 10416  ** Furthermore, it may only be called if the type of change that the iterator
 10417  ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
 10418  ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
 10419  **
 10420  ** Argument iVal must be greater than or equal to 0, and less than the number
 10421  ** of columns in the table affected by the current change. Otherwise,
 10422  ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
 10423  **
 10424  ** If successful, this function sets *ppValue to point to a protected
 10425  ** sqlite3_value object containing the iVal'th value from the vector of 
 10426  ** original row values stored as part of the UPDATE or DELETE change and
 10427  ** returns SQLITE_OK. The name of the function comes from the fact that this 
 10428  ** is similar to the "old.*" columns available to update or delete triggers.
 10429  **
 10430  ** If some other error occurs (e.g. an OOM condition), an SQLite error code
 10431  ** is returned and *ppValue is set to NULL.
 10432  */
 10433  SQLITE_API int sqlite3changeset_old(
 10434    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
 10435    int iVal,                       /* Column number */
 10436    sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */
 10437  );
 10438  
 10439  /*
 10440  ** CAPI3REF: Obtain new.* Values From A Changeset Iterator
 10441  **
 10442  ** The pIter argument passed to this function may either be an iterator
 10443  ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
 10444  ** created by [sqlite3changeset_start()]. In the latter case, the most recent
 10445  ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. 
 10446  ** Furthermore, it may only be called if the type of change that the iterator
 10447  ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
 10448  ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
 10449  **
 10450  ** Argument iVal must be greater than or equal to 0, and less than the number
 10451  ** of columns in the table affected by the current change. Otherwise,
 10452  ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
 10453  **
 10454  ** If successful, this function sets *ppValue to point to a protected
 10455  ** sqlite3_value object containing the iVal'th value from the vector of 
 10456  ** new row values stored as part of the UPDATE or INSERT change and
 10457  ** returns SQLITE_OK. If the change is an UPDATE and does not include
 10458  ** a new value for the requested column, *ppValue is set to NULL and 
 10459  ** SQLITE_OK returned. The name of the function comes from the fact that 
 10460  ** this is similar to the "new.*" columns available to update or delete 
 10461  ** triggers.
 10462  **
 10463  ** If some other error occurs (e.g. an OOM condition), an SQLite error code
 10464  ** is returned and *ppValue is set to NULL.
 10465  */
 10466  SQLITE_API int sqlite3changeset_new(
 10467    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
 10468    int iVal,                       /* Column number */
 10469    sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */
 10470  );
 10471  
 10472  /*
 10473  ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
 10474  **
 10475  ** This function should only be used with iterator objects passed to a
 10476  ** conflict-handler callback by [sqlite3changeset_apply()] with either
 10477  ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
 10478  ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
 10479  ** is set to NULL.
 10480  **
 10481  ** Argument iVal must be greater than or equal to 0, and less than the number
 10482  ** of columns in the table affected by the current change. Otherwise,
 10483  ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
 10484  **
 10485  ** If successful, this function sets *ppValue to point to a protected
 10486  ** sqlite3_value object containing the iVal'th value from the 
 10487  ** "conflicting row" associated with the current conflict-handler callback
 10488  ** and returns SQLITE_OK.
 10489  **
 10490  ** If some other error occurs (e.g. an OOM condition), an SQLite error code
 10491  ** is returned and *ppValue is set to NULL.
 10492  */
 10493  SQLITE_API int sqlite3changeset_conflict(
 10494    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
 10495    int iVal,                       /* Column number */
 10496    sqlite3_value **ppValue         /* OUT: Value from conflicting row */
 10497  );
 10498  
 10499  /*
 10500  ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
 10501  **
 10502  ** This function may only be called with an iterator passed to an
 10503  ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
 10504  ** it sets the output variable to the total number of known foreign key
 10505  ** violations in the destination database and returns SQLITE_OK.
 10506  **
 10507  ** In all other cases this function returns SQLITE_MISUSE.
 10508  */
 10509  SQLITE_API int sqlite3changeset_fk_conflicts(
 10510    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
 10511    int *pnOut                      /* OUT: Number of FK violations */
 10512  );
 10513  
 10514  
 10515  /*
 10516  ** CAPI3REF: Finalize A Changeset Iterator
 10517  **
 10518  ** This function is used to finalize an iterator allocated with
 10519  ** [sqlite3changeset_start()].
 10520  **
 10521  ** This function should only be called on iterators created using the
 10522  ** [sqlite3changeset_start()] function. If an application calls this
 10523  ** function with an iterator passed to a conflict-handler by
 10524  ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
 10525  ** call has no effect.
 10526  **
 10527  ** If an error was encountered within a call to an sqlite3changeset_xxx()
 10528  ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an 
 10529  ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
 10530  ** to that error is returned by this function. Otherwise, SQLITE_OK is
 10531  ** returned. This is to allow the following pattern (pseudo-code):
 10532  **
 10533  **   sqlite3changeset_start();
 10534  **   while( SQLITE_ROW==sqlite3changeset_next() ){
 10535  **     // Do something with change.
 10536  **   }
 10537  **   rc = sqlite3changeset_finalize();
 10538  **   if( rc!=SQLITE_OK ){
 10539  **     // An error has occurred 
 10540  **   }
 10541  */
 10542  SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
 10543  
 10544  /*
 10545  ** CAPI3REF: Invert A Changeset
 10546  **
 10547  ** This function is used to "invert" a changeset object. Applying an inverted
 10548  ** changeset to a database reverses the effects of applying the uninverted
 10549  ** changeset. Specifically:
 10550  **
 10551  ** <ul>
 10552  **   <li> Each DELETE change is changed to an INSERT, and
 10553  **   <li> Each INSERT change is changed to a DELETE, and
 10554  **   <li> For each UPDATE change, the old.* and new.* values are exchanged.
 10555  ** </ul>
 10556  **
 10557  ** This function does not change the order in which changes appear within
 10558  ** the changeset. It merely reverses the sense of each individual change.
 10559  **
 10560  ** If successful, a pointer to a buffer containing the inverted changeset
 10561  ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
 10562  ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
 10563  ** zeroed and an SQLite error code returned.
 10564  **
 10565  ** It is the responsibility of the caller to eventually call sqlite3_free()
 10566  ** on the *ppOut pointer to free the buffer allocation following a successful 
 10567  ** call to this function.
 10568  **
 10569  ** WARNING/TODO: This function currently assumes that the input is a valid
 10570  ** changeset. If it is not, the results are undefined.
 10571  */
 10572  SQLITE_API int sqlite3changeset_invert(
 10573    int nIn, const void *pIn,       /* Input changeset */
 10574    int *pnOut, void **ppOut        /* OUT: Inverse of input */
 10575  );
 10576  
 10577  /*
 10578  ** CAPI3REF: Concatenate Two Changeset Objects
 10579  **
 10580  ** This function is used to concatenate two changesets, A and B, into a 
 10581  ** single changeset. The result is a changeset equivalent to applying
 10582  ** changeset A followed by changeset B. 
 10583  **
 10584  ** This function combines the two input changesets using an 
 10585  ** sqlite3_changegroup object. Calling it produces similar results as the
 10586  ** following code fragment:
 10587  **
 10588  **   sqlite3_changegroup *pGrp;
 10589  **   rc = sqlite3_changegroup_new(&pGrp);
 10590  **   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
 10591  **   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
 10592  **   if( rc==SQLITE_OK ){
 10593  **     rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
 10594  **   }else{
 10595  **     *ppOut = 0;
 10596  **     *pnOut = 0;
 10597  **   }
 10598  **
 10599  ** Refer to the sqlite3_changegroup documentation below for details.
 10600  */
 10601  SQLITE_API int sqlite3changeset_concat(
 10602    int nA,                         /* Number of bytes in buffer pA */
 10603    void *pA,                       /* Pointer to buffer containing changeset A */
 10604    int nB,                         /* Number of bytes in buffer pB */
 10605    void *pB,                       /* Pointer to buffer containing changeset B */
 10606    int *pnOut,                     /* OUT: Number of bytes in output changeset */
 10607    void **ppOut                    /* OUT: Buffer containing output changeset */
 10608  );
 10609  
 10610  
 10611  /*
 10612  ** CAPI3REF: Changegroup Handle
 10613  */
 10614  typedef struct sqlite3_changegroup sqlite3_changegroup;
 10615  
 10616  /*
 10617  ** CAPI3REF: Create A New Changegroup Object
 10618  **
 10619  ** An sqlite3_changegroup object is used to combine two or more changesets
 10620  ** (or patchsets) into a single changeset (or patchset). A single changegroup
 10621  ** object may combine changesets or patchsets, but not both. The output is
 10622  ** always in the same format as the input.
 10623  **
 10624  ** If successful, this function returns SQLITE_OK and populates (*pp) with
 10625  ** a pointer to a new sqlite3_changegroup object before returning. The caller
 10626  ** should eventually free the returned object using a call to 
 10627  ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
 10628  ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
 10629  **
 10630  ** The usual usage pattern for an sqlite3_changegroup object is as follows:
 10631  **
 10632  ** <ul>
 10633  **   <li> It is created using a call to sqlite3changegroup_new().
 10634  **
 10635  **   <li> Zero or more changesets (or patchsets) are added to the object
 10636  **        by calling sqlite3changegroup_add().
 10637  **
 10638  **   <li> The result of combining all input changesets together is obtained 
 10639  **        by the application via a call to sqlite3changegroup_output().
 10640  **
 10641  **   <li> The object is deleted using a call to sqlite3changegroup_delete().
 10642  ** </ul>
 10643  **
 10644  ** Any number of calls to add() and output() may be made between the calls to
 10645  ** new() and delete(), and in any order.
 10646  **
 10647  ** As well as the regular sqlite3changegroup_add() and 
 10648  ** sqlite3changegroup_output() functions, also available are the streaming
 10649  ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
 10650  */
 10651  SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
 10652  
 10653  /*
 10654  ** CAPI3REF: Add A Changeset To A Changegroup
 10655  **
 10656  ** Add all changes within the changeset (or patchset) in buffer pData (size
 10657  ** nData bytes) to the changegroup. 
 10658  **
 10659  ** If the buffer contains a patchset, then all prior calls to this function
 10660  ** on the same changegroup object must also have specified patchsets. Or, if
 10661  ** the buffer contains a changeset, so must have the earlier calls to this
 10662  ** function. Otherwise, SQLITE_ERROR is returned and no changes are added
 10663  ** to the changegroup.
 10664  **
 10665  ** Rows within the changeset and changegroup are identified by the values in
 10666  ** their PRIMARY KEY columns. A change in the changeset is considered to
 10667  ** apply to the same row as a change already present in the changegroup if
 10668  ** the two rows have the same primary key.
 10669  **
 10670  ** Changes to rows that do not already appear in the changegroup are
 10671  ** simply copied into it. Or, if both the new changeset and the changegroup
 10672  ** contain changes that apply to a single row, the final contents of the
 10673  ** changegroup depends on the type of each change, as follows:
 10674  **
 10675  ** <table border=1 style="margin-left:8ex;margin-right:8ex">
 10676  **   <tr><th style="white-space:pre">Existing Change  </th>
 10677  **       <th style="white-space:pre">New Change       </th>
 10678  **       <th>Output Change
 10679  **   <tr><td>INSERT <td>INSERT <td>
 10680  **       The new change is ignored. This case does not occur if the new
 10681  **       changeset was recorded immediately after the changesets already
 10682  **       added to the changegroup.
 10683  **   <tr><td>INSERT <td>UPDATE <td>
 10684  **       The INSERT change remains in the changegroup. The values in the 
 10685  **       INSERT change are modified as if the row was inserted by the
 10686  **       existing change and then updated according to the new change.
 10687  **   <tr><td>INSERT <td>DELETE <td>
 10688  **       The existing INSERT is removed from the changegroup. The DELETE is
 10689  **       not added.
 10690  **   <tr><td>UPDATE <td>INSERT <td>
 10691  **       The new change is ignored. This case does not occur if the new
 10692  **       changeset was recorded immediately after the changesets already
 10693  **       added to the changegroup.
 10694  **   <tr><td>UPDATE <td>UPDATE <td>
 10695  **       The existing UPDATE remains within the changegroup. It is amended 
 10696  **       so that the accompanying values are as if the row was updated once 
 10697  **       by the existing change and then again by the new change.
 10698  **   <tr><td>UPDATE <td>DELETE <td>
 10699  **       The existing UPDATE is replaced by the new DELETE within the
 10700  **       changegroup.
 10701  **   <tr><td>DELETE <td>INSERT <td>
 10702  **       If one or more of the column values in the row inserted by the
 10703  **       new change differ from those in the row deleted by the existing 
 10704  **       change, the existing DELETE is replaced by an UPDATE within the
 10705  **       changegroup. Otherwise, if the inserted row is exactly the same 
 10706  **       as the deleted row, the existing DELETE is simply discarded.
 10707  **   <tr><td>DELETE <td>UPDATE <td>
 10708  **       The new change is ignored. This case does not occur if the new
 10709  **       changeset was recorded immediately after the changesets already
 10710  **       added to the changegroup.
 10711  **   <tr><td>DELETE <td>DELETE <td>
 10712  **       The new change is ignored. This case does not occur if the new
 10713  **       changeset was recorded immediately after the changesets already
 10714  **       added to the changegroup.
 10715  ** </table>
 10716  **
 10717  ** If the new changeset contains changes to a table that is already present
 10718  ** in the changegroup, then the number of columns and the position of the
 10719  ** primary key columns for the table must be consistent. If this is not the
 10720  ** case, this function fails with SQLITE_SCHEMA. If the input changeset
 10721  ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
 10722  ** returned. Or, if an out-of-memory condition occurs during processing, this
 10723  ** function returns SQLITE_NOMEM. In all cases, if an error occurs the
 10724  ** final contents of the changegroup is undefined.
 10725  **
 10726  ** If no error occurs, SQLITE_OK is returned.
 10727  */
 10728  SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
 10729  
 10730  /*
 10731  ** CAPI3REF: Obtain A Composite Changeset From A Changegroup
 10732  **
 10733  ** Obtain a buffer containing a changeset (or patchset) representing the
 10734  ** current contents of the changegroup. If the inputs to the changegroup
 10735  ** were themselves changesets, the output is a changeset. Or, if the
 10736  ** inputs were patchsets, the output is also a patchset.
 10737  **
 10738  ** As with the output of the sqlite3session_changeset() and
 10739  ** sqlite3session_patchset() functions, all changes related to a single
 10740  ** table are grouped together in the output of this function. Tables appear
 10741  ** in the same order as for the very first changeset added to the changegroup.
 10742  ** If the second or subsequent changesets added to the changegroup contain
 10743  ** changes for tables that do not appear in the first changeset, they are
 10744  ** appended onto the end of the output changeset, again in the order in
 10745  ** which they are first encountered.
 10746  **
 10747  ** If an error occurs, an SQLite error code is returned and the output
 10748  ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
 10749  ** is returned and the output variables are set to the size of and a 
 10750  ** pointer to the output buffer, respectively. In this case it is the
 10751  ** responsibility of the caller to eventually free the buffer using a
 10752  ** call to sqlite3_free().
 10753  */
 10754  SQLITE_API int sqlite3changegroup_output(
 10755    sqlite3_changegroup*,
 10756    int *pnData,                    /* OUT: Size of output buffer in bytes */
 10757    void **ppData                   /* OUT: Pointer to output buffer */
 10758  );
 10759  
 10760  /*
 10761  ** CAPI3REF: Delete A Changegroup Object
 10762  */
 10763  SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
 10764  
 10765  /*
 10766  ** CAPI3REF: Apply A Changeset To A Database
 10767  **
 10768  ** Apply a changeset to a database. This function attempts to update the
 10769  ** "main" database attached to handle db with the changes found in the
 10770  ** changeset passed via the second and third arguments.
 10771  **
 10772  ** The fourth argument (xFilter) passed to this function is the "filter
 10773  ** callback". If it is not NULL, then for each table affected by at least one
 10774  ** change in the changeset, the filter callback is invoked with
 10775  ** the table name as the second argument, and a copy of the context pointer
 10776  ** passed as the sixth argument to this function as the first. If the "filter
 10777  ** callback" returns zero, then no attempt is made to apply any changes to 
 10778  ** the table. Otherwise, if the return value is non-zero or the xFilter
 10779  ** argument to this function is NULL, all changes related to the table are
 10780  ** attempted.
 10781  **
 10782  ** For each table that is not excluded by the filter callback, this function 
 10783  ** tests that the target database contains a compatible table. A table is 
 10784  ** considered compatible if all of the following are true:
 10785  **
 10786  ** <ul>
 10787  **   <li> The table has the same name as the name recorded in the 
 10788  **        changeset, and
 10789  **   <li> The table has at least as many columns as recorded in the 
 10790  **        changeset, and
 10791  **   <li> The table has primary key columns in the same position as 
 10792  **        recorded in the changeset.
 10793  ** </ul>
 10794  **
 10795  ** If there is no compatible table, it is not an error, but none of the
 10796  ** changes associated with the table are applied. A warning message is issued
 10797  ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
 10798  ** one such warning is issued for each table in the changeset.
 10799  **
 10800  ** For each change for which there is a compatible table, an attempt is made 
 10801  ** to modify the table contents according to the UPDATE, INSERT or DELETE 
 10802  ** change. If a change cannot be applied cleanly, the conflict handler 
 10803  ** function passed as the fifth argument to sqlite3changeset_apply() may be 
 10804  ** invoked. A description of exactly when the conflict handler is invoked for 
 10805  ** each type of change is below.
 10806  **
 10807  ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
 10808  ** of passing anything other than a valid function pointer as the xConflict
 10809  ** argument are undefined.
 10810  **
 10811  ** Each time the conflict handler function is invoked, it must return one
 10812  ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or 
 10813  ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
 10814  ** if the second argument passed to the conflict handler is either
 10815  ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
 10816  ** returns an illegal value, any changes already made are rolled back and
 10817  ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different 
 10818  ** actions are taken by sqlite3changeset_apply() depending on the value
 10819  ** returned by each invocation of the conflict-handler function. Refer to
 10820  ** the documentation for the three 
 10821  ** [SQLITE_CHANGESET_OMIT|available return values] for details.
 10822  **
 10823  ** <dl>
 10824  ** <dt>DELETE Changes<dd>
 10825  **   For each DELETE change, this function checks if the target database 
 10826  **   contains a row with the same primary key value (or values) as the 
 10827  **   original row values stored in the changeset. If it does, and the values 
 10828  **   stored in all non-primary key columns also match the values stored in 
 10829  **   the changeset the row is deleted from the target database.
 10830  **
 10831  **   If a row with matching primary key values is found, but one or more of
 10832  **   the non-primary key fields contains a value different from the original
 10833  **   row value stored in the changeset, the conflict-handler function is
 10834  **   invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the
 10835  **   database table has more columns than are recorded in the changeset,
 10836  **   only the values of those non-primary key fields are compared against
 10837  **   the current database contents - any trailing database table columns
 10838  **   are ignored.
 10839  **
 10840  **   If no row with matching primary key values is found in the database,
 10841  **   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
 10842  **   passed as the second argument.
 10843  **
 10844  **   If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
 10845  **   (which can only happen if a foreign key constraint is violated), the
 10846  **   conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
 10847  **   passed as the second argument. This includes the case where the DELETE
 10848  **   operation is attempted because an earlier call to the conflict handler
 10849  **   function returned [SQLITE_CHANGESET_REPLACE].
 10850  **
 10851  ** <dt>INSERT Changes<dd>
 10852  **   For each INSERT change, an attempt is made to insert the new row into
 10853  **   the database. If the changeset row contains fewer fields than the
 10854  **   database table, the trailing fields are populated with their default
 10855  **   values.
 10856  **
 10857  **   If the attempt to insert the row fails because the database already 
 10858  **   contains a row with the same primary key values, the conflict handler
 10859  **   function is invoked with the second argument set to 
 10860  **   [SQLITE_CHANGESET_CONFLICT].
 10861  **
 10862  **   If the attempt to insert the row fails because of some other constraint
 10863  **   violation (e.g. NOT NULL or UNIQUE), the conflict handler function is 
 10864  **   invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
 10865  **   This includes the case where the INSERT operation is re-attempted because 
 10866  **   an earlier call to the conflict handler function returned 
 10867  **   [SQLITE_CHANGESET_REPLACE].
 10868  **
 10869  ** <dt>UPDATE Changes<dd>
 10870  **   For each UPDATE change, this function checks if the target database 
 10871  **   contains a row with the same primary key value (or values) as the 
 10872  **   original row values stored in the changeset. If it does, and the values 
 10873  **   stored in all modified non-primary key columns also match the values
 10874  **   stored in the changeset the row is updated within the target database.
 10875  **
 10876  **   If a row with matching primary key values is found, but one or more of
 10877  **   the modified non-primary key fields contains a value different from an
 10878  **   original row value stored in the changeset, the conflict-handler function
 10879  **   is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
 10880  **   UPDATE changes only contain values for non-primary key fields that are
 10881  **   to be modified, only those fields need to match the original values to
 10882  **   avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
 10883  **
 10884  **   If no row with matching primary key values is found in the database,
 10885  **   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
 10886  **   passed as the second argument.
 10887  **
 10888  **   If the UPDATE operation is attempted, but SQLite returns 
 10889  **   SQLITE_CONSTRAINT, the conflict-handler function is invoked with 
 10890  **   [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
 10891  **   This includes the case where the UPDATE operation is attempted after 
 10892  **   an earlier call to the conflict handler function returned
 10893  **   [SQLITE_CHANGESET_REPLACE].  
 10894  ** </dl>
 10895  **
 10896  ** It is safe to execute SQL statements, including those that write to the
 10897  ** table that the callback related to, from within the xConflict callback.
 10898  ** This can be used to further customize the applications conflict
 10899  ** resolution strategy.
 10900  **
 10901  ** All changes made by this function are enclosed in a savepoint transaction.
 10902  ** If any other error (aside from a constraint failure when attempting to
 10903  ** write to the target database) occurs, then the savepoint transaction is
 10904  ** rolled back, restoring the target database to its original state, and an 
 10905  ** SQLite error code returned.
 10906  */
 10907  SQLITE_API int sqlite3changeset_apply(
 10908    sqlite3 *db,                    /* Apply change to "main" db of this handle */
 10909    int nChangeset,                 /* Size of changeset in bytes */
 10910    void *pChangeset,               /* Changeset blob */
 10911    int(*xFilter)(
 10912      void *pCtx,                   /* Copy of sixth arg to _apply() */
 10913      const char *zTab              /* Table name */
 10914    ),
 10915    int(*xConflict)(
 10916      void *pCtx,                   /* Copy of sixth arg to _apply() */
 10917      int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
 10918      sqlite3_changeset_iter *p     /* Handle describing change and conflict */
 10919    ),
 10920    void *pCtx                      /* First argument passed to xConflict */
 10921  );
 10922  
 10923  /* 
 10924  ** CAPI3REF: Constants Passed To The Conflict Handler
 10925  **
 10926  ** Values that may be passed as the second argument to a conflict-handler.
 10927  **
 10928  ** <dl>
 10929  ** <dt>SQLITE_CHANGESET_DATA<dd>
 10930  **   The conflict handler is invoked with CHANGESET_DATA as the second argument
 10931  **   when processing a DELETE or UPDATE change if a row with the required
 10932  **   PRIMARY KEY fields is present in the database, but one or more other 
 10933  **   (non primary-key) fields modified by the update do not contain the 
 10934  **   expected "before" values.
 10935  ** 
 10936  **   The conflicting row, in this case, is the database row with the matching
 10937  **   primary key.
 10938  ** 
 10939  ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
 10940  **   The conflict handler is invoked with CHANGESET_NOTFOUND as the second
 10941  **   argument when processing a DELETE or UPDATE change if a row with the
 10942  **   required PRIMARY KEY fields is not present in the database.
 10943  ** 
 10944  **   There is no conflicting row in this case. The results of invoking the
 10945  **   sqlite3changeset_conflict() API are undefined.
 10946  ** 
 10947  ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
 10948  **   CHANGESET_CONFLICT is passed as the second argument to the conflict
 10949  **   handler while processing an INSERT change if the operation would result 
 10950  **   in duplicate primary key values.
 10951  ** 
 10952  **   The conflicting row in this case is the database row with the matching
 10953  **   primary key.
 10954  **
 10955  ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
 10956  **   If foreign key handling is enabled, and applying a changeset leaves the
 10957  **   database in a state containing foreign key violations, the conflict 
 10958  **   handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
 10959  **   exactly once before the changeset is committed. If the conflict handler
 10960  **   returns CHANGESET_OMIT, the changes, including those that caused the
 10961  **   foreign key constraint violation, are committed. Or, if it returns
 10962  **   CHANGESET_ABORT, the changeset is rolled back.
 10963  **
 10964  **   No current or conflicting row information is provided. The only function
 10965  **   it is possible to call on the supplied sqlite3_changeset_iter handle
 10966  **   is sqlite3changeset_fk_conflicts().
 10967  ** 
 10968  ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
 10969  **   If any other constraint violation occurs while applying a change (i.e. 
 10970  **   a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is 
 10971  **   invoked with CHANGESET_CONSTRAINT as the second argument.
 10972  ** 
 10973  **   There is no conflicting row in this case. The results of invoking the
 10974  **   sqlite3changeset_conflict() API are undefined.
 10975  **
 10976  ** </dl>
 10977  */
 10978  #define SQLITE_CHANGESET_DATA        1
 10979  #define SQLITE_CHANGESET_NOTFOUND    2
 10980  #define SQLITE_CHANGESET_CONFLICT    3
 10981  #define SQLITE_CHANGESET_CONSTRAINT  4
 10982  #define SQLITE_CHANGESET_FOREIGN_KEY 5
 10983  
 10984  /* 
 10985  ** CAPI3REF: Constants Returned By The Conflict Handler
 10986  **
 10987  ** A conflict handler callback must return one of the following three values.
 10988  **
 10989  ** <dl>
 10990  ** <dt>SQLITE_CHANGESET_OMIT<dd>
 10991  **   If a conflict handler returns this value no special action is taken. The
 10992  **   change that caused the conflict is not applied. The session module 
 10993  **   continues to the next change in the changeset.
 10994  **
 10995  ** <dt>SQLITE_CHANGESET_REPLACE<dd>
 10996  **   This value may only be returned if the second argument to the conflict
 10997  **   handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
 10998  **   is not the case, any changes applied so far are rolled back and the 
 10999  **   call to sqlite3changeset_apply() returns SQLITE_MISUSE.
 11000  **
 11001  **   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
 11002  **   handler, then the conflicting row is either updated or deleted, depending
 11003  **   on the type of change.
 11004  **
 11005  **   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
 11006  **   handler, then the conflicting row is removed from the database and a
 11007  **   second attempt to apply the change is made. If this second attempt fails,
 11008  **   the original row is restored to the database before continuing.
 11009  **
 11010  ** <dt>SQLITE_CHANGESET_ABORT<dd>
 11011  **   If this value is returned, any changes applied so far are rolled back 
 11012  **   and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
 11013  ** </dl>
 11014  */
 11015  #define SQLITE_CHANGESET_OMIT       0
 11016  #define SQLITE_CHANGESET_REPLACE    1
 11017  #define SQLITE_CHANGESET_ABORT      2
 11018  
 11019  /*
 11020  ** CAPI3REF: Streaming Versions of API functions.
 11021  **
 11022  ** The six streaming API xxx_strm() functions serve similar purposes to the 
 11023  ** corresponding non-streaming API functions:
 11024  **
 11025  ** <table border=1 style="margin-left:8ex;margin-right:8ex">
 11026  **   <tr><th>Streaming function<th>Non-streaming equivalent</th>
 11027  **   <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply] 
 11028  **   <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat] 
 11029  **   <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert] 
 11030  **   <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start] 
 11031  **   <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset] 
 11032  **   <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset] 
 11033  ** </table>
 11034  **
 11035  ** Non-streaming functions that accept changesets (or patchsets) as input
 11036  ** require that the entire changeset be stored in a single buffer in memory. 
 11037  ** Similarly, those that return a changeset or patchset do so by returning 
 11038  ** a pointer to a single large buffer allocated using sqlite3_malloc(). 
 11039  ** Normally this is convenient. However, if an application running in a 
 11040  ** low-memory environment is required to handle very large changesets, the
 11041  ** large contiguous memory allocations required can become onerous.
 11042  **
 11043  ** In order to avoid this problem, instead of a single large buffer, input
 11044  ** is passed to a streaming API functions by way of a callback function that
 11045  ** the sessions module invokes to incrementally request input data as it is
 11046  ** required. In all cases, a pair of API function parameters such as
 11047  **
 11048  **  <pre>
 11049  **  &nbsp;     int nChangeset,
 11050  **  &nbsp;     void *pChangeset,
 11051  **  </pre>
 11052  **
 11053  ** Is replaced by:
 11054  **
 11055  **  <pre>
 11056  **  &nbsp;     int (*xInput)(void *pIn, void *pData, int *pnData),
 11057  **  &nbsp;     void *pIn,
 11058  **  </pre>
 11059  **
 11060  ** Each time the xInput callback is invoked by the sessions module, the first
 11061  ** argument passed is a copy of the supplied pIn context pointer. The second 
 11062  ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no 
 11063  ** error occurs the xInput method should copy up to (*pnData) bytes of data 
 11064  ** into the buffer and set (*pnData) to the actual number of bytes copied 
 11065  ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData) 
 11066  ** should be set to zero to indicate this. Or, if an error occurs, an SQLite 
 11067  ** error code should be returned. In all cases, if an xInput callback returns
 11068  ** an error, all processing is abandoned and the streaming API function
 11069  ** returns a copy of the error code to the caller.
 11070  **
 11071  ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
 11072  ** invoked by the sessions module at any point during the lifetime of the
 11073  ** iterator. If such an xInput callback returns an error, the iterator enters
 11074  ** an error state, whereby all subsequent calls to iterator functions 
 11075  ** immediately fail with the same error code as returned by xInput.
 11076  **
 11077  ** Similarly, streaming API functions that return changesets (or patchsets)
 11078  ** return them in chunks by way of a callback function instead of via a
 11079  ** pointer to a single large buffer. In this case, a pair of parameters such
 11080  ** as:
 11081  **
 11082  **  <pre>
 11083  **  &nbsp;     int *pnChangeset,
 11084  **  &nbsp;     void **ppChangeset,
 11085  **  </pre>
 11086  **
 11087  ** Is replaced by:
 11088  **
 11089  **  <pre>
 11090  **  &nbsp;     int (*xOutput)(void *pOut, const void *pData, int nData),
 11091  **  &nbsp;     void *pOut
 11092  **  </pre>
 11093  **
 11094  ** The xOutput callback is invoked zero or more times to return data to
 11095  ** the application. The first parameter passed to each call is a copy of the
 11096  ** pOut pointer supplied by the application. The second parameter, pData,
 11097  ** points to a buffer nData bytes in size containing the chunk of output
 11098  ** data being returned. If the xOutput callback successfully processes the
 11099  ** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
 11100  ** it should return some other SQLite error code. In this case processing
 11101  ** is immediately abandoned and the streaming API function returns a copy
 11102  ** of the xOutput error code to the application.
 11103  **
 11104  ** The sessions module never invokes an xOutput callback with the third 
 11105  ** parameter set to a value less than or equal to zero. Other than this,
 11106  ** no guarantees are made as to the size of the chunks of data returned.
 11107  */
 11108  SQLITE_API int sqlite3changeset_apply_strm(
 11109    sqlite3 *db,                    /* Apply change to "main" db of this handle */
 11110    int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
 11111    void *pIn,                                          /* First arg for xInput */
 11112    int(*xFilter)(
 11113      void *pCtx,                   /* Copy of sixth arg to _apply() */
 11114      const char *zTab              /* Table name */
 11115    ),
 11116    int(*xConflict)(
 11117      void *pCtx,                   /* Copy of sixth arg to _apply() */
 11118      int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
 11119      sqlite3_changeset_iter *p     /* Handle describing change and conflict */
 11120    ),
 11121    void *pCtx                      /* First argument passed to xConflict */
 11122  );
 11123  SQLITE_API int sqlite3changeset_concat_strm(
 11124    int (*xInputA)(void *pIn, void *pData, int *pnData),
 11125    void *pInA,
 11126    int (*xInputB)(void *pIn, void *pData, int *pnData),
 11127    void *pInB,
 11128    int (*xOutput)(void *pOut, const void *pData, int nData),
 11129    void *pOut
 11130  );
 11131  SQLITE_API int sqlite3changeset_invert_strm(
 11132    int (*xInput)(void *pIn, void *pData, int *pnData),
 11133    void *pIn,
 11134    int (*xOutput)(void *pOut, const void *pData, int nData),
 11135    void *pOut
 11136  );
 11137  SQLITE_API int sqlite3changeset_start_strm(
 11138    sqlite3_changeset_iter **pp,
 11139    int (*xInput)(void *pIn, void *pData, int *pnData),
 11140    void *pIn
 11141  );
 11142  SQLITE_API int sqlite3session_changeset_strm(
 11143    sqlite3_session *pSession,
 11144    int (*xOutput)(void *pOut, const void *pData, int nData),
 11145    void *pOut
 11146  );
 11147  SQLITE_API int sqlite3session_patchset_strm(
 11148    sqlite3_session *pSession,
 11149    int (*xOutput)(void *pOut, const void *pData, int nData),
 11150    void *pOut
 11151  );
 11152  SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*, 
 11153      int (*xInput)(void *pIn, void *pData, int *pnData),
 11154      void *pIn
 11155  );
 11156  SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
 11157      int (*xOutput)(void *pOut, const void *pData, int nData), 
 11158      void *pOut
 11159  );
 11160  
 11161  
 11162  /*
 11163  ** Make sure we can call this stuff from C++.
 11164  */
 11165  #if 0
 11166  }
 11167  #endif
 11168  
 11169  #endif  /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
 11170  
 11171  /******** End of sqlite3session.h *********/
 11172  /******** Begin file fts5.h *********/
 11173  /*
 11174  ** 2014 May 31
 11175  **
 11176  ** The author disclaims copyright to this source code.  In place of
 11177  ** a legal notice, here is a blessing:
 11178  **
 11179  **    May you do good and not evil.
 11180  **    May you find forgiveness for yourself and forgive others.
 11181  **    May you share freely, never taking more than you give.
 11182  **
 11183  ******************************************************************************
 11184  **
 11185  ** Interfaces to extend FTS5. Using the interfaces defined in this file, 
 11186  ** FTS5 may be extended with:
 11187  **
 11188  **     * custom tokenizers, and
 11189  **     * custom auxiliary functions.
 11190  */
 11191  
 11192  
 11193  #ifndef _FTS5_H
 11194  #define _FTS5_H
 11195  
 11196  
 11197  #if 0
 11198  extern "C" {
 11199  #endif
 11200  
 11201  /*************************************************************************
 11202  ** CUSTOM AUXILIARY FUNCTIONS
 11203  **
 11204  ** Virtual table implementations may overload SQL functions by implementing
 11205  ** the sqlite3_module.xFindFunction() method.
 11206  */
 11207  
 11208  typedef struct Fts5ExtensionApi Fts5ExtensionApi;
 11209  typedef struct Fts5Context Fts5Context;
 11210  typedef struct Fts5PhraseIter Fts5PhraseIter;
 11211  
 11212  typedef void (*fts5_extension_function)(
 11213    const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
 11214    Fts5Context *pFts,              /* First arg to pass to pApi functions */
 11215    sqlite3_context *pCtx,          /* Context for returning result/error */
 11216    int nVal,                       /* Number of values in apVal[] array */
 11217    sqlite3_value **apVal           /* Array of trailing arguments */
 11218  );
 11219  
 11220  struct Fts5PhraseIter {
 11221    const unsigned char *a;
 11222    const unsigned char *b;
 11223  };
 11224  
 11225  /*
 11226  ** EXTENSION API FUNCTIONS
 11227  **
 11228  ** xUserData(pFts):
 11229  **   Return a copy of the context pointer the extension function was 
 11230  **   registered with.
 11231  **
 11232  ** xColumnTotalSize(pFts, iCol, pnToken):
 11233  **   If parameter iCol is less than zero, set output variable *pnToken
 11234  **   to the total number of tokens in the FTS5 table. Or, if iCol is
 11235  **   non-negative but less than the number of columns in the table, return
 11236  **   the total number of tokens in column iCol, considering all rows in 
 11237  **   the FTS5 table.
 11238  **
 11239  **   If parameter iCol is greater than or equal to the number of columns
 11240  **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
 11241  **   an OOM condition or IO error), an appropriate SQLite error code is 
 11242  **   returned.
 11243  **
 11244  ** xColumnCount(pFts):
 11245  **   Return the number of columns in the table.
 11246  **
 11247  ** xColumnSize(pFts, iCol, pnToken):
 11248  **   If parameter iCol is less than zero, set output variable *pnToken
 11249  **   to the total number of tokens in the current row. Or, if iCol is
 11250  **   non-negative but less than the number of columns in the table, set
 11251  **   *pnToken to the number of tokens in column iCol of the current row.
 11252  **
 11253  **   If parameter iCol is greater than or equal to the number of columns
 11254  **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
 11255  **   an OOM condition or IO error), an appropriate SQLite error code is 
 11256  **   returned.
 11257  **
 11258  **   This function may be quite inefficient if used with an FTS5 table
 11259  **   created with the "columnsize=0" option.
 11260  **
 11261  ** xColumnText:
 11262  **   This function attempts to retrieve the text of column iCol of the
 11263  **   current document. If successful, (*pz) is set to point to a buffer
 11264  **   containing the text in utf-8 encoding, (*pn) is set to the size in bytes
 11265  **   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
 11266  **   if an error occurs, an SQLite error code is returned and the final values
 11267  **   of (*pz) and (*pn) are undefined.
 11268  **
 11269  ** xPhraseCount:
 11270  **   Returns the number of phrases in the current query expression.
 11271  **
 11272  ** xPhraseSize:
 11273  **   Returns the number of tokens in phrase iPhrase of the query. Phrases
 11274  **   are numbered starting from zero.
 11275  **
 11276  ** xInstCount:
 11277  **   Set *pnInst to the total number of occurrences of all phrases within
 11278  **   the query within the current row. Return SQLITE_OK if successful, or
 11279  **   an error code (i.e. SQLITE_NOMEM) if an error occurs.
 11280  **
 11281  **   This API can be quite slow if used with an FTS5 table created with the
 11282  **   "detail=none" or "detail=column" option. If the FTS5 table is created 
 11283  **   with either "detail=none" or "detail=column" and "content=" option 
 11284  **   (i.e. if it is a contentless table), then this API always returns 0.
 11285  **
 11286  ** xInst:
 11287  **   Query for the details of phrase match iIdx within the current row.
 11288  **   Phrase matches are numbered starting from zero, so the iIdx argument
 11289  **   should be greater than or equal to zero and smaller than the value
 11290  **   output by xInstCount().
 11291  **
 11292  **   Usually, output parameter *piPhrase is set to the phrase number, *piCol
 11293  **   to the column in which it occurs and *piOff the token offset of the
 11294  **   first token of the phrase. The exception is if the table was created
 11295  **   with the offsets=0 option specified. In this case *piOff is always
 11296  **   set to -1.
 11297  **
 11298  **   Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM) 
 11299  **   if an error occurs.
 11300  **
 11301  **   This API can be quite slow if used with an FTS5 table created with the
 11302  **   "detail=none" or "detail=column" option. 
 11303  **
 11304  ** xRowid:
 11305  **   Returns the rowid of the current row.
 11306  **
 11307  ** xTokenize:
 11308  **   Tokenize text using the tokenizer belonging to the FTS5 table.
 11309  **
 11310  ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
 11311  **   This API function is used to query the FTS table for phrase iPhrase
 11312  **   of the current query. Specifically, a query equivalent to:
 11313  **
 11314  **       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
 11315  **
 11316  **   with $p set to a phrase equivalent to the phrase iPhrase of the
 11317  **   current query is executed. Any column filter that applies to
 11318  **   phrase iPhrase of the current query is included in $p. For each 
 11319  **   row visited, the callback function passed as the fourth argument 
 11320  **   is invoked. The context and API objects passed to the callback 
 11321  **   function may be used to access the properties of each matched row.
 11322  **   Invoking Api.xUserData() returns a copy of the pointer passed as 
 11323  **   the third argument to pUserData.
 11324  **
 11325  **   If the callback function returns any value other than SQLITE_OK, the
 11326  **   query is abandoned and the xQueryPhrase function returns immediately.
 11327  **   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
 11328  **   Otherwise, the error code is propagated upwards.
 11329  **
 11330  **   If the query runs to completion without incident, SQLITE_OK is returned.
 11331  **   Or, if some error occurs before the query completes or is aborted by
 11332  **   the callback, an SQLite error code is returned.
 11333  **
 11334  **
 11335  ** xSetAuxdata(pFts5, pAux, xDelete)
 11336  **
 11337  **   Save the pointer passed as the second argument as the extension functions 
 11338  **   "auxiliary data". The pointer may then be retrieved by the current or any
 11339  **   future invocation of the same fts5 extension function made as part of
 11340  **   of the same MATCH query using the xGetAuxdata() API.
 11341  **
 11342  **   Each extension function is allocated a single auxiliary data slot for
 11343  **   each FTS query (MATCH expression). If the extension function is invoked 
 11344  **   more than once for a single FTS query, then all invocations share a 
 11345  **   single auxiliary data context.
 11346  **
 11347  **   If there is already an auxiliary data pointer when this function is
 11348  **   invoked, then it is replaced by the new pointer. If an xDelete callback
 11349  **   was specified along with the original pointer, it is invoked at this
 11350  **   point.
 11351  **
 11352  **   The xDelete callback, if one is specified, is also invoked on the
 11353  **   auxiliary data pointer after the FTS5 query has finished.
 11354  **
 11355  **   If an error (e.g. an OOM condition) occurs within this function, an
 11356  **   the auxiliary data is set to NULL and an error code returned. If the
 11357  **   xDelete parameter was not NULL, it is invoked on the auxiliary data
 11358  **   pointer before returning.
 11359  **
 11360  **
 11361  ** xGetAuxdata(pFts5, bClear)
 11362  **
 11363  **   Returns the current auxiliary data pointer for the fts5 extension 
 11364  **   function. See the xSetAuxdata() method for details.
 11365  **
 11366  **   If the bClear argument is non-zero, then the auxiliary data is cleared
 11367  **   (set to NULL) before this function returns. In this case the xDelete,
 11368  **   if any, is not invoked.
 11369  **
 11370  **
 11371  ** xRowCount(pFts5, pnRow)
 11372  **
 11373  **   This function is used to retrieve the total number of rows in the table.
 11374  **   In other words, the same value that would be returned by:
 11375  **
 11376  **        SELECT count(*) FROM ftstable;
 11377  **
 11378  ** xPhraseFirst()
 11379  **   This function is used, along with type Fts5PhraseIter and the xPhraseNext
 11380  **   method, to iterate through all instances of a single query phrase within
 11381  **   the current row. This is the same information as is accessible via the
 11382  **   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
 11383  **   to use, this API may be faster under some circumstances. To iterate 
 11384  **   through instances of phrase iPhrase, use the following code:
 11385  **
 11386  **       Fts5PhraseIter iter;
 11387  **       int iCol, iOff;
 11388  **       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
 11389  **           iCol>=0;
 11390  **           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
 11391  **       ){
 11392  **         // An instance of phrase iPhrase at offset iOff of column iCol
 11393  **       }
 11394  **
 11395  **   The Fts5PhraseIter structure is defined above. Applications should not
 11396  **   modify this structure directly - it should only be used as shown above
 11397  **   with the xPhraseFirst() and xPhraseNext() API methods (and by
 11398  **   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
 11399  **
 11400  **   This API can be quite slow if used with an FTS5 table created with the
 11401  **   "detail=none" or "detail=column" option. If the FTS5 table is created 
 11402  **   with either "detail=none" or "detail=column" and "content=" option 
 11403  **   (i.e. if it is a contentless table), then this API always iterates
 11404  **   through an empty set (all calls to xPhraseFirst() set iCol to -1).
 11405  **
 11406  ** xPhraseNext()
 11407  **   See xPhraseFirst above.
 11408  **
 11409  ** xPhraseFirstColumn()
 11410  **   This function and xPhraseNextColumn() are similar to the xPhraseFirst()
 11411  **   and xPhraseNext() APIs described above. The difference is that instead
 11412  **   of iterating through all instances of a phrase in the current row, these
 11413  **   APIs are used to iterate through the set of columns in the current row
 11414  **   that contain one or more instances of a specified phrase. For example:
 11415  **
 11416  **       Fts5PhraseIter iter;
 11417  **       int iCol;
 11418  **       for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
 11419  **           iCol>=0;
 11420  **           pApi->xPhraseNextColumn(pFts, &iter, &iCol)
 11421  **       ){
 11422  **         // Column iCol contains at least one instance of phrase iPhrase
 11423  **       }
 11424  **
 11425  **   This API can be quite slow if used with an FTS5 table created with the
 11426  **   "detail=none" option. If the FTS5 table is created with either 
 11427  **   "detail=none" "content=" option (i.e. if it is a contentless table), 
 11428  **   then this API always iterates through an empty set (all calls to 
 11429  **   xPhraseFirstColumn() set iCol to -1).
 11430  **
 11431  **   The information accessed using this API and its companion
 11432  **   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
 11433  **   (or xInst/xInstCount). The chief advantage of this API is that it is
 11434  **   significantly more efficient than those alternatives when used with
 11435  **   "detail=column" tables.  
 11436  **
 11437  ** xPhraseNextColumn()
 11438  **   See xPhraseFirstColumn above.
 11439  */
 11440  struct Fts5ExtensionApi {
 11441    int iVersion;                   /* Currently always set to 3 */
 11442  
 11443    void *(*xUserData)(Fts5Context*);
 11444  
 11445    int (*xColumnCount)(Fts5Context*);
 11446    int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
 11447    int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
 11448  
 11449    int (*xTokenize)(Fts5Context*, 
 11450      const char *pText, int nText, /* Text to tokenize */
 11451      void *pCtx,                   /* Context passed to xToken() */
 11452      int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
 11453    );
 11454  
 11455    int (*xPhraseCount)(Fts5Context*);
 11456    int (*xPhraseSize)(Fts5Context*, int iPhrase);
 11457  
 11458    int (*xInstCount)(Fts5Context*, int *pnInst);
 11459    int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
 11460  
 11461    sqlite3_int64 (*xRowid)(Fts5Context*);
 11462    int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
 11463    int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
 11464  
 11465    int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
 11466      int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
 11467    );
 11468    int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
 11469    void *(*xGetAuxdata)(Fts5Context*, int bClear);
 11470  
 11471    int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
 11472    void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
 11473  
 11474    int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
 11475    void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
 11476  };
 11477  
 11478  /* 
 11479  ** CUSTOM AUXILIARY FUNCTIONS
 11480  *************************************************************************/
 11481  
 11482  /*************************************************************************
 11483  ** CUSTOM TOKENIZERS
 11484  **
 11485  ** Applications may also register custom tokenizer types. A tokenizer 
 11486  ** is registered by providing fts5 with a populated instance of the 
 11487  ** following structure. All structure methods must be defined, setting
 11488  ** any member of the fts5_tokenizer struct to NULL leads to undefined
 11489  ** behaviour. The structure methods are expected to function as follows:
 11490  **
 11491  ** xCreate:
 11492  **   This function is used to allocate and initialize a tokenizer instance.
 11493  **   A tokenizer instance is required to actually tokenize text.
 11494  **
 11495  **   The first argument passed to this function is a copy of the (void*)
 11496  **   pointer provided by the application when the fts5_tokenizer object
 11497  **   was registered with FTS5 (the third argument to xCreateTokenizer()). 
 11498  **   The second and third arguments are an array of nul-terminated strings
 11499  **   containing the tokenizer arguments, if any, specified following the
 11500  **   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
 11501  **   to create the FTS5 table.
 11502  **
 11503  **   The final argument is an output variable. If successful, (*ppOut) 
 11504  **   should be set to point to the new tokenizer handle and SQLITE_OK
 11505  **   returned. If an error occurs, some value other than SQLITE_OK should
 11506  **   be returned. In this case, fts5 assumes that the final value of *ppOut 
 11507  **   is undefined.
 11508  **
 11509  ** xDelete:
 11510  **   This function is invoked to delete a tokenizer handle previously
 11511  **   allocated using xCreate(). Fts5 guarantees that this function will
 11512  **   be invoked exactly once for each successful call to xCreate().
 11513  **
 11514  ** xTokenize:
 11515  **   This function is expected to tokenize the nText byte string indicated 
 11516  **   by argument pText. pText may or may not be nul-terminated. The first
 11517  **   argument passed to this function is a pointer to an Fts5Tokenizer object
 11518  **   returned by an earlier call to xCreate().
 11519  **
 11520  **   The second argument indicates the reason that FTS5 is requesting
 11521  **   tokenization of the supplied text. This is always one of the following
 11522  **   four values:
 11523  **
 11524  **   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
 11525  **            or removed from the FTS table. The tokenizer is being invoked to
 11526  **            determine the set of tokens to add to (or delete from) the
 11527  **            FTS index.
 11528  **
 11529  **       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed 
 11530  **            against the FTS index. The tokenizer is being called to tokenize 
 11531  **            a bareword or quoted string specified as part of the query.
 11532  **
 11533  **       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
 11534  **            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
 11535  **            followed by a "*" character, indicating that the last token
 11536  **            returned by the tokenizer will be treated as a token prefix.
 11537  **
 11538  **       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to 
 11539  **            satisfy an fts5_api.xTokenize() request made by an auxiliary
 11540  **            function. Or an fts5_api.xColumnSize() request made by the same
 11541  **            on a columnsize=0 database.  
 11542  **   </ul>
 11543  **
 11544  **   For each token in the input string, the supplied callback xToken() must
 11545  **   be invoked. The first argument to it should be a copy of the pointer
 11546  **   passed as the second argument to xTokenize(). The third and fourth
 11547  **   arguments are a pointer to a buffer containing the token text, and the
 11548  **   size of the token in bytes. The 4th and 5th arguments are the byte offsets
 11549  **   of the first byte of and first byte immediately following the text from
 11550  **   which the token is derived within the input.
 11551  **
 11552  **   The second argument passed to the xToken() callback ("tflags") should
 11553  **   normally be set to 0. The exception is if the tokenizer supports 
 11554  **   synonyms. In this case see the discussion below for details.
 11555  **
 11556  **   FTS5 assumes the xToken() callback is invoked for each token in the 
 11557  **   order that they occur within the input text.
 11558  **
 11559  **   If an xToken() callback returns any value other than SQLITE_OK, then
 11560  **   the tokenization should be abandoned and the xTokenize() method should
 11561  **   immediately return a copy of the xToken() return value. Or, if the
 11562  **   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
 11563  **   if an error occurs with the xTokenize() implementation itself, it
 11564  **   may abandon the tokenization and return any error code other than
 11565  **   SQLITE_OK or SQLITE_DONE.
 11566  **
 11567  ** SYNONYM SUPPORT
 11568  **
 11569  **   Custom tokenizers may also support synonyms. Consider a case in which a
 11570  **   user wishes to query for a phrase such as "first place". Using the 
 11571  **   built-in tokenizers, the FTS5 query 'first + place' will match instances
 11572  **   of "first place" within the document set, but not alternative forms
 11573  **   such as "1st place". In some applications, it would be better to match
 11574  **   all instances of "first place" or "1st place" regardless of which form
 11575  **   the user specified in the MATCH query text.
 11576  **
 11577  **   There are several ways to approach this in FTS5:
 11578  **
 11579  **   <ol><li> By mapping all synonyms to a single token. In this case, the 
 11580  **            In the above example, this means that the tokenizer returns the
 11581  **            same token for inputs "first" and "1st". Say that token is in
 11582  **            fact "first", so that when the user inserts the document "I won
 11583  **            1st place" entries are added to the index for tokens "i", "won",
 11584  **            "first" and "place". If the user then queries for '1st + place',
 11585  **            the tokenizer substitutes "first" for "1st" and the query works
 11586  **            as expected.
 11587  **
 11588  **       <li> By adding multiple synonyms for a single term to the FTS index.
 11589  **            In this case, when tokenizing query text, the tokenizer may 
 11590  **            provide multiple synonyms for a single term within the document.
 11591  **            FTS5 then queries the index for each synonym individually. For
 11592  **            example, faced with the query:
 11593  **
 11594  **   <codeblock>
 11595  **     ... MATCH 'first place'</codeblock>
 11596  **
 11597  **            the tokenizer offers both "1st" and "first" as synonyms for the
 11598  **            first token in the MATCH query and FTS5 effectively runs a query 
 11599  **            similar to:
 11600  **
 11601  **   <codeblock>
 11602  **     ... MATCH '(first OR 1st) place'</codeblock>
 11603  **
 11604  **            except that, for the purposes of auxiliary functions, the query
 11605  **            still appears to contain just two phrases - "(first OR 1st)" 
 11606  **            being treated as a single phrase.
 11607  **
 11608  **       <li> By adding multiple synonyms for a single term to the FTS index.
 11609  **            Using this method, when tokenizing document text, the tokenizer
 11610  **            provides multiple synonyms for each token. So that when a 
 11611  **            document such as "I won first place" is tokenized, entries are
 11612  **            added to the FTS index for "i", "won", "first", "1st" and
 11613  **            "place".
 11614  **
 11615  **            This way, even if the tokenizer does not provide synonyms
 11616  **            when tokenizing query text (it should not - to do would be
 11617  **            inefficient), it doesn't matter if the user queries for 
 11618  **            'first + place' or '1st + place', as there are entires in the
 11619  **            FTS index corresponding to both forms of the first token.
 11620  **   </ol>
 11621  **
 11622  **   Whether it is parsing document or query text, any call to xToken that
 11623  **   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
 11624  **   is considered to supply a synonym for the previous token. For example,
 11625  **   when parsing the document "I won first place", a tokenizer that supports
 11626  **   synonyms would call xToken() 5 times, as follows:
 11627  **
 11628  **   <codeblock>
 11629  **       xToken(pCtx, 0, "i",                      1,  0,  1);
 11630  **       xToken(pCtx, 0, "won",                    3,  2,  5);
 11631  **       xToken(pCtx, 0, "first",                  5,  6, 11);
 11632  **       xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3,  6, 11);
 11633  **       xToken(pCtx, 0, "place",                  5, 12, 17);
 11634  **</codeblock>
 11635  **
 11636  **   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
 11637  **   xToken() is called. Multiple synonyms may be specified for a single token
 11638  **   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence. 
 11639  **   There is no limit to the number of synonyms that may be provided for a
 11640  **   single token.
 11641  **
 11642  **   In many cases, method (1) above is the best approach. It does not add 
 11643  **   extra data to the FTS index or require FTS5 to query for multiple terms,
 11644  **   so it is efficient in terms of disk space and query speed. However, it
 11645  **   does not support prefix queries very well. If, as suggested above, the
 11646  **   token "first" is subsituted for "1st" by the tokenizer, then the query:
 11647  **
 11648  **   <codeblock>
 11649  **     ... MATCH '1s*'</codeblock>
 11650  **
 11651  **   will not match documents that contain the token "1st" (as the tokenizer
 11652  **   will probably not map "1s" to any prefix of "first").
 11653  **
 11654  **   For full prefix support, method (3) may be preferred. In this case, 
 11655  **   because the index contains entries for both "first" and "1st", prefix
 11656  **   queries such as 'fi*' or '1s*' will match correctly. However, because
 11657  **   extra entries are added to the FTS index, this method uses more space
 11658  **   within the database.
 11659  **
 11660  **   Method (2) offers a midpoint between (1) and (3). Using this method,
 11661  **   a query such as '1s*' will match documents that contain the literal 
 11662  **   token "1st", but not "first" (assuming the tokenizer is not able to
 11663  **   provide synonyms for prefixes). However, a non-prefix query like '1st'
 11664  **   will match against "1st" and "first". This method does not require
 11665  **   extra disk space, as no extra entries are added to the FTS index. 
 11666  **   On the other hand, it may require more CPU cycles to run MATCH queries,
 11667  **   as separate queries of the FTS index are required for each synonym.
 11668  **
 11669  **   When using methods (2) or (3), it is important that the tokenizer only
 11670  **   provide synonyms when tokenizing document text (method (2)) or query
 11671  **   text (method (3)), not both. Doing so will not cause any errors, but is
 11672  **   inefficient.
 11673  */
 11674  typedef struct Fts5Tokenizer Fts5Tokenizer;
 11675  typedef struct fts5_tokenizer fts5_tokenizer;
 11676  struct fts5_tokenizer {
 11677    int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
 11678    void (*xDelete)(Fts5Tokenizer*);
 11679    int (*xTokenize)(Fts5Tokenizer*, 
 11680        void *pCtx,
 11681        int flags,            /* Mask of FTS5_TOKENIZE_* flags */
 11682        const char *pText, int nText, 
 11683        int (*xToken)(
 11684          void *pCtx,         /* Copy of 2nd argument to xTokenize() */
 11685          int tflags,         /* Mask of FTS5_TOKEN_* flags */
 11686          const char *pToken, /* Pointer to buffer containing token */
 11687          int nToken,         /* Size of token in bytes */
 11688          int iStart,         /* Byte offset of token within input text */
 11689          int iEnd            /* Byte offset of end of token within input text */
 11690        )
 11691    );
 11692  };
 11693  
 11694  /* Flags that may be passed as the third argument to xTokenize() */
 11695  #define FTS5_TOKENIZE_QUERY     0x0001
 11696  #define FTS5_TOKENIZE_PREFIX    0x0002
 11697  #define FTS5_TOKENIZE_DOCUMENT  0x0004
 11698  #define FTS5_TOKENIZE_AUX       0x0008
 11699  
 11700  /* Flags that may be passed by the tokenizer implementation back to FTS5
 11701  ** as the third argument to the supplied xToken callback. */
 11702  #define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */
 11703  
 11704  /*
 11705  ** END OF CUSTOM TOKENIZERS
 11706  *************************************************************************/
 11707  
 11708  /*************************************************************************
 11709  ** FTS5 EXTENSION REGISTRATION API
 11710  */
 11711  typedef struct fts5_api fts5_api;
 11712  struct fts5_api {
 11713    int iVersion;                   /* Currently always set to 2 */
 11714  
 11715    /* Create a new tokenizer */
 11716    int (*xCreateTokenizer)(
 11717      fts5_api *pApi,
 11718      const char *zName,
 11719      void *pContext,
 11720      fts5_tokenizer *pTokenizer,
 11721      void (*xDestroy)(void*)
 11722    );
 11723  
 11724    /* Find an existing tokenizer */
 11725    int (*xFindTokenizer)(
 11726      fts5_api *pApi,
 11727      const char *zName,
 11728      void **ppContext,
 11729      fts5_tokenizer *pTokenizer
 11730    );
 11731  
 11732    /* Create a new auxiliary function */
 11733    int (*xCreateFunction)(
 11734      fts5_api *pApi,
 11735      const char *zName,
 11736      void *pContext,
 11737      fts5_extension_function xFunction,
 11738      void (*xDestroy)(void*)
 11739    );
 11740  };
 11741  
 11742  /*
 11743  ** END OF REGISTRATION API
 11744  *************************************************************************/
 11745  
 11746  #if 0
 11747  }  /* end of the 'extern "C"' block */
 11748  #endif
 11749  
 11750  #endif /* _FTS5_H */
 11751  
 11752  /******** End of fts5.h *********/
 11753  
 11754  /************** End of sqlite3.h *********************************************/
 11755  /************** Continuing where we left off in sqliteInt.h ******************/
 11756  
 11757  /*
 11758  ** Include the configuration header output by 'configure' if we're using the
 11759  ** autoconf-based build
 11760  */
 11761  #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
 11762  /* #include "config.h" */
 11763  #define SQLITECONFIG_H 1
 11764  #endif
 11765  
 11766  /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
 11767  /************** Begin file sqliteLimit.h *************************************/
 11768  /*
 11769  ** 2007 May 7
 11770  **
 11771  ** The author disclaims copyright to this source code.  In place of
 11772  ** a legal notice, here is a blessing:
 11773  **
 11774  **    May you do good and not evil.
 11775  **    May you find forgiveness for yourself and forgive others.
 11776  **    May you share freely, never taking more than you give.
 11777  **
 11778  *************************************************************************
 11779  ** 
 11780  ** This file defines various limits of what SQLite can process.
 11781  */
 11782  
 11783  /*
 11784  ** The maximum length of a TEXT or BLOB in bytes.   This also
 11785  ** limits the size of a row in a table or index.
 11786  **
 11787  ** The hard limit is the ability of a 32-bit signed integer
 11788  ** to count the size: 2^31-1 or 2147483647.
 11789  */
 11790  #ifndef SQLITE_MAX_LENGTH
 11791  # define SQLITE_MAX_LENGTH 1000000000
 11792  #endif
 11793  
 11794  /*
 11795  ** This is the maximum number of
 11796  **
 11797  **    * Columns in a table
 11798  **    * Columns in an index
 11799  **    * Columns in a view
 11800  **    * Terms in the SET clause of an UPDATE statement
 11801  **    * Terms in the result set of a SELECT statement
 11802  **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
 11803  **    * Terms in the VALUES clause of an INSERT statement
 11804  **
 11805  ** The hard upper limit here is 32676.  Most database people will
 11806  ** tell you that in a well-normalized database, you usually should
 11807  ** not have more than a dozen or so columns in any table.  And if
 11808  ** that is the case, there is no point in having more than a few
 11809  ** dozen values in any of the other situations described above.
 11810  */
 11811  #ifndef SQLITE_MAX_COLUMN
 11812  # define SQLITE_MAX_COLUMN 2000
 11813  #endif
 11814  
 11815  /*
 11816  ** The maximum length of a single SQL statement in bytes.
 11817  **
 11818  ** It used to be the case that setting this value to zero would
 11819  ** turn the limit off.  That is no longer true.  It is not possible
 11820  ** to turn this limit off.
 11821  */
 11822  #ifndef SQLITE_MAX_SQL_LENGTH
 11823  # define SQLITE_MAX_SQL_LENGTH 1000000000
 11824  #endif
 11825  
 11826  /*
 11827  ** The maximum depth of an expression tree. This is limited to 
 11828  ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
 11829  ** want to place more severe limits on the complexity of an 
 11830  ** expression.
 11831  **
 11832  ** A value of 0 used to mean that the limit was not enforced.
 11833  ** But that is no longer true.  The limit is now strictly enforced
 11834  ** at all times.
 11835  */
 11836  #ifndef SQLITE_MAX_EXPR_DEPTH
 11837  # define SQLITE_MAX_EXPR_DEPTH 1000
 11838  #endif
 11839  
 11840  /*
 11841  ** The maximum number of terms in a compound SELECT statement.
 11842  ** The code generator for compound SELECT statements does one
 11843  ** level of recursion for each term.  A stack overflow can result
 11844  ** if the number of terms is too large.  In practice, most SQL
 11845  ** never has more than 3 or 4 terms.  Use a value of 0 to disable
 11846  ** any limit on the number of terms in a compount SELECT.
 11847  */
 11848  #ifndef SQLITE_MAX_COMPOUND_SELECT
 11849  # define SQLITE_MAX_COMPOUND_SELECT 500
 11850  #endif
 11851  
 11852  /*
 11853  ** The maximum number of opcodes in a VDBE program.
 11854  ** Not currently enforced.
 11855  */
 11856  #ifndef SQLITE_MAX_VDBE_OP
 11857  # define SQLITE_MAX_VDBE_OP 250000000
 11858  #endif
 11859  
 11860  /*
 11861  ** The maximum number of arguments to an SQL function.
 11862  */
 11863  #ifndef SQLITE_MAX_FUNCTION_ARG
 11864  # define SQLITE_MAX_FUNCTION_ARG 127
 11865  #endif
 11866  
 11867  /*
 11868  ** The suggested maximum number of in-memory pages to use for
 11869  ** the main database table and for temporary tables.
 11870  **
 11871  ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
 11872  ** which means the cache size is limited to 2048000 bytes of memory.
 11873  ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
 11874  ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
 11875  */
 11876  #ifndef SQLITE_DEFAULT_CACHE_SIZE
 11877  # define SQLITE_DEFAULT_CACHE_SIZE  -2000
 11878  #endif
 11879  
 11880  /*
 11881  ** The default number of frames to accumulate in the log file before
 11882  ** checkpointing the database in WAL mode.
 11883  */
 11884  #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
 11885  # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
 11886  #endif
 11887  
 11888  /*
 11889  ** The maximum number of attached databases.  This must be between 0
 11890  ** and 125.  The upper bound of 125 is because the attached databases are
 11891  ** counted using a signed 8-bit integer which has a maximum value of 127
 11892  ** and we have to allow 2 extra counts for the "main" and "temp" databases.
 11893  */
 11894  #ifndef SQLITE_MAX_ATTACHED
 11895  # define SQLITE_MAX_ATTACHED 10
 11896  #endif
 11897  
 11898  
 11899  /*
 11900  ** The maximum value of a ?nnn wildcard that the parser will accept.
 11901  */
 11902  #ifndef SQLITE_MAX_VARIABLE_NUMBER
 11903  # define SQLITE_MAX_VARIABLE_NUMBER 999
 11904  #endif
 11905  
 11906  /* Maximum page size.  The upper bound on this value is 65536.  This a limit
 11907  ** imposed by the use of 16-bit offsets within each page.
 11908  **
 11909  ** Earlier versions of SQLite allowed the user to change this value at
 11910  ** compile time. This is no longer permitted, on the grounds that it creates
 11911  ** a library that is technically incompatible with an SQLite library 
 11912  ** compiled with a different limit. If a process operating on a database 
 11913  ** with a page-size of 65536 bytes crashes, then an instance of SQLite 
 11914  ** compiled with the default page-size limit will not be able to rollback 
 11915  ** the aborted transaction. This could lead to database corruption.
 11916  */
 11917  #ifdef SQLITE_MAX_PAGE_SIZE
 11918  # undef SQLITE_MAX_PAGE_SIZE
 11919  #endif
 11920  #define SQLITE_MAX_PAGE_SIZE 65536
 11921  
 11922  
 11923  /*
 11924  ** The default size of a database page.
 11925  */
 11926  #ifndef SQLITE_DEFAULT_PAGE_SIZE
 11927  # define SQLITE_DEFAULT_PAGE_SIZE 4096
 11928  #endif
 11929  #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
 11930  # undef SQLITE_DEFAULT_PAGE_SIZE
 11931  # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
 11932  #endif
 11933  
 11934  /*
 11935  ** Ordinarily, if no value is explicitly provided, SQLite creates databases
 11936  ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
 11937  ** device characteristics (sector-size and atomic write() support),
 11938  ** SQLite may choose a larger value. This constant is the maximum value
 11939  ** SQLite will choose on its own.
 11940  */
 11941  #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
 11942  # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
 11943  #endif
 11944  #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
 11945  # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
 11946  # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
 11947  #endif
 11948  
 11949  
 11950  /*
 11951  ** Maximum number of pages in one database file.
 11952  **
 11953  ** This is really just the default value for the max_page_count pragma.
 11954  ** This value can be lowered (or raised) at run-time using that the
 11955  ** max_page_count macro.
 11956  */
 11957  #ifndef SQLITE_MAX_PAGE_COUNT
 11958  # define SQLITE_MAX_PAGE_COUNT 1073741823
 11959  #endif
 11960  
 11961  /*
 11962  ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
 11963  ** operator.
 11964  */
 11965  #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
 11966  # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
 11967  #endif
 11968  
 11969  /*
 11970  ** Maximum depth of recursion for triggers.
 11971  **
 11972  ** A value of 1 means that a trigger program will not be able to itself
 11973  ** fire any triggers. A value of 0 means that no trigger programs at all 
 11974  ** may be executed.
 11975  */
 11976  #ifndef SQLITE_MAX_TRIGGER_DEPTH
 11977  # define SQLITE_MAX_TRIGGER_DEPTH 1000
 11978  #endif
 11979  
 11980  /************** End of sqliteLimit.h *****************************************/
 11981  /************** Continuing where we left off in sqliteInt.h ******************/
 11982  
 11983  /* Disable nuisance warnings on Borland compilers */
 11984  #if defined(__BORLANDC__)
 11985  #pragma warn -rch /* unreachable code */
 11986  #pragma warn -ccc /* Condition is always true or false */
 11987  #pragma warn -aus /* Assigned value is never used */
 11988  #pragma warn -csu /* Comparing signed and unsigned */
 11989  #pragma warn -spa /* Suspicious pointer arithmetic */
 11990  #endif
 11991  
 11992  /*
 11993  ** Include standard header files as necessary
 11994  */
 11995  #ifdef HAVE_STDINT_H
 11996  #include <stdint.h>
 11997  #endif
 11998  #ifdef HAVE_INTTYPES_H
 11999  #include <inttypes.h>
 12000  #endif
 12001  
 12002  /*
 12003  ** The following macros are used to cast pointers to integers and
 12004  ** integers to pointers.  The way you do this varies from one compiler
 12005  ** to the next, so we have developed the following set of #if statements
 12006  ** to generate appropriate macros for a wide range of compilers.
 12007  **
 12008  ** The correct "ANSI" way to do this is to use the intptr_t type.
 12009  ** Unfortunately, that typedef is not available on all compilers, or
 12010  ** if it is available, it requires an #include of specific headers
 12011  ** that vary from one machine to the next.
 12012  **
 12013  ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
 12014  ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
 12015  ** So we have to define the macros in different ways depending on the
 12016  ** compiler.
 12017  */
 12018  #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
 12019  # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
 12020  # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
 12021  #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
 12022  # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
 12023  # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
 12024  #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
 12025  # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
 12026  # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
 12027  #else                          /* Generates a warning - but it always works */
 12028  # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
 12029  # define SQLITE_PTR_TO_INT(X)  ((int)(X))
 12030  #endif
 12031  
 12032  /*
 12033  ** A macro to hint to the compiler that a function should not be
 12034  ** inlined.
 12035  */
 12036  #if defined(__GNUC__)
 12037  #  define SQLITE_NOINLINE  __attribute__((noinline))
 12038  #elif defined(_MSC_VER) && _MSC_VER>=1310
 12039  #  define SQLITE_NOINLINE  __declspec(noinline)
 12040  #else
 12041  #  define SQLITE_NOINLINE
 12042  #endif
 12043  
 12044  /*
 12045  ** Make sure that the compiler intrinsics we desire are enabled when
 12046  ** compiling with an appropriate version of MSVC unless prevented by
 12047  ** the SQLITE_DISABLE_INTRINSIC define.
 12048  */
 12049  #if !defined(SQLITE_DISABLE_INTRINSIC)
 12050  #  if defined(_MSC_VER) && _MSC_VER>=1400
 12051  #    if !defined(_WIN32_WCE)
 12052  #      include <intrin.h>
 12053  #      pragma intrinsic(_byteswap_ushort)
 12054  #      pragma intrinsic(_byteswap_ulong)
 12055  #      pragma intrinsic(_byteswap_uint64)
 12056  #      pragma intrinsic(_ReadWriteBarrier)
 12057  #    else
 12058  #      include <cmnintrin.h>
 12059  #    endif
 12060  #  endif
 12061  #endif
 12062  
 12063  /*
 12064  ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
 12065  ** 0 means mutexes are permanently disable and the library is never
 12066  ** threadsafe.  1 means the library is serialized which is the highest
 12067  ** level of threadsafety.  2 means the library is multithreaded - multiple
 12068  ** threads can use SQLite as long as no two threads try to use the same
 12069  ** database connection at the same time.
 12070  **
 12071  ** Older versions of SQLite used an optional THREADSAFE macro.
 12072  ** We support that for legacy.
 12073  **
 12074  ** To ensure that the correct value of "THREADSAFE" is reported when querying
 12075  ** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
 12076  ** logic is partially replicated in ctime.c. If it is updated here, it should
 12077  ** also be updated there.
 12078  */
 12079  #if !defined(SQLITE_THREADSAFE)
 12080  # if defined(THREADSAFE)
 12081  #   define SQLITE_THREADSAFE THREADSAFE
 12082  # else
 12083  #   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
 12084  # endif
 12085  #endif
 12086  
 12087  /*
 12088  ** Powersafe overwrite is on by default.  But can be turned off using
 12089  ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
 12090  */
 12091  #ifndef SQLITE_POWERSAFE_OVERWRITE
 12092  # define SQLITE_POWERSAFE_OVERWRITE 1
 12093  #endif
 12094  
 12095  /*
 12096  ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
 12097  ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
 12098  ** which case memory allocation statistics are disabled by default.
 12099  */
 12100  #if !defined(SQLITE_DEFAULT_MEMSTATUS)
 12101  # define SQLITE_DEFAULT_MEMSTATUS 1
 12102  #endif
 12103  
 12104  /*
 12105  ** Exactly one of the following macros must be defined in order to
 12106  ** specify which memory allocation subsystem to use.
 12107  **
 12108  **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
 12109  **     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
 12110  **     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
 12111  **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
 12112  **
 12113  ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
 12114  ** assert() macro is enabled, each call into the Win32 native heap subsystem
 12115  ** will cause HeapValidate to be called.  If heap validation should fail, an
 12116  ** assertion will be triggered.
 12117  **
 12118  ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
 12119  ** the default.
 12120  */
 12121  #if defined(SQLITE_SYSTEM_MALLOC) \
 12122    + defined(SQLITE_WIN32_MALLOC) \
 12123    + defined(SQLITE_ZERO_MALLOC) \
 12124    + defined(SQLITE_MEMDEBUG)>1
 12125  # error "Two or more of the following compile-time configuration options\
 12126   are defined but at most one is allowed:\
 12127   SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
 12128   SQLITE_ZERO_MALLOC"
 12129  #endif
 12130  #if defined(SQLITE_SYSTEM_MALLOC) \
 12131    + defined(SQLITE_WIN32_MALLOC) \
 12132    + defined(SQLITE_ZERO_MALLOC) \
 12133    + defined(SQLITE_MEMDEBUG)==0
 12134  # define SQLITE_SYSTEM_MALLOC 1
 12135  #endif
 12136  
 12137  /*
 12138  ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
 12139  ** sizes of memory allocations below this value where possible.
 12140  */
 12141  #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
 12142  # define SQLITE_MALLOC_SOFT_LIMIT 1024
 12143  #endif
 12144  
 12145  /*
 12146  ** We need to define _XOPEN_SOURCE as follows in order to enable
 12147  ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
 12148  ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
 12149  ** it.
 12150  */
 12151  #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
 12152  #  define _XOPEN_SOURCE 600
 12153  #endif
 12154  
 12155  /*
 12156  ** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
 12157  ** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
 12158  ** make it true by defining or undefining NDEBUG.
 12159  **
 12160  ** Setting NDEBUG makes the code smaller and faster by disabling the
 12161  ** assert() statements in the code.  So we want the default action
 12162  ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
 12163  ** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
 12164  ** feature.
 12165  */
 12166  #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
 12167  # define NDEBUG 1
 12168  #endif
 12169  #if defined(NDEBUG) && defined(SQLITE_DEBUG)
 12170  # undef NDEBUG
 12171  #endif
 12172  
 12173  /*
 12174  ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
 12175  */
 12176  #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
 12177  # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
 12178  #endif
 12179  
 12180  /*
 12181  ** The testcase() macro is used to aid in coverage testing.  When
 12182  ** doing coverage testing, the condition inside the argument to
 12183  ** testcase() must be evaluated both true and false in order to
 12184  ** get full branch coverage.  The testcase() macro is inserted
 12185  ** to help ensure adequate test coverage in places where simple
 12186  ** condition/decision coverage is inadequate.  For example, testcase()
 12187  ** can be used to make sure boundary values are tested.  For
 12188  ** bitmask tests, testcase() can be used to make sure each bit
 12189  ** is significant and used at least once.  On switch statements
 12190  ** where multiple cases go to the same block of code, testcase()
 12191  ** can insure that all cases are evaluated.
 12192  **
 12193  */
 12194  #ifdef SQLITE_COVERAGE_TEST
 12195  SQLITE_PRIVATE   void sqlite3Coverage(int);
 12196  # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
 12197  #else
 12198  # define testcase(X)
 12199  #endif
 12200  
 12201  /*
 12202  ** The TESTONLY macro is used to enclose variable declarations or
 12203  ** other bits of code that are needed to support the arguments
 12204  ** within testcase() and assert() macros.
 12205  */
 12206  #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
 12207  # define TESTONLY(X)  X
 12208  #else
 12209  # define TESTONLY(X)
 12210  #endif
 12211  
 12212  /*
 12213  ** Sometimes we need a small amount of code such as a variable initialization
 12214  ** to setup for a later assert() statement.  We do not want this code to
 12215  ** appear when assert() is disabled.  The following macro is therefore
 12216  ** used to contain that setup code.  The "VVA" acronym stands for
 12217  ** "Verification, Validation, and Accreditation".  In other words, the
 12218  ** code within VVA_ONLY() will only run during verification processes.
 12219  */
 12220  #ifndef NDEBUG
 12221  # define VVA_ONLY(X)  X
 12222  #else
 12223  # define VVA_ONLY(X)
 12224  #endif
 12225  
 12226  /*
 12227  ** The ALWAYS and NEVER macros surround boolean expressions which
 12228  ** are intended to always be true or false, respectively.  Such
 12229  ** expressions could be omitted from the code completely.  But they
 12230  ** are included in a few cases in order to enhance the resilience
 12231  ** of SQLite to unexpected behavior - to make the code "self-healing"
 12232  ** or "ductile" rather than being "brittle" and crashing at the first
 12233  ** hint of unplanned behavior.
 12234  **
 12235  ** In other words, ALWAYS and NEVER are added for defensive code.
 12236  **
 12237  ** When doing coverage testing ALWAYS and NEVER are hard-coded to
 12238  ** be true and false so that the unreachable code they specify will
 12239  ** not be counted as untested code.
 12240  */
 12241  #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
 12242  # define ALWAYS(X)      (1)
 12243  # define NEVER(X)       (0)
 12244  #elif !defined(NDEBUG)
 12245  # define ALWAYS(X)      ((X)?1:(assert(0),0))
 12246  # define NEVER(X)       ((X)?(assert(0),1):0)
 12247  #else
 12248  # define ALWAYS(X)      (X)
 12249  # define NEVER(X)       (X)
 12250  #endif
 12251  
 12252  /*
 12253  ** Some conditionals are optimizations only.  In other words, if the
 12254  ** conditionals are replaced with a constant 1 (true) or 0 (false) then
 12255  ** the correct answer is still obtained, though perhaps not as quickly.
 12256  **
 12257  ** The following macros mark these optimizations conditionals.
 12258  */
 12259  #if defined(SQLITE_MUTATION_TEST)
 12260  # define OK_IF_ALWAYS_TRUE(X)  (1)
 12261  # define OK_IF_ALWAYS_FALSE(X) (0)
 12262  #else
 12263  # define OK_IF_ALWAYS_TRUE(X)  (X)
 12264  # define OK_IF_ALWAYS_FALSE(X) (X)
 12265  #endif
 12266  
 12267  /*
 12268  ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
 12269  ** defined.  We need to defend against those failures when testing with
 12270  ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
 12271  ** during a normal build.  The following macro can be used to disable tests
 12272  ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
 12273  */
 12274  #if defined(SQLITE_TEST_REALLOC_STRESS)
 12275  # define ONLY_IF_REALLOC_STRESS(X)  (X)
 12276  #elif !defined(NDEBUG)
 12277  # define ONLY_IF_REALLOC_STRESS(X)  ((X)?(assert(0),1):0)
 12278  #else
 12279  # define ONLY_IF_REALLOC_STRESS(X)  (0)
 12280  #endif
 12281  
 12282  /*
 12283  ** Declarations used for tracing the operating system interfaces.
 12284  */
 12285  #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
 12286      (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
 12287    extern int sqlite3OSTrace;
 12288  # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
 12289  # define SQLITE_HAVE_OS_TRACE
 12290  #else
 12291  # define OSTRACE(X)
 12292  # undef  SQLITE_HAVE_OS_TRACE
 12293  #endif
 12294  
 12295  /*
 12296  ** Is the sqlite3ErrName() function needed in the build?  Currently,
 12297  ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
 12298  ** OSTRACE is enabled), and by several "test*.c" files (which are
 12299  ** compiled using SQLITE_TEST).
 12300  */
 12301  #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
 12302      (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
 12303  # define SQLITE_NEED_ERR_NAME
 12304  #else
 12305  # undef  SQLITE_NEED_ERR_NAME
 12306  #endif
 12307  
 12308  /*
 12309  ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
 12310  */
 12311  #ifdef SQLITE_OMIT_EXPLAIN
 12312  # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
 12313  #endif
 12314  
 12315  /*
 12316  ** Return true (non-zero) if the input is an integer that is too large
 12317  ** to fit in 32-bits.  This macro is used inside of various testcase()
 12318  ** macros to verify that we have tested SQLite for large-file support.
 12319  */
 12320  #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
 12321  
 12322  /*
 12323  ** The macro unlikely() is a hint that surrounds a boolean
 12324  ** expression that is usually false.  Macro likely() surrounds
 12325  ** a boolean expression that is usually true.  These hints could,
 12326  ** in theory, be used by the compiler to generate better code, but
 12327  ** currently they are just comments for human readers.
 12328  */
 12329  #define likely(X)    (X)
 12330  #define unlikely(X)  (X)
 12331  
 12332  /************** Include hash.h in the middle of sqliteInt.h ******************/
 12333  /************** Begin file hash.h ********************************************/
 12334  /*
 12335  ** 2001 September 22
 12336  **
 12337  ** The author disclaims copyright to this source code.  In place of
 12338  ** a legal notice, here is a blessing:
 12339  **
 12340  **    May you do good and not evil.
 12341  **    May you find forgiveness for yourself and forgive others.
 12342  **    May you share freely, never taking more than you give.
 12343  **
 12344  *************************************************************************
 12345  ** This is the header file for the generic hash-table implementation
 12346  ** used in SQLite.
 12347  */
 12348  #ifndef SQLITE_HASH_H
 12349  #define SQLITE_HASH_H
 12350  
 12351  /* Forward declarations of structures. */
 12352  typedef struct Hash Hash;
 12353  typedef struct HashElem HashElem;
 12354  
 12355  /* A complete hash table is an instance of the following structure.
 12356  ** The internals of this structure are intended to be opaque -- client
 12357  ** code should not attempt to access or modify the fields of this structure
 12358  ** directly.  Change this structure only by using the routines below.
 12359  ** However, some of the "procedures" and "functions" for modifying and
 12360  ** accessing this structure are really macros, so we can't really make
 12361  ** this structure opaque.
 12362  **
 12363  ** All elements of the hash table are on a single doubly-linked list.
 12364  ** Hash.first points to the head of this list.
 12365  **
 12366  ** There are Hash.htsize buckets.  Each bucket points to a spot in
 12367  ** the global doubly-linked list.  The contents of the bucket are the
 12368  ** element pointed to plus the next _ht.count-1 elements in the list.
 12369  **
 12370  ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
 12371  ** by a linear search of the global list.  For small tables, the 
 12372  ** Hash.ht table is never allocated because if there are few elements
 12373  ** in the table, it is faster to do a linear search than to manage
 12374  ** the hash table.
 12375  */
 12376  struct Hash {
 12377    unsigned int htsize;      /* Number of buckets in the hash table */
 12378    unsigned int count;       /* Number of entries in this table */
 12379    HashElem *first;          /* The first element of the array */
 12380    struct _ht {              /* the hash table */
 12381      int count;                 /* Number of entries with this hash */
 12382      HashElem *chain;           /* Pointer to first entry with this hash */
 12383    } *ht;
 12384  };
 12385  
 12386  /* Each element in the hash table is an instance of the following 
 12387  ** structure.  All elements are stored on a single doubly-linked list.
 12388  **
 12389  ** Again, this structure is intended to be opaque, but it can't really
 12390  ** be opaque because it is used by macros.
 12391  */
 12392  struct HashElem {
 12393    HashElem *next, *prev;       /* Next and previous elements in the table */
 12394    void *data;                  /* Data associated with this element */
 12395    const char *pKey;            /* Key associated with this element */
 12396  };
 12397  
 12398  /*
 12399  ** Access routines.  To delete, insert a NULL pointer.
 12400  */
 12401  SQLITE_PRIVATE void sqlite3HashInit(Hash*);
 12402  SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
 12403  SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
 12404  SQLITE_PRIVATE void sqlite3HashClear(Hash*);
 12405  
 12406  /*
 12407  ** Macros for looping over all elements of a hash table.  The idiom is
 12408  ** like this:
 12409  **
 12410  **   Hash h;
 12411  **   HashElem *p;
 12412  **   ...
 12413  **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
 12414  **     SomeStructure *pData = sqliteHashData(p);
 12415  **     // do something with pData
 12416  **   }
 12417  */
 12418  #define sqliteHashFirst(H)  ((H)->first)
 12419  #define sqliteHashNext(E)   ((E)->next)
 12420  #define sqliteHashData(E)   ((E)->data)
 12421  /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
 12422  /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
 12423  
 12424  /*
 12425  ** Number of entries in a hash table
 12426  */
 12427  /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
 12428  
 12429  #endif /* SQLITE_HASH_H */
 12430  
 12431  /************** End of hash.h ************************************************/
 12432  /************** Continuing where we left off in sqliteInt.h ******************/
 12433  /************** Include parse.h in the middle of sqliteInt.h *****************/
 12434  /************** Begin file parse.h *******************************************/
 12435  #define TK_SEMI                             1
 12436  #define TK_EXPLAIN                          2
 12437  #define TK_QUERY                            3
 12438  #define TK_PLAN                             4
 12439  #define TK_BEGIN                            5
 12440  #define TK_TRANSACTION                      6
 12441  #define TK_DEFERRED                         7
 12442  #define TK_IMMEDIATE                        8
 12443  #define TK_EXCLUSIVE                        9
 12444  #define TK_COMMIT                          10
 12445  #define TK_END                             11
 12446  #define TK_ROLLBACK                        12
 12447  #define TK_SAVEPOINT                       13
 12448  #define TK_RELEASE                         14
 12449  #define TK_TO                              15
 12450  #define TK_TABLE                           16
 12451  #define TK_CREATE                          17
 12452  #define TK_IF                              18
 12453  #define TK_NOT                             19
 12454  #define TK_EXISTS                          20
 12455  #define TK_TEMP                            21
 12456  #define TK_LP                              22
 12457  #define TK_RP                              23
 12458  #define TK_AS                              24
 12459  #define TK_WITHOUT                         25
 12460  #define TK_COMMA                           26
 12461  #define TK_ABORT                           27
 12462  #define TK_ACTION                          28
 12463  #define TK_AFTER                           29
 12464  #define TK_ANALYZE                         30
 12465  #define TK_ASC                             31
 12466  #define TK_ATTACH                          32
 12467  #define TK_BEFORE                          33
 12468  #define TK_BY                              34
 12469  #define TK_CASCADE                         35
 12470  #define TK_CAST                            36
 12471  #define TK_CONFLICT                        37
 12472  #define TK_DATABASE                        38
 12473  #define TK_DESC                            39
 12474  #define TK_DETACH                          40
 12475  #define TK_EACH                            41
 12476  #define TK_FAIL                            42
 12477  #define TK_OR                              43
 12478  #define TK_AND                             44
 12479  #define TK_IS                              45
 12480  #define TK_MATCH                           46
 12481  #define TK_LIKE_KW                         47
 12482  #define TK_BETWEEN                         48
 12483  #define TK_IN                              49
 12484  #define TK_ISNULL                          50
 12485  #define TK_NOTNULL                         51
 12486  #define TK_NE                              52
 12487  #define TK_EQ                              53
 12488  #define TK_GT                              54
 12489  #define TK_LE                              55
 12490  #define TK_LT                              56
 12491  #define TK_GE                              57
 12492  #define TK_ESCAPE                          58
 12493  #define TK_ID                              59
 12494  #define TK_COLUMNKW                        60
 12495  #define TK_FOR                             61
 12496  #define TK_IGNORE                          62
 12497  #define TK_INITIALLY                       63
 12498  #define TK_INSTEAD                         64
 12499  #define TK_NO                              65
 12500  #define TK_KEY                             66
 12501  #define TK_OF                              67
 12502  #define TK_OFFSET                          68
 12503  #define TK_PRAGMA                          69
 12504  #define TK_RAISE                           70
 12505  #define TK_RECURSIVE                       71
 12506  #define TK_REPLACE                         72
 12507  #define TK_RESTRICT                        73
 12508  #define TK_ROW                             74
 12509  #define TK_TRIGGER                         75
 12510  #define TK_VACUUM                          76
 12511  #define TK_VIEW                            77
 12512  #define TK_VIRTUAL                         78
 12513  #define TK_WITH                            79
 12514  #define TK_REINDEX                         80
 12515  #define TK_RENAME                          81
 12516  #define TK_CTIME_KW                        82
 12517  #define TK_ANY                             83
 12518  #define TK_BITAND                          84
 12519  #define TK_BITOR                           85
 12520  #define TK_LSHIFT                          86
 12521  #define TK_RSHIFT                          87
 12522  #define TK_PLUS                            88
 12523  #define TK_MINUS                           89
 12524  #define TK_STAR                            90
 12525  #define TK_SLASH                           91
 12526  #define TK_REM                             92
 12527  #define TK_CONCAT                          93
 12528  #define TK_COLLATE                         94
 12529  #define TK_BITNOT                          95
 12530  #define TK_INDEXED                         96
 12531  #define TK_STRING                          97
 12532  #define TK_JOIN_KW                         98
 12533  #define TK_CONSTRAINT                      99
 12534  #define TK_DEFAULT                        100
 12535  #define TK_NULL                           101
 12536  #define TK_PRIMARY                        102
 12537  #define TK_UNIQUE                         103
 12538  #define TK_CHECK                          104
 12539  #define TK_REFERENCES                     105
 12540  #define TK_AUTOINCR                       106
 12541  #define TK_ON                             107
 12542  #define TK_INSERT                         108
 12543  #define TK_DELETE                         109
 12544  #define TK_UPDATE                         110
 12545  #define TK_SET                            111
 12546  #define TK_DEFERRABLE                     112
 12547  #define TK_FOREIGN                        113
 12548  #define TK_DROP                           114
 12549  #define TK_UNION                          115
 12550  #define TK_ALL                            116
 12551  #define TK_EXCEPT                         117
 12552  #define TK_INTERSECT                      118
 12553  #define TK_SELECT                         119
 12554  #define TK_VALUES                         120
 12555  #define TK_DISTINCT                       121
 12556  #define TK_DOT                            122
 12557  #define TK_FROM                           123
 12558  #define TK_JOIN                           124
 12559  #define TK_USING                          125
 12560  #define TK_ORDER                          126
 12561  #define TK_GROUP                          127
 12562  #define TK_HAVING                         128
 12563  #define TK_LIMIT                          129
 12564  #define TK_WHERE                          130
 12565  #define TK_INTO                           131
 12566  #define TK_FLOAT                          132
 12567  #define TK_BLOB                           133
 12568  #define TK_INTEGER                        134
 12569  #define TK_VARIABLE                       135
 12570  #define TK_CASE                           136
 12571  #define TK_WHEN                           137
 12572  #define TK_THEN                           138
 12573  #define TK_ELSE                           139
 12574  #define TK_INDEX                          140
 12575  #define TK_ALTER                          141
 12576  #define TK_ADD                            142
 12577  #define TK_ISNOT                          143
 12578  #define TK_FUNCTION                       144
 12579  #define TK_COLUMN                         145
 12580  #define TK_AGG_FUNCTION                   146
 12581  #define TK_AGG_COLUMN                     147
 12582  #define TK_UMINUS                         148
 12583  #define TK_UPLUS                          149
 12584  #define TK_REGISTER                       150
 12585  #define TK_VECTOR                         151
 12586  #define TK_SELECT_COLUMN                  152
 12587  #define TK_IF_NULL_ROW                    153
 12588  #define TK_ASTERISK                       154
 12589  #define TK_SPAN                           155
 12590  #define TK_END_OF_FILE                    156
 12591  #define TK_UNCLOSED_STRING                157
 12592  #define TK_SPACE                          158
 12593  #define TK_ILLEGAL                        159
 12594  
 12595  /* The token codes above must all fit in 8 bits */
 12596  #define TKFLG_MASK           0xff  
 12597  
 12598  /* Flags that can be added to a token code when it is not
 12599  ** being stored in a u8: */
 12600  #define TKFLG_DONTFOLD       0x100  /* Omit constant folding optimizations */
 12601  
 12602  /************** End of parse.h ***********************************************/
 12603  /************** Continuing where we left off in sqliteInt.h ******************/
 12604  #include <stdio.h>
 12605  #include <stdlib.h>
 12606  #include <string.h>
 12607  #include <assert.h>
 12608  #include <stddef.h>
 12609  
 12610  /*
 12611  ** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
 12612  ** This allows better measurements of where memcpy() is used when running
 12613  ** cachegrind.  But this macro version of memcpy() is very slow so it
 12614  ** should not be used in production.  This is a performance measurement
 12615  ** hack only.
 12616  */
 12617  #ifdef SQLITE_INLINE_MEMCPY
 12618  # define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
 12619                          int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
 12620  #endif
 12621  
 12622  /*
 12623  ** If compiling for a processor that lacks floating point support,
 12624  ** substitute integer for floating-point
 12625  */
 12626  #ifdef SQLITE_OMIT_FLOATING_POINT
 12627  # define double sqlite_int64
 12628  # define float sqlite_int64
 12629  # define LONGDOUBLE_TYPE sqlite_int64
 12630  # ifndef SQLITE_BIG_DBL
 12631  #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
 12632  # endif
 12633  # define SQLITE_OMIT_DATETIME_FUNCS 1
 12634  # define SQLITE_OMIT_TRACE 1
 12635  # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
 12636  # undef SQLITE_HAVE_ISNAN
 12637  #endif
 12638  #ifndef SQLITE_BIG_DBL
 12639  # define SQLITE_BIG_DBL (1e99)
 12640  #endif
 12641  
 12642  /*
 12643  ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
 12644  ** afterward. Having this macro allows us to cause the C compiler
 12645  ** to omit code used by TEMP tables without messy #ifndef statements.
 12646  */
 12647  #ifdef SQLITE_OMIT_TEMPDB
 12648  #define OMIT_TEMPDB 1
 12649  #else
 12650  #define OMIT_TEMPDB 0
 12651  #endif
 12652  
 12653  /*
 12654  ** The "file format" number is an integer that is incremented whenever
 12655  ** the VDBE-level file format changes.  The following macros define the
 12656  ** the default file format for new databases and the maximum file format
 12657  ** that the library can read.
 12658  */
 12659  #define SQLITE_MAX_FILE_FORMAT 4
 12660  #ifndef SQLITE_DEFAULT_FILE_FORMAT
 12661  # define SQLITE_DEFAULT_FILE_FORMAT 4
 12662  #endif
 12663  
 12664  /*
 12665  ** Determine whether triggers are recursive by default.  This can be
 12666  ** changed at run-time using a pragma.
 12667  */
 12668  #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
 12669  # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
 12670  #endif
 12671  
 12672  /*
 12673  ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
 12674  ** on the command-line
 12675  */
 12676  #ifndef SQLITE_TEMP_STORE
 12677  # define SQLITE_TEMP_STORE 1
 12678  #endif
 12679  
 12680  /*
 12681  ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
 12682  ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
 12683  ** to zero.
 12684  */
 12685  #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
 12686  # undef SQLITE_MAX_WORKER_THREADS
 12687  # define SQLITE_MAX_WORKER_THREADS 0
 12688  #endif
 12689  #ifndef SQLITE_MAX_WORKER_THREADS
 12690  # define SQLITE_MAX_WORKER_THREADS 8
 12691  #endif
 12692  #ifndef SQLITE_DEFAULT_WORKER_THREADS
 12693  # define SQLITE_DEFAULT_WORKER_THREADS 0
 12694  #endif
 12695  #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
 12696  # undef SQLITE_MAX_WORKER_THREADS
 12697  # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
 12698  #endif
 12699  
 12700  /*
 12701  ** The default initial allocation for the pagecache when using separate
 12702  ** pagecaches for each database connection.  A positive number is the
 12703  ** number of pages.  A negative number N translations means that a buffer
 12704  ** of -1024*N bytes is allocated and used for as many pages as it will hold.
 12705  **
 12706  ** The default value of "20" was choosen to minimize the run-time of the
 12707  ** speedtest1 test program with options: --shrink-memory --reprepare
 12708  */
 12709  #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
 12710  # define SQLITE_DEFAULT_PCACHE_INITSZ 20
 12711  #endif
 12712  
 12713  /*
 12714  ** The compile-time options SQLITE_MMAP_READWRITE and 
 12715  ** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.
 12716  ** You must choose one or the other (or neither) but not both.
 12717  */
 12718  #if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
 12719  #error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE
 12720  #endif
 12721  
 12722  /*
 12723  ** GCC does not define the offsetof() macro so we'll have to do it
 12724  ** ourselves.
 12725  */
 12726  #ifndef offsetof
 12727  #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
 12728  #endif
 12729  
 12730  /*
 12731  ** Macros to compute minimum and maximum of two numbers.
 12732  */
 12733  #ifndef MIN
 12734  # define MIN(A,B) ((A)<(B)?(A):(B))
 12735  #endif
 12736  #ifndef MAX
 12737  # define MAX(A,B) ((A)>(B)?(A):(B))
 12738  #endif
 12739  
 12740  /*
 12741  ** Swap two objects of type TYPE.
 12742  */
 12743  #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
 12744  
 12745  /*
 12746  ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
 12747  ** not, there are still machines out there that use EBCDIC.)
 12748  */
 12749  #if 'A' == '\301'
 12750  # define SQLITE_EBCDIC 1
 12751  #else
 12752  # define SQLITE_ASCII 1
 12753  #endif
 12754  
 12755  /*
 12756  ** Integers of known sizes.  These typedefs might change for architectures
 12757  ** where the sizes very.  Preprocessor macros are available so that the
 12758  ** types can be conveniently redefined at compile-type.  Like this:
 12759  **
 12760  **         cc '-DUINTPTR_TYPE=long long int' ...
 12761  */
 12762  #ifndef UINT32_TYPE
 12763  # ifdef HAVE_UINT32_T
 12764  #  define UINT32_TYPE uint32_t
 12765  # else
 12766  #  define UINT32_TYPE unsigned int
 12767  # endif
 12768  #endif
 12769  #ifndef UINT16_TYPE
 12770  # ifdef HAVE_UINT16_T
 12771  #  define UINT16_TYPE uint16_t
 12772  # else
 12773  #  define UINT16_TYPE unsigned short int
 12774  # endif
 12775  #endif
 12776  #ifndef INT16_TYPE
 12777  # ifdef HAVE_INT16_T
 12778  #  define INT16_TYPE int16_t
 12779  # else
 12780  #  define INT16_TYPE short int
 12781  # endif
 12782  #endif
 12783  #ifndef UINT8_TYPE
 12784  # ifdef HAVE_UINT8_T
 12785  #  define UINT8_TYPE uint8_t
 12786  # else
 12787  #  define UINT8_TYPE unsigned char
 12788  # endif
 12789  #endif
 12790  #ifndef INT8_TYPE
 12791  # ifdef HAVE_INT8_T
 12792  #  define INT8_TYPE int8_t
 12793  # else
 12794  #  define INT8_TYPE signed char
 12795  # endif
 12796  #endif
 12797  #ifndef LONGDOUBLE_TYPE
 12798  # define LONGDOUBLE_TYPE long double
 12799  #endif
 12800  typedef sqlite_int64 i64;          /* 8-byte signed integer */
 12801  typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
 12802  typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
 12803  typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
 12804  typedef INT16_TYPE i16;            /* 2-byte signed integer */
 12805  typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
 12806  typedef INT8_TYPE i8;              /* 1-byte signed integer */
 12807  
 12808  /*
 12809  ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
 12810  ** that can be stored in a u32 without loss of data.  The value
 12811  ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
 12812  ** have to specify the value in the less intuitive manner shown:
 12813  */
 12814  #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
 12815  
 12816  /*
 12817  ** The datatype used to store estimates of the number of rows in a
 12818  ** table or index.  This is an unsigned integer type.  For 99.9% of
 12819  ** the world, a 32-bit integer is sufficient.  But a 64-bit integer
 12820  ** can be used at compile-time if desired.
 12821  */
 12822  #ifdef SQLITE_64BIT_STATS
 12823   typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
 12824  #else
 12825   typedef u32 tRowcnt;    /* 32-bit is the default */
 12826  #endif
 12827  
 12828  /*
 12829  ** Estimated quantities used for query planning are stored as 16-bit
 12830  ** logarithms.  For quantity X, the value stored is 10*log2(X).  This
 12831  ** gives a possible range of values of approximately 1.0e986 to 1e-986.
 12832  ** But the allowed values are "grainy".  Not every value is representable.
 12833  ** For example, quantities 16 and 17 are both represented by a LogEst
 12834  ** of 40.  However, since LogEst quantities are suppose to be estimates,
 12835  ** not exact values, this imprecision is not a problem.
 12836  **
 12837  ** "LogEst" is short for "Logarithmic Estimate".
 12838  **
 12839  ** Examples:
 12840  **      1 -> 0              20 -> 43          10000 -> 132
 12841  **      2 -> 10             25 -> 46          25000 -> 146
 12842  **      3 -> 16            100 -> 66        1000000 -> 199
 12843  **      4 -> 20           1000 -> 99        1048576 -> 200
 12844  **     10 -> 33           1024 -> 100    4294967296 -> 320
 12845  **
 12846  ** The LogEst can be negative to indicate fractional values.
 12847  ** Examples:
 12848  **
 12849  **    0.5 -> -10           0.1 -> -33        0.0625 -> -40
 12850  */
 12851  typedef INT16_TYPE LogEst;
 12852  
 12853  /*
 12854  ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
 12855  */
 12856  #ifndef SQLITE_PTRSIZE
 12857  # if defined(__SIZEOF_POINTER__)
 12858  #   define SQLITE_PTRSIZE __SIZEOF_POINTER__
 12859  # elif defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
 12860         defined(_M_ARM)   || defined(__arm__)    || defined(__x86)
 12861  #   define SQLITE_PTRSIZE 4
 12862  # else
 12863  #   define SQLITE_PTRSIZE 8
 12864  # endif
 12865  #endif
 12866  
 12867  /* The uptr type is an unsigned integer large enough to hold a pointer
 12868  */
 12869  #if defined(HAVE_STDINT_H)
 12870    typedef uintptr_t uptr;
 12871  #elif SQLITE_PTRSIZE==4
 12872    typedef u32 uptr;
 12873  #else
 12874    typedef u64 uptr;
 12875  #endif
 12876  
 12877  /*
 12878  ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
 12879  ** something between S (inclusive) and E (exclusive).
 12880  **
 12881  ** In other words, S is a buffer and E is a pointer to the first byte after
 12882  ** the end of buffer S.  This macro returns true if P points to something
 12883  ** contained within the buffer S.
 12884  */
 12885  #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
 12886  
 12887  
 12888  /*
 12889  ** Macros to determine whether the machine is big or little endian,
 12890  ** and whether or not that determination is run-time or compile-time.
 12891  **
 12892  ** For best performance, an attempt is made to guess at the byte-order
 12893  ** using C-preprocessor macros.  If that is unsuccessful, or if
 12894  ** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
 12895  ** at run-time.
 12896  */
 12897  #ifndef SQLITE_BYTEORDER
 12898  # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
 12899       defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
 12900       defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
 12901       defined(__arm__)
 12902  #   define SQLITE_BYTEORDER    1234
 12903  # elif defined(sparc)    || defined(__ppc__)
 12904  #   define SQLITE_BYTEORDER    4321
 12905  # else
 12906  #   define SQLITE_BYTEORDER 0
 12907  # endif
 12908  #endif
 12909  #if SQLITE_BYTEORDER==4321
 12910  # define SQLITE_BIGENDIAN    1
 12911  # define SQLITE_LITTLEENDIAN 0
 12912  # define SQLITE_UTF16NATIVE  SQLITE_UTF16BE
 12913  #elif SQLITE_BYTEORDER==1234
 12914  # define SQLITE_BIGENDIAN    0
 12915  # define SQLITE_LITTLEENDIAN 1
 12916  # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
 12917  #else
 12918  # ifdef SQLITE_AMALGAMATION
 12919    const int sqlite3one = 1;
 12920  # else
 12921    extern const int sqlite3one;
 12922  # endif
 12923  # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
 12924  # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
 12925  # define SQLITE_UTF16NATIVE  (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
 12926  #endif
 12927  
 12928  /*
 12929  ** Constants for the largest and smallest possible 64-bit signed integers.
 12930  ** These macros are designed to work correctly on both 32-bit and 64-bit
 12931  ** compilers.
 12932  */
 12933  #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
 12934  #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
 12935  
 12936  /*
 12937  ** Round up a number to the next larger multiple of 8.  This is used
 12938  ** to force 8-byte alignment on 64-bit architectures.
 12939  */
 12940  #define ROUND8(x)     (((x)+7)&~7)
 12941  
 12942  /*
 12943  ** Round down to the nearest multiple of 8
 12944  */
 12945  #define ROUNDDOWN8(x) ((x)&~7)
 12946  
 12947  /*
 12948  ** Assert that the pointer X is aligned to an 8-byte boundary.  This
 12949  ** macro is used only within assert() to verify that the code gets
 12950  ** all alignment restrictions correct.
 12951  **
 12952  ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
 12953  ** underlying malloc() implementation might return us 4-byte aligned
 12954  ** pointers.  In that case, only verify 4-byte alignment.
 12955  */
 12956  #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
 12957  # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
 12958  #else
 12959  # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
 12960  #endif
 12961  
 12962  /*
 12963  ** Disable MMAP on platforms where it is known to not work
 12964  */
 12965  #if defined(__OpenBSD__) || defined(__QNXNTO__)
 12966  # undef SQLITE_MAX_MMAP_SIZE
 12967  # define SQLITE_MAX_MMAP_SIZE 0
 12968  #endif
 12969  
 12970  /*
 12971  ** Default maximum size of memory used by memory-mapped I/O in the VFS
 12972  */
 12973  #ifdef __APPLE__
 12974  # include <TargetConditionals.h>
 12975  #endif
 12976  #ifndef SQLITE_MAX_MMAP_SIZE
 12977  # if defined(__linux__) \
 12978    || defined(_WIN32) \
 12979    || (defined(__APPLE__) && defined(__MACH__)) \
 12980    || defined(__sun) \
 12981    || defined(__FreeBSD__) \
 12982    || defined(__DragonFly__)
 12983  #   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */
 12984  # else
 12985  #   define SQLITE_MAX_MMAP_SIZE 0
 12986  # endif
 12987  #endif
 12988  
 12989  /*
 12990  ** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger
 12991  ** default MMAP_SIZE is specified at compile-time, make sure that it does
 12992  ** not exceed the maximum mmap size.
 12993  */
 12994  #ifndef SQLITE_DEFAULT_MMAP_SIZE
 12995  # define SQLITE_DEFAULT_MMAP_SIZE 0
 12996  #endif
 12997  #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
 12998  # undef SQLITE_DEFAULT_MMAP_SIZE
 12999  # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
 13000  #endif
 13001  
 13002  /*
 13003  ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
 13004  ** Priority is given to SQLITE_ENABLE_STAT4.  If either are defined, also
 13005  ** define SQLITE_ENABLE_STAT3_OR_STAT4
 13006  */
 13007  #ifdef SQLITE_ENABLE_STAT4
 13008  # undef SQLITE_ENABLE_STAT3
 13009  # define SQLITE_ENABLE_STAT3_OR_STAT4 1
 13010  #elif SQLITE_ENABLE_STAT3
 13011  # define SQLITE_ENABLE_STAT3_OR_STAT4 1
 13012  #elif SQLITE_ENABLE_STAT3_OR_STAT4
 13013  # undef SQLITE_ENABLE_STAT3_OR_STAT4
 13014  #endif
 13015  
 13016  /*
 13017  ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
 13018  ** the Select query generator tracing logic is turned on.
 13019  */
 13020  #if defined(SQLITE_ENABLE_SELECTTRACE)
 13021  # define SELECTTRACE_ENABLED 1
 13022  #else
 13023  # define SELECTTRACE_ENABLED 0
 13024  #endif
 13025  
 13026  /*
 13027  ** An instance of the following structure is used to store the busy-handler
 13028  ** callback for a given sqlite handle.
 13029  **
 13030  ** The sqlite.busyHandler member of the sqlite struct contains the busy
 13031  ** callback for the database handle. Each pager opened via the sqlite
 13032  ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
 13033  ** callback is currently invoked only from within pager.c.
 13034  */
 13035  typedef struct BusyHandler BusyHandler;
 13036  struct BusyHandler {
 13037    int (*xFunc)(void *,int);  /* The busy callback */
 13038    void *pArg;                /* First arg to busy callback */
 13039    int nBusy;                 /* Incremented with each busy call */
 13040  };
 13041  
 13042  /*
 13043  ** Name of the master database table.  The master database table
 13044  ** is a special table that holds the names and attributes of all
 13045  ** user tables and indices.
 13046  */
 13047  #define MASTER_NAME       "sqlite_master"
 13048  #define TEMP_MASTER_NAME  "sqlite_temp_master"
 13049  
 13050  /*
 13051  ** The root-page of the master database table.
 13052  */
 13053  #define MASTER_ROOT       1
 13054  
 13055  /*
 13056  ** The name of the schema table.
 13057  */
 13058  #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
 13059  
 13060  /*
 13061  ** A convenience macro that returns the number of elements in
 13062  ** an array.
 13063  */
 13064  #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
 13065  
 13066  /*
 13067  ** Determine if the argument is a power of two
 13068  */
 13069  #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
 13070  
 13071  /*
 13072  ** The following value as a destructor means to use sqlite3DbFree().
 13073  ** The sqlite3DbFree() routine requires two parameters instead of the
 13074  ** one parameter that destructors normally want.  So we have to introduce
 13075  ** this magic value that the code knows to handle differently.  Any
 13076  ** pointer will work here as long as it is distinct from SQLITE_STATIC
 13077  ** and SQLITE_TRANSIENT.
 13078  */
 13079  #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
 13080  
 13081  /*
 13082  ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
 13083  ** not support Writable Static Data (WSD) such as global and static variables.
 13084  ** All variables must either be on the stack or dynamically allocated from
 13085  ** the heap.  When WSD is unsupported, the variable declarations scattered
 13086  ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
 13087  ** macro is used for this purpose.  And instead of referencing the variable
 13088  ** directly, we use its constant as a key to lookup the run-time allocated
 13089  ** buffer that holds real variable.  The constant is also the initializer
 13090  ** for the run-time allocated buffer.
 13091  **
 13092  ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
 13093  ** macros become no-ops and have zero performance impact.
 13094  */
 13095  #ifdef SQLITE_OMIT_WSD
 13096    #define SQLITE_WSD const
 13097    #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
 13098    #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
 13099  SQLITE_API int sqlite3_wsd_init(int N, int J);
 13100  SQLITE_API void *sqlite3_wsd_find(void *K, int L);
 13101  #else
 13102    #define SQLITE_WSD
 13103    #define GLOBAL(t,v) v
 13104    #define sqlite3GlobalConfig sqlite3Config
 13105  #endif
 13106  
 13107  /*
 13108  ** The following macros are used to suppress compiler warnings and to
 13109  ** make it clear to human readers when a function parameter is deliberately
 13110  ** left unused within the body of a function. This usually happens when
 13111  ** a function is called via a function pointer. For example the
 13112  ** implementation of an SQL aggregate step callback may not use the
 13113  ** parameter indicating the number of arguments passed to the aggregate,
 13114  ** if it knows that this is enforced elsewhere.
 13115  **
 13116  ** When a function parameter is not used at all within the body of a function,
 13117  ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
 13118  ** However, these macros may also be used to suppress warnings related to
 13119  ** parameters that may or may not be used depending on compilation options.
 13120  ** For example those parameters only used in assert() statements. In these
 13121  ** cases the parameters are named as per the usual conventions.
 13122  */
 13123  #define UNUSED_PARAMETER(x) (void)(x)
 13124  #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
 13125  
 13126  /*
 13127  ** Forward references to structures
 13128  */
 13129  typedef struct AggInfo AggInfo;
 13130  typedef struct AuthContext AuthContext;
 13131  typedef struct AutoincInfo AutoincInfo;
 13132  typedef struct Bitvec Bitvec;
 13133  typedef struct CollSeq CollSeq;
 13134  typedef struct Column Column;
 13135  typedef struct Db Db;
 13136  typedef struct Schema Schema;
 13137  typedef struct Expr Expr;
 13138  typedef struct ExprList ExprList;
 13139  typedef struct ExprSpan ExprSpan;
 13140  typedef struct FKey FKey;
 13141  typedef struct FuncDestructor FuncDestructor;
 13142  typedef struct FuncDef FuncDef;
 13143  typedef struct FuncDefHash FuncDefHash;
 13144  typedef struct IdList IdList;
 13145  typedef struct Index Index;
 13146  typedef struct IndexSample IndexSample;
 13147  typedef struct KeyClass KeyClass;
 13148  typedef struct KeyInfo KeyInfo;
 13149  typedef struct Lookaside Lookaside;
 13150  typedef struct LookasideSlot LookasideSlot;
 13151  typedef struct Module Module;
 13152  typedef struct NameContext NameContext;
 13153  typedef struct Parse Parse;
 13154  typedef struct PreUpdate PreUpdate;
 13155  typedef struct PrintfArguments PrintfArguments;
 13156  typedef struct RowSet RowSet;
 13157  typedef struct Savepoint Savepoint;
 13158  typedef struct Select Select;
 13159  typedef struct SQLiteThread SQLiteThread;
 13160  typedef struct SelectDest SelectDest;
 13161  typedef struct SrcList SrcList;
 13162  typedef struct StrAccum StrAccum;
 13163  typedef struct Table Table;
 13164  typedef struct TableLock TableLock;
 13165  typedef struct Token Token;
 13166  typedef struct TreeView TreeView;
 13167  typedef struct Trigger Trigger;
 13168  typedef struct TriggerPrg TriggerPrg;
 13169  typedef struct TriggerStep TriggerStep;
 13170  typedef struct UnpackedRecord UnpackedRecord;
 13171  typedef struct VTable VTable;
 13172  typedef struct VtabCtx VtabCtx;
 13173  typedef struct Walker Walker;
 13174  typedef struct WhereInfo WhereInfo;
 13175  typedef struct With With;
 13176  
 13177  /* A VList object records a mapping between parameters/variables/wildcards
 13178  ** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
 13179  ** variable number associated with that parameter.  See the format description
 13180  ** on the sqlite3VListAdd() routine for more information.  A VList is really
 13181  ** just an array of integers.
 13182  */
 13183  typedef int VList;
 13184  
 13185  /*
 13186  ** Defer sourcing vdbe.h and btree.h until after the "u8" and
 13187  ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
 13188  ** pointer types (i.e. FuncDef) defined above.
 13189  */
 13190  /************** Include btree.h in the middle of sqliteInt.h *****************/
 13191  /************** Begin file btree.h *******************************************/
 13192  /*
 13193  ** 2001 September 15
 13194  **
 13195  ** The author disclaims copyright to this source code.  In place of
 13196  ** a legal notice, here is a blessing:
 13197  **
 13198  **    May you do good and not evil.
 13199  **    May you find forgiveness for yourself and forgive others.
 13200  **    May you share freely, never taking more than you give.
 13201  **
 13202  *************************************************************************
 13203  ** This header file defines the interface that the sqlite B-Tree file
 13204  ** subsystem.  See comments in the source code for a detailed description
 13205  ** of what each interface routine does.
 13206  */
 13207  #ifndef SQLITE_BTREE_H
 13208  #define SQLITE_BTREE_H
 13209  
 13210  /* TODO: This definition is just included so other modules compile. It
 13211  ** needs to be revisited.
 13212  */
 13213  #define SQLITE_N_BTREE_META 16
 13214  
 13215  /*
 13216  ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
 13217  ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
 13218  */
 13219  #ifndef SQLITE_DEFAULT_AUTOVACUUM
 13220    #define SQLITE_DEFAULT_AUTOVACUUM 0
 13221  #endif
 13222  
 13223  #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
 13224  #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
 13225  #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
 13226  
 13227  /*
 13228  ** Forward declarations of structure
 13229  */
 13230  typedef struct Btree Btree;
 13231  typedef struct BtCursor BtCursor;
 13232  typedef struct BtShared BtShared;
 13233  typedef struct BtreePayload BtreePayload;
 13234  
 13235  
 13236  SQLITE_PRIVATE int sqlite3BtreeOpen(
 13237    sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
 13238    const char *zFilename,   /* Name of database file to open */
 13239    sqlite3 *db,             /* Associated database connection */
 13240    Btree **ppBtree,         /* Return open Btree* here */
 13241    int flags,               /* Flags */
 13242    int vfsFlags             /* Flags passed through to VFS open */
 13243  );
 13244  
 13245  /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
 13246  ** following values.
 13247  **
 13248  ** NOTE:  These values must match the corresponding PAGER_ values in
 13249  ** pager.h.
 13250  */
 13251  #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
 13252  #define BTREE_MEMORY        2  /* This is an in-memory DB */
 13253  #define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
 13254  #define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
 13255  
 13256  SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
 13257  SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
 13258  SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
 13259  #if SQLITE_MAX_MMAP_SIZE>0
 13260  SQLITE_PRIVATE   int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
 13261  #endif
 13262  SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
 13263  SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
 13264  SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
 13265  SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
 13266  SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
 13267  SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
 13268  SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
 13269  SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
 13270  SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
 13271  SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
 13272  SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
 13273  SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
 13274  SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
 13275  SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
 13276  SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
 13277  SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
 13278  SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
 13279  SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
 13280  SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
 13281  SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
 13282  SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
 13283  SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
 13284  #ifndef SQLITE_OMIT_SHARED_CACHE
 13285  SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
 13286  #endif
 13287  SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
 13288  
 13289  SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
 13290  SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
 13291  SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
 13292  
 13293  SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
 13294  
 13295  /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
 13296  ** of the flags shown below.
 13297  **
 13298  ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
 13299  ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
 13300  ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
 13301  ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
 13302  ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
 13303  ** indices.)
 13304  */
 13305  #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
 13306  #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
 13307  
 13308  SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
 13309  SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
 13310  SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
 13311  SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
 13312  
 13313  SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
 13314  SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
 13315  
 13316  SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
 13317  
 13318  /*
 13319  ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
 13320  ** should be one of the following values. The integer values are assigned 
 13321  ** to constants so that the offset of the corresponding field in an
 13322  ** SQLite database header may be found using the following formula:
 13323  **
 13324  **   offset = 36 + (idx * 4)
 13325  **
 13326  ** For example, the free-page-count field is located at byte offset 36 of
 13327  ** the database file header. The incr-vacuum-flag field is located at
 13328  ** byte offset 64 (== 36+4*7).
 13329  **
 13330  ** The BTREE_DATA_VERSION value is not really a value stored in the header.
 13331  ** It is a read-only number computed by the pager.  But we merge it with
 13332  ** the header value access routines since its access pattern is the same.
 13333  ** Call it a "virtual meta value".
 13334  */
 13335  #define BTREE_FREE_PAGE_COUNT     0
 13336  #define BTREE_SCHEMA_VERSION      1
 13337  #define BTREE_FILE_FORMAT         2
 13338  #define BTREE_DEFAULT_CACHE_SIZE  3
 13339  #define BTREE_LARGEST_ROOT_PAGE   4
 13340  #define BTREE_TEXT_ENCODING       5
 13341  #define BTREE_USER_VERSION        6
 13342  #define BTREE_INCR_VACUUM         7
 13343  #define BTREE_APPLICATION_ID      8
 13344  #define BTREE_DATA_VERSION        15  /* A virtual meta-value */
 13345  
 13346  /*
 13347  ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
 13348  ** interface.
 13349  **
 13350  ** BTREE_HINT_RANGE  (arguments: Expr*, Mem*)
 13351  **
 13352  **     The first argument is an Expr* (which is guaranteed to be constant for
 13353  **     the lifetime of the cursor) that defines constraints on which rows
 13354  **     might be fetched with this cursor.  The Expr* tree may contain
 13355  **     TK_REGISTER nodes that refer to values stored in the array of registers
 13356  **     passed as the second parameter.  In other words, if Expr.op==TK_REGISTER
 13357  **     then the value of the node is the value in Mem[pExpr.iTable].  Any
 13358  **     TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
 13359  **     column of the b-tree of the cursor.  The Expr tree will not contain
 13360  **     any function calls nor subqueries nor references to b-trees other than
 13361  **     the cursor being hinted.
 13362  **
 13363  **     The design of the _RANGE hint is aid b-tree implementations that try
 13364  **     to prefetch content from remote machines - to provide those
 13365  **     implementations with limits on what needs to be prefetched and thereby
 13366  **     reduce network bandwidth.
 13367  **
 13368  ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
 13369  ** standard SQLite.  The other hints are provided for extentions that use
 13370  ** the SQLite parser and code generator but substitute their own storage
 13371  ** engine.
 13372  */
 13373  #define BTREE_HINT_RANGE 0       /* Range constraints on queries */
 13374  
 13375  /*
 13376  ** Values that may be OR'd together to form the argument to the
 13377  ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
 13378  **
 13379  ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
 13380  ** to be filled with content that is already in sorted order.
 13381  **
 13382  ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
 13383  ** OP_SeekLE opcodes for a range search, but where the range of entries
 13384  ** selected will all have the same key.  In other words, the cursor will
 13385  ** be used only for equality key searches.
 13386  **
 13387  */
 13388  #define BTREE_BULKLOAD 0x00000001  /* Used to full index in sorted order */
 13389  #define BTREE_SEEK_EQ  0x00000002  /* EQ seeks only - no range seeks */
 13390  
 13391  /* 
 13392  ** Flags passed as the third argument to sqlite3BtreeCursor().
 13393  **
 13394  ** For read-only cursors the wrFlag argument is always zero. For read-write
 13395  ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
 13396  ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
 13397  ** only be used by SQLite for the following:
 13398  **
 13399  **   * to seek to and then delete specific entries, and/or
 13400  **
 13401  **   * to read values that will be used to create keys that other
 13402  **     BTREE_FORDELETE cursors will seek to and delete.
 13403  **
 13404  ** The BTREE_FORDELETE flag is an optimization hint.  It is not used by
 13405  ** by this, the native b-tree engine of SQLite, but it is available to
 13406  ** alternative storage engines that might be substituted in place of this
 13407  ** b-tree system.  For alternative storage engines in which a delete of
 13408  ** the main table row automatically deletes corresponding index rows,
 13409  ** the FORDELETE flag hint allows those alternative storage engines to
 13410  ** skip a lot of work.  Namely:  FORDELETE cursors may treat all SEEK
 13411  ** and DELETE operations as no-ops, and any READ operation against a
 13412  ** FORDELETE cursor may return a null row: 0x01 0x00.
 13413  */
 13414  #define BTREE_WRCSR     0x00000004     /* read-write cursor */
 13415  #define BTREE_FORDELETE 0x00000008     /* Cursor is for seek/delete only */
 13416  
 13417  SQLITE_PRIVATE int sqlite3BtreeCursor(
 13418    Btree*,                              /* BTree containing table to open */
 13419    int iTable,                          /* Index of root page */
 13420    int wrFlag,                          /* 1 for writing.  0 for read-only */
 13421    struct KeyInfo*,                     /* First argument to compare function */
 13422    BtCursor *pCursor                    /* Space to write cursor structure */
 13423  );
 13424  SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void);
 13425  SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
 13426  SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
 13427  SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
 13428  #ifdef SQLITE_ENABLE_CURSOR_HINTS
 13429  SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
 13430  #endif
 13431  
 13432  SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
 13433  SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
 13434    BtCursor*,
 13435    UnpackedRecord *pUnKey,
 13436    i64 intKey,
 13437    int bias,
 13438    int *pRes
 13439  );
 13440  SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
 13441  SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
 13442  SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
 13443  
 13444  /* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */
 13445  #define BTREE_SAVEPOSITION 0x02  /* Leave cursor pointing at NEXT or PREV */
 13446  #define BTREE_AUXDELETE    0x04  /* not the primary delete operation */
 13447  #define BTREE_APPEND       0x08  /* Insert is likely an append */
 13448  
 13449  /* An instance of the BtreePayload object describes the content of a single
 13450  ** entry in either an index or table btree.
 13451  **
 13452  ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
 13453  ** an arbitrary key and no data.  These btrees have pKey,nKey set to their
 13454  ** key and pData,nData,nZero set to zero.
 13455  **
 13456  ** Table btrees (used for rowid tables) contain an integer rowid used as
 13457  ** the key and passed in the nKey field.  The pKey field is zero.  
 13458  ** pData,nData hold the content of the new entry.  nZero extra zero bytes
 13459  ** are appended to the end of the content when constructing the entry.
 13460  **
 13461  ** This object is used to pass information into sqlite3BtreeInsert().  The
 13462  ** same information used to be passed as five separate parameters.  But placing
 13463  ** the information into this object helps to keep the interface more 
 13464  ** organized and understandable, and it also helps the resulting code to
 13465  ** run a little faster by using fewer registers for parameter passing.
 13466  */
 13467  struct BtreePayload {
 13468    const void *pKey;       /* Key content for indexes.  NULL for tables */
 13469    sqlite3_int64 nKey;     /* Size of pKey for indexes.  PRIMARY KEY for tabs */
 13470    const void *pData;      /* Data for tables.  NULL for indexes */
 13471    sqlite3_value *aMem;    /* First of nMem value in the unpacked pKey */
 13472    u16 nMem;               /* Number of aMem[] value.  Might be zero */
 13473    int nData;              /* Size of pData.  0 if none. */
 13474    int nZero;              /* Extra zero data appended after pData,nData */
 13475  };
 13476  
 13477  SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
 13478                         int flags, int seekResult);
 13479  SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
 13480  SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
 13481  SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int flags);
 13482  SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
 13483  SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int flags);
 13484  SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
 13485  SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);
 13486  SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
 13487  SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
 13488  
 13489  SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
 13490  SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
 13491  SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);
 13492  
 13493  #ifndef SQLITE_OMIT_INCRBLOB
 13494  SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);
 13495  SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
 13496  SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
 13497  #endif
 13498  SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
 13499  SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
 13500  SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
 13501  SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
 13502  SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
 13503  
 13504  #ifndef NDEBUG
 13505  SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
 13506  #endif
 13507  SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);
 13508  
 13509  #ifndef SQLITE_OMIT_BTREECOUNT
 13510  SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
 13511  #endif
 13512  
 13513  #ifdef SQLITE_TEST
 13514  SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
 13515  SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
 13516  #endif
 13517  
 13518  #ifndef SQLITE_OMIT_WAL
 13519  SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
 13520  #endif
 13521  
 13522  /*
 13523  ** If we are not using shared cache, then there is no need to
 13524  ** use mutexes to access the BtShared structures.  So make the
 13525  ** Enter and Leave procedures no-ops.
 13526  */
 13527  #ifndef SQLITE_OMIT_SHARED_CACHE
 13528  SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
 13529  SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
 13530  SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
 13531  SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
 13532  SQLITE_PRIVATE   int sqlite3BtreeConnectionCount(Btree*);
 13533  #else
 13534  # define sqlite3BtreeEnter(X) 
 13535  # define sqlite3BtreeEnterAll(X)
 13536  # define sqlite3BtreeSharable(X) 0
 13537  # define sqlite3BtreeEnterCursor(X)
 13538  # define sqlite3BtreeConnectionCount(X) 1
 13539  #endif
 13540  
 13541  #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
 13542  SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
 13543  SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
 13544  SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
 13545  #ifndef NDEBUG
 13546    /* These routines are used inside assert() statements only. */
 13547  SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
 13548  SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
 13549  SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
 13550  #endif
 13551  #else
 13552  
 13553  # define sqlite3BtreeLeave(X)
 13554  # define sqlite3BtreeLeaveCursor(X)
 13555  # define sqlite3BtreeLeaveAll(X)
 13556  
 13557  # define sqlite3BtreeHoldsMutex(X) 1
 13558  # define sqlite3BtreeHoldsAllMutexes(X) 1
 13559  # define sqlite3SchemaMutexHeld(X,Y,Z) 1
 13560  #endif
 13561  
 13562  
 13563  #endif /* SQLITE_BTREE_H */
 13564  
 13565  /************** End of btree.h ***********************************************/
 13566  /************** Continuing where we left off in sqliteInt.h ******************/
 13567  /************** Include vdbe.h in the middle of sqliteInt.h ******************/
 13568  /************** Begin file vdbe.h ********************************************/
 13569  /*
 13570  ** 2001 September 15
 13571  **
 13572  ** The author disclaims copyright to this source code.  In place of
 13573  ** a legal notice, here is a blessing:
 13574  **
 13575  **    May you do good and not evil.
 13576  **    May you find forgiveness for yourself and forgive others.
 13577  **    May you share freely, never taking more than you give.
 13578  **
 13579  *************************************************************************
 13580  ** Header file for the Virtual DataBase Engine (VDBE)
 13581  **
 13582  ** This header defines the interface to the virtual database engine
 13583  ** or VDBE.  The VDBE implements an abstract machine that runs a
 13584  ** simple program to access and modify the underlying database.
 13585  */
 13586  #ifndef SQLITE_VDBE_H
 13587  #define SQLITE_VDBE_H
 13588  /* #include <stdio.h> */
 13589  
 13590  /*
 13591  ** A single VDBE is an opaque structure named "Vdbe".  Only routines
 13592  ** in the source file sqliteVdbe.c are allowed to see the insides
 13593  ** of this structure.
 13594  */
 13595  typedef struct Vdbe Vdbe;
 13596  
 13597  /*
 13598  ** The names of the following types declared in vdbeInt.h are required
 13599  ** for the VdbeOp definition.
 13600  */
 13601  typedef struct sqlite3_value Mem;
 13602  typedef struct SubProgram SubProgram;
 13603  
 13604  /*
 13605  ** A single instruction of the virtual machine has an opcode
 13606  ** and as many as three operands.  The instruction is recorded
 13607  ** as an instance of the following structure:
 13608  */
 13609  struct VdbeOp {
 13610    u8 opcode;          /* What operation to perform */
 13611    signed char p4type; /* One of the P4_xxx constants for p4 */
 13612    u16 p5;             /* Fifth parameter is an unsigned 16-bit integer */
 13613    int p1;             /* First operand */
 13614    int p2;             /* Second parameter (often the jump destination) */
 13615    int p3;             /* The third parameter */
 13616    union p4union {     /* fourth parameter */
 13617      int i;                 /* Integer value if p4type==P4_INT32 */
 13618      void *p;               /* Generic pointer */
 13619      char *z;               /* Pointer to data for string (char array) types */
 13620      i64 *pI64;             /* Used when p4type is P4_INT64 */
 13621      double *pReal;         /* Used when p4type is P4_REAL */
 13622      FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
 13623      sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
 13624      CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
 13625      Mem *pMem;             /* Used when p4type is P4_MEM */
 13626      VTable *pVtab;         /* Used when p4type is P4_VTAB */
 13627      KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
 13628      int *ai;               /* Used when p4type is P4_INTARRAY */
 13629      SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
 13630      Table *pTab;           /* Used when p4type is P4_TABLE */
 13631  #ifdef SQLITE_ENABLE_CURSOR_HINTS
 13632      Expr *pExpr;           /* Used when p4type is P4_EXPR */
 13633  #endif
 13634      int (*xAdvance)(BtCursor *, int);
 13635    } p4;
 13636  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 13637    char *zComment;          /* Comment to improve readability */
 13638  #endif
 13639  #ifdef VDBE_PROFILE
 13640    u32 cnt;                 /* Number of times this instruction was executed */
 13641    u64 cycles;              /* Total time spent executing this instruction */
 13642  #endif
 13643  #ifdef SQLITE_VDBE_COVERAGE
 13644    int iSrcLine;            /* Source-code line that generated this opcode */
 13645  #endif
 13646  };
 13647  typedef struct VdbeOp VdbeOp;
 13648  
 13649  
 13650  /*
 13651  ** A sub-routine used to implement a trigger program.
 13652  */
 13653  struct SubProgram {
 13654    VdbeOp *aOp;                  /* Array of opcodes for sub-program */
 13655    int nOp;                      /* Elements in aOp[] */
 13656    int nMem;                     /* Number of memory cells required */
 13657    int nCsr;                     /* Number of cursors required */
 13658    u8 *aOnce;                    /* Array of OP_Once flags */
 13659    void *token;                  /* id that may be used to recursive triggers */
 13660    SubProgram *pNext;            /* Next sub-program already visited */
 13661  };
 13662  
 13663  /*
 13664  ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
 13665  ** it takes up less space.
 13666  */
 13667  struct VdbeOpList {
 13668    u8 opcode;          /* What operation to perform */
 13669    signed char p1;     /* First operand */
 13670    signed char p2;     /* Second parameter (often the jump destination) */
 13671    signed char p3;     /* Third parameter */
 13672  };
 13673  typedef struct VdbeOpList VdbeOpList;
 13674  
 13675  /*
 13676  ** Allowed values of VdbeOp.p4type
 13677  */
 13678  #define P4_NOTUSED      0   /* The P4 parameter is not used */
 13679  #define P4_TRANSIENT    0   /* P4 is a pointer to a transient string */
 13680  #define P4_STATIC     (-1)  /* Pointer to a static string */
 13681  #define P4_COLLSEQ    (-2)  /* P4 is a pointer to a CollSeq structure */
 13682  #define P4_INT32      (-3)  /* P4 is a 32-bit signed integer */
 13683  #define P4_SUBPROGRAM (-4)  /* P4 is a pointer to a SubProgram structure */
 13684  #define P4_ADVANCE    (-5)  /* P4 is a pointer to BtreeNext() or BtreePrev() */
 13685  #define P4_TABLE      (-6)  /* P4 is a pointer to a Table structure */
 13686  /* Above do not own any resources.  Must free those below */
 13687  #define P4_FREE_IF_LE (-7)
 13688  #define P4_DYNAMIC    (-7)  /* Pointer to memory from sqliteMalloc() */
 13689  #define P4_FUNCDEF    (-8)  /* P4 is a pointer to a FuncDef structure */
 13690  #define P4_KEYINFO    (-9)  /* P4 is a pointer to a KeyInfo structure */
 13691  #define P4_EXPR       (-10) /* P4 is a pointer to an Expr tree */
 13692  #define P4_MEM        (-11) /* P4 is a pointer to a Mem*    structure */
 13693  #define P4_VTAB       (-12) /* P4 is a pointer to an sqlite3_vtab structure */
 13694  #define P4_REAL       (-13) /* P4 is a 64-bit floating point value */
 13695  #define P4_INT64      (-14) /* P4 is a 64-bit signed integer */
 13696  #define P4_INTARRAY   (-15) /* P4 is a vector of 32-bit integers */
 13697  #define P4_FUNCCTX    (-16) /* P4 is a pointer to an sqlite3_context object */
 13698  
 13699  /* Error message codes for OP_Halt */
 13700  #define P5_ConstraintNotNull 1
 13701  #define P5_ConstraintUnique  2
 13702  #define P5_ConstraintCheck   3
 13703  #define P5_ConstraintFK      4
 13704  
 13705  /*
 13706  ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
 13707  ** number of columns of data returned by the statement.
 13708  */
 13709  #define COLNAME_NAME     0
 13710  #define COLNAME_DECLTYPE 1
 13711  #define COLNAME_DATABASE 2
 13712  #define COLNAME_TABLE    3
 13713  #define COLNAME_COLUMN   4
 13714  #ifdef SQLITE_ENABLE_COLUMN_METADATA
 13715  # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
 13716  #else
 13717  # ifdef SQLITE_OMIT_DECLTYPE
 13718  #   define COLNAME_N      1      /* Store only the name */
 13719  # else
 13720  #   define COLNAME_N      2      /* Store the name and decltype */
 13721  # endif
 13722  #endif
 13723  
 13724  /*
 13725  ** The following macro converts a relative address in the p2 field
 13726  ** of a VdbeOp structure into a negative number so that 
 13727  ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
 13728  ** the macro again restores the address.
 13729  */
 13730  #define ADDR(X)  (-1-(X))
 13731  
 13732  /*
 13733  ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
 13734  ** header file that defines a number for each opcode used by the VDBE.
 13735  */
 13736  /************** Include opcodes.h in the middle of vdbe.h ********************/
 13737  /************** Begin file opcodes.h *****************************************/
 13738  /* Automatically generated.  Do not edit */
 13739  /* See the tool/mkopcodeh.tcl script for details */
 13740  #define OP_Savepoint       0
 13741  #define OP_AutoCommit      1
 13742  #define OP_Transaction     2
 13743  #define OP_SorterNext      3 /* jump                                       */
 13744  #define OP_PrevIfOpen      4 /* jump                                       */
 13745  #define OP_NextIfOpen      5 /* jump                                       */
 13746  #define OP_Prev            6 /* jump                                       */
 13747  #define OP_Next            7 /* jump                                       */
 13748  #define OP_Checkpoint      8
 13749  #define OP_JournalMode     9
 13750  #define OP_Vacuum         10
 13751  #define OP_VFilter        11 /* jump, synopsis: iplan=r[P3] zplan='P4'     */
 13752  #define OP_VUpdate        12 /* synopsis: data=r[P3@P2]                    */
 13753  #define OP_Goto           13 /* jump                                       */
 13754  #define OP_Gosub          14 /* jump                                       */
 13755  #define OP_InitCoroutine  15 /* jump                                       */
 13756  #define OP_Yield          16 /* jump                                       */
 13757  #define OP_MustBeInt      17 /* jump                                       */
 13758  #define OP_Jump           18 /* jump                                       */
 13759  #define OP_Not            19 /* same as TK_NOT, synopsis: r[P2]= !r[P1]    */
 13760  #define OP_Once           20 /* jump                                       */
 13761  #define OP_If             21 /* jump                                       */
 13762  #define OP_IfNot          22 /* jump                                       */
 13763  #define OP_IfNullRow      23 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */
 13764  #define OP_SeekLT         24 /* jump, synopsis: key=r[P3@P4]               */
 13765  #define OP_SeekLE         25 /* jump, synopsis: key=r[P3@P4]               */
 13766  #define OP_SeekGE         26 /* jump, synopsis: key=r[P3@P4]               */
 13767  #define OP_SeekGT         27 /* jump, synopsis: key=r[P3@P4]               */
 13768  #define OP_NoConflict     28 /* jump, synopsis: key=r[P3@P4]               */
 13769  #define OP_NotFound       29 /* jump, synopsis: key=r[P3@P4]               */
 13770  #define OP_Found          30 /* jump, synopsis: key=r[P3@P4]               */
 13771  #define OP_SeekRowid      31 /* jump, synopsis: intkey=r[P3]               */
 13772  #define OP_NotExists      32 /* jump, synopsis: intkey=r[P3]               */
 13773  #define OP_Last           33 /* jump                                       */
 13774  #define OP_IfSmaller      34 /* jump                                       */
 13775  #define OP_SorterSort     35 /* jump                                       */
 13776  #define OP_Sort           36 /* jump                                       */
 13777  #define OP_Rewind         37 /* jump                                       */
 13778  #define OP_IdxLE          38 /* jump, synopsis: key=r[P3@P4]               */
 13779  #define OP_IdxGT          39 /* jump, synopsis: key=r[P3@P4]               */
 13780  #define OP_IdxLT          40 /* jump, synopsis: key=r[P3@P4]               */
 13781  #define OP_IdxGE          41 /* jump, synopsis: key=r[P3@P4]               */
 13782  #define OP_RowSetRead     42 /* jump, synopsis: r[P3]=rowset(P1)           */
 13783  #define OP_Or             43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
 13784  #define OP_And            44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
 13785  #define OP_RowSetTest     45 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
 13786  #define OP_Program        46 /* jump                                       */
 13787  #define OP_FkIfZero       47 /* jump, synopsis: if fkctr[P1]==0 goto P2    */
 13788  #define OP_IfPos          48 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
 13789  #define OP_IfNotZero      49 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
 13790  #define OP_IsNull         50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
 13791  #define OP_NotNull        51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
 13792  #define OP_Ne             52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */
 13793  #define OP_Eq             53 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */
 13794  #define OP_Gt             54 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */
 13795  #define OP_Le             55 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */
 13796  #define OP_Lt             56 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */
 13797  #define OP_Ge             57 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */
 13798  #define OP_ElseNotEq      58 /* jump, same as TK_ESCAPE                    */
 13799  #define OP_DecrJumpZero   59 /* jump, synopsis: if (--r[P1])==0 goto P2    */
 13800  #define OP_IncrVacuum     60 /* jump                                       */
 13801  #define OP_VNext          61 /* jump                                       */
 13802  #define OP_Init           62 /* jump, synopsis: Start at P2                */
 13803  #define OP_Return         63
 13804  #define OP_EndCoroutine   64
 13805  #define OP_HaltIfNull     65 /* synopsis: if r[P3]=null halt               */
 13806  #define OP_Halt           66
 13807  #define OP_Integer        67 /* synopsis: r[P2]=P1                         */
 13808  #define OP_Int64          68 /* synopsis: r[P2]=P4                         */
 13809  #define OP_String         69 /* synopsis: r[P2]='P4' (len=P1)              */
 13810  #define OP_Null           70 /* synopsis: r[P2..P3]=NULL                   */
 13811  #define OP_SoftNull       71 /* synopsis: r[P1]=NULL                       */
 13812  #define OP_Blob           72 /* synopsis: r[P2]=P4 (len=P1)                */
 13813  #define OP_Variable       73 /* synopsis: r[P2]=parameter(P1,P4)           */
 13814  #define OP_Move           74 /* synopsis: r[P2@P3]=r[P1@P3]                */
 13815  #define OP_Copy           75 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */
 13816  #define OP_SCopy          76 /* synopsis: r[P2]=r[P1]                      */
 13817  #define OP_IntCopy        77 /* synopsis: r[P2]=r[P1]                      */
 13818  #define OP_ResultRow      78 /* synopsis: output=r[P1@P2]                  */
 13819  #define OP_CollSeq        79
 13820  #define OP_AddImm         80 /* synopsis: r[P1]=r[P1]+P2                   */
 13821  #define OP_RealAffinity   81
 13822  #define OP_Cast           82 /* synopsis: affinity(r[P1])                  */
 13823  #define OP_Permutation    83
 13824  #define OP_BitAnd         84 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
 13825  #define OP_BitOr          85 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
 13826  #define OP_ShiftLeft      86 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
 13827  #define OP_ShiftRight     87 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
 13828  #define OP_Add            88 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
 13829  #define OP_Subtract       89 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
 13830  #define OP_Multiply       90 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
 13831  #define OP_Divide         91 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
 13832  #define OP_Remainder      92 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
 13833  #define OP_Concat         93 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
 13834  #define OP_Compare        94 /* synopsis: r[P1@P3] <-> r[P2@P3]            */
 13835  #define OP_BitNot         95 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
 13836  #define OP_Column         96 /* synopsis: r[P3]=PX                         */
 13837  #define OP_String8        97 /* same as TK_STRING, synopsis: r[P2]='P4'    */
 13838  #define OP_Affinity       98 /* synopsis: affinity(r[P1@P2])               */
 13839  #define OP_MakeRecord     99 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
 13840  #define OP_Count         100 /* synopsis: r[P2]=count()                    */
 13841  #define OP_ReadCookie    101
 13842  #define OP_SetCookie     102
 13843  #define OP_ReopenIdx     103 /* synopsis: root=P2 iDb=P3                   */
 13844  #define OP_OpenRead      104 /* synopsis: root=P2 iDb=P3                   */
 13845  #define OP_OpenWrite     105 /* synopsis: root=P2 iDb=P3                   */
 13846  #define OP_OpenDup       106
 13847  #define OP_OpenAutoindex 107 /* synopsis: nColumn=P2                       */
 13848  #define OP_OpenEphemeral 108 /* synopsis: nColumn=P2                       */
 13849  #define OP_SorterOpen    109
 13850  #define OP_SequenceTest  110 /* synopsis: if( cursor[P1].ctr++ ) pc = P2   */
 13851  #define OP_OpenPseudo    111 /* synopsis: P3 columns in r[P2]              */
 13852  #define OP_Close         112
 13853  #define OP_ColumnsUsed   113
 13854  #define OP_Sequence      114 /* synopsis: r[P2]=cursor[P1].ctr++           */
 13855  #define OP_NewRowid      115 /* synopsis: r[P2]=rowid                      */
 13856  #define OP_Insert        116 /* synopsis: intkey=r[P3] data=r[P2]          */
 13857  #define OP_InsertInt     117 /* synopsis: intkey=P3 data=r[P2]             */
 13858  #define OP_Delete        118
 13859  #define OP_ResetCount    119
 13860  #define OP_SorterCompare 120 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
 13861  #define OP_SorterData    121 /* synopsis: r[P2]=data                       */
 13862  #define OP_RowData       122 /* synopsis: r[P2]=data                       */
 13863  #define OP_Rowid         123 /* synopsis: r[P2]=rowid                      */
 13864  #define OP_NullRow       124
 13865  #define OP_SeekEnd       125
 13866  #define OP_SorterInsert  126 /* synopsis: key=r[P2]                        */
 13867  #define OP_IdxInsert     127 /* synopsis: key=r[P2]                        */
 13868  #define OP_IdxDelete     128 /* synopsis: key=r[P2@P3]                     */
 13869  #define OP_DeferredSeek  129 /* synopsis: Move P3 to P1.rowid if needed    */
 13870  #define OP_IdxRowid      130 /* synopsis: r[P2]=rowid                      */
 13871  #define OP_Destroy       131
 13872  #define OP_Real          132 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
 13873  #define OP_Clear         133
 13874  #define OP_ResetSorter   134
 13875  #define OP_CreateBtree   135 /* synopsis: r[P2]=root iDb=P1 flags=P3       */
 13876  #define OP_SqlExec       136
 13877  #define OP_ParseSchema   137
 13878  #define OP_LoadAnalysis  138
 13879  #define OP_DropTable     139
 13880  #define OP_DropIndex     140
 13881  #define OP_DropTrigger   141
 13882  #define OP_IntegrityCk   142
 13883  #define OP_RowSetAdd     143 /* synopsis: rowset(P1)=r[P2]                 */
 13884  #define OP_Param         144
 13885  #define OP_FkCounter     145 /* synopsis: fkctr[P1]+=P2                    */
 13886  #define OP_MemMax        146 /* synopsis: r[P1]=max(r[P1],r[P2])           */
 13887  #define OP_OffsetLimit   147 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
 13888  #define OP_AggStep0      148 /* synopsis: accum=r[P3] step(r[P2@P5])       */
 13889  #define OP_AggStep       149 /* synopsis: accum=r[P3] step(r[P2@P5])       */
 13890  #define OP_AggFinal      150 /* synopsis: accum=r[P1] N=P2                 */
 13891  #define OP_Expire        151
 13892  #define OP_TableLock     152 /* synopsis: iDb=P1 root=P2 write=P3          */
 13893  #define OP_VBegin        153
 13894  #define OP_VCreate       154
 13895  #define OP_VDestroy      155
 13896  #define OP_VOpen         156
 13897  #define OP_VColumn       157 /* synopsis: r[P3]=vcolumn(P2)                */
 13898  #define OP_VRename       158
 13899  #define OP_Pagecount     159
 13900  #define OP_MaxPgcnt      160
 13901  #define OP_PureFunc0     161
 13902  #define OP_Function0     162 /* synopsis: r[P3]=func(r[P2@P5])             */
 13903  #define OP_PureFunc      163
 13904  #define OP_Function      164 /* synopsis: r[P3]=func(r[P2@P5])             */
 13905  #define OP_CursorHint    165
 13906  #define OP_Noop          166
 13907  #define OP_Explain       167
 13908  
 13909  /* Properties such as "out2" or "jump" that are specified in
 13910  ** comments following the "case" for each opcode in the vdbe.c
 13911  ** are encoded into bitvectors as follows:
 13912  */
 13913  #define OPFLG_JUMP        0x01  /* jump:  P2 holds jmp target */
 13914  #define OPFLG_IN1         0x02  /* in1:   P1 is an input */
 13915  #define OPFLG_IN2         0x04  /* in2:   P2 is an input */
 13916  #define OPFLG_IN3         0x08  /* in3:   P3 is an input */
 13917  #define OPFLG_OUT2        0x10  /* out2:  P2 is an output */
 13918  #define OPFLG_OUT3        0x20  /* out3:  P3 is an output */
 13919  #define OPFLG_INITIALIZER {\
 13920  /*   0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\
 13921  /*   8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\
 13922  /*  16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x01,\
 13923  /*  24 */ 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09,\
 13924  /*  32 */ 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\
 13925  /*  40 */ 0x01, 0x01, 0x23, 0x26, 0x26, 0x0b, 0x01, 0x01,\
 13926  /*  48 */ 0x03, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
 13927  /*  56 */ 0x0b, 0x0b, 0x01, 0x03, 0x01, 0x01, 0x01, 0x02,\
 13928  /*  64 */ 0x02, 0x08, 0x00, 0x10, 0x10, 0x10, 0x10, 0x00,\
 13929  /*  72 */ 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
 13930  /*  80 */ 0x02, 0x02, 0x02, 0x00, 0x26, 0x26, 0x26, 0x26,\
 13931  /*  88 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00, 0x12,\
 13932  /*  96 */ 0x00, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
 13933  /* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
 13934  /* 112 */ 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00,\
 13935  /* 120 */ 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x04, 0x04,\
 13936  /* 128 */ 0x00, 0x00, 0x10, 0x10, 0x10, 0x00, 0x00, 0x10,\
 13937  /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06,\
 13938  /* 144 */ 0x10, 0x00, 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00,\
 13939  /* 152 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\
 13940  /* 160 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
 13941  }
 13942  
 13943  /* The sqlite3P2Values() routine is able to run faster if it knows
 13944  ** the value of the largest JUMP opcode.  The smaller the maximum
 13945  ** JUMP opcode the better, so the mkopcodeh.tcl script that
 13946  ** generated this include file strives to group all JUMP opcodes
 13947  ** together near the beginning of the list.
 13948  */
 13949  #define SQLITE_MX_JUMP_OPCODE  62  /* Maximum JUMP opcode */
 13950  
 13951  /************** End of opcodes.h *********************************************/
 13952  /************** Continuing where we left off in vdbe.h ***********************/
 13953  
 13954  /*
 13955  ** Additional non-public SQLITE_PREPARE_* flags
 13956  */
 13957  #define SQLITE_PREPARE_SAVESQL  0x80  /* Preserve SQL text */
 13958  #define SQLITE_PREPARE_MASK     0x0f  /* Mask of public flags */
 13959  
 13960  /*
 13961  ** Prototypes for the VDBE interface.  See comments on the implementation
 13962  ** for a description of what each of these routines does.
 13963  */
 13964  SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
 13965  SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
 13966  SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
 13967  SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
 13968  SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
 13969  SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
 13970  SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
 13971  SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
 13972  SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
 13973  SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
 13974  SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
 13975  SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
 13976  #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
 13977  SQLITE_PRIVATE   void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
 13978  SQLITE_PRIVATE   void sqlite3VdbeVerifyNoResultRow(Vdbe *p);
 13979  #else
 13980  # define sqlite3VdbeVerifyNoMallocRequired(A,B)
 13981  # define sqlite3VdbeVerifyNoResultRow(A)
 13982  #endif
 13983  SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
 13984  SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
 13985  SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
 13986  SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
 13987  SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
 13988  SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
 13989  SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
 13990  SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
 13991  SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
 13992  SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
 13993  SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
 13994  SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);
 13995  SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
 13996  SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
 13997  SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
 13998  SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
 13999  SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
 14000  SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
 14001  SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
 14002  SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
 14003  SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
 14004  SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
 14005  SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
 14006  SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
 14007  #ifdef SQLITE_DEBUG
 14008  SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
 14009  #endif
 14010  SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
 14011  SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
 14012  SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
 14013  SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
 14014  SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
 14015  SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
 14016  SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
 14017  SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe*);
 14018  SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, u8);
 14019  SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
 14020  SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
 14021  SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
 14022  SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
 14023  #ifndef SQLITE_OMIT_TRACE
 14024  SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
 14025  #endif
 14026  SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
 14027  
 14028  SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
 14029  SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
 14030  SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
 14031  SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);
 14032  
 14033  typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
 14034  SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
 14035  
 14036  #ifndef SQLITE_OMIT_TRIGGER
 14037  SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
 14038  #endif
 14039  
 14040  SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*);
 14041  
 14042  /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
 14043  ** each VDBE opcode.
 14044  **
 14045  ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
 14046  ** comments in VDBE programs that show key decision points in the code
 14047  ** generator.
 14048  */
 14049  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 14050  SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
 14051  # define VdbeComment(X)  sqlite3VdbeComment X
 14052  SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
 14053  # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
 14054  # ifdef SQLITE_ENABLE_MODULE_COMMENTS
 14055  #   define VdbeModuleComment(X)  sqlite3VdbeNoopComment X
 14056  # else
 14057  #   define VdbeModuleComment(X)
 14058  # endif
 14059  #else
 14060  # define VdbeComment(X)
 14061  # define VdbeNoopComment(X)
 14062  # define VdbeModuleComment(X)
 14063  #endif
 14064  
 14065  /*
 14066  ** The VdbeCoverage macros are used to set a coverage testing point
 14067  ** for VDBE branch instructions.  The coverage testing points are line
 14068  ** numbers in the sqlite3.c source file.  VDBE branch coverage testing
 14069  ** only works with an amalagmation build.  That's ok since a VDBE branch
 14070  ** coverage build designed for testing the test suite only.  No application
 14071  ** should ever ship with VDBE branch coverage measuring turned on.
 14072  **
 14073  **    VdbeCoverage(v)                  // Mark the previously coded instruction
 14074  **                                     // as a branch
 14075  **
 14076  **    VdbeCoverageIf(v, conditional)   // Mark previous if conditional true
 14077  **
 14078  **    VdbeCoverageAlwaysTaken(v)       // Previous branch is always taken
 14079  **
 14080  **    VdbeCoverageNeverTaken(v)        // Previous branch is never taken
 14081  **
 14082  ** Every VDBE branch operation must be tagged with one of the macros above.
 14083  ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
 14084  ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
 14085  ** routine in vdbe.c, alerting the developer to the missed tag.
 14086  */
 14087  #ifdef SQLITE_VDBE_COVERAGE
 14088  SQLITE_PRIVATE   void sqlite3VdbeSetLineNumber(Vdbe*,int);
 14089  # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
 14090  # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
 14091  # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
 14092  # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
 14093  # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
 14094  #else
 14095  # define VdbeCoverage(v)
 14096  # define VdbeCoverageIf(v,x)
 14097  # define VdbeCoverageAlwaysTaken(v)
 14098  # define VdbeCoverageNeverTaken(v)
 14099  # define VDBE_OFFSET_LINENO(x) 0
 14100  #endif
 14101  
 14102  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 14103  SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
 14104  #else
 14105  # define sqlite3VdbeScanStatus(a,b,c,d,e)
 14106  #endif
 14107  
 14108  #endif /* SQLITE_VDBE_H */
 14109  
 14110  /************** End of vdbe.h ************************************************/
 14111  /************** Continuing where we left off in sqliteInt.h ******************/
 14112  /************** Include pager.h in the middle of sqliteInt.h *****************/
 14113  /************** Begin file pager.h *******************************************/
 14114  /*
 14115  ** 2001 September 15
 14116  **
 14117  ** The author disclaims copyright to this source code.  In place of
 14118  ** a legal notice, here is a blessing:
 14119  **
 14120  **    May you do good and not evil.
 14121  **    May you find forgiveness for yourself and forgive others.
 14122  **    May you share freely, never taking more than you give.
 14123  **
 14124  *************************************************************************
 14125  ** This header file defines the interface that the sqlite page cache
 14126  ** subsystem.  The page cache subsystem reads and writes a file a page
 14127  ** at a time and provides a journal for rollback.
 14128  */
 14129  
 14130  #ifndef SQLITE_PAGER_H
 14131  #define SQLITE_PAGER_H
 14132  
 14133  /*
 14134  ** Default maximum size for persistent journal files. A negative 
 14135  ** value means no limit. This value may be overridden using the 
 14136  ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
 14137  */
 14138  #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
 14139    #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
 14140  #endif
 14141  
 14142  /*
 14143  ** The type used to represent a page number.  The first page in a file
 14144  ** is called page 1.  0 is used to represent "not a page".
 14145  */
 14146  typedef u32 Pgno;
 14147  
 14148  /*
 14149  ** Each open file is managed by a separate instance of the "Pager" structure.
 14150  */
 14151  typedef struct Pager Pager;
 14152  
 14153  /*
 14154  ** Handle type for pages.
 14155  */
 14156  typedef struct PgHdr DbPage;
 14157  
 14158  /*
 14159  ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
 14160  ** reserved for working around a windows/posix incompatibility). It is
 14161  ** used in the journal to signify that the remainder of the journal file 
 14162  ** is devoted to storing a master journal name - there are no more pages to
 14163  ** roll back. See comments for function writeMasterJournal() in pager.c 
 14164  ** for details.
 14165  */
 14166  #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
 14167  
 14168  /*
 14169  ** Allowed values for the flags parameter to sqlite3PagerOpen().
 14170  **
 14171  ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
 14172  */
 14173  #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
 14174  #define PAGER_MEMORY        0x0002    /* In-memory database */
 14175  
 14176  /*
 14177  ** Valid values for the second argument to sqlite3PagerLockingMode().
 14178  */
 14179  #define PAGER_LOCKINGMODE_QUERY      -1
 14180  #define PAGER_LOCKINGMODE_NORMAL      0
 14181  #define PAGER_LOCKINGMODE_EXCLUSIVE   1
 14182  
 14183  /*
 14184  ** Numeric constants that encode the journalmode.
 14185  **
 14186  ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
 14187  ** are exposed in the API via the "PRAGMA journal_mode" command and
 14188  ** therefore cannot be changed without a compatibility break.
 14189  */
 14190  #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
 14191  #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
 14192  #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
 14193  #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
 14194  #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
 14195  #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
 14196  #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
 14197  
 14198  /*
 14199  ** Flags that make up the mask passed to sqlite3PagerGet().
 14200  */
 14201  #define PAGER_GET_NOCONTENT     0x01  /* Do not load data from disk */
 14202  #define PAGER_GET_READONLY      0x02  /* Read-only page is acceptable */
 14203  
 14204  /*
 14205  ** Flags for sqlite3PagerSetFlags()
 14206  **
 14207  ** Value constraints (enforced via assert()):
 14208  **    PAGER_FULLFSYNC      == SQLITE_FullFSync
 14209  **    PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
 14210  **    PAGER_CACHE_SPILL    == SQLITE_CacheSpill
 14211  */
 14212  #define PAGER_SYNCHRONOUS_OFF       0x01  /* PRAGMA synchronous=OFF */
 14213  #define PAGER_SYNCHRONOUS_NORMAL    0x02  /* PRAGMA synchronous=NORMAL */
 14214  #define PAGER_SYNCHRONOUS_FULL      0x03  /* PRAGMA synchronous=FULL */
 14215  #define PAGER_SYNCHRONOUS_EXTRA     0x04  /* PRAGMA synchronous=EXTRA */
 14216  #define PAGER_SYNCHRONOUS_MASK      0x07  /* Mask for four values above */
 14217  #define PAGER_FULLFSYNC             0x08  /* PRAGMA fullfsync=ON */
 14218  #define PAGER_CKPT_FULLFSYNC        0x10  /* PRAGMA checkpoint_fullfsync=ON */
 14219  #define PAGER_CACHESPILL            0x20  /* PRAGMA cache_spill=ON */
 14220  #define PAGER_FLAGS_MASK            0x38  /* All above except SYNCHRONOUS */
 14221  
 14222  /*
 14223  ** The remainder of this file contains the declarations of the functions
 14224  ** that make up the Pager sub-system API. See source code comments for 
 14225  ** a detailed description of each routine.
 14226  */
 14227  
 14228  /* Open and close a Pager connection. */ 
 14229  SQLITE_PRIVATE int sqlite3PagerOpen(
 14230    sqlite3_vfs*,
 14231    Pager **ppPager,
 14232    const char*,
 14233    int,
 14234    int,
 14235    int,
 14236    void(*)(DbPage*)
 14237  );
 14238  SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);
 14239  SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
 14240  
 14241  /* Functions used to configure a Pager object. */
 14242  SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
 14243  SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
 14244  #ifdef SQLITE_HAS_CODEC
 14245  SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
 14246  #endif
 14247  SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
 14248  SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
 14249  SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
 14250  SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
 14251  SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
 14252  SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
 14253  SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
 14254  SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
 14255  SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
 14256  SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
 14257  SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
 14258  SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
 14259  SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
 14260  
 14261  /* Functions used to obtain and release page references. */ 
 14262  SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
 14263  SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
 14264  SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
 14265  SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
 14266  SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
 14267  SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage*);
 14268  
 14269  /* Operations on page references. */
 14270  SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
 14271  SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
 14272  SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
 14273  SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
 14274  SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
 14275  SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
 14276  
 14277  /* Functions used to manage pager transactions and savepoints. */
 14278  SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
 14279  SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
 14280  SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
 14281  SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
 14282  SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
 14283  SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
 14284  SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
 14285  SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
 14286  SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
 14287  SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
 14288  
 14289  #ifndef SQLITE_OMIT_WAL
 14290  SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
 14291  SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
 14292  SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
 14293  SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
 14294  SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
 14295  # ifdef SQLITE_DIRECT_OVERFLOW_READ
 14296  SQLITE_PRIVATE   int sqlite3PagerUseWal(Pager *pPager, Pgno);
 14297  # endif
 14298  # ifdef SQLITE_ENABLE_SNAPSHOT
 14299  SQLITE_PRIVATE   int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
 14300  SQLITE_PRIVATE   int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
 14301  SQLITE_PRIVATE   int sqlite3PagerSnapshotRecover(Pager *pPager);
 14302  # endif
 14303  #else
 14304  # define sqlite3PagerUseWal(x,y) 0
 14305  #endif
 14306  
 14307  #ifdef SQLITE_ENABLE_ZIPVFS
 14308  SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
 14309  #endif
 14310  
 14311  /* Functions used to query pager state and configuration. */
 14312  SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
 14313  SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
 14314  #ifdef SQLITE_DEBUG
 14315  SQLITE_PRIVATE   int sqlite3PagerRefcount(Pager*);
 14316  #endif
 14317  SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
 14318  SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
 14319  SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
 14320  SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
 14321  SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
 14322  SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
 14323  SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
 14324  SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
 14325  SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
 14326  SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
 14327  SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
 14328  
 14329  /* Functions used to truncate the database file. */
 14330  SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
 14331  
 14332  SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
 14333  
 14334  #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
 14335  SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
 14336  #endif
 14337  
 14338  /* Functions to support testing and debugging. */
 14339  #if !defined(NDEBUG) || defined(SQLITE_TEST)
 14340  SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
 14341  SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
 14342  #endif
 14343  #ifdef SQLITE_TEST
 14344  SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
 14345  SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
 14346    void disable_simulated_io_errors(void);
 14347    void enable_simulated_io_errors(void);
 14348  #else
 14349  # define disable_simulated_io_errors()
 14350  # define enable_simulated_io_errors()
 14351  #endif
 14352  
 14353  #endif /* SQLITE_PAGER_H */
 14354  
 14355  /************** End of pager.h ***********************************************/
 14356  /************** Continuing where we left off in sqliteInt.h ******************/
 14357  /************** Include pcache.h in the middle of sqliteInt.h ****************/
 14358  /************** Begin file pcache.h ******************************************/
 14359  /*
 14360  ** 2008 August 05
 14361  **
 14362  ** The author disclaims copyright to this source code.  In place of
 14363  ** a legal notice, here is a blessing:
 14364  **
 14365  **    May you do good and not evil.
 14366  **    May you find forgiveness for yourself and forgive others.
 14367  **    May you share freely, never taking more than you give.
 14368  **
 14369  *************************************************************************
 14370  ** This header file defines the interface that the sqlite page cache
 14371  ** subsystem. 
 14372  */
 14373  
 14374  #ifndef _PCACHE_H_
 14375  
 14376  typedef struct PgHdr PgHdr;
 14377  typedef struct PCache PCache;
 14378  
 14379  /*
 14380  ** Every page in the cache is controlled by an instance of the following
 14381  ** structure.
 14382  */
 14383  struct PgHdr {
 14384    sqlite3_pcache_page *pPage;    /* Pcache object page handle */
 14385    void *pData;                   /* Page data */
 14386    void *pExtra;                  /* Extra content */
 14387    PCache *pCache;                /* PRIVATE: Cache that owns this page */
 14388    PgHdr *pDirty;                 /* Transient list of dirty sorted by pgno */
 14389    Pager *pPager;                 /* The pager this page is part of */
 14390    Pgno pgno;                     /* Page number for this page */
 14391  #ifdef SQLITE_CHECK_PAGES
 14392    u32 pageHash;                  /* Hash of page content */
 14393  #endif
 14394    u16 flags;                     /* PGHDR flags defined below */
 14395  
 14396    /**********************************************************************
 14397    ** Elements above, except pCache, are public.  All that follow are 
 14398    ** private to pcache.c and should not be accessed by other modules.
 14399    ** pCache is grouped with the public elements for efficiency.
 14400    */
 14401    i16 nRef;                      /* Number of users of this page */
 14402    PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
 14403    PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
 14404                            /* NB: pDirtyNext and pDirtyPrev are undefined if the
 14405                            ** PgHdr object is not dirty */
 14406  };
 14407  
 14408  /* Bit values for PgHdr.flags */
 14409  #define PGHDR_CLEAN           0x001  /* Page not on the PCache.pDirty list */
 14410  #define PGHDR_DIRTY           0x002  /* Page is on the PCache.pDirty list */
 14411  #define PGHDR_WRITEABLE       0x004  /* Journaled and ready to modify */
 14412  #define PGHDR_NEED_SYNC       0x008  /* Fsync the rollback journal before
 14413                                       ** writing this page to the database */
 14414  #define PGHDR_DONT_WRITE      0x010  /* Do not write content to disk */
 14415  #define PGHDR_MMAP            0x020  /* This is an mmap page object */
 14416  
 14417  #define PGHDR_WAL_APPEND      0x040  /* Appended to wal file */
 14418  
 14419  /* Initialize and shutdown the page cache subsystem */
 14420  SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
 14421  SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
 14422  
 14423  /* Page cache buffer management:
 14424  ** These routines implement SQLITE_CONFIG_PAGECACHE.
 14425  */
 14426  SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
 14427  
 14428  /* Create a new pager cache.
 14429  ** Under memory stress, invoke xStress to try to make pages clean.
 14430  ** Only clean and unpinned pages can be reclaimed.
 14431  */
 14432  SQLITE_PRIVATE int sqlite3PcacheOpen(
 14433    int szPage,                    /* Size of every page */
 14434    int szExtra,                   /* Extra space associated with each page */
 14435    int bPurgeable,                /* True if pages are on backing store */
 14436    int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
 14437    void *pStress,                 /* Argument to xStress */
 14438    PCache *pToInit                /* Preallocated space for the PCache */
 14439  );
 14440  
 14441  /* Modify the page-size after the cache has been created. */
 14442  SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
 14443  
 14444  /* Return the size in bytes of a PCache object.  Used to preallocate
 14445  ** storage space.
 14446  */
 14447  SQLITE_PRIVATE int sqlite3PcacheSize(void);
 14448  
 14449  /* One release per successful fetch.  Page is pinned until released.
 14450  ** Reference counted. 
 14451  */
 14452  SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
 14453  SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
 14454  SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
 14455  SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
 14456  
 14457  SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
 14458  SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
 14459  SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
 14460  SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
 14461  SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
 14462  
 14463  /* Change a page number.  Used by incr-vacuum. */
 14464  SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
 14465  
 14466  /* Remove all pages with pgno>x.  Reset the cache if x==0 */
 14467  SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
 14468  
 14469  /* Get a list of all dirty pages in the cache, sorted by page number */
 14470  SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
 14471  
 14472  /* Reset and close the cache object */
 14473  SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
 14474  
 14475  /* Clear flags from pages of the page cache */
 14476  SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
 14477  
 14478  /* Discard the contents of the cache */
 14479  SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
 14480  
 14481  /* Return the total number of outstanding page references */
 14482  SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
 14483  
 14484  /* Increment the reference count of an existing page */
 14485  SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
 14486  
 14487  SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
 14488  
 14489  /* Return the total number of pages stored in the cache */
 14490  SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
 14491  
 14492  #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
 14493  /* Iterate through all dirty pages currently stored in the cache. This
 14494  ** interface is only available if SQLITE_CHECK_PAGES is defined when the 
 14495  ** library is built.
 14496  */
 14497  SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
 14498  #endif
 14499  
 14500  #if defined(SQLITE_DEBUG)
 14501  /* Check invariants on a PgHdr object */
 14502  SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
 14503  #endif
 14504  
 14505  /* Set and get the suggested cache-size for the specified pager-cache.
 14506  **
 14507  ** If no global maximum is configured, then the system attempts to limit
 14508  ** the total number of pages cached by purgeable pager-caches to the sum
 14509  ** of the suggested cache-sizes.
 14510  */
 14511  SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
 14512  #ifdef SQLITE_TEST
 14513  SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
 14514  #endif
 14515  
 14516  /* Set or get the suggested spill-size for the specified pager-cache.
 14517  **
 14518  ** The spill-size is the minimum number of pages in cache before the cache
 14519  ** will attempt to spill dirty pages by calling xStress.
 14520  */
 14521  SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
 14522  
 14523  /* Free up as much memory as possible from the page cache */
 14524  SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
 14525  
 14526  #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
 14527  /* Try to return memory used by the pcache module to the main memory heap */
 14528  SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
 14529  #endif
 14530  
 14531  #ifdef SQLITE_TEST
 14532  SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
 14533  #endif
 14534  
 14535  SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
 14536  
 14537  /* Return the header size */
 14538  SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
 14539  SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
 14540  
 14541  /* Number of dirty pages as a percentage of the configured cache size */
 14542  SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
 14543  
 14544  #endif /* _PCACHE_H_ */
 14545  
 14546  /************** End of pcache.h **********************************************/
 14547  /************** Continuing where we left off in sqliteInt.h ******************/
 14548  /************** Include os.h in the middle of sqliteInt.h ********************/
 14549  /************** Begin file os.h **********************************************/
 14550  /*
 14551  ** 2001 September 16
 14552  **
 14553  ** The author disclaims copyright to this source code.  In place of
 14554  ** a legal notice, here is a blessing:
 14555  **
 14556  **    May you do good and not evil.
 14557  **    May you find forgiveness for yourself and forgive others.
 14558  **    May you share freely, never taking more than you give.
 14559  **
 14560  ******************************************************************************
 14561  **
 14562  ** This header file (together with is companion C source-code file
 14563  ** "os.c") attempt to abstract the underlying operating system so that
 14564  ** the SQLite library will work on both POSIX and windows systems.
 14565  **
 14566  ** This header file is #include-ed by sqliteInt.h and thus ends up
 14567  ** being included by every source file.
 14568  */
 14569  #ifndef _SQLITE_OS_H_
 14570  #define _SQLITE_OS_H_
 14571  
 14572  /*
 14573  ** Attempt to automatically detect the operating system and setup the
 14574  ** necessary pre-processor macros for it.
 14575  */
 14576  /************** Include os_setup.h in the middle of os.h *********************/
 14577  /************** Begin file os_setup.h ****************************************/
 14578  /*
 14579  ** 2013 November 25
 14580  **
 14581  ** The author disclaims copyright to this source code.  In place of
 14582  ** a legal notice, here is a blessing:
 14583  **
 14584  **    May you do good and not evil.
 14585  **    May you find forgiveness for yourself and forgive others.
 14586  **    May you share freely, never taking more than you give.
 14587  **
 14588  ******************************************************************************
 14589  **
 14590  ** This file contains pre-processor directives related to operating system
 14591  ** detection and/or setup.
 14592  */
 14593  #ifndef SQLITE_OS_SETUP_H
 14594  #define SQLITE_OS_SETUP_H
 14595  
 14596  /*
 14597  ** Figure out if we are dealing with Unix, Windows, or some other operating
 14598  ** system.
 14599  **
 14600  ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
 14601  ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0.  One of
 14602  ** the three will be 1.  The other two will be 0.
 14603  */
 14604  #if defined(SQLITE_OS_OTHER)
 14605  #  if SQLITE_OS_OTHER==1
 14606  #    undef SQLITE_OS_UNIX
 14607  #    define SQLITE_OS_UNIX 0
 14608  #    undef SQLITE_OS_WIN
 14609  #    define SQLITE_OS_WIN 0
 14610  #  else
 14611  #    undef SQLITE_OS_OTHER
 14612  #  endif
 14613  #endif
 14614  #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
 14615  #  define SQLITE_OS_OTHER 0
 14616  #  ifndef SQLITE_OS_WIN
 14617  #    if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
 14618          defined(__MINGW32__) || defined(__BORLANDC__)
 14619  #      define SQLITE_OS_WIN 1
 14620  #      define SQLITE_OS_UNIX 0
 14621  #    else
 14622  #      define SQLITE_OS_WIN 0
 14623  #      define SQLITE_OS_UNIX 1
 14624  #    endif
 14625  #  else
 14626  #    define SQLITE_OS_UNIX 0
 14627  #  endif
 14628  #else
 14629  #  ifndef SQLITE_OS_WIN
 14630  #    define SQLITE_OS_WIN 0
 14631  #  endif
 14632  #endif
 14633  
 14634  #endif /* SQLITE_OS_SETUP_H */
 14635  
 14636  /************** End of os_setup.h ********************************************/
 14637  /************** Continuing where we left off in os.h *************************/
 14638  
 14639  /* If the SET_FULLSYNC macro is not defined above, then make it
 14640  ** a no-op
 14641  */
 14642  #ifndef SET_FULLSYNC
 14643  # define SET_FULLSYNC(x,y)
 14644  #endif
 14645  
 14646  /*
 14647  ** The default size of a disk sector
 14648  */
 14649  #ifndef SQLITE_DEFAULT_SECTOR_SIZE
 14650  # define SQLITE_DEFAULT_SECTOR_SIZE 4096
 14651  #endif
 14652  
 14653  /*
 14654  ** Temporary files are named starting with this prefix followed by 16 random
 14655  ** alphanumeric characters, and no file extension. They are stored in the
 14656  ** OS's standard temporary file directory, and are deleted prior to exit.
 14657  ** If sqlite is being embedded in another program, you may wish to change the
 14658  ** prefix to reflect your program's name, so that if your program exits
 14659  ** prematurely, old temporary files can be easily identified. This can be done
 14660  ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
 14661  **
 14662  ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
 14663  ** Mcafee started using SQLite in their anti-virus product and it
 14664  ** started putting files with the "sqlite" name in the c:/temp folder.
 14665  ** This annoyed many windows users.  Those users would then do a 
 14666  ** Google search for "sqlite", find the telephone numbers of the
 14667  ** developers and call to wake them up at night and complain.
 14668  ** For this reason, the default name prefix is changed to be "sqlite" 
 14669  ** spelled backwards.  So the temp files are still identified, but
 14670  ** anybody smart enough to figure out the code is also likely smart
 14671  ** enough to know that calling the developer will not help get rid
 14672  ** of the file.
 14673  */
 14674  #ifndef SQLITE_TEMP_FILE_PREFIX
 14675  # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
 14676  #endif
 14677  
 14678  /*
 14679  ** The following values may be passed as the second argument to
 14680  ** sqlite3OsLock(). The various locks exhibit the following semantics:
 14681  **
 14682  ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
 14683  ** RESERVED:  A single process may hold a RESERVED lock on a file at
 14684  **            any time. Other processes may hold and obtain new SHARED locks.
 14685  ** PENDING:   A single process may hold a PENDING lock on a file at
 14686  **            any one time. Existing SHARED locks may persist, but no new
 14687  **            SHARED locks may be obtained by other processes.
 14688  ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
 14689  **
 14690  ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
 14691  ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
 14692  ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
 14693  ** sqlite3OsLock().
 14694  */
 14695  #define NO_LOCK         0
 14696  #define SHARED_LOCK     1
 14697  #define RESERVED_LOCK   2
 14698  #define PENDING_LOCK    3
 14699  #define EXCLUSIVE_LOCK  4
 14700  
 14701  /*
 14702  ** File Locking Notes:  (Mostly about windows but also some info for Unix)
 14703  **
 14704  ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
 14705  ** those functions are not available.  So we use only LockFile() and
 14706  ** UnlockFile().
 14707  **
 14708  ** LockFile() prevents not just writing but also reading by other processes.
 14709  ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
 14710  ** byte out of a specific range of bytes. The lock byte is obtained at 
 14711  ** random so two separate readers can probably access the file at the 
 14712  ** same time, unless they are unlucky and choose the same lock byte.
 14713  ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
 14714  ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
 14715  ** a single byte of the file that is designated as the reserved lock byte.
 14716  ** A PENDING_LOCK is obtained by locking a designated byte different from
 14717  ** the RESERVED_LOCK byte.
 14718  **
 14719  ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
 14720  ** which means we can use reader/writer locks.  When reader/writer locks
 14721  ** are used, the lock is placed on the same range of bytes that is used
 14722  ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
 14723  ** will support two or more Win95 readers or two or more WinNT readers.
 14724  ** But a single Win95 reader will lock out all WinNT readers and a single
 14725  ** WinNT reader will lock out all other Win95 readers.
 14726  **
 14727  ** The following #defines specify the range of bytes used for locking.
 14728  ** SHARED_SIZE is the number of bytes available in the pool from which
 14729  ** a random byte is selected for a shared lock.  The pool of bytes for
 14730  ** shared locks begins at SHARED_FIRST. 
 14731  **
 14732  ** The same locking strategy and
 14733  ** byte ranges are used for Unix.  This leaves open the possibility of having
 14734  ** clients on win95, winNT, and unix all talking to the same shared file
 14735  ** and all locking correctly.  To do so would require that samba (or whatever
 14736  ** tool is being used for file sharing) implements locks correctly between
 14737  ** windows and unix.  I'm guessing that isn't likely to happen, but by
 14738  ** using the same locking range we are at least open to the possibility.
 14739  **
 14740  ** Locking in windows is manditory.  For this reason, we cannot store
 14741  ** actual data in the bytes used for locking.  The pager never allocates
 14742  ** the pages involved in locking therefore.  SHARED_SIZE is selected so
 14743  ** that all locks will fit on a single page even at the minimum page size.
 14744  ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
 14745  ** is set high so that we don't have to allocate an unused page except
 14746  ** for very large databases.  But one should test the page skipping logic 
 14747  ** by setting PENDING_BYTE low and running the entire regression suite.
 14748  **
 14749  ** Changing the value of PENDING_BYTE results in a subtly incompatible
 14750  ** file format.  Depending on how it is changed, you might not notice
 14751  ** the incompatibility right away, even running a full regression test.
 14752  ** The default location of PENDING_BYTE is the first byte past the
 14753  ** 1GB boundary.
 14754  **
 14755  */
 14756  #ifdef SQLITE_OMIT_WSD
 14757  # define PENDING_BYTE     (0x40000000)
 14758  #else
 14759  # define PENDING_BYTE      sqlite3PendingByte
 14760  #endif
 14761  #define RESERVED_BYTE     (PENDING_BYTE+1)
 14762  #define SHARED_FIRST      (PENDING_BYTE+2)
 14763  #define SHARED_SIZE       510
 14764  
 14765  /*
 14766  ** Wrapper around OS specific sqlite3_os_init() function.
 14767  */
 14768  SQLITE_PRIVATE int sqlite3OsInit(void);
 14769  
 14770  /* 
 14771  ** Functions for accessing sqlite3_file methods 
 14772  */
 14773  SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
 14774  SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
 14775  SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
 14776  SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
 14777  SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
 14778  SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
 14779  SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
 14780  SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
 14781  SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
 14782  SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
 14783  SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
 14784  #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
 14785  SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
 14786  SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
 14787  #ifndef SQLITE_OMIT_WAL
 14788  SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
 14789  SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
 14790  SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
 14791  SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
 14792  #endif /* SQLITE_OMIT_WAL */
 14793  SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
 14794  SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
 14795  
 14796  
 14797  /* 
 14798  ** Functions for accessing sqlite3_vfs methods 
 14799  */
 14800  SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
 14801  SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
 14802  SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
 14803  SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
 14804  #ifndef SQLITE_OMIT_LOAD_EXTENSION
 14805  SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
 14806  SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
 14807  SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
 14808  SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
 14809  #endif /* SQLITE_OMIT_LOAD_EXTENSION */
 14810  SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
 14811  SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
 14812  SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
 14813  SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
 14814  
 14815  /*
 14816  ** Convenience functions for opening and closing files using 
 14817  ** sqlite3_malloc() to obtain space for the file-handle structure.
 14818  */
 14819  SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
 14820  SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
 14821  
 14822  #endif /* _SQLITE_OS_H_ */
 14823  
 14824  /************** End of os.h **************************************************/
 14825  /************** Continuing where we left off in sqliteInt.h ******************/
 14826  /************** Include mutex.h in the middle of sqliteInt.h *****************/
 14827  /************** Begin file mutex.h *******************************************/
 14828  /*
 14829  ** 2007 August 28
 14830  **
 14831  ** The author disclaims copyright to this source code.  In place of
 14832  ** a legal notice, here is a blessing:
 14833  **
 14834  **    May you do good and not evil.
 14835  **    May you find forgiveness for yourself and forgive others.
 14836  **    May you share freely, never taking more than you give.
 14837  **
 14838  *************************************************************************
 14839  **
 14840  ** This file contains the common header for all mutex implementations.
 14841  ** The sqliteInt.h header #includes this file so that it is available
 14842  ** to all source files.  We break it out in an effort to keep the code
 14843  ** better organized.
 14844  **
 14845  ** NOTE:  source files should *not* #include this header file directly.
 14846  ** Source files should #include the sqliteInt.h file and let that file
 14847  ** include this one indirectly.
 14848  */
 14849  
 14850  
 14851  /*
 14852  ** Figure out what version of the code to use.  The choices are
 14853  **
 14854  **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
 14855  **                             mutexes implementation cannot be overridden
 14856  **                             at start-time.
 14857  **
 14858  **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
 14859  **                             mutual exclusion is provided.  But this
 14860  **                             implementation can be overridden at
 14861  **                             start-time.
 14862  **
 14863  **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
 14864  **
 14865  **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
 14866  */
 14867  #if !SQLITE_THREADSAFE
 14868  # define SQLITE_MUTEX_OMIT
 14869  #endif
 14870  #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
 14871  #  if SQLITE_OS_UNIX
 14872  #    define SQLITE_MUTEX_PTHREADS
 14873  #  elif SQLITE_OS_WIN
 14874  #    define SQLITE_MUTEX_W32
 14875  #  else
 14876  #    define SQLITE_MUTEX_NOOP
 14877  #  endif
 14878  #endif
 14879  
 14880  #ifdef SQLITE_MUTEX_OMIT
 14881  /*
 14882  ** If this is a no-op implementation, implement everything as macros.
 14883  */
 14884  #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
 14885  #define sqlite3_mutex_free(X)
 14886  #define sqlite3_mutex_enter(X)    
 14887  #define sqlite3_mutex_try(X)      SQLITE_OK
 14888  #define sqlite3_mutex_leave(X)    
 14889  #define sqlite3_mutex_held(X)     ((void)(X),1)
 14890  #define sqlite3_mutex_notheld(X)  ((void)(X),1)
 14891  #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
 14892  #define sqlite3MutexInit()        SQLITE_OK
 14893  #define sqlite3MutexEnd()
 14894  #define MUTEX_LOGIC(X)
 14895  #else
 14896  #define MUTEX_LOGIC(X)            X
 14897  #endif /* defined(SQLITE_MUTEX_OMIT) */
 14898  
 14899  /************** End of mutex.h ***********************************************/
 14900  /************** Continuing where we left off in sqliteInt.h ******************/
 14901  
 14902  /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
 14903  ** synchronous setting to EXTRA.  It is no longer supported.
 14904  */
 14905  #ifdef SQLITE_EXTRA_DURABLE
 14906  # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
 14907  # define SQLITE_DEFAULT_SYNCHRONOUS 3
 14908  #endif
 14909  
 14910  /*
 14911  ** Default synchronous levels.
 14912  **
 14913  ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
 14914  ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
 14915  **
 14916  **           PAGER_SYNCHRONOUS       DEFAULT_SYNCHRONOUS
 14917  **   OFF           1                         0
 14918  **   NORMAL        2                         1
 14919  **   FULL          3                         2
 14920  **   EXTRA         4                         3
 14921  **
 14922  ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
 14923  ** In other words, the zero-based numbers are used for all external interfaces
 14924  ** and the one-based values are used internally.
 14925  */
 14926  #ifndef SQLITE_DEFAULT_SYNCHRONOUS
 14927  # define SQLITE_DEFAULT_SYNCHRONOUS 2
 14928  #endif
 14929  #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
 14930  # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
 14931  #endif
 14932  
 14933  /*
 14934  ** Each database file to be accessed by the system is an instance
 14935  ** of the following structure.  There are normally two of these structures
 14936  ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
 14937  ** aDb[1] is the database file used to hold temporary tables.  Additional
 14938  ** databases may be attached.
 14939  */
 14940  struct Db {
 14941    char *zDbSName;      /* Name of this database. (schema name, not filename) */
 14942    Btree *pBt;          /* The B*Tree structure for this database file */
 14943    u8 safety_level;     /* How aggressive at syncing data to disk */
 14944    u8 bSyncSet;         /* True if "PRAGMA synchronous=N" has been run */
 14945    Schema *pSchema;     /* Pointer to database schema (possibly shared) */
 14946  };
 14947  
 14948  /*
 14949  ** An instance of the following structure stores a database schema.
 14950  **
 14951  ** Most Schema objects are associated with a Btree.  The exception is
 14952  ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
 14953  ** In shared cache mode, a single Schema object can be shared by multiple
 14954  ** Btrees that refer to the same underlying BtShared object.
 14955  **
 14956  ** Schema objects are automatically deallocated when the last Btree that
 14957  ** references them is destroyed.   The TEMP Schema is manually freed by
 14958  ** sqlite3_close().
 14959  *
 14960  ** A thread must be holding a mutex on the corresponding Btree in order
 14961  ** to access Schema content.  This implies that the thread must also be
 14962  ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
 14963  ** For a TEMP Schema, only the connection mutex is required.
 14964  */
 14965  struct Schema {
 14966    int schema_cookie;   /* Database schema version number for this file */
 14967    int iGeneration;     /* Generation counter.  Incremented with each change */
 14968    Hash tblHash;        /* All tables indexed by name */
 14969    Hash idxHash;        /* All (named) indices indexed by name */
 14970    Hash trigHash;       /* All triggers indexed by name */
 14971    Hash fkeyHash;       /* All foreign keys by referenced table name */
 14972    Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
 14973    u8 file_format;      /* Schema format version for this file */
 14974    u8 enc;              /* Text encoding used by this database */
 14975    u16 schemaFlags;     /* Flags associated with this schema */
 14976    int cache_size;      /* Number of pages to use in the cache */
 14977  };
 14978  
 14979  /*
 14980  ** These macros can be used to test, set, or clear bits in the
 14981  ** Db.pSchema->flags field.
 14982  */
 14983  #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
 14984  #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
 14985  #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->schemaFlags|=(P)
 14986  #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->schemaFlags&=~(P)
 14987  
 14988  /*
 14989  ** Allowed values for the DB.pSchema->flags field.
 14990  **
 14991  ** The DB_SchemaLoaded flag is set after the database schema has been
 14992  ** read into internal hash tables.
 14993  **
 14994  ** DB_UnresetViews means that one or more views have column names that
 14995  ** have been filled out.  If the schema changes, these column names might
 14996  ** changes and so the view will need to be reset.
 14997  */
 14998  #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
 14999  #define DB_UnresetViews    0x0002  /* Some views have defined column names */
 15000  #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
 15001  #define DB_ResetWanted     0x0008  /* Reset the schema when nSchemaLock==0 */
 15002  
 15003  /*
 15004  ** The number of different kinds of things that can be limited
 15005  ** using the sqlite3_limit() interface.
 15006  */
 15007  #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
 15008  
 15009  /*
 15010  ** Lookaside malloc is a set of fixed-size buffers that can be used
 15011  ** to satisfy small transient memory allocation requests for objects
 15012  ** associated with a particular database connection.  The use of
 15013  ** lookaside malloc provides a significant performance enhancement
 15014  ** (approx 10%) by avoiding numerous malloc/free requests while parsing
 15015  ** SQL statements.
 15016  **
 15017  ** The Lookaside structure holds configuration information about the
 15018  ** lookaside malloc subsystem.  Each available memory allocation in
 15019  ** the lookaside subsystem is stored on a linked list of LookasideSlot
 15020  ** objects.
 15021  **
 15022  ** Lookaside allocations are only allowed for objects that are associated
 15023  ** with a particular database connection.  Hence, schema information cannot
 15024  ** be stored in lookaside because in shared cache mode the schema information
 15025  ** is shared by multiple database connections.  Therefore, while parsing
 15026  ** schema information, the Lookaside.bEnabled flag is cleared so that
 15027  ** lookaside allocations are not used to construct the schema objects.
 15028  */
 15029  struct Lookaside {
 15030    u32 bDisable;           /* Only operate the lookaside when zero */
 15031    u16 sz;                 /* Size of each buffer in bytes */
 15032    u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
 15033    u32 nSlot;              /* Number of lookaside slots allocated */
 15034    u32 anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
 15035    LookasideSlot *pInit;   /* List of buffers not previously used */
 15036    LookasideSlot *pFree;   /* List of available buffers */
 15037    void *pStart;           /* First byte of available memory space */
 15038    void *pEnd;             /* First byte past end of available space */
 15039  };
 15040  struct LookasideSlot {
 15041    LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
 15042  };
 15043  
 15044  /*
 15045  ** A hash table for built-in function definitions.  (Application-defined
 15046  ** functions use a regular table table from hash.h.)
 15047  **
 15048  ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
 15049  ** Collisions are on the FuncDef.u.pHash chain.
 15050  */
 15051  #define SQLITE_FUNC_HASH_SZ 23
 15052  struct FuncDefHash {
 15053    FuncDef *a[SQLITE_FUNC_HASH_SZ];       /* Hash table for functions */
 15054  };
 15055  
 15056  #ifdef SQLITE_USER_AUTHENTICATION
 15057  /*
 15058  ** Information held in the "sqlite3" database connection object and used
 15059  ** to manage user authentication.
 15060  */
 15061  typedef struct sqlite3_userauth sqlite3_userauth;
 15062  struct sqlite3_userauth {
 15063    u8 authLevel;                 /* Current authentication level */
 15064    int nAuthPW;                  /* Size of the zAuthPW in bytes */
 15065    char *zAuthPW;                /* Password used to authenticate */
 15066    char *zAuthUser;              /* User name used to authenticate */
 15067  };
 15068  
 15069  /* Allowed values for sqlite3_userauth.authLevel */
 15070  #define UAUTH_Unknown     0     /* Authentication not yet checked */
 15071  #define UAUTH_Fail        1     /* User authentication failed */
 15072  #define UAUTH_User        2     /* Authenticated as a normal user */
 15073  #define UAUTH_Admin       3     /* Authenticated as an administrator */
 15074  
 15075  /* Functions used only by user authorization logic */
 15076  SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
 15077  SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
 15078  SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
 15079  SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
 15080  
 15081  #endif /* SQLITE_USER_AUTHENTICATION */
 15082  
 15083  /*
 15084  ** typedef for the authorization callback function.
 15085  */
 15086  #ifdef SQLITE_USER_AUTHENTICATION
 15087    typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
 15088                                 const char*, const char*);
 15089  #else
 15090    typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
 15091                                 const char*);
 15092  #endif
 15093  
 15094  #ifndef SQLITE_OMIT_DEPRECATED
 15095  /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
 15096  ** in the style of sqlite3_trace()
 15097  */
 15098  #define SQLITE_TRACE_LEGACY  0x80
 15099  #else
 15100  #define SQLITE_TRACE_LEGACY  0
 15101  #endif /* SQLITE_OMIT_DEPRECATED */
 15102  
 15103  
 15104  /*
 15105  ** Each database connection is an instance of the following structure.
 15106  */
 15107  struct sqlite3 {
 15108    sqlite3_vfs *pVfs;            /* OS Interface */
 15109    struct Vdbe *pVdbe;           /* List of active virtual machines */
 15110    CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
 15111    sqlite3_mutex *mutex;         /* Connection mutex */
 15112    Db *aDb;                      /* All backends */
 15113    int nDb;                      /* Number of backends currently in use */
 15114    u32 mDbFlags;                 /* flags recording internal state */
 15115    u32 flags;                    /* flags settable by pragmas. See below */
 15116    i64 lastRowid;                /* ROWID of most recent insert (see above) */
 15117    i64 szMmap;                   /* Default mmap_size setting */
 15118    u32 nSchemaLock;              /* Do not reset the schema when non-zero */
 15119    unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
 15120    int errCode;                  /* Most recent error code (SQLITE_*) */
 15121    int errMask;                  /* & result codes with this before returning */
 15122    int iSysErrno;                /* Errno value from last system error */
 15123    u16 dbOptFlags;               /* Flags to enable/disable optimizations */
 15124    u8 enc;                       /* Text encoding */
 15125    u8 autoCommit;                /* The auto-commit flag. */
 15126    u8 temp_store;                /* 1: file 2: memory 0: default */
 15127    u8 mallocFailed;              /* True if we have seen a malloc failure */
 15128    u8 bBenignMalloc;             /* Do not require OOMs if true */
 15129    u8 dfltLockMode;              /* Default locking-mode for attached dbs */
 15130    signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
 15131    u8 suppressErr;               /* Do not issue error messages if true */
 15132    u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
 15133    u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
 15134    u8 mTrace;                    /* zero or more SQLITE_TRACE flags */
 15135    u8 skipBtreeMutex;            /* True if no shared-cache backends */
 15136    u8 nSqlExec;                  /* Number of pending OP_SqlExec opcodes */
 15137    int nextPagesize;             /* Pagesize after VACUUM if >0 */
 15138    u32 magic;                    /* Magic number for detect library misuse */
 15139    int nChange;                  /* Value returned by sqlite3_changes() */
 15140    int nTotalChange;             /* Value returned by sqlite3_total_changes() */
 15141    int aLimit[SQLITE_N_LIMIT];   /* Limits */
 15142    int nMaxSorterMmap;           /* Maximum size of regions mapped by sorter */
 15143    struct sqlite3InitInfo {      /* Information used during initialization */
 15144      int newTnum;                /* Rootpage of table being initialized */
 15145      u8 iDb;                     /* Which db file is being initialized */
 15146      u8 busy;                    /* TRUE if currently initializing */
 15147      u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
 15148      u8 imposterTable;           /* Building an imposter table */
 15149    } init;
 15150    int nVdbeActive;              /* Number of VDBEs currently running */
 15151    int nVdbeRead;                /* Number of active VDBEs that read or write */
 15152    int nVdbeWrite;               /* Number of active VDBEs that read and write */
 15153    int nVdbeExec;                /* Number of nested calls to VdbeExec() */
 15154    int nVDestroy;                /* Number of active OP_VDestroy operations */
 15155    int nExtension;               /* Number of loaded extensions */
 15156    void **aExtension;            /* Array of shared library handles */
 15157    int (*xTrace)(u32,void*,void*,void*);     /* Trace function */
 15158    void *pTraceArg;                          /* Argument to the trace function */
 15159    void (*xProfile)(void*,const char*,u64);  /* Profiling function */
 15160    void *pProfileArg;                        /* Argument to profile function */
 15161    void *pCommitArg;                 /* Argument to xCommitCallback() */
 15162    int (*xCommitCallback)(void*);    /* Invoked at every commit. */
 15163    void *pRollbackArg;               /* Argument to xRollbackCallback() */
 15164    void (*xRollbackCallback)(void*); /* Invoked at every commit. */
 15165    void *pUpdateArg;
 15166    void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
 15167  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 15168    void *pPreUpdateArg;          /* First argument to xPreUpdateCallback */
 15169    void (*xPreUpdateCallback)(   /* Registered using sqlite3_preupdate_hook() */
 15170      void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
 15171    );
 15172    PreUpdate *pPreUpdate;        /* Context for active pre-update callback */
 15173  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
 15174  #ifndef SQLITE_OMIT_WAL
 15175    int (*xWalCallback)(void *, sqlite3 *, const char *, int);
 15176    void *pWalArg;
 15177  #endif
 15178    void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
 15179    void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
 15180    void *pCollNeededArg;
 15181    sqlite3_value *pErr;          /* Most recent error message */
 15182    union {
 15183      volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
 15184      double notUsed1;            /* Spacer */
 15185    } u1;
 15186    Lookaside lookaside;          /* Lookaside malloc configuration */
 15187  #ifndef SQLITE_OMIT_AUTHORIZATION
 15188    sqlite3_xauth xAuth;          /* Access authorization function */
 15189    void *pAuthArg;               /* 1st argument to the access auth function */
 15190  #endif
 15191  #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
 15192    int (*xProgress)(void *);     /* The progress callback */
 15193    void *pProgressArg;           /* Argument to the progress callback */
 15194    unsigned nProgressOps;        /* Number of opcodes for progress callback */
 15195  #endif
 15196  #ifndef SQLITE_OMIT_VIRTUALTABLE
 15197    int nVTrans;                  /* Allocated size of aVTrans */
 15198    Hash aModule;                 /* populated by sqlite3_create_module() */
 15199    VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
 15200    VTable **aVTrans;             /* Virtual tables with open transactions */
 15201    VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
 15202  #endif
 15203    Hash aFunc;                   /* Hash table of connection functions */
 15204    Hash aCollSeq;                /* All collating sequences */
 15205    BusyHandler busyHandler;      /* Busy callback */
 15206    Db aDbStatic[2];              /* Static space for the 2 default backends */
 15207    Savepoint *pSavepoint;        /* List of active savepoints */
 15208    int busyTimeout;              /* Busy handler timeout, in msec */
 15209    int nSavepoint;               /* Number of non-transaction savepoints */
 15210    int nStatement;               /* Number of nested statement-transactions  */
 15211    i64 nDeferredCons;            /* Net deferred constraints this transaction. */
 15212    i64 nDeferredImmCons;         /* Net deferred immediate constraints */
 15213    int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
 15214  #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
 15215    /* The following variables are all protected by the STATIC_MASTER
 15216    ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
 15217    **
 15218    ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
 15219    ** unlock so that it can proceed.
 15220    **
 15221    ** When X.pBlockingConnection==Y, that means that something that X tried
 15222    ** tried to do recently failed with an SQLITE_LOCKED error due to locks
 15223    ** held by Y.
 15224    */
 15225    sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
 15226    sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
 15227    void *pUnlockArg;                     /* Argument to xUnlockNotify */
 15228    void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
 15229    sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
 15230  #endif
 15231  #ifdef SQLITE_USER_AUTHENTICATION
 15232    sqlite3_userauth auth;        /* User authentication information */
 15233  #endif
 15234  };
 15235  
 15236  /*
 15237  ** A macro to discover the encoding of a database.
 15238  */
 15239  #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
 15240  #define ENC(db)        ((db)->enc)
 15241  
 15242  /*
 15243  ** Possible values for the sqlite3.flags.
 15244  **
 15245  ** Value constraints (enforced via assert()):
 15246  **      SQLITE_FullFSync     == PAGER_FULLFSYNC
 15247  **      SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
 15248  **      SQLITE_CacheSpill    == PAGER_CACHE_SPILL
 15249  */
 15250  #define SQLITE_WriteSchema    0x00000001  /* OK to update SQLITE_MASTER */
 15251  #define SQLITE_LegacyFileFmt  0x00000002  /* Create new databases in format 1 */
 15252  #define SQLITE_FullColNames   0x00000004  /* Show full column names on SELECT */
 15253  #define SQLITE_FullFSync      0x00000008  /* Use full fsync on the backend */
 15254  #define SQLITE_CkptFullFSync  0x00000010  /* Use full fsync for checkpoint */
 15255  #define SQLITE_CacheSpill     0x00000020  /* OK to spill pager cache */
 15256  #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
 15257  #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
 15258                                            /*   DELETE, or UPDATE and return */
 15259                                            /*   the count using a callback. */
 15260  #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
 15261                                            /*   result set is empty */
 15262  #define SQLITE_IgnoreChecks   0x00000200  /* Do not enforce check constraints */
 15263  #define SQLITE_ReadUncommit   0x00000400  /* READ UNCOMMITTED in shared-cache */
 15264  #define SQLITE_NoCkptOnClose  0x00000800  /* No checkpoint on close()/DETACH */
 15265  #define SQLITE_ReverseOrder   0x00001000  /* Reverse unordered SELECTs */
 15266  #define SQLITE_RecTriggers    0x00002000  /* Enable recursive triggers */
 15267  #define SQLITE_ForeignKeys    0x00004000  /* Enforce foreign key constraints  */
 15268  #define SQLITE_AutoIndex      0x00008000  /* Enable automatic indexes */
 15269  #define SQLITE_LoadExtension  0x00010000  /* Enable load_extension */
 15270  #define SQLITE_LoadExtFunc    0x00020000  /* Enable load_extension() SQL func */
 15271  #define SQLITE_EnableTrigger  0x00040000  /* True to enable triggers */
 15272  #define SQLITE_DeferFKs       0x00080000  /* Defer all FK constraints */
 15273  #define SQLITE_QueryOnly      0x00100000  /* Disable database changes */
 15274  #define SQLITE_CellSizeCk     0x00200000  /* Check btree cell sizes on load */
 15275  #define SQLITE_Fts3Tokenizer  0x00400000  /* Enable fts3_tokenizer(2) */
 15276  #define SQLITE_EnableQPSG     0x00800000  /* Query Planner Stability Guarantee */
 15277  /* Flags used only if debugging */
 15278  #ifdef SQLITE_DEBUG
 15279  #define SQLITE_SqlTrace       0x08000000  /* Debug print SQL as it executes */
 15280  #define SQLITE_VdbeListing    0x10000000  /* Debug listings of VDBE programs */
 15281  #define SQLITE_VdbeTrace      0x20000000  /* True to trace VDBE execution */
 15282  #define SQLITE_VdbeAddopTrace 0x40000000  /* Trace sqlite3VdbeAddOp() calls */
 15283  #define SQLITE_VdbeEQP        0x80000000  /* Debug EXPLAIN QUERY PLAN */
 15284  #endif
 15285  
 15286  /*
 15287  ** Allowed values for sqlite3.mDbFlags
 15288  */
 15289  #define DBFLAG_SchemaChange   0x0001  /* Uncommitted Hash table changes */
 15290  #define DBFLAG_PreferBuiltin  0x0002  /* Preference to built-in funcs */
 15291  #define DBFLAG_Vacuum         0x0004  /* Currently in a VACUUM */
 15292  
 15293  /*
 15294  ** Bits of the sqlite3.dbOptFlags field that are used by the
 15295  ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
 15296  ** selectively disable various optimizations.
 15297  */
 15298  #define SQLITE_QueryFlattener 0x0001   /* Query flattening */
 15299  #define SQLITE_ColumnCache    0x0002   /* Column cache */
 15300  #define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
 15301  #define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
 15302  #define SQLITE_DistinctOpt    0x0010   /* DISTINCT using indexes */
 15303  #define SQLITE_CoverIdxScan   0x0020   /* Covering index scans */
 15304  #define SQLITE_OrderByIdxJoin 0x0040   /* ORDER BY of joins via index */
 15305  #define SQLITE_Transitive     0x0080   /* Transitive constraints */
 15306  #define SQLITE_OmitNoopJoin   0x0100   /* Omit unused tables in joins */
 15307  #define SQLITE_CountOfView    0x0200   /* The count-of-view optimization */
 15308  #define SQLITE_CursorHints    0x0400   /* Add OP_CursorHint opcodes */
 15309  #define SQLITE_Stat34         0x0800   /* Use STAT3 or STAT4 data */
 15310     /* TH3 expects the Stat34  ^^^^^^ value to be 0x0800.  Don't change it */
 15311  #define SQLITE_AllOpts        0xffff   /* All optimizations */
 15312  
 15313  /*
 15314  ** Macros for testing whether or not optimizations are enabled or disabled.
 15315  */
 15316  #define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
 15317  #define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
 15318  
 15319  /*
 15320  ** Return true if it OK to factor constant expressions into the initialization
 15321  ** code. The argument is a Parse object for the code generator.
 15322  */
 15323  #define ConstFactorOk(P) ((P)->okConstFactor)
 15324  
 15325  /*
 15326  ** Possible values for the sqlite.magic field.
 15327  ** The numbers are obtained at random and have no special meaning, other
 15328  ** than being distinct from one another.
 15329  */
 15330  #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
 15331  #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
 15332  #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
 15333  #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
 15334  #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
 15335  #define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
 15336  
 15337  /*
 15338  ** Each SQL function is defined by an instance of the following
 15339  ** structure.  For global built-in functions (ex: substr(), max(), count())
 15340  ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
 15341  ** For per-connection application-defined functions, a pointer to this
 15342  ** structure is held in the db->aHash hash table.
 15343  **
 15344  ** The u.pHash field is used by the global built-ins.  The u.pDestructor
 15345  ** field is used by per-connection app-def functions.
 15346  */
 15347  struct FuncDef {
 15348    i8 nArg;             /* Number of arguments.  -1 means unlimited */
 15349    u16 funcFlags;       /* Some combination of SQLITE_FUNC_* */
 15350    void *pUserData;     /* User data parameter */
 15351    FuncDef *pNext;      /* Next function with same name */
 15352    void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
 15353    void (*xFinalize)(sqlite3_context*);                  /* Agg finalizer */
 15354    const char *zName;   /* SQL name of the function. */
 15355    union {
 15356      FuncDef *pHash;      /* Next with a different name but the same hash */
 15357      FuncDestructor *pDestructor;   /* Reference counted destructor function */
 15358    } u;
 15359  };
 15360  
 15361  /*
 15362  ** This structure encapsulates a user-function destructor callback (as
 15363  ** configured using create_function_v2()) and a reference counter. When
 15364  ** create_function_v2() is called to create a function with a destructor,
 15365  ** a single object of this type is allocated. FuncDestructor.nRef is set to
 15366  ** the number of FuncDef objects created (either 1 or 3, depending on whether
 15367  ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
 15368  ** member of each of the new FuncDef objects is set to point to the allocated
 15369  ** FuncDestructor.
 15370  **
 15371  ** Thereafter, when one of the FuncDef objects is deleted, the reference
 15372  ** count on this object is decremented. When it reaches 0, the destructor
 15373  ** is invoked and the FuncDestructor structure freed.
 15374  */
 15375  struct FuncDestructor {
 15376    int nRef;
 15377    void (*xDestroy)(void *);
 15378    void *pUserData;
 15379  };
 15380  
 15381  /*
 15382  ** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
 15383  ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  And
 15384  ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC.  There
 15385  ** are assert() statements in the code to verify this.
 15386  **
 15387  ** Value constraints (enforced via assert()):
 15388  **     SQLITE_FUNC_MINMAX    ==  NC_MinMaxAgg      == SF_MinMaxAgg
 15389  **     SQLITE_FUNC_LENGTH    ==  OPFLAG_LENGTHARG
 15390  **     SQLITE_FUNC_TYPEOF    ==  OPFLAG_TYPEOFARG
 15391  **     SQLITE_FUNC_CONSTANT  ==  SQLITE_DETERMINISTIC from the API
 15392  **     SQLITE_FUNC_ENCMASK   depends on SQLITE_UTF* macros in the API
 15393  */
 15394  #define SQLITE_FUNC_ENCMASK  0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
 15395  #define SQLITE_FUNC_LIKE     0x0004 /* Candidate for the LIKE optimization */
 15396  #define SQLITE_FUNC_CASE     0x0008 /* Case-sensitive LIKE-type function */
 15397  #define SQLITE_FUNC_EPHEM    0x0010 /* Ephemeral.  Delete with VDBE */
 15398  #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
 15399  #define SQLITE_FUNC_LENGTH   0x0040 /* Built-in length() function */
 15400  #define SQLITE_FUNC_TYPEOF   0x0080 /* Built-in typeof() function */
 15401  #define SQLITE_FUNC_COUNT    0x0100 /* Built-in count(*) aggregate */
 15402  #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
 15403  #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
 15404  #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
 15405  #define SQLITE_FUNC_MINMAX   0x1000 /* True for min() and max() aggregates */
 15406  #define SQLITE_FUNC_SLOCHNG  0x2000 /* "Slow Change". Value constant during a
 15407                                      ** single query - might change over time */
 15408  #define SQLITE_FUNC_AFFINITY 0x4000 /* Built-in affinity() function */
 15409  
 15410  /*
 15411  ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
 15412  ** used to create the initializers for the FuncDef structures.
 15413  **
 15414  **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
 15415  **     Used to create a scalar function definition of a function zName
 15416  **     implemented by C function xFunc that accepts nArg arguments. The
 15417  **     value passed as iArg is cast to a (void*) and made available
 15418  **     as the user-data (sqlite3_user_data()) for the function. If
 15419  **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
 15420  **
 15421  **   VFUNCTION(zName, nArg, iArg, bNC, xFunc)
 15422  **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
 15423  **
 15424  **   DFUNCTION(zName, nArg, iArg, bNC, xFunc)
 15425  **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
 15426  **     adds the SQLITE_FUNC_SLOCHNG flag.  Used for date & time functions
 15427  **     and functions like sqlite_version() that can change, but not during
 15428  **     a single query.  The iArg is ignored.  The user-data is always set
 15429  **     to a NULL pointer.  The bNC parameter is not used.
 15430  **
 15431  **   PURE_DATE(zName, nArg, iArg, bNC, xFunc)
 15432  **     Used for "pure" date/time functions, this macro is like DFUNCTION
 15433  **     except that it does set the SQLITE_FUNC_CONSTANT flags.  iArg is
 15434  **     ignored and the user-data for these functions is set to an 
 15435  **     arbitrary non-NULL pointer.  The bNC parameter is not used.
 15436  **
 15437  **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
 15438  **     Used to create an aggregate function definition implemented by
 15439  **     the C functions xStep and xFinal. The first four parameters
 15440  **     are interpreted in the same way as the first 4 parameters to
 15441  **     FUNCTION().
 15442  **
 15443  **   LIKEFUNC(zName, nArg, pArg, flags)
 15444  **     Used to create a scalar function definition of a function zName
 15445  **     that accepts nArg arguments and is implemented by a call to C
 15446  **     function likeFunc. Argument pArg is cast to a (void *) and made
 15447  **     available as the function user-data (sqlite3_user_data()). The
 15448  **     FuncDef.flags variable is set to the value passed as the flags
 15449  **     parameter.
 15450  */
 15451  #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
 15452    {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
 15453     SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
 15454  #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
 15455    {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
 15456     SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
 15457  #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
 15458    {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
 15459     0, 0, xFunc, 0, #zName, {0} }
 15460  #define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \
 15461    {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
 15462     (void*)&sqlite3Config, 0, xFunc, 0, #zName, {0} }
 15463  #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
 15464    {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
 15465     SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
 15466  #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
 15467    {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
 15468     pArg, 0, xFunc, 0, #zName, }
 15469  #define LIKEFUNC(zName, nArg, arg, flags) \
 15470    {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
 15471     (void *)arg, 0, likeFunc, 0, #zName, {0} }
 15472  #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
 15473    {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
 15474     SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
 15475  #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
 15476    {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
 15477     SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
 15478  
 15479  /*
 15480  ** All current savepoints are stored in a linked list starting at
 15481  ** sqlite3.pSavepoint. The first element in the list is the most recently
 15482  ** opened savepoint. Savepoints are added to the list by the vdbe
 15483  ** OP_Savepoint instruction.
 15484  */
 15485  struct Savepoint {
 15486    char *zName;                        /* Savepoint name (nul-terminated) */
 15487    i64 nDeferredCons;                  /* Number of deferred fk violations */
 15488    i64 nDeferredImmCons;               /* Number of deferred imm fk. */
 15489    Savepoint *pNext;                   /* Parent savepoint (if any) */
 15490  };
 15491  
 15492  /*
 15493  ** The following are used as the second parameter to sqlite3Savepoint(),
 15494  ** and as the P1 argument to the OP_Savepoint instruction.
 15495  */
 15496  #define SAVEPOINT_BEGIN      0
 15497  #define SAVEPOINT_RELEASE    1
 15498  #define SAVEPOINT_ROLLBACK   2
 15499  
 15500  
 15501  /*
 15502  ** Each SQLite module (virtual table definition) is defined by an
 15503  ** instance of the following structure, stored in the sqlite3.aModule
 15504  ** hash table.
 15505  */
 15506  struct Module {
 15507    const sqlite3_module *pModule;       /* Callback pointers */
 15508    const char *zName;                   /* Name passed to create_module() */
 15509    void *pAux;                          /* pAux passed to create_module() */
 15510    void (*xDestroy)(void *);            /* Module destructor function */
 15511    Table *pEpoTab;                      /* Eponymous table for this module */
 15512  };
 15513  
 15514  /*
 15515  ** information about each column of an SQL table is held in an instance
 15516  ** of this structure.
 15517  */
 15518  struct Column {
 15519    char *zName;     /* Name of this column, \000, then the type */
 15520    Expr *pDflt;     /* Default value of this column */
 15521    char *zColl;     /* Collating sequence.  If NULL, use the default */
 15522    u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
 15523    char affinity;   /* One of the SQLITE_AFF_... values */
 15524    u8 szEst;        /* Estimated size of value in this column. sizeof(INT)==1 */
 15525    u8 colFlags;     /* Boolean properties.  See COLFLAG_ defines below */
 15526  };
 15527  
 15528  /* Allowed values for Column.colFlags:
 15529  */
 15530  #define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
 15531  #define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
 15532  #define COLFLAG_HASTYPE  0x0004    /* Type name follows column name */
 15533  
 15534  /*
 15535  ** A "Collating Sequence" is defined by an instance of the following
 15536  ** structure. Conceptually, a collating sequence consists of a name and
 15537  ** a comparison routine that defines the order of that sequence.
 15538  **
 15539  ** If CollSeq.xCmp is NULL, it means that the
 15540  ** collating sequence is undefined.  Indices built on an undefined
 15541  ** collating sequence may not be read or written.
 15542  */
 15543  struct CollSeq {
 15544    char *zName;          /* Name of the collating sequence, UTF-8 encoded */
 15545    u8 enc;               /* Text encoding handled by xCmp() */
 15546    void *pUser;          /* First argument to xCmp() */
 15547    int (*xCmp)(void*,int, const void*, int, const void*);
 15548    void (*xDel)(void*);  /* Destructor for pUser */
 15549  };
 15550  
 15551  /*
 15552  ** A sort order can be either ASC or DESC.
 15553  */
 15554  #define SQLITE_SO_ASC       0  /* Sort in ascending order */
 15555  #define SQLITE_SO_DESC      1  /* Sort in ascending order */
 15556  #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
 15557  
 15558  /*
 15559  ** Column affinity types.
 15560  **
 15561  ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
 15562  ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
 15563  ** the speed a little by numbering the values consecutively.
 15564  **
 15565  ** But rather than start with 0 or 1, we begin with 'A'.  That way,
 15566  ** when multiple affinity types are concatenated into a string and
 15567  ** used as the P4 operand, they will be more readable.
 15568  **
 15569  ** Note also that the numeric types are grouped together so that testing
 15570  ** for a numeric type is a single comparison.  And the BLOB type is first.
 15571  */
 15572  #define SQLITE_AFF_BLOB     'A'
 15573  #define SQLITE_AFF_TEXT     'B'
 15574  #define SQLITE_AFF_NUMERIC  'C'
 15575  #define SQLITE_AFF_INTEGER  'D'
 15576  #define SQLITE_AFF_REAL     'E'
 15577  
 15578  #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
 15579  
 15580  /*
 15581  ** The SQLITE_AFF_MASK values masks off the significant bits of an
 15582  ** affinity value.
 15583  */
 15584  #define SQLITE_AFF_MASK     0x47
 15585  
 15586  /*
 15587  ** Additional bit values that can be ORed with an affinity without
 15588  ** changing the affinity.
 15589  **
 15590  ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
 15591  ** It causes an assert() to fire if either operand to a comparison
 15592  ** operator is NULL.  It is added to certain comparison operators to
 15593  ** prove that the operands are always NOT NULL.
 15594  */
 15595  #define SQLITE_KEEPNULL     0x08  /* Used by vector == or <> */
 15596  #define SQLITE_JUMPIFNULL   0x10  /* jumps if either operand is NULL */
 15597  #define SQLITE_STOREP2      0x20  /* Store result in reg[P2] rather than jump */
 15598  #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
 15599  #define SQLITE_NOTNULL      0x90  /* Assert that operands are never NULL */
 15600  
 15601  /*
 15602  ** An object of this type is created for each virtual table present in
 15603  ** the database schema.
 15604  **
 15605  ** If the database schema is shared, then there is one instance of this
 15606  ** structure for each database connection (sqlite3*) that uses the shared
 15607  ** schema. This is because each database connection requires its own unique
 15608  ** instance of the sqlite3_vtab* handle used to access the virtual table
 15609  ** implementation. sqlite3_vtab* handles can not be shared between
 15610  ** database connections, even when the rest of the in-memory database
 15611  ** schema is shared, as the implementation often stores the database
 15612  ** connection handle passed to it via the xConnect() or xCreate() method
 15613  ** during initialization internally. This database connection handle may
 15614  ** then be used by the virtual table implementation to access real tables
 15615  ** within the database. So that they appear as part of the callers
 15616  ** transaction, these accesses need to be made via the same database
 15617  ** connection as that used to execute SQL operations on the virtual table.
 15618  **
 15619  ** All VTable objects that correspond to a single table in a shared
 15620  ** database schema are initially stored in a linked-list pointed to by
 15621  ** the Table.pVTable member variable of the corresponding Table object.
 15622  ** When an sqlite3_prepare() operation is required to access the virtual
 15623  ** table, it searches the list for the VTable that corresponds to the
 15624  ** database connection doing the preparing so as to use the correct
 15625  ** sqlite3_vtab* handle in the compiled query.
 15626  **
 15627  ** When an in-memory Table object is deleted (for example when the
 15628  ** schema is being reloaded for some reason), the VTable objects are not
 15629  ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
 15630  ** immediately. Instead, they are moved from the Table.pVTable list to
 15631  ** another linked list headed by the sqlite3.pDisconnect member of the
 15632  ** corresponding sqlite3 structure. They are then deleted/xDisconnected
 15633  ** next time a statement is prepared using said sqlite3*. This is done
 15634  ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
 15635  ** Refer to comments above function sqlite3VtabUnlockList() for an
 15636  ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
 15637  ** list without holding the corresponding sqlite3.mutex mutex.
 15638  **
 15639  ** The memory for objects of this type is always allocated by
 15640  ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
 15641  ** the first argument.
 15642  */
 15643  struct VTable {
 15644    sqlite3 *db;              /* Database connection associated with this table */
 15645    Module *pMod;             /* Pointer to module implementation */
 15646    sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
 15647    int nRef;                 /* Number of pointers to this structure */
 15648    u8 bConstraint;           /* True if constraints are supported */
 15649    int iSavepoint;           /* Depth of the SAVEPOINT stack */
 15650    VTable *pNext;            /* Next in linked list (see above) */
 15651  };
 15652  
 15653  /*
 15654  ** The schema for each SQL table and view is represented in memory
 15655  ** by an instance of the following structure.
 15656  */
 15657  struct Table {
 15658    char *zName;         /* Name of the table or view */
 15659    Column *aCol;        /* Information about each column */
 15660    Index *pIndex;       /* List of SQL indexes on this table. */
 15661    Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
 15662    FKey *pFKey;         /* Linked list of all foreign keys in this table */
 15663    char *zColAff;       /* String defining the affinity of each column */
 15664    ExprList *pCheck;    /* All CHECK constraints */
 15665                         /*   ... also used as column name list in a VIEW */
 15666    int tnum;            /* Root BTree page for this table */
 15667    u32 nTabRef;         /* Number of pointers to this Table */
 15668    u32 tabFlags;        /* Mask of TF_* values */
 15669    i16 iPKey;           /* If not negative, use aCol[iPKey] as the rowid */
 15670    i16 nCol;            /* Number of columns in this table */
 15671    LogEst nRowLogEst;   /* Estimated rows in table - from sqlite_stat1 table */
 15672    LogEst szTabRow;     /* Estimated size of each table row in bytes */
 15673  #ifdef SQLITE_ENABLE_COSTMULT
 15674    LogEst costMult;     /* Cost multiplier for using this table */
 15675  #endif
 15676    u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
 15677  #ifndef SQLITE_OMIT_ALTERTABLE
 15678    int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
 15679  #endif
 15680  #ifndef SQLITE_OMIT_VIRTUALTABLE
 15681    int nModuleArg;      /* Number of arguments to the module */
 15682    char **azModuleArg;  /* 0: module 1: schema 2: vtab name 3...: args */
 15683    VTable *pVTable;     /* List of VTable objects. */
 15684  #endif
 15685    Trigger *pTrigger;   /* List of triggers stored in pSchema */
 15686    Schema *pSchema;     /* Schema that contains this table */
 15687    Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
 15688  };
 15689  
 15690  /*
 15691  ** Allowed values for Table.tabFlags.
 15692  **
 15693  ** TF_OOOHidden applies to tables or view that have hidden columns that are
 15694  ** followed by non-hidden columns.  Example:  "CREATE VIRTUAL TABLE x USING
 15695  ** vtab1(a HIDDEN, b);".  Since "b" is a non-hidden column but "a" is hidden,
 15696  ** the TF_OOOHidden attribute would apply in this case.  Such tables require
 15697  ** special handling during INSERT processing.
 15698  */
 15699  #define TF_Readonly        0x0001    /* Read-only system table */
 15700  #define TF_Ephemeral       0x0002    /* An ephemeral table */
 15701  #define TF_HasPrimaryKey   0x0004    /* Table has a primary key */
 15702  #define TF_Autoincrement   0x0008    /* Integer primary key is autoincrement */
 15703  #define TF_HasStat1        0x0010    /* nRowLogEst set from sqlite_stat1 */
 15704  #define TF_WithoutRowid    0x0020    /* No rowid.  PRIMARY KEY is the key */
 15705  #define TF_NoVisibleRowid  0x0040    /* No user-visible "rowid" column */
 15706  #define TF_OOOHidden       0x0080    /* Out-of-Order hidden columns */
 15707  #define TF_StatsUsed       0x0100    /* Query planner decisions affected by
 15708                                       ** Index.aiRowLogEst[] values */
 15709  #define TF_HasNotNull      0x0200    /* Contains NOT NULL constraints */
 15710  
 15711  /*
 15712  ** Test to see whether or not a table is a virtual table.  This is
 15713  ** done as a macro so that it will be optimized out when virtual
 15714  ** table support is omitted from the build.
 15715  */
 15716  #ifndef SQLITE_OMIT_VIRTUALTABLE
 15717  #  define IsVirtual(X)      ((X)->nModuleArg)
 15718  #else
 15719  #  define IsVirtual(X)      0
 15720  #endif
 15721  
 15722  /*
 15723  ** Macros to determine if a column is hidden.  IsOrdinaryHiddenColumn()
 15724  ** only works for non-virtual tables (ordinary tables and views) and is
 15725  ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined.  The
 15726  ** IsHiddenColumn() macro is general purpose.
 15727  */
 15728  #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
 15729  #  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)
 15730  #  define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
 15731  #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
 15732  #  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)
 15733  #  define IsOrdinaryHiddenColumn(X) 0
 15734  #else
 15735  #  define IsHiddenColumn(X)         0
 15736  #  define IsOrdinaryHiddenColumn(X) 0
 15737  #endif
 15738  
 15739  
 15740  /* Does the table have a rowid */
 15741  #define HasRowid(X)     (((X)->tabFlags & TF_WithoutRowid)==0)
 15742  #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
 15743  
 15744  /*
 15745  ** Each foreign key constraint is an instance of the following structure.
 15746  **
 15747  ** A foreign key is associated with two tables.  The "from" table is
 15748  ** the table that contains the REFERENCES clause that creates the foreign
 15749  ** key.  The "to" table is the table that is named in the REFERENCES clause.
 15750  ** Consider this example:
 15751  **
 15752  **     CREATE TABLE ex1(
 15753  **       a INTEGER PRIMARY KEY,
 15754  **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
 15755  **     );
 15756  **
 15757  ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
 15758  ** Equivalent names:
 15759  **
 15760  **     from-table == child-table
 15761  **       to-table == parent-table
 15762  **
 15763  ** Each REFERENCES clause generates an instance of the following structure
 15764  ** which is attached to the from-table.  The to-table need not exist when
 15765  ** the from-table is created.  The existence of the to-table is not checked.
 15766  **
 15767  ** The list of all parents for child Table X is held at X.pFKey.
 15768  **
 15769  ** A list of all children for a table named Z (which might not even exist)
 15770  ** is held in Schema.fkeyHash with a hash key of Z.
 15771  */
 15772  struct FKey {
 15773    Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
 15774    FKey *pNextFrom;  /* Next FKey with the same in pFrom. Next parent of pFrom */
 15775    char *zTo;        /* Name of table that the key points to (aka: Parent) */
 15776    FKey *pNextTo;    /* Next with the same zTo. Next child of zTo. */
 15777    FKey *pPrevTo;    /* Previous with the same zTo */
 15778    int nCol;         /* Number of columns in this key */
 15779    /* EV: R-30323-21917 */
 15780    u8 isDeferred;       /* True if constraint checking is deferred till COMMIT */
 15781    u8 aAction[2];        /* ON DELETE and ON UPDATE actions, respectively */
 15782    Trigger *apTrigger[2];/* Triggers for aAction[] actions */
 15783    struct sColMap {      /* Mapping of columns in pFrom to columns in zTo */
 15784      int iFrom;            /* Index of column in pFrom */
 15785      char *zCol;           /* Name of column in zTo.  If NULL use PRIMARY KEY */
 15786    } aCol[1];            /* One entry for each of nCol columns */
 15787  };
 15788  
 15789  /*
 15790  ** SQLite supports many different ways to resolve a constraint
 15791  ** error.  ROLLBACK processing means that a constraint violation
 15792  ** causes the operation in process to fail and for the current transaction
 15793  ** to be rolled back.  ABORT processing means the operation in process
 15794  ** fails and any prior changes from that one operation are backed out,
 15795  ** but the transaction is not rolled back.  FAIL processing means that
 15796  ** the operation in progress stops and returns an error code.  But prior
 15797  ** changes due to the same operation are not backed out and no rollback
 15798  ** occurs.  IGNORE means that the particular row that caused the constraint
 15799  ** error is not inserted or updated.  Processing continues and no error
 15800  ** is returned.  REPLACE means that preexisting database rows that caused
 15801  ** a UNIQUE constraint violation are removed so that the new insert or
 15802  ** update can proceed.  Processing continues and no error is reported.
 15803  **
 15804  ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
 15805  ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
 15806  ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
 15807  ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
 15808  ** referenced table row is propagated into the row that holds the
 15809  ** foreign key.
 15810  **
 15811  ** The following symbolic values are used to record which type
 15812  ** of action to take.
 15813  */
 15814  #define OE_None     0   /* There is no constraint to check */
 15815  #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
 15816  #define OE_Abort    2   /* Back out changes but do no rollback transaction */
 15817  #define OE_Fail     3   /* Stop the operation but leave all prior changes */
 15818  #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
 15819  #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
 15820  
 15821  #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
 15822  #define OE_SetNull  7   /* Set the foreign key value to NULL */
 15823  #define OE_SetDflt  8   /* Set the foreign key value to its default */
 15824  #define OE_Cascade  9   /* Cascade the changes */
 15825  
 15826  #define OE_Default  10  /* Do whatever the default action is */
 15827  
 15828  
 15829  /*
 15830  ** An instance of the following structure is passed as the first
 15831  ** argument to sqlite3VdbeKeyCompare and is used to control the
 15832  ** comparison of the two index keys.
 15833  **
 15834  ** Note that aSortOrder[] and aColl[] have nField+1 slots.  There
 15835  ** are nField slots for the columns of an index then one extra slot
 15836  ** for the rowid at the end.
 15837  */
 15838  struct KeyInfo {
 15839    u32 nRef;           /* Number of references to this KeyInfo object */
 15840    u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
 15841    u16 nKeyField;      /* Number of key columns in the index */
 15842    u16 nAllField;      /* Total columns, including key plus others */
 15843    sqlite3 *db;        /* The database connection */
 15844    u8 *aSortOrder;     /* Sort order for each column. */
 15845    CollSeq *aColl[1];  /* Collating sequence for each term of the key */
 15846  };
 15847  
 15848  /*
 15849  ** This object holds a record which has been parsed out into individual
 15850  ** fields, for the purposes of doing a comparison.
 15851  **
 15852  ** A record is an object that contains one or more fields of data.
 15853  ** Records are used to store the content of a table row and to store
 15854  ** the key of an index.  A blob encoding of a record is created by
 15855  ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
 15856  ** OP_Column opcode.
 15857  **
 15858  ** An instance of this object serves as a "key" for doing a search on
 15859  ** an index b+tree. The goal of the search is to find the entry that
 15860  ** is closed to the key described by this object.  This object might hold
 15861  ** just a prefix of the key.  The number of fields is given by
 15862  ** pKeyInfo->nField.
 15863  **
 15864  ** The r1 and r2 fields are the values to return if this key is less than
 15865  ** or greater than a key in the btree, respectively.  These are normally
 15866  ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
 15867  ** is in DESC order.
 15868  **
 15869  ** The key comparison functions actually return default_rc when they find
 15870  ** an equals comparison.  default_rc can be -1, 0, or +1.  If there are
 15871  ** multiple entries in the b-tree with the same key (when only looking
 15872  ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
 15873  ** cause the search to find the last match, or +1 to cause the search to
 15874  ** find the first match.
 15875  **
 15876  ** The key comparison functions will set eqSeen to true if they ever
 15877  ** get and equal results when comparing this structure to a b-tree record.
 15878  ** When default_rc!=0, the search might end up on the record immediately
 15879  ** before the first match or immediately after the last match.  The
 15880  ** eqSeen field will indicate whether or not an exact match exists in the
 15881  ** b-tree.
 15882  */
 15883  struct UnpackedRecord {
 15884    KeyInfo *pKeyInfo;  /* Collation and sort-order information */
 15885    Mem *aMem;          /* Values */
 15886    u16 nField;         /* Number of entries in apMem[] */
 15887    i8 default_rc;      /* Comparison result if keys are equal */
 15888    u8 errCode;         /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
 15889    i8 r1;              /* Value to return if (lhs < rhs) */
 15890    i8 r2;              /* Value to return if (lhs > rhs) */
 15891    u8 eqSeen;          /* True if an equality comparison has been seen */
 15892  };
 15893  
 15894  
 15895  /*
 15896  ** Each SQL index is represented in memory by an
 15897  ** instance of the following structure.
 15898  **
 15899  ** The columns of the table that are to be indexed are described
 15900  ** by the aiColumn[] field of this structure.  For example, suppose
 15901  ** we have the following table and index:
 15902  **
 15903  **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
 15904  **     CREATE INDEX Ex2 ON Ex1(c3,c1);
 15905  **
 15906  ** In the Table structure describing Ex1, nCol==3 because there are
 15907  ** three columns in the table.  In the Index structure describing
 15908  ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
 15909  ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
 15910  ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
 15911  ** The second column to be indexed (c1) has an index of 0 in
 15912  ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
 15913  **
 15914  ** The Index.onError field determines whether or not the indexed columns
 15915  ** must be unique and what to do if they are not.  When Index.onError=OE_None,
 15916  ** it means this is not a unique index.  Otherwise it is a unique index
 15917  ** and the value of Index.onError indicate the which conflict resolution
 15918  ** algorithm to employ whenever an attempt is made to insert a non-unique
 15919  ** element.
 15920  **
 15921  ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
 15922  ** generate VDBE code (as opposed to parsing one read from an sqlite_master
 15923  ** table as part of parsing an existing database schema), transient instances
 15924  ** of this structure may be created. In this case the Index.tnum variable is
 15925  ** used to store the address of a VDBE instruction, not a database page
 15926  ** number (it cannot - the database page is not allocated until the VDBE
 15927  ** program is executed). See convertToWithoutRowidTable() for details.
 15928  */
 15929  struct Index {
 15930    char *zName;             /* Name of this index */
 15931    i16 *aiColumn;           /* Which columns are used by this index.  1st is 0 */
 15932    LogEst *aiRowLogEst;     /* From ANALYZE: Est. rows selected by each column */
 15933    Table *pTable;           /* The SQL table being indexed */
 15934    char *zColAff;           /* String defining the affinity of each column */
 15935    Index *pNext;            /* The next index associated with the same table */
 15936    Schema *pSchema;         /* Schema containing this index */
 15937    u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
 15938    const char **azColl;     /* Array of collation sequence names for index */
 15939    Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
 15940    ExprList *aColExpr;      /* Column expressions */
 15941    int tnum;                /* DB Page containing root of this index */
 15942    LogEst szIdxRow;         /* Estimated average row size in bytes */
 15943    u16 nKeyCol;             /* Number of columns forming the key */
 15944    u16 nColumn;             /* Number of columns stored in the index */
 15945    u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
 15946    unsigned idxType:2;      /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
 15947    unsigned bUnordered:1;   /* Use this index for == or IN queries only */
 15948    unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */
 15949    unsigned isResized:1;    /* True if resizeIndexObject() has been called */
 15950    unsigned isCovering:1;   /* True if this is a covering index */
 15951    unsigned noSkipScan:1;   /* Do not try to use skip-scan if true */
 15952    unsigned hasStat1:1;     /* aiRowLogEst values come from sqlite_stat1 */
 15953  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 15954    int nSample;             /* Number of elements in aSample[] */
 15955    int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
 15956    tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */
 15957    IndexSample *aSample;    /* Samples of the left-most key */
 15958    tRowcnt *aiRowEst;       /* Non-logarithmic stat1 data for this index */
 15959    tRowcnt nRowEst0;        /* Non-logarithmic number of rows in the index */
 15960  #endif
 15961  };
 15962  
 15963  /*
 15964  ** Allowed values for Index.idxType
 15965  */
 15966  #define SQLITE_IDXTYPE_APPDEF      0   /* Created using CREATE INDEX */
 15967  #define SQLITE_IDXTYPE_UNIQUE      1   /* Implements a UNIQUE constraint */
 15968  #define SQLITE_IDXTYPE_PRIMARYKEY  2   /* Is the PRIMARY KEY for the table */
 15969  
 15970  /* Return true if index X is a PRIMARY KEY index */
 15971  #define IsPrimaryKeyIndex(X)  ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
 15972  
 15973  /* Return true if index X is a UNIQUE index */
 15974  #define IsUniqueIndex(X)      ((X)->onError!=OE_None)
 15975  
 15976  /* The Index.aiColumn[] values are normally positive integer.  But
 15977  ** there are some negative values that have special meaning:
 15978  */
 15979  #define XN_ROWID     (-1)     /* Indexed column is the rowid */
 15980  #define XN_EXPR      (-2)     /* Indexed column is an expression */
 15981  
 15982  /*
 15983  ** Each sample stored in the sqlite_stat3 table is represented in memory
 15984  ** using a structure of this type.  See documentation at the top of the
 15985  ** analyze.c source file for additional information.
 15986  */
 15987  struct IndexSample {
 15988    void *p;          /* Pointer to sampled record */
 15989    int n;            /* Size of record in bytes */
 15990    tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */
 15991    tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */
 15992    tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */
 15993  };
 15994  
 15995  /*
 15996  ** Each token coming out of the lexer is an instance of
 15997  ** this structure.  Tokens are also used as part of an expression.
 15998  **
 15999  ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
 16000  ** may contain random values.  Do not make any assumptions about Token.dyn
 16001  ** and Token.n when Token.z==0.
 16002  */
 16003  struct Token {
 16004    const char *z;     /* Text of the token.  Not NULL-terminated! */
 16005    unsigned int n;    /* Number of characters in this token */
 16006  };
 16007  
 16008  /*
 16009  ** An instance of this structure contains information needed to generate
 16010  ** code for a SELECT that contains aggregate functions.
 16011  **
 16012  ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
 16013  ** pointer to this structure.  The Expr.iColumn field is the index in
 16014  ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
 16015  ** code for that node.
 16016  **
 16017  ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
 16018  ** original Select structure that describes the SELECT statement.  These
 16019  ** fields do not need to be freed when deallocating the AggInfo structure.
 16020  */
 16021  struct AggInfo {
 16022    u8 directMode;          /* Direct rendering mode means take data directly
 16023                            ** from source tables rather than from accumulators */
 16024    u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
 16025                            ** than the source table */
 16026    int sortingIdx;         /* Cursor number of the sorting index */
 16027    int sortingIdxPTab;     /* Cursor number of pseudo-table */
 16028    int nSortingColumn;     /* Number of columns in the sorting index */
 16029    int mnReg, mxReg;       /* Range of registers allocated for aCol and aFunc */
 16030    ExprList *pGroupBy;     /* The group by clause */
 16031    struct AggInfo_col {    /* For each column used in source tables */
 16032      Table *pTab;             /* Source table */
 16033      int iTable;              /* Cursor number of the source table */
 16034      int iColumn;             /* Column number within the source table */
 16035      int iSorterColumn;       /* Column number in the sorting index */
 16036      int iMem;                /* Memory location that acts as accumulator */
 16037      Expr *pExpr;             /* The original expression */
 16038    } *aCol;
 16039    int nColumn;            /* Number of used entries in aCol[] */
 16040    int nAccumulator;       /* Number of columns that show through to the output.
 16041                            ** Additional columns are used only as parameters to
 16042                            ** aggregate functions */
 16043    struct AggInfo_func {   /* For each aggregate function */
 16044      Expr *pExpr;             /* Expression encoding the function */
 16045      FuncDef *pFunc;          /* The aggregate function implementation */
 16046      int iMem;                /* Memory location that acts as accumulator */
 16047      int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
 16048    } *aFunc;
 16049    int nFunc;              /* Number of entries in aFunc[] */
 16050  };
 16051  
 16052  /*
 16053  ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
 16054  ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
 16055  ** than 32767 we have to make it 32-bit.  16-bit is preferred because
 16056  ** it uses less memory in the Expr object, which is a big memory user
 16057  ** in systems with lots of prepared statements.  And few applications
 16058  ** need more than about 10 or 20 variables.  But some extreme users want
 16059  ** to have prepared statements with over 32767 variables, and for them
 16060  ** the option is available (at compile-time).
 16061  */
 16062  #if SQLITE_MAX_VARIABLE_NUMBER<=32767
 16063  typedef i16 ynVar;
 16064  #else
 16065  typedef int ynVar;
 16066  #endif
 16067  
 16068  /*
 16069  ** Each node of an expression in the parse tree is an instance
 16070  ** of this structure.
 16071  **
 16072  ** Expr.op is the opcode. The integer parser token codes are reused
 16073  ** as opcodes here. For example, the parser defines TK_GE to be an integer
 16074  ** code representing the ">=" operator. This same integer code is reused
 16075  ** to represent the greater-than-or-equal-to operator in the expression
 16076  ** tree.
 16077  **
 16078  ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
 16079  ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
 16080  ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
 16081  ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
 16082  ** then Expr.token contains the name of the function.
 16083  **
 16084  ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
 16085  ** binary operator. Either or both may be NULL.
 16086  **
 16087  ** Expr.x.pList is a list of arguments if the expression is an SQL function,
 16088  ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
 16089  ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
 16090  ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
 16091  ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
 16092  ** valid.
 16093  **
 16094  ** An expression of the form ID or ID.ID refers to a column in a table.
 16095  ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
 16096  ** the integer cursor number of a VDBE cursor pointing to that table and
 16097  ** Expr.iColumn is the column number for the specific column.  If the
 16098  ** expression is used as a result in an aggregate SELECT, then the
 16099  ** value is also stored in the Expr.iAgg column in the aggregate so that
 16100  ** it can be accessed after all aggregates are computed.
 16101  **
 16102  ** If the expression is an unbound variable marker (a question mark
 16103  ** character '?' in the original SQL) then the Expr.iTable holds the index
 16104  ** number for that variable.
 16105  **
 16106  ** If the expression is a subquery then Expr.iColumn holds an integer
 16107  ** register number containing the result of the subquery.  If the
 16108  ** subquery gives a constant result, then iTable is -1.  If the subquery
 16109  ** gives a different answer at different times during statement processing
 16110  ** then iTable is the address of a subroutine that computes the subquery.
 16111  **
 16112  ** If the Expr is of type OP_Column, and the table it is selecting from
 16113  ** is a disk table or the "old.*" pseudo-table, then pTab points to the
 16114  ** corresponding table definition.
 16115  **
 16116  ** ALLOCATION NOTES:
 16117  **
 16118  ** Expr objects can use a lot of memory space in database schema.  To
 16119  ** help reduce memory requirements, sometimes an Expr object will be
 16120  ** truncated.  And to reduce the number of memory allocations, sometimes
 16121  ** two or more Expr objects will be stored in a single memory allocation,
 16122  ** together with Expr.zToken strings.
 16123  **
 16124  ** If the EP_Reduced and EP_TokenOnly flags are set when
 16125  ** an Expr object is truncated.  When EP_Reduced is set, then all
 16126  ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
 16127  ** are contained within the same memory allocation.  Note, however, that
 16128  ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
 16129  ** allocated, regardless of whether or not EP_Reduced is set.
 16130  */
 16131  struct Expr {
 16132    u8 op;                 /* Operation performed by this node */
 16133    char affinity;         /* The affinity of the column or 0 if not a column */
 16134    u32 flags;             /* Various flags.  EP_* See below */
 16135    union {
 16136      char *zToken;          /* Token value. Zero terminated and dequoted */
 16137      int iValue;            /* Non-negative integer value if EP_IntValue */
 16138    } u;
 16139  
 16140    /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
 16141    ** space is allocated for the fields below this point. An attempt to
 16142    ** access them will result in a segfault or malfunction.
 16143    *********************************************************************/
 16144  
 16145    Expr *pLeft;           /* Left subnode */
 16146    Expr *pRight;          /* Right subnode */
 16147    union {
 16148      ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
 16149      Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */
 16150    } x;
 16151  
 16152    /* If the EP_Reduced flag is set in the Expr.flags mask, then no
 16153    ** space is allocated for the fields below this point. An attempt to
 16154    ** access them will result in a segfault or malfunction.
 16155    *********************************************************************/
 16156  
 16157  #if SQLITE_MAX_EXPR_DEPTH>0
 16158    int nHeight;           /* Height of the tree headed by this node */
 16159  #endif
 16160    int iTable;            /* TK_COLUMN: cursor number of table holding column
 16161                           ** TK_REGISTER: register number
 16162                           ** TK_TRIGGER: 1 -> new, 0 -> old
 16163                           ** EP_Unlikely:  134217728 times likelihood
 16164                           ** TK_SELECT: 1st register of result vector */
 16165    ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
 16166                           ** TK_VARIABLE: variable number (always >= 1).
 16167                           ** TK_SELECT_COLUMN: column of the result vector */
 16168    i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
 16169    i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
 16170    u8 op2;                /* TK_REGISTER: original value of Expr.op
 16171                           ** TK_COLUMN: the value of p5 for OP_Column
 16172                           ** TK_AGG_FUNCTION: nesting depth */
 16173    AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
 16174    Table *pTab;           /* Table for TK_COLUMN expressions.  Can be NULL
 16175                           ** for a column of an index on an expression */
 16176  };
 16177  
 16178  /*
 16179  ** The following are the meanings of bits in the Expr.flags field.
 16180  */
 16181  #define EP_FromJoin  0x000001 /* Originates in ON/USING clause of outer join */
 16182  #define EP_Agg       0x000002 /* Contains one or more aggregate functions */
 16183                    /* 0x000004 // available for use */
 16184                    /* 0x000008 // available for use */
 16185  #define EP_Distinct  0x000010 /* Aggregate function with DISTINCT keyword */
 16186  #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
 16187  #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
 16188  #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
 16189  #define EP_Collate   0x000100 /* Tree contains a TK_COLLATE operator */
 16190  #define EP_Generic   0x000200 /* Ignore COLLATE or affinity on this tree */
 16191  #define EP_IntValue  0x000400 /* Integer value contained in u.iValue */
 16192  #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
 16193  #define EP_Skip      0x001000 /* COLLATE, AS, or UNLIKELY */
 16194  #define EP_Reduced   0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
 16195  #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
 16196  #define EP_Static    0x008000 /* Held in memory not obtained from malloc() */
 16197  #define EP_MemToken  0x010000 /* Need to sqlite3DbFree() Expr.zToken */
 16198  #define EP_NoReduce  0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
 16199  #define EP_Unlikely  0x040000 /* unlikely() or likelihood() function */
 16200  #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
 16201  #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
 16202  #define EP_Subquery  0x200000 /* Tree contains a TK_SELECT operator */
 16203  #define EP_Alias     0x400000 /* Is an alias for a result set column */
 16204  #define EP_Leaf      0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
 16205  
 16206  /*
 16207  ** Combinations of two or more EP_* flags
 16208  */
 16209  #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
 16210  
 16211  /*
 16212  ** These macros can be used to test, set, or clear bits in the
 16213  ** Expr.flags field.
 16214  */
 16215  #define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
 16216  #define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))
 16217  #define ExprSetProperty(E,P)     (E)->flags|=(P)
 16218  #define ExprClearProperty(E,P)   (E)->flags&=~(P)
 16219  
 16220  /* The ExprSetVVAProperty() macro is used for Verification, Validation,
 16221  ** and Accreditation only.  It works like ExprSetProperty() during VVA
 16222  ** processes but is a no-op for delivery.
 16223  */
 16224  #ifdef SQLITE_DEBUG
 16225  # define ExprSetVVAProperty(E,P)  (E)->flags|=(P)
 16226  #else
 16227  # define ExprSetVVAProperty(E,P)
 16228  #endif
 16229  
 16230  /*
 16231  ** Macros to determine the number of bytes required by a normal Expr
 16232  ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
 16233  ** and an Expr struct with the EP_TokenOnly flag set.
 16234  */
 16235  #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
 16236  #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
 16237  #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
 16238  
 16239  /*
 16240  ** Flags passed to the sqlite3ExprDup() function. See the header comment
 16241  ** above sqlite3ExprDup() for details.
 16242  */
 16243  #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
 16244  
 16245  /*
 16246  ** A list of expressions.  Each expression may optionally have a
 16247  ** name.  An expr/name combination can be used in several ways, such
 16248  ** as the list of "expr AS ID" fields following a "SELECT" or in the
 16249  ** list of "ID = expr" items in an UPDATE.  A list of expressions can
 16250  ** also be used as the argument to a function, in which case the a.zName
 16251  ** field is not used.
 16252  **
 16253  ** By default the Expr.zSpan field holds a human-readable description of
 16254  ** the expression that is used in the generation of error messages and
 16255  ** column labels.  In this case, Expr.zSpan is typically the text of a
 16256  ** column expression as it exists in a SELECT statement.  However, if
 16257  ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
 16258  ** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
 16259  ** form is used for name resolution with nested FROM clauses.
 16260  */
 16261  struct ExprList {
 16262    int nExpr;             /* Number of expressions on the list */
 16263    struct ExprList_item { /* For each expression in the list */
 16264      Expr *pExpr;            /* The parse tree for this expression */
 16265      char *zName;            /* Token associated with this expression */
 16266      char *zSpan;            /* Original text of the expression */
 16267      u8 sortOrder;           /* 1 for DESC or 0 for ASC */
 16268      unsigned done :1;       /* A flag to indicate when processing is finished */
 16269      unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
 16270      unsigned reusable :1;   /* Constant expression is reusable */
 16271      union {
 16272        struct {
 16273          u16 iOrderByCol;      /* For ORDER BY, column number in result set */
 16274          u16 iAlias;           /* Index into Parse.aAlias[] for zName */
 16275        } x;
 16276        int iConstExprReg;      /* Register in which Expr value is cached */
 16277      } u;
 16278    } a[1];                  /* One slot for each expression in the list */
 16279  };
 16280  
 16281  /*
 16282  ** An instance of this structure is used by the parser to record both
 16283  ** the parse tree for an expression and the span of input text for an
 16284  ** expression.
 16285  */
 16286  struct ExprSpan {
 16287    Expr *pExpr;          /* The expression parse tree */
 16288    const char *zStart;   /* First character of input text */
 16289    const char *zEnd;     /* One character past the end of input text */
 16290  };
 16291  
 16292  /*
 16293  ** An instance of this structure can hold a simple list of identifiers,
 16294  ** such as the list "a,b,c" in the following statements:
 16295  **
 16296  **      INSERT INTO t(a,b,c) VALUES ...;
 16297  **      CREATE INDEX idx ON t(a,b,c);
 16298  **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
 16299  **
 16300  ** The IdList.a.idx field is used when the IdList represents the list of
 16301  ** column names after a table name in an INSERT statement.  In the statement
 16302  **
 16303  **     INSERT INTO t(a,b,c) ...
 16304  **
 16305  ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
 16306  */
 16307  struct IdList {
 16308    struct IdList_item {
 16309      char *zName;      /* Name of the identifier */
 16310      int idx;          /* Index in some Table.aCol[] of a column named zName */
 16311    } *a;
 16312    int nId;         /* Number of identifiers on the list */
 16313  };
 16314  
 16315  /*
 16316  ** The bitmask datatype defined below is used for various optimizations.
 16317  **
 16318  ** Changing this from a 64-bit to a 32-bit type limits the number of
 16319  ** tables in a join to 32 instead of 64.  But it also reduces the size
 16320  ** of the library by 738 bytes on ix86.
 16321  */
 16322  #ifdef SQLITE_BITMASK_TYPE
 16323    typedef SQLITE_BITMASK_TYPE Bitmask;
 16324  #else
 16325    typedef u64 Bitmask;
 16326  #endif
 16327  
 16328  /*
 16329  ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
 16330  */
 16331  #define BMS  ((int)(sizeof(Bitmask)*8))
 16332  
 16333  /*
 16334  ** A bit in a Bitmask
 16335  */
 16336  #define MASKBIT(n)   (((Bitmask)1)<<(n))
 16337  #define MASKBIT32(n) (((unsigned int)1)<<(n))
 16338  #define ALLBITS      ((Bitmask)-1)
 16339  
 16340  /*
 16341  ** The following structure describes the FROM clause of a SELECT statement.
 16342  ** Each table or subquery in the FROM clause is a separate element of
 16343  ** the SrcList.a[] array.
 16344  **
 16345  ** With the addition of multiple database support, the following structure
 16346  ** can also be used to describe a particular table such as the table that
 16347  ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
 16348  ** such a table must be a simple name: ID.  But in SQLite, the table can
 16349  ** now be identified by a database name, a dot, then the table name: ID.ID.
 16350  **
 16351  ** The jointype starts out showing the join type between the current table
 16352  ** and the next table on the list.  The parser builds the list this way.
 16353  ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
 16354  ** jointype expresses the join between the table and the previous table.
 16355  **
 16356  ** In the colUsed field, the high-order bit (bit 63) is set if the table
 16357  ** contains more than 63 columns and the 64-th or later column is used.
 16358  */
 16359  struct SrcList {
 16360    int nSrc;        /* Number of tables or subqueries in the FROM clause */
 16361    u32 nAlloc;      /* Number of entries allocated in a[] below */
 16362    struct SrcList_item {
 16363      Schema *pSchema;  /* Schema to which this item is fixed */
 16364      char *zDatabase;  /* Name of database holding this table */
 16365      char *zName;      /* Name of the table */
 16366      char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
 16367      Table *pTab;      /* An SQL table corresponding to zName */
 16368      Select *pSelect;  /* A SELECT statement used in place of a table name */
 16369      int addrFillSub;  /* Address of subroutine to manifest a subquery */
 16370      int regReturn;    /* Register holding return address of addrFillSub */
 16371      int regResult;    /* Registers holding results of a co-routine */
 16372      struct {
 16373        u8 jointype;      /* Type of join between this table and the previous */
 16374        unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
 16375        unsigned isIndexedBy :1;   /* True if there is an INDEXED BY clause */
 16376        unsigned isTabFunc :1;     /* True if table-valued-function syntax */
 16377        unsigned isCorrelated :1;  /* True if sub-query is correlated */
 16378        unsigned viaCoroutine :1;  /* Implemented as a co-routine */
 16379        unsigned isRecursive :1;   /* True for recursive reference in WITH */
 16380      } fg;
 16381  #ifndef SQLITE_OMIT_EXPLAIN
 16382      u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
 16383  #endif
 16384      int iCursor;      /* The VDBE cursor number used to access this table */
 16385      Expr *pOn;        /* The ON clause of a join */
 16386      IdList *pUsing;   /* The USING clause of a join */
 16387      Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
 16388      union {
 16389        char *zIndexedBy;    /* Identifier from "INDEXED BY <zIndex>" clause */
 16390        ExprList *pFuncArg;  /* Arguments to table-valued-function */
 16391      } u1;
 16392      Index *pIBIndex;  /* Index structure corresponding to u1.zIndexedBy */
 16393    } a[1];             /* One entry for each identifier on the list */
 16394  };
 16395  
 16396  /*
 16397  ** Permitted values of the SrcList.a.jointype field
 16398  */
 16399  #define JT_INNER     0x0001    /* Any kind of inner or cross join */
 16400  #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
 16401  #define JT_NATURAL   0x0004    /* True for a "natural" join */
 16402  #define JT_LEFT      0x0008    /* Left outer join */
 16403  #define JT_RIGHT     0x0010    /* Right outer join */
 16404  #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
 16405  #define JT_ERROR     0x0040    /* unknown or unsupported join type */
 16406  
 16407  
 16408  /*
 16409  ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
 16410  ** and the WhereInfo.wctrlFlags member.
 16411  **
 16412  ** Value constraints (enforced via assert()):
 16413  **     WHERE_USE_LIMIT  == SF_FixedLimit
 16414  */
 16415  #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
 16416  #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
 16417  #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
 16418  #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
 16419  #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
 16420  #define WHERE_DUPLICATES_OK    0x0010 /* Ok to return a row more than once */
 16421  #define WHERE_OR_SUBCLAUSE     0x0020 /* Processing a sub-WHERE as part of
 16422                                        ** the OR optimization  */
 16423  #define WHERE_GROUPBY          0x0040 /* pOrderBy is really a GROUP BY */
 16424  #define WHERE_DISTINCTBY       0x0080 /* pOrderby is really a DISTINCT clause */
 16425  #define WHERE_WANT_DISTINCT    0x0100 /* All output needs to be distinct */
 16426  #define WHERE_SORTBYGROUP      0x0200 /* Support sqlite3WhereIsSorted() */
 16427  #define WHERE_SEEK_TABLE       0x0400 /* Do not defer seeks on main table */
 16428  #define WHERE_ORDERBY_LIMIT    0x0800 /* ORDERBY+LIMIT on the inner loop */
 16429  #define WHERE_SEEK_UNIQ_TABLE  0x1000 /* Do not defer seeks if unique */
 16430                          /*     0x2000    not currently used */
 16431  #define WHERE_USE_LIMIT        0x4000 /* Use the LIMIT in cost estimates */
 16432                          /*     0x8000    not currently used */
 16433  
 16434  /* Allowed return values from sqlite3WhereIsDistinct()
 16435  */
 16436  #define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
 16437  #define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
 16438  #define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
 16439  #define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
 16440  
 16441  /*
 16442  ** A NameContext defines a context in which to resolve table and column
 16443  ** names.  The context consists of a list of tables (the pSrcList) field and
 16444  ** a list of named expression (pEList).  The named expression list may
 16445  ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
 16446  ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
 16447  ** pEList corresponds to the result set of a SELECT and is NULL for
 16448  ** other statements.
 16449  **
 16450  ** NameContexts can be nested.  When resolving names, the inner-most
 16451  ** context is searched first.  If no match is found, the next outer
 16452  ** context is checked.  If there is still no match, the next context
 16453  ** is checked.  This process continues until either a match is found
 16454  ** or all contexts are check.  When a match is found, the nRef member of
 16455  ** the context containing the match is incremented.
 16456  **
 16457  ** Each subquery gets a new NameContext.  The pNext field points to the
 16458  ** NameContext in the parent query.  Thus the process of scanning the
 16459  ** NameContext list corresponds to searching through successively outer
 16460  ** subqueries looking for a match.
 16461  */
 16462  struct NameContext {
 16463    Parse *pParse;       /* The parser */
 16464    SrcList *pSrcList;   /* One or more tables used to resolve names */
 16465    ExprList *pEList;    /* Optional list of result-set columns */
 16466    AggInfo *pAggInfo;   /* Information about aggregates at this level */
 16467    NameContext *pNext;  /* Next outer name context.  NULL for outermost */
 16468    int nRef;            /* Number of names resolved by this context */
 16469    int nErr;            /* Number of errors encountered while resolving names */
 16470    u16 ncFlags;         /* Zero or more NC_* flags defined below */
 16471  };
 16472  
 16473  /*
 16474  ** Allowed values for the NameContext, ncFlags field.
 16475  **
 16476  ** Value constraints (all checked via assert()):
 16477  **    NC_HasAgg    == SF_HasAgg
 16478  **    NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
 16479  **
 16480  */
 16481  #define NC_AllowAgg  0x0001  /* Aggregate functions are allowed here */
 16482  #define NC_PartIdx   0x0002  /* True if resolving a partial index WHERE */
 16483  #define NC_IsCheck   0x0004  /* True if resolving names in a CHECK constraint */
 16484  #define NC_InAggFunc 0x0008  /* True if analyzing arguments to an agg func */
 16485  #define NC_HasAgg    0x0010  /* One or more aggregate functions seen */
 16486  #define NC_IdxExpr   0x0020  /* True if resolving columns of CREATE INDEX */
 16487  #define NC_VarSelect 0x0040  /* A correlated subquery has been seen */
 16488  #define NC_MinMaxAgg 0x1000  /* min/max aggregates seen.  See note above */
 16489  
 16490  /*
 16491  ** An instance of the following structure contains all information
 16492  ** needed to generate code for a single SELECT statement.
 16493  **
 16494  ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
 16495  ** If there is a LIMIT clause, the parser sets nLimit to the value of the
 16496  ** limit and nOffset to the value of the offset (or 0 if there is not
 16497  ** offset).  But later on, nLimit and nOffset become the memory locations
 16498  ** in the VDBE that record the limit and offset counters.
 16499  **
 16500  ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
 16501  ** These addresses must be stored so that we can go back and fill in
 16502  ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
 16503  ** the number of columns in P2 can be computed at the same time
 16504  ** as the OP_OpenEphm instruction is coded because not
 16505  ** enough information about the compound query is known at that point.
 16506  ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
 16507  ** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
 16508  ** sequences for the ORDER BY clause.
 16509  */
 16510  struct Select {
 16511    ExprList *pEList;      /* The fields of the result */
 16512    u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
 16513    LogEst nSelectRow;     /* Estimated number of result rows */
 16514    u32 selFlags;          /* Various SF_* values */
 16515    int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
 16516  #if SELECTTRACE_ENABLED
 16517    char zSelName[12];     /* Symbolic name of this SELECT use for debugging */
 16518  #endif
 16519    int addrOpenEphm[2];   /* OP_OpenEphem opcodes related to this select */
 16520    SrcList *pSrc;         /* The FROM clause */
 16521    Expr *pWhere;          /* The WHERE clause */
 16522    ExprList *pGroupBy;    /* The GROUP BY clause */
 16523    Expr *pHaving;         /* The HAVING clause */
 16524    ExprList *pOrderBy;    /* The ORDER BY clause */
 16525    Select *pPrior;        /* Prior select in a compound select statement */
 16526    Select *pNext;         /* Next select to the left in a compound */
 16527    Expr *pLimit;          /* LIMIT expression. NULL means not used. */
 16528    Expr *pOffset;         /* OFFSET expression. NULL means not used. */
 16529    With *pWith;           /* WITH clause attached to this select. Or NULL. */
 16530  };
 16531  
 16532  /*
 16533  ** Allowed values for Select.selFlags.  The "SF" prefix stands for
 16534  ** "Select Flag".
 16535  **
 16536  ** Value constraints (all checked via assert())
 16537  **     SF_HasAgg     == NC_HasAgg
 16538  **     SF_MinMaxAgg  == NC_MinMaxAgg     == SQLITE_FUNC_MINMAX
 16539  **     SF_FixedLimit == WHERE_USE_LIMIT
 16540  */
 16541  #define SF_Distinct       0x00001  /* Output should be DISTINCT */
 16542  #define SF_All            0x00002  /* Includes the ALL keyword */
 16543  #define SF_Resolved       0x00004  /* Identifiers have been resolved */
 16544  #define SF_Aggregate      0x00008  /* Contains agg functions or a GROUP BY */
 16545  #define SF_HasAgg         0x00010  /* Contains aggregate functions */
 16546  #define SF_UsesEphemeral  0x00020  /* Uses the OpenEphemeral opcode */
 16547  #define SF_Expanded       0x00040  /* sqlite3SelectExpand() called on this */
 16548  #define SF_HasTypeInfo    0x00080  /* FROM subqueries have Table metadata */
 16549  #define SF_Compound       0x00100  /* Part of a compound query */
 16550  #define SF_Values         0x00200  /* Synthesized from VALUES clause */
 16551  #define SF_MultiValue     0x00400  /* Single VALUES term with multiple rows */
 16552  #define SF_NestedFrom     0x00800  /* Part of a parenthesized FROM clause */
 16553  #define SF_MinMaxAgg      0x01000  /* Aggregate containing min() or max() */
 16554  #define SF_Recursive      0x02000  /* The recursive part of a recursive CTE */
 16555  #define SF_FixedLimit     0x04000  /* nSelectRow set by a constant LIMIT */
 16556  #define SF_MaybeConvert   0x08000  /* Need convertCompoundSelectToSubquery() */
 16557  #define SF_Converted      0x10000  /* By convertCompoundSelectToSubquery() */
 16558  #define SF_IncludeHidden  0x20000  /* Include hidden columns in output */
 16559  
 16560  
 16561  /*
 16562  ** The results of a SELECT can be distributed in several ways, as defined
 16563  ** by one of the following macros.  The "SRT" prefix means "SELECT Result
 16564  ** Type".
 16565  **
 16566  **     SRT_Union       Store results as a key in a temporary index
 16567  **                     identified by pDest->iSDParm.
 16568  **
 16569  **     SRT_Except      Remove results from the temporary index pDest->iSDParm.
 16570  **
 16571  **     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
 16572  **                     set is not empty.
 16573  **
 16574  **     SRT_Discard     Throw the results away.  This is used by SELECT
 16575  **                     statements within triggers whose only purpose is
 16576  **                     the side-effects of functions.
 16577  **
 16578  ** All of the above are free to ignore their ORDER BY clause. Those that
 16579  ** follow must honor the ORDER BY clause.
 16580  **
 16581  **     SRT_Output      Generate a row of output (using the OP_ResultRow
 16582  **                     opcode) for each row in the result set.
 16583  **
 16584  **     SRT_Mem         Only valid if the result is a single column.
 16585  **                     Store the first column of the first result row
 16586  **                     in register pDest->iSDParm then abandon the rest
 16587  **                     of the query.  This destination implies "LIMIT 1".
 16588  **
 16589  **     SRT_Set         The result must be a single column.  Store each
 16590  **                     row of result as the key in table pDest->iSDParm.
 16591  **                     Apply the affinity pDest->affSdst before storing
 16592  **                     results.  Used to implement "IN (SELECT ...)".
 16593  **
 16594  **     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
 16595  **                     the result there. The cursor is left open after
 16596  **                     returning.  This is like SRT_Table except that
 16597  **                     this destination uses OP_OpenEphemeral to create
 16598  **                     the table first.
 16599  **
 16600  **     SRT_Coroutine   Generate a co-routine that returns a new row of
 16601  **                     results each time it is invoked.  The entry point
 16602  **                     of the co-routine is stored in register pDest->iSDParm
 16603  **                     and the result row is stored in pDest->nDest registers
 16604  **                     starting with pDest->iSdst.
 16605  **
 16606  **     SRT_Table       Store results in temporary table pDest->iSDParm.
 16607  **     SRT_Fifo        This is like SRT_EphemTab except that the table
 16608  **                     is assumed to already be open.  SRT_Fifo has
 16609  **                     the additional property of being able to ignore
 16610  **                     the ORDER BY clause.
 16611  **
 16612  **     SRT_DistFifo    Store results in a temporary table pDest->iSDParm.
 16613  **                     But also use temporary table pDest->iSDParm+1 as
 16614  **                     a record of all prior results and ignore any duplicate
 16615  **                     rows.  Name means:  "Distinct Fifo".
 16616  **
 16617  **     SRT_Queue       Store results in priority queue pDest->iSDParm (really
 16618  **                     an index).  Append a sequence number so that all entries
 16619  **                     are distinct.
 16620  **
 16621  **     SRT_DistQueue   Store results in priority queue pDest->iSDParm only if
 16622  **                     the same record has never been stored before.  The
 16623  **                     index at pDest->iSDParm+1 hold all prior stores.
 16624  */
 16625  #define SRT_Union        1  /* Store result as keys in an index */
 16626  #define SRT_Except       2  /* Remove result from a UNION index */
 16627  #define SRT_Exists       3  /* Store 1 if the result is not empty */
 16628  #define SRT_Discard      4  /* Do not save the results anywhere */
 16629  #define SRT_Fifo         5  /* Store result as data with an automatic rowid */
 16630  #define SRT_DistFifo     6  /* Like SRT_Fifo, but unique results only */
 16631  #define SRT_Queue        7  /* Store result in an queue */
 16632  #define SRT_DistQueue    8  /* Like SRT_Queue, but unique results only */
 16633  
 16634  /* The ORDER BY clause is ignored for all of the above */
 16635  #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
 16636  
 16637  #define SRT_Output       9  /* Output each row of result */
 16638  #define SRT_Mem         10  /* Store result in a memory cell */
 16639  #define SRT_Set         11  /* Store results as keys in an index */
 16640  #define SRT_EphemTab    12  /* Create transient tab and store like SRT_Table */
 16641  #define SRT_Coroutine   13  /* Generate a single row of result */
 16642  #define SRT_Table       14  /* Store result as data with an automatic rowid */
 16643  
 16644  /*
 16645  ** An instance of this object describes where to put of the results of
 16646  ** a SELECT statement.
 16647  */
 16648  struct SelectDest {
 16649    u8 eDest;            /* How to dispose of the results.  On of SRT_* above. */
 16650    int iSDParm;         /* A parameter used by the eDest disposal method */
 16651    int iSdst;           /* Base register where results are written */
 16652    int nSdst;           /* Number of registers allocated */
 16653    char *zAffSdst;      /* Affinity used when eDest==SRT_Set */
 16654    ExprList *pOrderBy;  /* Key columns for SRT_Queue and SRT_DistQueue */
 16655  };
 16656  
 16657  /*
 16658  ** During code generation of statements that do inserts into AUTOINCREMENT
 16659  ** tables, the following information is attached to the Table.u.autoInc.p
 16660  ** pointer of each autoincrement table to record some side information that
 16661  ** the code generator needs.  We have to keep per-table autoincrement
 16662  ** information in case inserts are done within triggers.  Triggers do not
 16663  ** normally coordinate their activities, but we do need to coordinate the
 16664  ** loading and saving of autoincrement information.
 16665  */
 16666  struct AutoincInfo {
 16667    AutoincInfo *pNext;   /* Next info block in a list of them all */
 16668    Table *pTab;          /* Table this info block refers to */
 16669    int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
 16670    int regCtr;           /* Memory register holding the rowid counter */
 16671  };
 16672  
 16673  /*
 16674  ** Size of the column cache
 16675  */
 16676  #ifndef SQLITE_N_COLCACHE
 16677  # define SQLITE_N_COLCACHE 10
 16678  #endif
 16679  
 16680  /*
 16681  ** At least one instance of the following structure is created for each
 16682  ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
 16683  ** statement. All such objects are stored in the linked list headed at
 16684  ** Parse.pTriggerPrg and deleted once statement compilation has been
 16685  ** completed.
 16686  **
 16687  ** A Vdbe sub-program that implements the body and WHEN clause of trigger
 16688  ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
 16689  ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
 16690  ** The Parse.pTriggerPrg list never contains two entries with the same
 16691  ** values for both pTrigger and orconf.
 16692  **
 16693  ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
 16694  ** accessed (or set to 0 for triggers fired as a result of INSERT
 16695  ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
 16696  ** a mask of new.* columns used by the program.
 16697  */
 16698  struct TriggerPrg {
 16699    Trigger *pTrigger;      /* Trigger this program was coded from */
 16700    TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
 16701    SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
 16702    int orconf;             /* Default ON CONFLICT policy */
 16703    u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
 16704  };
 16705  
 16706  /*
 16707  ** The yDbMask datatype for the bitmask of all attached databases.
 16708  */
 16709  #if SQLITE_MAX_ATTACHED>30
 16710    typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
 16711  # define DbMaskTest(M,I)    (((M)[(I)/8]&(1<<((I)&7)))!=0)
 16712  # define DbMaskZero(M)      memset((M),0,sizeof(M))
 16713  # define DbMaskSet(M,I)     (M)[(I)/8]|=(1<<((I)&7))
 16714  # define DbMaskAllZero(M)   sqlite3DbMaskAllZero(M)
 16715  # define DbMaskNonZero(M)   (sqlite3DbMaskAllZero(M)==0)
 16716  #else
 16717    typedef unsigned int yDbMask;
 16718  # define DbMaskTest(M,I)    (((M)&(((yDbMask)1)<<(I)))!=0)
 16719  # define DbMaskZero(M)      (M)=0
 16720  # define DbMaskSet(M,I)     (M)|=(((yDbMask)1)<<(I))
 16721  # define DbMaskAllZero(M)   (M)==0
 16722  # define DbMaskNonZero(M)   (M)!=0
 16723  #endif
 16724  
 16725  /*
 16726  ** An SQL parser context.  A copy of this structure is passed through
 16727  ** the parser and down into all the parser action routine in order to
 16728  ** carry around information that is global to the entire parse.
 16729  **
 16730  ** The structure is divided into two parts.  When the parser and code
 16731  ** generate call themselves recursively, the first part of the structure
 16732  ** is constant but the second part is reset at the beginning and end of
 16733  ** each recursion.
 16734  **
 16735  ** The nTableLock and aTableLock variables are only used if the shared-cache
 16736  ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
 16737  ** used to store the set of table-locks required by the statement being
 16738  ** compiled. Function sqlite3TableLock() is used to add entries to the
 16739  ** list.
 16740  */
 16741  struct Parse {
 16742    sqlite3 *db;         /* The main database structure */
 16743    char *zErrMsg;       /* An error message */
 16744    Vdbe *pVdbe;         /* An engine for executing database bytecode */
 16745    int rc;              /* Return code from execution */
 16746    u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
 16747    u8 checkSchema;      /* Causes schema cookie check after an error */
 16748    u8 nested;           /* Number of nested calls to the parser/code generator */
 16749    u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
 16750    u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
 16751    u8 mayAbort;         /* True if statement may throw an ABORT exception */
 16752    u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
 16753    u8 okConstFactor;    /* OK to factor out constants */
 16754    u8 disableLookaside; /* Number of times lookaside has been disabled */
 16755    u8 nColCache;        /* Number of entries in aColCache[] */
 16756    int nRangeReg;       /* Size of the temporary register block */
 16757    int iRangeReg;       /* First register in temporary register block */
 16758    int nErr;            /* Number of errors seen */
 16759    int nTab;            /* Number of previously allocated VDBE cursors */
 16760    int nMem;            /* Number of memory cells used so far */
 16761    int nOpAlloc;        /* Number of slots allocated for Vdbe.aOp[] */
 16762    int szOpAlloc;       /* Bytes of memory space allocated for Vdbe.aOp[] */
 16763    int iSelfTab;        /* Table for associated with an index on expr, or negative
 16764                         ** of the base register during check-constraint eval */
 16765    int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
 16766    int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
 16767    int nLabel;          /* Number of labels used */
 16768    int *aLabel;         /* Space to hold the labels */
 16769    ExprList *pConstExpr;/* Constant expressions */
 16770    Token constraintName;/* Name of the constraint currently being parsed */
 16771    yDbMask writeMask;   /* Start a write transaction on these databases */
 16772    yDbMask cookieMask;  /* Bitmask of schema verified databases */
 16773    int regRowid;        /* Register holding rowid of CREATE TABLE entry */
 16774    int regRoot;         /* Register holding root page number for new objects */
 16775    int nMaxArg;         /* Max args passed to user function by sub-program */
 16776  #if SELECTTRACE_ENABLED
 16777    int nSelect;         /* Number of SELECT statements seen */
 16778    int nSelectIndent;   /* How far to indent SELECTTRACE() output */
 16779  #endif
 16780  #ifndef SQLITE_OMIT_SHARED_CACHE
 16781    int nTableLock;        /* Number of locks in aTableLock */
 16782    TableLock *aTableLock; /* Required table locks for shared-cache mode */
 16783  #endif
 16784    AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
 16785    Parse *pToplevel;    /* Parse structure for main program (or NULL) */
 16786    Table *pTriggerTab;  /* Table triggers are being coded for */
 16787    int addrCrTab;       /* Address of OP_CreateBtree opcode on CREATE TABLE */
 16788    u32 nQueryLoop;      /* Est number of iterations of a query (10*log2(N)) */
 16789    u32 oldmask;         /* Mask of old.* columns referenced */
 16790    u32 newmask;         /* Mask of new.* columns referenced */
 16791    u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
 16792    u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
 16793    u8 disableTriggers;  /* True to disable triggers */
 16794  
 16795    /**************************************************************************
 16796    ** Fields above must be initialized to zero.  The fields that follow,
 16797    ** down to the beginning of the recursive section, do not need to be
 16798    ** initialized as they will be set before being used.  The boundary is
 16799    ** determined by offsetof(Parse,aColCache).
 16800    **************************************************************************/
 16801  
 16802    struct yColCache {
 16803      int iTable;           /* Table cursor number */
 16804      i16 iColumn;          /* Table column number */
 16805      u8 tempReg;           /* iReg is a temp register that needs to be freed */
 16806      int iLevel;           /* Nesting level */
 16807      int iReg;             /* Reg with value of this column. 0 means none. */
 16808      int lru;              /* Least recently used entry has the smallest value */
 16809    } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
 16810    int aTempReg[8];        /* Holding area for temporary registers */
 16811    Token sNameToken;       /* Token with unqualified schema object name */
 16812  
 16813    /************************************************************************
 16814    ** Above is constant between recursions.  Below is reset before and after
 16815    ** each recursion.  The boundary between these two regions is determined
 16816    ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
 16817    ** first field in the recursive region.
 16818    ************************************************************************/
 16819  
 16820    Token sLastToken;       /* The last token parsed */
 16821    ynVar nVar;               /* Number of '?' variables seen in the SQL so far */
 16822    u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */
 16823    u8 explain;               /* True if the EXPLAIN flag is found on the query */
 16824  #ifndef SQLITE_OMIT_VIRTUALTABLE
 16825    u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
 16826    int nVtabLock;            /* Number of virtual tables to lock */
 16827  #endif
 16828    int nHeight;              /* Expression tree height of current sub-select */
 16829  #ifndef SQLITE_OMIT_EXPLAIN
 16830    int iSelectId;            /* ID of current select for EXPLAIN output */
 16831    int iNextSelectId;        /* Next available select ID for EXPLAIN output */
 16832  #endif
 16833    VList *pVList;            /* Mapping between variable names and numbers */
 16834    Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
 16835    const char *zTail;        /* All SQL text past the last semicolon parsed */
 16836    Table *pNewTable;         /* A table being constructed by CREATE TABLE */
 16837    Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
 16838    const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
 16839  #ifndef SQLITE_OMIT_VIRTUALTABLE
 16840    Token sArg;               /* Complete text of a module argument */
 16841    Table **apVtabLock;       /* Pointer to virtual tables needing locking */
 16842  #endif
 16843    Table *pZombieTab;        /* List of Table objects to delete after code gen */
 16844    TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
 16845    With *pWith;              /* Current WITH clause, or NULL */
 16846    With *pWithToFree;        /* Free this WITH object at the end of the parse */
 16847  };
 16848  
 16849  /*
 16850  ** Sizes and pointers of various parts of the Parse object.
 16851  */
 16852  #define PARSE_HDR_SZ offsetof(Parse,aColCache) /* Recursive part w/o aColCache*/
 16853  #define PARSE_RECURSE_SZ offsetof(Parse,sLastToken)    /* Recursive part */
 16854  #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
 16855  #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ)  /* Pointer to tail */
 16856  
 16857  /*
 16858  ** Return true if currently inside an sqlite3_declare_vtab() call.
 16859  */
 16860  #ifdef SQLITE_OMIT_VIRTUALTABLE
 16861    #define IN_DECLARE_VTAB 0
 16862  #else
 16863    #define IN_DECLARE_VTAB (pParse->declareVtab)
 16864  #endif
 16865  
 16866  /*
 16867  ** An instance of the following structure can be declared on a stack and used
 16868  ** to save the Parse.zAuthContext value so that it can be restored later.
 16869  */
 16870  struct AuthContext {
 16871    const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
 16872    Parse *pParse;              /* The Parse structure */
 16873  };
 16874  
 16875  /*
 16876  ** Bitfield flags for P5 value in various opcodes.
 16877  **
 16878  ** Value constraints (enforced via assert()):
 16879  **    OPFLAG_LENGTHARG    == SQLITE_FUNC_LENGTH
 16880  **    OPFLAG_TYPEOFARG    == SQLITE_FUNC_TYPEOF
 16881  **    OPFLAG_BULKCSR      == BTREE_BULKLOAD
 16882  **    OPFLAG_SEEKEQ       == BTREE_SEEK_EQ
 16883  **    OPFLAG_FORDELETE    == BTREE_FORDELETE
 16884  **    OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
 16885  **    OPFLAG_AUXDELETE    == BTREE_AUXDELETE
 16886  */
 16887  #define OPFLAG_NCHANGE       0x01    /* OP_Insert: Set to update db->nChange */
 16888                                       /* Also used in P2 (not P5) of OP_Delete */
 16889  #define OPFLAG_EPHEM         0x01    /* OP_Column: Ephemeral output is ok */
 16890  #define OPFLAG_LASTROWID     0x20    /* Set to update db->lastRowid */
 16891  #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
 16892  #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
 16893  #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
 16894  #define OPFLAG_ISNOOP        0x40    /* OP_Delete does pre-update-hook only */
 16895  #define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
 16896  #define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
 16897  #define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
 16898  #define OPFLAG_SEEKEQ        0x02    /* OP_Open** cursor uses EQ seek only */
 16899  #define OPFLAG_FORDELETE     0x08    /* OP_Open should use BTREE_FORDELETE */
 16900  #define OPFLAG_P2ISREG       0x10    /* P2 to OP_Open** is a register number */
 16901  #define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
 16902  #define OPFLAG_SAVEPOSITION  0x02    /* OP_Delete/Insert: save cursor pos */
 16903  #define OPFLAG_AUXDELETE     0x04    /* OP_Delete: index in a DELETE op */
 16904  
 16905  /*
 16906   * Each trigger present in the database schema is stored as an instance of
 16907   * struct Trigger.
 16908   *
 16909   * Pointers to instances of struct Trigger are stored in two ways.
 16910   * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
 16911   *    database). This allows Trigger structures to be retrieved by name.
 16912   * 2. All triggers associated with a single table form a linked list, using the
 16913   *    pNext member of struct Trigger. A pointer to the first element of the
 16914   *    linked list is stored as the "pTrigger" member of the associated
 16915   *    struct Table.
 16916   *
 16917   * The "step_list" member points to the first element of a linked list
 16918   * containing the SQL statements specified as the trigger program.
 16919   */
 16920  struct Trigger {
 16921    char *zName;            /* The name of the trigger                        */
 16922    char *table;            /* The table or view to which the trigger applies */
 16923    u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
 16924    u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
 16925    Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
 16926    IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
 16927                               the <column-list> is stored here */
 16928    Schema *pSchema;        /* Schema containing the trigger */
 16929    Schema *pTabSchema;     /* Schema containing the table */
 16930    TriggerStep *step_list; /* Link list of trigger program steps             */
 16931    Trigger *pNext;         /* Next trigger associated with the table */
 16932  };
 16933  
 16934  /*
 16935  ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
 16936  ** determine which.
 16937  **
 16938  ** If there are multiple triggers, you might of some BEFORE and some AFTER.
 16939  ** In that cases, the constants below can be ORed together.
 16940  */
 16941  #define TRIGGER_BEFORE  1
 16942  #define TRIGGER_AFTER   2
 16943  
 16944  /*
 16945   * An instance of struct TriggerStep is used to store a single SQL statement
 16946   * that is a part of a trigger-program.
 16947   *
 16948   * Instances of struct TriggerStep are stored in a singly linked list (linked
 16949   * using the "pNext" member) referenced by the "step_list" member of the
 16950   * associated struct Trigger instance. The first element of the linked list is
 16951   * the first step of the trigger-program.
 16952   *
 16953   * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
 16954   * "SELECT" statement. The meanings of the other members is determined by the
 16955   * value of "op" as follows:
 16956   *
 16957   * (op == TK_INSERT)
 16958   * orconf    -> stores the ON CONFLICT algorithm
 16959   * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
 16960   *              this stores a pointer to the SELECT statement. Otherwise NULL.
 16961   * zTarget   -> Dequoted name of the table to insert into.
 16962   * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
 16963   *              this stores values to be inserted. Otherwise NULL.
 16964   * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
 16965   *              statement, then this stores the column-names to be
 16966   *              inserted into.
 16967   *
 16968   * (op == TK_DELETE)
 16969   * zTarget   -> Dequoted name of the table to delete from.
 16970   * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
 16971   *              Otherwise NULL.
 16972   *
 16973   * (op == TK_UPDATE)
 16974   * zTarget   -> Dequoted name of the table to update.
 16975   * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
 16976   *              Otherwise NULL.
 16977   * pExprList -> A list of the columns to update and the expressions to update
 16978   *              them to. See sqlite3Update() documentation of "pChanges"
 16979   *              argument.
 16980   *
 16981   */
 16982  struct TriggerStep {
 16983    u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
 16984    u8 orconf;           /* OE_Rollback etc. */
 16985    Trigger *pTrig;      /* The trigger that this step is a part of */
 16986    Select *pSelect;     /* SELECT statement or RHS of INSERT INTO SELECT ... */
 16987    char *zTarget;       /* Target table for DELETE, UPDATE, INSERT */
 16988    Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
 16989    ExprList *pExprList; /* SET clause for UPDATE. */
 16990    IdList *pIdList;     /* Column names for INSERT */
 16991    TriggerStep *pNext;  /* Next in the link-list */
 16992    TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
 16993  };
 16994  
 16995  /*
 16996  ** The following structure contains information used by the sqliteFix...
 16997  ** routines as they walk the parse tree to make database references
 16998  ** explicit.
 16999  */
 17000  typedef struct DbFixer DbFixer;
 17001  struct DbFixer {
 17002    Parse *pParse;      /* The parsing context.  Error messages written here */
 17003    Schema *pSchema;    /* Fix items to this schema */
 17004    int bVarOnly;       /* Check for variable references only */
 17005    const char *zDb;    /* Make sure all objects are contained in this database */
 17006    const char *zType;  /* Type of the container - used for error messages */
 17007    const Token *pName; /* Name of the container - used for error messages */
 17008  };
 17009  
 17010  /*
 17011  ** An objected used to accumulate the text of a string where we
 17012  ** do not necessarily know how big the string will be in the end.
 17013  */
 17014  struct StrAccum {
 17015    sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
 17016    char *zText;         /* The string collected so far */
 17017    u32  nAlloc;         /* Amount of space allocated in zText */
 17018    u32  mxAlloc;        /* Maximum allowed allocation.  0 for no malloc usage */
 17019    u32  nChar;          /* Length of the string so far */
 17020    u8   accError;       /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
 17021    u8   printfFlags;    /* SQLITE_PRINTF flags below */
 17022  };
 17023  #define STRACCUM_NOMEM   1
 17024  #define STRACCUM_TOOBIG  2
 17025  #define SQLITE_PRINTF_INTERNAL 0x01  /* Internal-use-only converters allowed */
 17026  #define SQLITE_PRINTF_SQLFUNC  0x02  /* SQL function arguments to VXPrintf */
 17027  #define SQLITE_PRINTF_MALLOCED 0x04  /* True if xText is allocated space */
 17028  
 17029  #define isMalloced(X)  (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
 17030  
 17031  
 17032  /*
 17033  ** A pointer to this structure is used to communicate information
 17034  ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
 17035  */
 17036  typedef struct {
 17037    sqlite3 *db;        /* The database being initialized */
 17038    char **pzErrMsg;    /* Error message stored here */
 17039    int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
 17040    int rc;             /* Result code stored here */
 17041  } InitData;
 17042  
 17043  /*
 17044  ** Structure containing global configuration data for the SQLite library.
 17045  **
 17046  ** This structure also contains some state information.
 17047  */
 17048  struct Sqlite3Config {
 17049    int bMemstat;                     /* True to enable memory status */
 17050    int bCoreMutex;                   /* True to enable core mutexing */
 17051    int bFullMutex;                   /* True to enable full mutexing */
 17052    int bOpenUri;                     /* True to interpret filenames as URIs */
 17053    int bUseCis;                      /* Use covering indices for full-scans */
 17054    int bSmallMalloc;                 /* Avoid large memory allocations if true */
 17055    int mxStrlen;                     /* Maximum string length */
 17056    int neverCorrupt;                 /* Database is always well-formed */
 17057    int szLookaside;                  /* Default lookaside buffer size */
 17058    int nLookaside;                   /* Default lookaside buffer count */
 17059    int nStmtSpill;                   /* Stmt-journal spill-to-disk threshold */
 17060    sqlite3_mem_methods m;            /* Low-level memory allocation interface */
 17061    sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
 17062    sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
 17063    void *pHeap;                      /* Heap storage space */
 17064    int nHeap;                        /* Size of pHeap[] */
 17065    int mnReq, mxReq;                 /* Min and max heap requests sizes */
 17066    sqlite3_int64 szMmap;             /* mmap() space per open file */
 17067    sqlite3_int64 mxMmap;             /* Maximum value for szMmap */
 17068    void *pPage;                      /* Page cache memory */
 17069    int szPage;                       /* Size of each page in pPage[] */
 17070    int nPage;                        /* Number of pages in pPage[] */
 17071    int mxParserStack;                /* maximum depth of the parser stack */
 17072    int sharedCacheEnabled;           /* true if shared-cache mode enabled */
 17073    u32 szPma;                        /* Maximum Sorter PMA size */
 17074    /* The above might be initialized to non-zero.  The following need to always
 17075    ** initially be zero, however. */
 17076    int isInit;                       /* True after initialization has finished */
 17077    int inProgress;                   /* True while initialization in progress */
 17078    int isMutexInit;                  /* True after mutexes are initialized */
 17079    int isMallocInit;                 /* True after malloc is initialized */
 17080    int isPCacheInit;                 /* True after malloc is initialized */
 17081    int nRefInitMutex;                /* Number of users of pInitMutex */
 17082    sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
 17083    void (*xLog)(void*,int,const char*); /* Function for logging */
 17084    void *pLogArg;                       /* First argument to xLog() */
 17085  #ifdef SQLITE_ENABLE_SQLLOG
 17086    void(*xSqllog)(void*,sqlite3*,const char*, int);
 17087    void *pSqllogArg;
 17088  #endif
 17089  #ifdef SQLITE_VDBE_COVERAGE
 17090    /* The following callback (if not NULL) is invoked on every VDBE branch
 17091    ** operation.  Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
 17092    */
 17093    void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx);  /* Callback */
 17094    void *pVdbeBranchArg;                                     /* 1st argument */
 17095  #endif
 17096  #ifndef SQLITE_UNTESTABLE
 17097    int (*xTestCallback)(int);        /* Invoked by sqlite3FaultSim() */
 17098  #endif
 17099    int bLocaltimeFault;              /* True to fail localtime() calls */
 17100    int iOnceResetThreshold;          /* When to reset OP_Once counters */
 17101  };
 17102  
 17103  /*
 17104  ** This macro is used inside of assert() statements to indicate that
 17105  ** the assert is only valid on a well-formed database.  Instead of:
 17106  **
 17107  **     assert( X );
 17108  **
 17109  ** One writes:
 17110  **
 17111  **     assert( X || CORRUPT_DB );
 17112  **
 17113  ** CORRUPT_DB is true during normal operation.  CORRUPT_DB does not indicate
 17114  ** that the database is definitely corrupt, only that it might be corrupt.
 17115  ** For most test cases, CORRUPT_DB is set to false using a special
 17116  ** sqlite3_test_control().  This enables assert() statements to prove
 17117  ** things that are always true for well-formed databases.
 17118  */
 17119  #define CORRUPT_DB  (sqlite3Config.neverCorrupt==0)
 17120  
 17121  /*
 17122  ** Context pointer passed down through the tree-walk.
 17123  */
 17124  struct Walker {
 17125    Parse *pParse;                            /* Parser context.  */
 17126    int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
 17127    int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
 17128    void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
 17129    int walkerDepth;                          /* Number of subqueries */
 17130    u8 eCode;                                 /* A small processing code */
 17131    union {                                   /* Extra data for callback */
 17132      NameContext *pNC;                         /* Naming context */
 17133      int n;                                    /* A counter */
 17134      int iCur;                                 /* A cursor number */
 17135      SrcList *pSrcList;                        /* FROM clause */
 17136      struct SrcCount *pSrcCount;               /* Counting column references */
 17137      struct CCurHint *pCCurHint;               /* Used by codeCursorHint() */
 17138      int *aiCol;                               /* array of column indexes */
 17139      struct IdxCover *pIdxCover;               /* Check for index coverage */
 17140      struct IdxExprTrans *pIdxTrans;           /* Convert indexed expr to column */
 17141      ExprList *pGroupBy;                       /* GROUP BY clause */
 17142      struct HavingToWhereCtx *pHavingCtx;      /* HAVING to WHERE clause ctx */
 17143    } u;
 17144  };
 17145  
 17146  /* Forward declarations */
 17147  SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
 17148  SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
 17149  SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
 17150  SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
 17151  SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
 17152  SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
 17153  SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker*, Select*);
 17154  SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker*, Select*);
 17155  #ifdef SQLITE_DEBUG
 17156  SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker*, Select*);
 17157  #endif
 17158  
 17159  /*
 17160  ** Return code from the parse-tree walking primitives and their
 17161  ** callbacks.
 17162  */
 17163  #define WRC_Continue    0   /* Continue down into children */
 17164  #define WRC_Prune       1   /* Omit children but continue walking siblings */
 17165  #define WRC_Abort       2   /* Abandon the tree walk */
 17166  
 17167  /*
 17168  ** An instance of this structure represents a set of one or more CTEs
 17169  ** (common table expressions) created by a single WITH clause.
 17170  */
 17171  struct With {
 17172    int nCte;                       /* Number of CTEs in the WITH clause */
 17173    With *pOuter;                   /* Containing WITH clause, or NULL */
 17174    struct Cte {                    /* For each CTE in the WITH clause.... */
 17175      char *zName;                    /* Name of this CTE */
 17176      ExprList *pCols;                /* List of explicit column names, or NULL */
 17177      Select *pSelect;                /* The definition of this CTE */
 17178      const char *zCteErr;            /* Error message for circular references */
 17179    } a[1];
 17180  };
 17181  
 17182  #ifdef SQLITE_DEBUG
 17183  /*
 17184  ** An instance of the TreeView object is used for printing the content of
 17185  ** data structures on sqlite3DebugPrintf() using a tree-like view.
 17186  */
 17187  struct TreeView {
 17188    int iLevel;             /* Which level of the tree we are on */
 17189    u8  bLine[100];         /* Draw vertical in column i if bLine[i] is true */
 17190  };
 17191  #endif /* SQLITE_DEBUG */
 17192  
 17193  /*
 17194  ** Assuming zIn points to the first byte of a UTF-8 character,
 17195  ** advance zIn to point to the first byte of the next UTF-8 character.
 17196  */
 17197  #define SQLITE_SKIP_UTF8(zIn) {                        \
 17198    if( (*(zIn++))>=0xc0 ){                              \
 17199      while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
 17200    }                                                    \
 17201  }
 17202  
 17203  /*
 17204  ** The SQLITE_*_BKPT macros are substitutes for the error codes with
 17205  ** the same name but without the _BKPT suffix.  These macros invoke
 17206  ** routines that report the line-number on which the error originated
 17207  ** using sqlite3_log().  The routines also provide a convenient place
 17208  ** to set a debugger breakpoint.
 17209  */
 17210  SQLITE_PRIVATE int sqlite3CorruptError(int);
 17211  SQLITE_PRIVATE int sqlite3MisuseError(int);
 17212  SQLITE_PRIVATE int sqlite3CantopenError(int);
 17213  #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
 17214  #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
 17215  #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
 17216  #ifdef SQLITE_DEBUG
 17217  SQLITE_PRIVATE   int sqlite3NomemError(int);
 17218  SQLITE_PRIVATE   int sqlite3IoerrnomemError(int);
 17219  SQLITE_PRIVATE   int sqlite3CorruptPgnoError(int,Pgno);
 17220  # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
 17221  # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
 17222  # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))
 17223  #else
 17224  # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
 17225  # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
 17226  # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)
 17227  #endif
 17228  
 17229  /*
 17230  ** FTS3 and FTS4 both require virtual table support
 17231  */
 17232  #if defined(SQLITE_OMIT_VIRTUALTABLE)
 17233  # undef SQLITE_ENABLE_FTS3
 17234  # undef SQLITE_ENABLE_FTS4
 17235  #endif
 17236  
 17237  /*
 17238  ** FTS4 is really an extension for FTS3.  It is enabled using the
 17239  ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also call
 17240  ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
 17241  */
 17242  #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
 17243  # define SQLITE_ENABLE_FTS3 1
 17244  #endif
 17245  
 17246  /*
 17247  ** The ctype.h header is needed for non-ASCII systems.  It is also
 17248  ** needed by FTS3 when FTS3 is included in the amalgamation.
 17249  */
 17250  #if !defined(SQLITE_ASCII) || \
 17251      (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
 17252  # include <ctype.h>
 17253  #endif
 17254  
 17255  /*
 17256  ** The following macros mimic the standard library functions toupper(),
 17257  ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
 17258  ** sqlite versions only work for ASCII characters, regardless of locale.
 17259  */
 17260  #ifdef SQLITE_ASCII
 17261  # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
 17262  # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
 17263  # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
 17264  # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
 17265  # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
 17266  # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
 17267  # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
 17268  # define sqlite3Isquote(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
 17269  #else
 17270  # define sqlite3Toupper(x)   toupper((unsigned char)(x))
 17271  # define sqlite3Isspace(x)   isspace((unsigned char)(x))
 17272  # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
 17273  # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
 17274  # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
 17275  # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
 17276  # define sqlite3Tolower(x)   tolower((unsigned char)(x))
 17277  # define sqlite3Isquote(x)   ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
 17278  #endif
 17279  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
 17280  SQLITE_PRIVATE int sqlite3IsIdChar(u8);
 17281  #endif
 17282  
 17283  /*
 17284  ** Internal function prototypes
 17285  */
 17286  SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
 17287  SQLITE_PRIVATE int sqlite3Strlen30(const char*);
 17288  SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
 17289  #define sqlite3StrNICmp sqlite3_strnicmp
 17290  
 17291  SQLITE_PRIVATE int sqlite3MallocInit(void);
 17292  SQLITE_PRIVATE void sqlite3MallocEnd(void);
 17293  SQLITE_PRIVATE void *sqlite3Malloc(u64);
 17294  SQLITE_PRIVATE void *sqlite3MallocZero(u64);
 17295  SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
 17296  SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
 17297  SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
 17298  SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
 17299  SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
 17300  SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
 17301  SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
 17302  SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
 17303  SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
 17304  SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3*, void*);
 17305  SQLITE_PRIVATE int sqlite3MallocSize(void*);
 17306  SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
 17307  SQLITE_PRIVATE void *sqlite3PageMalloc(int);
 17308  SQLITE_PRIVATE void sqlite3PageFree(void*);
 17309  SQLITE_PRIVATE void sqlite3MemSetDefault(void);
 17310  #ifndef SQLITE_UNTESTABLE
 17311  SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
 17312  #endif
 17313  SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
 17314  
 17315  /*
 17316  ** On systems with ample stack space and that support alloca(), make
 17317  ** use of alloca() to obtain space for large automatic objects.  By default,
 17318  ** obtain space from malloc().
 17319  **
 17320  ** The alloca() routine never returns NULL.  This will cause code paths
 17321  ** that deal with sqlite3StackAlloc() failures to be unreachable.
 17322  */
 17323  #ifdef SQLITE_USE_ALLOCA
 17324  # define sqlite3StackAllocRaw(D,N)   alloca(N)
 17325  # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
 17326  # define sqlite3StackFree(D,P)
 17327  #else
 17328  # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
 17329  # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
 17330  # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
 17331  #endif
 17332  
 17333  /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together.  If they
 17334  ** are, disable MEMSYS3
 17335  */
 17336  #ifdef SQLITE_ENABLE_MEMSYS5
 17337  SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
 17338  #undef SQLITE_ENABLE_MEMSYS3
 17339  #endif
 17340  #ifdef SQLITE_ENABLE_MEMSYS3
 17341  SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
 17342  #endif
 17343  
 17344  
 17345  #ifndef SQLITE_MUTEX_OMIT
 17346  SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
 17347  SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
 17348  SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
 17349  SQLITE_PRIVATE   int sqlite3MutexInit(void);
 17350  SQLITE_PRIVATE   int sqlite3MutexEnd(void);
 17351  #endif
 17352  #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
 17353  SQLITE_PRIVATE   void sqlite3MemoryBarrier(void);
 17354  #else
 17355  # define sqlite3MemoryBarrier()
 17356  #endif
 17357  
 17358  SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
 17359  SQLITE_PRIVATE void sqlite3StatusUp(int, int);
 17360  SQLITE_PRIVATE void sqlite3StatusDown(int, int);
 17361  SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
 17362  SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3*,int*);
 17363  
 17364  /* Access to mutexes used by sqlite3_status() */
 17365  SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
 17366  SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
 17367  
 17368  #ifndef SQLITE_OMIT_FLOATING_POINT
 17369  SQLITE_PRIVATE   int sqlite3IsNaN(double);
 17370  #else
 17371  # define sqlite3IsNaN(X)  0
 17372  #endif
 17373  
 17374  /*
 17375  ** An instance of the following structure holds information about SQL
 17376  ** functions arguments that are the parameters to the printf() function.
 17377  */
 17378  struct PrintfArguments {
 17379    int nArg;                /* Total number of arguments */
 17380    int nUsed;               /* Number of arguments used so far */
 17381    sqlite3_value **apArg;   /* The argument values */
 17382  };
 17383  
 17384  SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, const char*, va_list);
 17385  SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
 17386  SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
 17387  SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
 17388  #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
 17389  SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
 17390  #endif
 17391  #if defined(SQLITE_TEST)
 17392  SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
 17393  #endif
 17394  
 17395  #if defined(SQLITE_DEBUG)
 17396  SQLITE_PRIVATE   void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
 17397  SQLITE_PRIVATE   void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
 17398  SQLITE_PRIVATE   void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
 17399  SQLITE_PRIVATE   void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
 17400  SQLITE_PRIVATE   void sqlite3TreeViewWith(TreeView*, const With*, u8);
 17401  #endif
 17402  
 17403  
 17404  SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
 17405  SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
 17406  SQLITE_PRIVATE void sqlite3Dequote(char*);
 17407  SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
 17408  SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
 17409  SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
 17410  SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
 17411  SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
 17412  SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
 17413  SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
 17414  SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
 17415  SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
 17416  #ifdef SQLITE_DEBUG
 17417  SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
 17418  #endif
 17419  SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
 17420  SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
 17421  SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
 17422  SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
 17423  SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
 17424  SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
 17425  SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
 17426  SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
 17427  SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
 17428  SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
 17429  SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
 17430  SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
 17431  SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
 17432  SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
 17433  SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
 17434  SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
 17435  SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
 17436  SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
 17437  SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
 17438  #ifndef SQLITE_OMIT_VIRTUALTABLE
 17439  SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
 17440  #endif
 17441  SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
 17442  SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
 17443  SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
 17444  SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
 17445  SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
 17446  SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
 17447  SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*);
 17448  SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
 17449  SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
 17450  SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
 17451  SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
 17452  SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
 17453  #if SQLITE_ENABLE_HIDDEN_COLUMNS
 17454  SQLITE_PRIVATE   void sqlite3ColumnPropertiesFromName(Table*, Column*);
 17455  #else
 17456  # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
 17457  #endif
 17458  SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
 17459  SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
 17460  SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
 17461  SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
 17462  SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
 17463  SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
 17464  SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
 17465  SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
 17466                      sqlite3_vfs**,char**,char **);
 17467  SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
 17468  
 17469  #ifdef SQLITE_UNTESTABLE
 17470  # define sqlite3FaultSim(X) SQLITE_OK
 17471  #else
 17472  SQLITE_PRIVATE   int sqlite3FaultSim(int);
 17473  #endif
 17474  
 17475  SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
 17476  SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
 17477  SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
 17478  SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
 17479  SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
 17480  SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
 17481  SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
 17482  #ifndef SQLITE_UNTESTABLE
 17483  SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
 17484  #endif
 17485  
 17486  SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
 17487  SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
 17488  SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
 17489  SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
 17490  SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
 17491  
 17492  SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
 17493  
 17494  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
 17495  SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
 17496  #else
 17497  # define sqlite3ViewGetColumnNames(A,B) 0
 17498  #endif
 17499  
 17500  #if SQLITE_MAX_ATTACHED>30
 17501  SQLITE_PRIVATE   int sqlite3DbMaskAllZero(yDbMask);
 17502  #endif
 17503  SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
 17504  SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
 17505  SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
 17506  #ifndef SQLITE_OMIT_AUTOINCREMENT
 17507  SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
 17508  SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
 17509  #else
 17510  # define sqlite3AutoincrementBegin(X)
 17511  # define sqlite3AutoincrementEnd(X)
 17512  #endif
 17513  SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
 17514  SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
 17515  SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
 17516  SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
 17517  SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
 17518  SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
 17519  SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
 17520                                        Token*, Select*, Expr*, IdList*);
 17521  SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
 17522  SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
 17523  SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
 17524  SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
 17525  SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
 17526  SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
 17527  SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
 17528  SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
 17529  SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
 17530                            Expr*, int, int, u8);
 17531  SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
 17532  SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
 17533  SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
 17534                           Expr*,ExprList*,u32,Expr*,Expr*);
 17535  SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
 17536  SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
 17537  SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
 17538  SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
 17539  #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
 17540  SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
 17541  #endif
 17542  SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
 17543  SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
 17544  SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
 17545  SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
 17546  SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
 17547  SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
 17548  SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
 17549  SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo*);
 17550  SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
 17551  SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
 17552  SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
 17553  SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
 17554  #define ONEPASS_OFF      0        /* Use of ONEPASS not allowed */
 17555  #define ONEPASS_SINGLE   1        /* ONEPASS valid for a single row update */
 17556  #define ONEPASS_MULTI    2        /* ONEPASS is valid for multiple rows */
 17557  SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
 17558  SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
 17559  SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int);
 17560  SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
 17561  SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
 17562  SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
 17563  SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
 17564  SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
 17565  SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
 17566  SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
 17567  SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
 17568  SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
 17569  SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
 17570  SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
 17571  SQLITE_PRIVATE int sqlite3ExprCodeAtInit(Parse*, Expr*, int);
 17572  SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
 17573  SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
 17574  SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
 17575  SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
 17576  #define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */
 17577  #define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */
 17578  #define SQLITE_ECEL_REF      0x04  /* Use ExprList.u.x.iOrderByCol */
 17579  #define SQLITE_ECEL_OMITREF  0x08  /* Omit if ExprList.u.x.iOrderByCol */
 17580  SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
 17581  SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
 17582  SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
 17583  SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
 17584  #define LOCATE_VIEW    0x01
 17585  #define LOCATE_NOERR   0x02
 17586  SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
 17587  SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
 17588  SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
 17589  SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
 17590  SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
 17591  SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*);
 17592  SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int);
 17593  SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
 17594  SQLITE_PRIVATE int sqlite3ExprCompare(Parse*,Expr*, Expr*, int);
 17595  SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*, Expr*, int);
 17596  SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
 17597  SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse*,Expr*, Expr*, int);
 17598  SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
 17599  SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
 17600  SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
 17601  SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
 17602  SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
 17603  #ifndef SQLITE_UNTESTABLE
 17604  SQLITE_PRIVATE void sqlite3PrngSaveState(void);
 17605  SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
 17606  #endif
 17607  SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
 17608  SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
 17609  SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
 17610  SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
 17611  SQLITE_PRIVATE void sqlite3EndTransaction(Parse*,int);
 17612  SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
 17613  SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
 17614  SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
 17615  SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
 17616  SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
 17617  SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
 17618  SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
 17619  SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
 17620  #ifdef SQLITE_ENABLE_CURSOR_HINTS
 17621  SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
 17622  #endif
 17623  SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
 17624  SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
 17625  SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
 17626  SQLITE_PRIVATE int sqlite3IsRowid(const char*);
 17627  SQLITE_PRIVATE void sqlite3GenerateRowDelete(
 17628      Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
 17629  SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
 17630  SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
 17631  SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
 17632  SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
 17633                                       u8,u8,int,int*,int*);
 17634  #ifdef SQLITE_ENABLE_NULL_TRIM
 17635  SQLITE_PRIVATE   void sqlite3SetMakeRecordP5(Vdbe*,Table*);
 17636  #else
 17637  # define sqlite3SetMakeRecordP5(A,B)
 17638  #endif
 17639  SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
 17640  SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
 17641  SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
 17642  SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
 17643  SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
 17644  SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
 17645  SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
 17646  SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
 17647  SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
 17648  SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
 17649  SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
 17650  SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
 17651  SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
 17652  #if SELECTTRACE_ENABLED
 17653  SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
 17654  #else
 17655  # define sqlite3SelectSetName(A,B)
 17656  #endif
 17657  SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
 17658  SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
 17659  SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
 17660  SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
 17661  SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
 17662  SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
 17663  SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
 17664  SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
 17665  
 17666  #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
 17667  SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
 17668  #endif
 17669  
 17670  #ifndef SQLITE_OMIT_TRIGGER
 17671  SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
 17672                             Expr*,int, int);
 17673  SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
 17674  SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
 17675  SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
 17676  SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
 17677  SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
 17678  SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
 17679                              int, int, int);
 17680  SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
 17681    void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
 17682  SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
 17683  SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
 17684  SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
 17685                                          Select*,u8);
 17686  SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
 17687  SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
 17688  SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
 17689  SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
 17690  SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
 17691  # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
 17692  # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
 17693  #else
 17694  # define sqlite3TriggersExist(B,C,D,E,F) 0
 17695  # define sqlite3DeleteTrigger(A,B)
 17696  # define sqlite3DropTriggerPtr(A,B)
 17697  # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
 17698  # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
 17699  # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
 17700  # define sqlite3TriggerList(X, Y) 0
 17701  # define sqlite3ParseToplevel(p) p
 17702  # define sqlite3IsToplevel(p) 1
 17703  # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
 17704  #endif
 17705  
 17706  SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
 17707  SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
 17708  SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
 17709  #ifndef SQLITE_OMIT_AUTHORIZATION
 17710  SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
 17711  SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
 17712  SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
 17713  SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
 17714  SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
 17715  #else
 17716  # define sqlite3AuthRead(a,b,c,d)
 17717  # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
 17718  # define sqlite3AuthContextPush(a,b,c)
 17719  # define sqlite3AuthContextPop(a)  ((void)(a))
 17720  #endif
 17721  SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
 17722  SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
 17723  SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
 17724  SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
 17725  SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
 17726  SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
 17727  SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
 17728  SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
 17729  SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
 17730  SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
 17731  SQLITE_PRIVATE int sqlite3Atoi(const char*);
 17732  #ifndef SQLITE_OMIT_UTF16
 17733  SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
 17734  #endif
 17735  SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
 17736  SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
 17737  SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
 17738  SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
 17739  #ifndef SQLITE_OMIT_VIRTUALTABLE
 17740  SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
 17741  #endif
 17742  #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
 17743      defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
 17744      defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
 17745  SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
 17746  #endif
 17747  SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
 17748  SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);
 17749  SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);
 17750  
 17751  /*
 17752  ** Routines to read and write variable-length integers.  These used to
 17753  ** be defined locally, but now we use the varint routines in the util.c
 17754  ** file.
 17755  */
 17756  SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
 17757  SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
 17758  SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
 17759  SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
 17760  
 17761  /*
 17762  ** The common case is for a varint to be a single byte.  They following
 17763  ** macros handle the common case without a procedure call, but then call
 17764  ** the procedure for larger varints.
 17765  */
 17766  #define getVarint32(A,B)  \
 17767    (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
 17768  #define putVarint32(A,B)  \
 17769    (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
 17770    sqlite3PutVarint((A),(B)))
 17771  #define getVarint    sqlite3GetVarint
 17772  #define putVarint    sqlite3PutVarint
 17773  
 17774  
 17775  SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
 17776  SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
 17777  SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
 17778  SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
 17779  SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int);
 17780  SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
 17781  SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
 17782  SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
 17783  SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
 17784  SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
 17785  SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
 17786  SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
 17787  SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
 17788  SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
 17789  
 17790  #if defined(SQLITE_NEED_ERR_NAME)
 17791  SQLITE_PRIVATE const char *sqlite3ErrName(int);
 17792  #endif
 17793  
 17794  SQLITE_PRIVATE const char *sqlite3ErrStr(int);
 17795  SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
 17796  SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
 17797  SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
 17798  SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
 17799  SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr);
 17800  SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,Expr*,Expr*);
 17801  SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
 17802  SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
 17803  SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
 17804  SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
 17805  SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
 17806  SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
 17807  SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
 17808  SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
 17809  SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
 17810  SQLITE_PRIVATE int sqlite3AbsInt32(int);
 17811  #ifdef SQLITE_ENABLE_8_3_NAMES
 17812  SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
 17813  #else
 17814  # define sqlite3FileSuffix3(X,Y)
 17815  #endif
 17816  SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
 17817  
 17818  SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
 17819  SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
 17820  SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
 17821                          void(*)(void*));
 17822  SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
 17823  SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
 17824  SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
 17825  #ifndef SQLITE_OMIT_UTF16
 17826  SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
 17827  #endif
 17828  SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
 17829  SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
 17830  #ifndef SQLITE_AMALGAMATION
 17831  SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
 17832  SQLITE_PRIVATE const char sqlite3StrBINARY[];
 17833  SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
 17834  SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
 17835  SQLITE_PRIVATE const Token sqlite3IntTokens[];
 17836  SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
 17837  SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
 17838  #ifndef SQLITE_OMIT_WSD
 17839  SQLITE_PRIVATE int sqlite3PendingByte;
 17840  #endif
 17841  #endif
 17842  SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
 17843  SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
 17844  SQLITE_PRIVATE void sqlite3AlterFunctions(void);
 17845  SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
 17846  SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
 17847  SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
 17848  SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
 17849  SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr *, int, int);
 17850  SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
 17851  SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
 17852  SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
 17853  SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
 17854  SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
 17855  SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
 17856  SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
 17857  SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
 17858  SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
 17859  SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
 17860  SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
 17861  SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
 17862  SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
 17863  SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
 17864  SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
 17865  SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
 17866  SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
 17867  SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
 17868  SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
 17869  SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
 17870  SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
 17871  SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
 17872  SQLITE_PRIVATE void sqlite3SchemaClear(void *);
 17873  SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
 17874  SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
 17875  SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
 17876  SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
 17877  SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
 17878  SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
 17879  #ifdef SQLITE_DEBUG
 17880  SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
 17881  #endif
 17882  SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
 17883    void (*)(sqlite3_context*,int,sqlite3_value **),
 17884    void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
 17885    FuncDestructor *pDestructor
 17886  );
 17887  SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
 17888  SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
 17889  SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
 17890  SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
 17891  
 17892  SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
 17893  SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
 17894  SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
 17895  SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
 17896  SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
 17897  SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
 17898  SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
 17899  SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
 17900  
 17901  SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
 17902  SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
 17903  
 17904  #ifndef SQLITE_OMIT_SUBQUERY
 17905  SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);
 17906  #else
 17907  # define sqlite3ExprCheckIN(x,y) SQLITE_OK
 17908  #endif
 17909  
 17910  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 17911  SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
 17912  SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
 17913      Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
 17914  SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
 17915  SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
 17916  SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
 17917  SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
 17918  #endif
 17919  
 17920  /*
 17921  ** The interface to the LEMON-generated parser
 17922  */
 17923  #ifndef SQLITE_AMALGAMATION
 17924  SQLITE_PRIVATE   void *sqlite3ParserAlloc(void*(*)(u64));
 17925  SQLITE_PRIVATE   void sqlite3ParserFree(void*, void(*)(void*));
 17926  #endif
 17927  SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
 17928  #ifdef YYTRACKMAXSTACKDEPTH
 17929  SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
 17930  #endif
 17931  
 17932  SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
 17933  #ifndef SQLITE_OMIT_LOAD_EXTENSION
 17934  SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
 17935  #else
 17936  # define sqlite3CloseExtensions(X)
 17937  #endif
 17938  
 17939  #ifndef SQLITE_OMIT_SHARED_CACHE
 17940  SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
 17941  #else
 17942    #define sqlite3TableLock(v,w,x,y,z)
 17943  #endif
 17944  
 17945  #ifdef SQLITE_TEST
 17946  SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
 17947  #endif
 17948  
 17949  #ifdef SQLITE_OMIT_VIRTUALTABLE
 17950  #  define sqlite3VtabClear(Y)
 17951  #  define sqlite3VtabSync(X,Y) SQLITE_OK
 17952  #  define sqlite3VtabRollback(X)
 17953  #  define sqlite3VtabCommit(X)
 17954  #  define sqlite3VtabInSync(db) 0
 17955  #  define sqlite3VtabLock(X)
 17956  #  define sqlite3VtabUnlock(X)
 17957  #  define sqlite3VtabUnlockList(X)
 17958  #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
 17959  #  define sqlite3GetVTable(X,Y)  ((VTable*)0)
 17960  #else
 17961  SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
 17962  SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
 17963  SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, Vdbe*);
 17964  SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
 17965  SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
 17966  SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
 17967  SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
 17968  SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
 17969  SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
 17970  SQLITE_PRIVATE    void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
 17971  SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
 17972  SQLITE_PRIVATE    Module *sqlite3VtabCreateModule(
 17973       sqlite3*,
 17974       const char*,
 17975       const sqlite3_module*,
 17976       void*,
 17977       void(*)(void*)
 17978     );
 17979  #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
 17980  #endif
 17981  SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
 17982  SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
 17983  SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
 17984  SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
 17985  SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
 17986  SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
 17987  SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
 17988  SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
 17989  SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
 17990  SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
 17991  SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
 17992  SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
 17993  SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
 17994  SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
 17995  SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
 17996  SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
 17997  SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
 17998  SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
 17999  SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
 18000  SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
 18001  SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
 18002  SQLITE_PRIVATE const char *sqlite3JournalModename(int);
 18003  #ifndef SQLITE_OMIT_WAL
 18004  SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
 18005  SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
 18006  #endif
 18007  #ifndef SQLITE_OMIT_CTE
 18008  SQLITE_PRIVATE   With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
 18009  SQLITE_PRIVATE   void sqlite3WithDelete(sqlite3*,With*);
 18010  SQLITE_PRIVATE   void sqlite3WithPush(Parse*, With*, u8);
 18011  #else
 18012  #define sqlite3WithPush(x,y,z)
 18013  #define sqlite3WithDelete(x,y)
 18014  #endif
 18015  
 18016  /* Declarations for functions in fkey.c. All of these are replaced by
 18017  ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
 18018  ** key functionality is available. If OMIT_TRIGGER is defined but
 18019  ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
 18020  ** this case foreign keys are parsed, but no other functionality is
 18021  ** provided (enforcement of FK constraints requires the triggers sub-system).
 18022  */
 18023  #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
 18024  SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
 18025  SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
 18026  SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
 18027  SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
 18028  SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
 18029  SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
 18030  #else
 18031    #define sqlite3FkActions(a,b,c,d,e,f)
 18032    #define sqlite3FkCheck(a,b,c,d,e,f)
 18033    #define sqlite3FkDropTable(a,b,c)
 18034    #define sqlite3FkOldmask(a,b)         0
 18035    #define sqlite3FkRequired(a,b,c,d)    0
 18036    #define sqlite3FkReferences(a)        0
 18037  #endif
 18038  #ifndef SQLITE_OMIT_FOREIGN_KEY
 18039  SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
 18040  SQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
 18041  #else
 18042    #define sqlite3FkDelete(a,b)
 18043    #define sqlite3FkLocateIndex(a,b,c,d,e)
 18044  #endif
 18045  
 18046  
 18047  /*
 18048  ** Available fault injectors.  Should be numbered beginning with 0.
 18049  */
 18050  #define SQLITE_FAULTINJECTOR_MALLOC     0
 18051  #define SQLITE_FAULTINJECTOR_COUNT      1
 18052  
 18053  /*
 18054  ** The interface to the code in fault.c used for identifying "benign"
 18055  ** malloc failures. This is only present if SQLITE_UNTESTABLE
 18056  ** is not defined.
 18057  */
 18058  #ifndef SQLITE_UNTESTABLE
 18059  SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
 18060  SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
 18061  #else
 18062    #define sqlite3BeginBenignMalloc()
 18063    #define sqlite3EndBenignMalloc()
 18064  #endif
 18065  
 18066  /*
 18067  ** Allowed return values from sqlite3FindInIndex()
 18068  */
 18069  #define IN_INDEX_ROWID        1   /* Search the rowid of the table */
 18070  #define IN_INDEX_EPH          2   /* Search an ephemeral b-tree */
 18071  #define IN_INDEX_INDEX_ASC    3   /* Existing index ASCENDING */
 18072  #define IN_INDEX_INDEX_DESC   4   /* Existing index DESCENDING */
 18073  #define IN_INDEX_NOOP         5   /* No table available. Use comparisons */
 18074  /*
 18075  ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
 18076  */
 18077  #define IN_INDEX_NOOP_OK     0x0001  /* OK to return IN_INDEX_NOOP */
 18078  #define IN_INDEX_MEMBERSHIP  0x0002  /* IN operator used for membership test */
 18079  #define IN_INDEX_LOOP        0x0004  /* IN operator used as a loop */
 18080  SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*);
 18081  
 18082  SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
 18083  SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
 18084  #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
 18085   || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
 18086  SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
 18087  #endif
 18088  
 18089  SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
 18090  SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
 18091  
 18092  SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
 18093  #if SQLITE_MAX_EXPR_DEPTH>0
 18094  SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
 18095  SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
 18096  #else
 18097    #define sqlite3SelectExprHeight(x) 0
 18098    #define sqlite3ExprCheckHeight(x,y)
 18099  #endif
 18100  
 18101  SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
 18102  SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
 18103  
 18104  #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
 18105  SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
 18106  SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
 18107  SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
 18108  #else
 18109    #define sqlite3ConnectionBlocked(x,y)
 18110    #define sqlite3ConnectionUnlocked(x)
 18111    #define sqlite3ConnectionClosed(x)
 18112  #endif
 18113  
 18114  #ifdef SQLITE_DEBUG
 18115  SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
 18116  #endif
 18117  
 18118  /*
 18119  ** If the SQLITE_ENABLE IOTRACE exists then the global variable
 18120  ** sqlite3IoTrace is a pointer to a printf-like routine used to
 18121  ** print I/O tracing messages.
 18122  */
 18123  #ifdef SQLITE_ENABLE_IOTRACE
 18124  # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
 18125  SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
 18126  SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
 18127  #else
 18128  # define IOTRACE(A)
 18129  # define sqlite3VdbeIOTraceSql(X)
 18130  #endif
 18131  
 18132  /*
 18133  ** These routines are available for the mem2.c debugging memory allocator
 18134  ** only.  They are used to verify that different "types" of memory
 18135  ** allocations are properly tracked by the system.
 18136  **
 18137  ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
 18138  ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
 18139  ** a single bit set.
 18140  **
 18141  ** sqlite3MemdebugHasType() returns true if any of the bits in its second
 18142  ** argument match the type set by the previous sqlite3MemdebugSetType().
 18143  ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
 18144  **
 18145  ** sqlite3MemdebugNoType() returns true if none of the bits in its second
 18146  ** argument match the type set by the previous sqlite3MemdebugSetType().
 18147  **
 18148  ** Perhaps the most important point is the difference between MEMTYPE_HEAP
 18149  ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
 18150  ** it might have been allocated by lookaside, except the allocation was
 18151  ** too large or lookaside was already full.  It is important to verify
 18152  ** that allocations that might have been satisfied by lookaside are not
 18153  ** passed back to non-lookaside free() routines.  Asserts such as the
 18154  ** example above are placed on the non-lookaside free() routines to verify
 18155  ** this constraint.
 18156  **
 18157  ** All of this is no-op for a production build.  It only comes into
 18158  ** play when the SQLITE_MEMDEBUG compile-time option is used.
 18159  */
 18160  #ifdef SQLITE_MEMDEBUG
 18161  SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
 18162  SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
 18163  SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
 18164  #else
 18165  # define sqlite3MemdebugSetType(X,Y)  /* no-op */
 18166  # define sqlite3MemdebugHasType(X,Y)  1
 18167  # define sqlite3MemdebugNoType(X,Y)   1
 18168  #endif
 18169  #define MEMTYPE_HEAP       0x01  /* General heap allocations */
 18170  #define MEMTYPE_LOOKASIDE  0x02  /* Heap that might have been lookaside */
 18171  #define MEMTYPE_PCACHE     0x04  /* Page cache allocations */
 18172  
 18173  /*
 18174  ** Threading interface
 18175  */
 18176  #if SQLITE_MAX_WORKER_THREADS>0
 18177  SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
 18178  SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
 18179  #endif
 18180  
 18181  #if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)
 18182  SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3*);
 18183  #endif
 18184  #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
 18185  SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
 18186  #endif
 18187  
 18188  SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr);
 18189  SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr);
 18190  SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);
 18191  SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int);
 18192  SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);
 18193  
 18194  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
 18195  SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt);
 18196  #endif
 18197  
 18198  #endif /* SQLITEINT_H */
 18199  
 18200  /************** End of sqliteInt.h *******************************************/
 18201  /************** Begin file global.c ******************************************/
 18202  /*
 18203  ** 2008 June 13
 18204  **
 18205  ** The author disclaims copyright to this source code.  In place of
 18206  ** a legal notice, here is a blessing:
 18207  **
 18208  **    May you do good and not evil.
 18209  **    May you find forgiveness for yourself and forgive others.
 18210  **    May you share freely, never taking more than you give.
 18211  **
 18212  *************************************************************************
 18213  **
 18214  ** This file contains definitions of global variables and constants.
 18215  */
 18216  /* #include "sqliteInt.h" */
 18217  
 18218  /* An array to map all upper-case characters into their corresponding
 18219  ** lower-case character. 
 18220  **
 18221  ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
 18222  ** handle case conversions for the UTF character set since the tables
 18223  ** involved are nearly as big or bigger than SQLite itself.
 18224  */
 18225  SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
 18226  #ifdef SQLITE_ASCII
 18227        0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
 18228       18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
 18229       36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
 18230       54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
 18231      104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
 18232      122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
 18233      108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
 18234      126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
 18235      144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
 18236      162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
 18237      180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
 18238      198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
 18239      216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
 18240      234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
 18241      252,253,254,255
 18242  #endif
 18243  #ifdef SQLITE_EBCDIC
 18244        0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
 18245       16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
 18246       32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
 18247       48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
 18248       64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
 18249       80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
 18250       96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
 18251      112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
 18252      128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
 18253      144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
 18254      160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
 18255      176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
 18256      192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
 18257      208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
 18258      224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
 18259      240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
 18260  #endif
 18261  };
 18262  
 18263  /*
 18264  ** The following 256 byte lookup table is used to support SQLites built-in
 18265  ** equivalents to the following standard library functions:
 18266  **
 18267  **   isspace()                        0x01
 18268  **   isalpha()                        0x02
 18269  **   isdigit()                        0x04
 18270  **   isalnum()                        0x06
 18271  **   isxdigit()                       0x08
 18272  **   toupper()                        0x20
 18273  **   SQLite identifier character      0x40
 18274  **   Quote character                  0x80
 18275  **
 18276  ** Bit 0x20 is set if the mapped character requires translation to upper
 18277  ** case. i.e. if the character is a lower-case ASCII character.
 18278  ** If x is a lower-case ASCII character, then its upper-case equivalent
 18279  ** is (x - 0x20). Therefore toupper() can be implemented as:
 18280  **
 18281  **   (x & ~(map[x]&0x20))
 18282  **
 18283  ** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
 18284  ** array. tolower() is used more often than toupper() by SQLite.
 18285  **
 18286  ** Bit 0x40 is set if the character is non-alphanumeric and can be used in an 
 18287  ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
 18288  ** non-ASCII UTF character. Hence the test for whether or not a character is
 18289  ** part of an identifier is 0x46.
 18290  */
 18291  #ifdef SQLITE_ASCII
 18292  SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
 18293    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
 18294    0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
 18295    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
 18296    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
 18297    0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80,  /* 20..27     !"#$%&' */
 18298    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
 18299    0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
 18300    0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
 18301  
 18302    0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
 18303    0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
 18304    0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
 18305    0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
 18306    0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
 18307    0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
 18308    0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
 18309    0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
 18310  
 18311    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
 18312    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
 18313    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
 18314    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
 18315    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
 18316    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
 18317    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
 18318    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
 18319  
 18320    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
 18321    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
 18322    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
 18323    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
 18324    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
 18325    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
 18326    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
 18327    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
 18328  };
 18329  #endif
 18330  
 18331  /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
 18332  ** compatibility for legacy applications, the URI filename capability is
 18333  ** disabled by default.
 18334  **
 18335  ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
 18336  ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
 18337  **
 18338  ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
 18339  ** disabled. The default value may be changed by compiling with the
 18340  ** SQLITE_USE_URI symbol defined.
 18341  **
 18342  ** URI filenames are enabled by default if SQLITE_HAS_CODEC is
 18343  ** enabled.
 18344  */
 18345  #ifndef SQLITE_USE_URI
 18346  # ifdef SQLITE_HAS_CODEC
 18347  #  define SQLITE_USE_URI 1
 18348  # else
 18349  #  define SQLITE_USE_URI 0
 18350  # endif
 18351  #endif
 18352  
 18353  /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
 18354  ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
 18355  ** that compile-time option is omitted.
 18356  */
 18357  #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
 18358  # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
 18359  #endif
 18360  
 18361  /* The minimum PMA size is set to this value multiplied by the database
 18362  ** page size in bytes.
 18363  */
 18364  #ifndef SQLITE_SORTER_PMASZ
 18365  # define SQLITE_SORTER_PMASZ 250
 18366  #endif
 18367  
 18368  /* Statement journals spill to disk when their size exceeds the following
 18369  ** threshold (in bytes). 0 means that statement journals are created and
 18370  ** written to disk immediately (the default behavior for SQLite versions
 18371  ** before 3.12.0).  -1 means always keep the entire statement journal in
 18372  ** memory.  (The statement journal is also always held entirely in memory
 18373  ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
 18374  ** setting.)
 18375  */
 18376  #ifndef SQLITE_STMTJRNL_SPILL 
 18377  # define SQLITE_STMTJRNL_SPILL (64*1024)
 18378  #endif
 18379  
 18380  /*
 18381  ** The default lookaside-configuration, the format "SZ,N".  SZ is the
 18382  ** number of bytes in each lookaside slot (should be a multiple of 8)
 18383  ** and N is the number of slots.  The lookaside-configuration can be
 18384  ** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
 18385  ** or at run-time for an individual database connection using
 18386  ** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);
 18387  */
 18388  #ifndef SQLITE_DEFAULT_LOOKASIDE
 18389  # define SQLITE_DEFAULT_LOOKASIDE 1200,100
 18390  #endif
 18391  
 18392  
 18393  /*
 18394  ** The following singleton contains the global configuration for
 18395  ** the SQLite library.
 18396  */
 18397  SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
 18398     SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
 18399     1,                         /* bCoreMutex */
 18400     SQLITE_THREADSAFE==1,      /* bFullMutex */
 18401     SQLITE_USE_URI,            /* bOpenUri */
 18402     SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
 18403     0,                         /* bSmallMalloc */
 18404     0x7ffffffe,                /* mxStrlen */
 18405     0,                         /* neverCorrupt */
 18406     SQLITE_DEFAULT_LOOKASIDE,  /* szLookaside, nLookaside */
 18407     SQLITE_STMTJRNL_SPILL,     /* nStmtSpill */
 18408     {0,0,0,0,0,0,0,0},         /* m */
 18409     {0,0,0,0,0,0,0,0,0},       /* mutex */
 18410     {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
 18411     (void*)0,                  /* pHeap */
 18412     0,                         /* nHeap */
 18413     0, 0,                      /* mnHeap, mxHeap */
 18414     SQLITE_DEFAULT_MMAP_SIZE,  /* szMmap */
 18415     SQLITE_MAX_MMAP_SIZE,      /* mxMmap */
 18416     (void*)0,                  /* pPage */
 18417     0,                         /* szPage */
 18418     SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
 18419     0,                         /* mxParserStack */
 18420     0,                         /* sharedCacheEnabled */
 18421     SQLITE_SORTER_PMASZ,       /* szPma */
 18422     /* All the rest should always be initialized to zero */
 18423     0,                         /* isInit */
 18424     0,                         /* inProgress */
 18425     0,                         /* isMutexInit */
 18426     0,                         /* isMallocInit */
 18427     0,                         /* isPCacheInit */
 18428     0,                         /* nRefInitMutex */
 18429     0,                         /* pInitMutex */
 18430     0,                         /* xLog */
 18431     0,                         /* pLogArg */
 18432  #ifdef SQLITE_ENABLE_SQLLOG
 18433     0,                         /* xSqllog */
 18434     0,                         /* pSqllogArg */
 18435  #endif
 18436  #ifdef SQLITE_VDBE_COVERAGE
 18437     0,                         /* xVdbeBranch */
 18438     0,                         /* pVbeBranchArg */
 18439  #endif
 18440  #ifndef SQLITE_UNTESTABLE
 18441     0,                         /* xTestCallback */
 18442  #endif
 18443     0,                         /* bLocaltimeFault */
 18444     0x7ffffffe                 /* iOnceResetThreshold */
 18445  };
 18446  
 18447  /*
 18448  ** Hash table for global functions - functions common to all
 18449  ** database connections.  After initialization, this table is
 18450  ** read-only.
 18451  */
 18452  SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
 18453  
 18454  /*
 18455  ** Constant tokens for values 0 and 1.
 18456  */
 18457  SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
 18458     { "0", 1 },
 18459     { "1", 1 }
 18460  };
 18461  
 18462  
 18463  /*
 18464  ** The value of the "pending" byte must be 0x40000000 (1 byte past the
 18465  ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
 18466  ** the database page that contains the pending byte.  It never attempts
 18467  ** to read or write that page.  The pending byte page is set aside
 18468  ** for use by the VFS layers as space for managing file locks.
 18469  **
 18470  ** During testing, it is often desirable to move the pending byte to
 18471  ** a different position in the file.  This allows code that has to
 18472  ** deal with the pending byte to run on files that are much smaller
 18473  ** than 1 GiB.  The sqlite3_test_control() interface can be used to
 18474  ** move the pending byte.
 18475  **
 18476  ** IMPORTANT:  Changing the pending byte to any value other than
 18477  ** 0x40000000 results in an incompatible database file format!
 18478  ** Changing the pending byte during operation will result in undefined
 18479  ** and incorrect behavior.
 18480  */
 18481  #ifndef SQLITE_OMIT_WSD
 18482  SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
 18483  #endif
 18484  
 18485  /* #include "opcodes.h" */
 18486  /*
 18487  ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
 18488  ** created by mkopcodeh.awk during compilation.  Data is obtained
 18489  ** from the comments following the "case OP_xxxx:" statements in
 18490  ** the vdbe.c file.  
 18491  */
 18492  SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
 18493  
 18494  /*
 18495  ** Name of the default collating sequence
 18496  */
 18497  SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
 18498  
 18499  /************** End of global.c **********************************************/
 18500  /************** Begin file status.c ******************************************/
 18501  /*
 18502  ** 2008 June 18
 18503  **
 18504  ** The author disclaims copyright to this source code.  In place of
 18505  ** a legal notice, here is a blessing:
 18506  **
 18507  **    May you do good and not evil.
 18508  **    May you find forgiveness for yourself and forgive others.
 18509  **    May you share freely, never taking more than you give.
 18510  **
 18511  *************************************************************************
 18512  **
 18513  ** This module implements the sqlite3_status() interface and related
 18514  ** functionality.
 18515  */
 18516  /* #include "sqliteInt.h" */
 18517  /************** Include vdbeInt.h in the middle of status.c ******************/
 18518  /************** Begin file vdbeInt.h *****************************************/
 18519  /*
 18520  ** 2003 September 6
 18521  **
 18522  ** The author disclaims copyright to this source code.  In place of
 18523  ** a legal notice, here is a blessing:
 18524  **
 18525  **    May you do good and not evil.
 18526  **    May you find forgiveness for yourself and forgive others.
 18527  **    May you share freely, never taking more than you give.
 18528  **
 18529  *************************************************************************
 18530  ** This is the header file for information that is private to the
 18531  ** VDBE.  This information used to all be at the top of the single
 18532  ** source code file "vdbe.c".  When that file became too big (over
 18533  ** 6000 lines long) it was split up into several smaller files and
 18534  ** this header information was factored out.
 18535  */
 18536  #ifndef SQLITE_VDBEINT_H
 18537  #define SQLITE_VDBEINT_H
 18538  
 18539  /*
 18540  ** The maximum number of times that a statement will try to reparse
 18541  ** itself before giving up and returning SQLITE_SCHEMA.
 18542  */
 18543  #ifndef SQLITE_MAX_SCHEMA_RETRY
 18544  # define SQLITE_MAX_SCHEMA_RETRY 50
 18545  #endif
 18546  
 18547  /*
 18548  ** VDBE_DISPLAY_P4 is true or false depending on whether or not the
 18549  ** "explain" P4 display logic is enabled.
 18550  */
 18551  #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
 18552       || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
 18553  # define VDBE_DISPLAY_P4 1
 18554  #else
 18555  # define VDBE_DISPLAY_P4 0
 18556  #endif
 18557  
 18558  /*
 18559  ** SQL is translated into a sequence of instructions to be
 18560  ** executed by a virtual machine.  Each instruction is an instance
 18561  ** of the following structure.
 18562  */
 18563  typedef struct VdbeOp Op;
 18564  
 18565  /*
 18566  ** Boolean values
 18567  */
 18568  typedef unsigned Bool;
 18569  
 18570  /* Opaque type used by code in vdbesort.c */
 18571  typedef struct VdbeSorter VdbeSorter;
 18572  
 18573  /* Elements of the linked list at Vdbe.pAuxData */
 18574  typedef struct AuxData AuxData;
 18575  
 18576  /* Types of VDBE cursors */
 18577  #define CURTYPE_BTREE       0
 18578  #define CURTYPE_SORTER      1
 18579  #define CURTYPE_VTAB        2
 18580  #define CURTYPE_PSEUDO      3
 18581  
 18582  /*
 18583  ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
 18584  **
 18585  **      * A b-tree cursor
 18586  **          -  In the main database or in an ephemeral database
 18587  **          -  On either an index or a table
 18588  **      * A sorter
 18589  **      * A virtual table
 18590  **      * A one-row "pseudotable" stored in a single register
 18591  */
 18592  typedef struct VdbeCursor VdbeCursor;
 18593  struct VdbeCursor {
 18594    u8 eCurType;            /* One of the CURTYPE_* values above */
 18595    i8 iDb;                 /* Index of cursor database in db->aDb[] (or -1) */
 18596    u8 nullRow;             /* True if pointing to a row with no data */
 18597    u8 deferredMoveto;      /* A call to sqlite3BtreeMoveto() is needed */
 18598    u8 isTable;             /* True for rowid tables.  False for indexes */
 18599  #ifdef SQLITE_DEBUG
 18600    u8 seekOp;              /* Most recent seek operation on this cursor */
 18601    u8 wrFlag;              /* The wrFlag argument to sqlite3BtreeCursor() */
 18602  #endif
 18603    Bool isEphemeral:1;     /* True for an ephemeral table */
 18604    Bool useRandomRowid:1;  /* Generate new record numbers semi-randomly */
 18605    Bool isOrdered:1;       /* True if the table is not BTREE_UNORDERED */
 18606    Btree *pBtx;            /* Separate file holding temporary table */
 18607    i64 seqCount;           /* Sequence counter */
 18608    int *aAltMap;           /* Mapping from table to index column numbers */
 18609  
 18610    /* Cached OP_Column parse information is only valid if cacheStatus matches
 18611    ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
 18612    ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that
 18613    ** the cache is out of date. */
 18614    u32 cacheStatus;        /* Cache is valid if this matches Vdbe.cacheCtr */
 18615    int seekResult;         /* Result of previous sqlite3BtreeMoveto() or 0
 18616                            ** if there have been no prior seeks on the cursor. */
 18617    /* seekResult does not distinguish between "no seeks have ever occurred
 18618    ** on this cursor" and "the most recent seek was an exact match".
 18619    ** For CURTYPE_PSEUDO, seekResult is the register holding the record */
 18620  
 18621    /* When a new VdbeCursor is allocated, only the fields above are zeroed.
 18622    ** The fields that follow are uninitialized, and must be individually
 18623    ** initialized prior to first use. */
 18624    VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
 18625    union {
 18626      BtCursor *pCursor;          /* CURTYPE_BTREE or _PSEUDO.  Btree cursor */
 18627      sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB.              Vtab cursor */
 18628      VdbeSorter *pSorter;        /* CURTYPE_SORTER.            Sorter object */
 18629    } uc;
 18630    KeyInfo *pKeyInfo;      /* Info about index keys needed by index cursors */
 18631    u32 iHdrOffset;         /* Offset to next unparsed byte of the header */
 18632    Pgno pgnoRoot;          /* Root page of the open btree cursor */
 18633    i16 nField;             /* Number of fields in the header */
 18634    u16 nHdrParsed;         /* Number of header fields parsed so far */
 18635    i64 movetoTarget;       /* Argument to the deferred sqlite3BtreeMoveto() */
 18636    u32 *aOffset;           /* Pointer to aType[nField] */
 18637    const u8 *aRow;         /* Data for the current row, if all on one page */
 18638    u32 payloadSize;        /* Total number of bytes in the record */
 18639    u32 szRow;              /* Byte available in aRow */
 18640  #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
 18641    u64 maskUsed;           /* Mask of columns used by this cursor */
 18642  #endif
 18643  
 18644    /* 2*nField extra array elements allocated for aType[], beyond the one
 18645    ** static element declared in the structure.  nField total array slots for
 18646    ** aType[] and nField+1 array slots for aOffset[] */
 18647    u32 aType[1];           /* Type values record decode.  MUST BE LAST */
 18648  };
 18649  
 18650  
 18651  /*
 18652  ** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
 18653  */
 18654  #define CACHE_STALE 0
 18655  
 18656  /*
 18657  ** When a sub-program is executed (OP_Program), a structure of this type
 18658  ** is allocated to store the current value of the program counter, as
 18659  ** well as the current memory cell array and various other frame specific
 18660  ** values stored in the Vdbe struct. When the sub-program is finished, 
 18661  ** these values are copied back to the Vdbe from the VdbeFrame structure,
 18662  ** restoring the state of the VM to as it was before the sub-program
 18663  ** began executing.
 18664  **
 18665  ** The memory for a VdbeFrame object is allocated and managed by a memory
 18666  ** cell in the parent (calling) frame. When the memory cell is deleted or
 18667  ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
 18668  ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
 18669  ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
 18670  ** this instead of deleting the VdbeFrame immediately is to avoid recursive
 18671  ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
 18672  ** child frame are released.
 18673  **
 18674  ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
 18675  ** set to NULL if the currently executing frame is the main program.
 18676  */
 18677  typedef struct VdbeFrame VdbeFrame;
 18678  struct VdbeFrame {
 18679    Vdbe *v;                /* VM this frame belongs to */
 18680    VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
 18681    Op *aOp;                /* Program instructions for parent frame */
 18682    i64 *anExec;            /* Event counters from parent frame */
 18683    Mem *aMem;              /* Array of memory cells for parent frame */
 18684    VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
 18685    u8 *aOnce;              /* Bitmask used by OP_Once */
 18686    void *token;            /* Copy of SubProgram.token */
 18687    i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
 18688    AuxData *pAuxData;      /* Linked list of auxdata allocations */
 18689    int nCursor;            /* Number of entries in apCsr */
 18690    int pc;                 /* Program Counter in parent (calling) frame */
 18691    int nOp;                /* Size of aOp array */
 18692    int nMem;               /* Number of entries in aMem */
 18693    int nChildMem;          /* Number of memory cells for child frame */
 18694    int nChildCsr;          /* Number of cursors for child frame */
 18695    int nChange;            /* Statement changes (Vdbe.nChange)     */
 18696    int nDbChange;          /* Value of db->nChange */
 18697  };
 18698  
 18699  #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
 18700  
 18701  /*
 18702  ** Internally, the vdbe manipulates nearly all SQL values as Mem
 18703  ** structures. Each Mem struct may cache multiple representations (string,
 18704  ** integer etc.) of the same value.
 18705  */
 18706  struct sqlite3_value {
 18707    union MemValue {
 18708      double r;           /* Real value used when MEM_Real is set in flags */
 18709      i64 i;              /* Integer value used when MEM_Int is set in flags */
 18710      int nZero;          /* Extra zero bytes when MEM_Zero and MEM_Blob set */
 18711      const char *zPType; /* Pointer type when MEM_Term|MEM_Subtype|MEM_Null */
 18712      FuncDef *pDef;      /* Used only when flags==MEM_Agg */
 18713      RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
 18714      VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
 18715    } u;
 18716    u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
 18717    u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
 18718    u8  eSubtype;       /* Subtype for this value */
 18719    int n;              /* Number of characters in string value, excluding '\0' */
 18720    char *z;            /* String or BLOB value */
 18721    /* ShallowCopy only needs to copy the information above */
 18722    char *zMalloc;      /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
 18723    int szMalloc;       /* Size of the zMalloc allocation */
 18724    u32 uTemp;          /* Transient storage for serial_type in OP_MakeRecord */
 18725    sqlite3 *db;        /* The associated database connection */
 18726    void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
 18727  #ifdef SQLITE_DEBUG
 18728    Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
 18729    void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
 18730  #endif
 18731  };
 18732  
 18733  /*
 18734  ** Size of struct Mem not including the Mem.zMalloc member or anything that
 18735  ** follows.
 18736  */
 18737  #define MEMCELLSIZE offsetof(Mem,zMalloc)
 18738  
 18739  /* One or more of the following flags are set to indicate the validOK
 18740  ** representations of the value stored in the Mem struct.
 18741  **
 18742  ** If the MEM_Null flag is set, then the value is an SQL NULL value.
 18743  ** For a pointer type created using sqlite3_bind_pointer() or
 18744  ** sqlite3_result_pointer() the MEM_Term and MEM_Subtype flags are also set.
 18745  **
 18746  ** If the MEM_Str flag is set then Mem.z points at a string representation.
 18747  ** Usually this is encoded in the same unicode encoding as the main
 18748  ** database (see below for exceptions). If the MEM_Term flag is also
 18749  ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
 18750  ** flags may coexist with the MEM_Str flag.
 18751  */
 18752  #define MEM_Null      0x0001   /* Value is NULL (or a pointer) */
 18753  #define MEM_Str       0x0002   /* Value is a string */
 18754  #define MEM_Int       0x0004   /* Value is an integer */
 18755  #define MEM_Real      0x0008   /* Value is a real number */
 18756  #define MEM_Blob      0x0010   /* Value is a BLOB */
 18757  #define MEM_AffMask   0x001f   /* Mask of affinity bits */
 18758  #define MEM_RowSet    0x0020   /* Value is a RowSet object */
 18759  #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
 18760  #define MEM_Undefined 0x0080   /* Value is undefined */
 18761  #define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
 18762  #define MEM_TypeMask  0xc1ff   /* Mask of type bits */
 18763  
 18764  
 18765  /* Whenever Mem contains a valid string or blob representation, one of
 18766  ** the following flags must be set to determine the memory management
 18767  ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
 18768  ** string is \000 or \u0000 terminated
 18769  */
 18770  #define MEM_Term      0x0200   /* String in Mem.z is zero terminated */
 18771  #define MEM_Dyn       0x0400   /* Need to call Mem.xDel() on Mem.z */
 18772  #define MEM_Static    0x0800   /* Mem.z points to a static string */
 18773  #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
 18774  #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
 18775  #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
 18776  #define MEM_Subtype   0x8000   /* Mem.eSubtype is valid */
 18777  #ifdef SQLITE_OMIT_INCRBLOB
 18778    #undef MEM_Zero
 18779    #define MEM_Zero 0x0000
 18780  #endif
 18781  
 18782  /* Return TRUE if Mem X contains dynamically allocated content - anything
 18783  ** that needs to be deallocated to avoid a leak.
 18784  */
 18785  #define VdbeMemDynamic(X)  \
 18786    (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
 18787  
 18788  /*
 18789  ** Clear any existing type flags from a Mem and replace them with f
 18790  */
 18791  #define MemSetTypeFlag(p, f) \
 18792     ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
 18793  
 18794  /*
 18795  ** Return true if a memory cell is not marked as invalid.  This macro
 18796  ** is for use inside assert() statements only.
 18797  */
 18798  #ifdef SQLITE_DEBUG
 18799  #define memIsValid(M)  ((M)->flags & MEM_Undefined)==0
 18800  #endif
 18801  
 18802  /*
 18803  ** Each auxiliary data pointer stored by a user defined function 
 18804  ** implementation calling sqlite3_set_auxdata() is stored in an instance
 18805  ** of this structure. All such structures associated with a single VM
 18806  ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
 18807  ** when the VM is halted (if not before).
 18808  */
 18809  struct AuxData {
 18810    int iAuxOp;                     /* Instruction number of OP_Function opcode */
 18811    int iAuxArg;                    /* Index of function argument. */
 18812    void *pAux;                     /* Aux data pointer */
 18813    void (*xDeleteAux)(void*);      /* Destructor for the aux data */
 18814    AuxData *pNextAux;              /* Next element in list */
 18815  };
 18816  
 18817  /*
 18818  ** The "context" argument for an installable function.  A pointer to an
 18819  ** instance of this structure is the first argument to the routines used
 18820  ** implement the SQL functions.
 18821  **
 18822  ** There is a typedef for this structure in sqlite.h.  So all routines,
 18823  ** even the public interface to SQLite, can use a pointer to this structure.
 18824  ** But this file is the only place where the internal details of this
 18825  ** structure are known.
 18826  **
 18827  ** This structure is defined inside of vdbeInt.h because it uses substructures
 18828  ** (Mem) which are only defined there.
 18829  */
 18830  struct sqlite3_context {
 18831    Mem *pOut;              /* The return value is stored here */
 18832    FuncDef *pFunc;         /* Pointer to function information */
 18833    Mem *pMem;              /* Memory cell used to store aggregate context */
 18834    Vdbe *pVdbe;            /* The VM that owns this context */
 18835    int iOp;                /* Instruction number of OP_Function */
 18836    int isError;            /* Error code returned by the function. */
 18837    u8 skipFlag;            /* Skip accumulator loading if true */
 18838    u8 fErrorOrAux;         /* isError!=0 or pVdbe->pAuxData modified */
 18839    u8 argc;                /* Number of arguments */
 18840    sqlite3_value *argv[1]; /* Argument set */
 18841  };
 18842  
 18843  /* A bitfield type for use inside of structures.  Always follow with :N where
 18844  ** N is the number of bits.
 18845  */
 18846  typedef unsigned bft;  /* Bit Field Type */
 18847  
 18848  typedef struct ScanStatus ScanStatus;
 18849  struct ScanStatus {
 18850    int addrExplain;                /* OP_Explain for loop */
 18851    int addrLoop;                   /* Address of "loops" counter */
 18852    int addrVisit;                  /* Address of "rows visited" counter */
 18853    int iSelectID;                  /* The "Select-ID" for this loop */
 18854    LogEst nEst;                    /* Estimated output rows per loop */
 18855    char *zName;                    /* Name of table or index */
 18856  };
 18857  
 18858  /*
 18859  ** An instance of the virtual machine.  This structure contains the complete
 18860  ** state of the virtual machine.
 18861  **
 18862  ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
 18863  ** is really a pointer to an instance of this structure.
 18864  */
 18865  struct Vdbe {
 18866    sqlite3 *db;            /* The database connection that owns this statement */
 18867    Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
 18868    Parse *pParse;          /* Parsing context used to create this Vdbe */
 18869    ynVar nVar;             /* Number of entries in aVar[] */
 18870    u32 magic;              /* Magic number for sanity checking */
 18871    int nMem;               /* Number of memory locations currently allocated */
 18872    int nCursor;            /* Number of slots in apCsr[] */
 18873    u32 cacheCtr;           /* VdbeCursor row cache generation counter */
 18874    int pc;                 /* The program counter */
 18875    int rc;                 /* Value to return */
 18876    int nChange;            /* Number of db changes made since last reset */
 18877    int iStatement;         /* Statement number (or 0 if has not opened stmt) */
 18878    i64 iCurrentTime;       /* Value of julianday('now') for this statement */
 18879    i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
 18880    i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
 18881    i64 nStmtDefImmCons;    /* Number of def. imm constraints when stmt started */
 18882  
 18883    /* When allocating a new Vdbe object, all of the fields below should be
 18884    ** initialized to zero or NULL */
 18885  
 18886    Op *aOp;                /* Space to hold the virtual machine's program */
 18887    Mem *aMem;              /* The memory locations */
 18888    Mem **apArg;            /* Arguments to currently executing user function */
 18889    Mem *aColName;          /* Column names to return */
 18890    Mem *pResultSet;        /* Pointer to an array of results */
 18891    char *zErrMsg;          /* Error message written here */
 18892    VdbeCursor **apCsr;     /* One element of this array for each open cursor */
 18893    Mem *aVar;              /* Values for the OP_Variable opcode. */
 18894    VList *pVList;          /* Name of variables */
 18895  #ifndef SQLITE_OMIT_TRACE
 18896    i64 startTime;          /* Time when query started - used for profiling */
 18897  #endif
 18898    int nOp;                /* Number of instructions in the program */
 18899  #ifdef SQLITE_DEBUG
 18900    int rcApp;              /* errcode set by sqlite3_result_error_code() */
 18901  #endif
 18902    u16 nResColumn;         /* Number of columns in one row of the result set */
 18903    u8 errorAction;         /* Recovery action to do in case of an error */
 18904    u8 minWriteFileFormat;  /* Minimum file format for writable database files */
 18905    u8 prepFlags;           /* SQLITE_PREPARE_* flags */
 18906    bft expired:1;          /* True if the VM needs to be recompiled */
 18907    bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
 18908    bft explain:2;          /* True if EXPLAIN present on SQL command */
 18909    bft changeCntOn:1;      /* True to update the change-counter */
 18910    bft runOnlyOnce:1;      /* Automatically expire on reset */
 18911    bft usesStmtJournal:1;  /* True if uses a statement journal */
 18912    bft readOnly:1;         /* True for statements that do not write */
 18913    bft bIsReader:1;        /* True for statements that read */
 18914    yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
 18915    yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
 18916    u32 aCounter[7];        /* Counters used by sqlite3_stmt_status() */
 18917    char *zSql;             /* Text of the SQL statement that generated this */
 18918    void *pFree;            /* Free this when deleting the vdbe */
 18919    VdbeFrame *pFrame;      /* Parent frame */
 18920    VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
 18921    int nFrame;             /* Number of frames in pFrame list */
 18922    u32 expmask;            /* Binding to these vars invalidates VM */
 18923    SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
 18924    AuxData *pAuxData;      /* Linked list of auxdata allocations */
 18925  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 18926    i64 *anExec;            /* Number of times each op has been executed */
 18927    int nScan;              /* Entries in aScan[] */
 18928    ScanStatus *aScan;      /* Scan definitions for sqlite3_stmt_scanstatus() */
 18929  #endif
 18930  };
 18931  
 18932  /*
 18933  ** The following are allowed values for Vdbe.magic
 18934  */
 18935  #define VDBE_MAGIC_INIT     0x16bceaa5    /* Building a VDBE program */
 18936  #define VDBE_MAGIC_RUN      0x2df20da3    /* VDBE is ready to execute */
 18937  #define VDBE_MAGIC_HALT     0x319c2973    /* VDBE has completed execution */
 18938  #define VDBE_MAGIC_RESET    0x48fa9f76    /* Reset and ready to run again */
 18939  #define VDBE_MAGIC_DEAD     0x5606c3c8    /* The VDBE has been deallocated */
 18940  
 18941  /*
 18942  ** Structure used to store the context required by the 
 18943  ** sqlite3_preupdate_*() API functions.
 18944  */
 18945  struct PreUpdate {
 18946    Vdbe *v;
 18947    VdbeCursor *pCsr;               /* Cursor to read old values from */
 18948    int op;                         /* One of SQLITE_INSERT, UPDATE, DELETE */
 18949    u8 *aRecord;                    /* old.* database record */
 18950    KeyInfo keyinfo;
 18951    UnpackedRecord *pUnpacked;      /* Unpacked version of aRecord[] */
 18952    UnpackedRecord *pNewUnpacked;   /* Unpacked version of new.* record */
 18953    int iNewReg;                    /* Register for new.* values */
 18954    i64 iKey1;                      /* First key value passed to hook */
 18955    i64 iKey2;                      /* Second key value passed to hook */
 18956    Mem *aNew;                      /* Array of new.* values */
 18957    Table *pTab;                    /* Schema object being upated */          
 18958    Index *pPk;                     /* PK index if pTab is WITHOUT ROWID */
 18959  };
 18960  
 18961  /*
 18962  ** Function prototypes
 18963  */
 18964  SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
 18965  SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
 18966  void sqliteVdbePopStack(Vdbe*,int);
 18967  SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
 18968  SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
 18969  #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
 18970  SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
 18971  #endif
 18972  SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
 18973  SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
 18974  SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
 18975  SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
 18976  SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
 18977  SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
 18978  
 18979  int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
 18980  SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
 18981  SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
 18982  SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
 18983  SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
 18984  SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
 18985  SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
 18986  SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
 18987  SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
 18988  SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
 18989  SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
 18990  SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
 18991  SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
 18992  SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
 18993  #ifdef SQLITE_OMIT_FLOATING_POINT
 18994  # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
 18995  #else
 18996  SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
 18997  #endif
 18998  SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(Mem*, void*, const char*, void(*)(void*));
 18999  SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
 19000  SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
 19001  SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
 19002  SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
 19003  SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
 19004  SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
 19005  SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
 19006  SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
 19007  SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
 19008  SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
 19009  SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
 19010  SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
 19011  SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
 19012  SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
 19013  SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
 19014  SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
 19015  SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
 19016  SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
 19017  SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
 19018  SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
 19019  SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
 19020  SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
 19021  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 19022  SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
 19023  #endif
 19024  SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
 19025  
 19026  SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
 19027  SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
 19028  SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
 19029  SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
 19030  SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *);
 19031  SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
 19032  SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
 19033  SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
 19034  
 19035  #if !defined(SQLITE_OMIT_SHARED_CACHE) 
 19036  SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
 19037  #else
 19038  # define sqlite3VdbeEnter(X)
 19039  #endif
 19040  
 19041  #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
 19042  SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
 19043  #else
 19044  # define sqlite3VdbeLeave(X)
 19045  #endif
 19046  
 19047  #ifdef SQLITE_DEBUG
 19048  SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
 19049  SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
 19050  #endif
 19051  
 19052  #ifndef SQLITE_OMIT_FOREIGN_KEY
 19053  SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
 19054  #else
 19055  # define sqlite3VdbeCheckFk(p,i) 0
 19056  #endif
 19057  
 19058  #ifdef SQLITE_DEBUG
 19059  SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
 19060  SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
 19061  #endif
 19062  #ifndef SQLITE_OMIT_UTF16
 19063  SQLITE_PRIVATE   int sqlite3VdbeMemTranslate(Mem*, u8);
 19064  SQLITE_PRIVATE   int sqlite3VdbeMemHandleBom(Mem *pMem);
 19065  #endif
 19066  
 19067  #ifndef SQLITE_OMIT_INCRBLOB
 19068  SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
 19069    #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
 19070  #else
 19071    #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
 19072    #define ExpandBlob(P) SQLITE_OK
 19073  #endif
 19074  
 19075  #endif /* !defined(SQLITE_VDBEINT_H) */
 19076  
 19077  /************** End of vdbeInt.h *********************************************/
 19078  /************** Continuing where we left off in status.c *********************/
 19079  
 19080  /*
 19081  ** Variables in which to record status information.
 19082  */
 19083  #if SQLITE_PTRSIZE>4
 19084  typedef sqlite3_int64 sqlite3StatValueType;
 19085  #else
 19086  typedef u32 sqlite3StatValueType;
 19087  #endif
 19088  typedef struct sqlite3StatType sqlite3StatType;
 19089  static SQLITE_WSD struct sqlite3StatType {
 19090    sqlite3StatValueType nowValue[10];  /* Current value */
 19091    sqlite3StatValueType mxValue[10];   /* Maximum value */
 19092  } sqlite3Stat = { {0,}, {0,} };
 19093  
 19094  /*
 19095  ** Elements of sqlite3Stat[] are protected by either the memory allocator
 19096  ** mutex, or by the pcache1 mutex.  The following array determines which.
 19097  */
 19098  static const char statMutex[] = {
 19099    0,  /* SQLITE_STATUS_MEMORY_USED */
 19100    1,  /* SQLITE_STATUS_PAGECACHE_USED */
 19101    1,  /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
 19102    0,  /* SQLITE_STATUS_SCRATCH_USED */
 19103    0,  /* SQLITE_STATUS_SCRATCH_OVERFLOW */
 19104    0,  /* SQLITE_STATUS_MALLOC_SIZE */
 19105    0,  /* SQLITE_STATUS_PARSER_STACK */
 19106    1,  /* SQLITE_STATUS_PAGECACHE_SIZE */
 19107    0,  /* SQLITE_STATUS_SCRATCH_SIZE */
 19108    0,  /* SQLITE_STATUS_MALLOC_COUNT */
 19109  };
 19110  
 19111  
 19112  /* The "wsdStat" macro will resolve to the status information
 19113  ** state vector.  If writable static data is unsupported on the target,
 19114  ** we have to locate the state vector at run-time.  In the more common
 19115  ** case where writable static data is supported, wsdStat can refer directly
 19116  ** to the "sqlite3Stat" state vector declared above.
 19117  */
 19118  #ifdef SQLITE_OMIT_WSD
 19119  # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
 19120  # define wsdStat x[0]
 19121  #else
 19122  # define wsdStatInit
 19123  # define wsdStat sqlite3Stat
 19124  #endif
 19125  
 19126  /*
 19127  ** Return the current value of a status parameter.  The caller must
 19128  ** be holding the appropriate mutex.
 19129  */
 19130  SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
 19131    wsdStatInit;
 19132    assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
 19133    assert( op>=0 && op<ArraySize(statMutex) );
 19134    assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
 19135                                             : sqlite3MallocMutex()) );
 19136    return wsdStat.nowValue[op];
 19137  }
 19138  
 19139  /*
 19140  ** Add N to the value of a status record.  The caller must hold the
 19141  ** appropriate mutex.  (Locking is checked by assert()).
 19142  **
 19143  ** The StatusUp() routine can accept positive or negative values for N.
 19144  ** The value of N is added to the current status value and the high-water
 19145  ** mark is adjusted if necessary.
 19146  **
 19147  ** The StatusDown() routine lowers the current value by N.  The highwater
 19148  ** mark is unchanged.  N must be non-negative for StatusDown().
 19149  */
 19150  SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
 19151    wsdStatInit;
 19152    assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
 19153    assert( op>=0 && op<ArraySize(statMutex) );
 19154    assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
 19155                                             : sqlite3MallocMutex()) );
 19156    wsdStat.nowValue[op] += N;
 19157    if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
 19158      wsdStat.mxValue[op] = wsdStat.nowValue[op];
 19159    }
 19160  }
 19161  SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
 19162    wsdStatInit;
 19163    assert( N>=0 );
 19164    assert( op>=0 && op<ArraySize(statMutex) );
 19165    assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
 19166                                             : sqlite3MallocMutex()) );
 19167    assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
 19168    wsdStat.nowValue[op] -= N;
 19169  }
 19170  
 19171  /*
 19172  ** Adjust the highwater mark if necessary.
 19173  ** The caller must hold the appropriate mutex.
 19174  */
 19175  SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
 19176    sqlite3StatValueType newValue;
 19177    wsdStatInit;
 19178    assert( X>=0 );
 19179    newValue = (sqlite3StatValueType)X;
 19180    assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
 19181    assert( op>=0 && op<ArraySize(statMutex) );
 19182    assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
 19183                                             : sqlite3MallocMutex()) );
 19184    assert( op==SQLITE_STATUS_MALLOC_SIZE
 19185            || op==SQLITE_STATUS_PAGECACHE_SIZE
 19186            || op==SQLITE_STATUS_PARSER_STACK );
 19187    if( newValue>wsdStat.mxValue[op] ){
 19188      wsdStat.mxValue[op] = newValue;
 19189    }
 19190  }
 19191  
 19192  /*
 19193  ** Query status information.
 19194  */
 19195  SQLITE_API int sqlite3_status64(
 19196    int op,
 19197    sqlite3_int64 *pCurrent,
 19198    sqlite3_int64 *pHighwater,
 19199    int resetFlag
 19200  ){
 19201    sqlite3_mutex *pMutex;
 19202    wsdStatInit;
 19203    if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
 19204      return SQLITE_MISUSE_BKPT;
 19205    }
 19206  #ifdef SQLITE_ENABLE_API_ARMOR
 19207    if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
 19208  #endif
 19209    pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
 19210    sqlite3_mutex_enter(pMutex);
 19211    *pCurrent = wsdStat.nowValue[op];
 19212    *pHighwater = wsdStat.mxValue[op];
 19213    if( resetFlag ){
 19214      wsdStat.mxValue[op] = wsdStat.nowValue[op];
 19215    }
 19216    sqlite3_mutex_leave(pMutex);
 19217    (void)pMutex;  /* Prevent warning when SQLITE_THREADSAFE=0 */
 19218    return SQLITE_OK;
 19219  }
 19220  SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
 19221    sqlite3_int64 iCur = 0, iHwtr = 0;
 19222    int rc;
 19223  #ifdef SQLITE_ENABLE_API_ARMOR
 19224    if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
 19225  #endif
 19226    rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
 19227    if( rc==0 ){
 19228      *pCurrent = (int)iCur;
 19229      *pHighwater = (int)iHwtr;
 19230    }
 19231    return rc;
 19232  }
 19233  
 19234  /*
 19235  ** Return the number of LookasideSlot elements on the linked list
 19236  */
 19237  static u32 countLookasideSlots(LookasideSlot *p){
 19238    u32 cnt = 0;
 19239    while( p ){
 19240      p = p->pNext;
 19241      cnt++;
 19242    }
 19243    return cnt;
 19244  }
 19245  
 19246  /*
 19247  ** Count the number of slots of lookaside memory that are outstanding
 19248  */
 19249  SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){
 19250    u32 nInit = countLookasideSlots(db->lookaside.pInit);
 19251    u32 nFree = countLookasideSlots(db->lookaside.pFree);
 19252    if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit;
 19253    return db->lookaside.nSlot - (nInit+nFree);
 19254  }
 19255  
 19256  /*
 19257  ** Query status information for a single database connection
 19258  */
 19259  SQLITE_API int sqlite3_db_status(
 19260    sqlite3 *db,          /* The database connection whose status is desired */
 19261    int op,               /* Status verb */
 19262    int *pCurrent,        /* Write current value here */
 19263    int *pHighwater,      /* Write high-water mark here */
 19264    int resetFlag         /* Reset high-water mark if true */
 19265  ){
 19266    int rc = SQLITE_OK;   /* Return code */
 19267  #ifdef SQLITE_ENABLE_API_ARMOR
 19268    if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
 19269      return SQLITE_MISUSE_BKPT;
 19270    }
 19271  #endif
 19272    sqlite3_mutex_enter(db->mutex);
 19273    switch( op ){
 19274      case SQLITE_DBSTATUS_LOOKASIDE_USED: {
 19275        *pCurrent = sqlite3LookasideUsed(db, pHighwater);
 19276        if( resetFlag ){
 19277          LookasideSlot *p = db->lookaside.pFree;
 19278          if( p ){
 19279            while( p->pNext ) p = p->pNext;
 19280            p->pNext = db->lookaside.pInit;
 19281            db->lookaside.pInit = db->lookaside.pFree;
 19282            db->lookaside.pFree = 0;
 19283          }
 19284        }
 19285        break;
 19286      }
 19287  
 19288      case SQLITE_DBSTATUS_LOOKASIDE_HIT:
 19289      case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
 19290      case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
 19291        testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
 19292        testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
 19293        testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
 19294        assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
 19295        assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
 19296        *pCurrent = 0;
 19297        *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
 19298        if( resetFlag ){
 19299          db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
 19300        }
 19301        break;
 19302      }
 19303  
 19304      /* 
 19305      ** Return an approximation for the amount of memory currently used
 19306      ** by all pagers associated with the given database connection.  The
 19307      ** highwater mark is meaningless and is returned as zero.
 19308      */
 19309      case SQLITE_DBSTATUS_CACHE_USED_SHARED:
 19310      case SQLITE_DBSTATUS_CACHE_USED: {
 19311        int totalUsed = 0;
 19312        int i;
 19313        sqlite3BtreeEnterAll(db);
 19314        for(i=0; i<db->nDb; i++){
 19315          Btree *pBt = db->aDb[i].pBt;
 19316          if( pBt ){
 19317            Pager *pPager = sqlite3BtreePager(pBt);
 19318            int nByte = sqlite3PagerMemUsed(pPager);
 19319            if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
 19320              nByte = nByte / sqlite3BtreeConnectionCount(pBt);
 19321            }
 19322            totalUsed += nByte;
 19323          }
 19324        }
 19325        sqlite3BtreeLeaveAll(db);
 19326        *pCurrent = totalUsed;
 19327        *pHighwater = 0;
 19328        break;
 19329      }
 19330  
 19331      /*
 19332      ** *pCurrent gets an accurate estimate of the amount of memory used
 19333      ** to store the schema for all databases (main, temp, and any ATTACHed
 19334      ** databases.  *pHighwater is set to zero.
 19335      */
 19336      case SQLITE_DBSTATUS_SCHEMA_USED: {
 19337        int i;                      /* Used to iterate through schemas */
 19338        int nByte = 0;              /* Used to accumulate return value */
 19339  
 19340        sqlite3BtreeEnterAll(db);
 19341        db->pnBytesFreed = &nByte;
 19342        for(i=0; i<db->nDb; i++){
 19343          Schema *pSchema = db->aDb[i].pSchema;
 19344          if( ALWAYS(pSchema!=0) ){
 19345            HashElem *p;
 19346  
 19347            nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
 19348                pSchema->tblHash.count 
 19349              + pSchema->trigHash.count
 19350              + pSchema->idxHash.count
 19351              + pSchema->fkeyHash.count
 19352            );
 19353            nByte += sqlite3_msize(pSchema->tblHash.ht);
 19354            nByte += sqlite3_msize(pSchema->trigHash.ht);
 19355            nByte += sqlite3_msize(pSchema->idxHash.ht);
 19356            nByte += sqlite3_msize(pSchema->fkeyHash.ht);
 19357  
 19358            for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
 19359              sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
 19360            }
 19361            for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
 19362              sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
 19363            }
 19364          }
 19365        }
 19366        db->pnBytesFreed = 0;
 19367        sqlite3BtreeLeaveAll(db);
 19368  
 19369        *pHighwater = 0;
 19370        *pCurrent = nByte;
 19371        break;
 19372      }
 19373  
 19374      /*
 19375      ** *pCurrent gets an accurate estimate of the amount of memory used
 19376      ** to store all prepared statements.
 19377      ** *pHighwater is set to zero.
 19378      */
 19379      case SQLITE_DBSTATUS_STMT_USED: {
 19380        struct Vdbe *pVdbe;         /* Used to iterate through VMs */
 19381        int nByte = 0;              /* Used to accumulate return value */
 19382  
 19383        db->pnBytesFreed = &nByte;
 19384        for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
 19385          sqlite3VdbeClearObject(db, pVdbe);
 19386          sqlite3DbFree(db, pVdbe);
 19387        }
 19388        db->pnBytesFreed = 0;
 19389  
 19390        *pHighwater = 0;  /* IMP: R-64479-57858 */
 19391        *pCurrent = nByte;
 19392  
 19393        break;
 19394      }
 19395  
 19396      /*
 19397      ** Set *pCurrent to the total cache hits or misses encountered by all
 19398      ** pagers the database handle is connected to. *pHighwater is always set 
 19399      ** to zero.
 19400      */
 19401      case SQLITE_DBSTATUS_CACHE_HIT:
 19402      case SQLITE_DBSTATUS_CACHE_MISS:
 19403      case SQLITE_DBSTATUS_CACHE_WRITE:{
 19404        int i;
 19405        int nRet = 0;
 19406        assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
 19407        assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
 19408  
 19409        for(i=0; i<db->nDb; i++){
 19410          if( db->aDb[i].pBt ){
 19411            Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
 19412            sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
 19413          }
 19414        }
 19415        *pHighwater = 0; /* IMP: R-42420-56072 */
 19416                         /* IMP: R-54100-20147 */
 19417                         /* IMP: R-29431-39229 */
 19418        *pCurrent = nRet;
 19419        break;
 19420      }
 19421  
 19422      /* Set *pCurrent to non-zero if there are unresolved deferred foreign
 19423      ** key constraints.  Set *pCurrent to zero if all foreign key constraints
 19424      ** have been satisfied.  The *pHighwater is always set to zero.
 19425      */
 19426      case SQLITE_DBSTATUS_DEFERRED_FKS: {
 19427        *pHighwater = 0;  /* IMP: R-11967-56545 */
 19428        *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
 19429        break;
 19430      }
 19431  
 19432      default: {
 19433        rc = SQLITE_ERROR;
 19434      }
 19435    }
 19436    sqlite3_mutex_leave(db->mutex);
 19437    return rc;
 19438  }
 19439  
 19440  /************** End of status.c **********************************************/
 19441  /************** Begin file date.c ********************************************/
 19442  /*
 19443  ** 2003 October 31
 19444  **
 19445  ** The author disclaims copyright to this source code.  In place of
 19446  ** a legal notice, here is a blessing:
 19447  **
 19448  **    May you do good and not evil.
 19449  **    May you find forgiveness for yourself and forgive others.
 19450  **    May you share freely, never taking more than you give.
 19451  **
 19452  *************************************************************************
 19453  ** This file contains the C functions that implement date and time
 19454  ** functions for SQLite.  
 19455  **
 19456  ** There is only one exported symbol in this file - the function
 19457  ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
 19458  ** All other code has file scope.
 19459  **
 19460  ** SQLite processes all times and dates as julian day numbers.  The
 19461  ** dates and times are stored as the number of days since noon
 19462  ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
 19463  ** calendar system. 
 19464  **
 19465  ** 1970-01-01 00:00:00 is JD 2440587.5
 19466  ** 2000-01-01 00:00:00 is JD 2451544.5
 19467  **
 19468  ** This implementation requires years to be expressed as a 4-digit number
 19469  ** which means that only dates between 0000-01-01 and 9999-12-31 can
 19470  ** be represented, even though julian day numbers allow a much wider
 19471  ** range of dates.
 19472  **
 19473  ** The Gregorian calendar system is used for all dates and times,
 19474  ** even those that predate the Gregorian calendar.  Historians usually
 19475  ** use the julian calendar for dates prior to 1582-10-15 and for some
 19476  ** dates afterwards, depending on locale.  Beware of this difference.
 19477  **
 19478  ** The conversion algorithms are implemented based on descriptions
 19479  ** in the following text:
 19480  **
 19481  **      Jean Meeus
 19482  **      Astronomical Algorithms, 2nd Edition, 1998
 19483  **      ISBM 0-943396-61-1
 19484  **      Willmann-Bell, Inc
 19485  **      Richmond, Virginia (USA)
 19486  */
 19487  /* #include "sqliteInt.h" */
 19488  /* #include <stdlib.h> */
 19489  /* #include <assert.h> */
 19490  #include <time.h>
 19491  
 19492  #ifndef SQLITE_OMIT_DATETIME_FUNCS
 19493  
 19494  /*
 19495  ** The MSVC CRT on Windows CE may not have a localtime() function.
 19496  ** So declare a substitute.  The substitute function itself is
 19497  ** defined in "os_win.c".
 19498  */
 19499  #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
 19500      (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
 19501  struct tm *__cdecl localtime(const time_t *);
 19502  #endif
 19503  
 19504  /*
 19505  ** A structure for holding a single date and time.
 19506  */
 19507  typedef struct DateTime DateTime;
 19508  struct DateTime {
 19509    sqlite3_int64 iJD;  /* The julian day number times 86400000 */
 19510    int Y, M, D;        /* Year, month, and day */
 19511    int h, m;           /* Hour and minutes */
 19512    int tz;             /* Timezone offset in minutes */
 19513    double s;           /* Seconds */
 19514    char validJD;       /* True (1) if iJD is valid */
 19515    char rawS;          /* Raw numeric value stored in s */
 19516    char validYMD;      /* True (1) if Y,M,D are valid */
 19517    char validHMS;      /* True (1) if h,m,s are valid */
 19518    char validTZ;       /* True (1) if tz is valid */
 19519    char tzSet;         /* Timezone was set explicitly */
 19520    char isError;       /* An overflow has occurred */
 19521  };
 19522  
 19523  
 19524  /*
 19525  ** Convert zDate into one or more integers according to the conversion
 19526  ** specifier zFormat.
 19527  **
 19528  ** zFormat[] contains 4 characters for each integer converted, except for
 19529  ** the last integer which is specified by three characters.  The meaning
 19530  ** of a four-character format specifiers ABCD is:
 19531  **
 19532  **    A:   number of digits to convert.  Always "2" or "4".
 19533  **    B:   minimum value.  Always "0" or "1".
 19534  **    C:   maximum value, decoded as:
 19535  **           a:  12
 19536  **           b:  14
 19537  **           c:  24
 19538  **           d:  31
 19539  **           e:  59
 19540  **           f:  9999
 19541  **    D:   the separator character, or \000 to indicate this is the
 19542  **         last number to convert.
 19543  **
 19544  ** Example:  To translate an ISO-8601 date YYYY-MM-DD, the format would
 19545  ** be "40f-21a-20c".  The "40f-" indicates the 4-digit year followed by "-".
 19546  ** The "21a-" indicates the 2-digit month followed by "-".  The "20c" indicates
 19547  ** the 2-digit day which is the last integer in the set.
 19548  **
 19549  ** The function returns the number of successful conversions.
 19550  */
 19551  static int getDigits(const char *zDate, const char *zFormat, ...){
 19552    /* The aMx[] array translates the 3rd character of each format
 19553    ** spec into a max size:    a   b   c   d   e     f */
 19554    static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
 19555    va_list ap;
 19556    int cnt = 0;
 19557    char nextC;
 19558    va_start(ap, zFormat);
 19559    do{
 19560      char N = zFormat[0] - '0';
 19561      char min = zFormat[1] - '0';
 19562      int val = 0;
 19563      u16 max;
 19564  
 19565      assert( zFormat[2]>='a' && zFormat[2]<='f' );
 19566      max = aMx[zFormat[2] - 'a'];
 19567      nextC = zFormat[3];
 19568      val = 0;
 19569      while( N-- ){
 19570        if( !sqlite3Isdigit(*zDate) ){
 19571          goto end_getDigits;
 19572        }
 19573        val = val*10 + *zDate - '0';
 19574        zDate++;
 19575      }
 19576      if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
 19577        goto end_getDigits;
 19578      }
 19579      *va_arg(ap,int*) = val;
 19580      zDate++;
 19581      cnt++;
 19582      zFormat += 4;
 19583    }while( nextC );
 19584  end_getDigits:
 19585    va_end(ap);
 19586    return cnt;
 19587  }
 19588  
 19589  /*
 19590  ** Parse a timezone extension on the end of a date-time.
 19591  ** The extension is of the form:
 19592  **
 19593  **        (+/-)HH:MM
 19594  **
 19595  ** Or the "zulu" notation:
 19596  **
 19597  **        Z
 19598  **
 19599  ** If the parse is successful, write the number of minutes
 19600  ** of change in p->tz and return 0.  If a parser error occurs,
 19601  ** return non-zero.
 19602  **
 19603  ** A missing specifier is not considered an error.
 19604  */
 19605  static int parseTimezone(const char *zDate, DateTime *p){
 19606    int sgn = 0;
 19607    int nHr, nMn;
 19608    int c;
 19609    while( sqlite3Isspace(*zDate) ){ zDate++; }
 19610    p->tz = 0;
 19611    c = *zDate;
 19612    if( c=='-' ){
 19613      sgn = -1;
 19614    }else if( c=='+' ){
 19615      sgn = +1;
 19616    }else if( c=='Z' || c=='z' ){
 19617      zDate++;
 19618      goto zulu_time;
 19619    }else{
 19620      return c!=0;
 19621    }
 19622    zDate++;
 19623    if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
 19624      return 1;
 19625    }
 19626    zDate += 5;
 19627    p->tz = sgn*(nMn + nHr*60);
 19628  zulu_time:
 19629    while( sqlite3Isspace(*zDate) ){ zDate++; }
 19630    p->tzSet = 1;
 19631    return *zDate!=0;
 19632  }
 19633  
 19634  /*
 19635  ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
 19636  ** The HH, MM, and SS must each be exactly 2 digits.  The
 19637  ** fractional seconds FFFF can be one or more digits.
 19638  **
 19639  ** Return 1 if there is a parsing error and 0 on success.
 19640  */
 19641  static int parseHhMmSs(const char *zDate, DateTime *p){
 19642    int h, m, s;
 19643    double ms = 0.0;
 19644    if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
 19645      return 1;
 19646    }
 19647    zDate += 5;
 19648    if( *zDate==':' ){
 19649      zDate++;
 19650      if( getDigits(zDate, "20e", &s)!=1 ){
 19651        return 1;
 19652      }
 19653      zDate += 2;
 19654      if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
 19655        double rScale = 1.0;
 19656        zDate++;
 19657        while( sqlite3Isdigit(*zDate) ){
 19658          ms = ms*10.0 + *zDate - '0';
 19659          rScale *= 10.0;
 19660          zDate++;
 19661        }
 19662        ms /= rScale;
 19663      }
 19664    }else{
 19665      s = 0;
 19666    }
 19667    p->validJD = 0;
 19668    p->rawS = 0;
 19669    p->validHMS = 1;
 19670    p->h = h;
 19671    p->m = m;
 19672    p->s = s + ms;
 19673    if( parseTimezone(zDate, p) ) return 1;
 19674    p->validTZ = (p->tz!=0)?1:0;
 19675    return 0;
 19676  }
 19677  
 19678  /*
 19679  ** Put the DateTime object into its error state.
 19680  */
 19681  static void datetimeError(DateTime *p){
 19682    memset(p, 0, sizeof(*p));
 19683    p->isError = 1;
 19684  }
 19685  
 19686  /*
 19687  ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
 19688  ** that the YYYY-MM-DD is according to the Gregorian calendar.
 19689  **
 19690  ** Reference:  Meeus page 61
 19691  */
 19692  static void computeJD(DateTime *p){
 19693    int Y, M, D, A, B, X1, X2;
 19694  
 19695    if( p->validJD ) return;
 19696    if( p->validYMD ){
 19697      Y = p->Y;
 19698      M = p->M;
 19699      D = p->D;
 19700    }else{
 19701      Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
 19702      M = 1;
 19703      D = 1;
 19704    }
 19705    if( Y<-4713 || Y>9999 || p->rawS ){
 19706      datetimeError(p);
 19707      return;
 19708    }
 19709    if( M<=2 ){
 19710      Y--;
 19711      M += 12;
 19712    }
 19713    A = Y/100;
 19714    B = 2 - A + (A/4);
 19715    X1 = 36525*(Y+4716)/100;
 19716    X2 = 306001*(M+1)/10000;
 19717    p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
 19718    p->validJD = 1;
 19719    if( p->validHMS ){
 19720      p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
 19721      if( p->validTZ ){
 19722        p->iJD -= p->tz*60000;
 19723        p->validYMD = 0;
 19724        p->validHMS = 0;
 19725        p->validTZ = 0;
 19726      }
 19727    }
 19728  }
 19729  
 19730  /*
 19731  ** Parse dates of the form
 19732  **
 19733  **     YYYY-MM-DD HH:MM:SS.FFF
 19734  **     YYYY-MM-DD HH:MM:SS
 19735  **     YYYY-MM-DD HH:MM
 19736  **     YYYY-MM-DD
 19737  **
 19738  ** Write the result into the DateTime structure and return 0
 19739  ** on success and 1 if the input string is not a well-formed
 19740  ** date.
 19741  */
 19742  static int parseYyyyMmDd(const char *zDate, DateTime *p){
 19743    int Y, M, D, neg;
 19744  
 19745    if( zDate[0]=='-' ){
 19746      zDate++;
 19747      neg = 1;
 19748    }else{
 19749      neg = 0;
 19750    }
 19751    if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
 19752      return 1;
 19753    }
 19754    zDate += 10;
 19755    while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
 19756    if( parseHhMmSs(zDate, p)==0 ){
 19757      /* We got the time */
 19758    }else if( *zDate==0 ){
 19759      p->validHMS = 0;
 19760    }else{
 19761      return 1;
 19762    }
 19763    p->validJD = 0;
 19764    p->validYMD = 1;
 19765    p->Y = neg ? -Y : Y;
 19766    p->M = M;
 19767    p->D = D;
 19768    if( p->validTZ ){
 19769      computeJD(p);
 19770    }
 19771    return 0;
 19772  }
 19773  
 19774  /*
 19775  ** Set the time to the current time reported by the VFS.
 19776  **
 19777  ** Return the number of errors.
 19778  */
 19779  static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
 19780    p->iJD = sqlite3StmtCurrentTime(context);
 19781    if( p->iJD>0 ){
 19782      p->validJD = 1;
 19783      return 0;
 19784    }else{
 19785      return 1;
 19786    }
 19787  }
 19788  
 19789  /*
 19790  ** Input "r" is a numeric quantity which might be a julian day number,
 19791  ** or the number of seconds since 1970.  If the value if r is within
 19792  ** range of a julian day number, install it as such and set validJD.
 19793  ** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
 19794  */
 19795  static void setRawDateNumber(DateTime *p, double r){
 19796    p->s = r;
 19797    p->rawS = 1;
 19798    if( r>=0.0 && r<5373484.5 ){
 19799      p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
 19800      p->validJD = 1;
 19801    }
 19802  }
 19803  
 19804  /*
 19805  ** Attempt to parse the given string into a julian day number.  Return
 19806  ** the number of errors.
 19807  **
 19808  ** The following are acceptable forms for the input string:
 19809  **
 19810  **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
 19811  **      DDDD.DD 
 19812  **      now
 19813  **
 19814  ** In the first form, the +/-HH:MM is always optional.  The fractional
 19815  ** seconds extension (the ".FFF") is optional.  The seconds portion
 19816  ** (":SS.FFF") is option.  The year and date can be omitted as long
 19817  ** as there is a time string.  The time string can be omitted as long
 19818  ** as there is a year and date.
 19819  */
 19820  static int parseDateOrTime(
 19821    sqlite3_context *context, 
 19822    const char *zDate, 
 19823    DateTime *p
 19824  ){
 19825    double r;
 19826    if( parseYyyyMmDd(zDate,p)==0 ){
 19827      return 0;
 19828    }else if( parseHhMmSs(zDate, p)==0 ){
 19829      return 0;
 19830    }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
 19831      return setDateTimeToCurrent(context, p);
 19832    }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
 19833      setRawDateNumber(p, r);
 19834      return 0;
 19835    }
 19836    return 1;
 19837  }
 19838  
 19839  /* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
 19840  ** Multiplying this by 86400000 gives 464269060799999 as the maximum value
 19841  ** for DateTime.iJD.
 19842  **
 19843  ** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with 
 19844  ** such a large integer literal, so we have to encode it.
 19845  */
 19846  #define INT_464269060799999  ((((i64)0x1a640)<<32)|0x1072fdff)
 19847  
 19848  /*
 19849  ** Return TRUE if the given julian day number is within range.
 19850  **
 19851  ** The input is the JulianDay times 86400000.
 19852  */
 19853  static int validJulianDay(sqlite3_int64 iJD){
 19854    return iJD>=0 && iJD<=INT_464269060799999;
 19855  }
 19856  
 19857  /*
 19858  ** Compute the Year, Month, and Day from the julian day number.
 19859  */
 19860  static void computeYMD(DateTime *p){
 19861    int Z, A, B, C, D, E, X1;
 19862    if( p->validYMD ) return;
 19863    if( !p->validJD ){
 19864      p->Y = 2000;
 19865      p->M = 1;
 19866      p->D = 1;
 19867    }else if( !validJulianDay(p->iJD) ){
 19868      datetimeError(p);
 19869      return;
 19870    }else{
 19871      Z = (int)((p->iJD + 43200000)/86400000);
 19872      A = (int)((Z - 1867216.25)/36524.25);
 19873      A = Z + 1 + A - (A/4);
 19874      B = A + 1524;
 19875      C = (int)((B - 122.1)/365.25);
 19876      D = (36525*(C&32767))/100;
 19877      E = (int)((B-D)/30.6001);
 19878      X1 = (int)(30.6001*E);
 19879      p->D = B - D - X1;
 19880      p->M = E<14 ? E-1 : E-13;
 19881      p->Y = p->M>2 ? C - 4716 : C - 4715;
 19882    }
 19883    p->validYMD = 1;
 19884  }
 19885  
 19886  /*
 19887  ** Compute the Hour, Minute, and Seconds from the julian day number.
 19888  */
 19889  static void computeHMS(DateTime *p){
 19890    int s;
 19891    if( p->validHMS ) return;
 19892    computeJD(p);
 19893    s = (int)((p->iJD + 43200000) % 86400000);
 19894    p->s = s/1000.0;
 19895    s = (int)p->s;
 19896    p->s -= s;
 19897    p->h = s/3600;
 19898    s -= p->h*3600;
 19899    p->m = s/60;
 19900    p->s += s - p->m*60;
 19901    p->rawS = 0;
 19902    p->validHMS = 1;
 19903  }
 19904  
 19905  /*
 19906  ** Compute both YMD and HMS
 19907  */
 19908  static void computeYMD_HMS(DateTime *p){
 19909    computeYMD(p);
 19910    computeHMS(p);
 19911  }
 19912  
 19913  /*
 19914  ** Clear the YMD and HMS and the TZ
 19915  */
 19916  static void clearYMD_HMS_TZ(DateTime *p){
 19917    p->validYMD = 0;
 19918    p->validHMS = 0;
 19919    p->validTZ = 0;
 19920  }
 19921  
 19922  #ifndef SQLITE_OMIT_LOCALTIME
 19923  /*
 19924  ** On recent Windows platforms, the localtime_s() function is available
 19925  ** as part of the "Secure CRT". It is essentially equivalent to 
 19926  ** localtime_r() available under most POSIX platforms, except that the 
 19927  ** order of the parameters is reversed.
 19928  **
 19929  ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
 19930  **
 19931  ** If the user has not indicated to use localtime_r() or localtime_s()
 19932  ** already, check for an MSVC build environment that provides 
 19933  ** localtime_s().
 19934  */
 19935  #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
 19936      && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
 19937  #undef  HAVE_LOCALTIME_S
 19938  #define HAVE_LOCALTIME_S 1
 19939  #endif
 19940  
 19941  /*
 19942  ** The following routine implements the rough equivalent of localtime_r()
 19943  ** using whatever operating-system specific localtime facility that
 19944  ** is available.  This routine returns 0 on success and
 19945  ** non-zero on any kind of error.
 19946  **
 19947  ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
 19948  ** routine will always fail.
 19949  **
 19950  ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
 19951  ** library function localtime_r() is used to assist in the calculation of
 19952  ** local time.
 19953  */
 19954  static int osLocaltime(time_t *t, struct tm *pTm){
 19955    int rc;
 19956  #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
 19957    struct tm *pX;
 19958  #if SQLITE_THREADSAFE>0
 19959    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
 19960  #endif
 19961    sqlite3_mutex_enter(mutex);
 19962    pX = localtime(t);
 19963  #ifndef SQLITE_UNTESTABLE
 19964    if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
 19965  #endif
 19966    if( pX ) *pTm = *pX;
 19967    sqlite3_mutex_leave(mutex);
 19968    rc = pX==0;
 19969  #else
 19970  #ifndef SQLITE_UNTESTABLE
 19971    if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
 19972  #endif
 19973  #if HAVE_LOCALTIME_R
 19974    rc = localtime_r(t, pTm)==0;
 19975  #else
 19976    rc = localtime_s(pTm, t);
 19977  #endif /* HAVE_LOCALTIME_R */
 19978  #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
 19979    return rc;
 19980  }
 19981  #endif /* SQLITE_OMIT_LOCALTIME */
 19982  
 19983  
 19984  #ifndef SQLITE_OMIT_LOCALTIME
 19985  /*
 19986  ** Compute the difference (in milliseconds) between localtime and UTC
 19987  ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
 19988  ** return this value and set *pRc to SQLITE_OK. 
 19989  **
 19990  ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
 19991  ** is undefined in this case.
 19992  */
 19993  static sqlite3_int64 localtimeOffset(
 19994    DateTime *p,                    /* Date at which to calculate offset */
 19995    sqlite3_context *pCtx,          /* Write error here if one occurs */
 19996    int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
 19997  ){
 19998    DateTime x, y;
 19999    time_t t;
 20000    struct tm sLocal;
 20001  
 20002    /* Initialize the contents of sLocal to avoid a compiler warning. */
 20003    memset(&sLocal, 0, sizeof(sLocal));
 20004  
 20005    x = *p;
 20006    computeYMD_HMS(&x);
 20007    if( x.Y<1971 || x.Y>=2038 ){
 20008      /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
 20009      ** works for years between 1970 and 2037. For dates outside this range,
 20010      ** SQLite attempts to map the year into an equivalent year within this
 20011      ** range, do the calculation, then map the year back.
 20012      */
 20013      x.Y = 2000;
 20014      x.M = 1;
 20015      x.D = 1;
 20016      x.h = 0;
 20017      x.m = 0;
 20018      x.s = 0.0;
 20019    } else {
 20020      int s = (int)(x.s + 0.5);
 20021      x.s = s;
 20022    }
 20023    x.tz = 0;
 20024    x.validJD = 0;
 20025    computeJD(&x);
 20026    t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
 20027    if( osLocaltime(&t, &sLocal) ){
 20028      sqlite3_result_error(pCtx, "local time unavailable", -1);
 20029      *pRc = SQLITE_ERROR;
 20030      return 0;
 20031    }
 20032    y.Y = sLocal.tm_year + 1900;
 20033    y.M = sLocal.tm_mon + 1;
 20034    y.D = sLocal.tm_mday;
 20035    y.h = sLocal.tm_hour;
 20036    y.m = sLocal.tm_min;
 20037    y.s = sLocal.tm_sec;
 20038    y.validYMD = 1;
 20039    y.validHMS = 1;
 20040    y.validJD = 0;
 20041    y.rawS = 0;
 20042    y.validTZ = 0;
 20043    y.isError = 0;
 20044    computeJD(&y);
 20045    *pRc = SQLITE_OK;
 20046    return y.iJD - x.iJD;
 20047  }
 20048  #endif /* SQLITE_OMIT_LOCALTIME */
 20049  
 20050  /*
 20051  ** The following table defines various date transformations of the form
 20052  **
 20053  **            'NNN days'
 20054  **
 20055  ** Where NNN is an arbitrary floating-point number and "days" can be one
 20056  ** of several units of time.
 20057  */
 20058  static const struct {
 20059    u8 eType;           /* Transformation type code */
 20060    u8 nName;           /* Length of th name */
 20061    char *zName;        /* Name of the transformation */
 20062    double rLimit;      /* Maximum NNN value for this transform */
 20063    double rXform;      /* Constant used for this transform */
 20064  } aXformType[] = {
 20065    { 0, 6, "second", 464269060800.0, 86400000.0/(24.0*60.0*60.0) },
 20066    { 0, 6, "minute", 7737817680.0,   86400000.0/(24.0*60.0)      },
 20067    { 0, 4, "hour",   128963628.0,    86400000.0/24.0             },
 20068    { 0, 3, "day",    5373485.0,      86400000.0                  },
 20069    { 1, 5, "month",  176546.0,       30.0*86400000.0             },
 20070    { 2, 4, "year",   14713.0,        365.0*86400000.0            },
 20071  };
 20072  
 20073  /*
 20074  ** Process a modifier to a date-time stamp.  The modifiers are
 20075  ** as follows:
 20076  **
 20077  **     NNN days
 20078  **     NNN hours
 20079  **     NNN minutes
 20080  **     NNN.NNNN seconds
 20081  **     NNN months
 20082  **     NNN years
 20083  **     start of month
 20084  **     start of year
 20085  **     start of week
 20086  **     start of day
 20087  **     weekday N
 20088  **     unixepoch
 20089  **     localtime
 20090  **     utc
 20091  **
 20092  ** Return 0 on success and 1 if there is any kind of error. If the error
 20093  ** is in a system call (i.e. localtime()), then an error message is written
 20094  ** to context pCtx. If the error is an unrecognized modifier, no error is
 20095  ** written to pCtx.
 20096  */
 20097  static int parseModifier(
 20098    sqlite3_context *pCtx,      /* Function context */
 20099    const char *z,              /* The text of the modifier */
 20100    int n,                      /* Length of zMod in bytes */
 20101    DateTime *p                 /* The date/time value to be modified */
 20102  ){
 20103    int rc = 1;
 20104    double r;
 20105    switch(sqlite3UpperToLower[(u8)z[0]] ){
 20106  #ifndef SQLITE_OMIT_LOCALTIME
 20107      case 'l': {
 20108        /*    localtime
 20109        **
 20110        ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
 20111        ** show local time.
 20112        */
 20113        if( sqlite3_stricmp(z, "localtime")==0 && sqlite3NotPureFunc(pCtx) ){
 20114          computeJD(p);
 20115          p->iJD += localtimeOffset(p, pCtx, &rc);
 20116          clearYMD_HMS_TZ(p);
 20117        }
 20118        break;
 20119      }
 20120  #endif
 20121      case 'u': {
 20122        /*
 20123        **    unixepoch
 20124        **
 20125        ** Treat the current value of p->s as the number of
 20126        ** seconds since 1970.  Convert to a real julian day number.
 20127        */
 20128        if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
 20129          r = p->s*1000.0 + 210866760000000.0;
 20130          if( r>=0.0 && r<464269060800000.0 ){
 20131            clearYMD_HMS_TZ(p);
 20132            p->iJD = (sqlite3_int64)r;
 20133            p->validJD = 1;
 20134            p->rawS = 0;
 20135            rc = 0;
 20136          }
 20137        }
 20138  #ifndef SQLITE_OMIT_LOCALTIME
 20139        else if( sqlite3_stricmp(z, "utc")==0 && sqlite3NotPureFunc(pCtx) ){
 20140          if( p->tzSet==0 ){
 20141            sqlite3_int64 c1;
 20142            computeJD(p);
 20143            c1 = localtimeOffset(p, pCtx, &rc);
 20144            if( rc==SQLITE_OK ){
 20145              p->iJD -= c1;
 20146              clearYMD_HMS_TZ(p);
 20147              p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
 20148            }
 20149            p->tzSet = 1;
 20150          }else{
 20151            rc = SQLITE_OK;
 20152          }
 20153        }
 20154  #endif
 20155        break;
 20156      }
 20157      case 'w': {
 20158        /*
 20159        **    weekday N
 20160        **
 20161        ** Move the date to the same time on the next occurrence of
 20162        ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
 20163        ** date is already on the appropriate weekday, this is a no-op.
 20164        */
 20165        if( sqlite3_strnicmp(z, "weekday ", 8)==0
 20166                 && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
 20167                 && (n=(int)r)==r && n>=0 && r<7 ){
 20168          sqlite3_int64 Z;
 20169          computeYMD_HMS(p);
 20170          p->validTZ = 0;
 20171          p->validJD = 0;
 20172          computeJD(p);
 20173          Z = ((p->iJD + 129600000)/86400000) % 7;
 20174          if( Z>n ) Z -= 7;
 20175          p->iJD += (n - Z)*86400000;
 20176          clearYMD_HMS_TZ(p);
 20177          rc = 0;
 20178        }
 20179        break;
 20180      }
 20181      case 's': {
 20182        /*
 20183        **    start of TTTTT
 20184        **
 20185        ** Move the date backwards to the beginning of the current day,
 20186        ** or month or year.
 20187        */
 20188        if( sqlite3_strnicmp(z, "start of ", 9)!=0 ) break;
 20189        if( !p->validJD && !p->validYMD && !p->validHMS ) break;
 20190        z += 9;
 20191        computeYMD(p);
 20192        p->validHMS = 1;
 20193        p->h = p->m = 0;
 20194        p->s = 0.0;
 20195        p->rawS = 0;
 20196        p->validTZ = 0;
 20197        p->validJD = 0;
 20198        if( sqlite3_stricmp(z,"month")==0 ){
 20199          p->D = 1;
 20200          rc = 0;
 20201        }else if( sqlite3_stricmp(z,"year")==0 ){
 20202          p->M = 1;
 20203          p->D = 1;
 20204          rc = 0;
 20205        }else if( sqlite3_stricmp(z,"day")==0 ){
 20206          rc = 0;
 20207        }
 20208        break;
 20209      }
 20210      case '+':
 20211      case '-':
 20212      case '0':
 20213      case '1':
 20214      case '2':
 20215      case '3':
 20216      case '4':
 20217      case '5':
 20218      case '6':
 20219      case '7':
 20220      case '8':
 20221      case '9': {
 20222        double rRounder;
 20223        int i;
 20224        for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
 20225        if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
 20226          rc = 1;
 20227          break;
 20228        }
 20229        if( z[n]==':' ){
 20230          /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
 20231          ** specified number of hours, minutes, seconds, and fractional seconds
 20232          ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
 20233          ** omitted.
 20234          */
 20235          const char *z2 = z;
 20236          DateTime tx;
 20237          sqlite3_int64 day;
 20238          if( !sqlite3Isdigit(*z2) ) z2++;
 20239          memset(&tx, 0, sizeof(tx));
 20240          if( parseHhMmSs(z2, &tx) ) break;
 20241          computeJD(&tx);
 20242          tx.iJD -= 43200000;
 20243          day = tx.iJD/86400000;
 20244          tx.iJD -= day*86400000;
 20245          if( z[0]=='-' ) tx.iJD = -tx.iJD;
 20246          computeJD(p);
 20247          clearYMD_HMS_TZ(p);
 20248          p->iJD += tx.iJD;
 20249          rc = 0;
 20250          break;
 20251        }
 20252  
 20253        /* If control reaches this point, it means the transformation is
 20254        ** one of the forms like "+NNN days".  */
 20255        z += n;
 20256        while( sqlite3Isspace(*z) ) z++;
 20257        n = sqlite3Strlen30(z);
 20258        if( n>10 || n<3 ) break;
 20259        if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
 20260        computeJD(p);
 20261        rc = 1;
 20262        rRounder = r<0 ? -0.5 : +0.5;
 20263        for(i=0; i<ArraySize(aXformType); i++){
 20264          if( aXformType[i].nName==n
 20265           && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
 20266           && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
 20267          ){
 20268            switch( aXformType[i].eType ){
 20269              case 1: { /* Special processing to add months */
 20270                int x;
 20271                computeYMD_HMS(p);
 20272                p->M += (int)r;
 20273                x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
 20274                p->Y += x;
 20275                p->M -= x*12;
 20276                p->validJD = 0;
 20277                r -= (int)r;
 20278                break;
 20279              }
 20280              case 2: { /* Special processing to add years */
 20281                int y = (int)r;
 20282                computeYMD_HMS(p);
 20283                p->Y += y;
 20284                p->validJD = 0;
 20285                r -= (int)r;
 20286                break;
 20287              }
 20288            }
 20289            computeJD(p);
 20290            p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder);
 20291            rc = 0;
 20292            break;
 20293          }
 20294        }
 20295        clearYMD_HMS_TZ(p);
 20296        break;
 20297      }
 20298      default: {
 20299        break;
 20300      }
 20301    }
 20302    return rc;
 20303  }
 20304  
 20305  /*
 20306  ** Process time function arguments.  argv[0] is a date-time stamp.
 20307  ** argv[1] and following are modifiers.  Parse them all and write
 20308  ** the resulting time into the DateTime structure p.  Return 0
 20309  ** on success and 1 if there are any errors.
 20310  **
 20311  ** If there are zero parameters (if even argv[0] is undefined)
 20312  ** then assume a default value of "now" for argv[0].
 20313  */
 20314  static int isDate(
 20315    sqlite3_context *context, 
 20316    int argc, 
 20317    sqlite3_value **argv, 
 20318    DateTime *p
 20319  ){
 20320    int i, n;
 20321    const unsigned char *z;
 20322    int eType;
 20323    memset(p, 0, sizeof(*p));
 20324    if( argc==0 ){
 20325      return setDateTimeToCurrent(context, p);
 20326    }
 20327    if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
 20328                     || eType==SQLITE_INTEGER ){
 20329      setRawDateNumber(p, sqlite3_value_double(argv[0]));
 20330    }else{
 20331      z = sqlite3_value_text(argv[0]);
 20332      if( !z || parseDateOrTime(context, (char*)z, p) ){
 20333        return 1;
 20334      }
 20335    }
 20336    for(i=1; i<argc; i++){
 20337      z = sqlite3_value_text(argv[i]);
 20338      n = sqlite3_value_bytes(argv[i]);
 20339      if( z==0 || parseModifier(context, (char*)z, n, p) ) return 1;
 20340    }
 20341    computeJD(p);
 20342    if( p->isError || !validJulianDay(p->iJD) ) return 1;
 20343    return 0;
 20344  }
 20345  
 20346  
 20347  /*
 20348  ** The following routines implement the various date and time functions
 20349  ** of SQLite.
 20350  */
 20351  
 20352  /*
 20353  **    julianday( TIMESTRING, MOD, MOD, ...)
 20354  **
 20355  ** Return the julian day number of the date specified in the arguments
 20356  */
 20357  static void juliandayFunc(
 20358    sqlite3_context *context,
 20359    int argc,
 20360    sqlite3_value **argv
 20361  ){
 20362    DateTime x;
 20363    if( isDate(context, argc, argv, &x)==0 ){
 20364      computeJD(&x);
 20365      sqlite3_result_double(context, x.iJD/86400000.0);
 20366    }
 20367  }
 20368  
 20369  /*
 20370  **    datetime( TIMESTRING, MOD, MOD, ...)
 20371  **
 20372  ** Return YYYY-MM-DD HH:MM:SS
 20373  */
 20374  static void datetimeFunc(
 20375    sqlite3_context *context,
 20376    int argc,
 20377    sqlite3_value **argv
 20378  ){
 20379    DateTime x;
 20380    if( isDate(context, argc, argv, &x)==0 ){
 20381      char zBuf[100];
 20382      computeYMD_HMS(&x);
 20383      sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
 20384                       x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
 20385      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
 20386    }
 20387  }
 20388  
 20389  /*
 20390  **    time( TIMESTRING, MOD, MOD, ...)
 20391  **
 20392  ** Return HH:MM:SS
 20393  */
 20394  static void timeFunc(
 20395    sqlite3_context *context,
 20396    int argc,
 20397    sqlite3_value **argv
 20398  ){
 20399    DateTime x;
 20400    if( isDate(context, argc, argv, &x)==0 ){
 20401      char zBuf[100];
 20402      computeHMS(&x);
 20403      sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
 20404      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
 20405    }
 20406  }
 20407  
 20408  /*
 20409  **    date( TIMESTRING, MOD, MOD, ...)
 20410  **
 20411  ** Return YYYY-MM-DD
 20412  */
 20413  static void dateFunc(
 20414    sqlite3_context *context,
 20415    int argc,
 20416    sqlite3_value **argv
 20417  ){
 20418    DateTime x;
 20419    if( isDate(context, argc, argv, &x)==0 ){
 20420      char zBuf[100];
 20421      computeYMD(&x);
 20422      sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
 20423      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
 20424    }
 20425  }
 20426  
 20427  /*
 20428  **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
 20429  **
 20430  ** Return a string described by FORMAT.  Conversions as follows:
 20431  **
 20432  **   %d  day of month
 20433  **   %f  ** fractional seconds  SS.SSS
 20434  **   %H  hour 00-24
 20435  **   %j  day of year 000-366
 20436  **   %J  ** julian day number
 20437  **   %m  month 01-12
 20438  **   %M  minute 00-59
 20439  **   %s  seconds since 1970-01-01
 20440  **   %S  seconds 00-59
 20441  **   %w  day of week 0-6  sunday==0
 20442  **   %W  week of year 00-53
 20443  **   %Y  year 0000-9999
 20444  **   %%  %
 20445  */
 20446  static void strftimeFunc(
 20447    sqlite3_context *context,
 20448    int argc,
 20449    sqlite3_value **argv
 20450  ){
 20451    DateTime x;
 20452    u64 n;
 20453    size_t i,j;
 20454    char *z;
 20455    sqlite3 *db;
 20456    const char *zFmt;
 20457    char zBuf[100];
 20458    if( argc==0 ) return;
 20459    zFmt = (const char*)sqlite3_value_text(argv[0]);
 20460    if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
 20461    db = sqlite3_context_db_handle(context);
 20462    for(i=0, n=1; zFmt[i]; i++, n++){
 20463      if( zFmt[i]=='%' ){
 20464        switch( zFmt[i+1] ){
 20465          case 'd':
 20466          case 'H':
 20467          case 'm':
 20468          case 'M':
 20469          case 'S':
 20470          case 'W':
 20471            n++;
 20472            /* fall thru */
 20473          case 'w':
 20474          case '%':
 20475            break;
 20476          case 'f':
 20477            n += 8;
 20478            break;
 20479          case 'j':
 20480            n += 3;
 20481            break;
 20482          case 'Y':
 20483            n += 8;
 20484            break;
 20485          case 's':
 20486          case 'J':
 20487            n += 50;
 20488            break;
 20489          default:
 20490            return;  /* ERROR.  return a NULL */
 20491        }
 20492        i++;
 20493      }
 20494    }
 20495    testcase( n==sizeof(zBuf)-1 );
 20496    testcase( n==sizeof(zBuf) );
 20497    testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
 20498    testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
 20499    if( n<sizeof(zBuf) ){
 20500      z = zBuf;
 20501    }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
 20502      sqlite3_result_error_toobig(context);
 20503      return;
 20504    }else{
 20505      z = sqlite3DbMallocRawNN(db, (int)n);
 20506      if( z==0 ){
 20507        sqlite3_result_error_nomem(context);
 20508        return;
 20509      }
 20510    }
 20511    computeJD(&x);
 20512    computeYMD_HMS(&x);
 20513    for(i=j=0; zFmt[i]; i++){
 20514      if( zFmt[i]!='%' ){
 20515        z[j++] = zFmt[i];
 20516      }else{
 20517        i++;
 20518        switch( zFmt[i] ){
 20519          case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
 20520          case 'f': {
 20521            double s = x.s;
 20522            if( s>59.999 ) s = 59.999;
 20523            sqlite3_snprintf(7, &z[j],"%06.3f", s);
 20524            j += sqlite3Strlen30(&z[j]);
 20525            break;
 20526          }
 20527          case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
 20528          case 'W': /* Fall thru */
 20529          case 'j': {
 20530            int nDay;             /* Number of days since 1st day of year */
 20531            DateTime y = x;
 20532            y.validJD = 0;
 20533            y.M = 1;
 20534            y.D = 1;
 20535            computeJD(&y);
 20536            nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
 20537            if( zFmt[i]=='W' ){
 20538              int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
 20539              wd = (int)(((x.iJD+43200000)/86400000)%7);
 20540              sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
 20541              j += 2;
 20542            }else{
 20543              sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
 20544              j += 3;
 20545            }
 20546            break;
 20547          }
 20548          case 'J': {
 20549            sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
 20550            j+=sqlite3Strlen30(&z[j]);
 20551            break;
 20552          }
 20553          case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
 20554          case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
 20555          case 's': {
 20556            sqlite3_snprintf(30,&z[j],"%lld",
 20557                             (i64)(x.iJD/1000 - 21086676*(i64)10000));
 20558            j += sqlite3Strlen30(&z[j]);
 20559            break;
 20560          }
 20561          case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
 20562          case 'w': {
 20563            z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
 20564            break;
 20565          }
 20566          case 'Y': {
 20567            sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
 20568            break;
 20569          }
 20570          default:   z[j++] = '%'; break;
 20571        }
 20572      }
 20573    }
 20574    z[j] = 0;
 20575    sqlite3_result_text(context, z, -1,
 20576                        z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
 20577  }
 20578  
 20579  /*
 20580  ** current_time()
 20581  **
 20582  ** This function returns the same value as time('now').
 20583  */
 20584  static void ctimeFunc(
 20585    sqlite3_context *context,
 20586    int NotUsed,
 20587    sqlite3_value **NotUsed2
 20588  ){
 20589    UNUSED_PARAMETER2(NotUsed, NotUsed2);
 20590    timeFunc(context, 0, 0);
 20591  }
 20592  
 20593  /*
 20594  ** current_date()
 20595  **
 20596  ** This function returns the same value as date('now').
 20597  */
 20598  static void cdateFunc(
 20599    sqlite3_context *context,
 20600    int NotUsed,
 20601    sqlite3_value **NotUsed2
 20602  ){
 20603    UNUSED_PARAMETER2(NotUsed, NotUsed2);
 20604    dateFunc(context, 0, 0);
 20605  }
 20606  
 20607  /*
 20608  ** current_timestamp()
 20609  **
 20610  ** This function returns the same value as datetime('now').
 20611  */
 20612  static void ctimestampFunc(
 20613    sqlite3_context *context,
 20614    int NotUsed,
 20615    sqlite3_value **NotUsed2
 20616  ){
 20617    UNUSED_PARAMETER2(NotUsed, NotUsed2);
 20618    datetimeFunc(context, 0, 0);
 20619  }
 20620  #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
 20621  
 20622  #ifdef SQLITE_OMIT_DATETIME_FUNCS
 20623  /*
 20624  ** If the library is compiled to omit the full-scale date and time
 20625  ** handling (to get a smaller binary), the following minimal version
 20626  ** of the functions current_time(), current_date() and current_timestamp()
 20627  ** are included instead. This is to support column declarations that
 20628  ** include "DEFAULT CURRENT_TIME" etc.
 20629  **
 20630  ** This function uses the C-library functions time(), gmtime()
 20631  ** and strftime(). The format string to pass to strftime() is supplied
 20632  ** as the user-data for the function.
 20633  */
 20634  static void currentTimeFunc(
 20635    sqlite3_context *context,
 20636    int argc,
 20637    sqlite3_value **argv
 20638  ){
 20639    time_t t;
 20640    char *zFormat = (char *)sqlite3_user_data(context);
 20641    sqlite3_int64 iT;
 20642    struct tm *pTm;
 20643    struct tm sNow;
 20644    char zBuf[20];
 20645  
 20646    UNUSED_PARAMETER(argc);
 20647    UNUSED_PARAMETER(argv);
 20648  
 20649    iT = sqlite3StmtCurrentTime(context);
 20650    if( iT<=0 ) return;
 20651    t = iT/1000 - 10000*(sqlite3_int64)21086676;
 20652  #if HAVE_GMTIME_R
 20653    pTm = gmtime_r(&t, &sNow);
 20654  #else
 20655    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
 20656    pTm = gmtime(&t);
 20657    if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
 20658    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
 20659  #endif
 20660    if( pTm ){
 20661      strftime(zBuf, 20, zFormat, &sNow);
 20662      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
 20663    }
 20664  }
 20665  #endif
 20666  
 20667  /*
 20668  ** This function registered all of the above C functions as SQL
 20669  ** functions.  This should be the only routine in this file with
 20670  ** external linkage.
 20671  */
 20672  SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
 20673    static FuncDef aDateTimeFuncs[] = {
 20674  #ifndef SQLITE_OMIT_DATETIME_FUNCS
 20675      PURE_DATE(julianday,        -1, 0, 0, juliandayFunc ),
 20676      PURE_DATE(date,             -1, 0, 0, dateFunc      ),
 20677      PURE_DATE(time,             -1, 0, 0, timeFunc      ),
 20678      PURE_DATE(datetime,         -1, 0, 0, datetimeFunc  ),
 20679      PURE_DATE(strftime,         -1, 0, 0, strftimeFunc  ),
 20680      DFUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
 20681      DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
 20682      DFUNCTION(current_date,      0, 0, 0, cdateFunc     ),
 20683  #else
 20684      STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
 20685      STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
 20686      STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
 20687  #endif
 20688    };
 20689    sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
 20690  }
 20691  
 20692  /************** End of date.c ************************************************/
 20693  /************** Begin file os.c **********************************************/
 20694  /*
 20695  ** 2005 November 29
 20696  **
 20697  ** The author disclaims copyright to this source code.  In place of
 20698  ** a legal notice, here is a blessing:
 20699  **
 20700  **    May you do good and not evil.
 20701  **    May you find forgiveness for yourself and forgive others.
 20702  **    May you share freely, never taking more than you give.
 20703  **
 20704  ******************************************************************************
 20705  **
 20706  ** This file contains OS interface code that is common to all
 20707  ** architectures.
 20708  */
 20709  /* #include "sqliteInt.h" */
 20710  
 20711  /*
 20712  ** If we compile with the SQLITE_TEST macro set, then the following block
 20713  ** of code will give us the ability to simulate a disk I/O error.  This
 20714  ** is used for testing the I/O recovery logic.
 20715  */
 20716  #if defined(SQLITE_TEST)
 20717  SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
 20718  SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
 20719  SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
 20720  SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
 20721  SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
 20722  SQLITE_API int sqlite3_diskfull_pending = 0;
 20723  SQLITE_API int sqlite3_diskfull = 0;
 20724  #endif /* defined(SQLITE_TEST) */
 20725  
 20726  /*
 20727  ** When testing, also keep a count of the number of open files.
 20728  */
 20729  #if defined(SQLITE_TEST)
 20730  SQLITE_API int sqlite3_open_file_count = 0;
 20731  #endif /* defined(SQLITE_TEST) */
 20732  
 20733  /*
 20734  ** The default SQLite sqlite3_vfs implementations do not allocate
 20735  ** memory (actually, os_unix.c allocates a small amount of memory
 20736  ** from within OsOpen()), but some third-party implementations may.
 20737  ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
 20738  ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
 20739  **
 20740  ** The following functions are instrumented for malloc() failure
 20741  ** testing:
 20742  **
 20743  **     sqlite3OsRead()
 20744  **     sqlite3OsWrite()
 20745  **     sqlite3OsSync()
 20746  **     sqlite3OsFileSize()
 20747  **     sqlite3OsLock()
 20748  **     sqlite3OsCheckReservedLock()
 20749  **     sqlite3OsFileControl()
 20750  **     sqlite3OsShmMap()
 20751  **     sqlite3OsOpen()
 20752  **     sqlite3OsDelete()
 20753  **     sqlite3OsAccess()
 20754  **     sqlite3OsFullPathname()
 20755  **
 20756  */
 20757  #if defined(SQLITE_TEST)
 20758  SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
 20759    #define DO_OS_MALLOC_TEST(x)                                       \
 20760    if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
 20761      void *pTstAlloc = sqlite3Malloc(10);                             \
 20762      if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT;                  \
 20763      sqlite3_free(pTstAlloc);                                         \
 20764    }
 20765  #else
 20766    #define DO_OS_MALLOC_TEST(x)
 20767  #endif
 20768  
 20769  /*
 20770  ** The following routines are convenience wrappers around methods
 20771  ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
 20772  ** of this would be completely automatic if SQLite were coded using
 20773  ** C++ instead of plain old C.
 20774  */
 20775  SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
 20776    if( pId->pMethods ){
 20777      pId->pMethods->xClose(pId);
 20778      pId->pMethods = 0;
 20779    }
 20780  }
 20781  SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
 20782    DO_OS_MALLOC_TEST(id);
 20783    return id->pMethods->xRead(id, pBuf, amt, offset);
 20784  }
 20785  SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
 20786    DO_OS_MALLOC_TEST(id);
 20787    return id->pMethods->xWrite(id, pBuf, amt, offset);
 20788  }
 20789  SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
 20790    return id->pMethods->xTruncate(id, size);
 20791  }
 20792  SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
 20793    DO_OS_MALLOC_TEST(id);
 20794    return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK;
 20795  }
 20796  SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
 20797    DO_OS_MALLOC_TEST(id);
 20798    return id->pMethods->xFileSize(id, pSize);
 20799  }
 20800  SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
 20801    DO_OS_MALLOC_TEST(id);
 20802    return id->pMethods->xLock(id, lockType);
 20803  }
 20804  SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
 20805    return id->pMethods->xUnlock(id, lockType);
 20806  }
 20807  SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
 20808    DO_OS_MALLOC_TEST(id);
 20809    return id->pMethods->xCheckReservedLock(id, pResOut);
 20810  }
 20811  
 20812  /*
 20813  ** Use sqlite3OsFileControl() when we are doing something that might fail
 20814  ** and we need to know about the failures.  Use sqlite3OsFileControlHint()
 20815  ** when simply tossing information over the wall to the VFS and we do not
 20816  ** really care if the VFS receives and understands the information since it
 20817  ** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
 20818  ** routine has no return value since the return value would be meaningless.
 20819  */
 20820  SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
 20821  #ifdef SQLITE_TEST
 20822    if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
 20823      /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
 20824      ** is using a regular VFS, it is called after the corresponding
 20825      ** transaction has been committed. Injecting a fault at this point
 20826      ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
 20827      ** but the transaction is committed anyway.
 20828      **
 20829      ** The core must call OsFileControl() though, not OsFileControlHint(),
 20830      ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
 20831      ** means the commit really has failed and an error should be returned
 20832      ** to the user.  */
 20833      DO_OS_MALLOC_TEST(id);
 20834    }
 20835  #endif
 20836    return id->pMethods->xFileControl(id, op, pArg);
 20837  }
 20838  SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
 20839    (void)id->pMethods->xFileControl(id, op, pArg);
 20840  }
 20841  
 20842  SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
 20843    int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
 20844    return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
 20845  }
 20846  SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
 20847    return id->pMethods->xDeviceCharacteristics(id);
 20848  }
 20849  #ifndef SQLITE_OMIT_WAL
 20850  SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
 20851    return id->pMethods->xShmLock(id, offset, n, flags);
 20852  }
 20853  SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
 20854    id->pMethods->xShmBarrier(id);
 20855  }
 20856  SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
 20857    return id->pMethods->xShmUnmap(id, deleteFlag);
 20858  }
 20859  SQLITE_PRIVATE int sqlite3OsShmMap(
 20860    sqlite3_file *id,               /* Database file handle */
 20861    int iPage,
 20862    int pgsz,
 20863    int bExtend,                    /* True to extend file if necessary */
 20864    void volatile **pp              /* OUT: Pointer to mapping */
 20865  ){
 20866    DO_OS_MALLOC_TEST(id);
 20867    return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
 20868  }
 20869  #endif /* SQLITE_OMIT_WAL */
 20870  
 20871  #if SQLITE_MAX_MMAP_SIZE>0
 20872  /* The real implementation of xFetch and xUnfetch */
 20873  SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
 20874    DO_OS_MALLOC_TEST(id);
 20875    return id->pMethods->xFetch(id, iOff, iAmt, pp);
 20876  }
 20877  SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
 20878    return id->pMethods->xUnfetch(id, iOff, p);
 20879  }
 20880  #else
 20881  /* No-op stubs to use when memory-mapped I/O is disabled */
 20882  SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
 20883    *pp = 0;
 20884    return SQLITE_OK;
 20885  }
 20886  SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
 20887    return SQLITE_OK;
 20888  }
 20889  #endif
 20890  
 20891  /*
 20892  ** The next group of routines are convenience wrappers around the
 20893  ** VFS methods.
 20894  */
 20895  SQLITE_PRIVATE int sqlite3OsOpen(
 20896    sqlite3_vfs *pVfs,
 20897    const char *zPath,
 20898    sqlite3_file *pFile,
 20899    int flags,
 20900    int *pFlagsOut
 20901  ){
 20902    int rc;
 20903    DO_OS_MALLOC_TEST(0);
 20904    /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
 20905    ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
 20906    ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
 20907    ** reaching the VFS. */
 20908    rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
 20909    assert( rc==SQLITE_OK || pFile->pMethods==0 );
 20910    return rc;
 20911  }
 20912  SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
 20913    DO_OS_MALLOC_TEST(0);
 20914    assert( dirSync==0 || dirSync==1 );
 20915    return pVfs->xDelete(pVfs, zPath, dirSync);
 20916  }
 20917  SQLITE_PRIVATE int sqlite3OsAccess(
 20918    sqlite3_vfs *pVfs,
 20919    const char *zPath,
 20920    int flags,
 20921    int *pResOut
 20922  ){
 20923    DO_OS_MALLOC_TEST(0);
 20924    return pVfs->xAccess(pVfs, zPath, flags, pResOut);
 20925  }
 20926  SQLITE_PRIVATE int sqlite3OsFullPathname(
 20927    sqlite3_vfs *pVfs,
 20928    const char *zPath,
 20929    int nPathOut,
 20930    char *zPathOut
 20931  ){
 20932    DO_OS_MALLOC_TEST(0);
 20933    zPathOut[0] = 0;
 20934    return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
 20935  }
 20936  #ifndef SQLITE_OMIT_LOAD_EXTENSION
 20937  SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
 20938    return pVfs->xDlOpen(pVfs, zPath);
 20939  }
 20940  SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
 20941    pVfs->xDlError(pVfs, nByte, zBufOut);
 20942  }
 20943  SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
 20944    return pVfs->xDlSym(pVfs, pHdle, zSym);
 20945  }
 20946  SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
 20947    pVfs->xDlClose(pVfs, pHandle);
 20948  }
 20949  #endif /* SQLITE_OMIT_LOAD_EXTENSION */
 20950  SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
 20951    return pVfs->xRandomness(pVfs, nByte, zBufOut);
 20952  }
 20953  SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
 20954    return pVfs->xSleep(pVfs, nMicro);
 20955  }
 20956  SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
 20957    return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
 20958  }
 20959  SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
 20960    int rc;
 20961    /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
 20962    ** method to get the current date and time if that method is available
 20963    ** (if iVersion is 2 or greater and the function pointer is not NULL) and
 20964    ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
 20965    ** unavailable.
 20966    */
 20967    if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
 20968      rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
 20969    }else{
 20970      double r;
 20971      rc = pVfs->xCurrentTime(pVfs, &r);
 20972      *pTimeOut = (sqlite3_int64)(r*86400000.0);
 20973    }
 20974    return rc;
 20975  }
 20976  
 20977  SQLITE_PRIVATE int sqlite3OsOpenMalloc(
 20978    sqlite3_vfs *pVfs,
 20979    const char *zFile,
 20980    sqlite3_file **ppFile,
 20981    int flags,
 20982    int *pOutFlags
 20983  ){
 20984    int rc;
 20985    sqlite3_file *pFile;
 20986    pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
 20987    if( pFile ){
 20988      rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
 20989      if( rc!=SQLITE_OK ){
 20990        sqlite3_free(pFile);
 20991      }else{
 20992        *ppFile = pFile;
 20993      }
 20994    }else{
 20995      rc = SQLITE_NOMEM_BKPT;
 20996    }
 20997    return rc;
 20998  }
 20999  SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
 21000    assert( pFile );
 21001    sqlite3OsClose(pFile);
 21002    sqlite3_free(pFile);
 21003  }
 21004  
 21005  /*
 21006  ** This function is a wrapper around the OS specific implementation of
 21007  ** sqlite3_os_init(). The purpose of the wrapper is to provide the
 21008  ** ability to simulate a malloc failure, so that the handling of an
 21009  ** error in sqlite3_os_init() by the upper layers can be tested.
 21010  */
 21011  SQLITE_PRIVATE int sqlite3OsInit(void){
 21012    void *p = sqlite3_malloc(10);
 21013    if( p==0 ) return SQLITE_NOMEM_BKPT;
 21014    sqlite3_free(p);
 21015    return sqlite3_os_init();
 21016  }
 21017  
 21018  /*
 21019  ** The list of all registered VFS implementations.
 21020  */
 21021  static sqlite3_vfs * SQLITE_WSD vfsList = 0;
 21022  #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
 21023  
 21024  /*
 21025  ** Locate a VFS by name.  If no name is given, simply return the
 21026  ** first VFS on the list.
 21027  */
 21028  SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
 21029    sqlite3_vfs *pVfs = 0;
 21030  #if SQLITE_THREADSAFE
 21031    sqlite3_mutex *mutex;
 21032  #endif
 21033  #ifndef SQLITE_OMIT_AUTOINIT
 21034    int rc = sqlite3_initialize();
 21035    if( rc ) return 0;
 21036  #endif
 21037  #if SQLITE_THREADSAFE
 21038    mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
 21039  #endif
 21040    sqlite3_mutex_enter(mutex);
 21041    for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
 21042      if( zVfs==0 ) break;
 21043      if( strcmp(zVfs, pVfs->zName)==0 ) break;
 21044    }
 21045    sqlite3_mutex_leave(mutex);
 21046    return pVfs;
 21047  }
 21048  
 21049  /*
 21050  ** Unlink a VFS from the linked list
 21051  */
 21052  static void vfsUnlink(sqlite3_vfs *pVfs){
 21053    assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
 21054    if( pVfs==0 ){
 21055      /* No-op */
 21056    }else if( vfsList==pVfs ){
 21057      vfsList = pVfs->pNext;
 21058    }else if( vfsList ){
 21059      sqlite3_vfs *p = vfsList;
 21060      while( p->pNext && p->pNext!=pVfs ){
 21061        p = p->pNext;
 21062      }
 21063      if( p->pNext==pVfs ){
 21064        p->pNext = pVfs->pNext;
 21065      }
 21066    }
 21067  }
 21068  
 21069  /*
 21070  ** Register a VFS with the system.  It is harmless to register the same
 21071  ** VFS multiple times.  The new VFS becomes the default if makeDflt is
 21072  ** true.
 21073  */
 21074  SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
 21075    MUTEX_LOGIC(sqlite3_mutex *mutex;)
 21076  #ifndef SQLITE_OMIT_AUTOINIT
 21077    int rc = sqlite3_initialize();
 21078    if( rc ) return rc;
 21079  #endif
 21080  #ifdef SQLITE_ENABLE_API_ARMOR
 21081    if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
 21082  #endif
 21083  
 21084    MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
 21085    sqlite3_mutex_enter(mutex);
 21086    vfsUnlink(pVfs);
 21087    if( makeDflt || vfsList==0 ){
 21088      pVfs->pNext = vfsList;
 21089      vfsList = pVfs;
 21090    }else{
 21091      pVfs->pNext = vfsList->pNext;
 21092      vfsList->pNext = pVfs;
 21093    }
 21094    assert(vfsList);
 21095    sqlite3_mutex_leave(mutex);
 21096    return SQLITE_OK;
 21097  }
 21098  
 21099  /*
 21100  ** Unregister a VFS so that it is no longer accessible.
 21101  */
 21102  SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
 21103  #if SQLITE_THREADSAFE
 21104    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
 21105  #endif
 21106    sqlite3_mutex_enter(mutex);
 21107    vfsUnlink(pVfs);
 21108    sqlite3_mutex_leave(mutex);
 21109    return SQLITE_OK;
 21110  }
 21111  
 21112  /************** End of os.c **************************************************/
 21113  /************** Begin file fault.c *******************************************/
 21114  /*
 21115  ** 2008 Jan 22
 21116  **
 21117  ** The author disclaims copyright to this source code.  In place of
 21118  ** a legal notice, here is a blessing:
 21119  **
 21120  **    May you do good and not evil.
 21121  **    May you find forgiveness for yourself and forgive others.
 21122  **    May you share freely, never taking more than you give.
 21123  **
 21124  *************************************************************************
 21125  **
 21126  ** This file contains code to support the concept of "benign" 
 21127  ** malloc failures (when the xMalloc() or xRealloc() method of the
 21128  ** sqlite3_mem_methods structure fails to allocate a block of memory
 21129  ** and returns 0). 
 21130  **
 21131  ** Most malloc failures are non-benign. After they occur, SQLite
 21132  ** abandons the current operation and returns an error code (usually
 21133  ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
 21134  ** fatal. For example, if a malloc fails while resizing a hash table, this 
 21135  ** is completely recoverable simply by not carrying out the resize. The 
 21136  ** hash table will continue to function normally.  So a malloc failure 
 21137  ** during a hash table resize is a benign fault.
 21138  */
 21139  
 21140  /* #include "sqliteInt.h" */
 21141  
 21142  #ifndef SQLITE_UNTESTABLE
 21143  
 21144  /*
 21145  ** Global variables.
 21146  */
 21147  typedef struct BenignMallocHooks BenignMallocHooks;
 21148  static SQLITE_WSD struct BenignMallocHooks {
 21149    void (*xBenignBegin)(void);
 21150    void (*xBenignEnd)(void);
 21151  } sqlite3Hooks = { 0, 0 };
 21152  
 21153  /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
 21154  ** structure.  If writable static data is unsupported on the target,
 21155  ** we have to locate the state vector at run-time.  In the more common
 21156  ** case where writable static data is supported, wsdHooks can refer directly
 21157  ** to the "sqlite3Hooks" state vector declared above.
 21158  */
 21159  #ifdef SQLITE_OMIT_WSD
 21160  # define wsdHooksInit \
 21161    BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
 21162  # define wsdHooks x[0]
 21163  #else
 21164  # define wsdHooksInit
 21165  # define wsdHooks sqlite3Hooks
 21166  #endif
 21167  
 21168  
 21169  /*
 21170  ** Register hooks to call when sqlite3BeginBenignMalloc() and
 21171  ** sqlite3EndBenignMalloc() are called, respectively.
 21172  */
 21173  SQLITE_PRIVATE void sqlite3BenignMallocHooks(
 21174    void (*xBenignBegin)(void),
 21175    void (*xBenignEnd)(void)
 21176  ){
 21177    wsdHooksInit;
 21178    wsdHooks.xBenignBegin = xBenignBegin;
 21179    wsdHooks.xBenignEnd = xBenignEnd;
 21180  }
 21181  
 21182  /*
 21183  ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
 21184  ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
 21185  ** indicates that subsequent malloc failures are non-benign.
 21186  */
 21187  SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
 21188    wsdHooksInit;
 21189    if( wsdHooks.xBenignBegin ){
 21190      wsdHooks.xBenignBegin();
 21191    }
 21192  }
 21193  SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
 21194    wsdHooksInit;
 21195    if( wsdHooks.xBenignEnd ){
 21196      wsdHooks.xBenignEnd();
 21197    }
 21198  }
 21199  
 21200  #endif   /* #ifndef SQLITE_UNTESTABLE */
 21201  
 21202  /************** End of fault.c ***********************************************/
 21203  /************** Begin file mem0.c ********************************************/
 21204  /*
 21205  ** 2008 October 28
 21206  **
 21207  ** The author disclaims copyright to this source code.  In place of
 21208  ** a legal notice, here is a blessing:
 21209  **
 21210  **    May you do good and not evil.
 21211  **    May you find forgiveness for yourself and forgive others.
 21212  **    May you share freely, never taking more than you give.
 21213  **
 21214  *************************************************************************
 21215  **
 21216  ** This file contains a no-op memory allocation drivers for use when
 21217  ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
 21218  ** here always fail.  SQLite will not operate with these drivers.  These
 21219  ** are merely placeholders.  Real drivers must be substituted using
 21220  ** sqlite3_config() before SQLite will operate.
 21221  */
 21222  /* #include "sqliteInt.h" */
 21223  
 21224  /*
 21225  ** This version of the memory allocator is the default.  It is
 21226  ** used when no other memory allocator is specified using compile-time
 21227  ** macros.
 21228  */
 21229  #ifdef SQLITE_ZERO_MALLOC
 21230  
 21231  /*
 21232  ** No-op versions of all memory allocation routines
 21233  */
 21234  static void *sqlite3MemMalloc(int nByte){ return 0; }
 21235  static void sqlite3MemFree(void *pPrior){ return; }
 21236  static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
 21237  static int sqlite3MemSize(void *pPrior){ return 0; }
 21238  static int sqlite3MemRoundup(int n){ return n; }
 21239  static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
 21240  static void sqlite3MemShutdown(void *NotUsed){ return; }
 21241  
 21242  /*
 21243  ** This routine is the only routine in this file with external linkage.
 21244  **
 21245  ** Populate the low-level memory allocation function pointers in
 21246  ** sqlite3GlobalConfig.m with pointers to the routines in this file.
 21247  */
 21248  SQLITE_PRIVATE void sqlite3MemSetDefault(void){
 21249    static const sqlite3_mem_methods defaultMethods = {
 21250       sqlite3MemMalloc,
 21251       sqlite3MemFree,
 21252       sqlite3MemRealloc,
 21253       sqlite3MemSize,
 21254       sqlite3MemRoundup,
 21255       sqlite3MemInit,
 21256       sqlite3MemShutdown,
 21257       0
 21258    };
 21259    sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
 21260  }
 21261  
 21262  #endif /* SQLITE_ZERO_MALLOC */
 21263  
 21264  /************** End of mem0.c ************************************************/
 21265  /************** Begin file mem1.c ********************************************/
 21266  /*
 21267  ** 2007 August 14
 21268  **
 21269  ** The author disclaims copyright to this source code.  In place of
 21270  ** a legal notice, here is a blessing:
 21271  **
 21272  **    May you do good and not evil.
 21273  **    May you find forgiveness for yourself and forgive others.
 21274  **    May you share freely, never taking more than you give.
 21275  **
 21276  *************************************************************************
 21277  **
 21278  ** This file contains low-level memory allocation drivers for when
 21279  ** SQLite will use the standard C-library malloc/realloc/free interface
 21280  ** to obtain the memory it needs.
 21281  **
 21282  ** This file contains implementations of the low-level memory allocation
 21283  ** routines specified in the sqlite3_mem_methods object.  The content of
 21284  ** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
 21285  ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
 21286  ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
 21287  ** default configuration is to use memory allocation routines in this
 21288  ** file.
 21289  **
 21290  ** C-preprocessor macro summary:
 21291  **
 21292  **    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
 21293  **                                the malloc_usable_size() interface exists
 21294  **                                on the target platform.  Or, this symbol
 21295  **                                can be set manually, if desired.
 21296  **                                If an equivalent interface exists by
 21297  **                                a different name, using a separate -D
 21298  **                                option to rename it.
 21299  **
 21300  **    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
 21301  **                                memory allocator.  Set this symbol to enable
 21302  **                                building on older macs.
 21303  **
 21304  **    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
 21305  **                                _msize() on windows systems.  This might
 21306  **                                be necessary when compiling for Delphi,
 21307  **                                for example.
 21308  */
 21309  /* #include "sqliteInt.h" */
 21310  
 21311  /*
 21312  ** This version of the memory allocator is the default.  It is
 21313  ** used when no other memory allocator is specified using compile-time
 21314  ** macros.
 21315  */
 21316  #ifdef SQLITE_SYSTEM_MALLOC
 21317  #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
 21318  
 21319  /*
 21320  ** Use the zone allocator available on apple products unless the
 21321  ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
 21322  */
 21323  #include <sys/sysctl.h>
 21324  #include <malloc/malloc.h>
 21325  #ifdef SQLITE_MIGHT_BE_SINGLE_CORE
 21326  #include <libkern/OSAtomic.h>
 21327  #endif /* SQLITE_MIGHT_BE_SINGLE_CORE */
 21328  static malloc_zone_t* _sqliteZone_;
 21329  #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
 21330  #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
 21331  #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
 21332  #define SQLITE_MALLOCSIZE(x) \
 21333          (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
 21334  
 21335  #else /* if not __APPLE__ */
 21336  
 21337  /*
 21338  ** Use standard C library malloc and free on non-Apple systems.  
 21339  ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
 21340  */
 21341  #define SQLITE_MALLOC(x)             malloc(x)
 21342  #define SQLITE_FREE(x)               free(x)
 21343  #define SQLITE_REALLOC(x,y)          realloc((x),(y))
 21344  
 21345  /*
 21346  ** The malloc.h header file is needed for malloc_usable_size() function
 21347  ** on some systems (e.g. Linux).
 21348  */
 21349  #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
 21350  #  define SQLITE_USE_MALLOC_H 1
 21351  #  define SQLITE_USE_MALLOC_USABLE_SIZE 1
 21352  /*
 21353  ** The MSVCRT has malloc_usable_size(), but it is called _msize().  The
 21354  ** use of _msize() is automatic, but can be disabled by compiling with
 21355  ** -DSQLITE_WITHOUT_MSIZE.  Using the _msize() function also requires
 21356  ** the malloc.h header file.
 21357  */
 21358  #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
 21359  #  define SQLITE_USE_MALLOC_H
 21360  #  define SQLITE_USE_MSIZE
 21361  #endif
 21362  
 21363  /*
 21364  ** Include the malloc.h header file, if necessary.  Also set define macro
 21365  ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
 21366  ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
 21367  ** The memory size function can always be overridden manually by defining
 21368  ** the macro SQLITE_MALLOCSIZE to the desired function name.
 21369  */
 21370  #if defined(SQLITE_USE_MALLOC_H)
 21371  #  include <malloc.h>
 21372  #  if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
 21373  #    if !defined(SQLITE_MALLOCSIZE)
 21374  #      define SQLITE_MALLOCSIZE(x)   malloc_usable_size(x)
 21375  #    endif
 21376  #  elif defined(SQLITE_USE_MSIZE)
 21377  #    if !defined(SQLITE_MALLOCSIZE)
 21378  #      define SQLITE_MALLOCSIZE      _msize
 21379  #    endif
 21380  #  endif
 21381  #endif /* defined(SQLITE_USE_MALLOC_H) */
 21382  
 21383  #endif /* __APPLE__ or not __APPLE__ */
 21384  
 21385  /*
 21386  ** Like malloc(), but remember the size of the allocation
 21387  ** so that we can find it later using sqlite3MemSize().
 21388  **
 21389  ** For this low-level routine, we are guaranteed that nByte>0 because
 21390  ** cases of nByte<=0 will be intercepted and dealt with by higher level
 21391  ** routines.
 21392  */
 21393  static void *sqlite3MemMalloc(int nByte){
 21394  #ifdef SQLITE_MALLOCSIZE
 21395    void *p;
 21396    testcase( ROUND8(nByte)==nByte );
 21397    p = SQLITE_MALLOC( nByte );
 21398    if( p==0 ){
 21399      testcase( sqlite3GlobalConfig.xLog!=0 );
 21400      sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
 21401    }
 21402    return p;
 21403  #else
 21404    sqlite3_int64 *p;
 21405    assert( nByte>0 );
 21406    testcase( ROUND8(nByte)!=nByte );
 21407    p = SQLITE_MALLOC( nByte+8 );
 21408    if( p ){
 21409      p[0] = nByte;
 21410      p++;
 21411    }else{
 21412      testcase( sqlite3GlobalConfig.xLog!=0 );
 21413      sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
 21414    }
 21415    return (void *)p;
 21416  #endif
 21417  }
 21418  
 21419  /*
 21420  ** Like free() but works for allocations obtained from sqlite3MemMalloc()
 21421  ** or sqlite3MemRealloc().
 21422  **
 21423  ** For this low-level routine, we already know that pPrior!=0 since
 21424  ** cases where pPrior==0 will have been intecepted and dealt with
 21425  ** by higher-level routines.
 21426  */
 21427  static void sqlite3MemFree(void *pPrior){
 21428  #ifdef SQLITE_MALLOCSIZE
 21429    SQLITE_FREE(pPrior);
 21430  #else
 21431    sqlite3_int64 *p = (sqlite3_int64*)pPrior;
 21432    assert( pPrior!=0 );
 21433    p--;
 21434    SQLITE_FREE(p);
 21435  #endif
 21436  }
 21437  
 21438  /*
 21439  ** Report the allocated size of a prior return from xMalloc()
 21440  ** or xRealloc().
 21441  */
 21442  static int sqlite3MemSize(void *pPrior){
 21443  #ifdef SQLITE_MALLOCSIZE
 21444    assert( pPrior!=0 );
 21445    return (int)SQLITE_MALLOCSIZE(pPrior);
 21446  #else
 21447    sqlite3_int64 *p;
 21448    assert( pPrior!=0 );
 21449    p = (sqlite3_int64*)pPrior;
 21450    p--;
 21451    return (int)p[0];
 21452  #endif
 21453  }
 21454  
 21455  /*
 21456  ** Like realloc().  Resize an allocation previously obtained from
 21457  ** sqlite3MemMalloc().
 21458  **
 21459  ** For this low-level interface, we know that pPrior!=0.  Cases where
 21460  ** pPrior==0 while have been intercepted by higher-level routine and
 21461  ** redirected to xMalloc.  Similarly, we know that nByte>0 because
 21462  ** cases where nByte<=0 will have been intercepted by higher-level
 21463  ** routines and redirected to xFree.
 21464  */
 21465  static void *sqlite3MemRealloc(void *pPrior, int nByte){
 21466  #ifdef SQLITE_MALLOCSIZE
 21467    void *p = SQLITE_REALLOC(pPrior, nByte);
 21468    if( p==0 ){
 21469      testcase( sqlite3GlobalConfig.xLog!=0 );
 21470      sqlite3_log(SQLITE_NOMEM,
 21471        "failed memory resize %u to %u bytes",
 21472        SQLITE_MALLOCSIZE(pPrior), nByte);
 21473    }
 21474    return p;
 21475  #else
 21476    sqlite3_int64 *p = (sqlite3_int64*)pPrior;
 21477    assert( pPrior!=0 && nByte>0 );
 21478    assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
 21479    p--;
 21480    p = SQLITE_REALLOC(p, nByte+8 );
 21481    if( p ){
 21482      p[0] = nByte;
 21483      p++;
 21484    }else{
 21485      testcase( sqlite3GlobalConfig.xLog!=0 );
 21486      sqlite3_log(SQLITE_NOMEM,
 21487        "failed memory resize %u to %u bytes",
 21488        sqlite3MemSize(pPrior), nByte);
 21489    }
 21490    return (void*)p;
 21491  #endif
 21492  }
 21493  
 21494  /*
 21495  ** Round up a request size to the next valid allocation size.
 21496  */
 21497  static int sqlite3MemRoundup(int n){
 21498    return ROUND8(n);
 21499  }
 21500  
 21501  /*
 21502  ** Initialize this module.
 21503  */
 21504  static int sqlite3MemInit(void *NotUsed){
 21505  #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
 21506    int cpuCount;
 21507    size_t len;
 21508    if( _sqliteZone_ ){
 21509      return SQLITE_OK;
 21510    }
 21511    len = sizeof(cpuCount);
 21512    /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
 21513    sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
 21514    if( cpuCount>1 ){
 21515      /* defer MT decisions to system malloc */
 21516      _sqliteZone_ = malloc_default_zone();
 21517    }else{
 21518      /* only 1 core, use our own zone to contention over global locks, 
 21519      ** e.g. we have our own dedicated locks */
 21520      _sqliteZone_ = malloc_create_zone(4096, 0);
 21521      malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap");
 21522    }
 21523  #endif /*  defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */
 21524    UNUSED_PARAMETER(NotUsed);
 21525    return SQLITE_OK;
 21526  }
 21527  
 21528  /*
 21529  ** Deinitialize this module.
 21530  */
 21531  static void sqlite3MemShutdown(void *NotUsed){
 21532    UNUSED_PARAMETER(NotUsed);
 21533    return;
 21534  }
 21535  
 21536  /*
 21537  ** This routine is the only routine in this file with external linkage.
 21538  **
 21539  ** Populate the low-level memory allocation function pointers in
 21540  ** sqlite3GlobalConfig.m with pointers to the routines in this file.
 21541  */
 21542  SQLITE_PRIVATE void sqlite3MemSetDefault(void){
 21543    static const sqlite3_mem_methods defaultMethods = {
 21544       sqlite3MemMalloc,
 21545       sqlite3MemFree,
 21546       sqlite3MemRealloc,
 21547       sqlite3MemSize,
 21548       sqlite3MemRoundup,
 21549       sqlite3MemInit,
 21550       sqlite3MemShutdown,
 21551       0
 21552    };
 21553    sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
 21554  }
 21555  
 21556  #endif /* SQLITE_SYSTEM_MALLOC */
 21557  
 21558  /************** End of mem1.c ************************************************/
 21559  /************** Begin file mem2.c ********************************************/
 21560  /*
 21561  ** 2007 August 15
 21562  **
 21563  ** The author disclaims copyright to this source code.  In place of
 21564  ** a legal notice, here is a blessing:
 21565  **
 21566  **    May you do good and not evil.
 21567  **    May you find forgiveness for yourself and forgive others.
 21568  **    May you share freely, never taking more than you give.
 21569  **
 21570  *************************************************************************
 21571  **
 21572  ** This file contains low-level memory allocation drivers for when
 21573  ** SQLite will use the standard C-library malloc/realloc/free interface
 21574  ** to obtain the memory it needs while adding lots of additional debugging
 21575  ** information to each allocation in order to help detect and fix memory
 21576  ** leaks and memory usage errors.
 21577  **
 21578  ** This file contains implementations of the low-level memory allocation
 21579  ** routines specified in the sqlite3_mem_methods object.
 21580  */
 21581  /* #include "sqliteInt.h" */
 21582  
 21583  /*
 21584  ** This version of the memory allocator is used only if the
 21585  ** SQLITE_MEMDEBUG macro is defined
 21586  */
 21587  #ifdef SQLITE_MEMDEBUG
 21588  
 21589  /*
 21590  ** The backtrace functionality is only available with GLIBC
 21591  */
 21592  #ifdef __GLIBC__
 21593    extern int backtrace(void**,int);
 21594    extern void backtrace_symbols_fd(void*const*,int,int);
 21595  #else
 21596  # define backtrace(A,B) 1
 21597  # define backtrace_symbols_fd(A,B,C)
 21598  #endif
 21599  /* #include <stdio.h> */
 21600  
 21601  /*
 21602  ** Each memory allocation looks like this:
 21603  **
 21604  **  ------------------------------------------------------------------------
 21605  **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
 21606  **  ------------------------------------------------------------------------
 21607  **
 21608  ** The application code sees only a pointer to the allocation.  We have
 21609  ** to back up from the allocation pointer to find the MemBlockHdr.  The
 21610  ** MemBlockHdr tells us the size of the allocation and the number of
 21611  ** backtrace pointers.  There is also a guard word at the end of the
 21612  ** MemBlockHdr.
 21613  */
 21614  struct MemBlockHdr {
 21615    i64 iSize;                          /* Size of this allocation */
 21616    struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
 21617    char nBacktrace;                    /* Number of backtraces on this alloc */
 21618    char nBacktraceSlots;               /* Available backtrace slots */
 21619    u8 nTitle;                          /* Bytes of title; includes '\0' */
 21620    u8 eType;                           /* Allocation type code */
 21621    int iForeGuard;                     /* Guard word for sanity */
 21622  };
 21623  
 21624  /*
 21625  ** Guard words
 21626  */
 21627  #define FOREGUARD 0x80F5E153
 21628  #define REARGUARD 0xE4676B53
 21629  
 21630  /*
 21631  ** Number of malloc size increments to track.
 21632  */
 21633  #define NCSIZE  1000
 21634  
 21635  /*
 21636  ** All of the static variables used by this module are collected
 21637  ** into a single structure named "mem".  This is to keep the
 21638  ** static variables organized and to reduce namespace pollution
 21639  ** when this module is combined with other in the amalgamation.
 21640  */
 21641  static struct {
 21642    
 21643    /*
 21644    ** Mutex to control access to the memory allocation subsystem.
 21645    */
 21646    sqlite3_mutex *mutex;
 21647  
 21648    /*
 21649    ** Head and tail of a linked list of all outstanding allocations
 21650    */
 21651    struct MemBlockHdr *pFirst;
 21652    struct MemBlockHdr *pLast;
 21653    
 21654    /*
 21655    ** The number of levels of backtrace to save in new allocations.
 21656    */
 21657    int nBacktrace;
 21658    void (*xBacktrace)(int, int, void **);
 21659  
 21660    /*
 21661    ** Title text to insert in front of each block
 21662    */
 21663    int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
 21664    char zTitle[100];  /* The title text */
 21665  
 21666    /* 
 21667    ** sqlite3MallocDisallow() increments the following counter.
 21668    ** sqlite3MallocAllow() decrements it.
 21669    */
 21670    int disallow; /* Do not allow memory allocation */
 21671  
 21672    /*
 21673    ** Gather statistics on the sizes of memory allocations.
 21674    ** nAlloc[i] is the number of allocation attempts of i*8
 21675    ** bytes.  i==NCSIZE is the number of allocation attempts for
 21676    ** sizes more than NCSIZE*8 bytes.
 21677    */
 21678    int nAlloc[NCSIZE];      /* Total number of allocations */
 21679    int nCurrent[NCSIZE];    /* Current number of allocations */
 21680    int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
 21681  
 21682  } mem;
 21683  
 21684  
 21685  /*
 21686  ** Adjust memory usage statistics
 21687  */
 21688  static void adjustStats(int iSize, int increment){
 21689    int i = ROUND8(iSize)/8;
 21690    if( i>NCSIZE-1 ){
 21691      i = NCSIZE - 1;
 21692    }
 21693    if( increment>0 ){
 21694      mem.nAlloc[i]++;
 21695      mem.nCurrent[i]++;
 21696      if( mem.nCurrent[i]>mem.mxCurrent[i] ){
 21697        mem.mxCurrent[i] = mem.nCurrent[i];
 21698      }
 21699    }else{
 21700      mem.nCurrent[i]--;
 21701      assert( mem.nCurrent[i]>=0 );
 21702    }
 21703  }
 21704  
 21705  /*
 21706  ** Given an allocation, find the MemBlockHdr for that allocation.
 21707  **
 21708  ** This routine checks the guards at either end of the allocation and
 21709  ** if they are incorrect it asserts.
 21710  */
 21711  static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
 21712    struct MemBlockHdr *p;
 21713    int *pInt;
 21714    u8 *pU8;
 21715    int nReserve;
 21716  
 21717    p = (struct MemBlockHdr*)pAllocation;
 21718    p--;
 21719    assert( p->iForeGuard==(int)FOREGUARD );
 21720    nReserve = ROUND8(p->iSize);
 21721    pInt = (int*)pAllocation;
 21722    pU8 = (u8*)pAllocation;
 21723    assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
 21724    /* This checks any of the "extra" bytes allocated due
 21725    ** to rounding up to an 8 byte boundary to ensure 
 21726    ** they haven't been overwritten.
 21727    */
 21728    while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
 21729    return p;
 21730  }
 21731  
 21732  /*
 21733  ** Return the number of bytes currently allocated at address p.
 21734  */
 21735  static int sqlite3MemSize(void *p){
 21736    struct MemBlockHdr *pHdr;
 21737    if( !p ){
 21738      return 0;
 21739    }
 21740    pHdr = sqlite3MemsysGetHeader(p);
 21741    return (int)pHdr->iSize;
 21742  }
 21743  
 21744  /*
 21745  ** Initialize the memory allocation subsystem.
 21746  */
 21747  static int sqlite3MemInit(void *NotUsed){
 21748    UNUSED_PARAMETER(NotUsed);
 21749    assert( (sizeof(struct MemBlockHdr)&7) == 0 );
 21750    if( !sqlite3GlobalConfig.bMemstat ){
 21751      /* If memory status is enabled, then the malloc.c wrapper will already
 21752      ** hold the STATIC_MEM mutex when the routines here are invoked. */
 21753      mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
 21754    }
 21755    return SQLITE_OK;
 21756  }
 21757  
 21758  /*
 21759  ** Deinitialize the memory allocation subsystem.
 21760  */
 21761  static void sqlite3MemShutdown(void *NotUsed){
 21762    UNUSED_PARAMETER(NotUsed);
 21763    mem.mutex = 0;
 21764  }
 21765  
 21766  /*
 21767  ** Round up a request size to the next valid allocation size.
 21768  */
 21769  static int sqlite3MemRoundup(int n){
 21770    return ROUND8(n);
 21771  }
 21772  
 21773  /*
 21774  ** Fill a buffer with pseudo-random bytes.  This is used to preset
 21775  ** the content of a new memory allocation to unpredictable values and
 21776  ** to clear the content of a freed allocation to unpredictable values.
 21777  */
 21778  static void randomFill(char *pBuf, int nByte){
 21779    unsigned int x, y, r;
 21780    x = SQLITE_PTR_TO_INT(pBuf);
 21781    y = nByte | 1;
 21782    while( nByte >= 4 ){
 21783      x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
 21784      y = y*1103515245 + 12345;
 21785      r = x ^ y;
 21786      *(int*)pBuf = r;
 21787      pBuf += 4;
 21788      nByte -= 4;
 21789    }
 21790    while( nByte-- > 0 ){
 21791      x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
 21792      y = y*1103515245 + 12345;
 21793      r = x ^ y;
 21794      *(pBuf++) = r & 0xff;
 21795    }
 21796  }
 21797  
 21798  /*
 21799  ** Allocate nByte bytes of memory.
 21800  */
 21801  static void *sqlite3MemMalloc(int nByte){
 21802    struct MemBlockHdr *pHdr;
 21803    void **pBt;
 21804    char *z;
 21805    int *pInt;
 21806    void *p = 0;
 21807    int totalSize;
 21808    int nReserve;
 21809    sqlite3_mutex_enter(mem.mutex);
 21810    assert( mem.disallow==0 );
 21811    nReserve = ROUND8(nByte);
 21812    totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
 21813                 mem.nBacktrace*sizeof(void*) + mem.nTitle;
 21814    p = malloc(totalSize);
 21815    if( p ){
 21816      z = p;
 21817      pBt = (void**)&z[mem.nTitle];
 21818      pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
 21819      pHdr->pNext = 0;
 21820      pHdr->pPrev = mem.pLast;
 21821      if( mem.pLast ){
 21822        mem.pLast->pNext = pHdr;
 21823      }else{
 21824        mem.pFirst = pHdr;
 21825      }
 21826      mem.pLast = pHdr;
 21827      pHdr->iForeGuard = FOREGUARD;
 21828      pHdr->eType = MEMTYPE_HEAP;
 21829      pHdr->nBacktraceSlots = mem.nBacktrace;
 21830      pHdr->nTitle = mem.nTitle;
 21831      if( mem.nBacktrace ){
 21832        void *aAddr[40];
 21833        pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
 21834        memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
 21835        assert(pBt[0]);
 21836        if( mem.xBacktrace ){
 21837          mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
 21838        }
 21839      }else{
 21840        pHdr->nBacktrace = 0;
 21841      }
 21842      if( mem.nTitle ){
 21843        memcpy(z, mem.zTitle, mem.nTitle);
 21844      }
 21845      pHdr->iSize = nByte;
 21846      adjustStats(nByte, +1);
 21847      pInt = (int*)&pHdr[1];
 21848      pInt[nReserve/sizeof(int)] = REARGUARD;
 21849      randomFill((char*)pInt, nByte);
 21850      memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
 21851      p = (void*)pInt;
 21852    }
 21853    sqlite3_mutex_leave(mem.mutex);
 21854    return p; 
 21855  }
 21856  
 21857  /*
 21858  ** Free memory.
 21859  */
 21860  static void sqlite3MemFree(void *pPrior){
 21861    struct MemBlockHdr *pHdr;
 21862    void **pBt;
 21863    char *z;
 21864    assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
 21865         || mem.mutex!=0 );
 21866    pHdr = sqlite3MemsysGetHeader(pPrior);
 21867    pBt = (void**)pHdr;
 21868    pBt -= pHdr->nBacktraceSlots;
 21869    sqlite3_mutex_enter(mem.mutex);
 21870    if( pHdr->pPrev ){
 21871      assert( pHdr->pPrev->pNext==pHdr );
 21872      pHdr->pPrev->pNext = pHdr->pNext;
 21873    }else{
 21874      assert( mem.pFirst==pHdr );
 21875      mem.pFirst = pHdr->pNext;
 21876    }
 21877    if( pHdr->pNext ){
 21878      assert( pHdr->pNext->pPrev==pHdr );
 21879      pHdr->pNext->pPrev = pHdr->pPrev;
 21880    }else{
 21881      assert( mem.pLast==pHdr );
 21882      mem.pLast = pHdr->pPrev;
 21883    }
 21884    z = (char*)pBt;
 21885    z -= pHdr->nTitle;
 21886    adjustStats((int)pHdr->iSize, -1);
 21887    randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
 21888                  (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
 21889    free(z);
 21890    sqlite3_mutex_leave(mem.mutex);  
 21891  }
 21892  
 21893  /*
 21894  ** Change the size of an existing memory allocation.
 21895  **
 21896  ** For this debugging implementation, we *always* make a copy of the
 21897  ** allocation into a new place in memory.  In this way, if the 
 21898  ** higher level code is using pointer to the old allocation, it is 
 21899  ** much more likely to break and we are much more liking to find
 21900  ** the error.
 21901  */
 21902  static void *sqlite3MemRealloc(void *pPrior, int nByte){
 21903    struct MemBlockHdr *pOldHdr;
 21904    void *pNew;
 21905    assert( mem.disallow==0 );
 21906    assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
 21907    pOldHdr = sqlite3MemsysGetHeader(pPrior);
 21908    pNew = sqlite3MemMalloc(nByte);
 21909    if( pNew ){
 21910      memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
 21911      if( nByte>pOldHdr->iSize ){
 21912        randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
 21913      }
 21914      sqlite3MemFree(pPrior);
 21915    }
 21916    return pNew;
 21917  }
 21918  
 21919  /*
 21920  ** Populate the low-level memory allocation function pointers in
 21921  ** sqlite3GlobalConfig.m with pointers to the routines in this file.
 21922  */
 21923  SQLITE_PRIVATE void sqlite3MemSetDefault(void){
 21924    static const sqlite3_mem_methods defaultMethods = {
 21925       sqlite3MemMalloc,
 21926       sqlite3MemFree,
 21927       sqlite3MemRealloc,
 21928       sqlite3MemSize,
 21929       sqlite3MemRoundup,
 21930       sqlite3MemInit,
 21931       sqlite3MemShutdown,
 21932       0
 21933    };
 21934    sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
 21935  }
 21936  
 21937  /*
 21938  ** Set the "type" of an allocation.
 21939  */
 21940  SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
 21941    if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
 21942      struct MemBlockHdr *pHdr;
 21943      pHdr = sqlite3MemsysGetHeader(p);
 21944      assert( pHdr->iForeGuard==FOREGUARD );
 21945      pHdr->eType = eType;
 21946    }
 21947  }
 21948  
 21949  /*
 21950  ** Return TRUE if the mask of type in eType matches the type of the
 21951  ** allocation p.  Also return true if p==NULL.
 21952  **
 21953  ** This routine is designed for use within an assert() statement, to
 21954  ** verify the type of an allocation.  For example:
 21955  **
 21956  **     assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
 21957  */
 21958  SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
 21959    int rc = 1;
 21960    if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
 21961      struct MemBlockHdr *pHdr;
 21962      pHdr = sqlite3MemsysGetHeader(p);
 21963      assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
 21964      if( (pHdr->eType&eType)==0 ){
 21965        rc = 0;
 21966      }
 21967    }
 21968    return rc;
 21969  }
 21970  
 21971  /*
 21972  ** Return TRUE if the mask of type in eType matches no bits of the type of the
 21973  ** allocation p.  Also return true if p==NULL.
 21974  **
 21975  ** This routine is designed for use within an assert() statement, to
 21976  ** verify the type of an allocation.  For example:
 21977  **
 21978  **     assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
 21979  */
 21980  SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
 21981    int rc = 1;
 21982    if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
 21983      struct MemBlockHdr *pHdr;
 21984      pHdr = sqlite3MemsysGetHeader(p);
 21985      assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
 21986      if( (pHdr->eType&eType)!=0 ){
 21987        rc = 0;
 21988      }
 21989    }
 21990    return rc;
 21991  }
 21992  
 21993  /*
 21994  ** Set the number of backtrace levels kept for each allocation.
 21995  ** A value of zero turns off backtracing.  The number is always rounded
 21996  ** up to a multiple of 2.
 21997  */
 21998  SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
 21999    if( depth<0 ){ depth = 0; }
 22000    if( depth>20 ){ depth = 20; }
 22001    depth = (depth+1)&0xfe;
 22002    mem.nBacktrace = depth;
 22003  }
 22004  
 22005  SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
 22006    mem.xBacktrace = xBacktrace;
 22007  }
 22008  
 22009  /*
 22010  ** Set the title string for subsequent allocations.
 22011  */
 22012  SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
 22013    unsigned int n = sqlite3Strlen30(zTitle) + 1;
 22014    sqlite3_mutex_enter(mem.mutex);
 22015    if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
 22016    memcpy(mem.zTitle, zTitle, n);
 22017    mem.zTitle[n] = 0;
 22018    mem.nTitle = ROUND8(n);
 22019    sqlite3_mutex_leave(mem.mutex);
 22020  }
 22021  
 22022  SQLITE_PRIVATE void sqlite3MemdebugSync(){
 22023    struct MemBlockHdr *pHdr;
 22024    for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
 22025      void **pBt = (void**)pHdr;
 22026      pBt -= pHdr->nBacktraceSlots;
 22027      mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
 22028    }
 22029  }
 22030  
 22031  /*
 22032  ** Open the file indicated and write a log of all unfreed memory 
 22033  ** allocations into that log.
 22034  */
 22035  SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
 22036    FILE *out;
 22037    struct MemBlockHdr *pHdr;
 22038    void **pBt;
 22039    int i;
 22040    out = fopen(zFilename, "w");
 22041    if( out==0 ){
 22042      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
 22043                      zFilename);
 22044      return;
 22045    }
 22046    for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
 22047      char *z = (char*)pHdr;
 22048      z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
 22049      fprintf(out, "**** %lld bytes at %p from %s ****\n", 
 22050              pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
 22051      if( pHdr->nBacktrace ){
 22052        fflush(out);
 22053        pBt = (void**)pHdr;
 22054        pBt -= pHdr->nBacktraceSlots;
 22055        backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
 22056        fprintf(out, "\n");
 22057      }
 22058    }
 22059    fprintf(out, "COUNTS:\n");
 22060    for(i=0; i<NCSIZE-1; i++){
 22061      if( mem.nAlloc[i] ){
 22062        fprintf(out, "   %5d: %10d %10d %10d\n", 
 22063              i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
 22064      }
 22065    }
 22066    if( mem.nAlloc[NCSIZE-1] ){
 22067      fprintf(out, "   %5d: %10d %10d %10d\n",
 22068               NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
 22069               mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
 22070    }
 22071    fclose(out);
 22072  }
 22073  
 22074  /*
 22075  ** Return the number of times sqlite3MemMalloc() has been called.
 22076  */
 22077  SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
 22078    int i;
 22079    int nTotal = 0;
 22080    for(i=0; i<NCSIZE; i++){
 22081      nTotal += mem.nAlloc[i];
 22082    }
 22083    return nTotal;
 22084  }
 22085  
 22086  
 22087  #endif /* SQLITE_MEMDEBUG */
 22088  
 22089  /************** End of mem2.c ************************************************/
 22090  /************** Begin file mem3.c ********************************************/
 22091  /*
 22092  ** 2007 October 14
 22093  **
 22094  ** The author disclaims copyright to this source code.  In place of
 22095  ** a legal notice, here is a blessing:
 22096  **
 22097  **    May you do good and not evil.
 22098  **    May you find forgiveness for yourself and forgive others.
 22099  **    May you share freely, never taking more than you give.
 22100  **
 22101  *************************************************************************
 22102  ** This file contains the C functions that implement a memory
 22103  ** allocation subsystem for use by SQLite. 
 22104  **
 22105  ** This version of the memory allocation subsystem omits all
 22106  ** use of malloc(). The SQLite user supplies a block of memory
 22107  ** before calling sqlite3_initialize() from which allocations
 22108  ** are made and returned by the xMalloc() and xRealloc() 
 22109  ** implementations. Once sqlite3_initialize() has been called,
 22110  ** the amount of memory available to SQLite is fixed and cannot
 22111  ** be changed.
 22112  **
 22113  ** This version of the memory allocation subsystem is included
 22114  ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
 22115  */
 22116  /* #include "sqliteInt.h" */
 22117  
 22118  /*
 22119  ** This version of the memory allocator is only built into the library
 22120  ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
 22121  ** mean that the library will use a memory-pool by default, just that
 22122  ** it is available. The mempool allocator is activated by calling
 22123  ** sqlite3_config().
 22124  */
 22125  #ifdef SQLITE_ENABLE_MEMSYS3
 22126  
 22127  /*
 22128  ** Maximum size (in Mem3Blocks) of a "small" chunk.
 22129  */
 22130  #define MX_SMALL 10
 22131  
 22132  
 22133  /*
 22134  ** Number of freelist hash slots
 22135  */
 22136  #define N_HASH  61
 22137  
 22138  /*
 22139  ** A memory allocation (also called a "chunk") consists of two or 
 22140  ** more blocks where each block is 8 bytes.  The first 8 bytes are 
 22141  ** a header that is not returned to the user.
 22142  **
 22143  ** A chunk is two or more blocks that is either checked out or
 22144  ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
 22145  ** size of the allocation in blocks if the allocation is free.
 22146  ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
 22147  ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
 22148  ** is true if the previous chunk is checked out and false if the
 22149  ** previous chunk is free.  The u.hdr.prevSize field is the size of
 22150  ** the previous chunk in blocks if the previous chunk is on the
 22151  ** freelist. If the previous chunk is checked out, then
 22152  ** u.hdr.prevSize can be part of the data for that chunk and should
 22153  ** not be read or written.
 22154  **
 22155  ** We often identify a chunk by its index in mem3.aPool[].  When
 22156  ** this is done, the chunk index refers to the second block of
 22157  ** the chunk.  In this way, the first chunk has an index of 1.
 22158  ** A chunk index of 0 means "no such chunk" and is the equivalent
 22159  ** of a NULL pointer.
 22160  **
 22161  ** The second block of free chunks is of the form u.list.  The
 22162  ** two fields form a double-linked list of chunks of related sizes.
 22163  ** Pointers to the head of the list are stored in mem3.aiSmall[] 
 22164  ** for smaller chunks and mem3.aiHash[] for larger chunks.
 22165  **
 22166  ** The second block of a chunk is user data if the chunk is checked 
 22167  ** out.  If a chunk is checked out, the user data may extend into
 22168  ** the u.hdr.prevSize value of the following chunk.
 22169  */
 22170  typedef struct Mem3Block Mem3Block;
 22171  struct Mem3Block {
 22172    union {
 22173      struct {
 22174        u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
 22175        u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
 22176      } hdr;
 22177      struct {
 22178        u32 next;       /* Index in mem3.aPool[] of next free chunk */
 22179        u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
 22180      } list;
 22181    } u;
 22182  };
 22183  
 22184  /*
 22185  ** All of the static variables used by this module are collected
 22186  ** into a single structure named "mem3".  This is to keep the
 22187  ** static variables organized and to reduce namespace pollution
 22188  ** when this module is combined with other in the amalgamation.
 22189  */
 22190  static SQLITE_WSD struct Mem3Global {
 22191    /*
 22192    ** Memory available for allocation. nPool is the size of the array
 22193    ** (in Mem3Blocks) pointed to by aPool less 2.
 22194    */
 22195    u32 nPool;
 22196    Mem3Block *aPool;
 22197  
 22198    /*
 22199    ** True if we are evaluating an out-of-memory callback.
 22200    */
 22201    int alarmBusy;
 22202    
 22203    /*
 22204    ** Mutex to control access to the memory allocation subsystem.
 22205    */
 22206    sqlite3_mutex *mutex;
 22207    
 22208    /*
 22209    ** The minimum amount of free space that we have seen.
 22210    */
 22211    u32 mnMaster;
 22212  
 22213    /*
 22214    ** iMaster is the index of the master chunk.  Most new allocations
 22215    ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
 22216    ** of the current master.  iMaster is 0 if there is not master chunk.
 22217    ** The master chunk is not in either the aiHash[] or aiSmall[].
 22218    */
 22219    u32 iMaster;
 22220    u32 szMaster;
 22221  
 22222    /*
 22223    ** Array of lists of free blocks according to the block size 
 22224    ** for smaller chunks, or a hash on the block size for larger
 22225    ** chunks.
 22226    */
 22227    u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
 22228    u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
 22229  } mem3 = { 97535575 };
 22230  
 22231  #define mem3 GLOBAL(struct Mem3Global, mem3)
 22232  
 22233  /*
 22234  ** Unlink the chunk at mem3.aPool[i] from list it is currently
 22235  ** on.  *pRoot is the list that i is a member of.
 22236  */
 22237  static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
 22238    u32 next = mem3.aPool[i].u.list.next;
 22239    u32 prev = mem3.aPool[i].u.list.prev;
 22240    assert( sqlite3_mutex_held(mem3.mutex) );
 22241    if( prev==0 ){
 22242      *pRoot = next;
 22243    }else{
 22244      mem3.aPool[prev].u.list.next = next;
 22245    }
 22246    if( next ){
 22247      mem3.aPool[next].u.list.prev = prev;
 22248    }
 22249    mem3.aPool[i].u.list.next = 0;
 22250    mem3.aPool[i].u.list.prev = 0;
 22251  }
 22252  
 22253  /*
 22254  ** Unlink the chunk at index i from 
 22255  ** whatever list is currently a member of.
 22256  */
 22257  static void memsys3Unlink(u32 i){
 22258    u32 size, hash;
 22259    assert( sqlite3_mutex_held(mem3.mutex) );
 22260    assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
 22261    assert( i>=1 );
 22262    size = mem3.aPool[i-1].u.hdr.size4x/4;
 22263    assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
 22264    assert( size>=2 );
 22265    if( size <= MX_SMALL ){
 22266      memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
 22267    }else{
 22268      hash = size % N_HASH;
 22269      memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
 22270    }
 22271  }
 22272  
 22273  /*
 22274  ** Link the chunk at mem3.aPool[i] so that is on the list rooted
 22275  ** at *pRoot.
 22276  */
 22277  static void memsys3LinkIntoList(u32 i, u32 *pRoot){
 22278    assert( sqlite3_mutex_held(mem3.mutex) );
 22279    mem3.aPool[i].u.list.next = *pRoot;
 22280    mem3.aPool[i].u.list.prev = 0;
 22281    if( *pRoot ){
 22282      mem3.aPool[*pRoot].u.list.prev = i;
 22283    }
 22284    *pRoot = i;
 22285  }
 22286  
 22287  /*
 22288  ** Link the chunk at index i into either the appropriate
 22289  ** small chunk list, or into the large chunk hash table.
 22290  */
 22291  static void memsys3Link(u32 i){
 22292    u32 size, hash;
 22293    assert( sqlite3_mutex_held(mem3.mutex) );
 22294    assert( i>=1 );
 22295    assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
 22296    size = mem3.aPool[i-1].u.hdr.size4x/4;
 22297    assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
 22298    assert( size>=2 );
 22299    if( size <= MX_SMALL ){
 22300      memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
 22301    }else{
 22302      hash = size % N_HASH;
 22303      memsys3LinkIntoList(i, &mem3.aiHash[hash]);
 22304    }
 22305  }
 22306  
 22307  /*
 22308  ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
 22309  ** will already be held (obtained by code in malloc.c) if
 22310  ** sqlite3GlobalConfig.bMemStat is true.
 22311  */
 22312  static void memsys3Enter(void){
 22313    if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
 22314      mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
 22315    }
 22316    sqlite3_mutex_enter(mem3.mutex);
 22317  }
 22318  static void memsys3Leave(void){
 22319    sqlite3_mutex_leave(mem3.mutex);
 22320  }
 22321  
 22322  /*
 22323  ** Called when we are unable to satisfy an allocation of nBytes.
 22324  */
 22325  static void memsys3OutOfMemory(int nByte){
 22326    if( !mem3.alarmBusy ){
 22327      mem3.alarmBusy = 1;
 22328      assert( sqlite3_mutex_held(mem3.mutex) );
 22329      sqlite3_mutex_leave(mem3.mutex);
 22330      sqlite3_release_memory(nByte);
 22331      sqlite3_mutex_enter(mem3.mutex);
 22332      mem3.alarmBusy = 0;
 22333    }
 22334  }
 22335  
 22336  
 22337  /*
 22338  ** Chunk i is a free chunk that has been unlinked.  Adjust its 
 22339  ** size parameters for check-out and return a pointer to the 
 22340  ** user portion of the chunk.
 22341  */
 22342  static void *memsys3Checkout(u32 i, u32 nBlock){
 22343    u32 x;
 22344    assert( sqlite3_mutex_held(mem3.mutex) );
 22345    assert( i>=1 );
 22346    assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
 22347    assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
 22348    x = mem3.aPool[i-1].u.hdr.size4x;
 22349    mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
 22350    mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
 22351    mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
 22352    return &mem3.aPool[i];
 22353  }
 22354  
 22355  /*
 22356  ** Carve a piece off of the end of the mem3.iMaster free chunk.
 22357  ** Return a pointer to the new allocation.  Or, if the master chunk
 22358  ** is not large enough, return 0.
 22359  */
 22360  static void *memsys3FromMaster(u32 nBlock){
 22361    assert( sqlite3_mutex_held(mem3.mutex) );
 22362    assert( mem3.szMaster>=nBlock );
 22363    if( nBlock>=mem3.szMaster-1 ){
 22364      /* Use the entire master */
 22365      void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
 22366      mem3.iMaster = 0;
 22367      mem3.szMaster = 0;
 22368      mem3.mnMaster = 0;
 22369      return p;
 22370    }else{
 22371      /* Split the master block.  Return the tail. */
 22372      u32 newi, x;
 22373      newi = mem3.iMaster + mem3.szMaster - nBlock;
 22374      assert( newi > mem3.iMaster+1 );
 22375      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
 22376      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
 22377      mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
 22378      mem3.szMaster -= nBlock;
 22379      mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
 22380      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
 22381      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
 22382      if( mem3.szMaster < mem3.mnMaster ){
 22383        mem3.mnMaster = mem3.szMaster;
 22384      }
 22385      return (void*)&mem3.aPool[newi];
 22386    }
 22387  }
 22388  
 22389  /*
 22390  ** *pRoot is the head of a list of free chunks of the same size
 22391  ** or same size hash.  In other words, *pRoot is an entry in either
 22392  ** mem3.aiSmall[] or mem3.aiHash[].  
 22393  **
 22394  ** This routine examines all entries on the given list and tries
 22395  ** to coalesce each entries with adjacent free chunks.  
 22396  **
 22397  ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
 22398  ** the current mem3.iMaster with the new larger chunk.  In order for
 22399  ** this mem3.iMaster replacement to work, the master chunk must be
 22400  ** linked into the hash tables.  That is not the normal state of
 22401  ** affairs, of course.  The calling routine must link the master
 22402  ** chunk before invoking this routine, then must unlink the (possibly
 22403  ** changed) master chunk once this routine has finished.
 22404  */
 22405  static void memsys3Merge(u32 *pRoot){
 22406    u32 iNext, prev, size, i, x;
 22407  
 22408    assert( sqlite3_mutex_held(mem3.mutex) );
 22409    for(i=*pRoot; i>0; i=iNext){
 22410      iNext = mem3.aPool[i].u.list.next;
 22411      size = mem3.aPool[i-1].u.hdr.size4x;
 22412      assert( (size&1)==0 );
 22413      if( (size&2)==0 ){
 22414        memsys3UnlinkFromList(i, pRoot);
 22415        assert( i > mem3.aPool[i-1].u.hdr.prevSize );
 22416        prev = i - mem3.aPool[i-1].u.hdr.prevSize;
 22417        if( prev==iNext ){
 22418          iNext = mem3.aPool[prev].u.list.next;
 22419        }
 22420        memsys3Unlink(prev);
 22421        size = i + size/4 - prev;
 22422        x = mem3.aPool[prev-1].u.hdr.size4x & 2;
 22423        mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
 22424        mem3.aPool[prev+size-1].u.hdr.prevSize = size;
 22425        memsys3Link(prev);
 22426        i = prev;
 22427      }else{
 22428        size /= 4;
 22429      }
 22430      if( size>mem3.szMaster ){
 22431        mem3.iMaster = i;
 22432        mem3.szMaster = size;
 22433      }
 22434    }
 22435  }
 22436  
 22437  /*
 22438  ** Return a block of memory of at least nBytes in size.
 22439  ** Return NULL if unable.
 22440  **
 22441  ** This function assumes that the necessary mutexes, if any, are
 22442  ** already held by the caller. Hence "Unsafe".
 22443  */
 22444  static void *memsys3MallocUnsafe(int nByte){
 22445    u32 i;
 22446    u32 nBlock;
 22447    u32 toFree;
 22448  
 22449    assert( sqlite3_mutex_held(mem3.mutex) );
 22450    assert( sizeof(Mem3Block)==8 );
 22451    if( nByte<=12 ){
 22452      nBlock = 2;
 22453    }else{
 22454      nBlock = (nByte + 11)/8;
 22455    }
 22456    assert( nBlock>=2 );
 22457  
 22458    /* STEP 1:
 22459    ** Look for an entry of the correct size in either the small
 22460    ** chunk table or in the large chunk hash table.  This is
 22461    ** successful most of the time (about 9 times out of 10).
 22462    */
 22463    if( nBlock <= MX_SMALL ){
 22464      i = mem3.aiSmall[nBlock-2];
 22465      if( i>0 ){
 22466        memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
 22467        return memsys3Checkout(i, nBlock);
 22468      }
 22469    }else{
 22470      int hash = nBlock % N_HASH;
 22471      for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
 22472        if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
 22473          memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
 22474          return memsys3Checkout(i, nBlock);
 22475        }
 22476      }
 22477    }
 22478  
 22479    /* STEP 2:
 22480    ** Try to satisfy the allocation by carving a piece off of the end
 22481    ** of the master chunk.  This step usually works if step 1 fails.
 22482    */
 22483    if( mem3.szMaster>=nBlock ){
 22484      return memsys3FromMaster(nBlock);
 22485    }
 22486  
 22487  
 22488    /* STEP 3:  
 22489    ** Loop through the entire memory pool.  Coalesce adjacent free
 22490    ** chunks.  Recompute the master chunk as the largest free chunk.
 22491    ** Then try again to satisfy the allocation by carving a piece off
 22492    ** of the end of the master chunk.  This step happens very
 22493    ** rarely (we hope!)
 22494    */
 22495    for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
 22496      memsys3OutOfMemory(toFree);
 22497      if( mem3.iMaster ){
 22498        memsys3Link(mem3.iMaster);
 22499        mem3.iMaster = 0;
 22500        mem3.szMaster = 0;
 22501      }
 22502      for(i=0; i<N_HASH; i++){
 22503        memsys3Merge(&mem3.aiHash[i]);
 22504      }
 22505      for(i=0; i<MX_SMALL-1; i++){
 22506        memsys3Merge(&mem3.aiSmall[i]);
 22507      }
 22508      if( mem3.szMaster ){
 22509        memsys3Unlink(mem3.iMaster);
 22510        if( mem3.szMaster>=nBlock ){
 22511          return memsys3FromMaster(nBlock);
 22512        }
 22513      }
 22514    }
 22515  
 22516    /* If none of the above worked, then we fail. */
 22517    return 0;
 22518  }
 22519  
 22520  /*
 22521  ** Free an outstanding memory allocation.
 22522  **
 22523  ** This function assumes that the necessary mutexes, if any, are
 22524  ** already held by the caller. Hence "Unsafe".
 22525  */
 22526  static void memsys3FreeUnsafe(void *pOld){
 22527    Mem3Block *p = (Mem3Block*)pOld;
 22528    int i;
 22529    u32 size, x;
 22530    assert( sqlite3_mutex_held(mem3.mutex) );
 22531    assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
 22532    i = p - mem3.aPool;
 22533    assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
 22534    size = mem3.aPool[i-1].u.hdr.size4x/4;
 22535    assert( i+size<=mem3.nPool+1 );
 22536    mem3.aPool[i-1].u.hdr.size4x &= ~1;
 22537    mem3.aPool[i+size-1].u.hdr.prevSize = size;
 22538    mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
 22539    memsys3Link(i);
 22540  
 22541    /* Try to expand the master using the newly freed chunk */
 22542    if( mem3.iMaster ){
 22543      while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
 22544        size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
 22545        mem3.iMaster -= size;
 22546        mem3.szMaster += size;
 22547        memsys3Unlink(mem3.iMaster);
 22548        x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
 22549        mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
 22550        mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
 22551      }
 22552      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
 22553      while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
 22554        memsys3Unlink(mem3.iMaster+mem3.szMaster);
 22555        mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
 22556        mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
 22557        mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
 22558      }
 22559    }
 22560  }
 22561  
 22562  /*
 22563  ** Return the size of an outstanding allocation, in bytes.  The
 22564  ** size returned omits the 8-byte header overhead.  This only
 22565  ** works for chunks that are currently checked out.
 22566  */
 22567  static int memsys3Size(void *p){
 22568    Mem3Block *pBlock;
 22569    assert( p!=0 );
 22570    pBlock = (Mem3Block*)p;
 22571    assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
 22572    return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
 22573  }
 22574  
 22575  /*
 22576  ** Round up a request size to the next valid allocation size.
 22577  */
 22578  static int memsys3Roundup(int n){
 22579    if( n<=12 ){
 22580      return 12;
 22581    }else{
 22582      return ((n+11)&~7) - 4;
 22583    }
 22584  }
 22585  
 22586  /*
 22587  ** Allocate nBytes of memory.
 22588  */
 22589  static void *memsys3Malloc(int nBytes){
 22590    sqlite3_int64 *p;
 22591    assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
 22592    memsys3Enter();
 22593    p = memsys3MallocUnsafe(nBytes);
 22594    memsys3Leave();
 22595    return (void*)p; 
 22596  }
 22597  
 22598  /*
 22599  ** Free memory.
 22600  */
 22601  static void memsys3Free(void *pPrior){
 22602    assert( pPrior );
 22603    memsys3Enter();
 22604    memsys3FreeUnsafe(pPrior);
 22605    memsys3Leave();
 22606  }
 22607  
 22608  /*
 22609  ** Change the size of an existing memory allocation
 22610  */
 22611  static void *memsys3Realloc(void *pPrior, int nBytes){
 22612    int nOld;
 22613    void *p;
 22614    if( pPrior==0 ){
 22615      return sqlite3_malloc(nBytes);
 22616    }
 22617    if( nBytes<=0 ){
 22618      sqlite3_free(pPrior);
 22619      return 0;
 22620    }
 22621    nOld = memsys3Size(pPrior);
 22622    if( nBytes<=nOld && nBytes>=nOld-128 ){
 22623      return pPrior;
 22624    }
 22625    memsys3Enter();
 22626    p = memsys3MallocUnsafe(nBytes);
 22627    if( p ){
 22628      if( nOld<nBytes ){
 22629        memcpy(p, pPrior, nOld);
 22630      }else{
 22631        memcpy(p, pPrior, nBytes);
 22632      }
 22633      memsys3FreeUnsafe(pPrior);
 22634    }
 22635    memsys3Leave();
 22636    return p;
 22637  }
 22638  
 22639  /*
 22640  ** Initialize this module.
 22641  */
 22642  static int memsys3Init(void *NotUsed){
 22643    UNUSED_PARAMETER(NotUsed);
 22644    if( !sqlite3GlobalConfig.pHeap ){
 22645      return SQLITE_ERROR;
 22646    }
 22647  
 22648    /* Store a pointer to the memory block in global structure mem3. */
 22649    assert( sizeof(Mem3Block)==8 );
 22650    mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
 22651    mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
 22652  
 22653    /* Initialize the master block. */
 22654    mem3.szMaster = mem3.nPool;
 22655    mem3.mnMaster = mem3.szMaster;
 22656    mem3.iMaster = 1;
 22657    mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
 22658    mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
 22659    mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
 22660  
 22661    return SQLITE_OK;
 22662  }
 22663  
 22664  /*
 22665  ** Deinitialize this module.
 22666  */
 22667  static void memsys3Shutdown(void *NotUsed){
 22668    UNUSED_PARAMETER(NotUsed);
 22669    mem3.mutex = 0;
 22670    return;
 22671  }
 22672  
 22673  
 22674  
 22675  /*
 22676  ** Open the file indicated and write a log of all unfreed memory 
 22677  ** allocations into that log.
 22678  */
 22679  SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
 22680  #ifdef SQLITE_DEBUG
 22681    FILE *out;
 22682    u32 i, j;
 22683    u32 size;
 22684    if( zFilename==0 || zFilename[0]==0 ){
 22685      out = stdout;
 22686    }else{
 22687      out = fopen(zFilename, "w");
 22688      if( out==0 ){
 22689        fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
 22690                        zFilename);
 22691        return;
 22692      }
 22693    }
 22694    memsys3Enter();
 22695    fprintf(out, "CHUNKS:\n");
 22696    for(i=1; i<=mem3.nPool; i+=size/4){
 22697      size = mem3.aPool[i-1].u.hdr.size4x;
 22698      if( size/4<=1 ){
 22699        fprintf(out, "%p size error\n", &mem3.aPool[i]);
 22700        assert( 0 );
 22701        break;
 22702      }
 22703      if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
 22704        fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
 22705        assert( 0 );
 22706        break;
 22707      }
 22708      if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
 22709        fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
 22710        assert( 0 );
 22711        break;
 22712      }
 22713      if( size&1 ){
 22714        fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
 22715      }else{
 22716        fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
 22717                    i==mem3.iMaster ? " **master**" : "");
 22718      }
 22719    }
 22720    for(i=0; i<MX_SMALL-1; i++){
 22721      if( mem3.aiSmall[i]==0 ) continue;
 22722      fprintf(out, "small(%2d):", i);
 22723      for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
 22724        fprintf(out, " %p(%d)", &mem3.aPool[j],
 22725                (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
 22726      }
 22727      fprintf(out, "\n"); 
 22728    }
 22729    for(i=0; i<N_HASH; i++){
 22730      if( mem3.aiHash[i]==0 ) continue;
 22731      fprintf(out, "hash(%2d):", i);
 22732      for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
 22733        fprintf(out, " %p(%d)", &mem3.aPool[j],
 22734                (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
 22735      }
 22736      fprintf(out, "\n"); 
 22737    }
 22738    fprintf(out, "master=%d\n", mem3.iMaster);
 22739    fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
 22740    fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
 22741    sqlite3_mutex_leave(mem3.mutex);
 22742    if( out==stdout ){
 22743      fflush(stdout);
 22744    }else{
 22745      fclose(out);
 22746    }
 22747  #else
 22748    UNUSED_PARAMETER(zFilename);
 22749  #endif
 22750  }
 22751  
 22752  /*
 22753  ** This routine is the only routine in this file with external 
 22754  ** linkage.
 22755  **
 22756  ** Populate the low-level memory allocation function pointers in
 22757  ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
 22758  ** arguments specify the block of memory to manage.
 22759  **
 22760  ** This routine is only called by sqlite3_config(), and therefore
 22761  ** is not required to be threadsafe (it is not).
 22762  */
 22763  SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
 22764    static const sqlite3_mem_methods mempoolMethods = {
 22765       memsys3Malloc,
 22766       memsys3Free,
 22767       memsys3Realloc,
 22768       memsys3Size,
 22769       memsys3Roundup,
 22770       memsys3Init,
 22771       memsys3Shutdown,
 22772       0
 22773    };
 22774    return &mempoolMethods;
 22775  }
 22776  
 22777  #endif /* SQLITE_ENABLE_MEMSYS3 */
 22778  
 22779  /************** End of mem3.c ************************************************/
 22780  /************** Begin file mem5.c ********************************************/
 22781  /*
 22782  ** 2007 October 14
 22783  **
 22784  ** The author disclaims copyright to this source code.  In place of
 22785  ** a legal notice, here is a blessing:
 22786  **
 22787  **    May you do good and not evil.
 22788  **    May you find forgiveness for yourself and forgive others.
 22789  **    May you share freely, never taking more than you give.
 22790  **
 22791  *************************************************************************
 22792  ** This file contains the C functions that implement a memory
 22793  ** allocation subsystem for use by SQLite. 
 22794  **
 22795  ** This version of the memory allocation subsystem omits all
 22796  ** use of malloc(). The application gives SQLite a block of memory
 22797  ** before calling sqlite3_initialize() from which allocations
 22798  ** are made and returned by the xMalloc() and xRealloc() 
 22799  ** implementations. Once sqlite3_initialize() has been called,
 22800  ** the amount of memory available to SQLite is fixed and cannot
 22801  ** be changed.
 22802  **
 22803  ** This version of the memory allocation subsystem is included
 22804  ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
 22805  **
 22806  ** This memory allocator uses the following algorithm:
 22807  **
 22808  **   1.  All memory allocation sizes are rounded up to a power of 2.
 22809  **
 22810  **   2.  If two adjacent free blocks are the halves of a larger block,
 22811  **       then the two blocks are coalesced into the single larger block.
 22812  **
 22813  **   3.  New memory is allocated from the first available free block.
 22814  **
 22815  ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
 22816  ** Concerning Dynamic Storage Allocation". Journal of the Association for
 22817  ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
 22818  ** 
 22819  ** Let n be the size of the largest allocation divided by the minimum
 22820  ** allocation size (after rounding all sizes up to a power of 2.)  Let M
 22821  ** be the maximum amount of memory ever outstanding at one time.  Let
 22822  ** N be the total amount of memory available for allocation.  Robson
 22823  ** proved that this memory allocator will never breakdown due to 
 22824  ** fragmentation as long as the following constraint holds:
 22825  **
 22826  **      N >=  M*(1 + log2(n)/2) - n + 1
 22827  **
 22828  ** The sqlite3_status() logic tracks the maximum values of n and M so
 22829  ** that an application can, at any time, verify this constraint.
 22830  */
 22831  /* #include "sqliteInt.h" */
 22832  
 22833  /*
 22834  ** This version of the memory allocator is used only when 
 22835  ** SQLITE_ENABLE_MEMSYS5 is defined.
 22836  */
 22837  #ifdef SQLITE_ENABLE_MEMSYS5
 22838  
 22839  /*
 22840  ** A minimum allocation is an instance of the following structure.
 22841  ** Larger allocations are an array of these structures where the
 22842  ** size of the array is a power of 2.
 22843  **
 22844  ** The size of this object must be a power of two.  That fact is
 22845  ** verified in memsys5Init().
 22846  */
 22847  typedef struct Mem5Link Mem5Link;
 22848  struct Mem5Link {
 22849    int next;       /* Index of next free chunk */
 22850    int prev;       /* Index of previous free chunk */
 22851  };
 22852  
 22853  /*
 22854  ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
 22855  ** mem5.szAtom is always at least 8 and 32-bit integers are used,
 22856  ** it is not actually possible to reach this limit.
 22857  */
 22858  #define LOGMAX 30
 22859  
 22860  /*
 22861  ** Masks used for mem5.aCtrl[] elements.
 22862  */
 22863  #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
 22864  #define CTRL_FREE     0x20    /* True if not checked out */
 22865  
 22866  /*
 22867  ** All of the static variables used by this module are collected
 22868  ** into a single structure named "mem5".  This is to keep the
 22869  ** static variables organized and to reduce namespace pollution
 22870  ** when this module is combined with other in the amalgamation.
 22871  */
 22872  static SQLITE_WSD struct Mem5Global {
 22873    /*
 22874    ** Memory available for allocation
 22875    */
 22876    int szAtom;      /* Smallest possible allocation in bytes */
 22877    int nBlock;      /* Number of szAtom sized blocks in zPool */
 22878    u8 *zPool;       /* Memory available to be allocated */
 22879    
 22880    /*
 22881    ** Mutex to control access to the memory allocation subsystem.
 22882    */
 22883    sqlite3_mutex *mutex;
 22884  
 22885  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
 22886    /*
 22887    ** Performance statistics
 22888    */
 22889    u64 nAlloc;         /* Total number of calls to malloc */
 22890    u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
 22891    u64 totalExcess;    /* Total internal fragmentation */
 22892    u32 currentOut;     /* Current checkout, including internal fragmentation */
 22893    u32 currentCount;   /* Current number of distinct checkouts */
 22894    u32 maxOut;         /* Maximum instantaneous currentOut */
 22895    u32 maxCount;       /* Maximum instantaneous currentCount */
 22896    u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
 22897  #endif
 22898    
 22899    /*
 22900    ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
 22901    ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
 22902    ** aiFreelist[2] holds free blocks of size szAtom*4.  And so forth.
 22903    */
 22904    int aiFreelist[LOGMAX+1];
 22905  
 22906    /*
 22907    ** Space for tracking which blocks are checked out and the size
 22908    ** of each block.  One byte per block.
 22909    */
 22910    u8 *aCtrl;
 22911  
 22912  } mem5;
 22913  
 22914  /*
 22915  ** Access the static variable through a macro for SQLITE_OMIT_WSD.
 22916  */
 22917  #define mem5 GLOBAL(struct Mem5Global, mem5)
 22918  
 22919  /*
 22920  ** Assuming mem5.zPool is divided up into an array of Mem5Link
 22921  ** structures, return a pointer to the idx-th such link.
 22922  */
 22923  #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
 22924  
 22925  /*
 22926  ** Unlink the chunk at mem5.aPool[i] from list it is currently
 22927  ** on.  It should be found on mem5.aiFreelist[iLogsize].
 22928  */
 22929  static void memsys5Unlink(int i, int iLogsize){
 22930    int next, prev;
 22931    assert( i>=0 && i<mem5.nBlock );
 22932    assert( iLogsize>=0 && iLogsize<=LOGMAX );
 22933    assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
 22934  
 22935    next = MEM5LINK(i)->next;
 22936    prev = MEM5LINK(i)->prev;
 22937    if( prev<0 ){
 22938      mem5.aiFreelist[iLogsize] = next;
 22939    }else{
 22940      MEM5LINK(prev)->next = next;
 22941    }
 22942    if( next>=0 ){
 22943      MEM5LINK(next)->prev = prev;
 22944    }
 22945  }
 22946  
 22947  /*
 22948  ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
 22949  ** free list.
 22950  */
 22951  static void memsys5Link(int i, int iLogsize){
 22952    int x;
 22953    assert( sqlite3_mutex_held(mem5.mutex) );
 22954    assert( i>=0 && i<mem5.nBlock );
 22955    assert( iLogsize>=0 && iLogsize<=LOGMAX );
 22956    assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
 22957  
 22958    x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
 22959    MEM5LINK(i)->prev = -1;
 22960    if( x>=0 ){
 22961      assert( x<mem5.nBlock );
 22962      MEM5LINK(x)->prev = i;
 22963    }
 22964    mem5.aiFreelist[iLogsize] = i;
 22965  }
 22966  
 22967  /*
 22968  ** Obtain or release the mutex needed to access global data structures.
 22969  */
 22970  static void memsys5Enter(void){
 22971    sqlite3_mutex_enter(mem5.mutex);
 22972  }
 22973  static void memsys5Leave(void){
 22974    sqlite3_mutex_leave(mem5.mutex);
 22975  }
 22976  
 22977  /*
 22978  ** Return the size of an outstanding allocation, in bytes.
 22979  ** This only works for chunks that are currently checked out.
 22980  */
 22981  static int memsys5Size(void *p){
 22982    int iSize, i;
 22983    assert( p!=0 );
 22984    i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
 22985    assert( i>=0 && i<mem5.nBlock );
 22986    iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
 22987    return iSize;
 22988  }
 22989  
 22990  /*
 22991  ** Return a block of memory of at least nBytes in size.
 22992  ** Return NULL if unable.  Return NULL if nBytes==0.
 22993  **
 22994  ** The caller guarantees that nByte is positive.
 22995  **
 22996  ** The caller has obtained a mutex prior to invoking this
 22997  ** routine so there is never any chance that two or more
 22998  ** threads can be in this routine at the same time.
 22999  */
 23000  static void *memsys5MallocUnsafe(int nByte){
 23001    int i;           /* Index of a mem5.aPool[] slot */
 23002    int iBin;        /* Index into mem5.aiFreelist[] */
 23003    int iFullSz;     /* Size of allocation rounded up to power of 2 */
 23004    int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
 23005  
 23006    /* nByte must be a positive */
 23007    assert( nByte>0 );
 23008  
 23009    /* No more than 1GiB per allocation */
 23010    if( nByte > 0x40000000 ) return 0;
 23011  
 23012  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
 23013    /* Keep track of the maximum allocation request.  Even unfulfilled
 23014    ** requests are counted */
 23015    if( (u32)nByte>mem5.maxRequest ){
 23016      mem5.maxRequest = nByte;
 23017    }
 23018  #endif
 23019  
 23020  
 23021    /* Round nByte up to the next valid power of two */
 23022    for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
 23023  
 23024    /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
 23025    ** block.  If not, then split a block of the next larger power of
 23026    ** two in order to create a new free block of size iLogsize.
 23027    */
 23028    for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
 23029    if( iBin>LOGMAX ){
 23030      testcase( sqlite3GlobalConfig.xLog!=0 );
 23031      sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
 23032      return 0;
 23033    }
 23034    i = mem5.aiFreelist[iBin];
 23035    memsys5Unlink(i, iBin);
 23036    while( iBin>iLogsize ){
 23037      int newSize;
 23038  
 23039      iBin--;
 23040      newSize = 1 << iBin;
 23041      mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
 23042      memsys5Link(i+newSize, iBin);
 23043    }
 23044    mem5.aCtrl[i] = iLogsize;
 23045  
 23046  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
 23047    /* Update allocator performance statistics. */
 23048    mem5.nAlloc++;
 23049    mem5.totalAlloc += iFullSz;
 23050    mem5.totalExcess += iFullSz - nByte;
 23051    mem5.currentCount++;
 23052    mem5.currentOut += iFullSz;
 23053    if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
 23054    if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
 23055  #endif
 23056  
 23057  #ifdef SQLITE_DEBUG
 23058    /* Make sure the allocated memory does not assume that it is set to zero
 23059    ** or retains a value from a previous allocation */
 23060    memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
 23061  #endif
 23062  
 23063    /* Return a pointer to the allocated memory. */
 23064    return (void*)&mem5.zPool[i*mem5.szAtom];
 23065  }
 23066  
 23067  /*
 23068  ** Free an outstanding memory allocation.
 23069  */
 23070  static void memsys5FreeUnsafe(void *pOld){
 23071    u32 size, iLogsize;
 23072    int iBlock;
 23073  
 23074    /* Set iBlock to the index of the block pointed to by pOld in 
 23075    ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
 23076    */
 23077    iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
 23078  
 23079    /* Check that the pointer pOld points to a valid, non-free block. */
 23080    assert( iBlock>=0 && iBlock<mem5.nBlock );
 23081    assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
 23082    assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
 23083  
 23084    iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
 23085    size = 1<<iLogsize;
 23086    assert( iBlock+size-1<(u32)mem5.nBlock );
 23087  
 23088    mem5.aCtrl[iBlock] |= CTRL_FREE;
 23089    mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
 23090  
 23091  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
 23092    assert( mem5.currentCount>0 );
 23093    assert( mem5.currentOut>=(size*mem5.szAtom) );
 23094    mem5.currentCount--;
 23095    mem5.currentOut -= size*mem5.szAtom;
 23096    assert( mem5.currentOut>0 || mem5.currentCount==0 );
 23097    assert( mem5.currentCount>0 || mem5.currentOut==0 );
 23098  #endif
 23099  
 23100    mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
 23101    while( ALWAYS(iLogsize<LOGMAX) ){
 23102      int iBuddy;
 23103      if( (iBlock>>iLogsize) & 1 ){
 23104        iBuddy = iBlock - size;
 23105        assert( iBuddy>=0 );
 23106      }else{
 23107        iBuddy = iBlock + size;
 23108        if( iBuddy>=mem5.nBlock ) break;
 23109      }
 23110      if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
 23111      memsys5Unlink(iBuddy, iLogsize);
 23112      iLogsize++;
 23113      if( iBuddy<iBlock ){
 23114        mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
 23115        mem5.aCtrl[iBlock] = 0;
 23116        iBlock = iBuddy;
 23117      }else{
 23118        mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
 23119        mem5.aCtrl[iBuddy] = 0;
 23120      }
 23121      size *= 2;
 23122    }
 23123  
 23124  #ifdef SQLITE_DEBUG
 23125    /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
 23126    ** not used after being freed */
 23127    memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
 23128  #endif
 23129  
 23130    memsys5Link(iBlock, iLogsize);
 23131  }
 23132  
 23133  /*
 23134  ** Allocate nBytes of memory.
 23135  */
 23136  static void *memsys5Malloc(int nBytes){
 23137    sqlite3_int64 *p = 0;
 23138    if( nBytes>0 ){
 23139      memsys5Enter();
 23140      p = memsys5MallocUnsafe(nBytes);
 23141      memsys5Leave();
 23142    }
 23143    return (void*)p; 
 23144  }
 23145  
 23146  /*
 23147  ** Free memory.
 23148  **
 23149  ** The outer layer memory allocator prevents this routine from
 23150  ** being called with pPrior==0.
 23151  */
 23152  static void memsys5Free(void *pPrior){
 23153    assert( pPrior!=0 );
 23154    memsys5Enter();
 23155    memsys5FreeUnsafe(pPrior);
 23156    memsys5Leave();  
 23157  }
 23158  
 23159  /*
 23160  ** Change the size of an existing memory allocation.
 23161  **
 23162  ** The outer layer memory allocator prevents this routine from
 23163  ** being called with pPrior==0.  
 23164  **
 23165  ** nBytes is always a value obtained from a prior call to
 23166  ** memsys5Round().  Hence nBytes is always a non-negative power
 23167  ** of two.  If nBytes==0 that means that an oversize allocation
 23168  ** (an allocation larger than 0x40000000) was requested and this
 23169  ** routine should return 0 without freeing pPrior.
 23170  */
 23171  static void *memsys5Realloc(void *pPrior, int nBytes){
 23172    int nOld;
 23173    void *p;
 23174    assert( pPrior!=0 );
 23175    assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
 23176    assert( nBytes>=0 );
 23177    if( nBytes==0 ){
 23178      return 0;
 23179    }
 23180    nOld = memsys5Size(pPrior);
 23181    if( nBytes<=nOld ){
 23182      return pPrior;
 23183    }
 23184    p = memsys5Malloc(nBytes);
 23185    if( p ){
 23186      memcpy(p, pPrior, nOld);
 23187      memsys5Free(pPrior);
 23188    }
 23189    return p;
 23190  }
 23191  
 23192  /*
 23193  ** Round up a request size to the next valid allocation size.  If
 23194  ** the allocation is too large to be handled by this allocation system,
 23195  ** return 0.
 23196  **
 23197  ** All allocations must be a power of two and must be expressed by a
 23198  ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
 23199  ** or 1073741824 bytes.
 23200  */
 23201  static int memsys5Roundup(int n){
 23202    int iFullSz;
 23203    if( n > 0x40000000 ) return 0;
 23204    for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
 23205    return iFullSz;
 23206  }
 23207  
 23208  /*
 23209  ** Return the ceiling of the logarithm base 2 of iValue.
 23210  **
 23211  ** Examples:   memsys5Log(1) -> 0
 23212  **             memsys5Log(2) -> 1
 23213  **             memsys5Log(4) -> 2
 23214  **             memsys5Log(5) -> 3
 23215  **             memsys5Log(8) -> 3
 23216  **             memsys5Log(9) -> 4
 23217  */
 23218  static int memsys5Log(int iValue){
 23219    int iLog;
 23220    for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
 23221    return iLog;
 23222  }
 23223  
 23224  /*
 23225  ** Initialize the memory allocator.
 23226  **
 23227  ** This routine is not threadsafe.  The caller must be holding a mutex
 23228  ** to prevent multiple threads from entering at the same time.
 23229  */
 23230  static int memsys5Init(void *NotUsed){
 23231    int ii;            /* Loop counter */
 23232    int nByte;         /* Number of bytes of memory available to this allocator */
 23233    u8 *zByte;         /* Memory usable by this allocator */
 23234    int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
 23235    int iOffset;       /* An offset into mem5.aCtrl[] */
 23236  
 23237    UNUSED_PARAMETER(NotUsed);
 23238  
 23239    /* For the purposes of this routine, disable the mutex */
 23240    mem5.mutex = 0;
 23241  
 23242    /* The size of a Mem5Link object must be a power of two.  Verify that
 23243    ** this is case.
 23244    */
 23245    assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
 23246  
 23247    nByte = sqlite3GlobalConfig.nHeap;
 23248    zByte = (u8*)sqlite3GlobalConfig.pHeap;
 23249    assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
 23250  
 23251    /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
 23252    nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
 23253    mem5.szAtom = (1<<nMinLog);
 23254    while( (int)sizeof(Mem5Link)>mem5.szAtom ){
 23255      mem5.szAtom = mem5.szAtom << 1;
 23256    }
 23257  
 23258    mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
 23259    mem5.zPool = zByte;
 23260    mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
 23261  
 23262    for(ii=0; ii<=LOGMAX; ii++){
 23263      mem5.aiFreelist[ii] = -1;
 23264    }
 23265  
 23266    iOffset = 0;
 23267    for(ii=LOGMAX; ii>=0; ii--){
 23268      int nAlloc = (1<<ii);
 23269      if( (iOffset+nAlloc)<=mem5.nBlock ){
 23270        mem5.aCtrl[iOffset] = ii | CTRL_FREE;
 23271        memsys5Link(iOffset, ii);
 23272        iOffset += nAlloc;
 23273      }
 23274      assert((iOffset+nAlloc)>mem5.nBlock);
 23275    }
 23276  
 23277    /* If a mutex is required for normal operation, allocate one */
 23278    if( sqlite3GlobalConfig.bMemstat==0 ){
 23279      mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
 23280    }
 23281  
 23282    return SQLITE_OK;
 23283  }
 23284  
 23285  /*
 23286  ** Deinitialize this module.
 23287  */
 23288  static void memsys5Shutdown(void *NotUsed){
 23289    UNUSED_PARAMETER(NotUsed);
 23290    mem5.mutex = 0;
 23291    return;
 23292  }
 23293  
 23294  #ifdef SQLITE_TEST
 23295  /*
 23296  ** Open the file indicated and write a log of all unfreed memory 
 23297  ** allocations into that log.
 23298  */
 23299  SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
 23300    FILE *out;
 23301    int i, j, n;
 23302    int nMinLog;
 23303  
 23304    if( zFilename==0 || zFilename[0]==0 ){
 23305      out = stdout;
 23306    }else{
 23307      out = fopen(zFilename, "w");
 23308      if( out==0 ){
 23309        fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
 23310                        zFilename);
 23311        return;
 23312      }
 23313    }
 23314    memsys5Enter();
 23315    nMinLog = memsys5Log(mem5.szAtom);
 23316    for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
 23317      for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
 23318      fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
 23319    }
 23320    fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
 23321    fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
 23322    fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
 23323    fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
 23324    fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
 23325    fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
 23326    fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
 23327    fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
 23328    memsys5Leave();
 23329    if( out==stdout ){
 23330      fflush(stdout);
 23331    }else{
 23332      fclose(out);
 23333    }
 23334  }
 23335  #endif
 23336  
 23337  /*
 23338  ** This routine is the only routine in this file with external 
 23339  ** linkage. It returns a pointer to a static sqlite3_mem_methods
 23340  ** struct populated with the memsys5 methods.
 23341  */
 23342  SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
 23343    static const sqlite3_mem_methods memsys5Methods = {
 23344       memsys5Malloc,
 23345       memsys5Free,
 23346       memsys5Realloc,
 23347       memsys5Size,
 23348       memsys5Roundup,
 23349       memsys5Init,
 23350       memsys5Shutdown,
 23351       0
 23352    };
 23353    return &memsys5Methods;
 23354  }
 23355  
 23356  #endif /* SQLITE_ENABLE_MEMSYS5 */
 23357  
 23358  /************** End of mem5.c ************************************************/
 23359  /************** Begin file mutex.c *******************************************/
 23360  /*
 23361  ** 2007 August 14
 23362  **
 23363  ** The author disclaims copyright to this source code.  In place of
 23364  ** a legal notice, here is a blessing:
 23365  **
 23366  **    May you do good and not evil.
 23367  **    May you find forgiveness for yourself and forgive others.
 23368  **    May you share freely, never taking more than you give.
 23369  **
 23370  *************************************************************************
 23371  ** This file contains the C functions that implement mutexes.
 23372  **
 23373  ** This file contains code that is common across all mutex implementations.
 23374  */
 23375  /* #include "sqliteInt.h" */
 23376  
 23377  #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
 23378  /*
 23379  ** For debugging purposes, record when the mutex subsystem is initialized
 23380  ** and uninitialized so that we can assert() if there is an attempt to
 23381  ** allocate a mutex while the system is uninitialized.
 23382  */
 23383  static SQLITE_WSD int mutexIsInit = 0;
 23384  #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
 23385  
 23386  
 23387  #ifndef SQLITE_MUTEX_OMIT
 23388  /*
 23389  ** Initialize the mutex system.
 23390  */
 23391  SQLITE_PRIVATE int sqlite3MutexInit(void){ 
 23392    int rc = SQLITE_OK;
 23393    if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
 23394      /* If the xMutexAlloc method has not been set, then the user did not
 23395      ** install a mutex implementation via sqlite3_config() prior to 
 23396      ** sqlite3_initialize() being called. This block copies pointers to
 23397      ** the default implementation into the sqlite3GlobalConfig structure.
 23398      */
 23399      sqlite3_mutex_methods const *pFrom;
 23400      sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
 23401  
 23402      if( sqlite3GlobalConfig.bCoreMutex ){
 23403        pFrom = sqlite3DefaultMutex();
 23404      }else{
 23405        pFrom = sqlite3NoopMutex();
 23406      }
 23407      pTo->xMutexInit = pFrom->xMutexInit;
 23408      pTo->xMutexEnd = pFrom->xMutexEnd;
 23409      pTo->xMutexFree = pFrom->xMutexFree;
 23410      pTo->xMutexEnter = pFrom->xMutexEnter;
 23411      pTo->xMutexTry = pFrom->xMutexTry;
 23412      pTo->xMutexLeave = pFrom->xMutexLeave;
 23413      pTo->xMutexHeld = pFrom->xMutexHeld;
 23414      pTo->xMutexNotheld = pFrom->xMutexNotheld;
 23415      sqlite3MemoryBarrier();
 23416      pTo->xMutexAlloc = pFrom->xMutexAlloc;
 23417    }
 23418    assert( sqlite3GlobalConfig.mutex.xMutexInit );
 23419    rc = sqlite3GlobalConfig.mutex.xMutexInit();
 23420  
 23421  #ifdef SQLITE_DEBUG
 23422    GLOBAL(int, mutexIsInit) = 1;
 23423  #endif
 23424  
 23425    return rc;
 23426  }
 23427  
 23428  /*
 23429  ** Shutdown the mutex system. This call frees resources allocated by
 23430  ** sqlite3MutexInit().
 23431  */
 23432  SQLITE_PRIVATE int sqlite3MutexEnd(void){
 23433    int rc = SQLITE_OK;
 23434    if( sqlite3GlobalConfig.mutex.xMutexEnd ){
 23435      rc = sqlite3GlobalConfig.mutex.xMutexEnd();
 23436    }
 23437  
 23438  #ifdef SQLITE_DEBUG
 23439    GLOBAL(int, mutexIsInit) = 0;
 23440  #endif
 23441  
 23442    return rc;
 23443  }
 23444  
 23445  /*
 23446  ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
 23447  */
 23448  SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
 23449  #ifndef SQLITE_OMIT_AUTOINIT
 23450    if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
 23451    if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
 23452  #endif
 23453    assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
 23454    return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
 23455  }
 23456  
 23457  SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
 23458    if( !sqlite3GlobalConfig.bCoreMutex ){
 23459      return 0;
 23460    }
 23461    assert( GLOBAL(int, mutexIsInit) );
 23462    assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
 23463    return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
 23464  }
 23465  
 23466  /*
 23467  ** Free a dynamic mutex.
 23468  */
 23469  SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
 23470    if( p ){
 23471      assert( sqlite3GlobalConfig.mutex.xMutexFree );
 23472      sqlite3GlobalConfig.mutex.xMutexFree(p);
 23473    }
 23474  }
 23475  
 23476  /*
 23477  ** Obtain the mutex p. If some other thread already has the mutex, block
 23478  ** until it can be obtained.
 23479  */
 23480  SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
 23481    if( p ){
 23482      assert( sqlite3GlobalConfig.mutex.xMutexEnter );
 23483      sqlite3GlobalConfig.mutex.xMutexEnter(p);
 23484    }
 23485  }
 23486  
 23487  /*
 23488  ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
 23489  ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
 23490  */
 23491  SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
 23492    int rc = SQLITE_OK;
 23493    if( p ){
 23494      assert( sqlite3GlobalConfig.mutex.xMutexTry );
 23495      return sqlite3GlobalConfig.mutex.xMutexTry(p);
 23496    }
 23497    return rc;
 23498  }
 23499  
 23500  /*
 23501  ** The sqlite3_mutex_leave() routine exits a mutex that was previously
 23502  ** entered by the same thread.  The behavior is undefined if the mutex 
 23503  ** is not currently entered. If a NULL pointer is passed as an argument
 23504  ** this function is a no-op.
 23505  */
 23506  SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
 23507    if( p ){
 23508      assert( sqlite3GlobalConfig.mutex.xMutexLeave );
 23509      sqlite3GlobalConfig.mutex.xMutexLeave(p);
 23510    }
 23511  }
 23512  
 23513  #ifndef NDEBUG
 23514  /*
 23515  ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
 23516  ** intended for use inside assert() statements.
 23517  */
 23518  SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
 23519    assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
 23520    return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
 23521  }
 23522  SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
 23523    assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
 23524    return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
 23525  }
 23526  #endif
 23527  
 23528  #endif /* !defined(SQLITE_MUTEX_OMIT) */
 23529  
 23530  /************** End of mutex.c ***********************************************/
 23531  /************** Begin file mutex_noop.c **************************************/
 23532  /*
 23533  ** 2008 October 07
 23534  **
 23535  ** The author disclaims copyright to this source code.  In place of
 23536  ** a legal notice, here is a blessing:
 23537  **
 23538  **    May you do good and not evil.
 23539  **    May you find forgiveness for yourself and forgive others.
 23540  **    May you share freely, never taking more than you give.
 23541  **
 23542  *************************************************************************
 23543  ** This file contains the C functions that implement mutexes.
 23544  **
 23545  ** This implementation in this file does not provide any mutual
 23546  ** exclusion and is thus suitable for use only in applications
 23547  ** that use SQLite in a single thread.  The routines defined
 23548  ** here are place-holders.  Applications can substitute working
 23549  ** mutex routines at start-time using the
 23550  **
 23551  **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
 23552  **
 23553  ** interface.
 23554  **
 23555  ** If compiled with SQLITE_DEBUG, then additional logic is inserted
 23556  ** that does error checking on mutexes to make sure they are being
 23557  ** called correctly.
 23558  */
 23559  /* #include "sqliteInt.h" */
 23560  
 23561  #ifndef SQLITE_MUTEX_OMIT
 23562  
 23563  #ifndef SQLITE_DEBUG
 23564  /*
 23565  ** Stub routines for all mutex methods.
 23566  **
 23567  ** This routines provide no mutual exclusion or error checking.
 23568  */
 23569  static int noopMutexInit(void){ return SQLITE_OK; }
 23570  static int noopMutexEnd(void){ return SQLITE_OK; }
 23571  static sqlite3_mutex *noopMutexAlloc(int id){ 
 23572    UNUSED_PARAMETER(id);
 23573    return (sqlite3_mutex*)8; 
 23574  }
 23575  static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
 23576  static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
 23577  static int noopMutexTry(sqlite3_mutex *p){
 23578    UNUSED_PARAMETER(p);
 23579    return SQLITE_OK;
 23580  }
 23581  static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
 23582  
 23583  SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
 23584    static const sqlite3_mutex_methods sMutex = {
 23585      noopMutexInit,
 23586      noopMutexEnd,
 23587      noopMutexAlloc,
 23588      noopMutexFree,
 23589      noopMutexEnter,
 23590      noopMutexTry,
 23591      noopMutexLeave,
 23592  
 23593      0,
 23594      0,
 23595    };
 23596  
 23597    return &sMutex;
 23598  }
 23599  #endif /* !SQLITE_DEBUG */
 23600  
 23601  #ifdef SQLITE_DEBUG
 23602  /*
 23603  ** In this implementation, error checking is provided for testing
 23604  ** and debugging purposes.  The mutexes still do not provide any
 23605  ** mutual exclusion.
 23606  */
 23607  
 23608  /*
 23609  ** The mutex object
 23610  */
 23611  typedef struct sqlite3_debug_mutex {
 23612    int id;     /* The mutex type */
 23613    int cnt;    /* Number of entries without a matching leave */
 23614  } sqlite3_debug_mutex;
 23615  
 23616  /*
 23617  ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
 23618  ** intended for use inside assert() statements.
 23619  */
 23620  static int debugMutexHeld(sqlite3_mutex *pX){
 23621    sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
 23622    return p==0 || p->cnt>0;
 23623  }
 23624  static int debugMutexNotheld(sqlite3_mutex *pX){
 23625    sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
 23626    return p==0 || p->cnt==0;
 23627  }
 23628  
 23629  /*
 23630  ** Initialize and deinitialize the mutex subsystem.
 23631  */
 23632  static int debugMutexInit(void){ return SQLITE_OK; }
 23633  static int debugMutexEnd(void){ return SQLITE_OK; }
 23634  
 23635  /*
 23636  ** The sqlite3_mutex_alloc() routine allocates a new
 23637  ** mutex and returns a pointer to it.  If it returns NULL
 23638  ** that means that a mutex could not be allocated. 
 23639  */
 23640  static sqlite3_mutex *debugMutexAlloc(int id){
 23641    static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
 23642    sqlite3_debug_mutex *pNew = 0;
 23643    switch( id ){
 23644      case SQLITE_MUTEX_FAST:
 23645      case SQLITE_MUTEX_RECURSIVE: {
 23646        pNew = sqlite3Malloc(sizeof(*pNew));
 23647        if( pNew ){
 23648          pNew->id = id;
 23649          pNew->cnt = 0;
 23650        }
 23651        break;
 23652      }
 23653      default: {
 23654  #ifdef SQLITE_ENABLE_API_ARMOR
 23655        if( id-2<0 || id-2>=ArraySize(aStatic) ){
 23656          (void)SQLITE_MISUSE_BKPT;
 23657          return 0;
 23658        }
 23659  #endif
 23660        pNew = &aStatic[id-2];
 23661        pNew->id = id;
 23662        break;
 23663      }
 23664    }
 23665    return (sqlite3_mutex*)pNew;
 23666  }
 23667  
 23668  /*
 23669  ** This routine deallocates a previously allocated mutex.
 23670  */
 23671  static void debugMutexFree(sqlite3_mutex *pX){
 23672    sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
 23673    assert( p->cnt==0 );
 23674    if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
 23675      sqlite3_free(p);
 23676    }else{
 23677  #ifdef SQLITE_ENABLE_API_ARMOR
 23678      (void)SQLITE_MISUSE_BKPT;
 23679  #endif
 23680    }
 23681  }
 23682  
 23683  /*
 23684  ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
 23685  ** to enter a mutex.  If another thread is already within the mutex,
 23686  ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
 23687  ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
 23688  ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
 23689  ** be entered multiple times by the same thread.  In such cases the,
 23690  ** mutex must be exited an equal number of times before another thread
 23691  ** can enter.  If the same thread tries to enter any other kind of mutex
 23692  ** more than once, the behavior is undefined.
 23693  */
 23694  static void debugMutexEnter(sqlite3_mutex *pX){
 23695    sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
 23696    assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
 23697    p->cnt++;
 23698  }
 23699  static int debugMutexTry(sqlite3_mutex *pX){
 23700    sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
 23701    assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
 23702    p->cnt++;
 23703    return SQLITE_OK;
 23704  }
 23705  
 23706  /*
 23707  ** The sqlite3_mutex_leave() routine exits a mutex that was
 23708  ** previously entered by the same thread.  The behavior
 23709  ** is undefined if the mutex is not currently entered or
 23710  ** is not currently allocated.  SQLite will never do either.
 23711  */
 23712  static void debugMutexLeave(sqlite3_mutex *pX){
 23713    sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
 23714    assert( debugMutexHeld(pX) );
 23715    p->cnt--;
 23716    assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
 23717  }
 23718  
 23719  SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
 23720    static const sqlite3_mutex_methods sMutex = {
 23721      debugMutexInit,
 23722      debugMutexEnd,
 23723      debugMutexAlloc,
 23724      debugMutexFree,
 23725      debugMutexEnter,
 23726      debugMutexTry,
 23727      debugMutexLeave,
 23728  
 23729      debugMutexHeld,
 23730      debugMutexNotheld
 23731    };
 23732  
 23733    return &sMutex;
 23734  }
 23735  #endif /* SQLITE_DEBUG */
 23736  
 23737  /*
 23738  ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
 23739  ** is used regardless of the run-time threadsafety setting.
 23740  */
 23741  #ifdef SQLITE_MUTEX_NOOP
 23742  SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
 23743    return sqlite3NoopMutex();
 23744  }
 23745  #endif /* defined(SQLITE_MUTEX_NOOP) */
 23746  #endif /* !defined(SQLITE_MUTEX_OMIT) */
 23747  
 23748  /************** End of mutex_noop.c ******************************************/
 23749  /************** Begin file mutex_unix.c **************************************/
 23750  /*
 23751  ** 2007 August 28
 23752  **
 23753  ** The author disclaims copyright to this source code.  In place of
 23754  ** a legal notice, here is a blessing:
 23755  **
 23756  **    May you do good and not evil.
 23757  **    May you find forgiveness for yourself and forgive others.
 23758  **    May you share freely, never taking more than you give.
 23759  **
 23760  *************************************************************************
 23761  ** This file contains the C functions that implement mutexes for pthreads
 23762  */
 23763  /* #include "sqliteInt.h" */
 23764  
 23765  /*
 23766  ** The code in this file is only used if we are compiling threadsafe
 23767  ** under unix with pthreads.
 23768  **
 23769  ** Note that this implementation requires a version of pthreads that
 23770  ** supports recursive mutexes.
 23771  */
 23772  #ifdef SQLITE_MUTEX_PTHREADS
 23773  
 23774  #include <pthread.h>
 23775  
 23776  /*
 23777  ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
 23778  ** are necessary under two condidtions:  (1) Debug builds and (2) using
 23779  ** home-grown mutexes.  Encapsulate these conditions into a single #define.
 23780  */
 23781  #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
 23782  # define SQLITE_MUTEX_NREF 1
 23783  #else
 23784  # define SQLITE_MUTEX_NREF 0
 23785  #endif
 23786  
 23787  /*
 23788  ** Each recursive mutex is an instance of the following structure.
 23789  */
 23790  struct sqlite3_mutex {
 23791    pthread_mutex_t mutex;     /* Mutex controlling the lock */
 23792  #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
 23793    int id;                    /* Mutex type */
 23794  #endif
 23795  #if SQLITE_MUTEX_NREF
 23796    volatile int nRef;         /* Number of entrances */
 23797    volatile pthread_t owner;  /* Thread that is within this mutex */
 23798    int trace;                 /* True to trace changes */
 23799  #endif
 23800  };
 23801  #if SQLITE_MUTEX_NREF
 23802  #define SQLITE3_MUTEX_INITIALIZER {PTHREAD_MUTEX_INITIALIZER,0,0,(pthread_t)0,0}
 23803  #elif defined(SQLITE_ENABLE_API_ARMOR)
 23804  #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0 }
 23805  #else
 23806  #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
 23807  #endif
 23808  
 23809  /*
 23810  ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
 23811  ** intended for use only inside assert() statements.  On some platforms,
 23812  ** there might be race conditions that can cause these routines to
 23813  ** deliver incorrect results.  In particular, if pthread_equal() is
 23814  ** not an atomic operation, then these routines might delivery
 23815  ** incorrect results.  On most platforms, pthread_equal() is a 
 23816  ** comparison of two integers and is therefore atomic.  But we are
 23817  ** told that HPUX is not such a platform.  If so, then these routines
 23818  ** will not always work correctly on HPUX.
 23819  **
 23820  ** On those platforms where pthread_equal() is not atomic, SQLite
 23821  ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
 23822  ** make sure no assert() statements are evaluated and hence these
 23823  ** routines are never called.
 23824  */
 23825  #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
 23826  static int pthreadMutexHeld(sqlite3_mutex *p){
 23827    return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
 23828  }
 23829  static int pthreadMutexNotheld(sqlite3_mutex *p){
 23830    return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
 23831  }
 23832  #endif
 23833  
 23834  /*
 23835  ** Try to provide a memory barrier operation, needed for initialization
 23836  ** and also for the implementation of xShmBarrier in the VFS in cases
 23837  ** where SQLite is compiled without mutexes.
 23838  */
 23839  SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
 23840  #if defined(SQLITE_MEMORY_BARRIER)
 23841    SQLITE_MEMORY_BARRIER;
 23842  #elif defined(__GNUC__) && GCC_VERSION>=4001000
 23843    __sync_synchronize();
 23844  #endif
 23845  }
 23846  
 23847  /*
 23848  ** Initialize and deinitialize the mutex subsystem.
 23849  */
 23850  static int pthreadMutexInit(void){ return SQLITE_OK; }
 23851  static int pthreadMutexEnd(void){ return SQLITE_OK; }
 23852  
 23853  /*
 23854  ** The sqlite3_mutex_alloc() routine allocates a new
 23855  ** mutex and returns a pointer to it.  If it returns NULL
 23856  ** that means that a mutex could not be allocated.  SQLite
 23857  ** will unwind its stack and return an error.  The argument
 23858  ** to sqlite3_mutex_alloc() is one of these integer constants:
 23859  **
 23860  ** <ul>
 23861  ** <li>  SQLITE_MUTEX_FAST
 23862  ** <li>  SQLITE_MUTEX_RECURSIVE
 23863  ** <li>  SQLITE_MUTEX_STATIC_MASTER
 23864  ** <li>  SQLITE_MUTEX_STATIC_MEM
 23865  ** <li>  SQLITE_MUTEX_STATIC_OPEN
 23866  ** <li>  SQLITE_MUTEX_STATIC_PRNG
 23867  ** <li>  SQLITE_MUTEX_STATIC_LRU
 23868  ** <li>  SQLITE_MUTEX_STATIC_PMEM
 23869  ** <li>  SQLITE_MUTEX_STATIC_APP1
 23870  ** <li>  SQLITE_MUTEX_STATIC_APP2
 23871  ** <li>  SQLITE_MUTEX_STATIC_APP3
 23872  ** <li>  SQLITE_MUTEX_STATIC_VFS1
 23873  ** <li>  SQLITE_MUTEX_STATIC_VFS2
 23874  ** <li>  SQLITE_MUTEX_STATIC_VFS3
 23875  ** </ul>
 23876  **
 23877  ** The first two constants cause sqlite3_mutex_alloc() to create
 23878  ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
 23879  ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
 23880  ** The mutex implementation does not need to make a distinction
 23881  ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
 23882  ** not want to.  But SQLite will only request a recursive mutex in
 23883  ** cases where it really needs one.  If a faster non-recursive mutex
 23884  ** implementation is available on the host platform, the mutex subsystem
 23885  ** might return such a mutex in response to SQLITE_MUTEX_FAST.
 23886  **
 23887  ** The other allowed parameters to sqlite3_mutex_alloc() each return
 23888  ** a pointer to a static preexisting mutex.  Six static mutexes are
 23889  ** used by the current version of SQLite.  Future versions of SQLite
 23890  ** may add additional static mutexes.  Static mutexes are for internal
 23891  ** use by SQLite only.  Applications that use SQLite mutexes should
 23892  ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
 23893  ** SQLITE_MUTEX_RECURSIVE.
 23894  **
 23895  ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
 23896  ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
 23897  ** returns a different mutex on every call.  But for the static 
 23898  ** mutex types, the same mutex is returned on every call that has
 23899  ** the same type number.
 23900  */
 23901  static sqlite3_mutex *pthreadMutexAlloc(int iType){
 23902    static sqlite3_mutex staticMutexes[] = {
 23903      SQLITE3_MUTEX_INITIALIZER,
 23904      SQLITE3_MUTEX_INITIALIZER,
 23905      SQLITE3_MUTEX_INITIALIZER,
 23906      SQLITE3_MUTEX_INITIALIZER,
 23907      SQLITE3_MUTEX_INITIALIZER,
 23908      SQLITE3_MUTEX_INITIALIZER,
 23909      SQLITE3_MUTEX_INITIALIZER,
 23910      SQLITE3_MUTEX_INITIALIZER,
 23911      SQLITE3_MUTEX_INITIALIZER,
 23912      SQLITE3_MUTEX_INITIALIZER,
 23913      SQLITE3_MUTEX_INITIALIZER,
 23914      SQLITE3_MUTEX_INITIALIZER
 23915    };
 23916    sqlite3_mutex *p;
 23917    switch( iType ){
 23918      case SQLITE_MUTEX_RECURSIVE: {
 23919        p = sqlite3MallocZero( sizeof(*p) );
 23920        if( p ){
 23921  #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
 23922          /* If recursive mutexes are not available, we will have to
 23923          ** build our own.  See below. */
 23924          pthread_mutex_init(&p->mutex, 0);
 23925  #else
 23926          /* Use a recursive mutex if it is available */
 23927          pthread_mutexattr_t recursiveAttr;
 23928          pthread_mutexattr_init(&recursiveAttr);
 23929          pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
 23930          pthread_mutex_init(&p->mutex, &recursiveAttr);
 23931          pthread_mutexattr_destroy(&recursiveAttr);
 23932  #endif
 23933        }
 23934        break;
 23935      }
 23936      case SQLITE_MUTEX_FAST: {
 23937        p = sqlite3MallocZero( sizeof(*p) );
 23938        if( p ){
 23939          pthread_mutex_init(&p->mutex, 0);
 23940        }
 23941        break;
 23942      }
 23943      default: {
 23944  #ifdef SQLITE_ENABLE_API_ARMOR
 23945        if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
 23946          (void)SQLITE_MISUSE_BKPT;
 23947          return 0;
 23948        }
 23949  #endif
 23950        p = &staticMutexes[iType-2];
 23951        break;
 23952      }
 23953    }
 23954  #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
 23955    if( p ) p->id = iType;
 23956  #endif
 23957    return p;
 23958  }
 23959  
 23960  
 23961  /*
 23962  ** This routine deallocates a previously
 23963  ** allocated mutex.  SQLite is careful to deallocate every
 23964  ** mutex that it allocates.
 23965  */
 23966  static void pthreadMutexFree(sqlite3_mutex *p){
 23967    assert( p->nRef==0 );
 23968  #if SQLITE_ENABLE_API_ARMOR
 23969    if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
 23970  #endif
 23971    {
 23972      pthread_mutex_destroy(&p->mutex);
 23973      sqlite3_free(p);
 23974    }
 23975  #ifdef SQLITE_ENABLE_API_ARMOR
 23976    else{
 23977      (void)SQLITE_MISUSE_BKPT;
 23978    }
 23979  #endif
 23980  }
 23981  
 23982  /*
 23983  ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
 23984  ** to enter a mutex.  If another thread is already within the mutex,
 23985  ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
 23986  ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
 23987  ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
 23988  ** be entered multiple times by the same thread.  In such cases the,
 23989  ** mutex must be exited an equal number of times before another thread
 23990  ** can enter.  If the same thread tries to enter any other kind of mutex
 23991  ** more than once, the behavior is undefined.
 23992  */
 23993  static void pthreadMutexEnter(sqlite3_mutex *p){
 23994    assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
 23995  
 23996  #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
 23997    /* If recursive mutexes are not available, then we have to grow
 23998    ** our own.  This implementation assumes that pthread_equal()
 23999    ** is atomic - that it cannot be deceived into thinking self
 24000    ** and p->owner are equal if p->owner changes between two values
 24001    ** that are not equal to self while the comparison is taking place.
 24002    ** This implementation also assumes a coherent cache - that 
 24003    ** separate processes cannot read different values from the same
 24004    ** address at the same time.  If either of these two conditions
 24005    ** are not met, then the mutexes will fail and problems will result.
 24006    */
 24007    {
 24008      pthread_t self = pthread_self();
 24009      if( p->nRef>0 && pthread_equal(p->owner, self) ){
 24010        p->nRef++;
 24011      }else{
 24012        pthread_mutex_lock(&p->mutex);
 24013        assert( p->nRef==0 );
 24014        p->owner = self;
 24015        p->nRef = 1;
 24016      }
 24017    }
 24018  #else
 24019    /* Use the built-in recursive mutexes if they are available.
 24020    */
 24021    pthread_mutex_lock(&p->mutex);
 24022  #if SQLITE_MUTEX_NREF
 24023    assert( p->nRef>0 || p->owner==0 );
 24024    p->owner = pthread_self();
 24025    p->nRef++;
 24026  #endif
 24027  #endif
 24028  
 24029  #ifdef SQLITE_DEBUG
 24030    if( p->trace ){
 24031      printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
 24032    }
 24033  #endif
 24034  }
 24035  static int pthreadMutexTry(sqlite3_mutex *p){
 24036    int rc;
 24037    assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
 24038  
 24039  #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
 24040    /* If recursive mutexes are not available, then we have to grow
 24041    ** our own.  This implementation assumes that pthread_equal()
 24042    ** is atomic - that it cannot be deceived into thinking self
 24043    ** and p->owner are equal if p->owner changes between two values
 24044    ** that are not equal to self while the comparison is taking place.
 24045    ** This implementation also assumes a coherent cache - that 
 24046    ** separate processes cannot read different values from the same
 24047    ** address at the same time.  If either of these two conditions
 24048    ** are not met, then the mutexes will fail and problems will result.
 24049    */
 24050    {
 24051      pthread_t self = pthread_self();
 24052      if( p->nRef>0 && pthread_equal(p->owner, self) ){
 24053        p->nRef++;
 24054        rc = SQLITE_OK;
 24055      }else if( pthread_mutex_trylock(&p->mutex)==0 ){
 24056        assert( p->nRef==0 );
 24057        p->owner = self;
 24058        p->nRef = 1;
 24059        rc = SQLITE_OK;
 24060      }else{
 24061        rc = SQLITE_BUSY;
 24062      }
 24063    }
 24064  #else
 24065    /* Use the built-in recursive mutexes if they are available.
 24066    */
 24067    if( pthread_mutex_trylock(&p->mutex)==0 ){
 24068  #if SQLITE_MUTEX_NREF
 24069      p->owner = pthread_self();
 24070      p->nRef++;
 24071  #endif
 24072      rc = SQLITE_OK;
 24073    }else{
 24074      rc = SQLITE_BUSY;
 24075    }
 24076  #endif
 24077  
 24078  #ifdef SQLITE_DEBUG
 24079    if( rc==SQLITE_OK && p->trace ){
 24080      printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
 24081    }
 24082  #endif
 24083    return rc;
 24084  }
 24085  
 24086  /*
 24087  ** The sqlite3_mutex_leave() routine exits a mutex that was
 24088  ** previously entered by the same thread.  The behavior
 24089  ** is undefined if the mutex is not currently entered or
 24090  ** is not currently allocated.  SQLite will never do either.
 24091  */
 24092  static void pthreadMutexLeave(sqlite3_mutex *p){
 24093    assert( pthreadMutexHeld(p) );
 24094  #if SQLITE_MUTEX_NREF
 24095    p->nRef--;
 24096    if( p->nRef==0 ) p->owner = 0;
 24097  #endif
 24098    assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
 24099  
 24100  #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
 24101    if( p->nRef==0 ){
 24102      pthread_mutex_unlock(&p->mutex);
 24103    }
 24104  #else
 24105    pthread_mutex_unlock(&p->mutex);
 24106  #endif
 24107  
 24108  #ifdef SQLITE_DEBUG
 24109    if( p->trace ){
 24110      printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
 24111    }
 24112  #endif
 24113  }
 24114  
 24115  SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
 24116    static const sqlite3_mutex_methods sMutex = {
 24117      pthreadMutexInit,
 24118      pthreadMutexEnd,
 24119      pthreadMutexAlloc,
 24120      pthreadMutexFree,
 24121      pthreadMutexEnter,
 24122      pthreadMutexTry,
 24123      pthreadMutexLeave,
 24124  #ifdef SQLITE_DEBUG
 24125      pthreadMutexHeld,
 24126      pthreadMutexNotheld
 24127  #else
 24128      0,
 24129      0
 24130  #endif
 24131    };
 24132  
 24133    return &sMutex;
 24134  }
 24135  
 24136  #endif /* SQLITE_MUTEX_PTHREADS */
 24137  
 24138  /************** End of mutex_unix.c ******************************************/
 24139  /************** Begin file mutex_w32.c ***************************************/
 24140  /*
 24141  ** 2007 August 14
 24142  **
 24143  ** The author disclaims copyright to this source code.  In place of
 24144  ** a legal notice, here is a blessing:
 24145  **
 24146  **    May you do good and not evil.
 24147  **    May you find forgiveness for yourself and forgive others.
 24148  **    May you share freely, never taking more than you give.
 24149  **
 24150  *************************************************************************
 24151  ** This file contains the C functions that implement mutexes for Win32.
 24152  */
 24153  /* #include "sqliteInt.h" */
 24154  
 24155  #if SQLITE_OS_WIN
 24156  /*
 24157  ** Include code that is common to all os_*.c files
 24158  */
 24159  /************** Include os_common.h in the middle of mutex_w32.c *************/
 24160  /************** Begin file os_common.h ***************************************/
 24161  /*
 24162  ** 2004 May 22
 24163  **
 24164  ** The author disclaims copyright to this source code.  In place of
 24165  ** a legal notice, here is a blessing:
 24166  **
 24167  **    May you do good and not evil.
 24168  **    May you find forgiveness for yourself and forgive others.
 24169  **    May you share freely, never taking more than you give.
 24170  **
 24171  ******************************************************************************
 24172  **
 24173  ** This file contains macros and a little bit of code that is common to
 24174  ** all of the platform-specific files (os_*.c) and is #included into those
 24175  ** files.
 24176  **
 24177  ** This file should be #included by the os_*.c files only.  It is not a
 24178  ** general purpose header file.
 24179  */
 24180  #ifndef _OS_COMMON_H_
 24181  #define _OS_COMMON_H_
 24182  
 24183  /*
 24184  ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
 24185  ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
 24186  ** switch.  The following code should catch this problem at compile-time.
 24187  */
 24188  #ifdef MEMORY_DEBUG
 24189  # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
 24190  #endif
 24191  
 24192  /*
 24193  ** Macros for performance tracing.  Normally turned off.  Only works
 24194  ** on i486 hardware.
 24195  */
 24196  #ifdef SQLITE_PERFORMANCE_TRACE
 24197  
 24198  /*
 24199  ** hwtime.h contains inline assembler code for implementing
 24200  ** high-performance timing routines.
 24201  */
 24202  /************** Include hwtime.h in the middle of os_common.h ****************/
 24203  /************** Begin file hwtime.h ******************************************/
 24204  /*
 24205  ** 2008 May 27
 24206  **
 24207  ** The author disclaims copyright to this source code.  In place of
 24208  ** a legal notice, here is a blessing:
 24209  **
 24210  **    May you do good and not evil.
 24211  **    May you find forgiveness for yourself and forgive others.
 24212  **    May you share freely, never taking more than you give.
 24213  **
 24214  ******************************************************************************
 24215  **
 24216  ** This file contains inline asm code for retrieving "high-performance"
 24217  ** counters for x86 class CPUs.
 24218  */
 24219  #ifndef SQLITE_HWTIME_H
 24220  #define SQLITE_HWTIME_H
 24221  
 24222  /*
 24223  ** The following routine only works on pentium-class (or newer) processors.
 24224  ** It uses the RDTSC opcode to read the cycle count value out of the
 24225  ** processor and returns that value.  This can be used for high-res
 24226  ** profiling.
 24227  */
 24228  #if (defined(__GNUC__) || defined(_MSC_VER)) && \
 24229        (defined(i386) || defined(__i386__) || defined(_M_IX86))
 24230  
 24231    #if defined(__GNUC__)
 24232  
 24233    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 24234       unsigned int lo, hi;
 24235       __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
 24236       return (sqlite_uint64)hi << 32 | lo;
 24237    }
 24238  
 24239    #elif defined(_MSC_VER)
 24240  
 24241    __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
 24242       __asm {
 24243          rdtsc
 24244          ret       ; return value at EDX:EAX
 24245       }
 24246    }
 24247  
 24248    #endif
 24249  
 24250  #elif (defined(__GNUC__) && defined(__x86_64__))
 24251  
 24252    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 24253        unsigned long val;
 24254        __asm__ __volatile__ ("rdtsc" : "=A" (val));
 24255        return val;
 24256    }
 24257   
 24258  #elif (defined(__GNUC__) && defined(__ppc__))
 24259  
 24260    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 24261        unsigned long long retval;
 24262        unsigned long junk;
 24263        __asm__ __volatile__ ("\n\
 24264            1:      mftbu   %1\n\
 24265                    mftb    %L0\n\
 24266                    mftbu   %0\n\
 24267                    cmpw    %0,%1\n\
 24268                    bne     1b"
 24269                    : "=r" (retval), "=r" (junk));
 24270        return retval;
 24271    }
 24272  
 24273  #else
 24274  
 24275    #error Need implementation of sqlite3Hwtime() for your platform.
 24276  
 24277    /*
 24278    ** To compile without implementing sqlite3Hwtime() for your platform,
 24279    ** you can remove the above #error and use the following
 24280    ** stub function.  You will lose timing support for many
 24281    ** of the debugging and testing utilities, but it should at
 24282    ** least compile and run.
 24283    */
 24284  SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
 24285  
 24286  #endif
 24287  
 24288  #endif /* !defined(SQLITE_HWTIME_H) */
 24289  
 24290  /************** End of hwtime.h **********************************************/
 24291  /************** Continuing where we left off in os_common.h ******************/
 24292  
 24293  static sqlite_uint64 g_start;
 24294  static sqlite_uint64 g_elapsed;
 24295  #define TIMER_START       g_start=sqlite3Hwtime()
 24296  #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
 24297  #define TIMER_ELAPSED     g_elapsed
 24298  #else
 24299  #define TIMER_START
 24300  #define TIMER_END
 24301  #define TIMER_ELAPSED     ((sqlite_uint64)0)
 24302  #endif
 24303  
 24304  /*
 24305  ** If we compile with the SQLITE_TEST macro set, then the following block
 24306  ** of code will give us the ability to simulate a disk I/O error.  This
 24307  ** is used for testing the I/O recovery logic.
 24308  */
 24309  #if defined(SQLITE_TEST)
 24310  SQLITE_API extern int sqlite3_io_error_hit;
 24311  SQLITE_API extern int sqlite3_io_error_hardhit;
 24312  SQLITE_API extern int sqlite3_io_error_pending;
 24313  SQLITE_API extern int sqlite3_io_error_persist;
 24314  SQLITE_API extern int sqlite3_io_error_benign;
 24315  SQLITE_API extern int sqlite3_diskfull_pending;
 24316  SQLITE_API extern int sqlite3_diskfull;
 24317  #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
 24318  #define SimulateIOError(CODE)  \
 24319    if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
 24320         || sqlite3_io_error_pending-- == 1 )  \
 24321                { local_ioerr(); CODE; }
 24322  static void local_ioerr(){
 24323    IOTRACE(("IOERR\n"));
 24324    sqlite3_io_error_hit++;
 24325    if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
 24326  }
 24327  #define SimulateDiskfullError(CODE) \
 24328     if( sqlite3_diskfull_pending ){ \
 24329       if( sqlite3_diskfull_pending == 1 ){ \
 24330         local_ioerr(); \
 24331         sqlite3_diskfull = 1; \
 24332         sqlite3_io_error_hit = 1; \
 24333         CODE; \
 24334       }else{ \
 24335         sqlite3_diskfull_pending--; \
 24336       } \
 24337     }
 24338  #else
 24339  #define SimulateIOErrorBenign(X)
 24340  #define SimulateIOError(A)
 24341  #define SimulateDiskfullError(A)
 24342  #endif /* defined(SQLITE_TEST) */
 24343  
 24344  /*
 24345  ** When testing, keep a count of the number of open files.
 24346  */
 24347  #if defined(SQLITE_TEST)
 24348  SQLITE_API extern int sqlite3_open_file_count;
 24349  #define OpenCounter(X)  sqlite3_open_file_count+=(X)
 24350  #else
 24351  #define OpenCounter(X)
 24352  #endif /* defined(SQLITE_TEST) */
 24353  
 24354  #endif /* !defined(_OS_COMMON_H_) */
 24355  
 24356  /************** End of os_common.h *******************************************/
 24357  /************** Continuing where we left off in mutex_w32.c ******************/
 24358  
 24359  /*
 24360  ** Include the header file for the Windows VFS.
 24361  */
 24362  /************** Include os_win.h in the middle of mutex_w32.c ****************/
 24363  /************** Begin file os_win.h ******************************************/
 24364  /*
 24365  ** 2013 November 25
 24366  **
 24367  ** The author disclaims copyright to this source code.  In place of
 24368  ** a legal notice, here is a blessing:
 24369  **
 24370  **    May you do good and not evil.
 24371  **    May you find forgiveness for yourself and forgive others.
 24372  **    May you share freely, never taking more than you give.
 24373  **
 24374  ******************************************************************************
 24375  **
 24376  ** This file contains code that is specific to Windows.
 24377  */
 24378  #ifndef SQLITE_OS_WIN_H
 24379  #define SQLITE_OS_WIN_H
 24380  
 24381  /*
 24382  ** Include the primary Windows SDK header file.
 24383  */
 24384  #include "windows.h"
 24385  
 24386  #ifdef __CYGWIN__
 24387  # include <sys/cygwin.h>
 24388  # include <errno.h> /* amalgamator: dontcache */
 24389  #endif
 24390  
 24391  /*
 24392  ** Determine if we are dealing with Windows NT.
 24393  **
 24394  ** We ought to be able to determine if we are compiling for Windows 9x or
 24395  ** Windows NT using the _WIN32_WINNT macro as follows:
 24396  **
 24397  ** #if defined(_WIN32_WINNT)
 24398  ** # define SQLITE_OS_WINNT 1
 24399  ** #else
 24400  ** # define SQLITE_OS_WINNT 0
 24401  ** #endif
 24402  **
 24403  ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
 24404  ** it ought to, so the above test does not work.  We'll just assume that
 24405  ** everything is Windows NT unless the programmer explicitly says otherwise
 24406  ** by setting SQLITE_OS_WINNT to 0.
 24407  */
 24408  #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
 24409  # define SQLITE_OS_WINNT 1
 24410  #endif
 24411  
 24412  /*
 24413  ** Determine if we are dealing with Windows CE - which has a much reduced
 24414  ** API.
 24415  */
 24416  #if defined(_WIN32_WCE)
 24417  # define SQLITE_OS_WINCE 1
 24418  #else
 24419  # define SQLITE_OS_WINCE 0
 24420  #endif
 24421  
 24422  /*
 24423  ** Determine if we are dealing with WinRT, which provides only a subset of
 24424  ** the full Win32 API.
 24425  */
 24426  #if !defined(SQLITE_OS_WINRT)
 24427  # define SQLITE_OS_WINRT 0
 24428  #endif
 24429  
 24430  /*
 24431  ** For WinCE, some API function parameters do not appear to be declared as
 24432  ** volatile.
 24433  */
 24434  #if SQLITE_OS_WINCE
 24435  # define SQLITE_WIN32_VOLATILE
 24436  #else
 24437  # define SQLITE_WIN32_VOLATILE volatile
 24438  #endif
 24439  
 24440  /*
 24441  ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
 24442  ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
 24443  */
 24444  #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
 24445      SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
 24446  # define SQLITE_OS_WIN_THREADS 1
 24447  #else
 24448  # define SQLITE_OS_WIN_THREADS 0
 24449  #endif
 24450  
 24451  #endif /* SQLITE_OS_WIN_H */
 24452  
 24453  /************** End of os_win.h **********************************************/
 24454  /************** Continuing where we left off in mutex_w32.c ******************/
 24455  #endif
 24456  
 24457  /*
 24458  ** The code in this file is only used if we are compiling multithreaded
 24459  ** on a Win32 system.
 24460  */
 24461  #ifdef SQLITE_MUTEX_W32
 24462  
 24463  /*
 24464  ** Each recursive mutex is an instance of the following structure.
 24465  */
 24466  struct sqlite3_mutex {
 24467    CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
 24468    int id;                    /* Mutex type */
 24469  #ifdef SQLITE_DEBUG
 24470    volatile int nRef;         /* Number of enterances */
 24471    volatile DWORD owner;      /* Thread holding this mutex */
 24472    volatile int trace;        /* True to trace changes */
 24473  #endif
 24474  };
 24475  
 24476  /*
 24477  ** These are the initializer values used when declaring a "static" mutex
 24478  ** on Win32.  It should be noted that all mutexes require initialization
 24479  ** on the Win32 platform.
 24480  */
 24481  #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
 24482  
 24483  #ifdef SQLITE_DEBUG
 24484  #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
 24485                                      0L, (DWORD)0, 0 }
 24486  #else
 24487  #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
 24488  #endif
 24489  
 24490  #ifdef SQLITE_DEBUG
 24491  /*
 24492  ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
 24493  ** intended for use only inside assert() statements.
 24494  */
 24495  static int winMutexHeld(sqlite3_mutex *p){
 24496    return p->nRef!=0 && p->owner==GetCurrentThreadId();
 24497  }
 24498  
 24499  static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
 24500    return p->nRef==0 || p->owner!=tid;
 24501  }
 24502  
 24503  static int winMutexNotheld(sqlite3_mutex *p){
 24504    DWORD tid = GetCurrentThreadId();
 24505    return winMutexNotheld2(p, tid);
 24506  }
 24507  #endif
 24508  
 24509  /*
 24510  ** Try to provide a memory barrier operation, needed for initialization
 24511  ** and also for the xShmBarrier method of the VFS in cases when SQLite is
 24512  ** compiled without mutexes (SQLITE_THREADSAFE=0).
 24513  */
 24514  SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
 24515  #if defined(SQLITE_MEMORY_BARRIER)
 24516    SQLITE_MEMORY_BARRIER;
 24517  #elif defined(__GNUC__)
 24518    __sync_synchronize();
 24519  #elif MSVC_VERSION>=1300
 24520    _ReadWriteBarrier();
 24521  #elif defined(MemoryBarrier)
 24522    MemoryBarrier();
 24523  #endif
 24524  }
 24525  
 24526  /*
 24527  ** Initialize and deinitialize the mutex subsystem.
 24528  */
 24529  static sqlite3_mutex winMutex_staticMutexes[] = {
 24530    SQLITE3_MUTEX_INITIALIZER,
 24531    SQLITE3_MUTEX_INITIALIZER,
 24532    SQLITE3_MUTEX_INITIALIZER,
 24533    SQLITE3_MUTEX_INITIALIZER,
 24534    SQLITE3_MUTEX_INITIALIZER,
 24535    SQLITE3_MUTEX_INITIALIZER,
 24536    SQLITE3_MUTEX_INITIALIZER,
 24537    SQLITE3_MUTEX_INITIALIZER,
 24538    SQLITE3_MUTEX_INITIALIZER,
 24539    SQLITE3_MUTEX_INITIALIZER,
 24540    SQLITE3_MUTEX_INITIALIZER,
 24541    SQLITE3_MUTEX_INITIALIZER
 24542  };
 24543  
 24544  static int winMutex_isInit = 0;
 24545  static int winMutex_isNt = -1; /* <0 means "need to query" */
 24546  
 24547  /* As the winMutexInit() and winMutexEnd() functions are called as part
 24548  ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
 24549  ** "interlocked" magic used here is probably not strictly necessary.
 24550  */
 24551  static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
 24552  
 24553  SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
 24554  SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
 24555  
 24556  static int winMutexInit(void){
 24557    /* The first to increment to 1 does actual initialization */
 24558    if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
 24559      int i;
 24560      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
 24561  #if SQLITE_OS_WINRT
 24562        InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
 24563  #else
 24564        InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
 24565  #endif
 24566      }
 24567      winMutex_isInit = 1;
 24568    }else{
 24569      /* Another thread is (in the process of) initializing the static
 24570      ** mutexes */
 24571      while( !winMutex_isInit ){
 24572        sqlite3_win32_sleep(1);
 24573      }
 24574    }
 24575    return SQLITE_OK;
 24576  }
 24577  
 24578  static int winMutexEnd(void){
 24579    /* The first to decrement to 0 does actual shutdown
 24580    ** (which should be the last to shutdown.) */
 24581    if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
 24582      if( winMutex_isInit==1 ){
 24583        int i;
 24584        for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
 24585          DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
 24586        }
 24587        winMutex_isInit = 0;
 24588      }
 24589    }
 24590    return SQLITE_OK;
 24591  }
 24592  
 24593  /*
 24594  ** The sqlite3_mutex_alloc() routine allocates a new
 24595  ** mutex and returns a pointer to it.  If it returns NULL
 24596  ** that means that a mutex could not be allocated.  SQLite
 24597  ** will unwind its stack and return an error.  The argument
 24598  ** to sqlite3_mutex_alloc() is one of these integer constants:
 24599  **
 24600  ** <ul>
 24601  ** <li>  SQLITE_MUTEX_FAST
 24602  ** <li>  SQLITE_MUTEX_RECURSIVE
 24603  ** <li>  SQLITE_MUTEX_STATIC_MASTER
 24604  ** <li>  SQLITE_MUTEX_STATIC_MEM
 24605  ** <li>  SQLITE_MUTEX_STATIC_OPEN
 24606  ** <li>  SQLITE_MUTEX_STATIC_PRNG
 24607  ** <li>  SQLITE_MUTEX_STATIC_LRU
 24608  ** <li>  SQLITE_MUTEX_STATIC_PMEM
 24609  ** <li>  SQLITE_MUTEX_STATIC_APP1
 24610  ** <li>  SQLITE_MUTEX_STATIC_APP2
 24611  ** <li>  SQLITE_MUTEX_STATIC_APP3
 24612  ** <li>  SQLITE_MUTEX_STATIC_VFS1
 24613  ** <li>  SQLITE_MUTEX_STATIC_VFS2
 24614  ** <li>  SQLITE_MUTEX_STATIC_VFS3
 24615  ** </ul>
 24616  **
 24617  ** The first two constants cause sqlite3_mutex_alloc() to create
 24618  ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
 24619  ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
 24620  ** The mutex implementation does not need to make a distinction
 24621  ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
 24622  ** not want to.  But SQLite will only request a recursive mutex in
 24623  ** cases where it really needs one.  If a faster non-recursive mutex
 24624  ** implementation is available on the host platform, the mutex subsystem
 24625  ** might return such a mutex in response to SQLITE_MUTEX_FAST.
 24626  **
 24627  ** The other allowed parameters to sqlite3_mutex_alloc() each return
 24628  ** a pointer to a static preexisting mutex.  Six static mutexes are
 24629  ** used by the current version of SQLite.  Future versions of SQLite
 24630  ** may add additional static mutexes.  Static mutexes are for internal
 24631  ** use by SQLite only.  Applications that use SQLite mutexes should
 24632  ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
 24633  ** SQLITE_MUTEX_RECURSIVE.
 24634  **
 24635  ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
 24636  ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
 24637  ** returns a different mutex on every call.  But for the static
 24638  ** mutex types, the same mutex is returned on every call that has
 24639  ** the same type number.
 24640  */
 24641  static sqlite3_mutex *winMutexAlloc(int iType){
 24642    sqlite3_mutex *p;
 24643  
 24644    switch( iType ){
 24645      case SQLITE_MUTEX_FAST:
 24646      case SQLITE_MUTEX_RECURSIVE: {
 24647        p = sqlite3MallocZero( sizeof(*p) );
 24648        if( p ){
 24649          p->id = iType;
 24650  #ifdef SQLITE_DEBUG
 24651  #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
 24652          p->trace = 1;
 24653  #endif
 24654  #endif
 24655  #if SQLITE_OS_WINRT
 24656          InitializeCriticalSectionEx(&p->mutex, 0, 0);
 24657  #else
 24658          InitializeCriticalSection(&p->mutex);
 24659  #endif
 24660        }
 24661        break;
 24662      }
 24663      default: {
 24664  #ifdef SQLITE_ENABLE_API_ARMOR
 24665        if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
 24666          (void)SQLITE_MISUSE_BKPT;
 24667          return 0;
 24668        }
 24669  #endif
 24670        p = &winMutex_staticMutexes[iType-2];
 24671        p->id = iType;
 24672  #ifdef SQLITE_DEBUG
 24673  #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
 24674        p->trace = 1;
 24675  #endif
 24676  #endif
 24677        break;
 24678      }
 24679    }
 24680    return p;
 24681  }
 24682  
 24683  
 24684  /*
 24685  ** This routine deallocates a previously
 24686  ** allocated mutex.  SQLite is careful to deallocate every
 24687  ** mutex that it allocates.
 24688  */
 24689  static void winMutexFree(sqlite3_mutex *p){
 24690    assert( p );
 24691    assert( p->nRef==0 && p->owner==0 );
 24692    if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
 24693      DeleteCriticalSection(&p->mutex);
 24694      sqlite3_free(p);
 24695    }else{
 24696  #ifdef SQLITE_ENABLE_API_ARMOR
 24697      (void)SQLITE_MISUSE_BKPT;
 24698  #endif
 24699    }
 24700  }
 24701  
 24702  /*
 24703  ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
 24704  ** to enter a mutex.  If another thread is already within the mutex,
 24705  ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
 24706  ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
 24707  ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
 24708  ** be entered multiple times by the same thread.  In such cases the,
 24709  ** mutex must be exited an equal number of times before another thread
 24710  ** can enter.  If the same thread tries to enter any other kind of mutex
 24711  ** more than once, the behavior is undefined.
 24712  */
 24713  static void winMutexEnter(sqlite3_mutex *p){
 24714  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
 24715    DWORD tid = GetCurrentThreadId();
 24716  #endif
 24717  #ifdef SQLITE_DEBUG
 24718    assert( p );
 24719    assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
 24720  #else
 24721    assert( p );
 24722  #endif
 24723    assert( winMutex_isInit==1 );
 24724    EnterCriticalSection(&p->mutex);
 24725  #ifdef SQLITE_DEBUG
 24726    assert( p->nRef>0 || p->owner==0 );
 24727    p->owner = tid;
 24728    p->nRef++;
 24729    if( p->trace ){
 24730      OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
 24731               tid, p->id, p, p->trace, p->nRef));
 24732    }
 24733  #endif
 24734  }
 24735  
 24736  static int winMutexTry(sqlite3_mutex *p){
 24737  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
 24738    DWORD tid = GetCurrentThreadId();
 24739  #endif
 24740    int rc = SQLITE_BUSY;
 24741    assert( p );
 24742    assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
 24743    /*
 24744    ** The sqlite3_mutex_try() routine is very rarely used, and when it
 24745    ** is used it is merely an optimization.  So it is OK for it to always
 24746    ** fail.
 24747    **
 24748    ** The TryEnterCriticalSection() interface is only available on WinNT.
 24749    ** And some windows compilers complain if you try to use it without
 24750    ** first doing some #defines that prevent SQLite from building on Win98.
 24751    ** For that reason, we will omit this optimization for now.  See
 24752    ** ticket #2685.
 24753    */
 24754  #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
 24755    assert( winMutex_isInit==1 );
 24756    assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
 24757    if( winMutex_isNt<0 ){
 24758      winMutex_isNt = sqlite3_win32_is_nt();
 24759    }
 24760    assert( winMutex_isNt==0 || winMutex_isNt==1 );
 24761    if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
 24762  #ifdef SQLITE_DEBUG
 24763      p->owner = tid;
 24764      p->nRef++;
 24765  #endif
 24766      rc = SQLITE_OK;
 24767    }
 24768  #else
 24769    UNUSED_PARAMETER(p);
 24770  #endif
 24771  #ifdef SQLITE_DEBUG
 24772    if( p->trace ){
 24773      OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
 24774               tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
 24775    }
 24776  #endif
 24777    return rc;
 24778  }
 24779  
 24780  /*
 24781  ** The sqlite3_mutex_leave() routine exits a mutex that was
 24782  ** previously entered by the same thread.  The behavior
 24783  ** is undefined if the mutex is not currently entered or
 24784  ** is not currently allocated.  SQLite will never do either.
 24785  */
 24786  static void winMutexLeave(sqlite3_mutex *p){
 24787  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
 24788    DWORD tid = GetCurrentThreadId();
 24789  #endif
 24790    assert( p );
 24791  #ifdef SQLITE_DEBUG
 24792    assert( p->nRef>0 );
 24793    assert( p->owner==tid );
 24794    p->nRef--;
 24795    if( p->nRef==0 ) p->owner = 0;
 24796    assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
 24797  #endif
 24798    assert( winMutex_isInit==1 );
 24799    LeaveCriticalSection(&p->mutex);
 24800  #ifdef SQLITE_DEBUG
 24801    if( p->trace ){
 24802      OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
 24803               tid, p->id, p, p->trace, p->nRef));
 24804    }
 24805  #endif
 24806  }
 24807  
 24808  SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
 24809    static const sqlite3_mutex_methods sMutex = {
 24810      winMutexInit,
 24811      winMutexEnd,
 24812      winMutexAlloc,
 24813      winMutexFree,
 24814      winMutexEnter,
 24815      winMutexTry,
 24816      winMutexLeave,
 24817  #ifdef SQLITE_DEBUG
 24818      winMutexHeld,
 24819      winMutexNotheld
 24820  #else
 24821      0,
 24822      0
 24823  #endif
 24824    };
 24825    return &sMutex;
 24826  }
 24827  
 24828  #endif /* SQLITE_MUTEX_W32 */
 24829  
 24830  /************** End of mutex_w32.c *******************************************/
 24831  /************** Begin file malloc.c ******************************************/
 24832  /*
 24833  ** 2001 September 15
 24834  **
 24835  ** The author disclaims copyright to this source code.  In place of
 24836  ** a legal notice, here is a blessing:
 24837  **
 24838  **    May you do good and not evil.
 24839  **    May you find forgiveness for yourself and forgive others.
 24840  **    May you share freely, never taking more than you give.
 24841  **
 24842  *************************************************************************
 24843  **
 24844  ** Memory allocation functions used throughout sqlite.
 24845  */
 24846  /* #include "sqliteInt.h" */
 24847  /* #include <stdarg.h> */
 24848  
 24849  /*
 24850  ** Attempt to release up to n bytes of non-essential memory currently
 24851  ** held by SQLite. An example of non-essential memory is memory used to
 24852  ** cache database pages that are not currently in use.
 24853  */
 24854  SQLITE_API int sqlite3_release_memory(int n){
 24855  #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
 24856    return sqlite3PcacheReleaseMemory(n);
 24857  #else
 24858    /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
 24859    ** is a no-op returning zero if SQLite is not compiled with
 24860    ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
 24861    UNUSED_PARAMETER(n);
 24862    return 0;
 24863  #endif
 24864  }
 24865  
 24866  /*
 24867  ** State information local to the memory allocation subsystem.
 24868  */
 24869  static SQLITE_WSD struct Mem0Global {
 24870    sqlite3_mutex *mutex;         /* Mutex to serialize access */
 24871    sqlite3_int64 alarmThreshold; /* The soft heap limit */
 24872  
 24873    /*
 24874    ** True if heap is nearly "full" where "full" is defined by the
 24875    ** sqlite3_soft_heap_limit() setting.
 24876    */
 24877    int nearlyFull;
 24878  } mem0 = { 0, 0, 0 };
 24879  
 24880  #define mem0 GLOBAL(struct Mem0Global, mem0)
 24881  
 24882  /*
 24883  ** Return the memory allocator mutex. sqlite3_status() needs it.
 24884  */
 24885  SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
 24886    return mem0.mutex;
 24887  }
 24888  
 24889  #ifndef SQLITE_OMIT_DEPRECATED
 24890  /*
 24891  ** Deprecated external interface.  It used to set an alarm callback
 24892  ** that was invoked when memory usage grew too large.  Now it is a
 24893  ** no-op.
 24894  */
 24895  SQLITE_API int sqlite3_memory_alarm(
 24896    void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
 24897    void *pArg,
 24898    sqlite3_int64 iThreshold
 24899  ){
 24900    (void)xCallback;
 24901    (void)pArg;
 24902    (void)iThreshold;
 24903    return SQLITE_OK;
 24904  }
 24905  #endif
 24906  
 24907  /*
 24908  ** Set the soft heap-size limit for the library. Passing a zero or 
 24909  ** negative value indicates no limit.
 24910  */
 24911  SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
 24912    sqlite3_int64 priorLimit;
 24913    sqlite3_int64 excess;
 24914    sqlite3_int64 nUsed;
 24915  #ifndef SQLITE_OMIT_AUTOINIT
 24916    int rc = sqlite3_initialize();
 24917    if( rc ) return -1;
 24918  #endif
 24919    sqlite3_mutex_enter(mem0.mutex);
 24920    priorLimit = mem0.alarmThreshold;
 24921    if( n<0 ){
 24922      sqlite3_mutex_leave(mem0.mutex);
 24923      return priorLimit;
 24924    }
 24925    mem0.alarmThreshold = n;
 24926    nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
 24927    mem0.nearlyFull = (n>0 && n<=nUsed);
 24928    sqlite3_mutex_leave(mem0.mutex);
 24929    excess = sqlite3_memory_used() - n;
 24930    if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
 24931    return priorLimit;
 24932  }
 24933  SQLITE_API void sqlite3_soft_heap_limit(int n){
 24934    if( n<0 ) n = 0;
 24935    sqlite3_soft_heap_limit64(n);
 24936  }
 24937  
 24938  /*
 24939  ** Initialize the memory allocation subsystem.
 24940  */
 24941  SQLITE_PRIVATE int sqlite3MallocInit(void){
 24942    int rc;
 24943    if( sqlite3GlobalConfig.m.xMalloc==0 ){
 24944      sqlite3MemSetDefault();
 24945    }
 24946    memset(&mem0, 0, sizeof(mem0));
 24947    mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
 24948    if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
 24949        || sqlite3GlobalConfig.nPage<=0 ){
 24950      sqlite3GlobalConfig.pPage = 0;
 24951      sqlite3GlobalConfig.szPage = 0;
 24952    }
 24953    rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
 24954    if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
 24955    return rc;
 24956  }
 24957  
 24958  /*
 24959  ** Return true if the heap is currently under memory pressure - in other
 24960  ** words if the amount of heap used is close to the limit set by
 24961  ** sqlite3_soft_heap_limit().
 24962  */
 24963  SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
 24964    return mem0.nearlyFull;
 24965  }
 24966  
 24967  /*
 24968  ** Deinitialize the memory allocation subsystem.
 24969  */
 24970  SQLITE_PRIVATE void sqlite3MallocEnd(void){
 24971    if( sqlite3GlobalConfig.m.xShutdown ){
 24972      sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
 24973    }
 24974    memset(&mem0, 0, sizeof(mem0));
 24975  }
 24976  
 24977  /*
 24978  ** Return the amount of memory currently checked out.
 24979  */
 24980  SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
 24981    sqlite3_int64 res, mx;
 24982    sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
 24983    return res;
 24984  }
 24985  
 24986  /*
 24987  ** Return the maximum amount of memory that has ever been
 24988  ** checked out since either the beginning of this process
 24989  ** or since the most recent reset.
 24990  */
 24991  SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
 24992    sqlite3_int64 res, mx;
 24993    sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
 24994    return mx;
 24995  }
 24996  
 24997  /*
 24998  ** Trigger the alarm 
 24999  */
 25000  static void sqlite3MallocAlarm(int nByte){
 25001    if( mem0.alarmThreshold<=0 ) return;
 25002    sqlite3_mutex_leave(mem0.mutex);
 25003    sqlite3_release_memory(nByte);
 25004    sqlite3_mutex_enter(mem0.mutex);
 25005  }
 25006  
 25007  /*
 25008  ** Do a memory allocation with statistics and alarms.  Assume the
 25009  ** lock is already held.
 25010  */
 25011  static void mallocWithAlarm(int n, void **pp){
 25012    void *p;
 25013    int nFull;
 25014    assert( sqlite3_mutex_held(mem0.mutex) );
 25015    assert( n>0 );
 25016  
 25017    /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
 25018    ** implementation of malloc_good_size(), which must be called in debug
 25019    ** mode and specifically when the DMD "Dark Matter Detector" is enabled
 25020    ** or else a crash results.  Hence, do not attempt to optimize out the
 25021    ** following xRoundup() call. */
 25022    nFull = sqlite3GlobalConfig.m.xRoundup(n);
 25023  
 25024  #ifdef SQLITE_MAX_MEMORY
 25025    if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nFull>SQLITE_MAX_MEMORY ){
 25026      *pp = 0;
 25027      return;
 25028    }
 25029  #endif
 25030  
 25031    sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
 25032    if( mem0.alarmThreshold>0 ){
 25033      sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
 25034      if( nUsed >= mem0.alarmThreshold - nFull ){
 25035        mem0.nearlyFull = 1;
 25036        sqlite3MallocAlarm(nFull);
 25037      }else{
 25038        mem0.nearlyFull = 0;
 25039      }
 25040    }
 25041    p = sqlite3GlobalConfig.m.xMalloc(nFull);
 25042  #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
 25043    if( p==0 && mem0.alarmThreshold>0 ){
 25044      sqlite3MallocAlarm(nFull);
 25045      p = sqlite3GlobalConfig.m.xMalloc(nFull);
 25046    }
 25047  #endif
 25048    if( p ){
 25049      nFull = sqlite3MallocSize(p);
 25050      sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
 25051      sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
 25052    }
 25053    *pp = p;
 25054  }
 25055  
 25056  /*
 25057  ** Allocate memory.  This routine is like sqlite3_malloc() except that it
 25058  ** assumes the memory subsystem has already been initialized.
 25059  */
 25060  SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
 25061    void *p;
 25062    if( n==0 || n>=0x7fffff00 ){
 25063      /* A memory allocation of a number of bytes which is near the maximum
 25064      ** signed integer value might cause an integer overflow inside of the
 25065      ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
 25066      ** 255 bytes of overhead.  SQLite itself will never use anything near
 25067      ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
 25068      p = 0;
 25069    }else if( sqlite3GlobalConfig.bMemstat ){
 25070      sqlite3_mutex_enter(mem0.mutex);
 25071      mallocWithAlarm((int)n, &p);
 25072      sqlite3_mutex_leave(mem0.mutex);
 25073    }else{
 25074      p = sqlite3GlobalConfig.m.xMalloc((int)n);
 25075    }
 25076    assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-11148-40995 */
 25077    return p;
 25078  }
 25079  
 25080  /*
 25081  ** This version of the memory allocation is for use by the application.
 25082  ** First make sure the memory subsystem is initialized, then do the
 25083  ** allocation.
 25084  */
 25085  SQLITE_API void *sqlite3_malloc(int n){
 25086  #ifndef SQLITE_OMIT_AUTOINIT
 25087    if( sqlite3_initialize() ) return 0;
 25088  #endif
 25089    return n<=0 ? 0 : sqlite3Malloc(n);
 25090  }
 25091  SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
 25092  #ifndef SQLITE_OMIT_AUTOINIT
 25093    if( sqlite3_initialize() ) return 0;
 25094  #endif
 25095    return sqlite3Malloc(n);
 25096  }
 25097  
 25098  /*
 25099  ** TRUE if p is a lookaside memory allocation from db
 25100  */
 25101  #ifndef SQLITE_OMIT_LOOKASIDE
 25102  static int isLookaside(sqlite3 *db, void *p){
 25103    return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
 25104  }
 25105  #else
 25106  #define isLookaside(A,B) 0
 25107  #endif
 25108  
 25109  /*
 25110  ** Return the size of a memory allocation previously obtained from
 25111  ** sqlite3Malloc() or sqlite3_malloc().
 25112  */
 25113  SQLITE_PRIVATE int sqlite3MallocSize(void *p){
 25114    assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
 25115    return sqlite3GlobalConfig.m.xSize(p);
 25116  }
 25117  SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
 25118    assert( p!=0 );
 25119    if( db==0 || !isLookaside(db,p) ){
 25120  #ifdef SQLITE_DEBUG
 25121      if( db==0 ){
 25122        assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
 25123        assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
 25124      }else{
 25125        assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
 25126        assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
 25127      }
 25128  #endif
 25129      return sqlite3GlobalConfig.m.xSize(p);
 25130    }else{
 25131      assert( sqlite3_mutex_held(db->mutex) );
 25132      return db->lookaside.sz;
 25133    }
 25134  }
 25135  SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
 25136    assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
 25137    assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
 25138    return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
 25139  }
 25140  
 25141  /*
 25142  ** Free memory previously obtained from sqlite3Malloc().
 25143  */
 25144  SQLITE_API void sqlite3_free(void *p){
 25145    if( p==0 ) return;  /* IMP: R-49053-54554 */
 25146    assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
 25147    assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
 25148    if( sqlite3GlobalConfig.bMemstat ){
 25149      sqlite3_mutex_enter(mem0.mutex);
 25150      sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
 25151      sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
 25152      sqlite3GlobalConfig.m.xFree(p);
 25153      sqlite3_mutex_leave(mem0.mutex);
 25154    }else{
 25155      sqlite3GlobalConfig.m.xFree(p);
 25156    }
 25157  }
 25158  
 25159  /*
 25160  ** Add the size of memory allocation "p" to the count in
 25161  ** *db->pnBytesFreed.
 25162  */
 25163  static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
 25164    *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
 25165  }
 25166  
 25167  /*
 25168  ** Free memory that might be associated with a particular database
 25169  ** connection.  Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
 25170  ** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
 25171  */
 25172  SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3 *db, void *p){
 25173    assert( db==0 || sqlite3_mutex_held(db->mutex) );
 25174    assert( p!=0 );
 25175    if( db ){
 25176      if( db->pnBytesFreed ){
 25177        measureAllocationSize(db, p);
 25178        return;
 25179      }
 25180      if( isLookaside(db, p) ){
 25181        LookasideSlot *pBuf = (LookasideSlot*)p;
 25182  #ifdef SQLITE_DEBUG
 25183        /* Trash all content in the buffer being freed */
 25184        memset(p, 0xaa, db->lookaside.sz);
 25185  #endif
 25186        pBuf->pNext = db->lookaside.pFree;
 25187        db->lookaside.pFree = pBuf;
 25188        return;
 25189      }
 25190    }
 25191    assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
 25192    assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
 25193    assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
 25194    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
 25195    sqlite3_free(p);
 25196  }
 25197  SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
 25198    assert( db==0 || sqlite3_mutex_held(db->mutex) );
 25199    if( p ) sqlite3DbFreeNN(db, p);
 25200  }
 25201  
 25202  /*
 25203  ** Change the size of an existing memory allocation
 25204  */
 25205  SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
 25206    int nOld, nNew, nDiff;
 25207    void *pNew;
 25208    assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
 25209    assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
 25210    if( pOld==0 ){
 25211      return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
 25212    }
 25213    if( nBytes==0 ){
 25214      sqlite3_free(pOld); /* IMP: R-26507-47431 */
 25215      return 0;
 25216    }
 25217    if( nBytes>=0x7fffff00 ){
 25218      /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
 25219      return 0;
 25220    }
 25221    nOld = sqlite3MallocSize(pOld);
 25222    /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
 25223    ** argument to xRealloc is always a value returned by a prior call to
 25224    ** xRoundup. */
 25225    nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
 25226    if( nOld==nNew ){
 25227      pNew = pOld;
 25228    }else if( sqlite3GlobalConfig.bMemstat ){
 25229      sqlite3_mutex_enter(mem0.mutex);
 25230      sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
 25231      nDiff = nNew - nOld;
 25232      if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= 
 25233            mem0.alarmThreshold-nDiff ){
 25234        sqlite3MallocAlarm(nDiff);
 25235      }
 25236      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
 25237      if( pNew==0 && mem0.alarmThreshold>0 ){
 25238        sqlite3MallocAlarm((int)nBytes);
 25239        pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
 25240      }
 25241      if( pNew ){
 25242        nNew = sqlite3MallocSize(pNew);
 25243        sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
 25244      }
 25245      sqlite3_mutex_leave(mem0.mutex);
 25246    }else{
 25247      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
 25248    }
 25249    assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
 25250    return pNew;
 25251  }
 25252  
 25253  /*
 25254  ** The public interface to sqlite3Realloc.  Make sure that the memory
 25255  ** subsystem is initialized prior to invoking sqliteRealloc.
 25256  */
 25257  SQLITE_API void *sqlite3_realloc(void *pOld, int n){
 25258  #ifndef SQLITE_OMIT_AUTOINIT
 25259    if( sqlite3_initialize() ) return 0;
 25260  #endif
 25261    if( n<0 ) n = 0;  /* IMP: R-26507-47431 */
 25262    return sqlite3Realloc(pOld, n);
 25263  }
 25264  SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
 25265  #ifndef SQLITE_OMIT_AUTOINIT
 25266    if( sqlite3_initialize() ) return 0;
 25267  #endif
 25268    return sqlite3Realloc(pOld, n);
 25269  }
 25270  
 25271  
 25272  /*
 25273  ** Allocate and zero memory.
 25274  */ 
 25275  SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
 25276    void *p = sqlite3Malloc(n);
 25277    if( p ){
 25278      memset(p, 0, (size_t)n);
 25279    }
 25280    return p;
 25281  }
 25282  
 25283  /*
 25284  ** Allocate and zero memory.  If the allocation fails, make
 25285  ** the mallocFailed flag in the connection pointer.
 25286  */
 25287  SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
 25288    void *p;
 25289    testcase( db==0 );
 25290    p = sqlite3DbMallocRaw(db, n);
 25291    if( p ) memset(p, 0, (size_t)n);
 25292    return p;
 25293  }
 25294  
 25295  
 25296  /* Finish the work of sqlite3DbMallocRawNN for the unusual and
 25297  ** slower case when the allocation cannot be fulfilled using lookaside.
 25298  */
 25299  static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
 25300    void *p;
 25301    assert( db!=0 );
 25302    p = sqlite3Malloc(n);
 25303    if( !p ) sqlite3OomFault(db);
 25304    sqlite3MemdebugSetType(p, 
 25305           (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
 25306    return p;
 25307  }
 25308  
 25309  /*
 25310  ** Allocate memory, either lookaside (if possible) or heap.  
 25311  ** If the allocation fails, set the mallocFailed flag in
 25312  ** the connection pointer.
 25313  **
 25314  ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
 25315  ** failure on the same database connection) then always return 0.
 25316  ** Hence for a particular database connection, once malloc starts
 25317  ** failing, it fails consistently until mallocFailed is reset.
 25318  ** This is an important assumption.  There are many places in the
 25319  ** code that do things like this:
 25320  **
 25321  **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
 25322  **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
 25323  **         if( b ) a[10] = 9;
 25324  **
 25325  ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
 25326  ** that all prior mallocs (ex: "a") worked too.
 25327  **
 25328  ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
 25329  ** not a NULL pointer.
 25330  */
 25331  SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
 25332    void *p;
 25333    if( db ) return sqlite3DbMallocRawNN(db, n);
 25334    p = sqlite3Malloc(n);
 25335    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
 25336    return p;
 25337  }
 25338  SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
 25339  #ifndef SQLITE_OMIT_LOOKASIDE
 25340    LookasideSlot *pBuf;
 25341    assert( db!=0 );
 25342    assert( sqlite3_mutex_held(db->mutex) );
 25343    assert( db->pnBytesFreed==0 );
 25344    if( db->lookaside.bDisable==0 ){
 25345      assert( db->mallocFailed==0 );
 25346      if( n>db->lookaside.sz ){
 25347        db->lookaside.anStat[1]++;
 25348      }else if( (pBuf = db->lookaside.pFree)!=0 ){
 25349        db->lookaside.pFree = pBuf->pNext;
 25350        db->lookaside.anStat[0]++;
 25351        return (void*)pBuf;
 25352      }else if( (pBuf = db->lookaside.pInit)!=0 ){
 25353        db->lookaside.pInit = pBuf->pNext;
 25354        db->lookaside.anStat[0]++;
 25355        return (void*)pBuf;
 25356      }else{
 25357        db->lookaside.anStat[2]++;
 25358      }
 25359    }else if( db->mallocFailed ){
 25360      return 0;
 25361    }
 25362  #else
 25363    assert( db!=0 );
 25364    assert( sqlite3_mutex_held(db->mutex) );
 25365    assert( db->pnBytesFreed==0 );
 25366    if( db->mallocFailed ){
 25367      return 0;
 25368    }
 25369  #endif
 25370    return dbMallocRawFinish(db, n);
 25371  }
 25372  
 25373  /* Forward declaration */
 25374  static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
 25375  
 25376  /*
 25377  ** Resize the block of memory pointed to by p to n bytes. If the
 25378  ** resize fails, set the mallocFailed flag in the connection object.
 25379  */
 25380  SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
 25381    assert( db!=0 );
 25382    if( p==0 ) return sqlite3DbMallocRawNN(db, n);
 25383    assert( sqlite3_mutex_held(db->mutex) );
 25384    if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
 25385    return dbReallocFinish(db, p, n);
 25386  }
 25387  static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
 25388    void *pNew = 0;
 25389    assert( db!=0 );
 25390    assert( p!=0 );
 25391    if( db->mallocFailed==0 ){
 25392      if( isLookaside(db, p) ){
 25393        pNew = sqlite3DbMallocRawNN(db, n);
 25394        if( pNew ){
 25395          memcpy(pNew, p, db->lookaside.sz);
 25396          sqlite3DbFree(db, p);
 25397        }
 25398      }else{
 25399        assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
 25400        assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
 25401        sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
 25402        pNew = sqlite3_realloc64(p, n);
 25403        if( !pNew ){
 25404          sqlite3OomFault(db);
 25405        }
 25406        sqlite3MemdebugSetType(pNew,
 25407              (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
 25408      }
 25409    }
 25410    return pNew;
 25411  }
 25412  
 25413  /*
 25414  ** Attempt to reallocate p.  If the reallocation fails, then free p
 25415  ** and set the mallocFailed flag in the database connection.
 25416  */
 25417  SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
 25418    void *pNew;
 25419    pNew = sqlite3DbRealloc(db, p, n);
 25420    if( !pNew ){
 25421      sqlite3DbFree(db, p);
 25422    }
 25423    return pNew;
 25424  }
 25425  
 25426  /*
 25427  ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
 25428  ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
 25429  ** is because when memory debugging is turned on, these two functions are 
 25430  ** called via macros that record the current file and line number in the
 25431  ** ThreadData structure.
 25432  */
 25433  SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
 25434    char *zNew;
 25435    size_t n;
 25436    if( z==0 ){
 25437      return 0;
 25438    }
 25439    n = strlen(z) + 1;
 25440    zNew = sqlite3DbMallocRaw(db, n);
 25441    if( zNew ){
 25442      memcpy(zNew, z, n);
 25443    }
 25444    return zNew;
 25445  }
 25446  SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
 25447    char *zNew;
 25448    assert( db!=0 );
 25449    if( z==0 ){
 25450      return 0;
 25451    }
 25452    assert( (n&0x7fffffff)==n );
 25453    zNew = sqlite3DbMallocRawNN(db, n+1);
 25454    if( zNew ){
 25455      memcpy(zNew, z, (size_t)n);
 25456      zNew[n] = 0;
 25457    }
 25458    return zNew;
 25459  }
 25460  
 25461  /*
 25462  ** Free any prior content in *pz and replace it with a copy of zNew.
 25463  */
 25464  SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
 25465    sqlite3DbFree(db, *pz);
 25466    *pz = sqlite3DbStrDup(db, zNew);
 25467  }
 25468  
 25469  /*
 25470  ** Call this routine to record the fact that an OOM (out-of-memory) error
 25471  ** has happened.  This routine will set db->mallocFailed, and also
 25472  ** temporarily disable the lookaside memory allocator and interrupt
 25473  ** any running VDBEs.
 25474  */
 25475  SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
 25476    if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
 25477      db->mallocFailed = 1;
 25478      if( db->nVdbeExec>0 ){
 25479        db->u1.isInterrupted = 1;
 25480      }
 25481      db->lookaside.bDisable++;
 25482    }
 25483  }
 25484  
 25485  /*
 25486  ** This routine reactivates the memory allocator and clears the
 25487  ** db->mallocFailed flag as necessary.
 25488  **
 25489  ** The memory allocator is not restarted if there are running
 25490  ** VDBEs.
 25491  */
 25492  SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
 25493    if( db->mallocFailed && db->nVdbeExec==0 ){
 25494      db->mallocFailed = 0;
 25495      db->u1.isInterrupted = 0;
 25496      assert( db->lookaside.bDisable>0 );
 25497      db->lookaside.bDisable--;
 25498    }
 25499  }
 25500  
 25501  /*
 25502  ** Take actions at the end of an API call to indicate an OOM error
 25503  */
 25504  static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
 25505    sqlite3OomClear(db);
 25506    sqlite3Error(db, SQLITE_NOMEM);
 25507    return SQLITE_NOMEM_BKPT;
 25508  }
 25509  
 25510  /*
 25511  ** This function must be called before exiting any API function (i.e. 
 25512  ** returning control to the user) that has called sqlite3_malloc or
 25513  ** sqlite3_realloc.
 25514  **
 25515  ** The returned value is normally a copy of the second argument to this
 25516  ** function. However, if a malloc() failure has occurred since the previous
 25517  ** invocation SQLITE_NOMEM is returned instead. 
 25518  **
 25519  ** If an OOM as occurred, then the connection error-code (the value
 25520  ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
 25521  */
 25522  SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
 25523    /* If the db handle must hold the connection handle mutex here.
 25524    ** Otherwise the read (and possible write) of db->mallocFailed 
 25525    ** is unsafe, as is the call to sqlite3Error().
 25526    */
 25527    assert( db!=0 );
 25528    assert( sqlite3_mutex_held(db->mutex) );
 25529    if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
 25530      return apiOomError(db);
 25531    }
 25532    return rc & db->errMask;
 25533  }
 25534  
 25535  /************** End of malloc.c **********************************************/
 25536  /************** Begin file printf.c ******************************************/
 25537  /*
 25538  ** The "printf" code that follows dates from the 1980's.  It is in
 25539  ** the public domain. 
 25540  **
 25541  **************************************************************************
 25542  **
 25543  ** This file contains code for a set of "printf"-like routines.  These
 25544  ** routines format strings much like the printf() from the standard C
 25545  ** library, though the implementation here has enhancements to support
 25546  ** SQLite.
 25547  */
 25548  /* #include "sqliteInt.h" */
 25549  
 25550  /*
 25551  ** Conversion types fall into various categories as defined by the
 25552  ** following enumeration.
 25553  */
 25554  #define etRADIX       0 /* non-decimal integer types.  %x %o */
 25555  #define etFLOAT       1 /* Floating point.  %f */
 25556  #define etEXP         2 /* Exponentional notation. %e and %E */
 25557  #define etGENERIC     3 /* Floating or exponential, depending on exponent. %g */
 25558  #define etSIZE        4 /* Return number of characters processed so far. %n */
 25559  #define etSTRING      5 /* Strings. %s */
 25560  #define etDYNSTRING   6 /* Dynamically allocated strings. %z */
 25561  #define etPERCENT     7 /* Percent symbol. %% */
 25562  #define etCHARX       8 /* Characters. %c */
 25563  /* The rest are extensions, not normally found in printf() */
 25564  #define etSQLESCAPE   9 /* Strings with '\'' doubled.  %q */
 25565  #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
 25566                            NULL pointers replaced by SQL NULL.  %Q */
 25567  #define etTOKEN      11 /* a pointer to a Token structure */
 25568  #define etSRCLIST    12 /* a pointer to a SrcList */
 25569  #define etPOINTER    13 /* The %p conversion */
 25570  #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
 25571  #define etORDINAL    15 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
 25572  #define etDECIMAL    16 /* %d or %u, but not %x, %o */
 25573  
 25574  #define etINVALID    17 /* Any unrecognized conversion type */
 25575  
 25576  
 25577  /*
 25578  ** An "etByte" is an 8-bit unsigned value.
 25579  */
 25580  typedef unsigned char etByte;
 25581  
 25582  /*
 25583  ** Each builtin conversion character (ex: the 'd' in "%d") is described
 25584  ** by an instance of the following structure
 25585  */
 25586  typedef struct et_info {   /* Information about each format field */
 25587    char fmttype;            /* The format field code letter */
 25588    etByte base;             /* The base for radix conversion */
 25589    etByte flags;            /* One or more of FLAG_ constants below */
 25590    etByte type;             /* Conversion paradigm */
 25591    etByte charset;          /* Offset into aDigits[] of the digits string */
 25592    etByte prefix;           /* Offset into aPrefix[] of the prefix string */
 25593  } et_info;
 25594  
 25595  /*
 25596  ** Allowed values for et_info.flags
 25597  */
 25598  #define FLAG_SIGNED    1     /* True if the value to convert is signed */
 25599  #define FLAG_STRING    4     /* Allow infinite precision */
 25600  
 25601  
 25602  /*
 25603  ** The following table is searched linearly, so it is good to put the
 25604  ** most frequently used conversion types first.
 25605  */
 25606  static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
 25607  static const char aPrefix[] = "-x0\000X0";
 25608  static const et_info fmtinfo[] = {
 25609    {  'd', 10, 1, etDECIMAL,    0,  0 },
 25610    {  's',  0, 4, etSTRING,     0,  0 },
 25611    {  'g',  0, 1, etGENERIC,    30, 0 },
 25612    {  'z',  0, 4, etDYNSTRING,  0,  0 },
 25613    {  'q',  0, 4, etSQLESCAPE,  0,  0 },
 25614    {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
 25615    {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
 25616    {  'c',  0, 0, etCHARX,      0,  0 },
 25617    {  'o',  8, 0, etRADIX,      0,  2 },
 25618    {  'u', 10, 0, etDECIMAL,    0,  0 },
 25619    {  'x', 16, 0, etRADIX,      16, 1 },
 25620    {  'X', 16, 0, etRADIX,      0,  4 },
 25621  #ifndef SQLITE_OMIT_FLOATING_POINT
 25622    {  'f',  0, 1, etFLOAT,      0,  0 },
 25623    {  'e',  0, 1, etEXP,        30, 0 },
 25624    {  'E',  0, 1, etEXP,        14, 0 },
 25625    {  'G',  0, 1, etGENERIC,    14, 0 },
 25626  #endif
 25627    {  'i', 10, 1, etDECIMAL,    0,  0 },
 25628    {  'n',  0, 0, etSIZE,       0,  0 },
 25629    {  '%',  0, 0, etPERCENT,    0,  0 },
 25630    {  'p', 16, 0, etPOINTER,    0,  1 },
 25631  
 25632    /* All the rest are undocumented and are for internal use only */
 25633    {  'T',  0, 0, etTOKEN,      0,  0 },
 25634    {  'S',  0, 0, etSRCLIST,    0,  0 },
 25635    {  'r', 10, 1, etORDINAL,    0,  0 },
 25636  };
 25637  
 25638  /*
 25639  ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
 25640  ** conversions will work.
 25641  */
 25642  #ifndef SQLITE_OMIT_FLOATING_POINT
 25643  /*
 25644  ** "*val" is a double such that 0.1 <= *val < 10.0
 25645  ** Return the ascii code for the leading digit of *val, then
 25646  ** multiply "*val" by 10.0 to renormalize.
 25647  **
 25648  ** Example:
 25649  **     input:     *val = 3.14159
 25650  **     output:    *val = 1.4159    function return = '3'
 25651  **
 25652  ** The counter *cnt is incremented each time.  After counter exceeds
 25653  ** 16 (the number of significant digits in a 64-bit float) '0' is
 25654  ** always returned.
 25655  */
 25656  static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
 25657    int digit;
 25658    LONGDOUBLE_TYPE d;
 25659    if( (*cnt)<=0 ) return '0';
 25660    (*cnt)--;
 25661    digit = (int)*val;
 25662    d = digit;
 25663    digit += '0';
 25664    *val = (*val - d)*10.0;
 25665    return (char)digit;
 25666  }
 25667  #endif /* SQLITE_OMIT_FLOATING_POINT */
 25668  
 25669  /*
 25670  ** Set the StrAccum object to an error mode.
 25671  */
 25672  static void setStrAccumError(StrAccum *p, u8 eError){
 25673    assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
 25674    p->accError = eError;
 25675    p->nAlloc = 0;
 25676  }
 25677  
 25678  /*
 25679  ** Extra argument values from a PrintfArguments object
 25680  */
 25681  static sqlite3_int64 getIntArg(PrintfArguments *p){
 25682    if( p->nArg<=p->nUsed ) return 0;
 25683    return sqlite3_value_int64(p->apArg[p->nUsed++]);
 25684  }
 25685  static double getDoubleArg(PrintfArguments *p){
 25686    if( p->nArg<=p->nUsed ) return 0.0;
 25687    return sqlite3_value_double(p->apArg[p->nUsed++]);
 25688  }
 25689  static char *getTextArg(PrintfArguments *p){
 25690    if( p->nArg<=p->nUsed ) return 0;
 25691    return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
 25692  }
 25693  
 25694  
 25695  /*
 25696  ** On machines with a small stack size, you can redefine the
 25697  ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
 25698  */
 25699  #ifndef SQLITE_PRINT_BUF_SIZE
 25700  # define SQLITE_PRINT_BUF_SIZE 70
 25701  #endif
 25702  #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
 25703  
 25704  /*
 25705  ** Render a string given by "fmt" into the StrAccum object.
 25706  */
 25707  SQLITE_PRIVATE void sqlite3VXPrintf(
 25708    StrAccum *pAccum,          /* Accumulate results here */
 25709    const char *fmt,           /* Format string */
 25710    va_list ap                 /* arguments */
 25711  ){
 25712    int c;                     /* Next character in the format string */
 25713    char *bufpt;               /* Pointer to the conversion buffer */
 25714    int precision;             /* Precision of the current field */
 25715    int length;                /* Length of the field */
 25716    int idx;                   /* A general purpose loop counter */
 25717    int width;                 /* Width of the current field */
 25718    etByte flag_leftjustify;   /* True if "-" flag is present */
 25719    etByte flag_prefix;        /* '+' or ' ' or 0 for prefix */
 25720    etByte flag_alternateform; /* True if "#" flag is present */
 25721    etByte flag_altform2;      /* True if "!" flag is present */
 25722    etByte flag_zeropad;       /* True if field width constant starts with zero */
 25723    etByte flag_long;          /* 1 for the "l" flag, 2 for "ll", 0 by default */
 25724    etByte done;               /* Loop termination flag */
 25725    etByte cThousand;          /* Thousands separator for %d and %u */
 25726    etByte xtype = etINVALID;  /* Conversion paradigm */
 25727    u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
 25728    char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
 25729    sqlite_uint64 longvalue;   /* Value for integer types */
 25730    LONGDOUBLE_TYPE realvalue; /* Value for real types */
 25731    const et_info *infop;      /* Pointer to the appropriate info structure */
 25732    char *zOut;                /* Rendering buffer */
 25733    int nOut;                  /* Size of the rendering buffer */
 25734    char *zExtra = 0;          /* Malloced memory used by some conversion */
 25735  #ifndef SQLITE_OMIT_FLOATING_POINT
 25736    int  exp, e2;              /* exponent of real numbers */
 25737    int nsd;                   /* Number of significant digits returned */
 25738    double rounder;            /* Used for rounding floating point values */
 25739    etByte flag_dp;            /* True if decimal point should be shown */
 25740    etByte flag_rtz;           /* True if trailing zeros should be removed */
 25741  #endif
 25742    PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
 25743    char buf[etBUFSIZE];       /* Conversion buffer */
 25744  
 25745    bufpt = 0;
 25746    if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
 25747      pArgList = va_arg(ap, PrintfArguments*);
 25748      bArgList = 1;
 25749    }else{
 25750      bArgList = 0;
 25751    }
 25752    for(; (c=(*fmt))!=0; ++fmt){
 25753      if( c!='%' ){
 25754        bufpt = (char *)fmt;
 25755  #if HAVE_STRCHRNUL
 25756        fmt = strchrnul(fmt, '%');
 25757  #else
 25758        do{ fmt++; }while( *fmt && *fmt != '%' );
 25759  #endif
 25760        sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
 25761        if( *fmt==0 ) break;
 25762      }
 25763      if( (c=(*++fmt))==0 ){
 25764        sqlite3StrAccumAppend(pAccum, "%", 1);
 25765        break;
 25766      }
 25767      /* Find out what flags are present */
 25768      flag_leftjustify = flag_prefix = cThousand =
 25769       flag_alternateform = flag_altform2 = flag_zeropad = 0;
 25770      done = 0;
 25771      do{
 25772        switch( c ){
 25773          case '-':   flag_leftjustify = 1;     break;
 25774          case '+':   flag_prefix = '+';        break;
 25775          case ' ':   flag_prefix = ' ';        break;
 25776          case '#':   flag_alternateform = 1;   break;
 25777          case '!':   flag_altform2 = 1;        break;
 25778          case '0':   flag_zeropad = 1;         break;
 25779          case ',':   cThousand = ',';          break;
 25780          default:    done = 1;                 break;
 25781        }
 25782      }while( !done && (c=(*++fmt))!=0 );
 25783      /* Get the field width */
 25784      if( c=='*' ){
 25785        if( bArgList ){
 25786          width = (int)getIntArg(pArgList);
 25787        }else{
 25788          width = va_arg(ap,int);
 25789        }
 25790        if( width<0 ){
 25791          flag_leftjustify = 1;
 25792          width = width >= -2147483647 ? -width : 0;
 25793        }
 25794        c = *++fmt;
 25795      }else{
 25796        unsigned wx = 0;
 25797        while( c>='0' && c<='9' ){
 25798          wx = wx*10 + c - '0';
 25799          c = *++fmt;
 25800        }
 25801        testcase( wx>0x7fffffff );
 25802        width = wx & 0x7fffffff;
 25803      }
 25804      assert( width>=0 );
 25805  #ifdef SQLITE_PRINTF_PRECISION_LIMIT
 25806      if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
 25807        width = SQLITE_PRINTF_PRECISION_LIMIT;
 25808      }
 25809  #endif
 25810  
 25811      /* Get the precision */
 25812      if( c=='.' ){
 25813        c = *++fmt;
 25814        if( c=='*' ){
 25815          if( bArgList ){
 25816            precision = (int)getIntArg(pArgList);
 25817          }else{
 25818            precision = va_arg(ap,int);
 25819          }
 25820          c = *++fmt;
 25821          if( precision<0 ){
 25822            precision = precision >= -2147483647 ? -precision : -1;
 25823          }
 25824        }else{
 25825          unsigned px = 0;
 25826          while( c>='0' && c<='9' ){
 25827            px = px*10 + c - '0';
 25828            c = *++fmt;
 25829          }
 25830          testcase( px>0x7fffffff );
 25831          precision = px & 0x7fffffff;
 25832        }
 25833      }else{
 25834        precision = -1;
 25835      }
 25836      assert( precision>=(-1) );
 25837  #ifdef SQLITE_PRINTF_PRECISION_LIMIT
 25838      if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
 25839        precision = SQLITE_PRINTF_PRECISION_LIMIT;
 25840      }
 25841  #endif
 25842  
 25843  
 25844      /* Get the conversion type modifier */
 25845      if( c=='l' ){
 25846        flag_long = 1;
 25847        c = *++fmt;
 25848        if( c=='l' ){
 25849          flag_long = 2;
 25850          c = *++fmt;
 25851        }
 25852      }else{
 25853        flag_long = 0;
 25854      }
 25855      /* Fetch the info entry for the field */
 25856      infop = &fmtinfo[0];
 25857      xtype = etINVALID;
 25858      for(idx=0; idx<ArraySize(fmtinfo); idx++){
 25859        if( c==fmtinfo[idx].fmttype ){
 25860          infop = &fmtinfo[idx];
 25861          xtype = infop->type;
 25862          break;
 25863        }
 25864      }
 25865  
 25866      /*
 25867      ** At this point, variables are initialized as follows:
 25868      **
 25869      **   flag_alternateform          TRUE if a '#' is present.
 25870      **   flag_altform2               TRUE if a '!' is present.
 25871      **   flag_prefix                 '+' or ' ' or zero
 25872      **   flag_leftjustify            TRUE if a '-' is present or if the
 25873      **                               field width was negative.
 25874      **   flag_zeropad                TRUE if the width began with 0.
 25875      **   flag_long                   1 for "l", 2 for "ll"
 25876      **   width                       The specified field width.  This is
 25877      **                               always non-negative.  Zero is the default.
 25878      **   precision                   The specified precision.  The default
 25879      **                               is -1.
 25880      **   xtype                       The class of the conversion.
 25881      **   infop                       Pointer to the appropriate info struct.
 25882      */
 25883      switch( xtype ){
 25884        case etPOINTER:
 25885          flag_long = sizeof(char*)==sizeof(i64) ? 2 :
 25886                       sizeof(char*)==sizeof(long int) ? 1 : 0;
 25887          /* Fall through into the next case */
 25888        case etORDINAL:
 25889        case etRADIX:      
 25890          cThousand = 0;
 25891          /* Fall through into the next case */
 25892        case etDECIMAL:
 25893          if( infop->flags & FLAG_SIGNED ){
 25894            i64 v;
 25895            if( bArgList ){
 25896              v = getIntArg(pArgList);
 25897            }else if( flag_long ){
 25898              if( flag_long==2 ){
 25899                v = va_arg(ap,i64) ;
 25900              }else{
 25901                v = va_arg(ap,long int);
 25902              }
 25903            }else{
 25904              v = va_arg(ap,int);
 25905            }
 25906            if( v<0 ){
 25907              if( v==SMALLEST_INT64 ){
 25908                longvalue = ((u64)1)<<63;
 25909              }else{
 25910                longvalue = -v;
 25911              }
 25912              prefix = '-';
 25913            }else{
 25914              longvalue = v;
 25915              prefix = flag_prefix;
 25916            }
 25917          }else{
 25918            if( bArgList ){
 25919              longvalue = (u64)getIntArg(pArgList);
 25920            }else if( flag_long ){
 25921              if( flag_long==2 ){
 25922                longvalue = va_arg(ap,u64);
 25923              }else{
 25924                longvalue = va_arg(ap,unsigned long int);
 25925              }
 25926            }else{
 25927              longvalue = va_arg(ap,unsigned int);
 25928            }
 25929            prefix = 0;
 25930          }
 25931          if( longvalue==0 ) flag_alternateform = 0;
 25932          if( flag_zeropad && precision<width-(prefix!=0) ){
 25933            precision = width-(prefix!=0);
 25934          }
 25935          if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
 25936            nOut = etBUFSIZE;
 25937            zOut = buf;
 25938          }else{
 25939            u64 n = (u64)precision + 10 + precision/3;
 25940            zOut = zExtra = sqlite3Malloc( n );
 25941            if( zOut==0 ){
 25942              setStrAccumError(pAccum, STRACCUM_NOMEM);
 25943              return;
 25944            }
 25945            nOut = (int)n;
 25946          }
 25947          bufpt = &zOut[nOut-1];
 25948          if( xtype==etORDINAL ){
 25949            static const char zOrd[] = "thstndrd";
 25950            int x = (int)(longvalue % 10);
 25951            if( x>=4 || (longvalue/10)%10==1 ){
 25952              x = 0;
 25953            }
 25954            *(--bufpt) = zOrd[x*2+1];
 25955            *(--bufpt) = zOrd[x*2];
 25956          }
 25957          {
 25958            const char *cset = &aDigits[infop->charset];
 25959            u8 base = infop->base;
 25960            do{                                           /* Convert to ascii */
 25961              *(--bufpt) = cset[longvalue%base];
 25962              longvalue = longvalue/base;
 25963            }while( longvalue>0 );
 25964          }
 25965          length = (int)(&zOut[nOut-1]-bufpt);
 25966          while( precision>length ){
 25967            *(--bufpt) = '0';                             /* Zero pad */
 25968            length++;
 25969          }
 25970          if( cThousand ){
 25971            int nn = (length - 1)/3;  /* Number of "," to insert */
 25972            int ix = (length - 1)%3 + 1;
 25973            bufpt -= nn;
 25974            for(idx=0; nn>0; idx++){
 25975              bufpt[idx] = bufpt[idx+nn];
 25976              ix--;
 25977              if( ix==0 ){
 25978                bufpt[++idx] = cThousand;
 25979                nn--;
 25980                ix = 3;
 25981              }
 25982            }
 25983          }
 25984          if( prefix ) *(--bufpt) = prefix;               /* Add sign */
 25985          if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
 25986            const char *pre;
 25987            char x;
 25988            pre = &aPrefix[infop->prefix];
 25989            for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
 25990          }
 25991          length = (int)(&zOut[nOut-1]-bufpt);
 25992          break;
 25993        case etFLOAT:
 25994        case etEXP:
 25995        case etGENERIC:
 25996          if( bArgList ){
 25997            realvalue = getDoubleArg(pArgList);
 25998          }else{
 25999            realvalue = va_arg(ap,double);
 26000          }
 26001  #ifdef SQLITE_OMIT_FLOATING_POINT
 26002          length = 0;
 26003  #else
 26004          if( precision<0 ) precision = 6;         /* Set default precision */
 26005          if( realvalue<0.0 ){
 26006            realvalue = -realvalue;
 26007            prefix = '-';
 26008          }else{
 26009            prefix = flag_prefix;
 26010          }
 26011          if( xtype==etGENERIC && precision>0 ) precision--;
 26012          testcase( precision>0xfff );
 26013          for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
 26014          if( xtype==etFLOAT ) realvalue += rounder;
 26015          /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
 26016          exp = 0;
 26017          if( sqlite3IsNaN((double)realvalue) ){
 26018            bufpt = "NaN";
 26019            length = 3;
 26020            break;
 26021          }
 26022          if( realvalue>0.0 ){
 26023            LONGDOUBLE_TYPE scale = 1.0;
 26024            while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
 26025            while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
 26026            while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
 26027            realvalue /= scale;
 26028            while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
 26029            while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
 26030            if( exp>350 ){
 26031              bufpt = buf;
 26032              buf[0] = prefix;
 26033              memcpy(buf+(prefix!=0),"Inf",4);
 26034              length = 3+(prefix!=0);
 26035              break;
 26036            }
 26037          }
 26038          bufpt = buf;
 26039          /*
 26040          ** If the field type is etGENERIC, then convert to either etEXP
 26041          ** or etFLOAT, as appropriate.
 26042          */
 26043          if( xtype!=etFLOAT ){
 26044            realvalue += rounder;
 26045            if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
 26046          }
 26047          if( xtype==etGENERIC ){
 26048            flag_rtz = !flag_alternateform;
 26049            if( exp<-4 || exp>precision ){
 26050              xtype = etEXP;
 26051            }else{
 26052              precision = precision - exp;
 26053              xtype = etFLOAT;
 26054            }
 26055          }else{
 26056            flag_rtz = flag_altform2;
 26057          }
 26058          if( xtype==etEXP ){
 26059            e2 = 0;
 26060          }else{
 26061            e2 = exp;
 26062          }
 26063          if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
 26064            bufpt = zExtra 
 26065                = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
 26066            if( bufpt==0 ){
 26067              setStrAccumError(pAccum, STRACCUM_NOMEM);
 26068              return;
 26069            }
 26070          }
 26071          zOut = bufpt;
 26072          nsd = 16 + flag_altform2*10;
 26073          flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
 26074          /* The sign in front of the number */
 26075          if( prefix ){
 26076            *(bufpt++) = prefix;
 26077          }
 26078          /* Digits prior to the decimal point */
 26079          if( e2<0 ){
 26080            *(bufpt++) = '0';
 26081          }else{
 26082            for(; e2>=0; e2--){
 26083              *(bufpt++) = et_getdigit(&realvalue,&nsd);
 26084            }
 26085          }
 26086          /* The decimal point */
 26087          if( flag_dp ){
 26088            *(bufpt++) = '.';
 26089          }
 26090          /* "0" digits after the decimal point but before the first
 26091          ** significant digit of the number */
 26092          for(e2++; e2<0; precision--, e2++){
 26093            assert( precision>0 );
 26094            *(bufpt++) = '0';
 26095          }
 26096          /* Significant digits after the decimal point */
 26097          while( (precision--)>0 ){
 26098            *(bufpt++) = et_getdigit(&realvalue,&nsd);
 26099          }
 26100          /* Remove trailing zeros and the "." if no digits follow the "." */
 26101          if( flag_rtz && flag_dp ){
 26102            while( bufpt[-1]=='0' ) *(--bufpt) = 0;
 26103            assert( bufpt>zOut );
 26104            if( bufpt[-1]=='.' ){
 26105              if( flag_altform2 ){
 26106                *(bufpt++) = '0';
 26107              }else{
 26108                *(--bufpt) = 0;
 26109              }
 26110            }
 26111          }
 26112          /* Add the "eNNN" suffix */
 26113          if( xtype==etEXP ){
 26114            *(bufpt++) = aDigits[infop->charset];
 26115            if( exp<0 ){
 26116              *(bufpt++) = '-'; exp = -exp;
 26117            }else{
 26118              *(bufpt++) = '+';
 26119            }
 26120            if( exp>=100 ){
 26121              *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
 26122              exp %= 100;
 26123            }
 26124            *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
 26125            *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
 26126          }
 26127          *bufpt = 0;
 26128  
 26129          /* The converted number is in buf[] and zero terminated. Output it.
 26130          ** Note that the number is in the usual order, not reversed as with
 26131          ** integer conversions. */
 26132          length = (int)(bufpt-zOut);
 26133          bufpt = zOut;
 26134  
 26135          /* Special case:  Add leading zeros if the flag_zeropad flag is
 26136          ** set and we are not left justified */
 26137          if( flag_zeropad && !flag_leftjustify && length < width){
 26138            int i;
 26139            int nPad = width - length;
 26140            for(i=width; i>=nPad; i--){
 26141              bufpt[i] = bufpt[i-nPad];
 26142            }
 26143            i = prefix!=0;
 26144            while( nPad-- ) bufpt[i++] = '0';
 26145            length = width;
 26146          }
 26147  #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
 26148          break;
 26149        case etSIZE:
 26150          if( !bArgList ){
 26151            *(va_arg(ap,int*)) = pAccum->nChar;
 26152          }
 26153          length = width = 0;
 26154          break;
 26155        case etPERCENT:
 26156          buf[0] = '%';
 26157          bufpt = buf;
 26158          length = 1;
 26159          break;
 26160        case etCHARX:
 26161          if( bArgList ){
 26162            bufpt = getTextArg(pArgList);
 26163            c = bufpt ? bufpt[0] : 0;
 26164          }else{
 26165            c = va_arg(ap,int);
 26166          }
 26167          if( precision>1 ){
 26168            width -= precision-1;
 26169            if( width>1 && !flag_leftjustify ){
 26170              sqlite3AppendChar(pAccum, width-1, ' ');
 26171              width = 0;
 26172            }
 26173            sqlite3AppendChar(pAccum, precision-1, c);
 26174          }
 26175          length = 1;
 26176          buf[0] = c;
 26177          bufpt = buf;
 26178          break;
 26179        case etSTRING:
 26180        case etDYNSTRING:
 26181          if( bArgList ){
 26182            bufpt = getTextArg(pArgList);
 26183            xtype = etSTRING;
 26184          }else{
 26185            bufpt = va_arg(ap,char*);
 26186          }
 26187          if( bufpt==0 ){
 26188            bufpt = "";
 26189          }else if( xtype==etDYNSTRING ){
 26190            zExtra = bufpt;
 26191          }
 26192          if( precision>=0 ){
 26193            for(length=0; length<precision && bufpt[length]; length++){}
 26194          }else{
 26195            length = 0x7fffffff & (int)strlen(bufpt);
 26196          }
 26197          break;
 26198        case etSQLESCAPE:           /* Escape ' characters */
 26199        case etSQLESCAPE2:          /* Escape ' and enclose in '...' */
 26200        case etSQLESCAPE3: {        /* Escape " characters */
 26201          int i, j, k, n, isnull;
 26202          int needQuote;
 26203          char ch;
 26204          char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
 26205          char *escarg;
 26206  
 26207          if( bArgList ){
 26208            escarg = getTextArg(pArgList);
 26209          }else{
 26210            escarg = va_arg(ap,char*);
 26211          }
 26212          isnull = escarg==0;
 26213          if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
 26214          k = precision;
 26215          for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
 26216            if( ch==q )  n++;
 26217          }
 26218          needQuote = !isnull && xtype==etSQLESCAPE2;
 26219          n += i + 3;
 26220          if( n>etBUFSIZE ){
 26221            bufpt = zExtra = sqlite3Malloc( n );
 26222            if( bufpt==0 ){
 26223              setStrAccumError(pAccum, STRACCUM_NOMEM);
 26224              return;
 26225            }
 26226          }else{
 26227            bufpt = buf;
 26228          }
 26229          j = 0;
 26230          if( needQuote ) bufpt[j++] = q;
 26231          k = i;
 26232          for(i=0; i<k; i++){
 26233            bufpt[j++] = ch = escarg[i];
 26234            if( ch==q ) bufpt[j++] = ch;
 26235          }
 26236          if( needQuote ) bufpt[j++] = q;
 26237          bufpt[j] = 0;
 26238          length = j;
 26239          /* The precision in %q and %Q means how many input characters to
 26240          ** consume, not the length of the output...
 26241          ** if( precision>=0 && precision<length ) length = precision; */
 26242          break;
 26243        }
 26244        case etTOKEN: {
 26245          Token *pToken;
 26246          if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
 26247          pToken = va_arg(ap, Token*);
 26248          assert( bArgList==0 );
 26249          if( pToken && pToken->n ){
 26250            sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
 26251          }
 26252          length = width = 0;
 26253          break;
 26254        }
 26255        case etSRCLIST: {
 26256          SrcList *pSrc;
 26257          int k;
 26258          struct SrcList_item *pItem;
 26259          if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
 26260          pSrc = va_arg(ap, SrcList*);
 26261          k = va_arg(ap, int);
 26262          pItem = &pSrc->a[k];
 26263          assert( bArgList==0 );
 26264          assert( k>=0 && k<pSrc->nSrc );
 26265          if( pItem->zDatabase ){
 26266            sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
 26267            sqlite3StrAccumAppend(pAccum, ".", 1);
 26268          }
 26269          sqlite3StrAccumAppendAll(pAccum, pItem->zName);
 26270          length = width = 0;
 26271          break;
 26272        }
 26273        default: {
 26274          assert( xtype==etINVALID );
 26275          return;
 26276        }
 26277      }/* End switch over the format type */
 26278      /*
 26279      ** The text of the conversion is pointed to by "bufpt" and is
 26280      ** "length" characters long.  The field width is "width".  Do
 26281      ** the output.
 26282      */
 26283      width -= length;
 26284      if( width>0 ){
 26285        if( !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
 26286        sqlite3StrAccumAppend(pAccum, bufpt, length);
 26287        if( flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
 26288      }else{
 26289        sqlite3StrAccumAppend(pAccum, bufpt, length);
 26290      }
 26291  
 26292      if( zExtra ){
 26293        sqlite3DbFree(pAccum->db, zExtra);
 26294        zExtra = 0;
 26295      }
 26296    }/* End for loop over the format string */
 26297  } /* End of function */
 26298  
 26299  /*
 26300  ** Enlarge the memory allocation on a StrAccum object so that it is
 26301  ** able to accept at least N more bytes of text.
 26302  **
 26303  ** Return the number of bytes of text that StrAccum is able to accept
 26304  ** after the attempted enlargement.  The value returned might be zero.
 26305  */
 26306  static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
 26307    char *zNew;
 26308    assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
 26309    if( p->accError ){
 26310      testcase(p->accError==STRACCUM_TOOBIG);
 26311      testcase(p->accError==STRACCUM_NOMEM);
 26312      return 0;
 26313    }
 26314    if( p->mxAlloc==0 ){
 26315      N = p->nAlloc - p->nChar - 1;
 26316      setStrAccumError(p, STRACCUM_TOOBIG);
 26317      return N;
 26318    }else{
 26319      char *zOld = isMalloced(p) ? p->zText : 0;
 26320      i64 szNew = p->nChar;
 26321      szNew += N + 1;
 26322      if( szNew+p->nChar<=p->mxAlloc ){
 26323        /* Force exponential buffer size growth as long as it does not overflow,
 26324        ** to avoid having to call this routine too often */
 26325        szNew += p->nChar;
 26326      }
 26327      if( szNew > p->mxAlloc ){
 26328        sqlite3StrAccumReset(p);
 26329        setStrAccumError(p, STRACCUM_TOOBIG);
 26330        return 0;
 26331      }else{
 26332        p->nAlloc = (int)szNew;
 26333      }
 26334      if( p->db ){
 26335        zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
 26336      }else{
 26337        zNew = sqlite3_realloc64(zOld, p->nAlloc);
 26338      }
 26339      if( zNew ){
 26340        assert( p->zText!=0 || p->nChar==0 );
 26341        if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
 26342        p->zText = zNew;
 26343        p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
 26344        p->printfFlags |= SQLITE_PRINTF_MALLOCED;
 26345      }else{
 26346        sqlite3StrAccumReset(p);
 26347        setStrAccumError(p, STRACCUM_NOMEM);
 26348        return 0;
 26349      }
 26350    }
 26351    return N;
 26352  }
 26353  
 26354  /*
 26355  ** Append N copies of character c to the given string buffer.
 26356  */
 26357  SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
 26358    testcase( p->nChar + (i64)N > 0x7fffffff );
 26359    if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
 26360      return;
 26361    }
 26362    while( (N--)>0 ) p->zText[p->nChar++] = c;
 26363  }
 26364  
 26365  /*
 26366  ** The StrAccum "p" is not large enough to accept N new bytes of z[].
 26367  ** So enlarge if first, then do the append.
 26368  **
 26369  ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
 26370  ** work (enlarging the buffer) using tail recursion, so that the
 26371  ** sqlite3StrAccumAppend() routine can use fast calling semantics.
 26372  */
 26373  static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
 26374    N = sqlite3StrAccumEnlarge(p, N);
 26375    if( N>0 ){
 26376      memcpy(&p->zText[p->nChar], z, N);
 26377      p->nChar += N;
 26378    }
 26379  }
 26380  
 26381  /*
 26382  ** Append N bytes of text from z to the StrAccum object.  Increase the
 26383  ** size of the memory allocation for StrAccum if necessary.
 26384  */
 26385  SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
 26386    assert( z!=0 || N==0 );
 26387    assert( p->zText!=0 || p->nChar==0 || p->accError );
 26388    assert( N>=0 );
 26389    assert( p->accError==0 || p->nAlloc==0 );
 26390    if( p->nChar+N >= p->nAlloc ){
 26391      enlargeAndAppend(p,z,N);
 26392    }else if( N ){
 26393      assert( p->zText );
 26394      p->nChar += N;
 26395      memcpy(&p->zText[p->nChar-N], z, N);
 26396    }
 26397  }
 26398  
 26399  /*
 26400  ** Append the complete text of zero-terminated string z[] to the p string.
 26401  */
 26402  SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
 26403    sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
 26404  }
 26405  
 26406  
 26407  /*
 26408  ** Finish off a string by making sure it is zero-terminated.
 26409  ** Return a pointer to the resulting string.  Return a NULL
 26410  ** pointer if any kind of error was encountered.
 26411  */
 26412  static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
 26413    char *zText;
 26414    assert( p->mxAlloc>0 && !isMalloced(p) );
 26415    zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
 26416    if( zText ){
 26417      memcpy(zText, p->zText, p->nChar+1);
 26418      p->printfFlags |= SQLITE_PRINTF_MALLOCED;
 26419    }else{
 26420      setStrAccumError(p, STRACCUM_NOMEM);
 26421    }
 26422    p->zText = zText;
 26423    return zText;
 26424  }
 26425  SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
 26426    if( p->zText ){
 26427      p->zText[p->nChar] = 0;
 26428      if( p->mxAlloc>0 && !isMalloced(p) ){
 26429        return strAccumFinishRealloc(p);
 26430      }
 26431    }
 26432    return p->zText;
 26433  }
 26434  
 26435  /*
 26436  ** Reset an StrAccum string.  Reclaim all malloced memory.
 26437  */
 26438  SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
 26439    if( isMalloced(p) ){
 26440      sqlite3DbFree(p->db, p->zText);
 26441      p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
 26442    }
 26443    p->zText = 0;
 26444  }
 26445  
 26446  /*
 26447  ** Initialize a string accumulator.
 26448  **
 26449  ** p:     The accumulator to be initialized.
 26450  ** db:    Pointer to a database connection.  May be NULL.  Lookaside
 26451  **        memory is used if not NULL. db->mallocFailed is set appropriately
 26452  **        when not NULL.
 26453  ** zBase: An initial buffer.  May be NULL in which case the initial buffer
 26454  **        is malloced.
 26455  ** n:     Size of zBase in bytes.  If total space requirements never exceed
 26456  **        n then no memory allocations ever occur.
 26457  ** mx:    Maximum number of bytes to accumulate.  If mx==0 then no memory
 26458  **        allocations will ever occur.
 26459  */
 26460  SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
 26461    p->zText = zBase;
 26462    p->db = db;
 26463    p->nAlloc = n;
 26464    p->mxAlloc = mx;
 26465    p->nChar = 0;
 26466    p->accError = 0;
 26467    p->printfFlags = 0;
 26468  }
 26469  
 26470  /*
 26471  ** Print into memory obtained from sqliteMalloc().  Use the internal
 26472  ** %-conversion extensions.
 26473  */
 26474  SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
 26475    char *z;
 26476    char zBase[SQLITE_PRINT_BUF_SIZE];
 26477    StrAccum acc;
 26478    assert( db!=0 );
 26479    sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
 26480                        db->aLimit[SQLITE_LIMIT_LENGTH]);
 26481    acc.printfFlags = SQLITE_PRINTF_INTERNAL;
 26482    sqlite3VXPrintf(&acc, zFormat, ap);
 26483    z = sqlite3StrAccumFinish(&acc);
 26484    if( acc.accError==STRACCUM_NOMEM ){
 26485      sqlite3OomFault(db);
 26486    }
 26487    return z;
 26488  }
 26489  
 26490  /*
 26491  ** Print into memory obtained from sqliteMalloc().  Use the internal
 26492  ** %-conversion extensions.
 26493  */
 26494  SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
 26495    va_list ap;
 26496    char *z;
 26497    va_start(ap, zFormat);
 26498    z = sqlite3VMPrintf(db, zFormat, ap);
 26499    va_end(ap);
 26500    return z;
 26501  }
 26502  
 26503  /*
 26504  ** Print into memory obtained from sqlite3_malloc().  Omit the internal
 26505  ** %-conversion extensions.
 26506  */
 26507  SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
 26508    char *z;
 26509    char zBase[SQLITE_PRINT_BUF_SIZE];
 26510    StrAccum acc;
 26511  
 26512  #ifdef SQLITE_ENABLE_API_ARMOR  
 26513    if( zFormat==0 ){
 26514      (void)SQLITE_MISUSE_BKPT;
 26515      return 0;
 26516    }
 26517  #endif
 26518  #ifndef SQLITE_OMIT_AUTOINIT
 26519    if( sqlite3_initialize() ) return 0;
 26520  #endif
 26521    sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
 26522    sqlite3VXPrintf(&acc, zFormat, ap);
 26523    z = sqlite3StrAccumFinish(&acc);
 26524    return z;
 26525  }
 26526  
 26527  /*
 26528  ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
 26529  ** %-conversion extensions.
 26530  */
 26531  SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
 26532    va_list ap;
 26533    char *z;
 26534  #ifndef SQLITE_OMIT_AUTOINIT
 26535    if( sqlite3_initialize() ) return 0;
 26536  #endif
 26537    va_start(ap, zFormat);
 26538    z = sqlite3_vmprintf(zFormat, ap);
 26539    va_end(ap);
 26540    return z;
 26541  }
 26542  
 26543  /*
 26544  ** sqlite3_snprintf() works like snprintf() except that it ignores the
 26545  ** current locale settings.  This is important for SQLite because we
 26546  ** are not able to use a "," as the decimal point in place of "." as
 26547  ** specified by some locales.
 26548  **
 26549  ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
 26550  ** from the snprintf() standard.  Unfortunately, it is too late to change
 26551  ** this without breaking compatibility, so we just have to live with the
 26552  ** mistake.
 26553  **
 26554  ** sqlite3_vsnprintf() is the varargs version.
 26555  */
 26556  SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
 26557    StrAccum acc;
 26558    if( n<=0 ) return zBuf;
 26559  #ifdef SQLITE_ENABLE_API_ARMOR
 26560    if( zBuf==0 || zFormat==0 ) {
 26561      (void)SQLITE_MISUSE_BKPT;
 26562      if( zBuf ) zBuf[0] = 0;
 26563      return zBuf;
 26564    }
 26565  #endif
 26566    sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
 26567    sqlite3VXPrintf(&acc, zFormat, ap);
 26568    zBuf[acc.nChar] = 0;
 26569    return zBuf;
 26570  }
 26571  SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
 26572    char *z;
 26573    va_list ap;
 26574    va_start(ap,zFormat);
 26575    z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
 26576    va_end(ap);
 26577    return z;
 26578  }
 26579  
 26580  /*
 26581  ** This is the routine that actually formats the sqlite3_log() message.
 26582  ** We house it in a separate routine from sqlite3_log() to avoid using
 26583  ** stack space on small-stack systems when logging is disabled.
 26584  **
 26585  ** sqlite3_log() must render into a static buffer.  It cannot dynamically
 26586  ** allocate memory because it might be called while the memory allocator
 26587  ** mutex is held.
 26588  **
 26589  ** sqlite3VXPrintf() might ask for *temporary* memory allocations for
 26590  ** certain format characters (%q) or for very large precisions or widths.
 26591  ** Care must be taken that any sqlite3_log() calls that occur while the
 26592  ** memory mutex is held do not use these mechanisms.
 26593  */
 26594  static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
 26595    StrAccum acc;                          /* String accumulator */
 26596    char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
 26597  
 26598    sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
 26599    sqlite3VXPrintf(&acc, zFormat, ap);
 26600    sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
 26601                             sqlite3StrAccumFinish(&acc));
 26602  }
 26603  
 26604  /*
 26605  ** Format and write a message to the log if logging is enabled.
 26606  */
 26607  SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
 26608    va_list ap;                             /* Vararg list */
 26609    if( sqlite3GlobalConfig.xLog ){
 26610      va_start(ap, zFormat);
 26611      renderLogMsg(iErrCode, zFormat, ap);
 26612      va_end(ap);
 26613    }
 26614  }
 26615  
 26616  #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
 26617  /*
 26618  ** A version of printf() that understands %lld.  Used for debugging.
 26619  ** The printf() built into some versions of windows does not understand %lld
 26620  ** and segfaults if you give it a long long int.
 26621  */
 26622  SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
 26623    va_list ap;
 26624    StrAccum acc;
 26625    char zBuf[500];
 26626    sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
 26627    va_start(ap,zFormat);
 26628    sqlite3VXPrintf(&acc, zFormat, ap);
 26629    va_end(ap);
 26630    sqlite3StrAccumFinish(&acc);
 26631    fprintf(stdout,"%s", zBuf);
 26632    fflush(stdout);
 26633  }
 26634  #endif
 26635  
 26636  
 26637  /*
 26638  ** variable-argument wrapper around sqlite3VXPrintf().  The bFlags argument
 26639  ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
 26640  */
 26641  SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
 26642    va_list ap;
 26643    va_start(ap,zFormat);
 26644    sqlite3VXPrintf(p, zFormat, ap);
 26645    va_end(ap);
 26646  }
 26647  
 26648  /************** End of printf.c **********************************************/
 26649  /************** Begin file treeview.c ****************************************/
 26650  /*
 26651  ** 2015-06-08
 26652  **
 26653  ** The author disclaims copyright to this source code.  In place of
 26654  ** a legal notice, here is a blessing:
 26655  **
 26656  **    May you do good and not evil.
 26657  **    May you find forgiveness for yourself and forgive others.
 26658  **    May you share freely, never taking more than you give.
 26659  **
 26660  *************************************************************************
 26661  **
 26662  ** This file contains C code to implement the TreeView debugging routines.
 26663  ** These routines print a parse tree to standard output for debugging and
 26664  ** analysis. 
 26665  **
 26666  ** The interfaces in this file is only available when compiling
 26667  ** with SQLITE_DEBUG.
 26668  */
 26669  /* #include "sqliteInt.h" */
 26670  #ifdef SQLITE_DEBUG
 26671  
 26672  /*
 26673  ** Add a new subitem to the tree.  The moreToFollow flag indicates that this
 26674  ** is not the last item in the tree.
 26675  */
 26676  static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
 26677    if( p==0 ){
 26678      p = sqlite3_malloc64( sizeof(*p) );
 26679      if( p==0 ) return 0;
 26680      memset(p, 0, sizeof(*p));
 26681    }else{
 26682      p->iLevel++;
 26683    }
 26684    assert( moreToFollow==0 || moreToFollow==1 );
 26685    if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
 26686    return p;
 26687  }
 26688  
 26689  /*
 26690  ** Finished with one layer of the tree
 26691  */
 26692  static void sqlite3TreeViewPop(TreeView *p){
 26693    if( p==0 ) return;
 26694    p->iLevel--;
 26695    if( p->iLevel<0 ) sqlite3_free(p);
 26696  }
 26697  
 26698  /*
 26699  ** Generate a single line of output for the tree, with a prefix that contains
 26700  ** all the appropriate tree lines
 26701  */
 26702  static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
 26703    va_list ap;
 26704    int i;
 26705    StrAccum acc;
 26706    char zBuf[500];
 26707    sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
 26708    if( p ){
 26709      for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
 26710        sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|   " : "    ", 4);
 26711      }
 26712      sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
 26713    }
 26714    va_start(ap, zFormat);
 26715    sqlite3VXPrintf(&acc, zFormat, ap);
 26716    va_end(ap);
 26717    assert( acc.nChar>0 );
 26718    if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
 26719    sqlite3StrAccumFinish(&acc);
 26720    fprintf(stdout,"%s", zBuf);
 26721    fflush(stdout);
 26722  }
 26723  
 26724  /*
 26725  ** Shorthand for starting a new tree item that consists of a single label
 26726  */
 26727  static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
 26728    p = sqlite3TreeViewPush(p, moreFollows);
 26729    sqlite3TreeViewLine(p, "%s", zLabel);
 26730  }
 26731  
 26732  /*
 26733  ** Generate a human-readable description of a WITH clause.
 26734  */
 26735  SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
 26736    int i;
 26737    if( pWith==0 ) return;
 26738    if( pWith->nCte==0 ) return;
 26739    if( pWith->pOuter ){
 26740      sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
 26741    }else{
 26742      sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
 26743    }
 26744    if( pWith->nCte>0 ){
 26745      pView = sqlite3TreeViewPush(pView, 1);
 26746      for(i=0; i<pWith->nCte; i++){
 26747        StrAccum x;
 26748        char zLine[1000];
 26749        const struct Cte *pCte = &pWith->a[i];
 26750        sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
 26751        sqlite3XPrintf(&x, "%s", pCte->zName);
 26752        if( pCte->pCols && pCte->pCols->nExpr>0 ){
 26753          char cSep = '(';
 26754          int j;
 26755          for(j=0; j<pCte->pCols->nExpr; j++){
 26756            sqlite3XPrintf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
 26757            cSep = ',';
 26758          }
 26759          sqlite3XPrintf(&x, ")");
 26760        }
 26761        sqlite3XPrintf(&x, " AS");
 26762        sqlite3StrAccumFinish(&x);
 26763        sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
 26764        sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
 26765        sqlite3TreeViewPop(pView);
 26766      }
 26767      sqlite3TreeViewPop(pView);
 26768    }
 26769  }
 26770  
 26771  
 26772  /*
 26773  ** Generate a human-readable description of a Select object.
 26774  */
 26775  SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
 26776    int n = 0;
 26777    int cnt = 0;
 26778    if( p==0 ){
 26779      sqlite3TreeViewLine(pView, "nil-SELECT");
 26780      return;
 26781    } 
 26782    pView = sqlite3TreeViewPush(pView, moreToFollow);
 26783    if( p->pWith ){
 26784      sqlite3TreeViewWith(pView, p->pWith, 1);
 26785      cnt = 1;
 26786      sqlite3TreeViewPush(pView, 1);
 26787    }
 26788    do{
 26789      sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d",
 26790        ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
 26791        ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags,
 26792        (int)p->nSelectRow
 26793      );
 26794      if( cnt++ ) sqlite3TreeViewPop(pView);
 26795      if( p->pPrior ){
 26796        n = 1000;
 26797      }else{
 26798        n = 0;
 26799        if( p->pSrc && p->pSrc->nSrc ) n++;
 26800        if( p->pWhere ) n++;
 26801        if( p->pGroupBy ) n++;
 26802        if( p->pHaving ) n++;
 26803        if( p->pOrderBy ) n++;
 26804        if( p->pLimit ) n++;
 26805        if( p->pOffset ) n++;
 26806      }
 26807      sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
 26808      if( p->pSrc && p->pSrc->nSrc ){
 26809        int i;
 26810        pView = sqlite3TreeViewPush(pView, (n--)>0);
 26811        sqlite3TreeViewLine(pView, "FROM");
 26812        for(i=0; i<p->pSrc->nSrc; i++){
 26813          struct SrcList_item *pItem = &p->pSrc->a[i];
 26814          StrAccum x;
 26815          char zLine[100];
 26816          sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
 26817          sqlite3XPrintf(&x, "{%d,*}", pItem->iCursor);
 26818          if( pItem->zDatabase ){
 26819            sqlite3XPrintf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
 26820          }else if( pItem->zName ){
 26821            sqlite3XPrintf(&x, " %s", pItem->zName);
 26822          }
 26823          if( pItem->pTab ){
 26824            sqlite3XPrintf(&x, " tabname=%Q", pItem->pTab->zName);
 26825          }
 26826          if( pItem->zAlias ){
 26827            sqlite3XPrintf(&x, " (AS %s)", pItem->zAlias);
 26828          }
 26829          if( pItem->fg.jointype & JT_LEFT ){
 26830            sqlite3XPrintf(&x, " LEFT-JOIN");
 26831          }
 26832          sqlite3StrAccumFinish(&x);
 26833          sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1); 
 26834          if( pItem->pSelect ){
 26835            sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
 26836          }
 26837          if( pItem->fg.isTabFunc ){
 26838            sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
 26839          }
 26840          sqlite3TreeViewPop(pView);
 26841        }
 26842        sqlite3TreeViewPop(pView);
 26843      }
 26844      if( p->pWhere ){
 26845        sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
 26846        sqlite3TreeViewExpr(pView, p->pWhere, 0);
 26847        sqlite3TreeViewPop(pView);
 26848      }
 26849      if( p->pGroupBy ){
 26850        sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
 26851      }
 26852      if( p->pHaving ){
 26853        sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
 26854        sqlite3TreeViewExpr(pView, p->pHaving, 0);
 26855        sqlite3TreeViewPop(pView);
 26856      }
 26857      if( p->pOrderBy ){
 26858        sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
 26859      }
 26860      if( p->pLimit ){
 26861        sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
 26862        sqlite3TreeViewExpr(pView, p->pLimit, 0);
 26863        sqlite3TreeViewPop(pView);
 26864      }
 26865      if( p->pOffset ){
 26866        sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
 26867        sqlite3TreeViewExpr(pView, p->pOffset, 0);
 26868        sqlite3TreeViewPop(pView);
 26869      }
 26870      if( p->pPrior ){
 26871        const char *zOp = "UNION";
 26872        switch( p->op ){
 26873          case TK_ALL:         zOp = "UNION ALL";  break;
 26874          case TK_INTERSECT:   zOp = "INTERSECT";  break;
 26875          case TK_EXCEPT:      zOp = "EXCEPT";     break;
 26876        }
 26877        sqlite3TreeViewItem(pView, zOp, 1);
 26878      }
 26879      p = p->pPrior;
 26880    }while( p!=0 );
 26881    sqlite3TreeViewPop(pView);
 26882  }
 26883  
 26884  /*
 26885  ** Generate a human-readable explanation of an expression tree.
 26886  */
 26887  SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
 26888    const char *zBinOp = 0;   /* Binary operator */
 26889    const char *zUniOp = 0;   /* Unary operator */
 26890    char zFlgs[60];
 26891    pView = sqlite3TreeViewPush(pView, moreToFollow);
 26892    if( pExpr==0 ){
 26893      sqlite3TreeViewLine(pView, "nil");
 26894      sqlite3TreeViewPop(pView);
 26895      return;
 26896    }
 26897    if( pExpr->flags ){
 26898      if( ExprHasProperty(pExpr, EP_FromJoin) ){
 26899        sqlite3_snprintf(sizeof(zFlgs),zFlgs,"  flags=0x%x iRJT=%d",
 26900                         pExpr->flags, pExpr->iRightJoinTable);
 26901      }else{
 26902        sqlite3_snprintf(sizeof(zFlgs),zFlgs,"  flags=0x%x",pExpr->flags);
 26903      }
 26904    }else{
 26905      zFlgs[0] = 0;
 26906    }
 26907    switch( pExpr->op ){
 26908      case TK_AGG_COLUMN: {
 26909        sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
 26910              pExpr->iTable, pExpr->iColumn, zFlgs);
 26911        break;
 26912      }
 26913      case TK_COLUMN: {
 26914        if( pExpr->iTable<0 ){
 26915          /* This only happens when coding check constraints */
 26916          sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
 26917        }else{
 26918          sqlite3TreeViewLine(pView, "{%d:%d}%s",
 26919                               pExpr->iTable, pExpr->iColumn, zFlgs);
 26920        }
 26921        break;
 26922      }
 26923      case TK_INTEGER: {
 26924        if( pExpr->flags & EP_IntValue ){
 26925          sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
 26926        }else{
 26927          sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
 26928        }
 26929        break;
 26930      }
 26931  #ifndef SQLITE_OMIT_FLOATING_POINT
 26932      case TK_FLOAT: {
 26933        sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
 26934        break;
 26935      }
 26936  #endif
 26937      case TK_STRING: {
 26938        sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
 26939        break;
 26940      }
 26941      case TK_NULL: {
 26942        sqlite3TreeViewLine(pView,"NULL");
 26943        break;
 26944      }
 26945  #ifndef SQLITE_OMIT_BLOB_LITERAL
 26946      case TK_BLOB: {
 26947        sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
 26948        break;
 26949      }
 26950  #endif
 26951      case TK_VARIABLE: {
 26952        sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
 26953                            pExpr->u.zToken, pExpr->iColumn);
 26954        break;
 26955      }
 26956      case TK_REGISTER: {
 26957        sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
 26958        break;
 26959      }
 26960      case TK_ID: {
 26961        sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
 26962        break;
 26963      }
 26964  #ifndef SQLITE_OMIT_CAST
 26965      case TK_CAST: {
 26966        /* Expressions of the form:   CAST(pLeft AS token) */
 26967        sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
 26968        sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
 26969        break;
 26970      }
 26971  #endif /* SQLITE_OMIT_CAST */
 26972      case TK_LT:      zBinOp = "LT";     break;
 26973      case TK_LE:      zBinOp = "LE";     break;
 26974      case TK_GT:      zBinOp = "GT";     break;
 26975      case TK_GE:      zBinOp = "GE";     break;
 26976      case TK_NE:      zBinOp = "NE";     break;
 26977      case TK_EQ:      zBinOp = "EQ";     break;
 26978      case TK_IS:      zBinOp = "IS";     break;
 26979      case TK_ISNOT:   zBinOp = "ISNOT";  break;
 26980      case TK_AND:     zBinOp = "AND";    break;
 26981      case TK_OR:      zBinOp = "OR";     break;
 26982      case TK_PLUS:    zBinOp = "ADD";    break;
 26983      case TK_STAR:    zBinOp = "MUL";    break;
 26984      case TK_MINUS:   zBinOp = "SUB";    break;
 26985      case TK_REM:     zBinOp = "REM";    break;
 26986      case TK_BITAND:  zBinOp = "BITAND"; break;
 26987      case TK_BITOR:   zBinOp = "BITOR";  break;
 26988      case TK_SLASH:   zBinOp = "DIV";    break;
 26989      case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
 26990      case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
 26991      case TK_CONCAT:  zBinOp = "CONCAT"; break;
 26992      case TK_DOT:     zBinOp = "DOT";    break;
 26993  
 26994      case TK_UMINUS:  zUniOp = "UMINUS"; break;
 26995      case TK_UPLUS:   zUniOp = "UPLUS";  break;
 26996      case TK_BITNOT:  zUniOp = "BITNOT"; break;
 26997      case TK_NOT:     zUniOp = "NOT";    break;
 26998      case TK_ISNULL:  zUniOp = "ISNULL"; break;
 26999      case TK_NOTNULL: zUniOp = "NOTNULL"; break;
 27000  
 27001      case TK_SPAN: {
 27002        sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
 27003        sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
 27004        break;
 27005      }
 27006  
 27007      case TK_COLLATE: {
 27008        sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
 27009        sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
 27010        break;
 27011      }
 27012  
 27013      case TK_AGG_FUNCTION:
 27014      case TK_FUNCTION: {
 27015        ExprList *pFarg;       /* List of function arguments */
 27016        if( ExprHasProperty(pExpr, EP_TokenOnly) ){
 27017          pFarg = 0;
 27018        }else{
 27019          pFarg = pExpr->x.pList;
 27020        }
 27021        if( pExpr->op==TK_AGG_FUNCTION ){
 27022          sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
 27023                               pExpr->op2, pExpr->u.zToken);
 27024        }else{
 27025          sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
 27026        }
 27027        if( pFarg ){
 27028          sqlite3TreeViewExprList(pView, pFarg, 0, 0);
 27029        }
 27030        break;
 27031      }
 27032  #ifndef SQLITE_OMIT_SUBQUERY
 27033      case TK_EXISTS: {
 27034        sqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags);
 27035        sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
 27036        break;
 27037      }
 27038      case TK_SELECT: {
 27039        sqlite3TreeViewLine(pView, "SELECT-expr flags=0x%x", pExpr->flags);
 27040        sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
 27041        break;
 27042      }
 27043      case TK_IN: {
 27044        sqlite3TreeViewLine(pView, "IN flags=0x%x", pExpr->flags);
 27045        sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
 27046        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
 27047          sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
 27048        }else{
 27049          sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
 27050        }
 27051        break;
 27052      }
 27053  #endif /* SQLITE_OMIT_SUBQUERY */
 27054  
 27055      /*
 27056      **    x BETWEEN y AND z
 27057      **
 27058      ** This is equivalent to
 27059      **
 27060      **    x>=y AND x<=z
 27061      **
 27062      ** X is stored in pExpr->pLeft.
 27063      ** Y is stored in pExpr->pList->a[0].pExpr.
 27064      ** Z is stored in pExpr->pList->a[1].pExpr.
 27065      */
 27066      case TK_BETWEEN: {
 27067        Expr *pX = pExpr->pLeft;
 27068        Expr *pY = pExpr->x.pList->a[0].pExpr;
 27069        Expr *pZ = pExpr->x.pList->a[1].pExpr;
 27070        sqlite3TreeViewLine(pView, "BETWEEN");
 27071        sqlite3TreeViewExpr(pView, pX, 1);
 27072        sqlite3TreeViewExpr(pView, pY, 1);
 27073        sqlite3TreeViewExpr(pView, pZ, 0);
 27074        break;
 27075      }
 27076      case TK_TRIGGER: {
 27077        /* If the opcode is TK_TRIGGER, then the expression is a reference
 27078        ** to a column in the new.* or old.* pseudo-tables available to
 27079        ** trigger programs. In this case Expr.iTable is set to 1 for the
 27080        ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
 27081        ** is set to the column of the pseudo-table to read, or to -1 to
 27082        ** read the rowid field.
 27083        */
 27084        sqlite3TreeViewLine(pView, "%s(%d)", 
 27085            pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
 27086        break;
 27087      }
 27088      case TK_CASE: {
 27089        sqlite3TreeViewLine(pView, "CASE");
 27090        sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
 27091        sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
 27092        break;
 27093      }
 27094  #ifndef SQLITE_OMIT_TRIGGER
 27095      case TK_RAISE: {
 27096        const char *zType = "unk";
 27097        switch( pExpr->affinity ){
 27098          case OE_Rollback:   zType = "rollback";  break;
 27099          case OE_Abort:      zType = "abort";     break;
 27100          case OE_Fail:       zType = "fail";      break;
 27101          case OE_Ignore:     zType = "ignore";    break;
 27102        }
 27103        sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
 27104        break;
 27105      }
 27106  #endif
 27107      case TK_MATCH: {
 27108        sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
 27109                            pExpr->iTable, pExpr->iColumn, zFlgs);
 27110        sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
 27111        break;
 27112      }
 27113      case TK_VECTOR: {
 27114        sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR");
 27115        break;
 27116      }
 27117      case TK_SELECT_COLUMN: {
 27118        sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn);
 27119        sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
 27120        break;
 27121      }
 27122      case TK_IF_NULL_ROW: {
 27123        sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable);
 27124        sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
 27125        break;
 27126      }
 27127      default: {
 27128        sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
 27129        break;
 27130      }
 27131    }
 27132    if( zBinOp ){
 27133      sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
 27134      sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
 27135      sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
 27136    }else if( zUniOp ){
 27137      sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
 27138      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
 27139    }
 27140    sqlite3TreeViewPop(pView);
 27141  }
 27142  
 27143  
 27144  /*
 27145  ** Generate a human-readable explanation of an expression list.
 27146  */
 27147  SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
 27148    TreeView *pView,
 27149    const ExprList *pList,
 27150    const char *zLabel
 27151  ){
 27152    if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
 27153    if( pList==0 ){
 27154      sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
 27155    }else{
 27156      int i;
 27157      sqlite3TreeViewLine(pView, "%s", zLabel);
 27158      for(i=0; i<pList->nExpr; i++){
 27159        int j = pList->a[i].u.x.iOrderByCol;
 27160        if( j ){
 27161          sqlite3TreeViewPush(pView, 0);
 27162          sqlite3TreeViewLine(pView, "iOrderByCol=%d", j);
 27163        }
 27164        sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
 27165        if( j ) sqlite3TreeViewPop(pView);
 27166      }
 27167    }
 27168  }
 27169  SQLITE_PRIVATE void sqlite3TreeViewExprList(
 27170    TreeView *pView,
 27171    const ExprList *pList,
 27172    u8 moreToFollow,
 27173    const char *zLabel
 27174  ){
 27175    pView = sqlite3TreeViewPush(pView, moreToFollow);
 27176    sqlite3TreeViewBareExprList(pView, pList, zLabel);
 27177    sqlite3TreeViewPop(pView);
 27178  }
 27179  
 27180  #endif /* SQLITE_DEBUG */
 27181  
 27182  /************** End of treeview.c ********************************************/
 27183  /************** Begin file random.c ******************************************/
 27184  /*
 27185  ** 2001 September 15
 27186  **
 27187  ** The author disclaims copyright to this source code.  In place of
 27188  ** a legal notice, here is a blessing:
 27189  **
 27190  **    May you do good and not evil.
 27191  **    May you find forgiveness for yourself and forgive others.
 27192  **    May you share freely, never taking more than you give.
 27193  **
 27194  *************************************************************************
 27195  ** This file contains code to implement a pseudo-random number
 27196  ** generator (PRNG) for SQLite.
 27197  **
 27198  ** Random numbers are used by some of the database backends in order
 27199  ** to generate random integer keys for tables or random filenames.
 27200  */
 27201  /* #include "sqliteInt.h" */
 27202  
 27203  
 27204  /* All threads share a single random number generator.
 27205  ** This structure is the current state of the generator.
 27206  */
 27207  static SQLITE_WSD struct sqlite3PrngType {
 27208    unsigned char isInit;          /* True if initialized */
 27209    unsigned char i, j;            /* State variables */
 27210    unsigned char s[256];          /* State variables */
 27211  } sqlite3Prng;
 27212  
 27213  /*
 27214  ** Return N random bytes.
 27215  */
 27216  SQLITE_API void sqlite3_randomness(int N, void *pBuf){
 27217    unsigned char t;
 27218    unsigned char *zBuf = pBuf;
 27219  
 27220    /* The "wsdPrng" macro will resolve to the pseudo-random number generator
 27221    ** state vector.  If writable static data is unsupported on the target,
 27222    ** we have to locate the state vector at run-time.  In the more common
 27223    ** case where writable static data is supported, wsdPrng can refer directly
 27224    ** to the "sqlite3Prng" state vector declared above.
 27225    */
 27226  #ifdef SQLITE_OMIT_WSD
 27227    struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
 27228  # define wsdPrng p[0]
 27229  #else
 27230  # define wsdPrng sqlite3Prng
 27231  #endif
 27232  
 27233  #if SQLITE_THREADSAFE
 27234    sqlite3_mutex *mutex;
 27235  #endif
 27236  
 27237  #ifndef SQLITE_OMIT_AUTOINIT
 27238    if( sqlite3_initialize() ) return;
 27239  #endif
 27240  
 27241  #if SQLITE_THREADSAFE
 27242    mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
 27243  #endif
 27244  
 27245    sqlite3_mutex_enter(mutex);
 27246    if( N<=0 || pBuf==0 ){
 27247      wsdPrng.isInit = 0;
 27248      sqlite3_mutex_leave(mutex);
 27249      return;
 27250    }
 27251  
 27252    /* Initialize the state of the random number generator once,
 27253    ** the first time this routine is called.  The seed value does
 27254    ** not need to contain a lot of randomness since we are not
 27255    ** trying to do secure encryption or anything like that...
 27256    **
 27257    ** Nothing in this file or anywhere else in SQLite does any kind of
 27258    ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
 27259    ** number generator) not as an encryption device.
 27260    */
 27261    if( !wsdPrng.isInit ){
 27262      int i;
 27263      char k[256];
 27264      wsdPrng.j = 0;
 27265      wsdPrng.i = 0;
 27266      sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
 27267      for(i=0; i<256; i++){
 27268        wsdPrng.s[i] = (u8)i;
 27269      }
 27270      for(i=0; i<256; i++){
 27271        wsdPrng.j += wsdPrng.s[i] + k[i];
 27272        t = wsdPrng.s[wsdPrng.j];
 27273        wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
 27274        wsdPrng.s[i] = t;
 27275      }
 27276      wsdPrng.isInit = 1;
 27277    }
 27278  
 27279    assert( N>0 );
 27280    do{
 27281      wsdPrng.i++;
 27282      t = wsdPrng.s[wsdPrng.i];
 27283      wsdPrng.j += t;
 27284      wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
 27285      wsdPrng.s[wsdPrng.j] = t;
 27286      t += wsdPrng.s[wsdPrng.i];
 27287      *(zBuf++) = wsdPrng.s[t];
 27288    }while( --N );
 27289    sqlite3_mutex_leave(mutex);
 27290  }
 27291  
 27292  #ifndef SQLITE_UNTESTABLE
 27293  /*
 27294  ** For testing purposes, we sometimes want to preserve the state of
 27295  ** PRNG and restore the PRNG to its saved state at a later time, or
 27296  ** to reset the PRNG to its initial state.  These routines accomplish
 27297  ** those tasks.
 27298  **
 27299  ** The sqlite3_test_control() interface calls these routines to
 27300  ** control the PRNG.
 27301  */
 27302  static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
 27303  SQLITE_PRIVATE void sqlite3PrngSaveState(void){
 27304    memcpy(
 27305      &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
 27306      &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
 27307      sizeof(sqlite3Prng)
 27308    );
 27309  }
 27310  SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
 27311    memcpy(
 27312      &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
 27313      &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
 27314      sizeof(sqlite3Prng)
 27315    );
 27316  }
 27317  #endif /* SQLITE_UNTESTABLE */
 27318  
 27319  /************** End of random.c **********************************************/
 27320  /************** Begin file threads.c *****************************************/
 27321  /*
 27322  ** 2012 July 21
 27323  **
 27324  ** The author disclaims copyright to this source code.  In place of
 27325  ** a legal notice, here is a blessing:
 27326  **
 27327  **    May you do good and not evil.
 27328  **    May you find forgiveness for yourself and forgive others.
 27329  **    May you share freely, never taking more than you give.
 27330  **
 27331  ******************************************************************************
 27332  **
 27333  ** This file presents a simple cross-platform threading interface for
 27334  ** use internally by SQLite.
 27335  **
 27336  ** A "thread" can be created using sqlite3ThreadCreate().  This thread
 27337  ** runs independently of its creator until it is joined using
 27338  ** sqlite3ThreadJoin(), at which point it terminates.
 27339  **
 27340  ** Threads do not have to be real.  It could be that the work of the
 27341  ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
 27342  ** or sqlite3ThreadJoin() call.  This is, in fact, what happens in
 27343  ** single threaded systems.  Nothing in SQLite requires multiple threads.
 27344  ** This interface exists so that applications that want to take advantage
 27345  ** of multiple cores can do so, while also allowing applications to stay
 27346  ** single-threaded if desired.
 27347  */
 27348  /* #include "sqliteInt.h" */
 27349  #if SQLITE_OS_WIN
 27350  /* #  include "os_win.h" */
 27351  #endif
 27352  
 27353  #if SQLITE_MAX_WORKER_THREADS>0
 27354  
 27355  /********************************* Unix Pthreads ****************************/
 27356  #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
 27357  
 27358  #define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
 27359  /* #include <pthread.h> */
 27360  
 27361  /* A running thread */
 27362  struct SQLiteThread {
 27363    pthread_t tid;                 /* Thread ID */
 27364    int done;                      /* Set to true when thread finishes */
 27365    void *pOut;                    /* Result returned by the thread */
 27366    void *(*xTask)(void*);         /* The thread routine */
 27367    void *pIn;                     /* Argument to the thread */
 27368  };
 27369  
 27370  /* Create a new thread */
 27371  SQLITE_PRIVATE int sqlite3ThreadCreate(
 27372    SQLiteThread **ppThread,  /* OUT: Write the thread object here */
 27373    void *(*xTask)(void*),    /* Routine to run in a separate thread */
 27374    void *pIn                 /* Argument passed into xTask() */
 27375  ){
 27376    SQLiteThread *p;
 27377    int rc;
 27378  
 27379    assert( ppThread!=0 );
 27380    assert( xTask!=0 );
 27381    /* This routine is never used in single-threaded mode */
 27382    assert( sqlite3GlobalConfig.bCoreMutex!=0 );
 27383  
 27384    *ppThread = 0;
 27385    p = sqlite3Malloc(sizeof(*p));
 27386    if( p==0 ) return SQLITE_NOMEM_BKPT;
 27387    memset(p, 0, sizeof(*p));
 27388    p->xTask = xTask;
 27389    p->pIn = pIn;
 27390    /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a 
 27391    ** function that returns SQLITE_ERROR when passed the argument 200, that
 27392    ** forces worker threads to run sequentially and deterministically 
 27393    ** for testing purposes. */
 27394    if( sqlite3FaultSim(200) ){
 27395      rc = 1;
 27396    }else{    
 27397      rc = pthread_create(&p->tid, 0, xTask, pIn);
 27398    }
 27399    if( rc ){
 27400      p->done = 1;
 27401      p->pOut = xTask(pIn);
 27402    }
 27403    *ppThread = p;
 27404    return SQLITE_OK;
 27405  }
 27406  
 27407  /* Get the results of the thread */
 27408  SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
 27409    int rc;
 27410  
 27411    assert( ppOut!=0 );
 27412    if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
 27413    if( p->done ){
 27414      *ppOut = p->pOut;
 27415      rc = SQLITE_OK;
 27416    }else{
 27417      rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
 27418    }
 27419    sqlite3_free(p);
 27420    return rc;
 27421  }
 27422  
 27423  #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
 27424  /******************************** End Unix Pthreads *************************/
 27425  
 27426  
 27427  /********************************* Win32 Threads ****************************/
 27428  #if SQLITE_OS_WIN_THREADS
 27429  
 27430  #define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
 27431  #include <process.h>
 27432  
 27433  /* A running thread */
 27434  struct SQLiteThread {
 27435    void *tid;               /* The thread handle */
 27436    unsigned id;             /* The thread identifier */
 27437    void *(*xTask)(void*);   /* The routine to run as a thread */
 27438    void *pIn;               /* Argument to xTask */
 27439    void *pResult;           /* Result of xTask */
 27440  };
 27441  
 27442  /* Thread procedure Win32 compatibility shim */
 27443  static unsigned __stdcall sqlite3ThreadProc(
 27444    void *pArg  /* IN: Pointer to the SQLiteThread structure */
 27445  ){
 27446    SQLiteThread *p = (SQLiteThread *)pArg;
 27447  
 27448    assert( p!=0 );
 27449  #if 0
 27450    /*
 27451    ** This assert appears to trigger spuriously on certain
 27452    ** versions of Windows, possibly due to _beginthreadex()
 27453    ** and/or CreateThread() not fully setting their thread
 27454    ** ID parameter before starting the thread.
 27455    */
 27456    assert( p->id==GetCurrentThreadId() );
 27457  #endif
 27458    assert( p->xTask!=0 );
 27459    p->pResult = p->xTask(p->pIn);
 27460  
 27461    _endthreadex(0);
 27462    return 0; /* NOT REACHED */
 27463  }
 27464  
 27465  /* Create a new thread */
 27466  SQLITE_PRIVATE int sqlite3ThreadCreate(
 27467    SQLiteThread **ppThread,  /* OUT: Write the thread object here */
 27468    void *(*xTask)(void*),    /* Routine to run in a separate thread */
 27469    void *pIn                 /* Argument passed into xTask() */
 27470  ){
 27471    SQLiteThread *p;
 27472  
 27473    assert( ppThread!=0 );
 27474    assert( xTask!=0 );
 27475    *ppThread = 0;
 27476    p = sqlite3Malloc(sizeof(*p));
 27477    if( p==0 ) return SQLITE_NOMEM_BKPT;
 27478    /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a 
 27479    ** function that returns SQLITE_ERROR when passed the argument 200, that
 27480    ** forces worker threads to run sequentially and deterministically 
 27481    ** (via the sqlite3FaultSim() term of the conditional) for testing
 27482    ** purposes. */
 27483    if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
 27484      memset(p, 0, sizeof(*p));
 27485    }else{
 27486      p->xTask = xTask;
 27487      p->pIn = pIn;
 27488      p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
 27489      if( p->tid==0 ){
 27490        memset(p, 0, sizeof(*p));
 27491      }
 27492    }
 27493    if( p->xTask==0 ){
 27494      p->id = GetCurrentThreadId();
 27495      p->pResult = xTask(pIn);
 27496    }
 27497    *ppThread = p;
 27498    return SQLITE_OK;
 27499  }
 27500  
 27501  SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
 27502  
 27503  /* Get the results of the thread */
 27504  SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
 27505    DWORD rc;
 27506    BOOL bRc;
 27507  
 27508    assert( ppOut!=0 );
 27509    if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
 27510    if( p->xTask==0 ){
 27511      /* assert( p->id==GetCurrentThreadId() ); */
 27512      rc = WAIT_OBJECT_0;
 27513      assert( p->tid==0 );
 27514    }else{
 27515      assert( p->id!=0 && p->id!=GetCurrentThreadId() );
 27516      rc = sqlite3Win32Wait((HANDLE)p->tid);
 27517      assert( rc!=WAIT_IO_COMPLETION );
 27518      bRc = CloseHandle((HANDLE)p->tid);
 27519      assert( bRc );
 27520    }
 27521    if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
 27522    sqlite3_free(p);
 27523    return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
 27524  }
 27525  
 27526  #endif /* SQLITE_OS_WIN_THREADS */
 27527  /******************************** End Win32 Threads *************************/
 27528  
 27529  
 27530  /********************************* Single-Threaded **************************/
 27531  #ifndef SQLITE_THREADS_IMPLEMENTED
 27532  /*
 27533  ** This implementation does not actually create a new thread.  It does the
 27534  ** work of the thread in the main thread, when either the thread is created
 27535  ** or when it is joined
 27536  */
 27537  
 27538  /* A running thread */
 27539  struct SQLiteThread {
 27540    void *(*xTask)(void*);   /* The routine to run as a thread */
 27541    void *pIn;               /* Argument to xTask */
 27542    void *pResult;           /* Result of xTask */
 27543  };
 27544  
 27545  /* Create a new thread */
 27546  SQLITE_PRIVATE int sqlite3ThreadCreate(
 27547    SQLiteThread **ppThread,  /* OUT: Write the thread object here */
 27548    void *(*xTask)(void*),    /* Routine to run in a separate thread */
 27549    void *pIn                 /* Argument passed into xTask() */
 27550  ){
 27551    SQLiteThread *p;
 27552  
 27553    assert( ppThread!=0 );
 27554    assert( xTask!=0 );
 27555    *ppThread = 0;
 27556    p = sqlite3Malloc(sizeof(*p));
 27557    if( p==0 ) return SQLITE_NOMEM_BKPT;
 27558    if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
 27559      p->xTask = xTask;
 27560      p->pIn = pIn;
 27561    }else{
 27562      p->xTask = 0;
 27563      p->pResult = xTask(pIn);
 27564    }
 27565    *ppThread = p;
 27566    return SQLITE_OK;
 27567  }
 27568  
 27569  /* Get the results of the thread */
 27570  SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
 27571  
 27572    assert( ppOut!=0 );
 27573    if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
 27574    if( p->xTask ){
 27575      *ppOut = p->xTask(p->pIn);
 27576    }else{
 27577      *ppOut = p->pResult;
 27578    }
 27579    sqlite3_free(p);
 27580  
 27581  #if defined(SQLITE_TEST)
 27582    {
 27583      void *pTstAlloc = sqlite3Malloc(10);
 27584      if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
 27585      sqlite3_free(pTstAlloc);
 27586    }
 27587  #endif
 27588  
 27589    return SQLITE_OK;
 27590  }
 27591  
 27592  #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
 27593  /****************************** End Single-Threaded *************************/
 27594  #endif /* SQLITE_MAX_WORKER_THREADS>0 */
 27595  
 27596  /************** End of threads.c *********************************************/
 27597  /************** Begin file utf.c *********************************************/
 27598  /*
 27599  ** 2004 April 13
 27600  **
 27601  ** The author disclaims copyright to this source code.  In place of
 27602  ** a legal notice, here is a blessing:
 27603  **
 27604  **    May you do good and not evil.
 27605  **    May you find forgiveness for yourself and forgive others.
 27606  **    May you share freely, never taking more than you give.
 27607  **
 27608  *************************************************************************
 27609  ** This file contains routines used to translate between UTF-8, 
 27610  ** UTF-16, UTF-16BE, and UTF-16LE.
 27611  **
 27612  ** Notes on UTF-8:
 27613  **
 27614  **   Byte-0    Byte-1    Byte-2    Byte-3    Value
 27615  **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
 27616  **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
 27617  **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
 27618  **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
 27619  **
 27620  **
 27621  ** Notes on UTF-16:  (with wwww+1==uuuuu)
 27622  **
 27623  **      Word-0               Word-1          Value
 27624  **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
 27625  **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
 27626  **
 27627  **
 27628  ** BOM or Byte Order Mark:
 27629  **     0xff 0xfe   little-endian utf-16 follows
 27630  **     0xfe 0xff   big-endian utf-16 follows
 27631  **
 27632  */
 27633  /* #include "sqliteInt.h" */
 27634  /* #include <assert.h> */
 27635  /* #include "vdbeInt.h" */
 27636  
 27637  #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
 27638  /*
 27639  ** The following constant value is used by the SQLITE_BIGENDIAN and
 27640  ** SQLITE_LITTLEENDIAN macros.
 27641  */
 27642  SQLITE_PRIVATE const int sqlite3one = 1;
 27643  #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
 27644  
 27645  /*
 27646  ** This lookup table is used to help decode the first byte of
 27647  ** a multi-byte UTF8 character.
 27648  */
 27649  static const unsigned char sqlite3Utf8Trans1[] = {
 27650    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
 27651    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
 27652    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
 27653    0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
 27654    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
 27655    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
 27656    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
 27657    0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
 27658  };
 27659  
 27660  
 27661  #define WRITE_UTF8(zOut, c) {                          \
 27662    if( c<0x00080 ){                                     \
 27663      *zOut++ = (u8)(c&0xFF);                            \
 27664    }                                                    \
 27665    else if( c<0x00800 ){                                \
 27666      *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
 27667      *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
 27668    }                                                    \
 27669    else if( c<0x10000 ){                                \
 27670      *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
 27671      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
 27672      *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
 27673    }else{                                               \
 27674      *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
 27675      *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
 27676      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
 27677      *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
 27678    }                                                    \
 27679  }
 27680  
 27681  #define WRITE_UTF16LE(zOut, c) {                                    \
 27682    if( c<=0xFFFF ){                                                  \
 27683      *zOut++ = (u8)(c&0x00FF);                                       \
 27684      *zOut++ = (u8)((c>>8)&0x00FF);                                  \
 27685    }else{                                                            \
 27686      *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
 27687      *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
 27688      *zOut++ = (u8)(c&0x00FF);                                       \
 27689      *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
 27690    }                                                                 \
 27691  }
 27692  
 27693  #define WRITE_UTF16BE(zOut, c) {                                    \
 27694    if( c<=0xFFFF ){                                                  \
 27695      *zOut++ = (u8)((c>>8)&0x00FF);                                  \
 27696      *zOut++ = (u8)(c&0x00FF);                                       \
 27697    }else{                                                            \
 27698      *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
 27699      *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
 27700      *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
 27701      *zOut++ = (u8)(c&0x00FF);                                       \
 27702    }                                                                 \
 27703  }
 27704  
 27705  #define READ_UTF16LE(zIn, TERM, c){                                   \
 27706    c = (*zIn++);                                                       \
 27707    c += ((*zIn++)<<8);                                                 \
 27708    if( c>=0xD800 && c<0xE000 && TERM ){                                \
 27709      int c2 = (*zIn++);                                                \
 27710      c2 += ((*zIn++)<<8);                                              \
 27711      c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
 27712    }                                                                   \
 27713  }
 27714  
 27715  #define READ_UTF16BE(zIn, TERM, c){                                   \
 27716    c = ((*zIn++)<<8);                                                  \
 27717    c += (*zIn++);                                                      \
 27718    if( c>=0xD800 && c<0xE000 && TERM ){                                \
 27719      int c2 = ((*zIn++)<<8);                                           \
 27720      c2 += (*zIn++);                                                   \
 27721      c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
 27722    }                                                                   \
 27723  }
 27724  
 27725  /*
 27726  ** Translate a single UTF-8 character.  Return the unicode value.
 27727  **
 27728  ** During translation, assume that the byte that zTerm points
 27729  ** is a 0x00.
 27730  **
 27731  ** Write a pointer to the next unread byte back into *pzNext.
 27732  **
 27733  ** Notes On Invalid UTF-8:
 27734  **
 27735  **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
 27736  **     be encoded as a multi-byte character.  Any multi-byte character that
 27737  **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
 27738  **
 27739  **  *  This routine never allows a UTF16 surrogate value to be encoded.
 27740  **     If a multi-byte character attempts to encode a value between
 27741  **     0xd800 and 0xe000 then it is rendered as 0xfffd.
 27742  **
 27743  **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
 27744  **     byte of a character are interpreted as single-byte characters
 27745  **     and rendered as themselves even though they are technically
 27746  **     invalid characters.
 27747  **
 27748  **  *  This routine accepts over-length UTF8 encodings
 27749  **     for unicode values 0x80 and greater.  It does not change over-length
 27750  **     encodings to 0xfffd as some systems recommend.
 27751  */
 27752  #define READ_UTF8(zIn, zTerm, c)                           \
 27753    c = *(zIn++);                                            \
 27754    if( c>=0xc0 ){                                           \
 27755      c = sqlite3Utf8Trans1[c-0xc0];                         \
 27756      while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
 27757        c = (c<<6) + (0x3f & *(zIn++));                      \
 27758      }                                                      \
 27759      if( c<0x80                                             \
 27760          || (c&0xFFFFF800)==0xD800                          \
 27761          || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
 27762    }
 27763  SQLITE_PRIVATE u32 sqlite3Utf8Read(
 27764    const unsigned char **pz    /* Pointer to string from which to read char */
 27765  ){
 27766    unsigned int c;
 27767  
 27768    /* Same as READ_UTF8() above but without the zTerm parameter.
 27769    ** For this routine, we assume the UTF8 string is always zero-terminated.
 27770    */
 27771    c = *((*pz)++);
 27772    if( c>=0xc0 ){
 27773      c = sqlite3Utf8Trans1[c-0xc0];
 27774      while( (*(*pz) & 0xc0)==0x80 ){
 27775        c = (c<<6) + (0x3f & *((*pz)++));
 27776      }
 27777      if( c<0x80
 27778          || (c&0xFFFFF800)==0xD800
 27779          || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
 27780    }
 27781    return c;
 27782  }
 27783  
 27784  
 27785  
 27786  
 27787  /*
 27788  ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
 27789  ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
 27790  */ 
 27791  /* #define TRANSLATE_TRACE 1 */
 27792  
 27793  #ifndef SQLITE_OMIT_UTF16
 27794  /*
 27795  ** This routine transforms the internal text encoding used by pMem to
 27796  ** desiredEnc. It is an error if the string is already of the desired
 27797  ** encoding, or if *pMem does not contain a string value.
 27798  */
 27799  SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
 27800    int len;                    /* Maximum length of output string in bytes */
 27801    unsigned char *zOut;                  /* Output buffer */
 27802    unsigned char *zIn;                   /* Input iterator */
 27803    unsigned char *zTerm;                 /* End of input */
 27804    unsigned char *z;                     /* Output iterator */
 27805    unsigned int c;
 27806  
 27807    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 27808    assert( pMem->flags&MEM_Str );
 27809    assert( pMem->enc!=desiredEnc );
 27810    assert( pMem->enc!=0 );
 27811    assert( pMem->n>=0 );
 27812  
 27813  #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
 27814    {
 27815      char zBuf[100];
 27816      sqlite3VdbeMemPrettyPrint(pMem, zBuf);
 27817      fprintf(stderr, "INPUT:  %s\n", zBuf);
 27818    }
 27819  #endif
 27820  
 27821    /* If the translation is between UTF-16 little and big endian, then 
 27822    ** all that is required is to swap the byte order. This case is handled
 27823    ** differently from the others.
 27824    */
 27825    if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
 27826      u8 temp;
 27827      int rc;
 27828      rc = sqlite3VdbeMemMakeWriteable(pMem);
 27829      if( rc!=SQLITE_OK ){
 27830        assert( rc==SQLITE_NOMEM );
 27831        return SQLITE_NOMEM_BKPT;
 27832      }
 27833      zIn = (u8*)pMem->z;
 27834      zTerm = &zIn[pMem->n&~1];
 27835      while( zIn<zTerm ){
 27836        temp = *zIn;
 27837        *zIn = *(zIn+1);
 27838        zIn++;
 27839        *zIn++ = temp;
 27840      }
 27841      pMem->enc = desiredEnc;
 27842      goto translate_out;
 27843    }
 27844  
 27845    /* Set len to the maximum number of bytes required in the output buffer. */
 27846    if( desiredEnc==SQLITE_UTF8 ){
 27847      /* When converting from UTF-16, the maximum growth results from
 27848      ** translating a 2-byte character to a 4-byte UTF-8 character.
 27849      ** A single byte is required for the output string
 27850      ** nul-terminator.
 27851      */
 27852      pMem->n &= ~1;
 27853      len = pMem->n * 2 + 1;
 27854    }else{
 27855      /* When converting from UTF-8 to UTF-16 the maximum growth is caused
 27856      ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
 27857      ** character. Two bytes are required in the output buffer for the
 27858      ** nul-terminator.
 27859      */
 27860      len = pMem->n * 2 + 2;
 27861    }
 27862  
 27863    /* Set zIn to point at the start of the input buffer and zTerm to point 1
 27864    ** byte past the end.
 27865    **
 27866    ** Variable zOut is set to point at the output buffer, space obtained
 27867    ** from sqlite3_malloc().
 27868    */
 27869    zIn = (u8*)pMem->z;
 27870    zTerm = &zIn[pMem->n];
 27871    zOut = sqlite3DbMallocRaw(pMem->db, len);
 27872    if( !zOut ){
 27873      return SQLITE_NOMEM_BKPT;
 27874    }
 27875    z = zOut;
 27876  
 27877    if( pMem->enc==SQLITE_UTF8 ){
 27878      if( desiredEnc==SQLITE_UTF16LE ){
 27879        /* UTF-8 -> UTF-16 Little-endian */
 27880        while( zIn<zTerm ){
 27881          READ_UTF8(zIn, zTerm, c);
 27882          WRITE_UTF16LE(z, c);
 27883        }
 27884      }else{
 27885        assert( desiredEnc==SQLITE_UTF16BE );
 27886        /* UTF-8 -> UTF-16 Big-endian */
 27887        while( zIn<zTerm ){
 27888          READ_UTF8(zIn, zTerm, c);
 27889          WRITE_UTF16BE(z, c);
 27890        }
 27891      }
 27892      pMem->n = (int)(z - zOut);
 27893      *z++ = 0;
 27894    }else{
 27895      assert( desiredEnc==SQLITE_UTF8 );
 27896      if( pMem->enc==SQLITE_UTF16LE ){
 27897        /* UTF-16 Little-endian -> UTF-8 */
 27898        while( zIn<zTerm ){
 27899          READ_UTF16LE(zIn, zIn<zTerm, c); 
 27900          WRITE_UTF8(z, c);
 27901        }
 27902      }else{
 27903        /* UTF-16 Big-endian -> UTF-8 */
 27904        while( zIn<zTerm ){
 27905          READ_UTF16BE(zIn, zIn<zTerm, c); 
 27906          WRITE_UTF8(z, c);
 27907        }
 27908      }
 27909      pMem->n = (int)(z - zOut);
 27910    }
 27911    *z = 0;
 27912    assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
 27913  
 27914    c = pMem->flags;
 27915    sqlite3VdbeMemRelease(pMem);
 27916    pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
 27917    pMem->enc = desiredEnc;
 27918    pMem->z = (char*)zOut;
 27919    pMem->zMalloc = pMem->z;
 27920    pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
 27921  
 27922  translate_out:
 27923  #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
 27924    {
 27925      char zBuf[100];
 27926      sqlite3VdbeMemPrettyPrint(pMem, zBuf);
 27927      fprintf(stderr, "OUTPUT: %s\n", zBuf);
 27928    }
 27929  #endif
 27930    return SQLITE_OK;
 27931  }
 27932  #endif /* SQLITE_OMIT_UTF16 */
 27933  
 27934  #ifndef SQLITE_OMIT_UTF16
 27935  /*
 27936  ** This routine checks for a byte-order mark at the beginning of the 
 27937  ** UTF-16 string stored in *pMem. If one is present, it is removed and
 27938  ** the encoding of the Mem adjusted. This routine does not do any
 27939  ** byte-swapping, it just sets Mem.enc appropriately.
 27940  **
 27941  ** The allocation (static, dynamic etc.) and encoding of the Mem may be
 27942  ** changed by this function.
 27943  */
 27944  SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
 27945    int rc = SQLITE_OK;
 27946    u8 bom = 0;
 27947  
 27948    assert( pMem->n>=0 );
 27949    if( pMem->n>1 ){
 27950      u8 b1 = *(u8 *)pMem->z;
 27951      u8 b2 = *(((u8 *)pMem->z) + 1);
 27952      if( b1==0xFE && b2==0xFF ){
 27953        bom = SQLITE_UTF16BE;
 27954      }
 27955      if( b1==0xFF && b2==0xFE ){
 27956        bom = SQLITE_UTF16LE;
 27957      }
 27958    }
 27959    
 27960    if( bom ){
 27961      rc = sqlite3VdbeMemMakeWriteable(pMem);
 27962      if( rc==SQLITE_OK ){
 27963        pMem->n -= 2;
 27964        memmove(pMem->z, &pMem->z[2], pMem->n);
 27965        pMem->z[pMem->n] = '\0';
 27966        pMem->z[pMem->n+1] = '\0';
 27967        pMem->flags |= MEM_Term;
 27968        pMem->enc = bom;
 27969      }
 27970    }
 27971    return rc;
 27972  }
 27973  #endif /* SQLITE_OMIT_UTF16 */
 27974  
 27975  /*
 27976  ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
 27977  ** return the number of unicode characters in pZ up to (but not including)
 27978  ** the first 0x00 byte. If nByte is not less than zero, return the
 27979  ** number of unicode characters in the first nByte of pZ (or up to 
 27980  ** the first 0x00, whichever comes first).
 27981  */
 27982  SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
 27983    int r = 0;
 27984    const u8 *z = (const u8*)zIn;
 27985    const u8 *zTerm;
 27986    if( nByte>=0 ){
 27987      zTerm = &z[nByte];
 27988    }else{
 27989      zTerm = (const u8*)(-1);
 27990    }
 27991    assert( z<=zTerm );
 27992    while( *z!=0 && z<zTerm ){
 27993      SQLITE_SKIP_UTF8(z);
 27994      r++;
 27995    }
 27996    return r;
 27997  }
 27998  
 27999  /* This test function is not currently used by the automated test-suite. 
 28000  ** Hence it is only available in debug builds.
 28001  */
 28002  #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
 28003  /*
 28004  ** Translate UTF-8 to UTF-8.
 28005  **
 28006  ** This has the effect of making sure that the string is well-formed
 28007  ** UTF-8.  Miscoded characters are removed.
 28008  **
 28009  ** The translation is done in-place and aborted if the output
 28010  ** overruns the input.
 28011  */
 28012  SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
 28013    unsigned char *zOut = zIn;
 28014    unsigned char *zStart = zIn;
 28015    u32 c;
 28016  
 28017    while( zIn[0] && zOut<=zIn ){
 28018      c = sqlite3Utf8Read((const u8**)&zIn);
 28019      if( c!=0xfffd ){
 28020        WRITE_UTF8(zOut, c);
 28021      }
 28022    }
 28023    *zOut = 0;
 28024    return (int)(zOut - zStart);
 28025  }
 28026  #endif
 28027  
 28028  #ifndef SQLITE_OMIT_UTF16
 28029  /*
 28030  ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
 28031  ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
 28032  ** be freed by the calling function.
 28033  **
 28034  ** NULL is returned if there is an allocation error.
 28035  */
 28036  SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
 28037    Mem m;
 28038    memset(&m, 0, sizeof(m));
 28039    m.db = db;
 28040    sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
 28041    sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
 28042    if( db->mallocFailed ){
 28043      sqlite3VdbeMemRelease(&m);
 28044      m.z = 0;
 28045    }
 28046    assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
 28047    assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
 28048    assert( m.z || db->mallocFailed );
 28049    return m.z;
 28050  }
 28051  
 28052  /*
 28053  ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
 28054  ** Return the number of bytes in the first nChar unicode characters
 28055  ** in pZ.  nChar must be non-negative.
 28056  */
 28057  SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
 28058    int c;
 28059    unsigned char const *z = zIn;
 28060    int n = 0;
 28061    
 28062    if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
 28063      while( n<nChar ){
 28064        READ_UTF16BE(z, 1, c);
 28065        n++;
 28066      }
 28067    }else{
 28068      while( n<nChar ){
 28069        READ_UTF16LE(z, 1, c);
 28070        n++;
 28071      }
 28072    }
 28073    return (int)(z-(unsigned char const *)zIn);
 28074  }
 28075  
 28076  #if defined(SQLITE_TEST)
 28077  /*
 28078  ** This routine is called from the TCL test function "translate_selftest".
 28079  ** It checks that the primitives for serializing and deserializing
 28080  ** characters in each encoding are inverses of each other.
 28081  */
 28082  SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
 28083    unsigned int i, t;
 28084    unsigned char zBuf[20];
 28085    unsigned char *z;
 28086    int n;
 28087    unsigned int c;
 28088  
 28089    for(i=0; i<0x00110000; i++){
 28090      z = zBuf;
 28091      WRITE_UTF8(z, i);
 28092      n = (int)(z-zBuf);
 28093      assert( n>0 && n<=4 );
 28094      z[0] = 0;
 28095      z = zBuf;
 28096      c = sqlite3Utf8Read((const u8**)&z);
 28097      t = i;
 28098      if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
 28099      if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
 28100      assert( c==t );
 28101      assert( (z-zBuf)==n );
 28102    }
 28103    for(i=0; i<0x00110000; i++){
 28104      if( i>=0xD800 && i<0xE000 ) continue;
 28105      z = zBuf;
 28106      WRITE_UTF16LE(z, i);
 28107      n = (int)(z-zBuf);
 28108      assert( n>0 && n<=4 );
 28109      z[0] = 0;
 28110      z = zBuf;
 28111      READ_UTF16LE(z, 1, c);
 28112      assert( c==i );
 28113      assert( (z-zBuf)==n );
 28114    }
 28115    for(i=0; i<0x00110000; i++){
 28116      if( i>=0xD800 && i<0xE000 ) continue;
 28117      z = zBuf;
 28118      WRITE_UTF16BE(z, i);
 28119      n = (int)(z-zBuf);
 28120      assert( n>0 && n<=4 );
 28121      z[0] = 0;
 28122      z = zBuf;
 28123      READ_UTF16BE(z, 1, c);
 28124      assert( c==i );
 28125      assert( (z-zBuf)==n );
 28126    }
 28127  }
 28128  #endif /* SQLITE_TEST */
 28129  #endif /* SQLITE_OMIT_UTF16 */
 28130  
 28131  /************** End of utf.c *************************************************/
 28132  /************** Begin file util.c ********************************************/
 28133  /*
 28134  ** 2001 September 15
 28135  **
 28136  ** The author disclaims copyright to this source code.  In place of
 28137  ** a legal notice, here is a blessing:
 28138  **
 28139  **    May you do good and not evil.
 28140  **    May you find forgiveness for yourself and forgive others.
 28141  **    May you share freely, never taking more than you give.
 28142  **
 28143  *************************************************************************
 28144  ** Utility functions used throughout sqlite.
 28145  **
 28146  ** This file contains functions for allocating memory, comparing
 28147  ** strings, and stuff like that.
 28148  **
 28149  */
 28150  /* #include "sqliteInt.h" */
 28151  /* #include <stdarg.h> */
 28152  #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
 28153  # include <math.h>
 28154  #endif
 28155  
 28156  /*
 28157  ** Routine needed to support the testcase() macro.
 28158  */
 28159  #ifdef SQLITE_COVERAGE_TEST
 28160  SQLITE_PRIVATE void sqlite3Coverage(int x){
 28161    static unsigned dummy = 0;
 28162    dummy += (unsigned)x;
 28163  }
 28164  #endif
 28165  
 28166  /*
 28167  ** Give a callback to the test harness that can be used to simulate faults
 28168  ** in places where it is difficult or expensive to do so purely by means
 28169  ** of inputs.
 28170  **
 28171  ** The intent of the integer argument is to let the fault simulator know
 28172  ** which of multiple sqlite3FaultSim() calls has been hit.
 28173  **
 28174  ** Return whatever integer value the test callback returns, or return
 28175  ** SQLITE_OK if no test callback is installed.
 28176  */
 28177  #ifndef SQLITE_UNTESTABLE
 28178  SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
 28179    int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
 28180    return xCallback ? xCallback(iTest) : SQLITE_OK;
 28181  }
 28182  #endif
 28183  
 28184  #ifndef SQLITE_OMIT_FLOATING_POINT
 28185  /*
 28186  ** Return true if the floating point value is Not a Number (NaN).
 28187  **
 28188  ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
 28189  ** Otherwise, we have our own implementation that works on most systems.
 28190  */
 28191  SQLITE_PRIVATE int sqlite3IsNaN(double x){
 28192    int rc;   /* The value return */
 28193  #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
 28194    /*
 28195    ** Systems that support the isnan() library function should probably
 28196    ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
 28197    ** found that many systems do not have a working isnan() function so
 28198    ** this implementation is provided as an alternative.
 28199    **
 28200    ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
 28201    ** On the other hand, the use of -ffast-math comes with the following
 28202    ** warning:
 28203    **
 28204    **      This option [-ffast-math] should never be turned on by any
 28205    **      -O option since it can result in incorrect output for programs
 28206    **      which depend on an exact implementation of IEEE or ISO 
 28207    **      rules/specifications for math functions.
 28208    **
 28209    ** Under MSVC, this NaN test may fail if compiled with a floating-
 28210    ** point precision mode other than /fp:precise.  From the MSDN 
 28211    ** documentation:
 28212    **
 28213    **      The compiler [with /fp:precise] will properly handle comparisons 
 28214    **      involving NaN. For example, x != x evaluates to true if x is NaN 
 28215    **      ...
 28216    */
 28217  #ifdef __FAST_MATH__
 28218  # error SQLite will not work correctly with the -ffast-math option of GCC.
 28219  #endif
 28220    volatile double y = x;
 28221    volatile double z = y;
 28222    rc = (y!=z);
 28223  #else  /* if HAVE_ISNAN */
 28224    rc = isnan(x);
 28225  #endif /* HAVE_ISNAN */
 28226    testcase( rc );
 28227    return rc;
 28228  }
 28229  #endif /* SQLITE_OMIT_FLOATING_POINT */
 28230  
 28231  /*
 28232  ** Compute a string length that is limited to what can be stored in
 28233  ** lower 30 bits of a 32-bit signed integer.
 28234  **
 28235  ** The value returned will never be negative.  Nor will it ever be greater
 28236  ** than the actual length of the string.  For very long strings (greater
 28237  ** than 1GiB) the value returned might be less than the true string length.
 28238  */
 28239  SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
 28240    if( z==0 ) return 0;
 28241    return 0x3fffffff & (int)strlen(z);
 28242  }
 28243  
 28244  /*
 28245  ** Return the declared type of a column.  Or return zDflt if the column 
 28246  ** has no declared type.
 28247  **
 28248  ** The column type is an extra string stored after the zero-terminator on
 28249  ** the column name if and only if the COLFLAG_HASTYPE flag is set.
 28250  */
 28251  SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
 28252    if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
 28253    return pCol->zName + strlen(pCol->zName) + 1;
 28254  }
 28255  
 28256  /*
 28257  ** Helper function for sqlite3Error() - called rarely.  Broken out into
 28258  ** a separate routine to avoid unnecessary register saves on entry to
 28259  ** sqlite3Error().
 28260  */
 28261  static SQLITE_NOINLINE void  sqlite3ErrorFinish(sqlite3 *db, int err_code){
 28262    if( db->pErr ) sqlite3ValueSetNull(db->pErr);
 28263    sqlite3SystemError(db, err_code);
 28264  }
 28265  
 28266  /*
 28267  ** Set the current error code to err_code and clear any prior error message.
 28268  ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
 28269  ** that would be appropriate.
 28270  */
 28271  SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
 28272    assert( db!=0 );
 28273    db->errCode = err_code;
 28274    if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
 28275  }
 28276  
 28277  /*
 28278  ** Load the sqlite3.iSysErrno field if that is an appropriate thing
 28279  ** to do based on the SQLite error code in rc.
 28280  */
 28281  SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
 28282    if( rc==SQLITE_IOERR_NOMEM ) return;
 28283    rc &= 0xff;
 28284    if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
 28285      db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
 28286    }
 28287  }
 28288  
 28289  /*
 28290  ** Set the most recent error code and error string for the sqlite
 28291  ** handle "db". The error code is set to "err_code".
 28292  **
 28293  ** If it is not NULL, string zFormat specifies the format of the
 28294  ** error string in the style of the printf functions: The following
 28295  ** format characters are allowed:
 28296  **
 28297  **      %s      Insert a string
 28298  **      %z      A string that should be freed after use
 28299  **      %d      Insert an integer
 28300  **      %T      Insert a token
 28301  **      %S      Insert the first element of a SrcList
 28302  **
 28303  ** zFormat and any string tokens that follow it are assumed to be
 28304  ** encoded in UTF-8.
 28305  **
 28306  ** To clear the most recent error for sqlite handle "db", sqlite3Error
 28307  ** should be called with err_code set to SQLITE_OK and zFormat set
 28308  ** to NULL.
 28309  */
 28310  SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
 28311    assert( db!=0 );
 28312    db->errCode = err_code;
 28313    sqlite3SystemError(db, err_code);
 28314    if( zFormat==0 ){
 28315      sqlite3Error(db, err_code);
 28316    }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
 28317      char *z;
 28318      va_list ap;
 28319      va_start(ap, zFormat);
 28320      z = sqlite3VMPrintf(db, zFormat, ap);
 28321      va_end(ap);
 28322      sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
 28323    }
 28324  }
 28325  
 28326  /*
 28327  ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
 28328  ** The following formatting characters are allowed:
 28329  **
 28330  **      %s      Insert a string
 28331  **      %z      A string that should be freed after use
 28332  **      %d      Insert an integer
 28333  **      %T      Insert a token
 28334  **      %S      Insert the first element of a SrcList
 28335  **
 28336  ** This function should be used to report any error that occurs while
 28337  ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
 28338  ** last thing the sqlite3_prepare() function does is copy the error
 28339  ** stored by this function into the database handle using sqlite3Error().
 28340  ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
 28341  ** during statement execution (sqlite3_step() etc.).
 28342  */
 28343  SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
 28344    char *zMsg;
 28345    va_list ap;
 28346    sqlite3 *db = pParse->db;
 28347    va_start(ap, zFormat);
 28348    zMsg = sqlite3VMPrintf(db, zFormat, ap);
 28349    va_end(ap);
 28350    if( db->suppressErr ){
 28351      sqlite3DbFree(db, zMsg);
 28352    }else{
 28353      pParse->nErr++;
 28354      sqlite3DbFree(db, pParse->zErrMsg);
 28355      pParse->zErrMsg = zMsg;
 28356      pParse->rc = SQLITE_ERROR;
 28357    }
 28358  }
 28359  
 28360  /*
 28361  ** Convert an SQL-style quoted string into a normal string by removing
 28362  ** the quote characters.  The conversion is done in-place.  If the
 28363  ** input does not begin with a quote character, then this routine
 28364  ** is a no-op.
 28365  **
 28366  ** The input string must be zero-terminated.  A new zero-terminator
 28367  ** is added to the dequoted string.
 28368  **
 28369  ** The return value is -1 if no dequoting occurs or the length of the
 28370  ** dequoted string, exclusive of the zero terminator, if dequoting does
 28371  ** occur.
 28372  **
 28373  ** 2002-Feb-14: This routine is extended to remove MS-Access style
 28374  ** brackets from around identifiers.  For example:  "[a-b-c]" becomes
 28375  ** "a-b-c".
 28376  */
 28377  SQLITE_PRIVATE void sqlite3Dequote(char *z){
 28378    char quote;
 28379    int i, j;
 28380    if( z==0 ) return;
 28381    quote = z[0];
 28382    if( !sqlite3Isquote(quote) ) return;
 28383    if( quote=='[' ) quote = ']';
 28384    for(i=1, j=0;; i++){
 28385      assert( z[i] );
 28386      if( z[i]==quote ){
 28387        if( z[i+1]==quote ){
 28388          z[j++] = quote;
 28389          i++;
 28390        }else{
 28391          break;
 28392        }
 28393      }else{
 28394        z[j++] = z[i];
 28395      }
 28396    }
 28397    z[j] = 0;
 28398  }
 28399  
 28400  /*
 28401  ** Generate a Token object from a string
 28402  */
 28403  SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
 28404    p->z = z;
 28405    p->n = sqlite3Strlen30(z);
 28406  }
 28407  
 28408  /* Convenient short-hand */
 28409  #define UpperToLower sqlite3UpperToLower
 28410  
 28411  /*
 28412  ** Some systems have stricmp().  Others have strcasecmp().  Because
 28413  ** there is no consistency, we will define our own.
 28414  **
 28415  ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
 28416  ** sqlite3_strnicmp() APIs allow applications and extensions to compare
 28417  ** the contents of two buffers containing UTF-8 strings in a
 28418  ** case-independent fashion, using the same definition of "case
 28419  ** independence" that SQLite uses internally when comparing identifiers.
 28420  */
 28421  SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
 28422    if( zLeft==0 ){
 28423      return zRight ? -1 : 0;
 28424    }else if( zRight==0 ){
 28425      return 1;
 28426    }
 28427    return sqlite3StrICmp(zLeft, zRight);
 28428  }
 28429  SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
 28430    unsigned char *a, *b;
 28431    int c;
 28432    a = (unsigned char *)zLeft;
 28433    b = (unsigned char *)zRight;
 28434    for(;;){
 28435      c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
 28436      if( c || *a==0 ) break;
 28437      a++;
 28438      b++;
 28439    }
 28440    return c;
 28441  }
 28442  SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
 28443    register unsigned char *a, *b;
 28444    if( zLeft==0 ){
 28445      return zRight ? -1 : 0;
 28446    }else if( zRight==0 ){
 28447      return 1;
 28448    }
 28449    a = (unsigned char *)zLeft;
 28450    b = (unsigned char *)zRight;
 28451    while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
 28452    return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
 28453  }
 28454  
 28455  /*
 28456  ** The string z[] is an text representation of a real number.
 28457  ** Convert this string to a double and write it into *pResult.
 28458  **
 28459  ** The string z[] is length bytes in length (bytes, not characters) and
 28460  ** uses the encoding enc.  The string is not necessarily zero-terminated.
 28461  **
 28462  ** Return TRUE if the result is a valid real number (or integer) and FALSE
 28463  ** if the string is empty or contains extraneous text.  Valid numbers
 28464  ** are in one of these formats:
 28465  **
 28466  **    [+-]digits[E[+-]digits]
 28467  **    [+-]digits.[digits][E[+-]digits]
 28468  **    [+-].digits[E[+-]digits]
 28469  **
 28470  ** Leading and trailing whitespace is ignored for the purpose of determining
 28471  ** validity.
 28472  **
 28473  ** If some prefix of the input string is a valid number, this routine
 28474  ** returns FALSE but it still converts the prefix and writes the result
 28475  ** into *pResult.
 28476  */
 28477  SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
 28478  #ifndef SQLITE_OMIT_FLOATING_POINT
 28479    int incr;
 28480    const char *zEnd = z + length;
 28481    /* sign * significand * (10 ^ (esign * exponent)) */
 28482    int sign = 1;    /* sign of significand */
 28483    i64 s = 0;       /* significand */
 28484    int d = 0;       /* adjust exponent for shifting decimal point */
 28485    int esign = 1;   /* sign of exponent */
 28486    int e = 0;       /* exponent */
 28487    int eValid = 1;  /* True exponent is either not used or is well-formed */
 28488    double result;
 28489    int nDigits = 0;
 28490    int nonNum = 0;  /* True if input contains UTF16 with high byte non-zero */
 28491  
 28492    assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
 28493    *pResult = 0.0;   /* Default return value, in case of an error */
 28494  
 28495    if( enc==SQLITE_UTF8 ){
 28496      incr = 1;
 28497    }else{
 28498      int i;
 28499      incr = 2;
 28500      assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
 28501      for(i=3-enc; i<length && z[i]==0; i+=2){}
 28502      nonNum = i<length;
 28503      zEnd = &z[i^1];
 28504      z += (enc&1);
 28505    }
 28506  
 28507    /* skip leading spaces */
 28508    while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
 28509    if( z>=zEnd ) return 0;
 28510  
 28511    /* get sign of significand */
 28512    if( *z=='-' ){
 28513      sign = -1;
 28514      z+=incr;
 28515    }else if( *z=='+' ){
 28516      z+=incr;
 28517    }
 28518  
 28519    /* copy max significant digits to significand */
 28520    while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
 28521      s = s*10 + (*z - '0');
 28522      z+=incr, nDigits++;
 28523    }
 28524  
 28525    /* skip non-significant significand digits
 28526    ** (increase exponent by d to shift decimal left) */
 28527    while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
 28528    if( z>=zEnd ) goto do_atof_calc;
 28529  
 28530    /* if decimal point is present */
 28531    if( *z=='.' ){
 28532      z+=incr;
 28533      /* copy digits from after decimal to significand
 28534      ** (decrease exponent by d to shift decimal right) */
 28535      while( z<zEnd && sqlite3Isdigit(*z) ){
 28536        if( s<((LARGEST_INT64-9)/10) ){
 28537          s = s*10 + (*z - '0');
 28538          d--;
 28539        }
 28540        z+=incr, nDigits++;
 28541      }
 28542    }
 28543    if( z>=zEnd ) goto do_atof_calc;
 28544  
 28545    /* if exponent is present */
 28546    if( *z=='e' || *z=='E' ){
 28547      z+=incr;
 28548      eValid = 0;
 28549  
 28550      /* This branch is needed to avoid a (harmless) buffer overread.  The 
 28551      ** special comment alerts the mutation tester that the correct answer
 28552      ** is obtained even if the branch is omitted */
 28553      if( z>=zEnd ) goto do_atof_calc;              /*PREVENTS-HARMLESS-OVERREAD*/
 28554  
 28555      /* get sign of exponent */
 28556      if( *z=='-' ){
 28557        esign = -1;
 28558        z+=incr;
 28559      }else if( *z=='+' ){
 28560        z+=incr;
 28561      }
 28562      /* copy digits to exponent */
 28563      while( z<zEnd && sqlite3Isdigit(*z) ){
 28564        e = e<10000 ? (e*10 + (*z - '0')) : 10000;
 28565        z+=incr;
 28566        eValid = 1;
 28567      }
 28568    }
 28569  
 28570    /* skip trailing spaces */
 28571    while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
 28572  
 28573  do_atof_calc:
 28574    /* adjust exponent by d, and update sign */
 28575    e = (e*esign) + d;
 28576    if( e<0 ) {
 28577      esign = -1;
 28578      e *= -1;
 28579    } else {
 28580      esign = 1;
 28581    }
 28582  
 28583    if( s==0 ) {
 28584      /* In the IEEE 754 standard, zero is signed. */
 28585      result = sign<0 ? -(double)0 : (double)0;
 28586    } else {
 28587      /* Attempt to reduce exponent.
 28588      **
 28589      ** Branches that are not required for the correct answer but which only
 28590      ** help to obtain the correct answer faster are marked with special
 28591      ** comments, as a hint to the mutation tester.
 28592      */
 28593      while( e>0 ){                                       /*OPTIMIZATION-IF-TRUE*/
 28594        if( esign>0 ){
 28595          if( s>=(LARGEST_INT64/10) ) break;             /*OPTIMIZATION-IF-FALSE*/
 28596          s *= 10;
 28597        }else{
 28598          if( s%10!=0 ) break;                           /*OPTIMIZATION-IF-FALSE*/
 28599          s /= 10;
 28600        }
 28601        e--;
 28602      }
 28603  
 28604      /* adjust the sign of significand */
 28605      s = sign<0 ? -s : s;
 28606  
 28607      if( e==0 ){                                         /*OPTIMIZATION-IF-TRUE*/
 28608        result = (double)s;
 28609      }else{
 28610        LONGDOUBLE_TYPE scale = 1.0;
 28611        /* attempt to handle extremely small/large numbers better */
 28612        if( e>307 ){                                      /*OPTIMIZATION-IF-TRUE*/
 28613          if( e<342 ){                                    /*OPTIMIZATION-IF-TRUE*/
 28614            while( e%308 ) { scale *= 1.0e+1; e -= 1; }
 28615            if( esign<0 ){
 28616              result = s / scale;
 28617              result /= 1.0e+308;
 28618            }else{
 28619              result = s * scale;
 28620              result *= 1.0e+308;
 28621            }
 28622          }else{ assert( e>=342 );
 28623            if( esign<0 ){
 28624              result = 0.0*s;
 28625            }else{
 28626  #ifdef INFINITY
 28627              result = INFINITY*s;
 28628  #else
 28629              result = 1e308*1e308*s;  /* Infinity */
 28630  #endif
 28631            }
 28632          }
 28633        }else{
 28634          /* 1.0e+22 is the largest power of 10 than can be 
 28635          ** represented exactly. */
 28636          while( e%22 ) { scale *= 1.0e+1; e -= 1; }
 28637          while( e>0 ) { scale *= 1.0e+22; e -= 22; }
 28638          if( esign<0 ){
 28639            result = s / scale;
 28640          }else{
 28641            result = s * scale;
 28642          }
 28643        }
 28644      }
 28645    }
 28646  
 28647    /* store the result */
 28648    *pResult = result;
 28649  
 28650    /* return true if number and no extra non-whitespace chracters after */
 28651    return z==zEnd && nDigits>0 && eValid && nonNum==0;
 28652  #else
 28653    return !sqlite3Atoi64(z, pResult, length, enc);
 28654  #endif /* SQLITE_OMIT_FLOATING_POINT */
 28655  }
 28656  
 28657  /*
 28658  ** Compare the 19-character string zNum against the text representation
 28659  ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
 28660  ** if zNum is less than, equal to, or greater than the string.
 28661  ** Note that zNum must contain exactly 19 characters.
 28662  **
 28663  ** Unlike memcmp() this routine is guaranteed to return the difference
 28664  ** in the values of the last digit if the only difference is in the
 28665  ** last digit.  So, for example,
 28666  **
 28667  **      compare2pow63("9223372036854775800", 1)
 28668  **
 28669  ** will return -8.
 28670  */
 28671  static int compare2pow63(const char *zNum, int incr){
 28672    int c = 0;
 28673    int i;
 28674                      /* 012345678901234567 */
 28675    const char *pow63 = "922337203685477580";
 28676    for(i=0; c==0 && i<18; i++){
 28677      c = (zNum[i*incr]-pow63[i])*10;
 28678    }
 28679    if( c==0 ){
 28680      c = zNum[18*incr] - '8';
 28681      testcase( c==(-1) );
 28682      testcase( c==0 );
 28683      testcase( c==(+1) );
 28684    }
 28685    return c;
 28686  }
 28687  
 28688  /*
 28689  ** Convert zNum to a 64-bit signed integer.  zNum must be decimal. This
 28690  ** routine does *not* accept hexadecimal notation.
 28691  **
 28692  ** Returns:
 28693  **
 28694  **     0    Successful transformation.  Fits in a 64-bit signed integer.
 28695  **     1    Excess text after the integer value
 28696  **     2    Integer too large for a 64-bit signed integer or is malformed
 28697  **     3    Special case of 9223372036854775808
 28698  **
 28699  ** length is the number of bytes in the string (bytes, not characters).
 28700  ** The string is not necessarily zero-terminated.  The encoding is
 28701  ** given by enc.
 28702  */
 28703  SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
 28704    int incr;
 28705    u64 u = 0;
 28706    int neg = 0; /* assume positive */
 28707    int i;
 28708    int c = 0;
 28709    int nonNum = 0;  /* True if input contains UTF16 with high byte non-zero */
 28710    int rc;          /* Baseline return code */
 28711    const char *zStart;
 28712    const char *zEnd = zNum + length;
 28713    assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
 28714    if( enc==SQLITE_UTF8 ){
 28715      incr = 1;
 28716    }else{
 28717      incr = 2;
 28718      assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
 28719      for(i=3-enc; i<length && zNum[i]==0; i+=2){}
 28720      nonNum = i<length;
 28721      zEnd = &zNum[i^1];
 28722      zNum += (enc&1);
 28723    }
 28724    while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
 28725    if( zNum<zEnd ){
 28726      if( *zNum=='-' ){
 28727        neg = 1;
 28728        zNum+=incr;
 28729      }else if( *zNum=='+' ){
 28730        zNum+=incr;
 28731      }
 28732    }
 28733    zStart = zNum;
 28734    while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
 28735    for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
 28736      u = u*10 + c - '0';
 28737    }
 28738    if( u>LARGEST_INT64 ){
 28739      *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
 28740    }else if( neg ){
 28741      *pNum = -(i64)u;
 28742    }else{
 28743      *pNum = (i64)u;
 28744    }
 28745    testcase( i==18 );
 28746    testcase( i==19 );
 28747    testcase( i==20 );
 28748    if( &zNum[i]<zEnd              /* Extra bytes at the end */
 28749     || (i==0 && zStart==zNum)     /* No digits */
 28750     || nonNum                     /* UTF16 with high-order bytes non-zero */
 28751    ){
 28752      rc = 1;
 28753    }else{
 28754      rc = 0;
 28755    }
 28756    if( i>19*incr ){                /* Too many digits */
 28757      /* zNum is empty or contains non-numeric text or is longer
 28758      ** than 19 digits (thus guaranteeing that it is too large) */
 28759      return 2;
 28760    }else if( i<19*incr ){
 28761      /* Less than 19 digits, so we know that it fits in 64 bits */
 28762      assert( u<=LARGEST_INT64 );
 28763      return rc;
 28764    }else{
 28765      /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
 28766      c = compare2pow63(zNum, incr);
 28767      if( c<0 ){
 28768        /* zNum is less than 9223372036854775808 so it fits */
 28769        assert( u<=LARGEST_INT64 );
 28770        return rc;
 28771      }else if( c>0 ){
 28772        /* zNum is greater than 9223372036854775808 so it overflows */
 28773        return 2;
 28774      }else{
 28775        /* zNum is exactly 9223372036854775808.  Fits if negative.  The
 28776        ** special case 2 overflow if positive */
 28777        assert( u-1==LARGEST_INT64 );
 28778        return neg ? rc : 3;
 28779      }
 28780    }
 28781  }
 28782  
 28783  /*
 28784  ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
 28785  ** into a 64-bit signed integer.  This routine accepts hexadecimal literals,
 28786  ** whereas sqlite3Atoi64() does not.
 28787  **
 28788  ** Returns:
 28789  **
 28790  **     0    Successful transformation.  Fits in a 64-bit signed integer.
 28791  **     1    Excess text after the integer value
 28792  **     2    Integer too large for a 64-bit signed integer or is malformed
 28793  **     3    Special case of 9223372036854775808
 28794  */
 28795  SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
 28796  #ifndef SQLITE_OMIT_HEX_INTEGER
 28797    if( z[0]=='0'
 28798     && (z[1]=='x' || z[1]=='X')
 28799    ){
 28800      u64 u = 0;
 28801      int i, k;
 28802      for(i=2; z[i]=='0'; i++){}
 28803      for(k=i; sqlite3Isxdigit(z[k]); k++){
 28804        u = u*16 + sqlite3HexToInt(z[k]);
 28805      }
 28806      memcpy(pOut, &u, 8);
 28807      return (z[k]==0 && k-i<=16) ? 0 : 2;
 28808    }else
 28809  #endif /* SQLITE_OMIT_HEX_INTEGER */
 28810    {
 28811      return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
 28812    }
 28813  }
 28814  
 28815  /*
 28816  ** If zNum represents an integer that will fit in 32-bits, then set
 28817  ** *pValue to that integer and return true.  Otherwise return false.
 28818  **
 28819  ** This routine accepts both decimal and hexadecimal notation for integers.
 28820  **
 28821  ** Any non-numeric characters that following zNum are ignored.
 28822  ** This is different from sqlite3Atoi64() which requires the
 28823  ** input number to be zero-terminated.
 28824  */
 28825  SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
 28826    sqlite_int64 v = 0;
 28827    int i, c;
 28828    int neg = 0;
 28829    if( zNum[0]=='-' ){
 28830      neg = 1;
 28831      zNum++;
 28832    }else if( zNum[0]=='+' ){
 28833      zNum++;
 28834    }
 28835  #ifndef SQLITE_OMIT_HEX_INTEGER
 28836    else if( zNum[0]=='0'
 28837          && (zNum[1]=='x' || zNum[1]=='X')
 28838          && sqlite3Isxdigit(zNum[2])
 28839    ){
 28840      u32 u = 0;
 28841      zNum += 2;
 28842      while( zNum[0]=='0' ) zNum++;
 28843      for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
 28844        u = u*16 + sqlite3HexToInt(zNum[i]);
 28845      }
 28846      if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
 28847        memcpy(pValue, &u, 4);
 28848        return 1;
 28849      }else{
 28850        return 0;
 28851      }
 28852    }
 28853  #endif
 28854    if( !sqlite3Isdigit(zNum[0]) ) return 0;
 28855    while( zNum[0]=='0' ) zNum++;
 28856    for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
 28857      v = v*10 + c;
 28858    }
 28859  
 28860    /* The longest decimal representation of a 32 bit integer is 10 digits:
 28861    **
 28862    **             1234567890
 28863    **     2^31 -> 2147483648
 28864    */
 28865    testcase( i==10 );
 28866    if( i>10 ){
 28867      return 0;
 28868    }
 28869    testcase( v-neg==2147483647 );
 28870    if( v-neg>2147483647 ){
 28871      return 0;
 28872    }
 28873    if( neg ){
 28874      v = -v;
 28875    }
 28876    *pValue = (int)v;
 28877    return 1;
 28878  }
 28879  
 28880  /*
 28881  ** Return a 32-bit integer value extracted from a string.  If the
 28882  ** string is not an integer, just return 0.
 28883  */
 28884  SQLITE_PRIVATE int sqlite3Atoi(const char *z){
 28885    int x = 0;
 28886    if( z ) sqlite3GetInt32(z, &x);
 28887    return x;
 28888  }
 28889  
 28890  /*
 28891  ** The variable-length integer encoding is as follows:
 28892  **
 28893  ** KEY:
 28894  **         A = 0xxxxxxx    7 bits of data and one flag bit
 28895  **         B = 1xxxxxxx    7 bits of data and one flag bit
 28896  **         C = xxxxxxxx    8 bits of data
 28897  **
 28898  **  7 bits - A
 28899  ** 14 bits - BA
 28900  ** 21 bits - BBA
 28901  ** 28 bits - BBBA
 28902  ** 35 bits - BBBBA
 28903  ** 42 bits - BBBBBA
 28904  ** 49 bits - BBBBBBA
 28905  ** 56 bits - BBBBBBBA
 28906  ** 64 bits - BBBBBBBBC
 28907  */
 28908  
 28909  /*
 28910  ** Write a 64-bit variable-length integer to memory starting at p[0].
 28911  ** The length of data write will be between 1 and 9 bytes.  The number
 28912  ** of bytes written is returned.
 28913  **
 28914  ** A variable-length integer consists of the lower 7 bits of each byte
 28915  ** for all bytes that have the 8th bit set and one byte with the 8th
 28916  ** bit clear.  Except, if we get to the 9th byte, it stores the full
 28917  ** 8 bits and is the last byte.
 28918  */
 28919  static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
 28920    int i, j, n;
 28921    u8 buf[10];
 28922    if( v & (((u64)0xff000000)<<32) ){
 28923      p[8] = (u8)v;
 28924      v >>= 8;
 28925      for(i=7; i>=0; i--){
 28926        p[i] = (u8)((v & 0x7f) | 0x80);
 28927        v >>= 7;
 28928      }
 28929      return 9;
 28930    }    
 28931    n = 0;
 28932    do{
 28933      buf[n++] = (u8)((v & 0x7f) | 0x80);
 28934      v >>= 7;
 28935    }while( v!=0 );
 28936    buf[0] &= 0x7f;
 28937    assert( n<=9 );
 28938    for(i=0, j=n-1; j>=0; j--, i++){
 28939      p[i] = buf[j];
 28940    }
 28941    return n;
 28942  }
 28943  SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
 28944    if( v<=0x7f ){
 28945      p[0] = v&0x7f;
 28946      return 1;
 28947    }
 28948    if( v<=0x3fff ){
 28949      p[0] = ((v>>7)&0x7f)|0x80;
 28950      p[1] = v&0x7f;
 28951      return 2;
 28952    }
 28953    return putVarint64(p,v);
 28954  }
 28955  
 28956  /*
 28957  ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
 28958  ** are defined here rather than simply putting the constant expressions
 28959  ** inline in order to work around bugs in the RVT compiler.
 28960  **
 28961  ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
 28962  **
 28963  ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
 28964  */
 28965  #define SLOT_2_0     0x001fc07f
 28966  #define SLOT_4_2_0   0xf01fc07f
 28967  
 28968  
 28969  /*
 28970  ** Read a 64-bit variable-length integer from memory starting at p[0].
 28971  ** Return the number of bytes read.  The value is stored in *v.
 28972  */
 28973  SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
 28974    u32 a,b,s;
 28975  
 28976    a = *p;
 28977    /* a: p0 (unmasked) */
 28978    if (!(a&0x80))
 28979    {
 28980      *v = a;
 28981      return 1;
 28982    }
 28983  
 28984    p++;
 28985    b = *p;
 28986    /* b: p1 (unmasked) */
 28987    if (!(b&0x80))
 28988    {
 28989      a &= 0x7f;
 28990      a = a<<7;
 28991      a |= b;
 28992      *v = a;
 28993      return 2;
 28994    }
 28995  
 28996    /* Verify that constants are precomputed correctly */
 28997    assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
 28998    assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
 28999  
 29000    p++;
 29001    a = a<<14;
 29002    a |= *p;
 29003    /* a: p0<<14 | p2 (unmasked) */
 29004    if (!(a&0x80))
 29005    {
 29006      a &= SLOT_2_0;
 29007      b &= 0x7f;
 29008      b = b<<7;
 29009      a |= b;
 29010      *v = a;
 29011      return 3;
 29012    }
 29013  
 29014    /* CSE1 from below */
 29015    a &= SLOT_2_0;
 29016    p++;
 29017    b = b<<14;
 29018    b |= *p;
 29019    /* b: p1<<14 | p3 (unmasked) */
 29020    if (!(b&0x80))
 29021    {
 29022      b &= SLOT_2_0;
 29023      /* moved CSE1 up */
 29024      /* a &= (0x7f<<14)|(0x7f); */
 29025      a = a<<7;
 29026      a |= b;
 29027      *v = a;
 29028      return 4;
 29029    }
 29030  
 29031    /* a: p0<<14 | p2 (masked) */
 29032    /* b: p1<<14 | p3 (unmasked) */
 29033    /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
 29034    /* moved CSE1 up */
 29035    /* a &= (0x7f<<14)|(0x7f); */
 29036    b &= SLOT_2_0;
 29037    s = a;
 29038    /* s: p0<<14 | p2 (masked) */
 29039  
 29040    p++;
 29041    a = a<<14;
 29042    a |= *p;
 29043    /* a: p0<<28 | p2<<14 | p4 (unmasked) */
 29044    if (!(a&0x80))
 29045    {
 29046      /* we can skip these cause they were (effectively) done above
 29047      ** while calculating s */
 29048      /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
 29049      /* b &= (0x7f<<14)|(0x7f); */
 29050      b = b<<7;
 29051      a |= b;
 29052      s = s>>18;
 29053      *v = ((u64)s)<<32 | a;
 29054      return 5;
 29055    }
 29056  
 29057    /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
 29058    s = s<<7;
 29059    s |= b;
 29060    /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
 29061  
 29062    p++;
 29063    b = b<<14;
 29064    b |= *p;
 29065    /* b: p1<<28 | p3<<14 | p5 (unmasked) */
 29066    if (!(b&0x80))
 29067    {
 29068      /* we can skip this cause it was (effectively) done above in calc'ing s */
 29069      /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
 29070      a &= SLOT_2_0;
 29071      a = a<<7;
 29072      a |= b;
 29073      s = s>>18;
 29074      *v = ((u64)s)<<32 | a;
 29075      return 6;
 29076    }
 29077  
 29078    p++;
 29079    a = a<<14;
 29080    a |= *p;
 29081    /* a: p2<<28 | p4<<14 | p6 (unmasked) */
 29082    if (!(a&0x80))
 29083    {
 29084      a &= SLOT_4_2_0;
 29085      b &= SLOT_2_0;
 29086      b = b<<7;
 29087      a |= b;
 29088      s = s>>11;
 29089      *v = ((u64)s)<<32 | a;
 29090      return 7;
 29091    }
 29092  
 29093    /* CSE2 from below */
 29094    a &= SLOT_2_0;
 29095    p++;
 29096    b = b<<14;
 29097    b |= *p;
 29098    /* b: p3<<28 | p5<<14 | p7 (unmasked) */
 29099    if (!(b&0x80))
 29100    {
 29101      b &= SLOT_4_2_0;
 29102      /* moved CSE2 up */
 29103      /* a &= (0x7f<<14)|(0x7f); */
 29104      a = a<<7;
 29105      a |= b;
 29106      s = s>>4;
 29107      *v = ((u64)s)<<32 | a;
 29108      return 8;
 29109    }
 29110  
 29111    p++;
 29112    a = a<<15;
 29113    a |= *p;
 29114    /* a: p4<<29 | p6<<15 | p8 (unmasked) */
 29115  
 29116    /* moved CSE2 up */
 29117    /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
 29118    b &= SLOT_2_0;
 29119    b = b<<8;
 29120    a |= b;
 29121  
 29122    s = s<<4;
 29123    b = p[-4];
 29124    b &= 0x7f;
 29125    b = b>>3;
 29126    s |= b;
 29127  
 29128    *v = ((u64)s)<<32 | a;
 29129  
 29130    return 9;
 29131  }
 29132  
 29133  /*
 29134  ** Read a 32-bit variable-length integer from memory starting at p[0].
 29135  ** Return the number of bytes read.  The value is stored in *v.
 29136  **
 29137  ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
 29138  ** integer, then set *v to 0xffffffff.
 29139  **
 29140  ** A MACRO version, getVarint32, is provided which inlines the 
 29141  ** single-byte case.  All code should use the MACRO version as 
 29142  ** this function assumes the single-byte case has already been handled.
 29143  */
 29144  SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
 29145    u32 a,b;
 29146  
 29147    /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
 29148    ** by the getVarin32() macro */
 29149    a = *p;
 29150    /* a: p0 (unmasked) */
 29151  #ifndef getVarint32
 29152    if (!(a&0x80))
 29153    {
 29154      /* Values between 0 and 127 */
 29155      *v = a;
 29156      return 1;
 29157    }
 29158  #endif
 29159  
 29160    /* The 2-byte case */
 29161    p++;
 29162    b = *p;
 29163    /* b: p1 (unmasked) */
 29164    if (!(b&0x80))
 29165    {
 29166      /* Values between 128 and 16383 */
 29167      a &= 0x7f;
 29168      a = a<<7;
 29169      *v = a | b;
 29170      return 2;
 29171    }
 29172  
 29173    /* The 3-byte case */
 29174    p++;
 29175    a = a<<14;
 29176    a |= *p;
 29177    /* a: p0<<14 | p2 (unmasked) */
 29178    if (!(a&0x80))
 29179    {
 29180      /* Values between 16384 and 2097151 */
 29181      a &= (0x7f<<14)|(0x7f);
 29182      b &= 0x7f;
 29183      b = b<<7;
 29184      *v = a | b;
 29185      return 3;
 29186    }
 29187  
 29188    /* A 32-bit varint is used to store size information in btrees.
 29189    ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
 29190    ** A 3-byte varint is sufficient, for example, to record the size
 29191    ** of a 1048569-byte BLOB or string.
 29192    **
 29193    ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
 29194    ** rare larger cases can be handled by the slower 64-bit varint
 29195    ** routine.
 29196    */
 29197  #if 1
 29198    {
 29199      u64 v64;
 29200      u8 n;
 29201  
 29202      p -= 2;
 29203      n = sqlite3GetVarint(p, &v64);
 29204      assert( n>3 && n<=9 );
 29205      if( (v64 & SQLITE_MAX_U32)!=v64 ){
 29206        *v = 0xffffffff;
 29207      }else{
 29208        *v = (u32)v64;
 29209      }
 29210      return n;
 29211    }
 29212  
 29213  #else
 29214    /* For following code (kept for historical record only) shows an
 29215    ** unrolling for the 3- and 4-byte varint cases.  This code is
 29216    ** slightly faster, but it is also larger and much harder to test.
 29217    */
 29218    p++;
 29219    b = b<<14;
 29220    b |= *p;
 29221    /* b: p1<<14 | p3 (unmasked) */
 29222    if (!(b&0x80))
 29223    {
 29224      /* Values between 2097152 and 268435455 */
 29225      b &= (0x7f<<14)|(0x7f);
 29226      a &= (0x7f<<14)|(0x7f);
 29227      a = a<<7;
 29228      *v = a | b;
 29229      return 4;
 29230    }
 29231  
 29232    p++;
 29233    a = a<<14;
 29234    a |= *p;
 29235    /* a: p0<<28 | p2<<14 | p4 (unmasked) */
 29236    if (!(a&0x80))
 29237    {
 29238      /* Values  between 268435456 and 34359738367 */
 29239      a &= SLOT_4_2_0;
 29240      b &= SLOT_4_2_0;
 29241      b = b<<7;
 29242      *v = a | b;
 29243      return 5;
 29244    }
 29245  
 29246    /* We can only reach this point when reading a corrupt database
 29247    ** file.  In that case we are not in any hurry.  Use the (relatively
 29248    ** slow) general-purpose sqlite3GetVarint() routine to extract the
 29249    ** value. */
 29250    {
 29251      u64 v64;
 29252      u8 n;
 29253  
 29254      p -= 4;
 29255      n = sqlite3GetVarint(p, &v64);
 29256      assert( n>5 && n<=9 );
 29257      *v = (u32)v64;
 29258      return n;
 29259    }
 29260  #endif
 29261  }
 29262  
 29263  /*
 29264  ** Return the number of bytes that will be needed to store the given
 29265  ** 64-bit integer.
 29266  */
 29267  SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
 29268    int i;
 29269    for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
 29270    return i;
 29271  }
 29272  
 29273  
 29274  /*
 29275  ** Read or write a four-byte big-endian integer value.
 29276  */
 29277  SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
 29278  #if SQLITE_BYTEORDER==4321
 29279    u32 x;
 29280    memcpy(&x,p,4);
 29281    return x;
 29282  #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
 29283    u32 x;
 29284    memcpy(&x,p,4);
 29285    return __builtin_bswap32(x);
 29286  #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
 29287    u32 x;
 29288    memcpy(&x,p,4);
 29289    return _byteswap_ulong(x);
 29290  #else
 29291    testcase( p[0]&0x80 );
 29292    return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
 29293  #endif
 29294  }
 29295  SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
 29296  #if SQLITE_BYTEORDER==4321
 29297    memcpy(p,&v,4);
 29298  #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
 29299    u32 x = __builtin_bswap32(v);
 29300    memcpy(p,&x,4);
 29301  #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
 29302    u32 x = _byteswap_ulong(v);
 29303    memcpy(p,&x,4);
 29304  #else
 29305    p[0] = (u8)(v>>24);
 29306    p[1] = (u8)(v>>16);
 29307    p[2] = (u8)(v>>8);
 29308    p[3] = (u8)v;
 29309  #endif
 29310  }
 29311  
 29312  
 29313  
 29314  /*
 29315  ** Translate a single byte of Hex into an integer.
 29316  ** This routine only works if h really is a valid hexadecimal
 29317  ** character:  0..9a..fA..F
 29318  */
 29319  SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
 29320    assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
 29321  #ifdef SQLITE_ASCII
 29322    h += 9*(1&(h>>6));
 29323  #endif
 29324  #ifdef SQLITE_EBCDIC
 29325    h += 9*(1&~(h>>4));
 29326  #endif
 29327    return (u8)(h & 0xf);
 29328  }
 29329  
 29330  #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
 29331  /*
 29332  ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
 29333  ** value.  Return a pointer to its binary value.  Space to hold the
 29334  ** binary value has been obtained from malloc and must be freed by
 29335  ** the calling routine.
 29336  */
 29337  SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
 29338    char *zBlob;
 29339    int i;
 29340  
 29341    zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
 29342    n--;
 29343    if( zBlob ){
 29344      for(i=0; i<n; i+=2){
 29345        zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
 29346      }
 29347      zBlob[i/2] = 0;
 29348    }
 29349    return zBlob;
 29350  }
 29351  #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
 29352  
 29353  /*
 29354  ** Log an error that is an API call on a connection pointer that should
 29355  ** not have been used.  The "type" of connection pointer is given as the
 29356  ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
 29357  */
 29358  static void logBadConnection(const char *zType){
 29359    sqlite3_log(SQLITE_MISUSE, 
 29360       "API call with %s database connection pointer",
 29361       zType
 29362    );
 29363  }
 29364  
 29365  /*
 29366  ** Check to make sure we have a valid db pointer.  This test is not
 29367  ** foolproof but it does provide some measure of protection against
 29368  ** misuse of the interface such as passing in db pointers that are
 29369  ** NULL or which have been previously closed.  If this routine returns
 29370  ** 1 it means that the db pointer is valid and 0 if it should not be
 29371  ** dereferenced for any reason.  The calling function should invoke
 29372  ** SQLITE_MISUSE immediately.
 29373  **
 29374  ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
 29375  ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
 29376  ** open properly and is not fit for general use but which can be
 29377  ** used as an argument to sqlite3_errmsg() or sqlite3_close().
 29378  */
 29379  SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
 29380    u32 magic;
 29381    if( db==0 ){
 29382      logBadConnection("NULL");
 29383      return 0;
 29384    }
 29385    magic = db->magic;
 29386    if( magic!=SQLITE_MAGIC_OPEN ){
 29387      if( sqlite3SafetyCheckSickOrOk(db) ){
 29388        testcase( sqlite3GlobalConfig.xLog!=0 );
 29389        logBadConnection("unopened");
 29390      }
 29391      return 0;
 29392    }else{
 29393      return 1;
 29394    }
 29395  }
 29396  SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
 29397    u32 magic;
 29398    magic = db->magic;
 29399    if( magic!=SQLITE_MAGIC_SICK &&
 29400        magic!=SQLITE_MAGIC_OPEN &&
 29401        magic!=SQLITE_MAGIC_BUSY ){
 29402      testcase( sqlite3GlobalConfig.xLog!=0 );
 29403      logBadConnection("invalid");
 29404      return 0;
 29405    }else{
 29406      return 1;
 29407    }
 29408  }
 29409  
 29410  /*
 29411  ** Attempt to add, substract, or multiply the 64-bit signed value iB against
 29412  ** the other 64-bit signed integer at *pA and store the result in *pA.
 29413  ** Return 0 on success.  Or if the operation would have resulted in an
 29414  ** overflow, leave *pA unchanged and return 1.
 29415  */
 29416  SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
 29417  #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
 29418    return __builtin_add_overflow(*pA, iB, pA);
 29419  #else
 29420    i64 iA = *pA;
 29421    testcase( iA==0 ); testcase( iA==1 );
 29422    testcase( iB==-1 ); testcase( iB==0 );
 29423    if( iB>=0 ){
 29424      testcase( iA>0 && LARGEST_INT64 - iA == iB );
 29425      testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
 29426      if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
 29427    }else{
 29428      testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
 29429      testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
 29430      if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
 29431    }
 29432    *pA += iB;
 29433    return 0; 
 29434  #endif
 29435  }
 29436  SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
 29437  #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
 29438    return __builtin_sub_overflow(*pA, iB, pA);
 29439  #else
 29440    testcase( iB==SMALLEST_INT64+1 );
 29441    if( iB==SMALLEST_INT64 ){
 29442      testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
 29443      if( (*pA)>=0 ) return 1;
 29444      *pA -= iB;
 29445      return 0;
 29446    }else{
 29447      return sqlite3AddInt64(pA, -iB);
 29448    }
 29449  #endif
 29450  }
 29451  SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
 29452  #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
 29453    return __builtin_mul_overflow(*pA, iB, pA);
 29454  #else
 29455    i64 iA = *pA;
 29456    if( iB>0 ){
 29457      if( iA>LARGEST_INT64/iB ) return 1;
 29458      if( iA<SMALLEST_INT64/iB ) return 1;
 29459    }else if( iB<0 ){
 29460      if( iA>0 ){
 29461        if( iB<SMALLEST_INT64/iA ) return 1;
 29462      }else if( iA<0 ){
 29463        if( iB==SMALLEST_INT64 ) return 1;
 29464        if( iA==SMALLEST_INT64 ) return 1;
 29465        if( -iA>LARGEST_INT64/-iB ) return 1;
 29466      }
 29467    }
 29468    *pA = iA*iB;
 29469    return 0;
 29470  #endif
 29471  }
 29472  
 29473  /*
 29474  ** Compute the absolute value of a 32-bit signed integer, of possible.  Or 
 29475  ** if the integer has a value of -2147483648, return +2147483647
 29476  */
 29477  SQLITE_PRIVATE int sqlite3AbsInt32(int x){
 29478    if( x>=0 ) return x;
 29479    if( x==(int)0x80000000 ) return 0x7fffffff;
 29480    return -x;
 29481  }
 29482  
 29483  #ifdef SQLITE_ENABLE_8_3_NAMES
 29484  /*
 29485  ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
 29486  ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
 29487  ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
 29488  ** three characters, then shorten the suffix on z[] to be the last three
 29489  ** characters of the original suffix.
 29490  **
 29491  ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
 29492  ** do the suffix shortening regardless of URI parameter.
 29493  **
 29494  ** Examples:
 29495  **
 29496  **     test.db-journal    =>   test.nal
 29497  **     test.db-wal        =>   test.wal
 29498  **     test.db-shm        =>   test.shm
 29499  **     test.db-mj7f3319fa =>   test.9fa
 29500  */
 29501  SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
 29502  #if SQLITE_ENABLE_8_3_NAMES<2
 29503    if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
 29504  #endif
 29505    {
 29506      int i, sz;
 29507      sz = sqlite3Strlen30(z);
 29508      for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
 29509      if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
 29510    }
 29511  }
 29512  #endif
 29513  
 29514  /* 
 29515  ** Find (an approximate) sum of two LogEst values.  This computation is
 29516  ** not a simple "+" operator because LogEst is stored as a logarithmic
 29517  ** value.
 29518  ** 
 29519  */
 29520  SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
 29521    static const unsigned char x[] = {
 29522       10, 10,                         /* 0,1 */
 29523        9, 9,                          /* 2,3 */
 29524        8, 8,                          /* 4,5 */
 29525        7, 7, 7,                       /* 6,7,8 */
 29526        6, 6, 6,                       /* 9,10,11 */
 29527        5, 5, 5,                       /* 12-14 */
 29528        4, 4, 4, 4,                    /* 15-18 */
 29529        3, 3, 3, 3, 3, 3,              /* 19-24 */
 29530        2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
 29531    };
 29532    if( a>=b ){
 29533      if( a>b+49 ) return a;
 29534      if( a>b+31 ) return a+1;
 29535      return a+x[a-b];
 29536    }else{
 29537      if( b>a+49 ) return b;
 29538      if( b>a+31 ) return b+1;
 29539      return b+x[b-a];
 29540    }
 29541  }
 29542  
 29543  /*
 29544  ** Convert an integer into a LogEst.  In other words, compute an
 29545  ** approximation for 10*log2(x).
 29546  */
 29547  SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
 29548    static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
 29549    LogEst y = 40;
 29550    if( x<8 ){
 29551      if( x<2 ) return 0;
 29552      while( x<8 ){  y -= 10; x <<= 1; }
 29553    }else{
 29554  #if GCC_VERSION>=5004000
 29555      int i = 60 - __builtin_clzll(x);
 29556      y += i*10;
 29557      x >>= i;
 29558  #else
 29559      while( x>255 ){ y += 40; x >>= 4; }  /*OPTIMIZATION-IF-TRUE*/
 29560      while( x>15 ){  y += 10; x >>= 1; }
 29561  #endif
 29562    }
 29563    return a[x&7] + y - 10;
 29564  }
 29565  
 29566  #ifndef SQLITE_OMIT_VIRTUALTABLE
 29567  /*
 29568  ** Convert a double into a LogEst
 29569  ** In other words, compute an approximation for 10*log2(x).
 29570  */
 29571  SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
 29572    u64 a;
 29573    LogEst e;
 29574    assert( sizeof(x)==8 && sizeof(a)==8 );
 29575    if( x<=1 ) return 0;
 29576    if( x<=2000000000 ) return sqlite3LogEst((u64)x);
 29577    memcpy(&a, &x, 8);
 29578    e = (a>>52) - 1022;
 29579    return e*10;
 29580  }
 29581  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 29582  
 29583  #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
 29584      defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
 29585      defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
 29586  /*
 29587  ** Convert a LogEst into an integer.
 29588  **
 29589  ** Note that this routine is only used when one or more of various
 29590  ** non-standard compile-time options is enabled.
 29591  */
 29592  SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
 29593    u64 n;
 29594    n = x%10;
 29595    x /= 10;
 29596    if( n>=5 ) n -= 2;
 29597    else if( n>=1 ) n -= 1;
 29598  #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
 29599      defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
 29600    if( x>60 ) return (u64)LARGEST_INT64;
 29601  #else
 29602    /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
 29603    ** possible to this routine is 310, resulting in a maximum x of 31 */
 29604    assert( x<=60 );
 29605  #endif
 29606    return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
 29607  }
 29608  #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
 29609  
 29610  /*
 29611  ** Add a new name/number pair to a VList.  This might require that the
 29612  ** VList object be reallocated, so return the new VList.  If an OOM
 29613  ** error occurs, the original VList returned and the
 29614  ** db->mallocFailed flag is set.
 29615  **
 29616  ** A VList is really just an array of integers.  To destroy a VList,
 29617  ** simply pass it to sqlite3DbFree().
 29618  **
 29619  ** The first integer is the number of integers allocated for the whole
 29620  ** VList.  The second integer is the number of integers actually used.
 29621  ** Each name/number pair is encoded by subsequent groups of 3 or more
 29622  ** integers.
 29623  **
 29624  ** Each name/number pair starts with two integers which are the numeric
 29625  ** value for the pair and the size of the name/number pair, respectively.
 29626  ** The text name overlays one or more following integers.  The text name
 29627  ** is always zero-terminated.
 29628  **
 29629  ** Conceptually:
 29630  **
 29631  **    struct VList {
 29632  **      int nAlloc;   // Number of allocated slots 
 29633  **      int nUsed;    // Number of used slots 
 29634  **      struct VListEntry {
 29635  **        int iValue;    // Value for this entry
 29636  **        int nSlot;     // Slots used by this entry
 29637  **        // ... variable name goes here
 29638  **      } a[0];
 29639  **    }
 29640  **
 29641  ** During code generation, pointers to the variable names within the
 29642  ** VList are taken.  When that happens, nAlloc is set to zero as an 
 29643  ** indication that the VList may never again be enlarged, since the
 29644  ** accompanying realloc() would invalidate the pointers.
 29645  */
 29646  SQLITE_PRIVATE VList *sqlite3VListAdd(
 29647    sqlite3 *db,           /* The database connection used for malloc() */
 29648    VList *pIn,            /* The input VList.  Might be NULL */
 29649    const char *zName,     /* Name of symbol to add */
 29650    int nName,             /* Bytes of text in zName */
 29651    int iVal               /* Value to associate with zName */
 29652  ){
 29653    int nInt;              /* number of sizeof(int) objects needed for zName */
 29654    char *z;               /* Pointer to where zName will be stored */
 29655    int i;                 /* Index in pIn[] where zName is stored */
 29656  
 29657    nInt = nName/4 + 3;
 29658    assert( pIn==0 || pIn[0]>=3 );  /* Verify ok to add new elements */
 29659    if( pIn==0 || pIn[1]+nInt > pIn[0] ){
 29660      /* Enlarge the allocation */
 29661      int nAlloc = (pIn ? pIn[0]*2 : 10) + nInt;
 29662      VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
 29663      if( pOut==0 ) return pIn;
 29664      if( pIn==0 ) pOut[1] = 2;
 29665      pIn = pOut;
 29666      pIn[0] = nAlloc;
 29667    }
 29668    i = pIn[1];
 29669    pIn[i] = iVal;
 29670    pIn[i+1] = nInt;
 29671    z = (char*)&pIn[i+2];
 29672    pIn[1] = i+nInt;
 29673    assert( pIn[1]<=pIn[0] );
 29674    memcpy(z, zName, nName);
 29675    z[nName] = 0;
 29676    return pIn;
 29677  }
 29678  
 29679  /*
 29680  ** Return a pointer to the name of a variable in the given VList that
 29681  ** has the value iVal.  Or return a NULL if there is no such variable in
 29682  ** the list
 29683  */
 29684  SQLITE_PRIVATE const char *sqlite3VListNumToName(VList *pIn, int iVal){
 29685    int i, mx;
 29686    if( pIn==0 ) return 0;
 29687    mx = pIn[1];
 29688    i = 2;
 29689    do{
 29690      if( pIn[i]==iVal ) return (char*)&pIn[i+2];
 29691      i += pIn[i+1];
 29692    }while( i<mx );
 29693    return 0;
 29694  }
 29695  
 29696  /*
 29697  ** Return the number of the variable named zName, if it is in VList.
 29698  ** or return 0 if there is no such variable.
 29699  */
 29700  SQLITE_PRIVATE int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
 29701    int i, mx;
 29702    if( pIn==0 ) return 0;
 29703    mx = pIn[1];
 29704    i = 2;
 29705    do{
 29706      const char *z = (const char*)&pIn[i+2];
 29707      if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
 29708      i += pIn[i+1];
 29709    }while( i<mx );
 29710    return 0;
 29711  }
 29712  
 29713  /************** End of util.c ************************************************/
 29714  /************** Begin file hash.c ********************************************/
 29715  /*
 29716  ** 2001 September 22
 29717  **
 29718  ** The author disclaims copyright to this source code.  In place of
 29719  ** a legal notice, here is a blessing:
 29720  **
 29721  **    May you do good and not evil.
 29722  **    May you find forgiveness for yourself and forgive others.
 29723  **    May you share freely, never taking more than you give.
 29724  **
 29725  *************************************************************************
 29726  ** This is the implementation of generic hash-tables
 29727  ** used in SQLite.
 29728  */
 29729  /* #include "sqliteInt.h" */
 29730  /* #include <assert.h> */
 29731  
 29732  /* Turn bulk memory into a hash table object by initializing the
 29733  ** fields of the Hash structure.
 29734  **
 29735  ** "pNew" is a pointer to the hash table that is to be initialized.
 29736  */
 29737  SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
 29738    assert( pNew!=0 );
 29739    pNew->first = 0;
 29740    pNew->count = 0;
 29741    pNew->htsize = 0;
 29742    pNew->ht = 0;
 29743  }
 29744  
 29745  /* Remove all entries from a hash table.  Reclaim all memory.
 29746  ** Call this routine to delete a hash table or to reset a hash table
 29747  ** to the empty state.
 29748  */
 29749  SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
 29750    HashElem *elem;         /* For looping over all elements of the table */
 29751  
 29752    assert( pH!=0 );
 29753    elem = pH->first;
 29754    pH->first = 0;
 29755    sqlite3_free(pH->ht);
 29756    pH->ht = 0;
 29757    pH->htsize = 0;
 29758    while( elem ){
 29759      HashElem *next_elem = elem->next;
 29760      sqlite3_free(elem);
 29761      elem = next_elem;
 29762    }
 29763    pH->count = 0;
 29764  }
 29765  
 29766  /*
 29767  ** The hashing function.
 29768  */
 29769  static unsigned int strHash(const char *z){
 29770    unsigned int h = 0;
 29771    unsigned char c;
 29772    while( (c = (unsigned char)*z++)!=0 ){     /*OPTIMIZATION-IF-TRUE*/
 29773      /* Knuth multiplicative hashing.  (Sorting & Searching, p. 510).
 29774      ** 0x9e3779b1 is 2654435761 which is the closest prime number to
 29775      ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
 29776      h += sqlite3UpperToLower[c];
 29777      h *= 0x9e3779b1;
 29778    }
 29779    return h;
 29780  }
 29781  
 29782  
 29783  /* Link pNew element into the hash table pH.  If pEntry!=0 then also
 29784  ** insert pNew into the pEntry hash bucket.
 29785  */
 29786  static void insertElement(
 29787    Hash *pH,              /* The complete hash table */
 29788    struct _ht *pEntry,    /* The entry into which pNew is inserted */
 29789    HashElem *pNew         /* The element to be inserted */
 29790  ){
 29791    HashElem *pHead;       /* First element already in pEntry */
 29792    if( pEntry ){
 29793      pHead = pEntry->count ? pEntry->chain : 0;
 29794      pEntry->count++;
 29795      pEntry->chain = pNew;
 29796    }else{
 29797      pHead = 0;
 29798    }
 29799    if( pHead ){
 29800      pNew->next = pHead;
 29801      pNew->prev = pHead->prev;
 29802      if( pHead->prev ){ pHead->prev->next = pNew; }
 29803      else             { pH->first = pNew; }
 29804      pHead->prev = pNew;
 29805    }else{
 29806      pNew->next = pH->first;
 29807      if( pH->first ){ pH->first->prev = pNew; }
 29808      pNew->prev = 0;
 29809      pH->first = pNew;
 29810    }
 29811  }
 29812  
 29813  
 29814  /* Resize the hash table so that it cantains "new_size" buckets.
 29815  **
 29816  ** The hash table might fail to resize if sqlite3_malloc() fails or
 29817  ** if the new size is the same as the prior size.
 29818  ** Return TRUE if the resize occurs and false if not.
 29819  */
 29820  static int rehash(Hash *pH, unsigned int new_size){
 29821    struct _ht *new_ht;            /* The new hash table */
 29822    HashElem *elem, *next_elem;    /* For looping over existing elements */
 29823  
 29824  #if SQLITE_MALLOC_SOFT_LIMIT>0
 29825    if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
 29826      new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
 29827    }
 29828    if( new_size==pH->htsize ) return 0;
 29829  #endif
 29830  
 29831    /* The inability to allocates space for a larger hash table is
 29832    ** a performance hit but it is not a fatal error.  So mark the
 29833    ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of 
 29834    ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
 29835    ** only zeroes the requested number of bytes whereas this module will
 29836    ** use the actual amount of space allocated for the hash table (which
 29837    ** may be larger than the requested amount).
 29838    */
 29839    sqlite3BeginBenignMalloc();
 29840    new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
 29841    sqlite3EndBenignMalloc();
 29842  
 29843    if( new_ht==0 ) return 0;
 29844    sqlite3_free(pH->ht);
 29845    pH->ht = new_ht;
 29846    pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
 29847    memset(new_ht, 0, new_size*sizeof(struct _ht));
 29848    for(elem=pH->first, pH->first=0; elem; elem = next_elem){
 29849      unsigned int h = strHash(elem->pKey) % new_size;
 29850      next_elem = elem->next;
 29851      insertElement(pH, &new_ht[h], elem);
 29852    }
 29853    return 1;
 29854  }
 29855  
 29856  /* This function (for internal use only) locates an element in an
 29857  ** hash table that matches the given key.  If no element is found,
 29858  ** a pointer to a static null element with HashElem.data==0 is returned.
 29859  ** If pH is not NULL, then the hash for this key is written to *pH.
 29860  */
 29861  static HashElem *findElementWithHash(
 29862    const Hash *pH,     /* The pH to be searched */
 29863    const char *pKey,   /* The key we are searching for */
 29864    unsigned int *pHash /* Write the hash value here */
 29865  ){
 29866    HashElem *elem;                /* Used to loop thru the element list */
 29867    int count;                     /* Number of elements left to test */
 29868    unsigned int h;                /* The computed hash */
 29869    static HashElem nullElement = { 0, 0, 0, 0 };
 29870  
 29871    if( pH->ht ){   /*OPTIMIZATION-IF-TRUE*/
 29872      struct _ht *pEntry;
 29873      h = strHash(pKey) % pH->htsize;
 29874      pEntry = &pH->ht[h];
 29875      elem = pEntry->chain;
 29876      count = pEntry->count;
 29877    }else{
 29878      h = 0;
 29879      elem = pH->first;
 29880      count = pH->count;
 29881    }
 29882    if( pHash ) *pHash = h;
 29883    while( count-- ){
 29884      assert( elem!=0 );
 29885      if( sqlite3StrICmp(elem->pKey,pKey)==0 ){ 
 29886        return elem;
 29887      }
 29888      elem = elem->next;
 29889    }
 29890    return &nullElement;
 29891  }
 29892  
 29893  /* Remove a single entry from the hash table given a pointer to that
 29894  ** element and a hash on the element's key.
 29895  */
 29896  static void removeElementGivenHash(
 29897    Hash *pH,         /* The pH containing "elem" */
 29898    HashElem* elem,   /* The element to be removed from the pH */
 29899    unsigned int h    /* Hash value for the element */
 29900  ){
 29901    struct _ht *pEntry;
 29902    if( elem->prev ){
 29903      elem->prev->next = elem->next; 
 29904    }else{
 29905      pH->first = elem->next;
 29906    }
 29907    if( elem->next ){
 29908      elem->next->prev = elem->prev;
 29909    }
 29910    if( pH->ht ){
 29911      pEntry = &pH->ht[h];
 29912      if( pEntry->chain==elem ){
 29913        pEntry->chain = elem->next;
 29914      }
 29915      pEntry->count--;
 29916      assert( pEntry->count>=0 );
 29917    }
 29918    sqlite3_free( elem );
 29919    pH->count--;
 29920    if( pH->count==0 ){
 29921      assert( pH->first==0 );
 29922      assert( pH->count==0 );
 29923      sqlite3HashClear(pH);
 29924    }
 29925  }
 29926  
 29927  /* Attempt to locate an element of the hash table pH with a key
 29928  ** that matches pKey.  Return the data for this element if it is
 29929  ** found, or NULL if there is no match.
 29930  */
 29931  SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
 29932    assert( pH!=0 );
 29933    assert( pKey!=0 );
 29934    return findElementWithHash(pH, pKey, 0)->data;
 29935  }
 29936  
 29937  /* Insert an element into the hash table pH.  The key is pKey
 29938  ** and the data is "data".
 29939  **
 29940  ** If no element exists with a matching key, then a new
 29941  ** element is created and NULL is returned.
 29942  **
 29943  ** If another element already exists with the same key, then the
 29944  ** new data replaces the old data and the old data is returned.
 29945  ** The key is not copied in this instance.  If a malloc fails, then
 29946  ** the new data is returned and the hash table is unchanged.
 29947  **
 29948  ** If the "data" parameter to this function is NULL, then the
 29949  ** element corresponding to "key" is removed from the hash table.
 29950  */
 29951  SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
 29952    unsigned int h;       /* the hash of the key modulo hash table size */
 29953    HashElem *elem;       /* Used to loop thru the element list */
 29954    HashElem *new_elem;   /* New element added to the pH */
 29955  
 29956    assert( pH!=0 );
 29957    assert( pKey!=0 );
 29958    elem = findElementWithHash(pH,pKey,&h);
 29959    if( elem->data ){
 29960      void *old_data = elem->data;
 29961      if( data==0 ){
 29962        removeElementGivenHash(pH,elem,h);
 29963      }else{
 29964        elem->data = data;
 29965        elem->pKey = pKey;
 29966      }
 29967      return old_data;
 29968    }
 29969    if( data==0 ) return 0;
 29970    new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
 29971    if( new_elem==0 ) return data;
 29972    new_elem->pKey = pKey;
 29973    new_elem->data = data;
 29974    pH->count++;
 29975    if( pH->count>=10 && pH->count > 2*pH->htsize ){
 29976      if( rehash(pH, pH->count*2) ){
 29977        assert( pH->htsize>0 );
 29978        h = strHash(pKey) % pH->htsize;
 29979      }
 29980    }
 29981    insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
 29982    return 0;
 29983  }
 29984  
 29985  /************** End of hash.c ************************************************/
 29986  /************** Begin file opcodes.c *****************************************/
 29987  /* Automatically generated.  Do not edit */
 29988  /* See the tool/mkopcodec.tcl script for details. */
 29989  #if !defined(SQLITE_OMIT_EXPLAIN) \
 29990   || defined(VDBE_PROFILE) \
 29991   || defined(SQLITE_DEBUG)
 29992  #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
 29993  # define OpHelp(X) "\0" X
 29994  #else
 29995  # define OpHelp(X)
 29996  #endif
 29997  SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
 29998   static const char *const azName[] = {
 29999      /*   0 */ "Savepoint"        OpHelp(""),
 30000      /*   1 */ "AutoCommit"       OpHelp(""),
 30001      /*   2 */ "Transaction"      OpHelp(""),
 30002      /*   3 */ "SorterNext"       OpHelp(""),
 30003      /*   4 */ "PrevIfOpen"       OpHelp(""),
 30004      /*   5 */ "NextIfOpen"       OpHelp(""),
 30005      /*   6 */ "Prev"             OpHelp(""),
 30006      /*   7 */ "Next"             OpHelp(""),
 30007      /*   8 */ "Checkpoint"       OpHelp(""),
 30008      /*   9 */ "JournalMode"      OpHelp(""),
 30009      /*  10 */ "Vacuum"           OpHelp(""),
 30010      /*  11 */ "VFilter"          OpHelp("iplan=r[P3] zplan='P4'"),
 30011      /*  12 */ "VUpdate"          OpHelp("data=r[P3@P2]"),
 30012      /*  13 */ "Goto"             OpHelp(""),
 30013      /*  14 */ "Gosub"            OpHelp(""),
 30014      /*  15 */ "InitCoroutine"    OpHelp(""),
 30015      /*  16 */ "Yield"            OpHelp(""),
 30016      /*  17 */ "MustBeInt"        OpHelp(""),
 30017      /*  18 */ "Jump"             OpHelp(""),
 30018      /*  19 */ "Not"              OpHelp("r[P2]= !r[P1]"),
 30019      /*  20 */ "Once"             OpHelp(""),
 30020      /*  21 */ "If"               OpHelp(""),
 30021      /*  22 */ "IfNot"            OpHelp(""),
 30022      /*  23 */ "IfNullRow"        OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"),
 30023      /*  24 */ "SeekLT"           OpHelp("key=r[P3@P4]"),
 30024      /*  25 */ "SeekLE"           OpHelp("key=r[P3@P4]"),
 30025      /*  26 */ "SeekGE"           OpHelp("key=r[P3@P4]"),
 30026      /*  27 */ "SeekGT"           OpHelp("key=r[P3@P4]"),
 30027      /*  28 */ "NoConflict"       OpHelp("key=r[P3@P4]"),
 30028      /*  29 */ "NotFound"         OpHelp("key=r[P3@P4]"),
 30029      /*  30 */ "Found"            OpHelp("key=r[P3@P4]"),
 30030      /*  31 */ "SeekRowid"        OpHelp("intkey=r[P3]"),
 30031      /*  32 */ "NotExists"        OpHelp("intkey=r[P3]"),
 30032      /*  33 */ "Last"             OpHelp(""),
 30033      /*  34 */ "IfSmaller"        OpHelp(""),
 30034      /*  35 */ "SorterSort"       OpHelp(""),
 30035      /*  36 */ "Sort"             OpHelp(""),
 30036      /*  37 */ "Rewind"           OpHelp(""),
 30037      /*  38 */ "IdxLE"            OpHelp("key=r[P3@P4]"),
 30038      /*  39 */ "IdxGT"            OpHelp("key=r[P3@P4]"),
 30039      /*  40 */ "IdxLT"            OpHelp("key=r[P3@P4]"),
 30040      /*  41 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
 30041      /*  42 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
 30042      /*  43 */ "Or"               OpHelp("r[P3]=(r[P1] || r[P2])"),
 30043      /*  44 */ "And"              OpHelp("r[P3]=(r[P1] && r[P2])"),
 30044      /*  45 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
 30045      /*  46 */ "Program"          OpHelp(""),
 30046      /*  47 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),
 30047      /*  48 */ "IfPos"            OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
 30048      /*  49 */ "IfNotZero"        OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
 30049      /*  50 */ "IsNull"           OpHelp("if r[P1]==NULL goto P2"),
 30050      /*  51 */ "NotNull"          OpHelp("if r[P1]!=NULL goto P2"),
 30051      /*  52 */ "Ne"               OpHelp("IF r[P3]!=r[P1]"),
 30052      /*  53 */ "Eq"               OpHelp("IF r[P3]==r[P1]"),
 30053      /*  54 */ "Gt"               OpHelp("IF r[P3]>r[P1]"),
 30054      /*  55 */ "Le"               OpHelp("IF r[P3]<=r[P1]"),
 30055      /*  56 */ "Lt"               OpHelp("IF r[P3]<r[P1]"),
 30056      /*  57 */ "Ge"               OpHelp("IF r[P3]>=r[P1]"),
 30057      /*  58 */ "ElseNotEq"        OpHelp(""),
 30058      /*  59 */ "DecrJumpZero"     OpHelp("if (--r[P1])==0 goto P2"),
 30059      /*  60 */ "IncrVacuum"       OpHelp(""),
 30060      /*  61 */ "VNext"            OpHelp(""),
 30061      /*  62 */ "Init"             OpHelp("Start at P2"),
 30062      /*  63 */ "Return"           OpHelp(""),
 30063      /*  64 */ "EndCoroutine"     OpHelp(""),
 30064      /*  65 */ "HaltIfNull"       OpHelp("if r[P3]=null halt"),
 30065      /*  66 */ "Halt"             OpHelp(""),
 30066      /*  67 */ "Integer"          OpHelp("r[P2]=P1"),
 30067      /*  68 */ "Int64"            OpHelp("r[P2]=P4"),
 30068      /*  69 */ "String"           OpHelp("r[P2]='P4' (len=P1)"),
 30069      /*  70 */ "Null"             OpHelp("r[P2..P3]=NULL"),
 30070      /*  71 */ "SoftNull"         OpHelp("r[P1]=NULL"),
 30071      /*  72 */ "Blob"             OpHelp("r[P2]=P4 (len=P1)"),
 30072      /*  73 */ "Variable"         OpHelp("r[P2]=parameter(P1,P4)"),
 30073      /*  74 */ "Move"             OpHelp("r[P2@P3]=r[P1@P3]"),
 30074      /*  75 */ "Copy"             OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
 30075      /*  76 */ "SCopy"            OpHelp("r[P2]=r[P1]"),
 30076      /*  77 */ "IntCopy"          OpHelp("r[P2]=r[P1]"),
 30077      /*  78 */ "ResultRow"        OpHelp("output=r[P1@P2]"),
 30078      /*  79 */ "CollSeq"          OpHelp(""),
 30079      /*  80 */ "AddImm"           OpHelp("r[P1]=r[P1]+P2"),
 30080      /*  81 */ "RealAffinity"     OpHelp(""),
 30081      /*  82 */ "Cast"             OpHelp("affinity(r[P1])"),
 30082      /*  83 */ "Permutation"      OpHelp(""),
 30083      /*  84 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
 30084      /*  85 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
 30085      /*  86 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
 30086      /*  87 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
 30087      /*  88 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
 30088      /*  89 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
 30089      /*  90 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
 30090      /*  91 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
 30091      /*  92 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
 30092      /*  93 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),
 30093      /*  94 */ "Compare"          OpHelp("r[P1@P3] <-> r[P2@P3]"),
 30094      /*  95 */ "BitNot"           OpHelp("r[P1]= ~r[P1]"),
 30095      /*  96 */ "Column"           OpHelp("r[P3]=PX"),
 30096      /*  97 */ "String8"          OpHelp("r[P2]='P4'"),
 30097      /*  98 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
 30098      /*  99 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
 30099      /* 100 */ "Count"            OpHelp("r[P2]=count()"),
 30100      /* 101 */ "ReadCookie"       OpHelp(""),
 30101      /* 102 */ "SetCookie"        OpHelp(""),
 30102      /* 103 */ "ReopenIdx"        OpHelp("root=P2 iDb=P3"),
 30103      /* 104 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
 30104      /* 105 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
 30105      /* 106 */ "OpenDup"          OpHelp(""),
 30106      /* 107 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
 30107      /* 108 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
 30108      /* 109 */ "SorterOpen"       OpHelp(""),
 30109      /* 110 */ "SequenceTest"     OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
 30110      /* 111 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
 30111      /* 112 */ "Close"            OpHelp(""),
 30112      /* 113 */ "ColumnsUsed"      OpHelp(""),
 30113      /* 114 */ "Sequence"         OpHelp("r[P2]=cursor[P1].ctr++"),
 30114      /* 115 */ "NewRowid"         OpHelp("r[P2]=rowid"),
 30115      /* 116 */ "Insert"           OpHelp("intkey=r[P3] data=r[P2]"),
 30116      /* 117 */ "InsertInt"        OpHelp("intkey=P3 data=r[P2]"),
 30117      /* 118 */ "Delete"           OpHelp(""),
 30118      /* 119 */ "ResetCount"       OpHelp(""),
 30119      /* 120 */ "SorterCompare"    OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
 30120      /* 121 */ "SorterData"       OpHelp("r[P2]=data"),
 30121      /* 122 */ "RowData"          OpHelp("r[P2]=data"),
 30122      /* 123 */ "Rowid"            OpHelp("r[P2]=rowid"),
 30123      /* 124 */ "NullRow"          OpHelp(""),
 30124      /* 125 */ "SeekEnd"          OpHelp(""),
 30125      /* 126 */ "SorterInsert"     OpHelp("key=r[P2]"),
 30126      /* 127 */ "IdxInsert"        OpHelp("key=r[P2]"),
 30127      /* 128 */ "IdxDelete"        OpHelp("key=r[P2@P3]"),
 30128      /* 129 */ "DeferredSeek"     OpHelp("Move P3 to P1.rowid if needed"),
 30129      /* 130 */ "IdxRowid"         OpHelp("r[P2]=rowid"),
 30130      /* 131 */ "Destroy"          OpHelp(""),
 30131      /* 132 */ "Real"             OpHelp("r[P2]=P4"),
 30132      /* 133 */ "Clear"            OpHelp(""),
 30133      /* 134 */ "ResetSorter"      OpHelp(""),
 30134      /* 135 */ "CreateBtree"      OpHelp("r[P2]=root iDb=P1 flags=P3"),
 30135      /* 136 */ "SqlExec"          OpHelp(""),
 30136      /* 137 */ "ParseSchema"      OpHelp(""),
 30137      /* 138 */ "LoadAnalysis"     OpHelp(""),
 30138      /* 139 */ "DropTable"        OpHelp(""),
 30139      /* 140 */ "DropIndex"        OpHelp(""),
 30140      /* 141 */ "DropTrigger"      OpHelp(""),
 30141      /* 142 */ "IntegrityCk"      OpHelp(""),
 30142      /* 143 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
 30143      /* 144 */ "Param"            OpHelp(""),
 30144      /* 145 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
 30145      /* 146 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
 30146      /* 147 */ "OffsetLimit"      OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
 30147      /* 148 */ "AggStep0"         OpHelp("accum=r[P3] step(r[P2@P5])"),
 30148      /* 149 */ "AggStep"          OpHelp("accum=r[P3] step(r[P2@P5])"),
 30149      /* 150 */ "AggFinal"         OpHelp("accum=r[P1] N=P2"),
 30150      /* 151 */ "Expire"           OpHelp(""),
 30151      /* 152 */ "TableLock"        OpHelp("iDb=P1 root=P2 write=P3"),
 30152      /* 153 */ "VBegin"           OpHelp(""),
 30153      /* 154 */ "VCreate"          OpHelp(""),
 30154      /* 155 */ "VDestroy"         OpHelp(""),
 30155      /* 156 */ "VOpen"            OpHelp(""),
 30156      /* 157 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
 30157      /* 158 */ "VRename"          OpHelp(""),
 30158      /* 159 */ "Pagecount"        OpHelp(""),
 30159      /* 160 */ "MaxPgcnt"         OpHelp(""),
 30160      /* 161 */ "PureFunc0"        OpHelp(""),
 30161      /* 162 */ "Function0"        OpHelp("r[P3]=func(r[P2@P5])"),
 30162      /* 163 */ "PureFunc"         OpHelp(""),
 30163      /* 164 */ "Function"         OpHelp("r[P3]=func(r[P2@P5])"),
 30164      /* 165 */ "CursorHint"       OpHelp(""),
 30165      /* 166 */ "Noop"             OpHelp(""),
 30166      /* 167 */ "Explain"          OpHelp(""),
 30167    };
 30168    return azName[i];
 30169  }
 30170  #endif
 30171  
 30172  /************** End of opcodes.c *********************************************/
 30173  /************** Begin file os_unix.c *****************************************/
 30174  /*
 30175  ** 2004 May 22
 30176  **
 30177  ** The author disclaims copyright to this source code.  In place of
 30178  ** a legal notice, here is a blessing:
 30179  **
 30180  **    May you do good and not evil.
 30181  **    May you find forgiveness for yourself and forgive others.
 30182  **    May you share freely, never taking more than you give.
 30183  **
 30184  ******************************************************************************
 30185  **
 30186  ** This file contains the VFS implementation for unix-like operating systems
 30187  ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
 30188  **
 30189  ** There are actually several different VFS implementations in this file.
 30190  ** The differences are in the way that file locking is done.  The default
 30191  ** implementation uses Posix Advisory Locks.  Alternative implementations
 30192  ** use flock(), dot-files, various proprietary locking schemas, or simply
 30193  ** skip locking all together.
 30194  **
 30195  ** This source file is organized into divisions where the logic for various
 30196  ** subfunctions is contained within the appropriate division.  PLEASE
 30197  ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
 30198  ** in the correct division and should be clearly labeled.
 30199  **
 30200  ** The layout of divisions is as follows:
 30201  **
 30202  **   *  General-purpose declarations and utility functions.
 30203  **   *  Unique file ID logic used by VxWorks.
 30204  **   *  Various locking primitive implementations (all except proxy locking):
 30205  **      + for Posix Advisory Locks
 30206  **      + for no-op locks
 30207  **      + for dot-file locks
 30208  **      + for flock() locking
 30209  **      + for named semaphore locks (VxWorks only)
 30210  **      + for AFP filesystem locks (MacOSX only)
 30211  **   *  sqlite3_file methods not associated with locking.
 30212  **   *  Definitions of sqlite3_io_methods objects for all locking
 30213  **      methods plus "finder" functions for each locking method.
 30214  **   *  sqlite3_vfs method implementations.
 30215  **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
 30216  **   *  Definitions of sqlite3_vfs objects for all locking methods
 30217  **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
 30218  */
 30219  /* #include "sqliteInt.h" */
 30220  #if SQLITE_OS_UNIX              /* This file is used on unix only */
 30221  
 30222  /*
 30223  ** There are various methods for file locking used for concurrency
 30224  ** control:
 30225  **
 30226  **   1. POSIX locking (the default),
 30227  **   2. No locking,
 30228  **   3. Dot-file locking,
 30229  **   4. flock() locking,
 30230  **   5. AFP locking (OSX only),
 30231  **   6. Named POSIX semaphores (VXWorks only),
 30232  **   7. proxy locking. (OSX only)
 30233  **
 30234  ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
 30235  ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
 30236  ** selection of the appropriate locking style based on the filesystem
 30237  ** where the database is located.  
 30238  */
 30239  #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
 30240  #  if defined(__APPLE__)
 30241  #    define SQLITE_ENABLE_LOCKING_STYLE 1
 30242  #  else
 30243  #    define SQLITE_ENABLE_LOCKING_STYLE 0
 30244  #  endif
 30245  #endif
 30246  
 30247  /* Use pread() and pwrite() if they are available */
 30248  #if defined(__APPLE__)
 30249  # define HAVE_PREAD 1
 30250  # define HAVE_PWRITE 1
 30251  #endif
 30252  #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
 30253  # undef USE_PREAD
 30254  # define USE_PREAD64 1
 30255  #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
 30256  # undef USE_PREAD64
 30257  # define USE_PREAD 1
 30258  #endif
 30259  
 30260  /*
 30261  ** standard include files.
 30262  */
 30263  #include <sys/types.h>
 30264  #include <sys/stat.h>
 30265  #include <fcntl.h>
 30266  #include <sys/ioctl.h>
 30267  #include <unistd.h>
 30268  /* #include <time.h> */
 30269  #include <sys/time.h>
 30270  #include <errno.h>
 30271  #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
 30272  # include <sys/mman.h>
 30273  #endif
 30274  
 30275  #if SQLITE_ENABLE_LOCKING_STYLE
 30276  /* # include <sys/ioctl.h> */
 30277  # include <sys/file.h>
 30278  # include <sys/param.h>
 30279  #endif /* SQLITE_ENABLE_LOCKING_STYLE */
 30280  
 30281  #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
 30282                             (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
 30283  #  if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
 30284         && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
 30285  #    define HAVE_GETHOSTUUID 1
 30286  #  else
 30287  #    warning "gethostuuid() is disabled."
 30288  #  endif
 30289  #endif
 30290  
 30291  
 30292  #if OS_VXWORKS
 30293  /* # include <sys/ioctl.h> */
 30294  # include <semaphore.h>
 30295  # include <limits.h>
 30296  #endif /* OS_VXWORKS */
 30297  
 30298  #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
 30299  # include <sys/mount.h>
 30300  #endif
 30301  
 30302  #ifdef HAVE_UTIME
 30303  # include <utime.h>
 30304  #endif
 30305  
 30306  /*
 30307  ** Allowed values of unixFile.fsFlags
 30308  */
 30309  #define SQLITE_FSFLAGS_IS_MSDOS     0x1
 30310  
 30311  /*
 30312  ** If we are to be thread-safe, include the pthreads header and define
 30313  ** the SQLITE_UNIX_THREADS macro.
 30314  */
 30315  #if SQLITE_THREADSAFE
 30316  /* # include <pthread.h> */
 30317  # define SQLITE_UNIX_THREADS 1
 30318  #endif
 30319  
 30320  /*
 30321  ** Default permissions when creating a new file
 30322  */
 30323  #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
 30324  # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
 30325  #endif
 30326  
 30327  /*
 30328  ** Default permissions when creating auto proxy dir
 30329  */
 30330  #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
 30331  # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
 30332  #endif
 30333  
 30334  /*
 30335  ** Maximum supported path-length.
 30336  */
 30337  #define MAX_PATHNAME 512
 30338  
 30339  /*
 30340  ** Maximum supported symbolic links
 30341  */
 30342  #define SQLITE_MAX_SYMLINKS 100
 30343  
 30344  /* Always cast the getpid() return type for compatibility with
 30345  ** kernel modules in VxWorks. */
 30346  #define osGetpid(X) (pid_t)getpid()
 30347  
 30348  /*
 30349  ** Only set the lastErrno if the error code is a real error and not 
 30350  ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
 30351  */
 30352  #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
 30353  
 30354  /* Forward references */
 30355  typedef struct unixShm unixShm;               /* Connection shared memory */
 30356  typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
 30357  typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
 30358  typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
 30359  
 30360  /*
 30361  ** Sometimes, after a file handle is closed by SQLite, the file descriptor
 30362  ** cannot be closed immediately. In these cases, instances of the following
 30363  ** structure are used to store the file descriptor while waiting for an
 30364  ** opportunity to either close or reuse it.
 30365  */
 30366  struct UnixUnusedFd {
 30367    int fd;                   /* File descriptor to close */
 30368    int flags;                /* Flags this file descriptor was opened with */
 30369    UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
 30370  };
 30371  
 30372  /*
 30373  ** The unixFile structure is subclass of sqlite3_file specific to the unix
 30374  ** VFS implementations.
 30375  */
 30376  typedef struct unixFile unixFile;
 30377  struct unixFile {
 30378    sqlite3_io_methods const *pMethod;  /* Always the first entry */
 30379    sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
 30380    unixInodeInfo *pInode;              /* Info about locks on this inode */
 30381    int h;                              /* The file descriptor */
 30382    unsigned char eFileLock;            /* The type of lock held on this fd */
 30383    unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
 30384    int lastErrno;                      /* The unix errno from last I/O error */
 30385    void *lockingContext;               /* Locking style specific state */
 30386    UnixUnusedFd *pPreallocatedUnused;  /* Pre-allocated UnixUnusedFd */
 30387    const char *zPath;                  /* Name of the file */
 30388    unixShm *pShm;                      /* Shared memory segment information */
 30389    int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
 30390  #if SQLITE_MAX_MMAP_SIZE>0
 30391    int nFetchOut;                      /* Number of outstanding xFetch refs */
 30392    sqlite3_int64 mmapSize;             /* Usable size of mapping at pMapRegion */
 30393    sqlite3_int64 mmapSizeActual;       /* Actual size of mapping at pMapRegion */
 30394    sqlite3_int64 mmapSizeMax;          /* Configured FCNTL_MMAP_SIZE value */
 30395    void *pMapRegion;                   /* Memory mapped region */
 30396  #endif
 30397    int sectorSize;                     /* Device sector size */
 30398    int deviceCharacteristics;          /* Precomputed device characteristics */
 30399  #if SQLITE_ENABLE_LOCKING_STYLE
 30400    int openFlags;                      /* The flags specified at open() */
 30401  #endif
 30402  #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
 30403    unsigned fsFlags;                   /* cached details from statfs() */
 30404  #endif
 30405  #if OS_VXWORKS
 30406    struct vxworksFileId *pId;          /* Unique file ID */
 30407  #endif
 30408  #ifdef SQLITE_DEBUG
 30409    /* The next group of variables are used to track whether or not the
 30410    ** transaction counter in bytes 24-27 of database files are updated
 30411    ** whenever any part of the database changes.  An assertion fault will
 30412    ** occur if a file is updated without also updating the transaction
 30413    ** counter.  This test is made to avoid new problems similar to the
 30414    ** one described by ticket #3584. 
 30415    */
 30416    unsigned char transCntrChng;   /* True if the transaction counter changed */
 30417    unsigned char dbUpdate;        /* True if any part of database file changed */
 30418    unsigned char inNormalWrite;   /* True if in a normal write operation */
 30419  
 30420  #endif
 30421  
 30422  #ifdef SQLITE_TEST
 30423    /* In test mode, increase the size of this structure a bit so that 
 30424    ** it is larger than the struct CrashFile defined in test6.c.
 30425    */
 30426    char aPadding[32];
 30427  #endif
 30428  };
 30429  
 30430  /* This variable holds the process id (pid) from when the xRandomness()
 30431  ** method was called.  If xOpen() is called from a different process id,
 30432  ** indicating that a fork() has occurred, the PRNG will be reset.
 30433  */
 30434  static pid_t randomnessPid = 0;
 30435  
 30436  /*
 30437  ** Allowed values for the unixFile.ctrlFlags bitmask:
 30438  */
 30439  #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
 30440  #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
 30441  #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
 30442  #ifndef SQLITE_DISABLE_DIRSYNC
 30443  # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
 30444  #else
 30445  # define UNIXFILE_DIRSYNC    0x00
 30446  #endif
 30447  #define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
 30448  #define UNIXFILE_DELETE      0x20     /* Delete on close */
 30449  #define UNIXFILE_URI         0x40     /* Filename might have query parameters */
 30450  #define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
 30451  
 30452  /*
 30453  ** Include code that is common to all os_*.c files
 30454  */
 30455  /************** Include os_common.h in the middle of os_unix.c ***************/
 30456  /************** Begin file os_common.h ***************************************/
 30457  /*
 30458  ** 2004 May 22
 30459  **
 30460  ** The author disclaims copyright to this source code.  In place of
 30461  ** a legal notice, here is a blessing:
 30462  **
 30463  **    May you do good and not evil.
 30464  **    May you find forgiveness for yourself and forgive others.
 30465  **    May you share freely, never taking more than you give.
 30466  **
 30467  ******************************************************************************
 30468  **
 30469  ** This file contains macros and a little bit of code that is common to
 30470  ** all of the platform-specific files (os_*.c) and is #included into those
 30471  ** files.
 30472  **
 30473  ** This file should be #included by the os_*.c files only.  It is not a
 30474  ** general purpose header file.
 30475  */
 30476  #ifndef _OS_COMMON_H_
 30477  #define _OS_COMMON_H_
 30478  
 30479  /*
 30480  ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
 30481  ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
 30482  ** switch.  The following code should catch this problem at compile-time.
 30483  */
 30484  #ifdef MEMORY_DEBUG
 30485  # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
 30486  #endif
 30487  
 30488  /*
 30489  ** Macros for performance tracing.  Normally turned off.  Only works
 30490  ** on i486 hardware.
 30491  */
 30492  #ifdef SQLITE_PERFORMANCE_TRACE
 30493  
 30494  /*
 30495  ** hwtime.h contains inline assembler code for implementing
 30496  ** high-performance timing routines.
 30497  */
 30498  /************** Include hwtime.h in the middle of os_common.h ****************/
 30499  /************** Begin file hwtime.h ******************************************/
 30500  /*
 30501  ** 2008 May 27
 30502  **
 30503  ** The author disclaims copyright to this source code.  In place of
 30504  ** a legal notice, here is a blessing:
 30505  **
 30506  **    May you do good and not evil.
 30507  **    May you find forgiveness for yourself and forgive others.
 30508  **    May you share freely, never taking more than you give.
 30509  **
 30510  ******************************************************************************
 30511  **
 30512  ** This file contains inline asm code for retrieving "high-performance"
 30513  ** counters for x86 class CPUs.
 30514  */
 30515  #ifndef SQLITE_HWTIME_H
 30516  #define SQLITE_HWTIME_H
 30517  
 30518  /*
 30519  ** The following routine only works on pentium-class (or newer) processors.
 30520  ** It uses the RDTSC opcode to read the cycle count value out of the
 30521  ** processor and returns that value.  This can be used for high-res
 30522  ** profiling.
 30523  */
 30524  #if (defined(__GNUC__) || defined(_MSC_VER)) && \
 30525        (defined(i386) || defined(__i386__) || defined(_M_IX86))
 30526  
 30527    #if defined(__GNUC__)
 30528  
 30529    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 30530       unsigned int lo, hi;
 30531       __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
 30532       return (sqlite_uint64)hi << 32 | lo;
 30533    }
 30534  
 30535    #elif defined(_MSC_VER)
 30536  
 30537    __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
 30538       __asm {
 30539          rdtsc
 30540          ret       ; return value at EDX:EAX
 30541       }
 30542    }
 30543  
 30544    #endif
 30545  
 30546  #elif (defined(__GNUC__) && defined(__x86_64__))
 30547  
 30548    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 30549        unsigned long val;
 30550        __asm__ __volatile__ ("rdtsc" : "=A" (val));
 30551        return val;
 30552    }
 30553   
 30554  #elif (defined(__GNUC__) && defined(__ppc__))
 30555  
 30556    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 30557        unsigned long long retval;
 30558        unsigned long junk;
 30559        __asm__ __volatile__ ("\n\
 30560            1:      mftbu   %1\n\
 30561                    mftb    %L0\n\
 30562                    mftbu   %0\n\
 30563                    cmpw    %0,%1\n\
 30564                    bne     1b"
 30565                    : "=r" (retval), "=r" (junk));
 30566        return retval;
 30567    }
 30568  
 30569  #else
 30570  
 30571    #error Need implementation of sqlite3Hwtime() for your platform.
 30572  
 30573    /*
 30574    ** To compile without implementing sqlite3Hwtime() for your platform,
 30575    ** you can remove the above #error and use the following
 30576    ** stub function.  You will lose timing support for many
 30577    ** of the debugging and testing utilities, but it should at
 30578    ** least compile and run.
 30579    */
 30580  SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
 30581  
 30582  #endif
 30583  
 30584  #endif /* !defined(SQLITE_HWTIME_H) */
 30585  
 30586  /************** End of hwtime.h **********************************************/
 30587  /************** Continuing where we left off in os_common.h ******************/
 30588  
 30589  static sqlite_uint64 g_start;
 30590  static sqlite_uint64 g_elapsed;
 30591  #define TIMER_START       g_start=sqlite3Hwtime()
 30592  #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
 30593  #define TIMER_ELAPSED     g_elapsed
 30594  #else
 30595  #define TIMER_START
 30596  #define TIMER_END
 30597  #define TIMER_ELAPSED     ((sqlite_uint64)0)
 30598  #endif
 30599  
 30600  /*
 30601  ** If we compile with the SQLITE_TEST macro set, then the following block
 30602  ** of code will give us the ability to simulate a disk I/O error.  This
 30603  ** is used for testing the I/O recovery logic.
 30604  */
 30605  #if defined(SQLITE_TEST)
 30606  SQLITE_API extern int sqlite3_io_error_hit;
 30607  SQLITE_API extern int sqlite3_io_error_hardhit;
 30608  SQLITE_API extern int sqlite3_io_error_pending;
 30609  SQLITE_API extern int sqlite3_io_error_persist;
 30610  SQLITE_API extern int sqlite3_io_error_benign;
 30611  SQLITE_API extern int sqlite3_diskfull_pending;
 30612  SQLITE_API extern int sqlite3_diskfull;
 30613  #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
 30614  #define SimulateIOError(CODE)  \
 30615    if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
 30616         || sqlite3_io_error_pending-- == 1 )  \
 30617                { local_ioerr(); CODE; }
 30618  static void local_ioerr(){
 30619    IOTRACE(("IOERR\n"));
 30620    sqlite3_io_error_hit++;
 30621    if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
 30622  }
 30623  #define SimulateDiskfullError(CODE) \
 30624     if( sqlite3_diskfull_pending ){ \
 30625       if( sqlite3_diskfull_pending == 1 ){ \
 30626         local_ioerr(); \
 30627         sqlite3_diskfull = 1; \
 30628         sqlite3_io_error_hit = 1; \
 30629         CODE; \
 30630       }else{ \
 30631         sqlite3_diskfull_pending--; \
 30632       } \
 30633     }
 30634  #else
 30635  #define SimulateIOErrorBenign(X)
 30636  #define SimulateIOError(A)
 30637  #define SimulateDiskfullError(A)
 30638  #endif /* defined(SQLITE_TEST) */
 30639  
 30640  /*
 30641  ** When testing, keep a count of the number of open files.
 30642  */
 30643  #if defined(SQLITE_TEST)
 30644  SQLITE_API extern int sqlite3_open_file_count;
 30645  #define OpenCounter(X)  sqlite3_open_file_count+=(X)
 30646  #else
 30647  #define OpenCounter(X)
 30648  #endif /* defined(SQLITE_TEST) */
 30649  
 30650  #endif /* !defined(_OS_COMMON_H_) */
 30651  
 30652  /************** End of os_common.h *******************************************/
 30653  /************** Continuing where we left off in os_unix.c ********************/
 30654  
 30655  /*
 30656  ** Define various macros that are missing from some systems.
 30657  */
 30658  #ifndef O_LARGEFILE
 30659  # define O_LARGEFILE 0
 30660  #endif
 30661  #ifdef SQLITE_DISABLE_LFS
 30662  # undef O_LARGEFILE
 30663  # define O_LARGEFILE 0
 30664  #endif
 30665  #ifndef O_NOFOLLOW
 30666  # define O_NOFOLLOW 0
 30667  #endif
 30668  #ifndef O_BINARY
 30669  # define O_BINARY 0
 30670  #endif
 30671  
 30672  /*
 30673  ** The threadid macro resolves to the thread-id or to 0.  Used for
 30674  ** testing and debugging only.
 30675  */
 30676  #if SQLITE_THREADSAFE
 30677  #define threadid pthread_self()
 30678  #else
 30679  #define threadid 0
 30680  #endif
 30681  
 30682  /*
 30683  ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
 30684  */
 30685  #if !defined(HAVE_MREMAP)
 30686  # if defined(__linux__) && defined(_GNU_SOURCE)
 30687  #  define HAVE_MREMAP 1
 30688  # else
 30689  #  define HAVE_MREMAP 0
 30690  # endif
 30691  #endif
 30692  
 30693  /*
 30694  ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
 30695  ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
 30696  */
 30697  #ifdef __ANDROID__
 30698  # define lseek lseek64
 30699  #endif
 30700  
 30701  #ifdef __linux__
 30702  /*
 30703  ** Linux-specific IOCTL magic numbers used for controlling F2FS
 30704  */
 30705  #define F2FS_IOCTL_MAGIC        0xf5
 30706  #define F2FS_IOC_START_ATOMIC_WRITE     _IO(F2FS_IOCTL_MAGIC, 1)
 30707  #define F2FS_IOC_COMMIT_ATOMIC_WRITE    _IO(F2FS_IOCTL_MAGIC, 2)
 30708  #define F2FS_IOC_START_VOLATILE_WRITE   _IO(F2FS_IOCTL_MAGIC, 3)
 30709  #define F2FS_IOC_ABORT_VOLATILE_WRITE   _IO(F2FS_IOCTL_MAGIC, 5)
 30710  #define F2FS_IOC_GET_FEATURES           _IOR(F2FS_IOCTL_MAGIC, 12, u32)
 30711  #define F2FS_FEATURE_ATOMIC_WRITE 0x0004
 30712  #endif /* __linux__ */
 30713  
 30714  
 30715  /*
 30716  ** Different Unix systems declare open() in different ways.  Same use
 30717  ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
 30718  ** The difference is important when using a pointer to the function.
 30719  **
 30720  ** The safest way to deal with the problem is to always use this wrapper
 30721  ** which always has the same well-defined interface.
 30722  */
 30723  static int posixOpen(const char *zFile, int flags, int mode){
 30724    return open(zFile, flags, mode);
 30725  }
 30726  
 30727  /* Forward reference */
 30728  static int openDirectory(const char*, int*);
 30729  static int unixGetpagesize(void);
 30730  
 30731  /*
 30732  ** Many system calls are accessed through pointer-to-functions so that
 30733  ** they may be overridden at runtime to facilitate fault injection during
 30734  ** testing and sandboxing.  The following array holds the names and pointers
 30735  ** to all overrideable system calls.
 30736  */
 30737  static struct unix_syscall {
 30738    const char *zName;            /* Name of the system call */
 30739    sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
 30740    sqlite3_syscall_ptr pDefault; /* Default value */
 30741  } aSyscall[] = {
 30742    { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
 30743  #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
 30744  
 30745    { "close",        (sqlite3_syscall_ptr)close,      0  },
 30746  #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
 30747  
 30748    { "access",       (sqlite3_syscall_ptr)access,     0  },
 30749  #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
 30750  
 30751    { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
 30752  #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
 30753  
 30754    { "stat",         (sqlite3_syscall_ptr)stat,       0  },
 30755  #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
 30756  
 30757  /*
 30758  ** The DJGPP compiler environment looks mostly like Unix, but it
 30759  ** lacks the fcntl() system call.  So redefine fcntl() to be something
 30760  ** that always succeeds.  This means that locking does not occur under
 30761  ** DJGPP.  But it is DOS - what did you expect?
 30762  */
 30763  #ifdef __DJGPP__
 30764    { "fstat",        0,                 0  },
 30765  #define osFstat(a,b,c)    0
 30766  #else     
 30767    { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
 30768  #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
 30769  #endif
 30770  
 30771    { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
 30772  #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
 30773  
 30774    { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
 30775  #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
 30776  
 30777    { "read",         (sqlite3_syscall_ptr)read,       0  },
 30778  #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
 30779  
 30780  #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
 30781    { "pread",        (sqlite3_syscall_ptr)pread,      0  },
 30782  #else
 30783    { "pread",        (sqlite3_syscall_ptr)0,          0  },
 30784  #endif
 30785  #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
 30786  
 30787  #if defined(USE_PREAD64)
 30788    { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
 30789  #else
 30790    { "pread64",      (sqlite3_syscall_ptr)0,          0  },
 30791  #endif
 30792  #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
 30793  
 30794    { "write",        (sqlite3_syscall_ptr)write,      0  },
 30795  #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
 30796  
 30797  #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
 30798    { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
 30799  #else
 30800    { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
 30801  #endif
 30802  #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
 30803                      aSyscall[12].pCurrent)
 30804  
 30805  #if defined(USE_PREAD64)
 30806    { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
 30807  #else
 30808    { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
 30809  #endif
 30810  #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off64_t))\
 30811                      aSyscall[13].pCurrent)
 30812  
 30813    { "fchmod",       (sqlite3_syscall_ptr)fchmod,          0  },
 30814  #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
 30815  
 30816  #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
 30817    { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
 30818  #else
 30819    { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
 30820  #endif
 30821  #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
 30822  
 30823    { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
 30824  #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
 30825  
 30826    { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
 30827  #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
 30828  
 30829    { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
 30830  #define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
 30831  
 30832    { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
 30833  #define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
 30834  
 30835  #if defined(HAVE_FCHOWN)
 30836    { "fchown",       (sqlite3_syscall_ptr)fchown,          0 },
 30837  #else
 30838    { "fchown",       (sqlite3_syscall_ptr)0,               0 },
 30839  #endif
 30840  #define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
 30841  
 30842    { "geteuid",      (sqlite3_syscall_ptr)geteuid,         0 },
 30843  #define osGeteuid   ((uid_t(*)(void))aSyscall[21].pCurrent)
 30844  
 30845  #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
 30846    { "mmap",         (sqlite3_syscall_ptr)mmap,            0 },
 30847  #else
 30848    { "mmap",         (sqlite3_syscall_ptr)0,               0 },
 30849  #endif
 30850  #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
 30851  
 30852  #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
 30853    { "munmap",       (sqlite3_syscall_ptr)munmap,          0 },
 30854  #else
 30855    { "munmap",       (sqlite3_syscall_ptr)0,               0 },
 30856  #endif
 30857  #define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
 30858  
 30859  #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
 30860    { "mremap",       (sqlite3_syscall_ptr)mremap,          0 },
 30861  #else
 30862    { "mremap",       (sqlite3_syscall_ptr)0,               0 },
 30863  #endif
 30864  #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
 30865  
 30866  #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
 30867    { "getpagesize",  (sqlite3_syscall_ptr)unixGetpagesize, 0 },
 30868  #else
 30869    { "getpagesize",  (sqlite3_syscall_ptr)0,               0 },
 30870  #endif
 30871  #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
 30872  
 30873  #if defined(HAVE_READLINK)
 30874    { "readlink",     (sqlite3_syscall_ptr)readlink,        0 },
 30875  #else
 30876    { "readlink",     (sqlite3_syscall_ptr)0,               0 },
 30877  #endif
 30878  #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
 30879  
 30880  #if defined(HAVE_LSTAT)
 30881    { "lstat",         (sqlite3_syscall_ptr)lstat,          0 },
 30882  #else
 30883    { "lstat",         (sqlite3_syscall_ptr)0,              0 },
 30884  #endif
 30885  #define osLstat      ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
 30886  
 30887    { "ioctl",         (sqlite3_syscall_ptr)ioctl,          0 },
 30888  #define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
 30889  
 30890  }; /* End of the overrideable system calls */
 30891  
 30892  
 30893  /*
 30894  ** On some systems, calls to fchown() will trigger a message in a security
 30895  ** log if they come from non-root processes.  So avoid calling fchown() if
 30896  ** we are not running as root.
 30897  */
 30898  static int robustFchown(int fd, uid_t uid, gid_t gid){
 30899  #if defined(HAVE_FCHOWN)
 30900    return osGeteuid() ? 0 : osFchown(fd,uid,gid);
 30901  #else
 30902    return 0;
 30903  #endif
 30904  }
 30905  
 30906  /*
 30907  ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
 30908  ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
 30909  ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
 30910  ** system call named zName.
 30911  */
 30912  static int unixSetSystemCall(
 30913    sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
 30914    const char *zName,            /* Name of system call to override */
 30915    sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
 30916  ){
 30917    unsigned int i;
 30918    int rc = SQLITE_NOTFOUND;
 30919  
 30920    UNUSED_PARAMETER(pNotUsed);
 30921    if( zName==0 ){
 30922      /* If no zName is given, restore all system calls to their default
 30923      ** settings and return NULL
 30924      */
 30925      rc = SQLITE_OK;
 30926      for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
 30927        if( aSyscall[i].pDefault ){
 30928          aSyscall[i].pCurrent = aSyscall[i].pDefault;
 30929        }
 30930      }
 30931    }else{
 30932      /* If zName is specified, operate on only the one system call
 30933      ** specified.
 30934      */
 30935      for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
 30936        if( strcmp(zName, aSyscall[i].zName)==0 ){
 30937          if( aSyscall[i].pDefault==0 ){
 30938            aSyscall[i].pDefault = aSyscall[i].pCurrent;
 30939          }
 30940          rc = SQLITE_OK;
 30941          if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
 30942          aSyscall[i].pCurrent = pNewFunc;
 30943          break;
 30944        }
 30945      }
 30946    }
 30947    return rc;
 30948  }
 30949  
 30950  /*
 30951  ** Return the value of a system call.  Return NULL if zName is not a
 30952  ** recognized system call name.  NULL is also returned if the system call
 30953  ** is currently undefined.
 30954  */
 30955  static sqlite3_syscall_ptr unixGetSystemCall(
 30956    sqlite3_vfs *pNotUsed,
 30957    const char *zName
 30958  ){
 30959    unsigned int i;
 30960  
 30961    UNUSED_PARAMETER(pNotUsed);
 30962    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
 30963      if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
 30964    }
 30965    return 0;
 30966  }
 30967  
 30968  /*
 30969  ** Return the name of the first system call after zName.  If zName==NULL
 30970  ** then return the name of the first system call.  Return NULL if zName
 30971  ** is the last system call or if zName is not the name of a valid
 30972  ** system call.
 30973  */
 30974  static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
 30975    int i = -1;
 30976  
 30977    UNUSED_PARAMETER(p);
 30978    if( zName ){
 30979      for(i=0; i<ArraySize(aSyscall)-1; i++){
 30980        if( strcmp(zName, aSyscall[i].zName)==0 ) break;
 30981      }
 30982    }
 30983    for(i++; i<ArraySize(aSyscall); i++){
 30984      if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
 30985    }
 30986    return 0;
 30987  }
 30988  
 30989  /*
 30990  ** Do not accept any file descriptor less than this value, in order to avoid
 30991  ** opening database file using file descriptors that are commonly used for 
 30992  ** standard input, output, and error.
 30993  */
 30994  #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
 30995  # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
 30996  #endif
 30997  
 30998  /*
 30999  ** Invoke open().  Do so multiple times, until it either succeeds or
 31000  ** fails for some reason other than EINTR.
 31001  **
 31002  ** If the file creation mode "m" is 0 then set it to the default for
 31003  ** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
 31004  ** 0644) as modified by the system umask.  If m is not 0, then
 31005  ** make the file creation mode be exactly m ignoring the umask.
 31006  **
 31007  ** The m parameter will be non-zero only when creating -wal, -journal,
 31008  ** and -shm files.  We want those files to have *exactly* the same
 31009  ** permissions as their original database, unadulterated by the umask.
 31010  ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
 31011  ** transaction crashes and leaves behind hot journals, then any
 31012  ** process that is able to write to the database will also be able to
 31013  ** recover the hot journals.
 31014  */
 31015  static int robust_open(const char *z, int f, mode_t m){
 31016    int fd;
 31017    mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
 31018    while(1){
 31019  #if defined(O_CLOEXEC)
 31020      fd = osOpen(z,f|O_CLOEXEC,m2);
 31021  #else
 31022      fd = osOpen(z,f,m2);
 31023  #endif
 31024      if( fd<0 ){
 31025        if( errno==EINTR ) continue;
 31026        break;
 31027      }
 31028      if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
 31029      osClose(fd);
 31030      sqlite3_log(SQLITE_WARNING, 
 31031                  "attempt to open \"%s\" as file descriptor %d", z, fd);
 31032      fd = -1;
 31033      if( osOpen("/dev/null", f, m)<0 ) break;
 31034    }
 31035    if( fd>=0 ){
 31036      if( m!=0 ){
 31037        struct stat statbuf;
 31038        if( osFstat(fd, &statbuf)==0 
 31039         && statbuf.st_size==0
 31040         && (statbuf.st_mode&0777)!=m 
 31041        ){
 31042          osFchmod(fd, m);
 31043        }
 31044      }
 31045  #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
 31046      osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
 31047  #endif
 31048    }
 31049    return fd;
 31050  }
 31051  
 31052  /*
 31053  ** Helper functions to obtain and relinquish the global mutex. The
 31054  ** global mutex is used to protect the unixInodeInfo and
 31055  ** vxworksFileId objects used by this file, all of which may be 
 31056  ** shared by multiple threads.
 31057  **
 31058  ** Function unixMutexHeld() is used to assert() that the global mutex 
 31059  ** is held when required. This function is only used as part of assert() 
 31060  ** statements. e.g.
 31061  **
 31062  **   unixEnterMutex()
 31063  **     assert( unixMutexHeld() );
 31064  **   unixEnterLeave()
 31065  */
 31066  static void unixEnterMutex(void){
 31067    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
 31068  }
 31069  static void unixLeaveMutex(void){
 31070    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
 31071  }
 31072  #ifdef SQLITE_DEBUG
 31073  static int unixMutexHeld(void) {
 31074    return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
 31075  }
 31076  #endif
 31077  
 31078  
 31079  #ifdef SQLITE_HAVE_OS_TRACE
 31080  /*
 31081  ** Helper function for printing out trace information from debugging
 31082  ** binaries. This returns the string representation of the supplied
 31083  ** integer lock-type.
 31084  */
 31085  static const char *azFileLock(int eFileLock){
 31086    switch( eFileLock ){
 31087      case NO_LOCK: return "NONE";
 31088      case SHARED_LOCK: return "SHARED";
 31089      case RESERVED_LOCK: return "RESERVED";
 31090      case PENDING_LOCK: return "PENDING";
 31091      case EXCLUSIVE_LOCK: return "EXCLUSIVE";
 31092    }
 31093    return "ERROR";
 31094  }
 31095  #endif
 31096  
 31097  #ifdef SQLITE_LOCK_TRACE
 31098  /*
 31099  ** Print out information about all locking operations.
 31100  **
 31101  ** This routine is used for troubleshooting locks on multithreaded
 31102  ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
 31103  ** command-line option on the compiler.  This code is normally
 31104  ** turned off.
 31105  */
 31106  static int lockTrace(int fd, int op, struct flock *p){
 31107    char *zOpName, *zType;
 31108    int s;
 31109    int savedErrno;
 31110    if( op==F_GETLK ){
 31111      zOpName = "GETLK";
 31112    }else if( op==F_SETLK ){
 31113      zOpName = "SETLK";
 31114    }else{
 31115      s = osFcntl(fd, op, p);
 31116      sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
 31117      return s;
 31118    }
 31119    if( p->l_type==F_RDLCK ){
 31120      zType = "RDLCK";
 31121    }else if( p->l_type==F_WRLCK ){
 31122      zType = "WRLCK";
 31123    }else if( p->l_type==F_UNLCK ){
 31124      zType = "UNLCK";
 31125    }else{
 31126      assert( 0 );
 31127    }
 31128    assert( p->l_whence==SEEK_SET );
 31129    s = osFcntl(fd, op, p);
 31130    savedErrno = errno;
 31131    sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
 31132       threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
 31133       (int)p->l_pid, s);
 31134    if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
 31135      struct flock l2;
 31136      l2 = *p;
 31137      osFcntl(fd, F_GETLK, &l2);
 31138      if( l2.l_type==F_RDLCK ){
 31139        zType = "RDLCK";
 31140      }else if( l2.l_type==F_WRLCK ){
 31141        zType = "WRLCK";
 31142      }else if( l2.l_type==F_UNLCK ){
 31143        zType = "UNLCK";
 31144      }else{
 31145        assert( 0 );
 31146      }
 31147      sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
 31148         zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
 31149    }
 31150    errno = savedErrno;
 31151    return s;
 31152  }
 31153  #undef osFcntl
 31154  #define osFcntl lockTrace
 31155  #endif /* SQLITE_LOCK_TRACE */
 31156  
 31157  /*
 31158  ** Retry ftruncate() calls that fail due to EINTR
 31159  **
 31160  ** All calls to ftruncate() within this file should be made through
 31161  ** this wrapper.  On the Android platform, bypassing the logic below
 31162  ** could lead to a corrupt database.
 31163  */
 31164  static int robust_ftruncate(int h, sqlite3_int64 sz){
 31165    int rc;
 31166  #ifdef __ANDROID__
 31167    /* On Android, ftruncate() always uses 32-bit offsets, even if 
 31168    ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
 31169    ** truncate a file to any size larger than 2GiB. Silently ignore any
 31170    ** such attempts.  */
 31171    if( sz>(sqlite3_int64)0x7FFFFFFF ){
 31172      rc = SQLITE_OK;
 31173    }else
 31174  #endif
 31175    do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
 31176    return rc;
 31177  }
 31178  
 31179  /*
 31180  ** This routine translates a standard POSIX errno code into something
 31181  ** useful to the clients of the sqlite3 functions.  Specifically, it is
 31182  ** intended to translate a variety of "try again" errors into SQLITE_BUSY
 31183  ** and a variety of "please close the file descriptor NOW" errors into 
 31184  ** SQLITE_IOERR
 31185  ** 
 31186  ** Errors during initialization of locks, or file system support for locks,
 31187  ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
 31188  */
 31189  static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
 31190    assert( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
 31191            (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
 31192            (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
 31193            (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
 31194    switch (posixError) {
 31195    case EACCES: 
 31196    case EAGAIN:
 31197    case ETIMEDOUT:
 31198    case EBUSY:
 31199    case EINTR:
 31200    case ENOLCK:  
 31201      /* random NFS retry error, unless during file system support 
 31202       * introspection, in which it actually means what it says */
 31203      return SQLITE_BUSY;
 31204      
 31205    case EPERM: 
 31206      return SQLITE_PERM;
 31207      
 31208    default: 
 31209      return sqliteIOErr;
 31210    }
 31211  }
 31212  
 31213  
 31214  /******************************************************************************
 31215  ****************** Begin Unique File ID Utility Used By VxWorks ***************
 31216  **
 31217  ** On most versions of unix, we can get a unique ID for a file by concatenating
 31218  ** the device number and the inode number.  But this does not work on VxWorks.
 31219  ** On VxWorks, a unique file id must be based on the canonical filename.
 31220  **
 31221  ** A pointer to an instance of the following structure can be used as a
 31222  ** unique file ID in VxWorks.  Each instance of this structure contains
 31223  ** a copy of the canonical filename.  There is also a reference count.  
 31224  ** The structure is reclaimed when the number of pointers to it drops to
 31225  ** zero.
 31226  **
 31227  ** There are never very many files open at one time and lookups are not
 31228  ** a performance-critical path, so it is sufficient to put these
 31229  ** structures on a linked list.
 31230  */
 31231  struct vxworksFileId {
 31232    struct vxworksFileId *pNext;  /* Next in a list of them all */
 31233    int nRef;                     /* Number of references to this one */
 31234    int nName;                    /* Length of the zCanonicalName[] string */
 31235    char *zCanonicalName;         /* Canonical filename */
 31236  };
 31237  
 31238  #if OS_VXWORKS
 31239  /* 
 31240  ** All unique filenames are held on a linked list headed by this
 31241  ** variable:
 31242  */
 31243  static struct vxworksFileId *vxworksFileList = 0;
 31244  
 31245  /*
 31246  ** Simplify a filename into its canonical form
 31247  ** by making the following changes:
 31248  **
 31249  **  * removing any trailing and duplicate /
 31250  **  * convert /./ into just /
 31251  **  * convert /A/../ where A is any simple name into just /
 31252  **
 31253  ** Changes are made in-place.  Return the new name length.
 31254  **
 31255  ** The original filename is in z[0..n-1].  Return the number of
 31256  ** characters in the simplified name.
 31257  */
 31258  static int vxworksSimplifyName(char *z, int n){
 31259    int i, j;
 31260    while( n>1 && z[n-1]=='/' ){ n--; }
 31261    for(i=j=0; i<n; i++){
 31262      if( z[i]=='/' ){
 31263        if( z[i+1]=='/' ) continue;
 31264        if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
 31265          i += 1;
 31266          continue;
 31267        }
 31268        if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
 31269          while( j>0 && z[j-1]!='/' ){ j--; }
 31270          if( j>0 ){ j--; }
 31271          i += 2;
 31272          continue;
 31273        }
 31274      }
 31275      z[j++] = z[i];
 31276    }
 31277    z[j] = 0;
 31278    return j;
 31279  }
 31280  
 31281  /*
 31282  ** Find a unique file ID for the given absolute pathname.  Return
 31283  ** a pointer to the vxworksFileId object.  This pointer is the unique
 31284  ** file ID.
 31285  **
 31286  ** The nRef field of the vxworksFileId object is incremented before
 31287  ** the object is returned.  A new vxworksFileId object is created
 31288  ** and added to the global list if necessary.
 31289  **
 31290  ** If a memory allocation error occurs, return NULL.
 31291  */
 31292  static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
 31293    struct vxworksFileId *pNew;         /* search key and new file ID */
 31294    struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
 31295    int n;                              /* Length of zAbsoluteName string */
 31296  
 31297    assert( zAbsoluteName[0]=='/' );
 31298    n = (int)strlen(zAbsoluteName);
 31299    pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
 31300    if( pNew==0 ) return 0;
 31301    pNew->zCanonicalName = (char*)&pNew[1];
 31302    memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
 31303    n = vxworksSimplifyName(pNew->zCanonicalName, n);
 31304  
 31305    /* Search for an existing entry that matching the canonical name.
 31306    ** If found, increment the reference count and return a pointer to
 31307    ** the existing file ID.
 31308    */
 31309    unixEnterMutex();
 31310    for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
 31311      if( pCandidate->nName==n 
 31312       && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
 31313      ){
 31314         sqlite3_free(pNew);
 31315         pCandidate->nRef++;
 31316         unixLeaveMutex();
 31317         return pCandidate;
 31318      }
 31319    }
 31320  
 31321    /* No match was found.  We will make a new file ID */
 31322    pNew->nRef = 1;
 31323    pNew->nName = n;
 31324    pNew->pNext = vxworksFileList;
 31325    vxworksFileList = pNew;
 31326    unixLeaveMutex();
 31327    return pNew;
 31328  }
 31329  
 31330  /*
 31331  ** Decrement the reference count on a vxworksFileId object.  Free
 31332  ** the object when the reference count reaches zero.
 31333  */
 31334  static void vxworksReleaseFileId(struct vxworksFileId *pId){
 31335    unixEnterMutex();
 31336    assert( pId->nRef>0 );
 31337    pId->nRef--;
 31338    if( pId->nRef==0 ){
 31339      struct vxworksFileId **pp;
 31340      for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
 31341      assert( *pp==pId );
 31342      *pp = pId->pNext;
 31343      sqlite3_free(pId);
 31344    }
 31345    unixLeaveMutex();
 31346  }
 31347  #endif /* OS_VXWORKS */
 31348  /*************** End of Unique File ID Utility Used By VxWorks ****************
 31349  ******************************************************************************/
 31350  
 31351  
 31352  /******************************************************************************
 31353  *************************** Posix Advisory Locking ****************************
 31354  **
 31355  ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
 31356  ** section 6.5.2.2 lines 483 through 490 specify that when a process
 31357  ** sets or clears a lock, that operation overrides any prior locks set
 31358  ** by the same process.  It does not explicitly say so, but this implies
 31359  ** that it overrides locks set by the same process using a different
 31360  ** file descriptor.  Consider this test case:
 31361  **
 31362  **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
 31363  **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
 31364  **
 31365  ** Suppose ./file1 and ./file2 are really the same file (because
 31366  ** one is a hard or symbolic link to the other) then if you set
 31367  ** an exclusive lock on fd1, then try to get an exclusive lock
 31368  ** on fd2, it works.  I would have expected the second lock to
 31369  ** fail since there was already a lock on the file due to fd1.
 31370  ** But not so.  Since both locks came from the same process, the
 31371  ** second overrides the first, even though they were on different
 31372  ** file descriptors opened on different file names.
 31373  **
 31374  ** This means that we cannot use POSIX locks to synchronize file access
 31375  ** among competing threads of the same process.  POSIX locks will work fine
 31376  ** to synchronize access for threads in separate processes, but not
 31377  ** threads within the same process.
 31378  **
 31379  ** To work around the problem, SQLite has to manage file locks internally
 31380  ** on its own.  Whenever a new database is opened, we have to find the
 31381  ** specific inode of the database file (the inode is determined by the
 31382  ** st_dev and st_ino fields of the stat structure that fstat() fills in)
 31383  ** and check for locks already existing on that inode.  When locks are
 31384  ** created or removed, we have to look at our own internal record of the
 31385  ** locks to see if another thread has previously set a lock on that same
 31386  ** inode.
 31387  **
 31388  ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
 31389  ** For VxWorks, we have to use the alternative unique ID system based on
 31390  ** canonical filename and implemented in the previous division.)
 31391  **
 31392  ** The sqlite3_file structure for POSIX is no longer just an integer file
 31393  ** descriptor.  It is now a structure that holds the integer file
 31394  ** descriptor and a pointer to a structure that describes the internal
 31395  ** locks on the corresponding inode.  There is one locking structure
 31396  ** per inode, so if the same inode is opened twice, both unixFile structures
 31397  ** point to the same locking structure.  The locking structure keeps
 31398  ** a reference count (so we will know when to delete it) and a "cnt"
 31399  ** field that tells us its internal lock status.  cnt==0 means the
 31400  ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
 31401  ** cnt>0 means there are cnt shared locks on the file.
 31402  **
 31403  ** Any attempt to lock or unlock a file first checks the locking
 31404  ** structure.  The fcntl() system call is only invoked to set a 
 31405  ** POSIX lock if the internal lock structure transitions between
 31406  ** a locked and an unlocked state.
 31407  **
 31408  ** But wait:  there are yet more problems with POSIX advisory locks.
 31409  **
 31410  ** If you close a file descriptor that points to a file that has locks,
 31411  ** all locks on that file that are owned by the current process are
 31412  ** released.  To work around this problem, each unixInodeInfo object
 31413  ** maintains a count of the number of pending locks on tha inode.
 31414  ** When an attempt is made to close an unixFile, if there are
 31415  ** other unixFile open on the same inode that are holding locks, the call
 31416  ** to close() the file descriptor is deferred until all of the locks clear.
 31417  ** The unixInodeInfo structure keeps a list of file descriptors that need to
 31418  ** be closed and that list is walked (and cleared) when the last lock
 31419  ** clears.
 31420  **
 31421  ** Yet another problem:  LinuxThreads do not play well with posix locks.
 31422  **
 31423  ** Many older versions of linux use the LinuxThreads library which is
 31424  ** not posix compliant.  Under LinuxThreads, a lock created by thread
 31425  ** A cannot be modified or overridden by a different thread B.
 31426  ** Only thread A can modify the lock.  Locking behavior is correct
 31427  ** if the appliation uses the newer Native Posix Thread Library (NPTL)
 31428  ** on linux - with NPTL a lock created by thread A can override locks
 31429  ** in thread B.  But there is no way to know at compile-time which
 31430  ** threading library is being used.  So there is no way to know at
 31431  ** compile-time whether or not thread A can override locks on thread B.
 31432  ** One has to do a run-time check to discover the behavior of the
 31433  ** current process.
 31434  **
 31435  ** SQLite used to support LinuxThreads.  But support for LinuxThreads
 31436  ** was dropped beginning with version 3.7.0.  SQLite will still work with
 31437  ** LinuxThreads provided that (1) there is no more than one connection 
 31438  ** per database file in the same process and (2) database connections
 31439  ** do not move across threads.
 31440  */
 31441  
 31442  /*
 31443  ** An instance of the following structure serves as the key used
 31444  ** to locate a particular unixInodeInfo object.
 31445  */
 31446  struct unixFileId {
 31447    dev_t dev;                  /* Device number */
 31448  #if OS_VXWORKS
 31449    struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
 31450  #else
 31451    /* We are told that some versions of Android contain a bug that
 31452    ** sizes ino_t at only 32-bits instead of 64-bits. (See
 31453    ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
 31454    ** To work around this, always allocate 64-bits for the inode number.  
 31455    ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
 31456    ** but that should not be a big deal. */
 31457    /* WAS:  ino_t ino;   */
 31458    u64 ino;                   /* Inode number */
 31459  #endif
 31460  };
 31461  
 31462  /*
 31463  ** An instance of the following structure is allocated for each open
 31464  ** inode.  Or, on LinuxThreads, there is one of these structures for
 31465  ** each inode opened by each thread.
 31466  **
 31467  ** A single inode can have multiple file descriptors, so each unixFile
 31468  ** structure contains a pointer to an instance of this object and this
 31469  ** object keeps a count of the number of unixFile pointing to it.
 31470  */
 31471  struct unixInodeInfo {
 31472    struct unixFileId fileId;       /* The lookup key */
 31473    int nShared;                    /* Number of SHARED locks held */
 31474    unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
 31475    unsigned char bProcessLock;     /* An exclusive process lock is held */
 31476    int nRef;                       /* Number of pointers to this structure */
 31477    unixShmNode *pShmNode;          /* Shared memory associated with this inode */
 31478    int nLock;                      /* Number of outstanding file locks */
 31479    UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
 31480    unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
 31481    unixInodeInfo *pPrev;           /*    .... doubly linked */
 31482  #if SQLITE_ENABLE_LOCKING_STYLE
 31483    unsigned long long sharedByte;  /* for AFP simulated shared lock */
 31484  #endif
 31485  #if OS_VXWORKS
 31486    sem_t *pSem;                    /* Named POSIX semaphore */
 31487    char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
 31488  #endif
 31489  };
 31490  
 31491  /*
 31492  ** A lists of all unixInodeInfo objects.
 31493  */
 31494  static unixInodeInfo *inodeList = 0;  /* All unixInodeInfo objects */
 31495  static unsigned int nUnusedFd = 0;    /* Total unused file descriptors */
 31496  
 31497  /*
 31498  **
 31499  ** This function - unixLogErrorAtLine(), is only ever called via the macro
 31500  ** unixLogError().
 31501  **
 31502  ** It is invoked after an error occurs in an OS function and errno has been
 31503  ** set. It logs a message using sqlite3_log() containing the current value of
 31504  ** errno and, if possible, the human-readable equivalent from strerror() or
 31505  ** strerror_r().
 31506  **
 31507  ** The first argument passed to the macro should be the error code that
 31508  ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
 31509  ** The two subsequent arguments should be the name of the OS function that
 31510  ** failed (e.g. "unlink", "open") and the associated file-system path,
 31511  ** if any.
 31512  */
 31513  #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
 31514  static int unixLogErrorAtLine(
 31515    int errcode,                    /* SQLite error code */
 31516    const char *zFunc,              /* Name of OS function that failed */
 31517    const char *zPath,              /* File path associated with error */
 31518    int iLine                       /* Source line number where error occurred */
 31519  ){
 31520    char *zErr;                     /* Message from strerror() or equivalent */
 31521    int iErrno = errno;             /* Saved syscall error number */
 31522  
 31523    /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
 31524    ** the strerror() function to obtain the human-readable error message
 31525    ** equivalent to errno. Otherwise, use strerror_r().
 31526    */ 
 31527  #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
 31528    char aErr[80];
 31529    memset(aErr, 0, sizeof(aErr));
 31530    zErr = aErr;
 31531  
 31532    /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
 31533    ** assume that the system provides the GNU version of strerror_r() that
 31534    ** returns a pointer to a buffer containing the error message. That pointer 
 31535    ** may point to aErr[], or it may point to some static storage somewhere. 
 31536    ** Otherwise, assume that the system provides the POSIX version of 
 31537    ** strerror_r(), which always writes an error message into aErr[].
 31538    **
 31539    ** If the code incorrectly assumes that it is the POSIX version that is
 31540    ** available, the error message will often be an empty string. Not a
 31541    ** huge problem. Incorrectly concluding that the GNU version is available 
 31542    ** could lead to a segfault though.
 31543    */
 31544  #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
 31545    zErr = 
 31546  # endif
 31547    strerror_r(iErrno, aErr, sizeof(aErr)-1);
 31548  
 31549  #elif SQLITE_THREADSAFE
 31550    /* This is a threadsafe build, but strerror_r() is not available. */
 31551    zErr = "";
 31552  #else
 31553    /* Non-threadsafe build, use strerror(). */
 31554    zErr = strerror(iErrno);
 31555  #endif
 31556  
 31557    if( zPath==0 ) zPath = "";
 31558    sqlite3_log(errcode,
 31559        "os_unix.c:%d: (%d) %s(%s) - %s",
 31560        iLine, iErrno, zFunc, zPath, zErr
 31561    );
 31562  
 31563    return errcode;
 31564  }
 31565  
 31566  /*
 31567  ** Close a file descriptor.
 31568  **
 31569  ** We assume that close() almost always works, since it is only in a
 31570  ** very sick application or on a very sick platform that it might fail.
 31571  ** If it does fail, simply leak the file descriptor, but do log the
 31572  ** error.
 31573  **
 31574  ** Note that it is not safe to retry close() after EINTR since the
 31575  ** file descriptor might have already been reused by another thread.
 31576  ** So we don't even try to recover from an EINTR.  Just log the error
 31577  ** and move on.
 31578  */
 31579  static void robust_close(unixFile *pFile, int h, int lineno){
 31580    if( osClose(h) ){
 31581      unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
 31582                         pFile ? pFile->zPath : 0, lineno);
 31583    }
 31584  }
 31585  
 31586  /*
 31587  ** Set the pFile->lastErrno.  Do this in a subroutine as that provides
 31588  ** a convenient place to set a breakpoint.
 31589  */
 31590  static void storeLastErrno(unixFile *pFile, int error){
 31591    pFile->lastErrno = error;
 31592  }
 31593  
 31594  /*
 31595  ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
 31596  */ 
 31597  static void closePendingFds(unixFile *pFile){
 31598    unixInodeInfo *pInode = pFile->pInode;
 31599    UnixUnusedFd *p;
 31600    UnixUnusedFd *pNext;
 31601    for(p=pInode->pUnused; p; p=pNext){
 31602      pNext = p->pNext;
 31603      robust_close(pFile, p->fd, __LINE__);
 31604      sqlite3_free(p);
 31605      nUnusedFd--;
 31606    }
 31607    pInode->pUnused = 0;
 31608  }
 31609  
 31610  /*
 31611  ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
 31612  **
 31613  ** The mutex entered using the unixEnterMutex() function must be held
 31614  ** when this function is called.
 31615  */
 31616  static void releaseInodeInfo(unixFile *pFile){
 31617    unixInodeInfo *pInode = pFile->pInode;
 31618    assert( unixMutexHeld() );
 31619    if( ALWAYS(pInode) ){
 31620      pInode->nRef--;
 31621      if( pInode->nRef==0 ){
 31622        assert( pInode->pShmNode==0 );
 31623        closePendingFds(pFile);
 31624        if( pInode->pPrev ){
 31625          assert( pInode->pPrev->pNext==pInode );
 31626          pInode->pPrev->pNext = pInode->pNext;
 31627        }else{
 31628          assert( inodeList==pInode );
 31629          inodeList = pInode->pNext;
 31630        }
 31631        if( pInode->pNext ){
 31632          assert( pInode->pNext->pPrev==pInode );
 31633          pInode->pNext->pPrev = pInode->pPrev;
 31634        }
 31635        sqlite3_free(pInode);
 31636      }
 31637    }
 31638    assert( inodeList!=0 || nUnusedFd==0 );
 31639  }
 31640  
 31641  /*
 31642  ** Given a file descriptor, locate the unixInodeInfo object that
 31643  ** describes that file descriptor.  Create a new one if necessary.  The
 31644  ** return value might be uninitialized if an error occurs.
 31645  **
 31646  ** The mutex entered using the unixEnterMutex() function must be held
 31647  ** when this function is called.
 31648  **
 31649  ** Return an appropriate error code.
 31650  */
 31651  static int findInodeInfo(
 31652    unixFile *pFile,               /* Unix file with file desc used in the key */
 31653    unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
 31654  ){
 31655    int rc;                        /* System call return code */
 31656    int fd;                        /* The file descriptor for pFile */
 31657    struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
 31658    struct stat statbuf;           /* Low-level file information */
 31659    unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
 31660  
 31661    assert( unixMutexHeld() );
 31662  
 31663    /* Get low-level information about the file that we can used to
 31664    ** create a unique name for the file.
 31665    */
 31666    fd = pFile->h;
 31667    rc = osFstat(fd, &statbuf);
 31668    if( rc!=0 ){
 31669      storeLastErrno(pFile, errno);
 31670  #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
 31671      if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
 31672  #endif
 31673      return SQLITE_IOERR;
 31674    }
 31675  
 31676  #ifdef __APPLE__
 31677    /* On OS X on an msdos filesystem, the inode number is reported
 31678    ** incorrectly for zero-size files.  See ticket #3260.  To work
 31679    ** around this problem (we consider it a bug in OS X, not SQLite)
 31680    ** we always increase the file size to 1 by writing a single byte
 31681    ** prior to accessing the inode number.  The one byte written is
 31682    ** an ASCII 'S' character which also happens to be the first byte
 31683    ** in the header of every SQLite database.  In this way, if there
 31684    ** is a race condition such that another thread has already populated
 31685    ** the first page of the database, no damage is done.
 31686    */
 31687    if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
 31688      do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
 31689      if( rc!=1 ){
 31690        storeLastErrno(pFile, errno);
 31691        return SQLITE_IOERR;
 31692      }
 31693      rc = osFstat(fd, &statbuf);
 31694      if( rc!=0 ){
 31695        storeLastErrno(pFile, errno);
 31696        return SQLITE_IOERR;
 31697      }
 31698    }
 31699  #endif
 31700  
 31701    memset(&fileId, 0, sizeof(fileId));
 31702    fileId.dev = statbuf.st_dev;
 31703  #if OS_VXWORKS
 31704    fileId.pId = pFile->pId;
 31705  #else
 31706    fileId.ino = (u64)statbuf.st_ino;
 31707  #endif
 31708    assert( inodeList!=0 || nUnusedFd==0 );
 31709    pInode = inodeList;
 31710    while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
 31711      pInode = pInode->pNext;
 31712    }
 31713    if( pInode==0 ){
 31714      pInode = sqlite3_malloc64( sizeof(*pInode) );
 31715      if( pInode==0 ){
 31716        return SQLITE_NOMEM_BKPT;
 31717      }
 31718      memset(pInode, 0, sizeof(*pInode));
 31719      memcpy(&pInode->fileId, &fileId, sizeof(fileId));
 31720      pInode->nRef = 1;
 31721      pInode->pNext = inodeList;
 31722      pInode->pPrev = 0;
 31723      if( inodeList ) inodeList->pPrev = pInode;
 31724      inodeList = pInode;
 31725    }else{
 31726      pInode->nRef++;
 31727    }
 31728    *ppInode = pInode;
 31729    return SQLITE_OK;
 31730  }
 31731  
 31732  /*
 31733  ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
 31734  */
 31735  static int fileHasMoved(unixFile *pFile){
 31736  #if OS_VXWORKS
 31737    return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
 31738  #else
 31739    struct stat buf;
 31740    return pFile->pInode!=0 &&
 31741        (osStat(pFile->zPath, &buf)!=0 
 31742           || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
 31743  #endif
 31744  }
 31745  
 31746  
 31747  /*
 31748  ** Check a unixFile that is a database.  Verify the following:
 31749  **
 31750  ** (1) There is exactly one hard link on the file
 31751  ** (2) The file is not a symbolic link
 31752  ** (3) The file has not been renamed or unlinked
 31753  **
 31754  ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
 31755  */
 31756  static void verifyDbFile(unixFile *pFile){
 31757    struct stat buf;
 31758    int rc;
 31759  
 31760    /* These verifications occurs for the main database only */
 31761    if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
 31762  
 31763    rc = osFstat(pFile->h, &buf);
 31764    if( rc!=0 ){
 31765      sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
 31766      return;
 31767    }
 31768    if( buf.st_nlink==0 ){
 31769      sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
 31770      return;
 31771    }
 31772    if( buf.st_nlink>1 ){
 31773      sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
 31774      return;
 31775    }
 31776    if( fileHasMoved(pFile) ){
 31777      sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
 31778      return;
 31779    }
 31780  }
 31781  
 31782  
 31783  /*
 31784  ** This routine checks if there is a RESERVED lock held on the specified
 31785  ** file by this or any other process. If such a lock is held, set *pResOut
 31786  ** to a non-zero value otherwise *pResOut is set to zero.  The return value
 31787  ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
 31788  */
 31789  static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
 31790    int rc = SQLITE_OK;
 31791    int reserved = 0;
 31792    unixFile *pFile = (unixFile*)id;
 31793  
 31794    SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
 31795  
 31796    assert( pFile );
 31797    assert( pFile->eFileLock<=SHARED_LOCK );
 31798    unixEnterMutex(); /* Because pFile->pInode is shared across threads */
 31799  
 31800    /* Check if a thread in this process holds such a lock */
 31801    if( pFile->pInode->eFileLock>SHARED_LOCK ){
 31802      reserved = 1;
 31803    }
 31804  
 31805    /* Otherwise see if some other process holds it.
 31806    */
 31807  #ifndef __DJGPP__
 31808    if( !reserved && !pFile->pInode->bProcessLock ){
 31809      struct flock lock;
 31810      lock.l_whence = SEEK_SET;
 31811      lock.l_start = RESERVED_BYTE;
 31812      lock.l_len = 1;
 31813      lock.l_type = F_WRLCK;
 31814      if( osFcntl(pFile->h, F_GETLK, &lock) ){
 31815        rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
 31816        storeLastErrno(pFile, errno);
 31817      } else if( lock.l_type!=F_UNLCK ){
 31818        reserved = 1;
 31819      }
 31820    }
 31821  #endif
 31822    
 31823    unixLeaveMutex();
 31824    OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
 31825  
 31826    *pResOut = reserved;
 31827    return rc;
 31828  }
 31829  
 31830  /*
 31831  ** Attempt to set a system-lock on the file pFile.  The lock is 
 31832  ** described by pLock.
 31833  **
 31834  ** If the pFile was opened read/write from unix-excl, then the only lock
 31835  ** ever obtained is an exclusive lock, and it is obtained exactly once
 31836  ** the first time any lock is attempted.  All subsequent system locking
 31837  ** operations become no-ops.  Locking operations still happen internally,
 31838  ** in order to coordinate access between separate database connections
 31839  ** within this process, but all of that is handled in memory and the
 31840  ** operating system does not participate.
 31841  **
 31842  ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
 31843  ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
 31844  ** and is read-only.
 31845  **
 31846  ** Zero is returned if the call completes successfully, or -1 if a call
 31847  ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
 31848  */
 31849  static int unixFileLock(unixFile *pFile, struct flock *pLock){
 31850    int rc;
 31851    unixInodeInfo *pInode = pFile->pInode;
 31852    assert( unixMutexHeld() );
 31853    assert( pInode!=0 );
 31854    if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
 31855      if( pInode->bProcessLock==0 ){
 31856        struct flock lock;
 31857        assert( pInode->nLock==0 );
 31858        lock.l_whence = SEEK_SET;
 31859        lock.l_start = SHARED_FIRST;
 31860        lock.l_len = SHARED_SIZE;
 31861        lock.l_type = F_WRLCK;
 31862        rc = osFcntl(pFile->h, F_SETLK, &lock);
 31863        if( rc<0 ) return rc;
 31864        pInode->bProcessLock = 1;
 31865        pInode->nLock++;
 31866      }else{
 31867        rc = 0;
 31868      }
 31869    }else{
 31870      rc = osFcntl(pFile->h, F_SETLK, pLock);
 31871    }
 31872    return rc;
 31873  }
 31874  
 31875  /*
 31876  ** Lock the file with the lock specified by parameter eFileLock - one
 31877  ** of the following:
 31878  **
 31879  **     (1) SHARED_LOCK
 31880  **     (2) RESERVED_LOCK
 31881  **     (3) PENDING_LOCK
 31882  **     (4) EXCLUSIVE_LOCK
 31883  **
 31884  ** Sometimes when requesting one lock state, additional lock states
 31885  ** are inserted in between.  The locking might fail on one of the later
 31886  ** transitions leaving the lock state different from what it started but
 31887  ** still short of its goal.  The following chart shows the allowed
 31888  ** transitions and the inserted intermediate states:
 31889  **
 31890  **    UNLOCKED -> SHARED
 31891  **    SHARED -> RESERVED
 31892  **    SHARED -> (PENDING) -> EXCLUSIVE
 31893  **    RESERVED -> (PENDING) -> EXCLUSIVE
 31894  **    PENDING -> EXCLUSIVE
 31895  **
 31896  ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
 31897  ** routine to lower a locking level.
 31898  */
 31899  static int unixLock(sqlite3_file *id, int eFileLock){
 31900    /* The following describes the implementation of the various locks and
 31901    ** lock transitions in terms of the POSIX advisory shared and exclusive
 31902    ** lock primitives (called read-locks and write-locks below, to avoid
 31903    ** confusion with SQLite lock names). The algorithms are complicated
 31904    ** slightly in order to be compatible with Windows95 systems simultaneously
 31905    ** accessing the same database file, in case that is ever required.
 31906    **
 31907    ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
 31908    ** byte', each single bytes at well known offsets, and the 'shared byte
 31909    ** range', a range of 510 bytes at a well known offset.
 31910    **
 31911    ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
 31912    ** byte'.  If this is successful, 'shared byte range' is read-locked
 31913    ** and the lock on the 'pending byte' released.  (Legacy note:  When
 31914    ** SQLite was first developed, Windows95 systems were still very common,
 31915    ** and Widnows95 lacks a shared-lock capability.  So on Windows95, a
 31916    ** single randomly selected by from the 'shared byte range' is locked.
 31917    ** Windows95 is now pretty much extinct, but this work-around for the
 31918    ** lack of shared-locks on Windows95 lives on, for backwards
 31919    ** compatibility.)
 31920    **
 31921    ** A process may only obtain a RESERVED lock after it has a SHARED lock.
 31922    ** A RESERVED lock is implemented by grabbing a write-lock on the
 31923    ** 'reserved byte'. 
 31924    **
 31925    ** A process may only obtain a PENDING lock after it has obtained a
 31926    ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
 31927    ** on the 'pending byte'. This ensures that no new SHARED locks can be
 31928    ** obtained, but existing SHARED locks are allowed to persist. A process
 31929    ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
 31930    ** This property is used by the algorithm for rolling back a journal file
 31931    ** after a crash.
 31932    **
 31933    ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
 31934    ** implemented by obtaining a write-lock on the entire 'shared byte
 31935    ** range'. Since all other locks require a read-lock on one of the bytes
 31936    ** within this range, this ensures that no other locks are held on the
 31937    ** database. 
 31938    */
 31939    int rc = SQLITE_OK;
 31940    unixFile *pFile = (unixFile*)id;
 31941    unixInodeInfo *pInode;
 31942    struct flock lock;
 31943    int tErrno = 0;
 31944  
 31945    assert( pFile );
 31946    OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
 31947        azFileLock(eFileLock), azFileLock(pFile->eFileLock),
 31948        azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
 31949        osGetpid(0)));
 31950  
 31951    /* If there is already a lock of this type or more restrictive on the
 31952    ** unixFile, do nothing. Don't use the end_lock: exit path, as
 31953    ** unixEnterMutex() hasn't been called yet.
 31954    */
 31955    if( pFile->eFileLock>=eFileLock ){
 31956      OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
 31957              azFileLock(eFileLock)));
 31958      return SQLITE_OK;
 31959    }
 31960  
 31961    /* Make sure the locking sequence is correct.
 31962    **  (1) We never move from unlocked to anything higher than shared lock.
 31963    **  (2) SQLite never explicitly requests a pendig lock.
 31964    **  (3) A shared lock is always held when a reserve lock is requested.
 31965    */
 31966    assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
 31967    assert( eFileLock!=PENDING_LOCK );
 31968    assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
 31969  
 31970    /* This mutex is needed because pFile->pInode is shared across threads
 31971    */
 31972    unixEnterMutex();
 31973    pInode = pFile->pInode;
 31974  
 31975    /* If some thread using this PID has a lock via a different unixFile*
 31976    ** handle that precludes the requested lock, return BUSY.
 31977    */
 31978    if( (pFile->eFileLock!=pInode->eFileLock && 
 31979            (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
 31980    ){
 31981      rc = SQLITE_BUSY;
 31982      goto end_lock;
 31983    }
 31984  
 31985    /* If a SHARED lock is requested, and some thread using this PID already
 31986    ** has a SHARED or RESERVED lock, then increment reference counts and
 31987    ** return SQLITE_OK.
 31988    */
 31989    if( eFileLock==SHARED_LOCK && 
 31990        (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
 31991      assert( eFileLock==SHARED_LOCK );
 31992      assert( pFile->eFileLock==0 );
 31993      assert( pInode->nShared>0 );
 31994      pFile->eFileLock = SHARED_LOCK;
 31995      pInode->nShared++;
 31996      pInode->nLock++;
 31997      goto end_lock;
 31998    }
 31999  
 32000  
 32001    /* A PENDING lock is needed before acquiring a SHARED lock and before
 32002    ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
 32003    ** be released.
 32004    */
 32005    lock.l_len = 1L;
 32006    lock.l_whence = SEEK_SET;
 32007    if( eFileLock==SHARED_LOCK 
 32008        || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
 32009    ){
 32010      lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
 32011      lock.l_start = PENDING_BYTE;
 32012      if( unixFileLock(pFile, &lock) ){
 32013        tErrno = errno;
 32014        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
 32015        if( rc!=SQLITE_BUSY ){
 32016          storeLastErrno(pFile, tErrno);
 32017        }
 32018        goto end_lock;
 32019      }
 32020    }
 32021  
 32022  
 32023    /* If control gets to this point, then actually go ahead and make
 32024    ** operating system calls for the specified lock.
 32025    */
 32026    if( eFileLock==SHARED_LOCK ){
 32027      assert( pInode->nShared==0 );
 32028      assert( pInode->eFileLock==0 );
 32029      assert( rc==SQLITE_OK );
 32030  
 32031      /* Now get the read-lock */
 32032      lock.l_start = SHARED_FIRST;
 32033      lock.l_len = SHARED_SIZE;
 32034      if( unixFileLock(pFile, &lock) ){
 32035        tErrno = errno;
 32036        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
 32037      }
 32038  
 32039      /* Drop the temporary PENDING lock */
 32040      lock.l_start = PENDING_BYTE;
 32041      lock.l_len = 1L;
 32042      lock.l_type = F_UNLCK;
 32043      if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
 32044        /* This could happen with a network mount */
 32045        tErrno = errno;
 32046        rc = SQLITE_IOERR_UNLOCK; 
 32047      }
 32048  
 32049      if( rc ){
 32050        if( rc!=SQLITE_BUSY ){
 32051          storeLastErrno(pFile, tErrno);
 32052        }
 32053        goto end_lock;
 32054      }else{
 32055        pFile->eFileLock = SHARED_LOCK;
 32056        pInode->nLock++;
 32057        pInode->nShared = 1;
 32058      }
 32059    }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
 32060      /* We are trying for an exclusive lock but another thread in this
 32061      ** same process is still holding a shared lock. */
 32062      rc = SQLITE_BUSY;
 32063    }else{
 32064      /* The request was for a RESERVED or EXCLUSIVE lock.  It is
 32065      ** assumed that there is a SHARED or greater lock on the file
 32066      ** already.
 32067      */
 32068      assert( 0!=pFile->eFileLock );
 32069      lock.l_type = F_WRLCK;
 32070  
 32071      assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
 32072      if( eFileLock==RESERVED_LOCK ){
 32073        lock.l_start = RESERVED_BYTE;
 32074        lock.l_len = 1L;
 32075      }else{
 32076        lock.l_start = SHARED_FIRST;
 32077        lock.l_len = SHARED_SIZE;
 32078      }
 32079  
 32080      if( unixFileLock(pFile, &lock) ){
 32081        tErrno = errno;
 32082        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
 32083        if( rc!=SQLITE_BUSY ){
 32084          storeLastErrno(pFile, tErrno);
 32085        }
 32086      }
 32087    }
 32088    
 32089  
 32090  #ifdef SQLITE_DEBUG
 32091    /* Set up the transaction-counter change checking flags when
 32092    ** transitioning from a SHARED to a RESERVED lock.  The change
 32093    ** from SHARED to RESERVED marks the beginning of a normal
 32094    ** write operation (not a hot journal rollback).
 32095    */
 32096    if( rc==SQLITE_OK
 32097     && pFile->eFileLock<=SHARED_LOCK
 32098     && eFileLock==RESERVED_LOCK
 32099    ){
 32100      pFile->transCntrChng = 0;
 32101      pFile->dbUpdate = 0;
 32102      pFile->inNormalWrite = 1;
 32103    }
 32104  #endif
 32105  
 32106  
 32107    if( rc==SQLITE_OK ){
 32108      pFile->eFileLock = eFileLock;
 32109      pInode->eFileLock = eFileLock;
 32110    }else if( eFileLock==EXCLUSIVE_LOCK ){
 32111      pFile->eFileLock = PENDING_LOCK;
 32112      pInode->eFileLock = PENDING_LOCK;
 32113    }
 32114  
 32115  end_lock:
 32116    unixLeaveMutex();
 32117    OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
 32118        rc==SQLITE_OK ? "ok" : "failed"));
 32119    return rc;
 32120  }
 32121  
 32122  /*
 32123  ** Add the file descriptor used by file handle pFile to the corresponding
 32124  ** pUnused list.
 32125  */
 32126  static void setPendingFd(unixFile *pFile){
 32127    unixInodeInfo *pInode = pFile->pInode;
 32128    UnixUnusedFd *p = pFile->pPreallocatedUnused;
 32129    p->pNext = pInode->pUnused;
 32130    pInode->pUnused = p;
 32131    pFile->h = -1;
 32132    pFile->pPreallocatedUnused = 0;
 32133    nUnusedFd++;
 32134  }
 32135  
 32136  /*
 32137  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 32138  ** must be either NO_LOCK or SHARED_LOCK.
 32139  **
 32140  ** If the locking level of the file descriptor is already at or below
 32141  ** the requested locking level, this routine is a no-op.
 32142  ** 
 32143  ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
 32144  ** the byte range is divided into 2 parts and the first part is unlocked then
 32145  ** set to a read lock, then the other part is simply unlocked.  This works 
 32146  ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
 32147  ** remove the write lock on a region when a read lock is set.
 32148  */
 32149  static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
 32150    unixFile *pFile = (unixFile*)id;
 32151    unixInodeInfo *pInode;
 32152    struct flock lock;
 32153    int rc = SQLITE_OK;
 32154  
 32155    assert( pFile );
 32156    OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
 32157        pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
 32158        osGetpid(0)));
 32159  
 32160    assert( eFileLock<=SHARED_LOCK );
 32161    if( pFile->eFileLock<=eFileLock ){
 32162      return SQLITE_OK;
 32163    }
 32164    unixEnterMutex();
 32165    pInode = pFile->pInode;
 32166    assert( pInode->nShared!=0 );
 32167    if( pFile->eFileLock>SHARED_LOCK ){
 32168      assert( pInode->eFileLock==pFile->eFileLock );
 32169  
 32170  #ifdef SQLITE_DEBUG
 32171      /* When reducing a lock such that other processes can start
 32172      ** reading the database file again, make sure that the
 32173      ** transaction counter was updated if any part of the database
 32174      ** file changed.  If the transaction counter is not updated,
 32175      ** other connections to the same file might not realize that
 32176      ** the file has changed and hence might not know to flush their
 32177      ** cache.  The use of a stale cache can lead to database corruption.
 32178      */
 32179      pFile->inNormalWrite = 0;
 32180  #endif
 32181  
 32182      /* downgrading to a shared lock on NFS involves clearing the write lock
 32183      ** before establishing the readlock - to avoid a race condition we downgrade
 32184      ** the lock in 2 blocks, so that part of the range will be covered by a 
 32185      ** write lock until the rest is covered by a read lock:
 32186      **  1:   [WWWWW]
 32187      **  2:   [....W]
 32188      **  3:   [RRRRW]
 32189      **  4:   [RRRR.]
 32190      */
 32191      if( eFileLock==SHARED_LOCK ){
 32192  #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
 32193        (void)handleNFSUnlock;
 32194        assert( handleNFSUnlock==0 );
 32195  #endif
 32196  #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 32197        if( handleNFSUnlock ){
 32198          int tErrno;               /* Error code from system call errors */
 32199          off_t divSize = SHARED_SIZE - 1;
 32200          
 32201          lock.l_type = F_UNLCK;
 32202          lock.l_whence = SEEK_SET;
 32203          lock.l_start = SHARED_FIRST;
 32204          lock.l_len = divSize;
 32205          if( unixFileLock(pFile, &lock)==(-1) ){
 32206            tErrno = errno;
 32207            rc = SQLITE_IOERR_UNLOCK;
 32208            storeLastErrno(pFile, tErrno);
 32209            goto end_unlock;
 32210          }
 32211          lock.l_type = F_RDLCK;
 32212          lock.l_whence = SEEK_SET;
 32213          lock.l_start = SHARED_FIRST;
 32214          lock.l_len = divSize;
 32215          if( unixFileLock(pFile, &lock)==(-1) ){
 32216            tErrno = errno;
 32217            rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
 32218            if( IS_LOCK_ERROR(rc) ){
 32219              storeLastErrno(pFile, tErrno);
 32220            }
 32221            goto end_unlock;
 32222          }
 32223          lock.l_type = F_UNLCK;
 32224          lock.l_whence = SEEK_SET;
 32225          lock.l_start = SHARED_FIRST+divSize;
 32226          lock.l_len = SHARED_SIZE-divSize;
 32227          if( unixFileLock(pFile, &lock)==(-1) ){
 32228            tErrno = errno;
 32229            rc = SQLITE_IOERR_UNLOCK;
 32230            storeLastErrno(pFile, tErrno);
 32231            goto end_unlock;
 32232          }
 32233        }else
 32234  #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
 32235        {
 32236          lock.l_type = F_RDLCK;
 32237          lock.l_whence = SEEK_SET;
 32238          lock.l_start = SHARED_FIRST;
 32239          lock.l_len = SHARED_SIZE;
 32240          if( unixFileLock(pFile, &lock) ){
 32241            /* In theory, the call to unixFileLock() cannot fail because another
 32242            ** process is holding an incompatible lock. If it does, this 
 32243            ** indicates that the other process is not following the locking
 32244            ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
 32245            ** SQLITE_BUSY would confuse the upper layer (in practice it causes 
 32246            ** an assert to fail). */ 
 32247            rc = SQLITE_IOERR_RDLOCK;
 32248            storeLastErrno(pFile, errno);
 32249            goto end_unlock;
 32250          }
 32251        }
 32252      }
 32253      lock.l_type = F_UNLCK;
 32254      lock.l_whence = SEEK_SET;
 32255      lock.l_start = PENDING_BYTE;
 32256      lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
 32257      if( unixFileLock(pFile, &lock)==0 ){
 32258        pInode->eFileLock = SHARED_LOCK;
 32259      }else{
 32260        rc = SQLITE_IOERR_UNLOCK;
 32261        storeLastErrno(pFile, errno);
 32262        goto end_unlock;
 32263      }
 32264    }
 32265    if( eFileLock==NO_LOCK ){
 32266      /* Decrement the shared lock counter.  Release the lock using an
 32267      ** OS call only when all threads in this same process have released
 32268      ** the lock.
 32269      */
 32270      pInode->nShared--;
 32271      if( pInode->nShared==0 ){
 32272        lock.l_type = F_UNLCK;
 32273        lock.l_whence = SEEK_SET;
 32274        lock.l_start = lock.l_len = 0L;
 32275        if( unixFileLock(pFile, &lock)==0 ){
 32276          pInode->eFileLock = NO_LOCK;
 32277        }else{
 32278          rc = SQLITE_IOERR_UNLOCK;
 32279          storeLastErrno(pFile, errno);
 32280          pInode->eFileLock = NO_LOCK;
 32281          pFile->eFileLock = NO_LOCK;
 32282        }
 32283      }
 32284  
 32285      /* Decrement the count of locks against this same file.  When the
 32286      ** count reaches zero, close any other file descriptors whose close
 32287      ** was deferred because of outstanding locks.
 32288      */
 32289      pInode->nLock--;
 32290      assert( pInode->nLock>=0 );
 32291      if( pInode->nLock==0 ){
 32292        closePendingFds(pFile);
 32293      }
 32294    }
 32295  
 32296  end_unlock:
 32297    unixLeaveMutex();
 32298    if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
 32299    return rc;
 32300  }
 32301  
 32302  /*
 32303  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 32304  ** must be either NO_LOCK or SHARED_LOCK.
 32305  **
 32306  ** If the locking level of the file descriptor is already at or below
 32307  ** the requested locking level, this routine is a no-op.
 32308  */
 32309  static int unixUnlock(sqlite3_file *id, int eFileLock){
 32310  #if SQLITE_MAX_MMAP_SIZE>0
 32311    assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
 32312  #endif
 32313    return posixUnlock(id, eFileLock, 0);
 32314  }
 32315  
 32316  #if SQLITE_MAX_MMAP_SIZE>0
 32317  static int unixMapfile(unixFile *pFd, i64 nByte);
 32318  static void unixUnmapfile(unixFile *pFd);
 32319  #endif
 32320  
 32321  /*
 32322  ** This function performs the parts of the "close file" operation 
 32323  ** common to all locking schemes. It closes the directory and file
 32324  ** handles, if they are valid, and sets all fields of the unixFile
 32325  ** structure to 0.
 32326  **
 32327  ** It is *not* necessary to hold the mutex when this routine is called,
 32328  ** even on VxWorks.  A mutex will be acquired on VxWorks by the
 32329  ** vxworksReleaseFileId() routine.
 32330  */
 32331  static int closeUnixFile(sqlite3_file *id){
 32332    unixFile *pFile = (unixFile*)id;
 32333  #if SQLITE_MAX_MMAP_SIZE>0
 32334    unixUnmapfile(pFile);
 32335  #endif
 32336    if( pFile->h>=0 ){
 32337      robust_close(pFile, pFile->h, __LINE__);
 32338      pFile->h = -1;
 32339    }
 32340  #if OS_VXWORKS
 32341    if( pFile->pId ){
 32342      if( pFile->ctrlFlags & UNIXFILE_DELETE ){
 32343        osUnlink(pFile->pId->zCanonicalName);
 32344      }
 32345      vxworksReleaseFileId(pFile->pId);
 32346      pFile->pId = 0;
 32347    }
 32348  #endif
 32349  #ifdef SQLITE_UNLINK_AFTER_CLOSE
 32350    if( pFile->ctrlFlags & UNIXFILE_DELETE ){
 32351      osUnlink(pFile->zPath);
 32352      sqlite3_free(*(char**)&pFile->zPath);
 32353      pFile->zPath = 0;
 32354    }
 32355  #endif
 32356    OSTRACE(("CLOSE   %-3d\n", pFile->h));
 32357    OpenCounter(-1);
 32358    sqlite3_free(pFile->pPreallocatedUnused);
 32359    memset(pFile, 0, sizeof(unixFile));
 32360    return SQLITE_OK;
 32361  }
 32362  
 32363  /*
 32364  ** Close a file.
 32365  */
 32366  static int unixClose(sqlite3_file *id){
 32367    int rc = SQLITE_OK;
 32368    unixFile *pFile = (unixFile *)id;
 32369    verifyDbFile(pFile);
 32370    unixUnlock(id, NO_LOCK);
 32371    unixEnterMutex();
 32372  
 32373    /* unixFile.pInode is always valid here. Otherwise, a different close
 32374    ** routine (e.g. nolockClose()) would be called instead.
 32375    */
 32376    assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
 32377    if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
 32378      /* If there are outstanding locks, do not actually close the file just
 32379      ** yet because that would clear those locks.  Instead, add the file
 32380      ** descriptor to pInode->pUnused list.  It will be automatically closed 
 32381      ** when the last lock is cleared.
 32382      */
 32383      setPendingFd(pFile);
 32384    }
 32385    releaseInodeInfo(pFile);
 32386    rc = closeUnixFile(id);
 32387    unixLeaveMutex();
 32388    return rc;
 32389  }
 32390  
 32391  /************** End of the posix advisory lock implementation *****************
 32392  ******************************************************************************/
 32393  
 32394  /******************************************************************************
 32395  ****************************** No-op Locking **********************************
 32396  **
 32397  ** Of the various locking implementations available, this is by far the
 32398  ** simplest:  locking is ignored.  No attempt is made to lock the database
 32399  ** file for reading or writing.
 32400  **
 32401  ** This locking mode is appropriate for use on read-only databases
 32402  ** (ex: databases that are burned into CD-ROM, for example.)  It can
 32403  ** also be used if the application employs some external mechanism to
 32404  ** prevent simultaneous access of the same database by two or more
 32405  ** database connections.  But there is a serious risk of database
 32406  ** corruption if this locking mode is used in situations where multiple
 32407  ** database connections are accessing the same database file at the same
 32408  ** time and one or more of those connections are writing.
 32409  */
 32410  
 32411  static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
 32412    UNUSED_PARAMETER(NotUsed);
 32413    *pResOut = 0;
 32414    return SQLITE_OK;
 32415  }
 32416  static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
 32417    UNUSED_PARAMETER2(NotUsed, NotUsed2);
 32418    return SQLITE_OK;
 32419  }
 32420  static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
 32421    UNUSED_PARAMETER2(NotUsed, NotUsed2);
 32422    return SQLITE_OK;
 32423  }
 32424  
 32425  /*
 32426  ** Close the file.
 32427  */
 32428  static int nolockClose(sqlite3_file *id) {
 32429    return closeUnixFile(id);
 32430  }
 32431  
 32432  /******************* End of the no-op lock implementation *********************
 32433  ******************************************************************************/
 32434  
 32435  /******************************************************************************
 32436  ************************* Begin dot-file Locking ******************************
 32437  **
 32438  ** The dotfile locking implementation uses the existence of separate lock
 32439  ** files (really a directory) to control access to the database.  This works
 32440  ** on just about every filesystem imaginable.  But there are serious downsides:
 32441  **
 32442  **    (1)  There is zero concurrency.  A single reader blocks all other
 32443  **         connections from reading or writing the database.
 32444  **
 32445  **    (2)  An application crash or power loss can leave stale lock files
 32446  **         sitting around that need to be cleared manually.
 32447  **
 32448  ** Nevertheless, a dotlock is an appropriate locking mode for use if no
 32449  ** other locking strategy is available.
 32450  **
 32451  ** Dotfile locking works by creating a subdirectory in the same directory as
 32452  ** the database and with the same name but with a ".lock" extension added.
 32453  ** The existence of a lock directory implies an EXCLUSIVE lock.  All other
 32454  ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
 32455  */
 32456  
 32457  /*
 32458  ** The file suffix added to the data base filename in order to create the
 32459  ** lock directory.
 32460  */
 32461  #define DOTLOCK_SUFFIX ".lock"
 32462  
 32463  /*
 32464  ** This routine checks if there is a RESERVED lock held on the specified
 32465  ** file by this or any other process. If such a lock is held, set *pResOut
 32466  ** to a non-zero value otherwise *pResOut is set to zero.  The return value
 32467  ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
 32468  **
 32469  ** In dotfile locking, either a lock exists or it does not.  So in this
 32470  ** variation of CheckReservedLock(), *pResOut is set to true if any lock
 32471  ** is held on the file and false if the file is unlocked.
 32472  */
 32473  static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
 32474    int rc = SQLITE_OK;
 32475    int reserved = 0;
 32476    unixFile *pFile = (unixFile*)id;
 32477  
 32478    SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
 32479    
 32480    assert( pFile );
 32481    reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
 32482    OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
 32483    *pResOut = reserved;
 32484    return rc;
 32485  }
 32486  
 32487  /*
 32488  ** Lock the file with the lock specified by parameter eFileLock - one
 32489  ** of the following:
 32490  **
 32491  **     (1) SHARED_LOCK
 32492  **     (2) RESERVED_LOCK
 32493  **     (3) PENDING_LOCK
 32494  **     (4) EXCLUSIVE_LOCK
 32495  **
 32496  ** Sometimes when requesting one lock state, additional lock states
 32497  ** are inserted in between.  The locking might fail on one of the later
 32498  ** transitions leaving the lock state different from what it started but
 32499  ** still short of its goal.  The following chart shows the allowed
 32500  ** transitions and the inserted intermediate states:
 32501  **
 32502  **    UNLOCKED -> SHARED
 32503  **    SHARED -> RESERVED
 32504  **    SHARED -> (PENDING) -> EXCLUSIVE
 32505  **    RESERVED -> (PENDING) -> EXCLUSIVE
 32506  **    PENDING -> EXCLUSIVE
 32507  **
 32508  ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
 32509  ** routine to lower a locking level.
 32510  **
 32511  ** With dotfile locking, we really only support state (4): EXCLUSIVE.
 32512  ** But we track the other locking levels internally.
 32513  */
 32514  static int dotlockLock(sqlite3_file *id, int eFileLock) {
 32515    unixFile *pFile = (unixFile*)id;
 32516    char *zLockFile = (char *)pFile->lockingContext;
 32517    int rc = SQLITE_OK;
 32518  
 32519  
 32520    /* If we have any lock, then the lock file already exists.  All we have
 32521    ** to do is adjust our internal record of the lock level.
 32522    */
 32523    if( pFile->eFileLock > NO_LOCK ){
 32524      pFile->eFileLock = eFileLock;
 32525      /* Always update the timestamp on the old file */
 32526  #ifdef HAVE_UTIME
 32527      utime(zLockFile, NULL);
 32528  #else
 32529      utimes(zLockFile, NULL);
 32530  #endif
 32531      return SQLITE_OK;
 32532    }
 32533    
 32534    /* grab an exclusive lock */
 32535    rc = osMkdir(zLockFile, 0777);
 32536    if( rc<0 ){
 32537      /* failed to open/create the lock directory */
 32538      int tErrno = errno;
 32539      if( EEXIST == tErrno ){
 32540        rc = SQLITE_BUSY;
 32541      } else {
 32542        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
 32543        if( rc!=SQLITE_BUSY ){
 32544          storeLastErrno(pFile, tErrno);
 32545        }
 32546      }
 32547      return rc;
 32548    } 
 32549    
 32550    /* got it, set the type and return ok */
 32551    pFile->eFileLock = eFileLock;
 32552    return rc;
 32553  }
 32554  
 32555  /*
 32556  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 32557  ** must be either NO_LOCK or SHARED_LOCK.
 32558  **
 32559  ** If the locking level of the file descriptor is already at or below
 32560  ** the requested locking level, this routine is a no-op.
 32561  **
 32562  ** When the locking level reaches NO_LOCK, delete the lock file.
 32563  */
 32564  static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
 32565    unixFile *pFile = (unixFile*)id;
 32566    char *zLockFile = (char *)pFile->lockingContext;
 32567    int rc;
 32568  
 32569    assert( pFile );
 32570    OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
 32571             pFile->eFileLock, osGetpid(0)));
 32572    assert( eFileLock<=SHARED_LOCK );
 32573    
 32574    /* no-op if possible */
 32575    if( pFile->eFileLock==eFileLock ){
 32576      return SQLITE_OK;
 32577    }
 32578  
 32579    /* To downgrade to shared, simply update our internal notion of the
 32580    ** lock state.  No need to mess with the file on disk.
 32581    */
 32582    if( eFileLock==SHARED_LOCK ){
 32583      pFile->eFileLock = SHARED_LOCK;
 32584      return SQLITE_OK;
 32585    }
 32586    
 32587    /* To fully unlock the database, delete the lock file */
 32588    assert( eFileLock==NO_LOCK );
 32589    rc = osRmdir(zLockFile);
 32590    if( rc<0 ){
 32591      int tErrno = errno;
 32592      if( tErrno==ENOENT ){
 32593        rc = SQLITE_OK;
 32594      }else{
 32595        rc = SQLITE_IOERR_UNLOCK;
 32596        storeLastErrno(pFile, tErrno);
 32597      }
 32598      return rc; 
 32599    }
 32600    pFile->eFileLock = NO_LOCK;
 32601    return SQLITE_OK;
 32602  }
 32603  
 32604  /*
 32605  ** Close a file.  Make sure the lock has been released before closing.
 32606  */
 32607  static int dotlockClose(sqlite3_file *id) {
 32608    unixFile *pFile = (unixFile*)id;
 32609    assert( id!=0 );
 32610    dotlockUnlock(id, NO_LOCK);
 32611    sqlite3_free(pFile->lockingContext);
 32612    return closeUnixFile(id);
 32613  }
 32614  /****************** End of the dot-file lock implementation *******************
 32615  ******************************************************************************/
 32616  
 32617  /******************************************************************************
 32618  ************************** Begin flock Locking ********************************
 32619  **
 32620  ** Use the flock() system call to do file locking.
 32621  **
 32622  ** flock() locking is like dot-file locking in that the various
 32623  ** fine-grain locking levels supported by SQLite are collapsed into
 32624  ** a single exclusive lock.  In other words, SHARED, RESERVED, and
 32625  ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
 32626  ** still works when you do this, but concurrency is reduced since
 32627  ** only a single process can be reading the database at a time.
 32628  **
 32629  ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
 32630  */
 32631  #if SQLITE_ENABLE_LOCKING_STYLE
 32632  
 32633  /*
 32634  ** Retry flock() calls that fail with EINTR
 32635  */
 32636  #ifdef EINTR
 32637  static int robust_flock(int fd, int op){
 32638    int rc;
 32639    do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
 32640    return rc;
 32641  }
 32642  #else
 32643  # define robust_flock(a,b) flock(a,b)
 32644  #endif
 32645       
 32646  
 32647  /*
 32648  ** This routine checks if there is a RESERVED lock held on the specified
 32649  ** file by this or any other process. If such a lock is held, set *pResOut
 32650  ** to a non-zero value otherwise *pResOut is set to zero.  The return value
 32651  ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
 32652  */
 32653  static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
 32654    int rc = SQLITE_OK;
 32655    int reserved = 0;
 32656    unixFile *pFile = (unixFile*)id;
 32657    
 32658    SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
 32659    
 32660    assert( pFile );
 32661    
 32662    /* Check if a thread in this process holds such a lock */
 32663    if( pFile->eFileLock>SHARED_LOCK ){
 32664      reserved = 1;
 32665    }
 32666    
 32667    /* Otherwise see if some other process holds it. */
 32668    if( !reserved ){
 32669      /* attempt to get the lock */
 32670      int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
 32671      if( !lrc ){
 32672        /* got the lock, unlock it */
 32673        lrc = robust_flock(pFile->h, LOCK_UN);
 32674        if ( lrc ) {
 32675          int tErrno = errno;
 32676          /* unlock failed with an error */
 32677          lrc = SQLITE_IOERR_UNLOCK; 
 32678          storeLastErrno(pFile, tErrno);
 32679          rc = lrc;
 32680        }
 32681      } else {
 32682        int tErrno = errno;
 32683        reserved = 1;
 32684        /* someone else might have it reserved */
 32685        lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
 32686        if( IS_LOCK_ERROR(lrc) ){
 32687          storeLastErrno(pFile, tErrno);
 32688          rc = lrc;
 32689        }
 32690      }
 32691    }
 32692    OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
 32693  
 32694  #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
 32695    if( (rc & 0xff) == SQLITE_IOERR ){
 32696      rc = SQLITE_OK;
 32697      reserved=1;
 32698    }
 32699  #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
 32700    *pResOut = reserved;
 32701    return rc;
 32702  }
 32703  
 32704  /*
 32705  ** Lock the file with the lock specified by parameter eFileLock - one
 32706  ** of the following:
 32707  **
 32708  **     (1) SHARED_LOCK
 32709  **     (2) RESERVED_LOCK
 32710  **     (3) PENDING_LOCK
 32711  **     (4) EXCLUSIVE_LOCK
 32712  **
 32713  ** Sometimes when requesting one lock state, additional lock states
 32714  ** are inserted in between.  The locking might fail on one of the later
 32715  ** transitions leaving the lock state different from what it started but
 32716  ** still short of its goal.  The following chart shows the allowed
 32717  ** transitions and the inserted intermediate states:
 32718  **
 32719  **    UNLOCKED -> SHARED
 32720  **    SHARED -> RESERVED
 32721  **    SHARED -> (PENDING) -> EXCLUSIVE
 32722  **    RESERVED -> (PENDING) -> EXCLUSIVE
 32723  **    PENDING -> EXCLUSIVE
 32724  **
 32725  ** flock() only really support EXCLUSIVE locks.  We track intermediate
 32726  ** lock states in the sqlite3_file structure, but all locks SHARED or
 32727  ** above are really EXCLUSIVE locks and exclude all other processes from
 32728  ** access the file.
 32729  **
 32730  ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
 32731  ** routine to lower a locking level.
 32732  */
 32733  static int flockLock(sqlite3_file *id, int eFileLock) {
 32734    int rc = SQLITE_OK;
 32735    unixFile *pFile = (unixFile*)id;
 32736  
 32737    assert( pFile );
 32738  
 32739    /* if we already have a lock, it is exclusive.  
 32740    ** Just adjust level and punt on outta here. */
 32741    if (pFile->eFileLock > NO_LOCK) {
 32742      pFile->eFileLock = eFileLock;
 32743      return SQLITE_OK;
 32744    }
 32745    
 32746    /* grab an exclusive lock */
 32747    
 32748    if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
 32749      int tErrno = errno;
 32750      /* didn't get, must be busy */
 32751      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
 32752      if( IS_LOCK_ERROR(rc) ){
 32753        storeLastErrno(pFile, tErrno);
 32754      }
 32755    } else {
 32756      /* got it, set the type and return ok */
 32757      pFile->eFileLock = eFileLock;
 32758    }
 32759    OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
 32760             rc==SQLITE_OK ? "ok" : "failed"));
 32761  #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
 32762    if( (rc & 0xff) == SQLITE_IOERR ){
 32763      rc = SQLITE_BUSY;
 32764    }
 32765  #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
 32766    return rc;
 32767  }
 32768  
 32769  
 32770  /*
 32771  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 32772  ** must be either NO_LOCK or SHARED_LOCK.
 32773  **
 32774  ** If the locking level of the file descriptor is already at or below
 32775  ** the requested locking level, this routine is a no-op.
 32776  */
 32777  static int flockUnlock(sqlite3_file *id, int eFileLock) {
 32778    unixFile *pFile = (unixFile*)id;
 32779    
 32780    assert( pFile );
 32781    OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
 32782             pFile->eFileLock, osGetpid(0)));
 32783    assert( eFileLock<=SHARED_LOCK );
 32784    
 32785    /* no-op if possible */
 32786    if( pFile->eFileLock==eFileLock ){
 32787      return SQLITE_OK;
 32788    }
 32789    
 32790    /* shared can just be set because we always have an exclusive */
 32791    if (eFileLock==SHARED_LOCK) {
 32792      pFile->eFileLock = eFileLock;
 32793      return SQLITE_OK;
 32794    }
 32795    
 32796    /* no, really, unlock. */
 32797    if( robust_flock(pFile->h, LOCK_UN) ){
 32798  #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
 32799      return SQLITE_OK;
 32800  #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
 32801      return SQLITE_IOERR_UNLOCK;
 32802    }else{
 32803      pFile->eFileLock = NO_LOCK;
 32804      return SQLITE_OK;
 32805    }
 32806  }
 32807  
 32808  /*
 32809  ** Close a file.
 32810  */
 32811  static int flockClose(sqlite3_file *id) {
 32812    assert( id!=0 );
 32813    flockUnlock(id, NO_LOCK);
 32814    return closeUnixFile(id);
 32815  }
 32816  
 32817  #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
 32818  
 32819  /******************* End of the flock lock implementation *********************
 32820  ******************************************************************************/
 32821  
 32822  /******************************************************************************
 32823  ************************ Begin Named Semaphore Locking ************************
 32824  **
 32825  ** Named semaphore locking is only supported on VxWorks.
 32826  **
 32827  ** Semaphore locking is like dot-lock and flock in that it really only
 32828  ** supports EXCLUSIVE locking.  Only a single process can read or write
 32829  ** the database file at a time.  This reduces potential concurrency, but
 32830  ** makes the lock implementation much easier.
 32831  */
 32832  #if OS_VXWORKS
 32833  
 32834  /*
 32835  ** This routine checks if there is a RESERVED lock held on the specified
 32836  ** file by this or any other process. If such a lock is held, set *pResOut
 32837  ** to a non-zero value otherwise *pResOut is set to zero.  The return value
 32838  ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
 32839  */
 32840  static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
 32841    int rc = SQLITE_OK;
 32842    int reserved = 0;
 32843    unixFile *pFile = (unixFile*)id;
 32844  
 32845    SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
 32846    
 32847    assert( pFile );
 32848  
 32849    /* Check if a thread in this process holds such a lock */
 32850    if( pFile->eFileLock>SHARED_LOCK ){
 32851      reserved = 1;
 32852    }
 32853    
 32854    /* Otherwise see if some other process holds it. */
 32855    if( !reserved ){
 32856      sem_t *pSem = pFile->pInode->pSem;
 32857  
 32858      if( sem_trywait(pSem)==-1 ){
 32859        int tErrno = errno;
 32860        if( EAGAIN != tErrno ){
 32861          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
 32862          storeLastErrno(pFile, tErrno);
 32863        } else {
 32864          /* someone else has the lock when we are in NO_LOCK */
 32865          reserved = (pFile->eFileLock < SHARED_LOCK);
 32866        }
 32867      }else{
 32868        /* we could have it if we want it */
 32869        sem_post(pSem);
 32870      }
 32871    }
 32872    OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
 32873  
 32874    *pResOut = reserved;
 32875    return rc;
 32876  }
 32877  
 32878  /*
 32879  ** Lock the file with the lock specified by parameter eFileLock - one
 32880  ** of the following:
 32881  **
 32882  **     (1) SHARED_LOCK
 32883  **     (2) RESERVED_LOCK
 32884  **     (3) PENDING_LOCK
 32885  **     (4) EXCLUSIVE_LOCK
 32886  **
 32887  ** Sometimes when requesting one lock state, additional lock states
 32888  ** are inserted in between.  The locking might fail on one of the later
 32889  ** transitions leaving the lock state different from what it started but
 32890  ** still short of its goal.  The following chart shows the allowed
 32891  ** transitions and the inserted intermediate states:
 32892  **
 32893  **    UNLOCKED -> SHARED
 32894  **    SHARED -> RESERVED
 32895  **    SHARED -> (PENDING) -> EXCLUSIVE
 32896  **    RESERVED -> (PENDING) -> EXCLUSIVE
 32897  **    PENDING -> EXCLUSIVE
 32898  **
 32899  ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
 32900  ** lock states in the sqlite3_file structure, but all locks SHARED or
 32901  ** above are really EXCLUSIVE locks and exclude all other processes from
 32902  ** access the file.
 32903  **
 32904  ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
 32905  ** routine to lower a locking level.
 32906  */
 32907  static int semXLock(sqlite3_file *id, int eFileLock) {
 32908    unixFile *pFile = (unixFile*)id;
 32909    sem_t *pSem = pFile->pInode->pSem;
 32910    int rc = SQLITE_OK;
 32911  
 32912    /* if we already have a lock, it is exclusive.  
 32913    ** Just adjust level and punt on outta here. */
 32914    if (pFile->eFileLock > NO_LOCK) {
 32915      pFile->eFileLock = eFileLock;
 32916      rc = SQLITE_OK;
 32917      goto sem_end_lock;
 32918    }
 32919    
 32920    /* lock semaphore now but bail out when already locked. */
 32921    if( sem_trywait(pSem)==-1 ){
 32922      rc = SQLITE_BUSY;
 32923      goto sem_end_lock;
 32924    }
 32925  
 32926    /* got it, set the type and return ok */
 32927    pFile->eFileLock = eFileLock;
 32928  
 32929   sem_end_lock:
 32930    return rc;
 32931  }
 32932  
 32933  /*
 32934  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 32935  ** must be either NO_LOCK or SHARED_LOCK.
 32936  **
 32937  ** If the locking level of the file descriptor is already at or below
 32938  ** the requested locking level, this routine is a no-op.
 32939  */
 32940  static int semXUnlock(sqlite3_file *id, int eFileLock) {
 32941    unixFile *pFile = (unixFile*)id;
 32942    sem_t *pSem = pFile->pInode->pSem;
 32943  
 32944    assert( pFile );
 32945    assert( pSem );
 32946    OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
 32947             pFile->eFileLock, osGetpid(0)));
 32948    assert( eFileLock<=SHARED_LOCK );
 32949    
 32950    /* no-op if possible */
 32951    if( pFile->eFileLock==eFileLock ){
 32952      return SQLITE_OK;
 32953    }
 32954    
 32955    /* shared can just be set because we always have an exclusive */
 32956    if (eFileLock==SHARED_LOCK) {
 32957      pFile->eFileLock = eFileLock;
 32958      return SQLITE_OK;
 32959    }
 32960    
 32961    /* no, really unlock. */
 32962    if ( sem_post(pSem)==-1 ) {
 32963      int rc, tErrno = errno;
 32964      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
 32965      if( IS_LOCK_ERROR(rc) ){
 32966        storeLastErrno(pFile, tErrno);
 32967      }
 32968      return rc; 
 32969    }
 32970    pFile->eFileLock = NO_LOCK;
 32971    return SQLITE_OK;
 32972  }
 32973  
 32974  /*
 32975   ** Close a file.
 32976   */
 32977  static int semXClose(sqlite3_file *id) {
 32978    if( id ){
 32979      unixFile *pFile = (unixFile*)id;
 32980      semXUnlock(id, NO_LOCK);
 32981      assert( pFile );
 32982      unixEnterMutex();
 32983      releaseInodeInfo(pFile);
 32984      unixLeaveMutex();
 32985      closeUnixFile(id);
 32986    }
 32987    return SQLITE_OK;
 32988  }
 32989  
 32990  #endif /* OS_VXWORKS */
 32991  /*
 32992  ** Named semaphore locking is only available on VxWorks.
 32993  **
 32994  *************** End of the named semaphore lock implementation ****************
 32995  ******************************************************************************/
 32996  
 32997  
 32998  /******************************************************************************
 32999  *************************** Begin AFP Locking *********************************
 33000  **
 33001  ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
 33002  ** on Apple Macintosh computers - both OS9 and OSX.
 33003  **
 33004  ** Third-party implementations of AFP are available.  But this code here
 33005  ** only works on OSX.
 33006  */
 33007  
 33008  #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 33009  /*
 33010  ** The afpLockingContext structure contains all afp lock specific state
 33011  */
 33012  typedef struct afpLockingContext afpLockingContext;
 33013  struct afpLockingContext {
 33014    int reserved;
 33015    const char *dbPath;             /* Name of the open file */
 33016  };
 33017  
 33018  struct ByteRangeLockPB2
 33019  {
 33020    unsigned long long offset;        /* offset to first byte to lock */
 33021    unsigned long long length;        /* nbr of bytes to lock */
 33022    unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
 33023    unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
 33024    unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
 33025    int fd;                           /* file desc to assoc this lock with */
 33026  };
 33027  
 33028  #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
 33029  
 33030  /*
 33031  ** This is a utility for setting or clearing a bit-range lock on an
 33032  ** AFP filesystem.
 33033  ** 
 33034  ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
 33035  */
 33036  static int afpSetLock(
 33037    const char *path,              /* Name of the file to be locked or unlocked */
 33038    unixFile *pFile,               /* Open file descriptor on path */
 33039    unsigned long long offset,     /* First byte to be locked */
 33040    unsigned long long length,     /* Number of bytes to lock */
 33041    int setLockFlag                /* True to set lock.  False to clear lock */
 33042  ){
 33043    struct ByteRangeLockPB2 pb;
 33044    int err;
 33045    
 33046    pb.unLockFlag = setLockFlag ? 0 : 1;
 33047    pb.startEndFlag = 0;
 33048    pb.offset = offset;
 33049    pb.length = length; 
 33050    pb.fd = pFile->h;
 33051    
 33052    OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
 33053      (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
 33054      offset, length));
 33055    err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
 33056    if ( err==-1 ) {
 33057      int rc;
 33058      int tErrno = errno;
 33059      OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
 33060               path, tErrno, strerror(tErrno)));
 33061  #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
 33062      rc = SQLITE_BUSY;
 33063  #else
 33064      rc = sqliteErrorFromPosixError(tErrno,
 33065                      setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
 33066  #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
 33067      if( IS_LOCK_ERROR(rc) ){
 33068        storeLastErrno(pFile, tErrno);
 33069      }
 33070      return rc;
 33071    } else {
 33072      return SQLITE_OK;
 33073    }
 33074  }
 33075  
 33076  /*
 33077  ** This routine checks if there is a RESERVED lock held on the specified
 33078  ** file by this or any other process. If such a lock is held, set *pResOut
 33079  ** to a non-zero value otherwise *pResOut is set to zero.  The return value
 33080  ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
 33081  */
 33082  static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
 33083    int rc = SQLITE_OK;
 33084    int reserved = 0;
 33085    unixFile *pFile = (unixFile*)id;
 33086    afpLockingContext *context;
 33087    
 33088    SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
 33089    
 33090    assert( pFile );
 33091    context = (afpLockingContext *) pFile->lockingContext;
 33092    if( context->reserved ){
 33093      *pResOut = 1;
 33094      return SQLITE_OK;
 33095    }
 33096    unixEnterMutex(); /* Because pFile->pInode is shared across threads */
 33097    
 33098    /* Check if a thread in this process holds such a lock */
 33099    if( pFile->pInode->eFileLock>SHARED_LOCK ){
 33100      reserved = 1;
 33101    }
 33102    
 33103    /* Otherwise see if some other process holds it.
 33104     */
 33105    if( !reserved ){
 33106      /* lock the RESERVED byte */
 33107      int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
 33108      if( SQLITE_OK==lrc ){
 33109        /* if we succeeded in taking the reserved lock, unlock it to restore
 33110        ** the original state */
 33111        lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
 33112      } else {
 33113        /* if we failed to get the lock then someone else must have it */
 33114        reserved = 1;
 33115      }
 33116      if( IS_LOCK_ERROR(lrc) ){
 33117        rc=lrc;
 33118      }
 33119    }
 33120    
 33121    unixLeaveMutex();
 33122    OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
 33123    
 33124    *pResOut = reserved;
 33125    return rc;
 33126  }
 33127  
 33128  /*
 33129  ** Lock the file with the lock specified by parameter eFileLock - one
 33130  ** of the following:
 33131  **
 33132  **     (1) SHARED_LOCK
 33133  **     (2) RESERVED_LOCK
 33134  **     (3) PENDING_LOCK
 33135  **     (4) EXCLUSIVE_LOCK
 33136  **
 33137  ** Sometimes when requesting one lock state, additional lock states
 33138  ** are inserted in between.  The locking might fail on one of the later
 33139  ** transitions leaving the lock state different from what it started but
 33140  ** still short of its goal.  The following chart shows the allowed
 33141  ** transitions and the inserted intermediate states:
 33142  **
 33143  **    UNLOCKED -> SHARED
 33144  **    SHARED -> RESERVED
 33145  **    SHARED -> (PENDING) -> EXCLUSIVE
 33146  **    RESERVED -> (PENDING) -> EXCLUSIVE
 33147  **    PENDING -> EXCLUSIVE
 33148  **
 33149  ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
 33150  ** routine to lower a locking level.
 33151  */
 33152  static int afpLock(sqlite3_file *id, int eFileLock){
 33153    int rc = SQLITE_OK;
 33154    unixFile *pFile = (unixFile*)id;
 33155    unixInodeInfo *pInode = pFile->pInode;
 33156    afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
 33157    
 33158    assert( pFile );
 33159    OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
 33160             azFileLock(eFileLock), azFileLock(pFile->eFileLock),
 33161             azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
 33162  
 33163    /* If there is already a lock of this type or more restrictive on the
 33164    ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
 33165    ** unixEnterMutex() hasn't been called yet.
 33166    */
 33167    if( pFile->eFileLock>=eFileLock ){
 33168      OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
 33169             azFileLock(eFileLock)));
 33170      return SQLITE_OK;
 33171    }
 33172  
 33173    /* Make sure the locking sequence is correct
 33174    **  (1) We never move from unlocked to anything higher than shared lock.
 33175    **  (2) SQLite never explicitly requests a pendig lock.
 33176    **  (3) A shared lock is always held when a reserve lock is requested.
 33177    */
 33178    assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
 33179    assert( eFileLock!=PENDING_LOCK );
 33180    assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
 33181    
 33182    /* This mutex is needed because pFile->pInode is shared across threads
 33183    */
 33184    unixEnterMutex();
 33185    pInode = pFile->pInode;
 33186  
 33187    /* If some thread using this PID has a lock via a different unixFile*
 33188    ** handle that precludes the requested lock, return BUSY.
 33189    */
 33190    if( (pFile->eFileLock!=pInode->eFileLock && 
 33191         (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
 33192       ){
 33193      rc = SQLITE_BUSY;
 33194      goto afp_end_lock;
 33195    }
 33196    
 33197    /* If a SHARED lock is requested, and some thread using this PID already
 33198    ** has a SHARED or RESERVED lock, then increment reference counts and
 33199    ** return SQLITE_OK.
 33200    */
 33201    if( eFileLock==SHARED_LOCK && 
 33202       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
 33203      assert( eFileLock==SHARED_LOCK );
 33204      assert( pFile->eFileLock==0 );
 33205      assert( pInode->nShared>0 );
 33206      pFile->eFileLock = SHARED_LOCK;
 33207      pInode->nShared++;
 33208      pInode->nLock++;
 33209      goto afp_end_lock;
 33210    }
 33211      
 33212    /* A PENDING lock is needed before acquiring a SHARED lock and before
 33213    ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
 33214    ** be released.
 33215    */
 33216    if( eFileLock==SHARED_LOCK 
 33217        || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
 33218    ){
 33219      int failed;
 33220      failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
 33221      if (failed) {
 33222        rc = failed;
 33223        goto afp_end_lock;
 33224      }
 33225    }
 33226    
 33227    /* If control gets to this point, then actually go ahead and make
 33228    ** operating system calls for the specified lock.
 33229    */
 33230    if( eFileLock==SHARED_LOCK ){
 33231      int lrc1, lrc2, lrc1Errno = 0;
 33232      long lk, mask;
 33233      
 33234      assert( pInode->nShared==0 );
 33235      assert( pInode->eFileLock==0 );
 33236          
 33237      mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
 33238      /* Now get the read-lock SHARED_LOCK */
 33239      /* note that the quality of the randomness doesn't matter that much */
 33240      lk = random(); 
 33241      pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
 33242      lrc1 = afpSetLock(context->dbPath, pFile, 
 33243            SHARED_FIRST+pInode->sharedByte, 1, 1);
 33244      if( IS_LOCK_ERROR(lrc1) ){
 33245        lrc1Errno = pFile->lastErrno;
 33246      }
 33247      /* Drop the temporary PENDING lock */
 33248      lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
 33249      
 33250      if( IS_LOCK_ERROR(lrc1) ) {
 33251        storeLastErrno(pFile, lrc1Errno);
 33252        rc = lrc1;
 33253        goto afp_end_lock;
 33254      } else if( IS_LOCK_ERROR(lrc2) ){
 33255        rc = lrc2;
 33256        goto afp_end_lock;
 33257      } else if( lrc1 != SQLITE_OK ) {
 33258        rc = lrc1;
 33259      } else {
 33260        pFile->eFileLock = SHARED_LOCK;
 33261        pInode->nLock++;
 33262        pInode->nShared = 1;
 33263      }
 33264    }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
 33265      /* We are trying for an exclusive lock but another thread in this
 33266       ** same process is still holding a shared lock. */
 33267      rc = SQLITE_BUSY;
 33268    }else{
 33269      /* The request was for a RESERVED or EXCLUSIVE lock.  It is
 33270      ** assumed that there is a SHARED or greater lock on the file
 33271      ** already.
 33272      */
 33273      int failed = 0;
 33274      assert( 0!=pFile->eFileLock );
 33275      if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
 33276          /* Acquire a RESERVED lock */
 33277          failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
 33278        if( !failed ){
 33279          context->reserved = 1;
 33280        }
 33281      }
 33282      if (!failed && eFileLock == EXCLUSIVE_LOCK) {
 33283        /* Acquire an EXCLUSIVE lock */
 33284          
 33285        /* Remove the shared lock before trying the range.  we'll need to 
 33286        ** reestablish the shared lock if we can't get the  afpUnlock
 33287        */
 33288        if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
 33289                           pInode->sharedByte, 1, 0)) ){
 33290          int failed2 = SQLITE_OK;
 33291          /* now attemmpt to get the exclusive lock range */
 33292          failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
 33293                                 SHARED_SIZE, 1);
 33294          if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
 33295                         SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
 33296            /* Can't reestablish the shared lock.  Sqlite can't deal, this is
 33297            ** a critical I/O error
 33298            */
 33299            rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 : 
 33300                 SQLITE_IOERR_LOCK;
 33301            goto afp_end_lock;
 33302          } 
 33303        }else{
 33304          rc = failed; 
 33305        }
 33306      }
 33307      if( failed ){
 33308        rc = failed;
 33309      }
 33310    }
 33311    
 33312    if( rc==SQLITE_OK ){
 33313      pFile->eFileLock = eFileLock;
 33314      pInode->eFileLock = eFileLock;
 33315    }else if( eFileLock==EXCLUSIVE_LOCK ){
 33316      pFile->eFileLock = PENDING_LOCK;
 33317      pInode->eFileLock = PENDING_LOCK;
 33318    }
 33319    
 33320  afp_end_lock:
 33321    unixLeaveMutex();
 33322    OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
 33323           rc==SQLITE_OK ? "ok" : "failed"));
 33324    return rc;
 33325  }
 33326  
 33327  /*
 33328  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 33329  ** must be either NO_LOCK or SHARED_LOCK.
 33330  **
 33331  ** If the locking level of the file descriptor is already at or below
 33332  ** the requested locking level, this routine is a no-op.
 33333  */
 33334  static int afpUnlock(sqlite3_file *id, int eFileLock) {
 33335    int rc = SQLITE_OK;
 33336    unixFile *pFile = (unixFile*)id;
 33337    unixInodeInfo *pInode;
 33338    afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
 33339    int skipShared = 0;
 33340  #ifdef SQLITE_TEST
 33341    int h = pFile->h;
 33342  #endif
 33343  
 33344    assert( pFile );
 33345    OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
 33346             pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
 33347             osGetpid(0)));
 33348  
 33349    assert( eFileLock<=SHARED_LOCK );
 33350    if( pFile->eFileLock<=eFileLock ){
 33351      return SQLITE_OK;
 33352    }
 33353    unixEnterMutex();
 33354    pInode = pFile->pInode;
 33355    assert( pInode->nShared!=0 );
 33356    if( pFile->eFileLock>SHARED_LOCK ){
 33357      assert( pInode->eFileLock==pFile->eFileLock );
 33358      SimulateIOErrorBenign(1);
 33359      SimulateIOError( h=(-1) )
 33360      SimulateIOErrorBenign(0);
 33361      
 33362  #ifdef SQLITE_DEBUG
 33363      /* When reducing a lock such that other processes can start
 33364      ** reading the database file again, make sure that the
 33365      ** transaction counter was updated if any part of the database
 33366      ** file changed.  If the transaction counter is not updated,
 33367      ** other connections to the same file might not realize that
 33368      ** the file has changed and hence might not know to flush their
 33369      ** cache.  The use of a stale cache can lead to database corruption.
 33370      */
 33371      assert( pFile->inNormalWrite==0
 33372             || pFile->dbUpdate==0
 33373             || pFile->transCntrChng==1 );
 33374      pFile->inNormalWrite = 0;
 33375  #endif
 33376      
 33377      if( pFile->eFileLock==EXCLUSIVE_LOCK ){
 33378        rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
 33379        if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
 33380          /* only re-establish the shared lock if necessary */
 33381          int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
 33382          rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
 33383        } else {
 33384          skipShared = 1;
 33385        }
 33386      }
 33387      if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
 33388        rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
 33389      } 
 33390      if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
 33391        rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
 33392        if( !rc ){ 
 33393          context->reserved = 0; 
 33394        }
 33395      }
 33396      if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
 33397        pInode->eFileLock = SHARED_LOCK;
 33398      }
 33399    }
 33400    if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
 33401  
 33402      /* Decrement the shared lock counter.  Release the lock using an
 33403      ** OS call only when all threads in this same process have released
 33404      ** the lock.
 33405      */
 33406      unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
 33407      pInode->nShared--;
 33408      if( pInode->nShared==0 ){
 33409        SimulateIOErrorBenign(1);
 33410        SimulateIOError( h=(-1) )
 33411        SimulateIOErrorBenign(0);
 33412        if( !skipShared ){
 33413          rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
 33414        }
 33415        if( !rc ){
 33416          pInode->eFileLock = NO_LOCK;
 33417          pFile->eFileLock = NO_LOCK;
 33418        }
 33419      }
 33420      if( rc==SQLITE_OK ){
 33421        pInode->nLock--;
 33422        assert( pInode->nLock>=0 );
 33423        if( pInode->nLock==0 ){
 33424          closePendingFds(pFile);
 33425        }
 33426      }
 33427    }
 33428    
 33429    unixLeaveMutex();
 33430    if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
 33431    return rc;
 33432  }
 33433  
 33434  /*
 33435  ** Close a file & cleanup AFP specific locking context 
 33436  */
 33437  static int afpClose(sqlite3_file *id) {
 33438    int rc = SQLITE_OK;
 33439    unixFile *pFile = (unixFile*)id;
 33440    assert( id!=0 );
 33441    afpUnlock(id, NO_LOCK);
 33442    unixEnterMutex();
 33443    if( pFile->pInode && pFile->pInode->nLock ){
 33444      /* If there are outstanding locks, do not actually close the file just
 33445      ** yet because that would clear those locks.  Instead, add the file
 33446      ** descriptor to pInode->aPending.  It will be automatically closed when
 33447      ** the last lock is cleared.
 33448      */
 33449      setPendingFd(pFile);
 33450    }
 33451    releaseInodeInfo(pFile);
 33452    sqlite3_free(pFile->lockingContext);
 33453    rc = closeUnixFile(id);
 33454    unixLeaveMutex();
 33455    return rc;
 33456  }
 33457  
 33458  #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
 33459  /*
 33460  ** The code above is the AFP lock implementation.  The code is specific
 33461  ** to MacOSX and does not work on other unix platforms.  No alternative
 33462  ** is available.  If you don't compile for a mac, then the "unix-afp"
 33463  ** VFS is not available.
 33464  **
 33465  ********************* End of the AFP lock implementation **********************
 33466  ******************************************************************************/
 33467  
 33468  /******************************************************************************
 33469  *************************** Begin NFS Locking ********************************/
 33470  
 33471  #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 33472  /*
 33473   ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 33474   ** must be either NO_LOCK or SHARED_LOCK.
 33475   **
 33476   ** If the locking level of the file descriptor is already at or below
 33477   ** the requested locking level, this routine is a no-op.
 33478   */
 33479  static int nfsUnlock(sqlite3_file *id, int eFileLock){
 33480    return posixUnlock(id, eFileLock, 1);
 33481  }
 33482  
 33483  #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
 33484  /*
 33485  ** The code above is the NFS lock implementation.  The code is specific
 33486  ** to MacOSX and does not work on other unix platforms.  No alternative
 33487  ** is available.  
 33488  **
 33489  ********************* End of the NFS lock implementation **********************
 33490  ******************************************************************************/
 33491  
 33492  /******************************************************************************
 33493  **************** Non-locking sqlite3_file methods *****************************
 33494  **
 33495  ** The next division contains implementations for all methods of the 
 33496  ** sqlite3_file object other than the locking methods.  The locking
 33497  ** methods were defined in divisions above (one locking method per
 33498  ** division).  Those methods that are common to all locking modes
 33499  ** are gather together into this division.
 33500  */
 33501  
 33502  /*
 33503  ** Seek to the offset passed as the second argument, then read cnt 
 33504  ** bytes into pBuf. Return the number of bytes actually read.
 33505  **
 33506  ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
 33507  ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
 33508  ** one system to another.  Since SQLite does not define USE_PREAD
 33509  ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
 33510  ** See tickets #2741 and #2681.
 33511  **
 33512  ** To avoid stomping the errno value on a failed read the lastErrno value
 33513  ** is set before returning.
 33514  */
 33515  static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
 33516    int got;
 33517    int prior = 0;
 33518  #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
 33519    i64 newOffset;
 33520  #endif
 33521    TIMER_START;
 33522    assert( cnt==(cnt&0x1ffff) );
 33523    assert( id->h>2 );
 33524    do{
 33525  #if defined(USE_PREAD)
 33526      got = osPread(id->h, pBuf, cnt, offset);
 33527      SimulateIOError( got = -1 );
 33528  #elif defined(USE_PREAD64)
 33529      got = osPread64(id->h, pBuf, cnt, offset);
 33530      SimulateIOError( got = -1 );
 33531  #else
 33532      newOffset = lseek(id->h, offset, SEEK_SET);
 33533      SimulateIOError( newOffset = -1 );
 33534      if( newOffset<0 ){
 33535        storeLastErrno((unixFile*)id, errno);
 33536        return -1;
 33537      }
 33538      got = osRead(id->h, pBuf, cnt);
 33539  #endif
 33540      if( got==cnt ) break;
 33541      if( got<0 ){
 33542        if( errno==EINTR ){ got = 1; continue; }
 33543        prior = 0;
 33544        storeLastErrno((unixFile*)id,  errno);
 33545        break;
 33546      }else if( got>0 ){
 33547        cnt -= got;
 33548        offset += got;
 33549        prior += got;
 33550        pBuf = (void*)(got + (char*)pBuf);
 33551      }
 33552    }while( got>0 );
 33553    TIMER_END;
 33554    OSTRACE(("READ    %-3d %5d %7lld %llu\n",
 33555              id->h, got+prior, offset-prior, TIMER_ELAPSED));
 33556    return got+prior;
 33557  }
 33558  
 33559  /*
 33560  ** Read data from a file into a buffer.  Return SQLITE_OK if all
 33561  ** bytes were read successfully and SQLITE_IOERR if anything goes
 33562  ** wrong.
 33563  */
 33564  static int unixRead(
 33565    sqlite3_file *id, 
 33566    void *pBuf, 
 33567    int amt,
 33568    sqlite3_int64 offset
 33569  ){
 33570    unixFile *pFile = (unixFile *)id;
 33571    int got;
 33572    assert( id );
 33573    assert( offset>=0 );
 33574    assert( amt>0 );
 33575  
 33576    /* If this is a database file (not a journal, master-journal or temp
 33577    ** file), the bytes in the locking range should never be read or written. */
 33578  #if 0
 33579    assert( pFile->pPreallocatedUnused==0
 33580         || offset>=PENDING_BYTE+512
 33581         || offset+amt<=PENDING_BYTE 
 33582    );
 33583  #endif
 33584  
 33585  #if SQLITE_MAX_MMAP_SIZE>0
 33586    /* Deal with as much of this read request as possible by transfering
 33587    ** data from the memory mapping using memcpy().  */
 33588    if( offset<pFile->mmapSize ){
 33589      if( offset+amt <= pFile->mmapSize ){
 33590        memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
 33591        return SQLITE_OK;
 33592      }else{
 33593        int nCopy = pFile->mmapSize - offset;
 33594        memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
 33595        pBuf = &((u8 *)pBuf)[nCopy];
 33596        amt -= nCopy;
 33597        offset += nCopy;
 33598      }
 33599    }
 33600  #endif
 33601  
 33602    got = seekAndRead(pFile, offset, pBuf, amt);
 33603    if( got==amt ){
 33604      return SQLITE_OK;
 33605    }else if( got<0 ){
 33606      /* lastErrno set by seekAndRead */
 33607      return SQLITE_IOERR_READ;
 33608    }else{
 33609      storeLastErrno(pFile, 0);   /* not a system error */
 33610      /* Unread parts of the buffer must be zero-filled */
 33611      memset(&((char*)pBuf)[got], 0, amt-got);
 33612      return SQLITE_IOERR_SHORT_READ;
 33613    }
 33614  }
 33615  
 33616  /*
 33617  ** Attempt to seek the file-descriptor passed as the first argument to
 33618  ** absolute offset iOff, then attempt to write nBuf bytes of data from
 33619  ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise, 
 33620  ** return the actual number of bytes written (which may be less than
 33621  ** nBuf).
 33622  */
 33623  static int seekAndWriteFd(
 33624    int fd,                         /* File descriptor to write to */
 33625    i64 iOff,                       /* File offset to begin writing at */
 33626    const void *pBuf,               /* Copy data from this buffer to the file */
 33627    int nBuf,                       /* Size of buffer pBuf in bytes */
 33628    int *piErrno                    /* OUT: Error number if error occurs */
 33629  ){
 33630    int rc = 0;                     /* Value returned by system call */
 33631  
 33632    assert( nBuf==(nBuf&0x1ffff) );
 33633    assert( fd>2 );
 33634    assert( piErrno!=0 );
 33635    nBuf &= 0x1ffff;
 33636    TIMER_START;
 33637  
 33638  #if defined(USE_PREAD)
 33639    do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
 33640  #elif defined(USE_PREAD64)
 33641    do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
 33642  #else
 33643    do{
 33644      i64 iSeek = lseek(fd, iOff, SEEK_SET);
 33645      SimulateIOError( iSeek = -1 );
 33646      if( iSeek<0 ){
 33647        rc = -1;
 33648        break;
 33649      }
 33650      rc = osWrite(fd, pBuf, nBuf);
 33651    }while( rc<0 && errno==EINTR );
 33652  #endif
 33653  
 33654    TIMER_END;
 33655    OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
 33656  
 33657    if( rc<0 ) *piErrno = errno;
 33658    return rc;
 33659  }
 33660  
 33661  
 33662  /*
 33663  ** Seek to the offset in id->offset then read cnt bytes into pBuf.
 33664  ** Return the number of bytes actually read.  Update the offset.
 33665  **
 33666  ** To avoid stomping the errno value on a failed write the lastErrno value
 33667  ** is set before returning.
 33668  */
 33669  static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
 33670    return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
 33671  }
 33672  
 33673  
 33674  /*
 33675  ** Write data from a buffer into a file.  Return SQLITE_OK on success
 33676  ** or some other error code on failure.
 33677  */
 33678  static int unixWrite(
 33679    sqlite3_file *id, 
 33680    const void *pBuf, 
 33681    int amt,
 33682    sqlite3_int64 offset 
 33683  ){
 33684    unixFile *pFile = (unixFile*)id;
 33685    int wrote = 0;
 33686    assert( id );
 33687    assert( amt>0 );
 33688  
 33689    /* If this is a database file (not a journal, master-journal or temp
 33690    ** file), the bytes in the locking range should never be read or written. */
 33691  #if 0
 33692    assert( pFile->pPreallocatedUnused==0
 33693         || offset>=PENDING_BYTE+512
 33694         || offset+amt<=PENDING_BYTE 
 33695    );
 33696  #endif
 33697  
 33698  #ifdef SQLITE_DEBUG
 33699    /* If we are doing a normal write to a database file (as opposed to
 33700    ** doing a hot-journal rollback or a write to some file other than a
 33701    ** normal database file) then record the fact that the database
 33702    ** has changed.  If the transaction counter is modified, record that
 33703    ** fact too.
 33704    */
 33705    if( pFile->inNormalWrite ){
 33706      pFile->dbUpdate = 1;  /* The database has been modified */
 33707      if( offset<=24 && offset+amt>=27 ){
 33708        int rc;
 33709        char oldCntr[4];
 33710        SimulateIOErrorBenign(1);
 33711        rc = seekAndRead(pFile, 24, oldCntr, 4);
 33712        SimulateIOErrorBenign(0);
 33713        if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
 33714          pFile->transCntrChng = 1;  /* The transaction counter has changed */
 33715        }
 33716      }
 33717    }
 33718  #endif
 33719  
 33720  #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
 33721    /* Deal with as much of this write request as possible by transfering
 33722    ** data from the memory mapping using memcpy().  */
 33723    if( offset<pFile->mmapSize ){
 33724      if( offset+amt <= pFile->mmapSize ){
 33725        memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
 33726        return SQLITE_OK;
 33727      }else{
 33728        int nCopy = pFile->mmapSize - offset;
 33729        memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
 33730        pBuf = &((u8 *)pBuf)[nCopy];
 33731        amt -= nCopy;
 33732        offset += nCopy;
 33733      }
 33734    }
 33735  #endif
 33736   
 33737    while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
 33738      amt -= wrote;
 33739      offset += wrote;
 33740      pBuf = &((char*)pBuf)[wrote];
 33741    }
 33742    SimulateIOError(( wrote=(-1), amt=1 ));
 33743    SimulateDiskfullError(( wrote=0, amt=1 ));
 33744  
 33745    if( amt>wrote ){
 33746      if( wrote<0 && pFile->lastErrno!=ENOSPC ){
 33747        /* lastErrno set by seekAndWrite */
 33748        return SQLITE_IOERR_WRITE;
 33749      }else{
 33750        storeLastErrno(pFile, 0); /* not a system error */
 33751        return SQLITE_FULL;
 33752      }
 33753    }
 33754  
 33755    return SQLITE_OK;
 33756  }
 33757  
 33758  #ifdef SQLITE_TEST
 33759  /*
 33760  ** Count the number of fullsyncs and normal syncs.  This is used to test
 33761  ** that syncs and fullsyncs are occurring at the right times.
 33762  */
 33763  SQLITE_API int sqlite3_sync_count = 0;
 33764  SQLITE_API int sqlite3_fullsync_count = 0;
 33765  #endif
 33766  
 33767  /*
 33768  ** We do not trust systems to provide a working fdatasync().  Some do.
 33769  ** Others do no.  To be safe, we will stick with the (slightly slower)
 33770  ** fsync(). If you know that your system does support fdatasync() correctly,
 33771  ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
 33772  */
 33773  #if !defined(fdatasync) && !HAVE_FDATASYNC
 33774  # define fdatasync fsync
 33775  #endif
 33776  
 33777  /*
 33778  ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
 33779  ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
 33780  ** only available on Mac OS X.  But that could change.
 33781  */
 33782  #ifdef F_FULLFSYNC
 33783  # define HAVE_FULLFSYNC 1
 33784  #else
 33785  # define HAVE_FULLFSYNC 0
 33786  #endif
 33787  
 33788  
 33789  /*
 33790  ** The fsync() system call does not work as advertised on many
 33791  ** unix systems.  The following procedure is an attempt to make
 33792  ** it work better.
 33793  **
 33794  ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
 33795  ** for testing when we want to run through the test suite quickly.
 33796  ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
 33797  ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
 33798  ** or power failure will likely corrupt the database file.
 33799  **
 33800  ** SQLite sets the dataOnly flag if the size of the file is unchanged.
 33801  ** The idea behind dataOnly is that it should only write the file content
 33802  ** to disk, not the inode.  We only set dataOnly if the file size is 
 33803  ** unchanged since the file size is part of the inode.  However, 
 33804  ** Ted Ts'o tells us that fdatasync() will also write the inode if the
 33805  ** file size has changed.  The only real difference between fdatasync()
 33806  ** and fsync(), Ted tells us, is that fdatasync() will not flush the
 33807  ** inode if the mtime or owner or other inode attributes have changed.
 33808  ** We only care about the file size, not the other file attributes, so
 33809  ** as far as SQLite is concerned, an fdatasync() is always adequate.
 33810  ** So, we always use fdatasync() if it is available, regardless of
 33811  ** the value of the dataOnly flag.
 33812  */
 33813  static int full_fsync(int fd, int fullSync, int dataOnly){
 33814    int rc;
 33815  
 33816    /* The following "ifdef/elif/else/" block has the same structure as
 33817    ** the one below. It is replicated here solely to avoid cluttering 
 33818    ** up the real code with the UNUSED_PARAMETER() macros.
 33819    */
 33820  #ifdef SQLITE_NO_SYNC
 33821    UNUSED_PARAMETER(fd);
 33822    UNUSED_PARAMETER(fullSync);
 33823    UNUSED_PARAMETER(dataOnly);
 33824  #elif HAVE_FULLFSYNC
 33825    UNUSED_PARAMETER(dataOnly);
 33826  #else
 33827    UNUSED_PARAMETER(fullSync);
 33828    UNUSED_PARAMETER(dataOnly);
 33829  #endif
 33830  
 33831    /* Record the number of times that we do a normal fsync() and 
 33832    ** FULLSYNC.  This is used during testing to verify that this procedure
 33833    ** gets called with the correct arguments.
 33834    */
 33835  #ifdef SQLITE_TEST
 33836    if( fullSync ) sqlite3_fullsync_count++;
 33837    sqlite3_sync_count++;
 33838  #endif
 33839  
 33840    /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
 33841    ** no-op.  But go ahead and call fstat() to validate the file
 33842    ** descriptor as we need a method to provoke a failure during
 33843    ** coverate testing.
 33844    */
 33845  #ifdef SQLITE_NO_SYNC
 33846    {
 33847      struct stat buf;
 33848      rc = osFstat(fd, &buf);
 33849    }
 33850  #elif HAVE_FULLFSYNC
 33851    if( fullSync ){
 33852      rc = osFcntl(fd, F_FULLFSYNC, 0);
 33853    }else{
 33854      rc = 1;
 33855    }
 33856    /* If the FULLFSYNC failed, fall back to attempting an fsync().
 33857    ** It shouldn't be possible for fullfsync to fail on the local 
 33858    ** file system (on OSX), so failure indicates that FULLFSYNC
 33859    ** isn't supported for this file system. So, attempt an fsync 
 33860    ** and (for now) ignore the overhead of a superfluous fcntl call.  
 33861    ** It'd be better to detect fullfsync support once and avoid 
 33862    ** the fcntl call every time sync is called.
 33863    */
 33864    if( rc ) rc = fsync(fd);
 33865  
 33866  #elif defined(__APPLE__)
 33867    /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
 33868    ** so currently we default to the macro that redefines fdatasync to fsync
 33869    */
 33870    rc = fsync(fd);
 33871  #else 
 33872    rc = fdatasync(fd);
 33873  #if OS_VXWORKS
 33874    if( rc==-1 && errno==ENOTSUP ){
 33875      rc = fsync(fd);
 33876    }
 33877  #endif /* OS_VXWORKS */
 33878  #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
 33879  
 33880    if( OS_VXWORKS && rc!= -1 ){
 33881      rc = 0;
 33882    }
 33883    return rc;
 33884  }
 33885  
 33886  /*
 33887  ** Open a file descriptor to the directory containing file zFilename.
 33888  ** If successful, *pFd is set to the opened file descriptor and
 33889  ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
 33890  ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
 33891  ** value.
 33892  **
 33893  ** The directory file descriptor is used for only one thing - to
 33894  ** fsync() a directory to make sure file creation and deletion events
 33895  ** are flushed to disk.  Such fsyncs are not needed on newer
 33896  ** journaling filesystems, but are required on older filesystems.
 33897  **
 33898  ** This routine can be overridden using the xSetSysCall interface.
 33899  ** The ability to override this routine was added in support of the
 33900  ** chromium sandbox.  Opening a directory is a security risk (we are
 33901  ** told) so making it overrideable allows the chromium sandbox to
 33902  ** replace this routine with a harmless no-op.  To make this routine
 33903  ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
 33904  ** *pFd set to a negative number.
 33905  **
 33906  ** If SQLITE_OK is returned, the caller is responsible for closing
 33907  ** the file descriptor *pFd using close().
 33908  */
 33909  static int openDirectory(const char *zFilename, int *pFd){
 33910    int ii;
 33911    int fd = -1;
 33912    char zDirname[MAX_PATHNAME+1];
 33913  
 33914    sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
 33915    for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
 33916    if( ii>0 ){
 33917      zDirname[ii] = '\0';
 33918    }else{
 33919      if( zDirname[0]!='/' ) zDirname[0] = '.';
 33920      zDirname[1] = 0;
 33921    }
 33922    fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
 33923    if( fd>=0 ){
 33924      OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
 33925    }
 33926    *pFd = fd;
 33927    if( fd>=0 ) return SQLITE_OK;
 33928    return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
 33929  }
 33930  
 33931  /*
 33932  ** Make sure all writes to a particular file are committed to disk.
 33933  **
 33934  ** If dataOnly==0 then both the file itself and its metadata (file
 33935  ** size, access time, etc) are synced.  If dataOnly!=0 then only the
 33936  ** file data is synced.
 33937  **
 33938  ** Under Unix, also make sure that the directory entry for the file
 33939  ** has been created by fsync-ing the directory that contains the file.
 33940  ** If we do not do this and we encounter a power failure, the directory
 33941  ** entry for the journal might not exist after we reboot.  The next
 33942  ** SQLite to access the file will not know that the journal exists (because
 33943  ** the directory entry for the journal was never created) and the transaction
 33944  ** will not roll back - possibly leading to database corruption.
 33945  */
 33946  static int unixSync(sqlite3_file *id, int flags){
 33947    int rc;
 33948    unixFile *pFile = (unixFile*)id;
 33949  
 33950    int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
 33951    int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
 33952  
 33953    /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
 33954    assert((flags&0x0F)==SQLITE_SYNC_NORMAL
 33955        || (flags&0x0F)==SQLITE_SYNC_FULL
 33956    );
 33957  
 33958    /* Unix cannot, but some systems may return SQLITE_FULL from here. This
 33959    ** line is to test that doing so does not cause any problems.
 33960    */
 33961    SimulateDiskfullError( return SQLITE_FULL );
 33962  
 33963    assert( pFile );
 33964    OSTRACE(("SYNC    %-3d\n", pFile->h));
 33965    rc = full_fsync(pFile->h, isFullsync, isDataOnly);
 33966    SimulateIOError( rc=1 );
 33967    if( rc ){
 33968      storeLastErrno(pFile, errno);
 33969      return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
 33970    }
 33971  
 33972    /* Also fsync the directory containing the file if the DIRSYNC flag
 33973    ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
 33974    ** are unable to fsync a directory, so ignore errors on the fsync.
 33975    */
 33976    if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
 33977      int dirfd;
 33978      OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
 33979              HAVE_FULLFSYNC, isFullsync));
 33980      rc = osOpenDirectory(pFile->zPath, &dirfd);
 33981      if( rc==SQLITE_OK ){
 33982        full_fsync(dirfd, 0, 0);
 33983        robust_close(pFile, dirfd, __LINE__);
 33984      }else{
 33985        assert( rc==SQLITE_CANTOPEN );
 33986        rc = SQLITE_OK;
 33987      }
 33988      pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
 33989    }
 33990    return rc;
 33991  }
 33992  
 33993  /*
 33994  ** Truncate an open file to a specified size
 33995  */
 33996  static int unixTruncate(sqlite3_file *id, i64 nByte){
 33997    unixFile *pFile = (unixFile *)id;
 33998    int rc;
 33999    assert( pFile );
 34000    SimulateIOError( return SQLITE_IOERR_TRUNCATE );
 34001  
 34002    /* If the user has configured a chunk-size for this file, truncate the
 34003    ** file so that it consists of an integer number of chunks (i.e. the
 34004    ** actual file size after the operation may be larger than the requested
 34005    ** size).
 34006    */
 34007    if( pFile->szChunk>0 ){
 34008      nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
 34009    }
 34010  
 34011    rc = robust_ftruncate(pFile->h, nByte);
 34012    if( rc ){
 34013      storeLastErrno(pFile, errno);
 34014      return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
 34015    }else{
 34016  #ifdef SQLITE_DEBUG
 34017      /* If we are doing a normal write to a database file (as opposed to
 34018      ** doing a hot-journal rollback or a write to some file other than a
 34019      ** normal database file) and we truncate the file to zero length,
 34020      ** that effectively updates the change counter.  This might happen
 34021      ** when restoring a database using the backup API from a zero-length
 34022      ** source.
 34023      */
 34024      if( pFile->inNormalWrite && nByte==0 ){
 34025        pFile->transCntrChng = 1;
 34026      }
 34027  #endif
 34028  
 34029  #if SQLITE_MAX_MMAP_SIZE>0
 34030      /* If the file was just truncated to a size smaller than the currently
 34031      ** mapped region, reduce the effective mapping size as well. SQLite will
 34032      ** use read() and write() to access data beyond this point from now on.  
 34033      */
 34034      if( nByte<pFile->mmapSize ){
 34035        pFile->mmapSize = nByte;
 34036      }
 34037  #endif
 34038  
 34039      return SQLITE_OK;
 34040    }
 34041  }
 34042  
 34043  /*
 34044  ** Determine the current size of a file in bytes
 34045  */
 34046  static int unixFileSize(sqlite3_file *id, i64 *pSize){
 34047    int rc;
 34048    struct stat buf;
 34049    assert( id );
 34050    rc = osFstat(((unixFile*)id)->h, &buf);
 34051    SimulateIOError( rc=1 );
 34052    if( rc!=0 ){
 34053      storeLastErrno((unixFile*)id, errno);
 34054      return SQLITE_IOERR_FSTAT;
 34055    }
 34056    *pSize = buf.st_size;
 34057  
 34058    /* When opening a zero-size database, the findInodeInfo() procedure
 34059    ** writes a single byte into that file in order to work around a bug
 34060    ** in the OS-X msdos filesystem.  In order to avoid problems with upper
 34061    ** layers, we need to report this file size as zero even though it is
 34062    ** really 1.   Ticket #3260.
 34063    */
 34064    if( *pSize==1 ) *pSize = 0;
 34065  
 34066  
 34067    return SQLITE_OK;
 34068  }
 34069  
 34070  #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
 34071  /*
 34072  ** Handler for proxy-locking file-control verbs.  Defined below in the
 34073  ** proxying locking division.
 34074  */
 34075  static int proxyFileControl(sqlite3_file*,int,void*);
 34076  #endif
 34077  
 34078  /* 
 34079  ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT 
 34080  ** file-control operation.  Enlarge the database to nBytes in size
 34081  ** (rounded up to the next chunk-size).  If the database is already
 34082  ** nBytes or larger, this routine is a no-op.
 34083  */
 34084  static int fcntlSizeHint(unixFile *pFile, i64 nByte){
 34085    if( pFile->szChunk>0 ){
 34086      i64 nSize;                    /* Required file size */
 34087      struct stat buf;              /* Used to hold return values of fstat() */
 34088     
 34089      if( osFstat(pFile->h, &buf) ){
 34090        return SQLITE_IOERR_FSTAT;
 34091      }
 34092  
 34093      nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
 34094      if( nSize>(i64)buf.st_size ){
 34095  
 34096  #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
 34097        /* The code below is handling the return value of osFallocate() 
 34098        ** correctly. posix_fallocate() is defined to "returns zero on success, 
 34099        ** or an error number on  failure". See the manpage for details. */
 34100        int err;
 34101        do{
 34102          err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
 34103        }while( err==EINTR );
 34104        if( err ) return SQLITE_IOERR_WRITE;
 34105  #else
 34106        /* If the OS does not have posix_fallocate(), fake it. Write a 
 34107        ** single byte to the last byte in each block that falls entirely
 34108        ** within the extended region. Then, if required, a single byte
 34109        ** at offset (nSize-1), to set the size of the file correctly.
 34110        ** This is a similar technique to that used by glibc on systems
 34111        ** that do not have a real fallocate() call.
 34112        */
 34113        int nBlk = buf.st_blksize;  /* File-system block size */
 34114        int nWrite = 0;             /* Number of bytes written by seekAndWrite */
 34115        i64 iWrite;                 /* Next offset to write to */
 34116  
 34117        iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
 34118        assert( iWrite>=buf.st_size );
 34119        assert( ((iWrite+1)%nBlk)==0 );
 34120        for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
 34121          if( iWrite>=nSize ) iWrite = nSize - 1;
 34122          nWrite = seekAndWrite(pFile, iWrite, "", 1);
 34123          if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
 34124        }
 34125  #endif
 34126      }
 34127    }
 34128  
 34129  #if SQLITE_MAX_MMAP_SIZE>0
 34130    if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
 34131      int rc;
 34132      if( pFile->szChunk<=0 ){
 34133        if( robust_ftruncate(pFile->h, nByte) ){
 34134          storeLastErrno(pFile, errno);
 34135          return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
 34136        }
 34137      }
 34138  
 34139      rc = unixMapfile(pFile, nByte);
 34140      return rc;
 34141    }
 34142  #endif
 34143  
 34144    return SQLITE_OK;
 34145  }
 34146  
 34147  /*
 34148  ** If *pArg is initially negative then this is a query.  Set *pArg to
 34149  ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
 34150  **
 34151  ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
 34152  */
 34153  static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
 34154    if( *pArg<0 ){
 34155      *pArg = (pFile->ctrlFlags & mask)!=0;
 34156    }else if( (*pArg)==0 ){
 34157      pFile->ctrlFlags &= ~mask;
 34158    }else{
 34159      pFile->ctrlFlags |= mask;
 34160    }
 34161  }
 34162  
 34163  /* Forward declaration */
 34164  static int unixGetTempname(int nBuf, char *zBuf);
 34165  
 34166  /*
 34167  ** Information and control of an open file handle.
 34168  */
 34169  static int unixFileControl(sqlite3_file *id, int op, void *pArg){
 34170    unixFile *pFile = (unixFile*)id;
 34171    switch( op ){
 34172  #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
 34173      case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
 34174        int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
 34175        return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
 34176      }
 34177      case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
 34178        int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
 34179        return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
 34180      }
 34181      case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
 34182        int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
 34183        return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
 34184      }
 34185  #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
 34186  
 34187      case SQLITE_FCNTL_LOCKSTATE: {
 34188        *(int*)pArg = pFile->eFileLock;
 34189        return SQLITE_OK;
 34190      }
 34191      case SQLITE_FCNTL_LAST_ERRNO: {
 34192        *(int*)pArg = pFile->lastErrno;
 34193        return SQLITE_OK;
 34194      }
 34195      case SQLITE_FCNTL_CHUNK_SIZE: {
 34196        pFile->szChunk = *(int *)pArg;
 34197        return SQLITE_OK;
 34198      }
 34199      case SQLITE_FCNTL_SIZE_HINT: {
 34200        int rc;
 34201        SimulateIOErrorBenign(1);
 34202        rc = fcntlSizeHint(pFile, *(i64 *)pArg);
 34203        SimulateIOErrorBenign(0);
 34204        return rc;
 34205      }
 34206      case SQLITE_FCNTL_PERSIST_WAL: {
 34207        unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
 34208        return SQLITE_OK;
 34209      }
 34210      case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
 34211        unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
 34212        return SQLITE_OK;
 34213      }
 34214      case SQLITE_FCNTL_VFSNAME: {
 34215        *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
 34216        return SQLITE_OK;
 34217      }
 34218      case SQLITE_FCNTL_TEMPFILENAME: {
 34219        char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
 34220        if( zTFile ){
 34221          unixGetTempname(pFile->pVfs->mxPathname, zTFile);
 34222          *(char**)pArg = zTFile;
 34223        }
 34224        return SQLITE_OK;
 34225      }
 34226      case SQLITE_FCNTL_HAS_MOVED: {
 34227        *(int*)pArg = fileHasMoved(pFile);
 34228        return SQLITE_OK;
 34229      }
 34230  #if SQLITE_MAX_MMAP_SIZE>0
 34231      case SQLITE_FCNTL_MMAP_SIZE: {
 34232        i64 newLimit = *(i64*)pArg;
 34233        int rc = SQLITE_OK;
 34234        if( newLimit>sqlite3GlobalConfig.mxMmap ){
 34235          newLimit = sqlite3GlobalConfig.mxMmap;
 34236        }
 34237  
 34238        /* The value of newLimit may be eventually cast to (size_t) and passed
 34239        ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
 34240        ** 64-bit type. */
 34241        if( newLimit>0 && sizeof(size_t)<8 ){
 34242          newLimit = (newLimit & 0x7FFFFFFF);
 34243        }
 34244  
 34245        *(i64*)pArg = pFile->mmapSizeMax;
 34246        if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
 34247          pFile->mmapSizeMax = newLimit;
 34248          if( pFile->mmapSize>0 ){
 34249            unixUnmapfile(pFile);
 34250            rc = unixMapfile(pFile, -1);
 34251          }
 34252        }
 34253        return rc;
 34254      }
 34255  #endif
 34256  #ifdef SQLITE_DEBUG
 34257      /* The pager calls this method to signal that it has done
 34258      ** a rollback and that the database is therefore unchanged and
 34259      ** it hence it is OK for the transaction change counter to be
 34260      ** unchanged.
 34261      */
 34262      case SQLITE_FCNTL_DB_UNCHANGED: {
 34263        ((unixFile*)id)->dbUpdate = 0;
 34264        return SQLITE_OK;
 34265      }
 34266  #endif
 34267  #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
 34268      case SQLITE_FCNTL_SET_LOCKPROXYFILE:
 34269      case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
 34270        return proxyFileControl(id,op,pArg);
 34271      }
 34272  #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
 34273    }
 34274    return SQLITE_NOTFOUND;
 34275  }
 34276  
 34277  /*
 34278  ** If pFd->sectorSize is non-zero when this function is called, it is a
 34279  ** no-op. Otherwise, the values of pFd->sectorSize and 
 34280  ** pFd->deviceCharacteristics are set according to the file-system 
 34281  ** characteristics. 
 34282  **
 34283  ** There are two versions of this function. One for QNX and one for all
 34284  ** other systems.
 34285  */
 34286  #ifndef __QNXNTO__
 34287  static void setDeviceCharacteristics(unixFile *pFd){
 34288    assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
 34289    if( pFd->sectorSize==0 ){
 34290  #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
 34291      int res;
 34292      u32 f = 0;
 34293  
 34294      /* Check for support for F2FS atomic batch writes. */
 34295      res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
 34296      if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
 34297        pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
 34298      }
 34299  #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
 34300  
 34301      /* Set the POWERSAFE_OVERWRITE flag if requested. */
 34302      if( pFd->ctrlFlags & UNIXFILE_PSOW ){
 34303        pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
 34304      }
 34305  
 34306      pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
 34307    }
 34308  }
 34309  #else
 34310  #include <sys/dcmd_blk.h>
 34311  #include <sys/statvfs.h>
 34312  static void setDeviceCharacteristics(unixFile *pFile){
 34313    if( pFile->sectorSize == 0 ){
 34314      struct statvfs fsInfo;
 34315         
 34316      /* Set defaults for non-supported filesystems */
 34317      pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
 34318      pFile->deviceCharacteristics = 0;
 34319      if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
 34320        return pFile->sectorSize;
 34321      }
 34322  
 34323      if( !strcmp(fsInfo.f_basetype, "tmp") ) {
 34324        pFile->sectorSize = fsInfo.f_bsize;
 34325        pFile->deviceCharacteristics =
 34326          SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
 34327          SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
 34328                                        ** the write succeeds */
 34329          SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
 34330                                        ** so it is ordered */
 34331          0;
 34332      }else if( strstr(fsInfo.f_basetype, "etfs") ){
 34333        pFile->sectorSize = fsInfo.f_bsize;
 34334        pFile->deviceCharacteristics =
 34335          /* etfs cluster size writes are atomic */
 34336          (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
 34337          SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
 34338                                        ** the write succeeds */
 34339          SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
 34340                                        ** so it is ordered */
 34341          0;
 34342      }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
 34343        pFile->sectorSize = fsInfo.f_bsize;
 34344        pFile->deviceCharacteristics =
 34345          SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
 34346          SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
 34347                                        ** the write succeeds */
 34348          SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
 34349                                        ** so it is ordered */
 34350          0;
 34351      }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
 34352        pFile->sectorSize = fsInfo.f_bsize;
 34353        pFile->deviceCharacteristics =
 34354          /* full bitset of atomics from max sector size and smaller */
 34355          ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
 34356          SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
 34357                                        ** so it is ordered */
 34358          0;
 34359      }else if( strstr(fsInfo.f_basetype, "dos") ){
 34360        pFile->sectorSize = fsInfo.f_bsize;
 34361        pFile->deviceCharacteristics =
 34362          /* full bitset of atomics from max sector size and smaller */
 34363          ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
 34364          SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
 34365                                        ** so it is ordered */
 34366          0;
 34367      }else{
 34368        pFile->deviceCharacteristics =
 34369          SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
 34370          SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
 34371                                        ** the write succeeds */
 34372          0;
 34373      }
 34374    }
 34375    /* Last chance verification.  If the sector size isn't a multiple of 512
 34376    ** then it isn't valid.*/
 34377    if( pFile->sectorSize % 512 != 0 ){
 34378      pFile->deviceCharacteristics = 0;
 34379      pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
 34380    }
 34381  }
 34382  #endif
 34383  
 34384  /*
 34385  ** Return the sector size in bytes of the underlying block device for
 34386  ** the specified file. This is almost always 512 bytes, but may be
 34387  ** larger for some devices.
 34388  **
 34389  ** SQLite code assumes this function cannot fail. It also assumes that
 34390  ** if two files are created in the same file-system directory (i.e.
 34391  ** a database and its journal file) that the sector size will be the
 34392  ** same for both.
 34393  */
 34394  static int unixSectorSize(sqlite3_file *id){
 34395    unixFile *pFd = (unixFile*)id;
 34396    setDeviceCharacteristics(pFd);
 34397    return pFd->sectorSize;
 34398  }
 34399  
 34400  /*
 34401  ** Return the device characteristics for the file.
 34402  **
 34403  ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
 34404  ** However, that choice is controversial since technically the underlying
 34405  ** file system does not always provide powersafe overwrites.  (In other
 34406  ** words, after a power-loss event, parts of the file that were never
 34407  ** written might end up being altered.)  However, non-PSOW behavior is very,
 34408  ** very rare.  And asserting PSOW makes a large reduction in the amount
 34409  ** of required I/O for journaling, since a lot of padding is eliminated.
 34410  **  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
 34411  ** available to turn it off and URI query parameter available to turn it off.
 34412  */
 34413  static int unixDeviceCharacteristics(sqlite3_file *id){
 34414    unixFile *pFd = (unixFile*)id;
 34415    setDeviceCharacteristics(pFd);
 34416    return pFd->deviceCharacteristics;
 34417  }
 34418  
 34419  #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
 34420  
 34421  /*
 34422  ** Return the system page size.
 34423  **
 34424  ** This function should not be called directly by other code in this file. 
 34425  ** Instead, it should be called via macro osGetpagesize().
 34426  */
 34427  static int unixGetpagesize(void){
 34428  #if OS_VXWORKS
 34429    return 1024;
 34430  #elif defined(_BSD_SOURCE)
 34431    return getpagesize();
 34432  #else
 34433    return (int)sysconf(_SC_PAGESIZE);
 34434  #endif
 34435  }
 34436  
 34437  #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
 34438  
 34439  #ifndef SQLITE_OMIT_WAL
 34440  
 34441  /*
 34442  ** Object used to represent an shared memory buffer.  
 34443  **
 34444  ** When multiple threads all reference the same wal-index, each thread
 34445  ** has its own unixShm object, but they all point to a single instance
 34446  ** of this unixShmNode object.  In other words, each wal-index is opened
 34447  ** only once per process.
 34448  **
 34449  ** Each unixShmNode object is connected to a single unixInodeInfo object.
 34450  ** We could coalesce this object into unixInodeInfo, but that would mean
 34451  ** every open file that does not use shared memory (in other words, most
 34452  ** open files) would have to carry around this extra information.  So
 34453  ** the unixInodeInfo object contains a pointer to this unixShmNode object
 34454  ** and the unixShmNode object is created only when needed.
 34455  **
 34456  ** unixMutexHeld() must be true when creating or destroying
 34457  ** this object or while reading or writing the following fields:
 34458  **
 34459  **      nRef
 34460  **
 34461  ** The following fields are read-only after the object is created:
 34462  ** 
 34463  **      fid
 34464  **      zFilename
 34465  **
 34466  ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
 34467  ** unixMutexHeld() is true when reading or writing any other field
 34468  ** in this structure.
 34469  */
 34470  struct unixShmNode {
 34471    unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
 34472    sqlite3_mutex *mutex;      /* Mutex to access this object */
 34473    char *zFilename;           /* Name of the mmapped file */
 34474    int h;                     /* Open file descriptor */
 34475    int szRegion;              /* Size of shared-memory regions */
 34476    u16 nRegion;               /* Size of array apRegion */
 34477    u8 isReadonly;             /* True if read-only */
 34478    char **apRegion;           /* Array of mapped shared-memory regions */
 34479    int nRef;                  /* Number of unixShm objects pointing to this */
 34480    unixShm *pFirst;           /* All unixShm objects pointing to this */
 34481  #ifdef SQLITE_DEBUG
 34482    u8 exclMask;               /* Mask of exclusive locks held */
 34483    u8 sharedMask;             /* Mask of shared locks held */
 34484    u8 nextShmId;              /* Next available unixShm.id value */
 34485  #endif
 34486  };
 34487  
 34488  /*
 34489  ** Structure used internally by this VFS to record the state of an
 34490  ** open shared memory connection.
 34491  **
 34492  ** The following fields are initialized when this object is created and
 34493  ** are read-only thereafter:
 34494  **
 34495  **    unixShm.pFile
 34496  **    unixShm.id
 34497  **
 34498  ** All other fields are read/write.  The unixShm.pFile->mutex must be held
 34499  ** while accessing any read/write fields.
 34500  */
 34501  struct unixShm {
 34502    unixShmNode *pShmNode;     /* The underlying unixShmNode object */
 34503    unixShm *pNext;            /* Next unixShm with the same unixShmNode */
 34504    u8 hasMutex;               /* True if holding the unixShmNode mutex */
 34505    u8 id;                     /* Id of this connection within its unixShmNode */
 34506    u16 sharedMask;            /* Mask of shared locks held */
 34507    u16 exclMask;              /* Mask of exclusive locks held */
 34508  };
 34509  
 34510  /*
 34511  ** Constants used for locking
 34512  */
 34513  #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
 34514  #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
 34515  
 34516  /*
 34517  ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
 34518  **
 34519  ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
 34520  ** otherwise.
 34521  */
 34522  static int unixShmSystemLock(
 34523    unixFile *pFile,       /* Open connection to the WAL file */
 34524    int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
 34525    int ofst,              /* First byte of the locking range */
 34526    int n                  /* Number of bytes to lock */
 34527  ){
 34528    unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
 34529    struct flock f;        /* The posix advisory locking structure */
 34530    int rc = SQLITE_OK;    /* Result code form fcntl() */
 34531  
 34532    /* Access to the unixShmNode object is serialized by the caller */
 34533    pShmNode = pFile->pInode->pShmNode;
 34534    assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
 34535  
 34536    /* Shared locks never span more than one byte */
 34537    assert( n==1 || lockType!=F_RDLCK );
 34538  
 34539    /* Locks are within range */
 34540    assert( n>=1 && n<=SQLITE_SHM_NLOCK );
 34541  
 34542    if( pShmNode->h>=0 ){
 34543      /* Initialize the locking parameters */
 34544      memset(&f, 0, sizeof(f));
 34545      f.l_type = lockType;
 34546      f.l_whence = SEEK_SET;
 34547      f.l_start = ofst;
 34548      f.l_len = n;
 34549  
 34550      rc = osFcntl(pShmNode->h, F_SETLK, &f);
 34551      rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
 34552    }
 34553  
 34554    /* Update the global lock state and do debug tracing */
 34555  #ifdef SQLITE_DEBUG
 34556    { u16 mask;
 34557    OSTRACE(("SHM-LOCK "));
 34558    mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
 34559    if( rc==SQLITE_OK ){
 34560      if( lockType==F_UNLCK ){
 34561        OSTRACE(("unlock %d ok", ofst));
 34562        pShmNode->exclMask &= ~mask;
 34563        pShmNode->sharedMask &= ~mask;
 34564      }else if( lockType==F_RDLCK ){
 34565        OSTRACE(("read-lock %d ok", ofst));
 34566        pShmNode->exclMask &= ~mask;
 34567        pShmNode->sharedMask |= mask;
 34568      }else{
 34569        assert( lockType==F_WRLCK );
 34570        OSTRACE(("write-lock %d ok", ofst));
 34571        pShmNode->exclMask |= mask;
 34572        pShmNode->sharedMask &= ~mask;
 34573      }
 34574    }else{
 34575      if( lockType==F_UNLCK ){
 34576        OSTRACE(("unlock %d failed", ofst));
 34577      }else if( lockType==F_RDLCK ){
 34578        OSTRACE(("read-lock failed"));
 34579      }else{
 34580        assert( lockType==F_WRLCK );
 34581        OSTRACE(("write-lock %d failed", ofst));
 34582      }
 34583    }
 34584    OSTRACE((" - afterwards %03x,%03x\n",
 34585             pShmNode->sharedMask, pShmNode->exclMask));
 34586    }
 34587  #endif
 34588  
 34589    return rc;        
 34590  }
 34591  
 34592  /*
 34593  ** Return the minimum number of 32KB shm regions that should be mapped at
 34594  ** a time, assuming that each mapping must be an integer multiple of the
 34595  ** current system page-size.
 34596  **
 34597  ** Usually, this is 1. The exception seems to be systems that are configured
 34598  ** to use 64KB pages - in this case each mapping must cover at least two
 34599  ** shm regions.
 34600  */
 34601  static int unixShmRegionPerMap(void){
 34602    int shmsz = 32*1024;            /* SHM region size */
 34603    int pgsz = osGetpagesize();   /* System page size */
 34604    assert( ((pgsz-1)&pgsz)==0 );   /* Page size must be a power of 2 */
 34605    if( pgsz<shmsz ) return 1;
 34606    return pgsz/shmsz;
 34607  }
 34608  
 34609  /*
 34610  ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
 34611  **
 34612  ** This is not a VFS shared-memory method; it is a utility function called
 34613  ** by VFS shared-memory methods.
 34614  */
 34615  static void unixShmPurge(unixFile *pFd){
 34616    unixShmNode *p = pFd->pInode->pShmNode;
 34617    assert( unixMutexHeld() );
 34618    if( p && ALWAYS(p->nRef==0) ){
 34619      int nShmPerMap = unixShmRegionPerMap();
 34620      int i;
 34621      assert( p->pInode==pFd->pInode );
 34622      sqlite3_mutex_free(p->mutex);
 34623      for(i=0; i<p->nRegion; i+=nShmPerMap){
 34624        if( p->h>=0 ){
 34625          osMunmap(p->apRegion[i], p->szRegion);
 34626        }else{
 34627          sqlite3_free(p->apRegion[i]);
 34628        }
 34629      }
 34630      sqlite3_free(p->apRegion);
 34631      if( p->h>=0 ){
 34632        robust_close(pFd, p->h, __LINE__);
 34633        p->h = -1;
 34634      }
 34635      p->pInode->pShmNode = 0;
 34636      sqlite3_free(p);
 34637    }
 34638  }
 34639  
 34640  /*
 34641  ** Open a shared-memory area associated with open database file pDbFd.  
 34642  ** This particular implementation uses mmapped files.
 34643  **
 34644  ** The file used to implement shared-memory is in the same directory
 34645  ** as the open database file and has the same name as the open database
 34646  ** file with the "-shm" suffix added.  For example, if the database file
 34647  ** is "/home/user1/config.db" then the file that is created and mmapped
 34648  ** for shared memory will be called "/home/user1/config.db-shm".  
 34649  **
 34650  ** Another approach to is to use files in /dev/shm or /dev/tmp or an
 34651  ** some other tmpfs mount. But if a file in a different directory
 34652  ** from the database file is used, then differing access permissions
 34653  ** or a chroot() might cause two different processes on the same
 34654  ** database to end up using different files for shared memory - 
 34655  ** meaning that their memory would not really be shared - resulting
 34656  ** in database corruption.  Nevertheless, this tmpfs file usage
 34657  ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
 34658  ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
 34659  ** option results in an incompatible build of SQLite;  builds of SQLite
 34660  ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
 34661  ** same database file at the same time, database corruption will likely
 34662  ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
 34663  ** "unsupported" and may go away in a future SQLite release.
 34664  **
 34665  ** When opening a new shared-memory file, if no other instances of that
 34666  ** file are currently open, in this process or in other processes, then
 34667  ** the file must be truncated to zero length or have its header cleared.
 34668  **
 34669  ** If the original database file (pDbFd) is using the "unix-excl" VFS
 34670  ** that means that an exclusive lock is held on the database file and
 34671  ** that no other processes are able to read or write the database.  In
 34672  ** that case, we do not really need shared memory.  No shared memory
 34673  ** file is created.  The shared memory will be simulated with heap memory.
 34674  */
 34675  static int unixOpenSharedMemory(unixFile *pDbFd){
 34676    struct unixShm *p = 0;          /* The connection to be opened */
 34677    struct unixShmNode *pShmNode;   /* The underlying mmapped file */
 34678    int rc;                         /* Result code */
 34679    unixInodeInfo *pInode;          /* The inode of fd */
 34680    char *zShmFilename;             /* Name of the file used for SHM */
 34681    int nShmFilename;               /* Size of the SHM filename in bytes */
 34682  
 34683    /* Allocate space for the new unixShm object. */
 34684    p = sqlite3_malloc64( sizeof(*p) );
 34685    if( p==0 ) return SQLITE_NOMEM_BKPT;
 34686    memset(p, 0, sizeof(*p));
 34687    assert( pDbFd->pShm==0 );
 34688  
 34689    /* Check to see if a unixShmNode object already exists. Reuse an existing
 34690    ** one if present. Create a new one if necessary.
 34691    */
 34692    unixEnterMutex();
 34693    pInode = pDbFd->pInode;
 34694    pShmNode = pInode->pShmNode;
 34695    if( pShmNode==0 ){
 34696      struct stat sStat;                 /* fstat() info for database file */
 34697  #ifndef SQLITE_SHM_DIRECTORY
 34698      const char *zBasePath = pDbFd->zPath;
 34699  #endif
 34700  
 34701      /* Call fstat() to figure out the permissions on the database file. If
 34702      ** a new *-shm file is created, an attempt will be made to create it
 34703      ** with the same permissions.
 34704      */
 34705      if( osFstat(pDbFd->h, &sStat) ){
 34706        rc = SQLITE_IOERR_FSTAT;
 34707        goto shm_open_err;
 34708      }
 34709  
 34710  #ifdef SQLITE_SHM_DIRECTORY
 34711      nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
 34712  #else
 34713      nShmFilename = 6 + (int)strlen(zBasePath);
 34714  #endif
 34715      pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
 34716      if( pShmNode==0 ){
 34717        rc = SQLITE_NOMEM_BKPT;
 34718        goto shm_open_err;
 34719      }
 34720      memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
 34721      zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
 34722  #ifdef SQLITE_SHM_DIRECTORY
 34723      sqlite3_snprintf(nShmFilename, zShmFilename, 
 34724                       SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
 34725                       (u32)sStat.st_ino, (u32)sStat.st_dev);
 34726  #else
 34727      sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
 34728      sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
 34729  #endif
 34730      pShmNode->h = -1;
 34731      pDbFd->pInode->pShmNode = pShmNode;
 34732      pShmNode->pInode = pDbFd->pInode;
 34733      if( sqlite3GlobalConfig.bCoreMutex ){
 34734        pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
 34735        if( pShmNode->mutex==0 ){
 34736          rc = SQLITE_NOMEM_BKPT;
 34737          goto shm_open_err;
 34738        }
 34739      }
 34740  
 34741      if( pInode->bProcessLock==0 ){
 34742        int openFlags = O_RDWR | O_CREAT;
 34743        if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
 34744          openFlags = O_RDONLY;
 34745          pShmNode->isReadonly = 1;
 34746        }
 34747        pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
 34748        if( pShmNode->h<0 ){
 34749          rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
 34750          goto shm_open_err;
 34751        }
 34752  
 34753        /* If this process is running as root, make sure that the SHM file
 34754        ** is owned by the same user that owns the original database.  Otherwise,
 34755        ** the original owner will not be able to connect.
 34756        */
 34757        robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
 34758    
 34759        /* Check to see if another process is holding the dead-man switch.
 34760        ** If not, truncate the file to zero length. 
 34761        */
 34762        rc = SQLITE_OK;
 34763        if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
 34764          if( robust_ftruncate(pShmNode->h, 0) ){
 34765            rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
 34766          }
 34767        }
 34768        if( rc==SQLITE_OK ){
 34769          rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
 34770        }
 34771        if( rc ) goto shm_open_err;
 34772      }
 34773    }
 34774  
 34775    /* Make the new connection a child of the unixShmNode */
 34776    p->pShmNode = pShmNode;
 34777  #ifdef SQLITE_DEBUG
 34778    p->id = pShmNode->nextShmId++;
 34779  #endif
 34780    pShmNode->nRef++;
 34781    pDbFd->pShm = p;
 34782    unixLeaveMutex();
 34783  
 34784    /* The reference count on pShmNode has already been incremented under
 34785    ** the cover of the unixEnterMutex() mutex and the pointer from the
 34786    ** new (struct unixShm) object to the pShmNode has been set. All that is
 34787    ** left to do is to link the new object into the linked list starting
 34788    ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
 34789    ** mutex.
 34790    */
 34791    sqlite3_mutex_enter(pShmNode->mutex);
 34792    p->pNext = pShmNode->pFirst;
 34793    pShmNode->pFirst = p;
 34794    sqlite3_mutex_leave(pShmNode->mutex);
 34795    return SQLITE_OK;
 34796  
 34797    /* Jump here on any error */
 34798  shm_open_err:
 34799    unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
 34800    sqlite3_free(p);
 34801    unixLeaveMutex();
 34802    return rc;
 34803  }
 34804  
 34805  /*
 34806  ** This function is called to obtain a pointer to region iRegion of the 
 34807  ** shared-memory associated with the database file fd. Shared-memory regions 
 34808  ** are numbered starting from zero. Each shared-memory region is szRegion 
 34809  ** bytes in size.
 34810  **
 34811  ** If an error occurs, an error code is returned and *pp is set to NULL.
 34812  **
 34813  ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
 34814  ** region has not been allocated (by any client, including one running in a
 34815  ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
 34816  ** bExtend is non-zero and the requested shared-memory region has not yet 
 34817  ** been allocated, it is allocated by this function.
 34818  **
 34819  ** If the shared-memory region has already been allocated or is allocated by
 34820  ** this call as described above, then it is mapped into this processes 
 34821  ** address space (if it is not already), *pp is set to point to the mapped 
 34822  ** memory and SQLITE_OK returned.
 34823  */
 34824  static int unixShmMap(
 34825    sqlite3_file *fd,               /* Handle open on database file */
 34826    int iRegion,                    /* Region to retrieve */
 34827    int szRegion,                   /* Size of regions */
 34828    int bExtend,                    /* True to extend file if necessary */
 34829    void volatile **pp              /* OUT: Mapped memory */
 34830  ){
 34831    unixFile *pDbFd = (unixFile*)fd;
 34832    unixShm *p;
 34833    unixShmNode *pShmNode;
 34834    int rc = SQLITE_OK;
 34835    int nShmPerMap = unixShmRegionPerMap();
 34836    int nReqRegion;
 34837  
 34838    /* If the shared-memory file has not yet been opened, open it now. */
 34839    if( pDbFd->pShm==0 ){
 34840      rc = unixOpenSharedMemory(pDbFd);
 34841      if( rc!=SQLITE_OK ) return rc;
 34842    }
 34843  
 34844    p = pDbFd->pShm;
 34845    pShmNode = p->pShmNode;
 34846    sqlite3_mutex_enter(pShmNode->mutex);
 34847    assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
 34848    assert( pShmNode->pInode==pDbFd->pInode );
 34849    assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
 34850    assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
 34851  
 34852    /* Minimum number of regions required to be mapped. */
 34853    nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
 34854  
 34855    if( pShmNode->nRegion<nReqRegion ){
 34856      char **apNew;                      /* New apRegion[] array */
 34857      int nByte = nReqRegion*szRegion;   /* Minimum required file size */
 34858      struct stat sStat;                 /* Used by fstat() */
 34859  
 34860      pShmNode->szRegion = szRegion;
 34861  
 34862      if( pShmNode->h>=0 ){
 34863        /* The requested region is not mapped into this processes address space.
 34864        ** Check to see if it has been allocated (i.e. if the wal-index file is
 34865        ** large enough to contain the requested region).
 34866        */
 34867        if( osFstat(pShmNode->h, &sStat) ){
 34868          rc = SQLITE_IOERR_SHMSIZE;
 34869          goto shmpage_out;
 34870        }
 34871    
 34872        if( sStat.st_size<nByte ){
 34873          /* The requested memory region does not exist. If bExtend is set to
 34874          ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
 34875          */
 34876          if( !bExtend ){
 34877            goto shmpage_out;
 34878          }
 34879  
 34880          /* Alternatively, if bExtend is true, extend the file. Do this by
 34881          ** writing a single byte to the end of each (OS) page being
 34882          ** allocated or extended. Technically, we need only write to the
 34883          ** last page in order to extend the file. But writing to all new
 34884          ** pages forces the OS to allocate them immediately, which reduces
 34885          ** the chances of SIGBUS while accessing the mapped region later on.
 34886          */
 34887          else{
 34888            static const int pgsz = 4096;
 34889            int iPg;
 34890  
 34891            /* Write to the last byte of each newly allocated or extended page */
 34892            assert( (nByte % pgsz)==0 );
 34893            for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
 34894              int x = 0;
 34895              if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
 34896                const char *zFile = pShmNode->zFilename;
 34897                rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
 34898                goto shmpage_out;
 34899              }
 34900            }
 34901          }
 34902        }
 34903      }
 34904  
 34905      /* Map the requested memory region into this processes address space. */
 34906      apNew = (char **)sqlite3_realloc(
 34907          pShmNode->apRegion, nReqRegion*sizeof(char *)
 34908      );
 34909      if( !apNew ){
 34910        rc = SQLITE_IOERR_NOMEM_BKPT;
 34911        goto shmpage_out;
 34912      }
 34913      pShmNode->apRegion = apNew;
 34914      while( pShmNode->nRegion<nReqRegion ){
 34915        int nMap = szRegion*nShmPerMap;
 34916        int i;
 34917        void *pMem;
 34918        if( pShmNode->h>=0 ){
 34919          pMem = osMmap(0, nMap,
 34920              pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, 
 34921              MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
 34922          );
 34923          if( pMem==MAP_FAILED ){
 34924            rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
 34925            goto shmpage_out;
 34926          }
 34927        }else{
 34928          pMem = sqlite3_malloc64(szRegion);
 34929          if( pMem==0 ){
 34930            rc = SQLITE_NOMEM_BKPT;
 34931            goto shmpage_out;
 34932          }
 34933          memset(pMem, 0, szRegion);
 34934        }
 34935  
 34936        for(i=0; i<nShmPerMap; i++){
 34937          pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
 34938        }
 34939        pShmNode->nRegion += nShmPerMap;
 34940      }
 34941    }
 34942  
 34943  shmpage_out:
 34944    if( pShmNode->nRegion>iRegion ){
 34945      *pp = pShmNode->apRegion[iRegion];
 34946    }else{
 34947      *pp = 0;
 34948    }
 34949    if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
 34950    sqlite3_mutex_leave(pShmNode->mutex);
 34951    return rc;
 34952  }
 34953  
 34954  /*
 34955  ** Change the lock state for a shared-memory segment.
 34956  **
 34957  ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
 34958  ** different here than in posix.  In xShmLock(), one can go from unlocked
 34959  ** to shared and back or from unlocked to exclusive and back.  But one may
 34960  ** not go from shared to exclusive or from exclusive to shared.
 34961  */
 34962  static int unixShmLock(
 34963    sqlite3_file *fd,          /* Database file holding the shared memory */
 34964    int ofst,                  /* First lock to acquire or release */
 34965    int n,                     /* Number of locks to acquire or release */
 34966    int flags                  /* What to do with the lock */
 34967  ){
 34968    unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
 34969    unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
 34970    unixShm *pX;                          /* For looping over all siblings */
 34971    unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
 34972    int rc = SQLITE_OK;                   /* Result code */
 34973    u16 mask;                             /* Mask of locks to take or release */
 34974  
 34975    assert( pShmNode==pDbFd->pInode->pShmNode );
 34976    assert( pShmNode->pInode==pDbFd->pInode );
 34977    assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
 34978    assert( n>=1 );
 34979    assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
 34980         || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
 34981         || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
 34982         || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
 34983    assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
 34984    assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
 34985    assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
 34986  
 34987    mask = (1<<(ofst+n)) - (1<<ofst);
 34988    assert( n>1 || mask==(1<<ofst) );
 34989    sqlite3_mutex_enter(pShmNode->mutex);
 34990    if( flags & SQLITE_SHM_UNLOCK ){
 34991      u16 allMask = 0; /* Mask of locks held by siblings */
 34992  
 34993      /* See if any siblings hold this same lock */
 34994      for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
 34995        if( pX==p ) continue;
 34996        assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
 34997        allMask |= pX->sharedMask;
 34998      }
 34999  
 35000      /* Unlock the system-level locks */
 35001      if( (mask & allMask)==0 ){
 35002        rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
 35003      }else{
 35004        rc = SQLITE_OK;
 35005      }
 35006  
 35007      /* Undo the local locks */
 35008      if( rc==SQLITE_OK ){
 35009        p->exclMask &= ~mask;
 35010        p->sharedMask &= ~mask;
 35011      } 
 35012    }else if( flags & SQLITE_SHM_SHARED ){
 35013      u16 allShared = 0;  /* Union of locks held by connections other than "p" */
 35014  
 35015      /* Find out which shared locks are already held by sibling connections.
 35016      ** If any sibling already holds an exclusive lock, go ahead and return
 35017      ** SQLITE_BUSY.
 35018      */
 35019      for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
 35020        if( (pX->exclMask & mask)!=0 ){
 35021          rc = SQLITE_BUSY;
 35022          break;
 35023        }
 35024        allShared |= pX->sharedMask;
 35025      }
 35026  
 35027      /* Get shared locks at the system level, if necessary */
 35028      if( rc==SQLITE_OK ){
 35029        if( (allShared & mask)==0 ){
 35030          rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
 35031        }else{
 35032          rc = SQLITE_OK;
 35033        }
 35034      }
 35035  
 35036      /* Get the local shared locks */
 35037      if( rc==SQLITE_OK ){
 35038        p->sharedMask |= mask;
 35039      }
 35040    }else{
 35041      /* Make sure no sibling connections hold locks that will block this
 35042      ** lock.  If any do, return SQLITE_BUSY right away.
 35043      */
 35044      for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
 35045        if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
 35046          rc = SQLITE_BUSY;
 35047          break;
 35048        }
 35049      }
 35050    
 35051      /* Get the exclusive locks at the system level.  Then if successful
 35052      ** also mark the local connection as being locked.
 35053      */
 35054      if( rc==SQLITE_OK ){
 35055        rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
 35056        if( rc==SQLITE_OK ){
 35057          assert( (p->sharedMask & mask)==0 );
 35058          p->exclMask |= mask;
 35059        }
 35060      }
 35061    }
 35062    sqlite3_mutex_leave(pShmNode->mutex);
 35063    OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
 35064             p->id, osGetpid(0), p->sharedMask, p->exclMask));
 35065    return rc;
 35066  }
 35067  
 35068  /*
 35069  ** Implement a memory barrier or memory fence on shared memory.  
 35070  **
 35071  ** All loads and stores begun before the barrier must complete before
 35072  ** any load or store begun after the barrier.
 35073  */
 35074  static void unixShmBarrier(
 35075    sqlite3_file *fd                /* Database file holding the shared memory */
 35076  ){
 35077    UNUSED_PARAMETER(fd);
 35078    sqlite3MemoryBarrier();         /* compiler-defined memory barrier */
 35079    unixEnterMutex();               /* Also mutex, for redundancy */
 35080    unixLeaveMutex();
 35081  }
 35082  
 35083  /*
 35084  ** Close a connection to shared-memory.  Delete the underlying 
 35085  ** storage if deleteFlag is true.
 35086  **
 35087  ** If there is no shared memory associated with the connection then this
 35088  ** routine is a harmless no-op.
 35089  */
 35090  static int unixShmUnmap(
 35091    sqlite3_file *fd,               /* The underlying database file */
 35092    int deleteFlag                  /* Delete shared-memory if true */
 35093  ){
 35094    unixShm *p;                     /* The connection to be closed */
 35095    unixShmNode *pShmNode;          /* The underlying shared-memory file */
 35096    unixShm **pp;                   /* For looping over sibling connections */
 35097    unixFile *pDbFd;                /* The underlying database file */
 35098  
 35099    pDbFd = (unixFile*)fd;
 35100    p = pDbFd->pShm;
 35101    if( p==0 ) return SQLITE_OK;
 35102    pShmNode = p->pShmNode;
 35103  
 35104    assert( pShmNode==pDbFd->pInode->pShmNode );
 35105    assert( pShmNode->pInode==pDbFd->pInode );
 35106  
 35107    /* Remove connection p from the set of connections associated
 35108    ** with pShmNode */
 35109    sqlite3_mutex_enter(pShmNode->mutex);
 35110    for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
 35111    *pp = p->pNext;
 35112  
 35113    /* Free the connection p */
 35114    sqlite3_free(p);
 35115    pDbFd->pShm = 0;
 35116    sqlite3_mutex_leave(pShmNode->mutex);
 35117  
 35118    /* If pShmNode->nRef has reached 0, then close the underlying
 35119    ** shared-memory file, too */
 35120    unixEnterMutex();
 35121    assert( pShmNode->nRef>0 );
 35122    pShmNode->nRef--;
 35123    if( pShmNode->nRef==0 ){
 35124      if( deleteFlag && pShmNode->h>=0 ){
 35125        osUnlink(pShmNode->zFilename);
 35126      }
 35127      unixShmPurge(pDbFd);
 35128    }
 35129    unixLeaveMutex();
 35130  
 35131    return SQLITE_OK;
 35132  }
 35133  
 35134  
 35135  #else
 35136  # define unixShmMap     0
 35137  # define unixShmLock    0
 35138  # define unixShmBarrier 0
 35139  # define unixShmUnmap   0
 35140  #endif /* #ifndef SQLITE_OMIT_WAL */
 35141  
 35142  #if SQLITE_MAX_MMAP_SIZE>0
 35143  /*
 35144  ** If it is currently memory mapped, unmap file pFd.
 35145  */
 35146  static void unixUnmapfile(unixFile *pFd){
 35147    assert( pFd->nFetchOut==0 );
 35148    if( pFd->pMapRegion ){
 35149      osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
 35150      pFd->pMapRegion = 0;
 35151      pFd->mmapSize = 0;
 35152      pFd->mmapSizeActual = 0;
 35153    }
 35154  }
 35155  
 35156  /*
 35157  ** Attempt to set the size of the memory mapping maintained by file 
 35158  ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
 35159  **
 35160  ** If successful, this function sets the following variables:
 35161  **
 35162  **       unixFile.pMapRegion
 35163  **       unixFile.mmapSize
 35164  **       unixFile.mmapSizeActual
 35165  **
 35166  ** If unsuccessful, an error message is logged via sqlite3_log() and
 35167  ** the three variables above are zeroed. In this case SQLite should
 35168  ** continue accessing the database using the xRead() and xWrite()
 35169  ** methods.
 35170  */
 35171  static void unixRemapfile(
 35172    unixFile *pFd,                  /* File descriptor object */
 35173    i64 nNew                        /* Required mapping size */
 35174  ){
 35175    const char *zErr = "mmap";
 35176    int h = pFd->h;                      /* File descriptor open on db file */
 35177    u8 *pOrig = (u8 *)pFd->pMapRegion;   /* Pointer to current file mapping */
 35178    i64 nOrig = pFd->mmapSizeActual;     /* Size of pOrig region in bytes */
 35179    u8 *pNew = 0;                        /* Location of new mapping */
 35180    int flags = PROT_READ;               /* Flags to pass to mmap() */
 35181  
 35182    assert( pFd->nFetchOut==0 );
 35183    assert( nNew>pFd->mmapSize );
 35184    assert( nNew<=pFd->mmapSizeMax );
 35185    assert( nNew>0 );
 35186    assert( pFd->mmapSizeActual>=pFd->mmapSize );
 35187    assert( MAP_FAILED!=0 );
 35188  
 35189  #ifdef SQLITE_MMAP_READWRITE
 35190    if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
 35191  #endif
 35192  
 35193    if( pOrig ){
 35194  #if HAVE_MREMAP
 35195      i64 nReuse = pFd->mmapSize;
 35196  #else
 35197      const int szSyspage = osGetpagesize();
 35198      i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
 35199  #endif
 35200      u8 *pReq = &pOrig[nReuse];
 35201  
 35202      /* Unmap any pages of the existing mapping that cannot be reused. */
 35203      if( nReuse!=nOrig ){
 35204        osMunmap(pReq, nOrig-nReuse);
 35205      }
 35206  
 35207  #if HAVE_MREMAP
 35208      pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
 35209      zErr = "mremap";
 35210  #else
 35211      pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
 35212      if( pNew!=MAP_FAILED ){
 35213        if( pNew!=pReq ){
 35214          osMunmap(pNew, nNew - nReuse);
 35215          pNew = 0;
 35216        }else{
 35217          pNew = pOrig;
 35218        }
 35219      }
 35220  #endif
 35221  
 35222      /* The attempt to extend the existing mapping failed. Free it. */
 35223      if( pNew==MAP_FAILED || pNew==0 ){
 35224        osMunmap(pOrig, nReuse);
 35225      }
 35226    }
 35227  
 35228    /* If pNew is still NULL, try to create an entirely new mapping. */
 35229    if( pNew==0 ){
 35230      pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
 35231    }
 35232  
 35233    if( pNew==MAP_FAILED ){
 35234      pNew = 0;
 35235      nNew = 0;
 35236      unixLogError(SQLITE_OK, zErr, pFd->zPath);
 35237  
 35238      /* If the mmap() above failed, assume that all subsequent mmap() calls
 35239      ** will probably fail too. Fall back to using xRead/xWrite exclusively
 35240      ** in this case.  */
 35241      pFd->mmapSizeMax = 0;
 35242    }
 35243    pFd->pMapRegion = (void *)pNew;
 35244    pFd->mmapSize = pFd->mmapSizeActual = nNew;
 35245  }
 35246  
 35247  /*
 35248  ** Memory map or remap the file opened by file-descriptor pFd (if the file
 35249  ** is already mapped, the existing mapping is replaced by the new). Or, if 
 35250  ** there already exists a mapping for this file, and there are still 
 35251  ** outstanding xFetch() references to it, this function is a no-op.
 35252  **
 35253  ** If parameter nByte is non-negative, then it is the requested size of 
 35254  ** the mapping to create. Otherwise, if nByte is less than zero, then the 
 35255  ** requested size is the size of the file on disk. The actual size of the
 35256  ** created mapping is either the requested size or the value configured 
 35257  ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
 35258  **
 35259  ** SQLITE_OK is returned if no error occurs (even if the mapping is not
 35260  ** recreated as a result of outstanding references) or an SQLite error
 35261  ** code otherwise.
 35262  */
 35263  static int unixMapfile(unixFile *pFd, i64 nMap){
 35264    assert( nMap>=0 || pFd->nFetchOut==0 );
 35265    assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
 35266    if( pFd->nFetchOut>0 ) return SQLITE_OK;
 35267  
 35268    if( nMap<0 ){
 35269      struct stat statbuf;          /* Low-level file information */
 35270      if( osFstat(pFd->h, &statbuf) ){
 35271        return SQLITE_IOERR_FSTAT;
 35272      }
 35273      nMap = statbuf.st_size;
 35274    }
 35275    if( nMap>pFd->mmapSizeMax ){
 35276      nMap = pFd->mmapSizeMax;
 35277    }
 35278  
 35279    assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
 35280    if( nMap!=pFd->mmapSize ){
 35281      unixRemapfile(pFd, nMap);
 35282    }
 35283  
 35284    return SQLITE_OK;
 35285  }
 35286  #endif /* SQLITE_MAX_MMAP_SIZE>0 */
 35287  
 35288  /*
 35289  ** If possible, return a pointer to a mapping of file fd starting at offset
 35290  ** iOff. The mapping must be valid for at least nAmt bytes.
 35291  **
 35292  ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
 35293  ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
 35294  ** Finally, if an error does occur, return an SQLite error code. The final
 35295  ** value of *pp is undefined in this case.
 35296  **
 35297  ** If this function does return a pointer, the caller must eventually 
 35298  ** release the reference by calling unixUnfetch().
 35299  */
 35300  static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
 35301  #if SQLITE_MAX_MMAP_SIZE>0
 35302    unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
 35303  #endif
 35304    *pp = 0;
 35305  
 35306  #if SQLITE_MAX_MMAP_SIZE>0
 35307    if( pFd->mmapSizeMax>0 ){
 35308      if( pFd->pMapRegion==0 ){
 35309        int rc = unixMapfile(pFd, -1);
 35310        if( rc!=SQLITE_OK ) return rc;
 35311      }
 35312      if( pFd->mmapSize >= iOff+nAmt ){
 35313        *pp = &((u8 *)pFd->pMapRegion)[iOff];
 35314        pFd->nFetchOut++;
 35315      }
 35316    }
 35317  #endif
 35318    return SQLITE_OK;
 35319  }
 35320  
 35321  /*
 35322  ** If the third argument is non-NULL, then this function releases a 
 35323  ** reference obtained by an earlier call to unixFetch(). The second
 35324  ** argument passed to this function must be the same as the corresponding
 35325  ** argument that was passed to the unixFetch() invocation. 
 35326  **
 35327  ** Or, if the third argument is NULL, then this function is being called 
 35328  ** to inform the VFS layer that, according to POSIX, any existing mapping 
 35329  ** may now be invalid and should be unmapped.
 35330  */
 35331  static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
 35332  #if SQLITE_MAX_MMAP_SIZE>0
 35333    unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
 35334    UNUSED_PARAMETER(iOff);
 35335  
 35336    /* If p==0 (unmap the entire file) then there must be no outstanding 
 35337    ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
 35338    ** then there must be at least one outstanding.  */
 35339    assert( (p==0)==(pFd->nFetchOut==0) );
 35340  
 35341    /* If p!=0, it must match the iOff value. */
 35342    assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
 35343  
 35344    if( p ){
 35345      pFd->nFetchOut--;
 35346    }else{
 35347      unixUnmapfile(pFd);
 35348    }
 35349  
 35350    assert( pFd->nFetchOut>=0 );
 35351  #else
 35352    UNUSED_PARAMETER(fd);
 35353    UNUSED_PARAMETER(p);
 35354    UNUSED_PARAMETER(iOff);
 35355  #endif
 35356    return SQLITE_OK;
 35357  }
 35358  
 35359  /*
 35360  ** Here ends the implementation of all sqlite3_file methods.
 35361  **
 35362  ********************** End sqlite3_file Methods *******************************
 35363  ******************************************************************************/
 35364  
 35365  /*
 35366  ** This division contains definitions of sqlite3_io_methods objects that
 35367  ** implement various file locking strategies.  It also contains definitions
 35368  ** of "finder" functions.  A finder-function is used to locate the appropriate
 35369  ** sqlite3_io_methods object for a particular database file.  The pAppData
 35370  ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
 35371  ** the correct finder-function for that VFS.
 35372  **
 35373  ** Most finder functions return a pointer to a fixed sqlite3_io_methods
 35374  ** object.  The only interesting finder-function is autolockIoFinder, which
 35375  ** looks at the filesystem type and tries to guess the best locking
 35376  ** strategy from that.
 35377  **
 35378  ** For finder-function F, two objects are created:
 35379  **
 35380  **    (1) The real finder-function named "FImpt()".
 35381  **
 35382  **    (2) A constant pointer to this function named just "F".
 35383  **
 35384  **
 35385  ** A pointer to the F pointer is used as the pAppData value for VFS
 35386  ** objects.  We have to do this instead of letting pAppData point
 35387  ** directly at the finder-function since C90 rules prevent a void*
 35388  ** from be cast into a function pointer.
 35389  **
 35390  **
 35391  ** Each instance of this macro generates two objects:
 35392  **
 35393  **   *  A constant sqlite3_io_methods object call METHOD that has locking
 35394  **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
 35395  **
 35396  **   *  An I/O method finder function called FINDER that returns a pointer
 35397  **      to the METHOD object in the previous bullet.
 35398  */
 35399  #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP)     \
 35400  static const sqlite3_io_methods METHOD = {                                   \
 35401     VERSION,                    /* iVersion */                                \
 35402     CLOSE,                      /* xClose */                                  \
 35403     unixRead,                   /* xRead */                                   \
 35404     unixWrite,                  /* xWrite */                                  \
 35405     unixTruncate,               /* xTruncate */                               \
 35406     unixSync,                   /* xSync */                                   \
 35407     unixFileSize,               /* xFileSize */                               \
 35408     LOCK,                       /* xLock */                                   \
 35409     UNLOCK,                     /* xUnlock */                                 \
 35410     CKLOCK,                     /* xCheckReservedLock */                      \
 35411     unixFileControl,            /* xFileControl */                            \
 35412     unixSectorSize,             /* xSectorSize */                             \
 35413     unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
 35414     SHMMAP,                     /* xShmMap */                                 \
 35415     unixShmLock,                /* xShmLock */                                \
 35416     unixShmBarrier,             /* xShmBarrier */                             \
 35417     unixShmUnmap,               /* xShmUnmap */                               \
 35418     unixFetch,                  /* xFetch */                                  \
 35419     unixUnfetch,                /* xUnfetch */                                \
 35420  };                                                                           \
 35421  static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
 35422    UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
 35423    return &METHOD;                                                            \
 35424  }                                                                            \
 35425  static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
 35426      = FINDER##Impl;
 35427  
 35428  /*
 35429  ** Here are all of the sqlite3_io_methods objects for each of the
 35430  ** locking strategies.  Functions that return pointers to these methods
 35431  ** are also created.
 35432  */
 35433  IOMETHODS(
 35434    posixIoFinder,            /* Finder function name */
 35435    posixIoMethods,           /* sqlite3_io_methods object name */
 35436    3,                        /* shared memory and mmap are enabled */
 35437    unixClose,                /* xClose method */
 35438    unixLock,                 /* xLock method */
 35439    unixUnlock,               /* xUnlock method */
 35440    unixCheckReservedLock,    /* xCheckReservedLock method */
 35441    unixShmMap                /* xShmMap method */
 35442  )
 35443  IOMETHODS(
 35444    nolockIoFinder,           /* Finder function name */
 35445    nolockIoMethods,          /* sqlite3_io_methods object name */
 35446    3,                        /* shared memory is disabled */
 35447    nolockClose,              /* xClose method */
 35448    nolockLock,               /* xLock method */
 35449    nolockUnlock,             /* xUnlock method */
 35450    nolockCheckReservedLock,  /* xCheckReservedLock method */
 35451    0                         /* xShmMap method */
 35452  )
 35453  IOMETHODS(
 35454    dotlockIoFinder,          /* Finder function name */
 35455    dotlockIoMethods,         /* sqlite3_io_methods object name */
 35456    1,                        /* shared memory is disabled */
 35457    dotlockClose,             /* xClose method */
 35458    dotlockLock,              /* xLock method */
 35459    dotlockUnlock,            /* xUnlock method */
 35460    dotlockCheckReservedLock, /* xCheckReservedLock method */
 35461    0                         /* xShmMap method */
 35462  )
 35463  
 35464  #if SQLITE_ENABLE_LOCKING_STYLE
 35465  IOMETHODS(
 35466    flockIoFinder,            /* Finder function name */
 35467    flockIoMethods,           /* sqlite3_io_methods object name */
 35468    1,                        /* shared memory is disabled */
 35469    flockClose,               /* xClose method */
 35470    flockLock,                /* xLock method */
 35471    flockUnlock,              /* xUnlock method */
 35472    flockCheckReservedLock,   /* xCheckReservedLock method */
 35473    0                         /* xShmMap method */
 35474  )
 35475  #endif
 35476  
 35477  #if OS_VXWORKS
 35478  IOMETHODS(
 35479    semIoFinder,              /* Finder function name */
 35480    semIoMethods,             /* sqlite3_io_methods object name */
 35481    1,                        /* shared memory is disabled */
 35482    semXClose,                /* xClose method */
 35483    semXLock,                 /* xLock method */
 35484    semXUnlock,               /* xUnlock method */
 35485    semXCheckReservedLock,    /* xCheckReservedLock method */
 35486    0                         /* xShmMap method */
 35487  )
 35488  #endif
 35489  
 35490  #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 35491  IOMETHODS(
 35492    afpIoFinder,              /* Finder function name */
 35493    afpIoMethods,             /* sqlite3_io_methods object name */
 35494    1,                        /* shared memory is disabled */
 35495    afpClose,                 /* xClose method */
 35496    afpLock,                  /* xLock method */
 35497    afpUnlock,                /* xUnlock method */
 35498    afpCheckReservedLock,     /* xCheckReservedLock method */
 35499    0                         /* xShmMap method */
 35500  )
 35501  #endif
 35502  
 35503  /*
 35504  ** The proxy locking method is a "super-method" in the sense that it
 35505  ** opens secondary file descriptors for the conch and lock files and
 35506  ** it uses proxy, dot-file, AFP, and flock() locking methods on those
 35507  ** secondary files.  For this reason, the division that implements
 35508  ** proxy locking is located much further down in the file.  But we need
 35509  ** to go ahead and define the sqlite3_io_methods and finder function
 35510  ** for proxy locking here.  So we forward declare the I/O methods.
 35511  */
 35512  #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 35513  static int proxyClose(sqlite3_file*);
 35514  static int proxyLock(sqlite3_file*, int);
 35515  static int proxyUnlock(sqlite3_file*, int);
 35516  static int proxyCheckReservedLock(sqlite3_file*, int*);
 35517  IOMETHODS(
 35518    proxyIoFinder,            /* Finder function name */
 35519    proxyIoMethods,           /* sqlite3_io_methods object name */
 35520    1,                        /* shared memory is disabled */
 35521    proxyClose,               /* xClose method */
 35522    proxyLock,                /* xLock method */
 35523    proxyUnlock,              /* xUnlock method */
 35524    proxyCheckReservedLock,   /* xCheckReservedLock method */
 35525    0                         /* xShmMap method */
 35526  )
 35527  #endif
 35528  
 35529  /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
 35530  #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 35531  IOMETHODS(
 35532    nfsIoFinder,               /* Finder function name */
 35533    nfsIoMethods,              /* sqlite3_io_methods object name */
 35534    1,                         /* shared memory is disabled */
 35535    unixClose,                 /* xClose method */
 35536    unixLock,                  /* xLock method */
 35537    nfsUnlock,                 /* xUnlock method */
 35538    unixCheckReservedLock,     /* xCheckReservedLock method */
 35539    0                          /* xShmMap method */
 35540  )
 35541  #endif
 35542  
 35543  #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 35544  /* 
 35545  ** This "finder" function attempts to determine the best locking strategy 
 35546  ** for the database file "filePath".  It then returns the sqlite3_io_methods
 35547  ** object that implements that strategy.
 35548  **
 35549  ** This is for MacOSX only.
 35550  */
 35551  static const sqlite3_io_methods *autolockIoFinderImpl(
 35552    const char *filePath,    /* name of the database file */
 35553    unixFile *pNew           /* open file object for the database file */
 35554  ){
 35555    static const struct Mapping {
 35556      const char *zFilesystem;              /* Filesystem type name */
 35557      const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
 35558    } aMap[] = {
 35559      { "hfs",    &posixIoMethods },
 35560      { "ufs",    &posixIoMethods },
 35561      { "afpfs",  &afpIoMethods },
 35562      { "smbfs",  &afpIoMethods },
 35563      { "webdav", &nolockIoMethods },
 35564      { 0, 0 }
 35565    };
 35566    int i;
 35567    struct statfs fsInfo;
 35568    struct flock lockInfo;
 35569  
 35570    if( !filePath ){
 35571      /* If filePath==NULL that means we are dealing with a transient file
 35572      ** that does not need to be locked. */
 35573      return &nolockIoMethods;
 35574    }
 35575    if( statfs(filePath, &fsInfo) != -1 ){
 35576      if( fsInfo.f_flags & MNT_RDONLY ){
 35577        return &nolockIoMethods;
 35578      }
 35579      for(i=0; aMap[i].zFilesystem; i++){
 35580        if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
 35581          return aMap[i].pMethods;
 35582        }
 35583      }
 35584    }
 35585  
 35586    /* Default case. Handles, amongst others, "nfs".
 35587    ** Test byte-range lock using fcntl(). If the call succeeds, 
 35588    ** assume that the file-system supports POSIX style locks. 
 35589    */
 35590    lockInfo.l_len = 1;
 35591    lockInfo.l_start = 0;
 35592    lockInfo.l_whence = SEEK_SET;
 35593    lockInfo.l_type = F_RDLCK;
 35594    if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
 35595      if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
 35596        return &nfsIoMethods;
 35597      } else {
 35598        return &posixIoMethods;
 35599      }
 35600    }else{
 35601      return &dotlockIoMethods;
 35602    }
 35603  }
 35604  static const sqlite3_io_methods 
 35605    *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
 35606  
 35607  #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
 35608  
 35609  #if OS_VXWORKS
 35610  /*
 35611  ** This "finder" function for VxWorks checks to see if posix advisory
 35612  ** locking works.  If it does, then that is what is used.  If it does not
 35613  ** work, then fallback to named semaphore locking.
 35614  */
 35615  static const sqlite3_io_methods *vxworksIoFinderImpl(
 35616    const char *filePath,    /* name of the database file */
 35617    unixFile *pNew           /* the open file object */
 35618  ){
 35619    struct flock lockInfo;
 35620  
 35621    if( !filePath ){
 35622      /* If filePath==NULL that means we are dealing with a transient file
 35623      ** that does not need to be locked. */
 35624      return &nolockIoMethods;
 35625    }
 35626  
 35627    /* Test if fcntl() is supported and use POSIX style locks.
 35628    ** Otherwise fall back to the named semaphore method.
 35629    */
 35630    lockInfo.l_len = 1;
 35631    lockInfo.l_start = 0;
 35632    lockInfo.l_whence = SEEK_SET;
 35633    lockInfo.l_type = F_RDLCK;
 35634    if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
 35635      return &posixIoMethods;
 35636    }else{
 35637      return &semIoMethods;
 35638    }
 35639  }
 35640  static const sqlite3_io_methods 
 35641    *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
 35642  
 35643  #endif /* OS_VXWORKS */
 35644  
 35645  /*
 35646  ** An abstract type for a pointer to an IO method finder function:
 35647  */
 35648  typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
 35649  
 35650  
 35651  /****************************************************************************
 35652  **************************** sqlite3_vfs methods ****************************
 35653  **
 35654  ** This division contains the implementation of methods on the
 35655  ** sqlite3_vfs object.
 35656  */
 35657  
 35658  /*
 35659  ** Initialize the contents of the unixFile structure pointed to by pId.
 35660  */
 35661  static int fillInUnixFile(
 35662    sqlite3_vfs *pVfs,      /* Pointer to vfs object */
 35663    int h,                  /* Open file descriptor of file being opened */
 35664    sqlite3_file *pId,      /* Write to the unixFile structure here */
 35665    const char *zFilename,  /* Name of the file being opened */
 35666    int ctrlFlags           /* Zero or more UNIXFILE_* values */
 35667  ){
 35668    const sqlite3_io_methods *pLockingStyle;
 35669    unixFile *pNew = (unixFile *)pId;
 35670    int rc = SQLITE_OK;
 35671  
 35672    assert( pNew->pInode==NULL );
 35673  
 35674    /* No locking occurs in temporary files */
 35675    assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
 35676  
 35677    OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
 35678    pNew->h = h;
 35679    pNew->pVfs = pVfs;
 35680    pNew->zPath = zFilename;
 35681    pNew->ctrlFlags = (u8)ctrlFlags;
 35682  #if SQLITE_MAX_MMAP_SIZE>0
 35683    pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
 35684  #endif
 35685    if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
 35686                             "psow", SQLITE_POWERSAFE_OVERWRITE) ){
 35687      pNew->ctrlFlags |= UNIXFILE_PSOW;
 35688    }
 35689    if( strcmp(pVfs->zName,"unix-excl")==0 ){
 35690      pNew->ctrlFlags |= UNIXFILE_EXCL;
 35691    }
 35692  
 35693  #if OS_VXWORKS
 35694    pNew->pId = vxworksFindFileId(zFilename);
 35695    if( pNew->pId==0 ){
 35696      ctrlFlags |= UNIXFILE_NOLOCK;
 35697      rc = SQLITE_NOMEM_BKPT;
 35698    }
 35699  #endif
 35700  
 35701    if( ctrlFlags & UNIXFILE_NOLOCK ){
 35702      pLockingStyle = &nolockIoMethods;
 35703    }else{
 35704      pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
 35705  #if SQLITE_ENABLE_LOCKING_STYLE
 35706      /* Cache zFilename in the locking context (AFP and dotlock override) for
 35707      ** proxyLock activation is possible (remote proxy is based on db name)
 35708      ** zFilename remains valid until file is closed, to support */
 35709      pNew->lockingContext = (void*)zFilename;
 35710  #endif
 35711    }
 35712  
 35713    if( pLockingStyle == &posixIoMethods
 35714  #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 35715      || pLockingStyle == &nfsIoMethods
 35716  #endif
 35717    ){
 35718      unixEnterMutex();
 35719      rc = findInodeInfo(pNew, &pNew->pInode);
 35720      if( rc!=SQLITE_OK ){
 35721        /* If an error occurred in findInodeInfo(), close the file descriptor
 35722        ** immediately, before releasing the mutex. findInodeInfo() may fail
 35723        ** in two scenarios:
 35724        **
 35725        **   (a) A call to fstat() failed.
 35726        **   (b) A malloc failed.
 35727        **
 35728        ** Scenario (b) may only occur if the process is holding no other
 35729        ** file descriptors open on the same file. If there were other file
 35730        ** descriptors on this file, then no malloc would be required by
 35731        ** findInodeInfo(). If this is the case, it is quite safe to close
 35732        ** handle h - as it is guaranteed that no posix locks will be released
 35733        ** by doing so.
 35734        **
 35735        ** If scenario (a) caused the error then things are not so safe. The
 35736        ** implicit assumption here is that if fstat() fails, things are in
 35737        ** such bad shape that dropping a lock or two doesn't matter much.
 35738        */
 35739        robust_close(pNew, h, __LINE__);
 35740        h = -1;
 35741      }
 35742      unixLeaveMutex();
 35743    }
 35744  
 35745  #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
 35746    else if( pLockingStyle == &afpIoMethods ){
 35747      /* AFP locking uses the file path so it needs to be included in
 35748      ** the afpLockingContext.
 35749      */
 35750      afpLockingContext *pCtx;
 35751      pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
 35752      if( pCtx==0 ){
 35753        rc = SQLITE_NOMEM_BKPT;
 35754      }else{
 35755        /* NB: zFilename exists and remains valid until the file is closed
 35756        ** according to requirement F11141.  So we do not need to make a
 35757        ** copy of the filename. */
 35758        pCtx->dbPath = zFilename;
 35759        pCtx->reserved = 0;
 35760        srandomdev();
 35761        unixEnterMutex();
 35762        rc = findInodeInfo(pNew, &pNew->pInode);
 35763        if( rc!=SQLITE_OK ){
 35764          sqlite3_free(pNew->lockingContext);
 35765          robust_close(pNew, h, __LINE__);
 35766          h = -1;
 35767        }
 35768        unixLeaveMutex();        
 35769      }
 35770    }
 35771  #endif
 35772  
 35773    else if( pLockingStyle == &dotlockIoMethods ){
 35774      /* Dotfile locking uses the file path so it needs to be included in
 35775      ** the dotlockLockingContext 
 35776      */
 35777      char *zLockFile;
 35778      int nFilename;
 35779      assert( zFilename!=0 );
 35780      nFilename = (int)strlen(zFilename) + 6;
 35781      zLockFile = (char *)sqlite3_malloc64(nFilename);
 35782      if( zLockFile==0 ){
 35783        rc = SQLITE_NOMEM_BKPT;
 35784      }else{
 35785        sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
 35786      }
 35787      pNew->lockingContext = zLockFile;
 35788    }
 35789  
 35790  #if OS_VXWORKS
 35791    else if( pLockingStyle == &semIoMethods ){
 35792      /* Named semaphore locking uses the file path so it needs to be
 35793      ** included in the semLockingContext
 35794      */
 35795      unixEnterMutex();
 35796      rc = findInodeInfo(pNew, &pNew->pInode);
 35797      if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
 35798        char *zSemName = pNew->pInode->aSemName;
 35799        int n;
 35800        sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
 35801                         pNew->pId->zCanonicalName);
 35802        for( n=1; zSemName[n]; n++ )
 35803          if( zSemName[n]=='/' ) zSemName[n] = '_';
 35804        pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
 35805        if( pNew->pInode->pSem == SEM_FAILED ){
 35806          rc = SQLITE_NOMEM_BKPT;
 35807          pNew->pInode->aSemName[0] = '\0';
 35808        }
 35809      }
 35810      unixLeaveMutex();
 35811    }
 35812  #endif
 35813    
 35814    storeLastErrno(pNew, 0);
 35815  #if OS_VXWORKS
 35816    if( rc!=SQLITE_OK ){
 35817      if( h>=0 ) robust_close(pNew, h, __LINE__);
 35818      h = -1;
 35819      osUnlink(zFilename);
 35820      pNew->ctrlFlags |= UNIXFILE_DELETE;
 35821    }
 35822  #endif
 35823    if( rc!=SQLITE_OK ){
 35824      if( h>=0 ) robust_close(pNew, h, __LINE__);
 35825    }else{
 35826      pNew->pMethod = pLockingStyle;
 35827      OpenCounter(+1);
 35828      verifyDbFile(pNew);
 35829    }
 35830    return rc;
 35831  }
 35832  
 35833  /*
 35834  ** Return the name of a directory in which to put temporary files.
 35835  ** If no suitable temporary file directory can be found, return NULL.
 35836  */
 35837  static const char *unixTempFileDir(void){
 35838    static const char *azDirs[] = {
 35839       0,
 35840       0,
 35841       "/var/tmp",
 35842       "/usr/tmp",
 35843       "/tmp",
 35844       "."
 35845    };
 35846    unsigned int i = 0;
 35847    struct stat buf;
 35848    const char *zDir = sqlite3_temp_directory;
 35849  
 35850    if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
 35851    if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
 35852    while(1){
 35853      if( zDir!=0
 35854       && osStat(zDir, &buf)==0
 35855       && S_ISDIR(buf.st_mode)
 35856       && osAccess(zDir, 03)==0
 35857      ){
 35858        return zDir;
 35859      }
 35860      if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
 35861      zDir = azDirs[i++];
 35862    }
 35863    return 0;
 35864  }
 35865  
 35866  /*
 35867  ** Create a temporary file name in zBuf.  zBuf must be allocated
 35868  ** by the calling process and must be big enough to hold at least
 35869  ** pVfs->mxPathname bytes.
 35870  */
 35871  static int unixGetTempname(int nBuf, char *zBuf){
 35872    const char *zDir;
 35873    int iLimit = 0;
 35874  
 35875    /* It's odd to simulate an io-error here, but really this is just
 35876    ** using the io-error infrastructure to test that SQLite handles this
 35877    ** function failing. 
 35878    */
 35879    zBuf[0] = 0;
 35880    SimulateIOError( return SQLITE_IOERR );
 35881  
 35882    zDir = unixTempFileDir();
 35883    if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
 35884    do{
 35885      u64 r;
 35886      sqlite3_randomness(sizeof(r), &r);
 35887      assert( nBuf>2 );
 35888      zBuf[nBuf-2] = 0;
 35889      sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
 35890                       zDir, r, 0);
 35891      if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
 35892    }while( osAccess(zBuf,0)==0 );
 35893    return SQLITE_OK;
 35894  }
 35895  
 35896  #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
 35897  /*
 35898  ** Routine to transform a unixFile into a proxy-locking unixFile.
 35899  ** Implementation in the proxy-lock division, but used by unixOpen()
 35900  ** if SQLITE_PREFER_PROXY_LOCKING is defined.
 35901  */
 35902  static int proxyTransformUnixFile(unixFile*, const char*);
 35903  #endif
 35904  
 35905  /*
 35906  ** Search for an unused file descriptor that was opened on the database 
 35907  ** file (not a journal or master-journal file) identified by pathname
 35908  ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
 35909  ** argument to this function.
 35910  **
 35911  ** Such a file descriptor may exist if a database connection was closed
 35912  ** but the associated file descriptor could not be closed because some
 35913  ** other file descriptor open on the same file is holding a file-lock.
 35914  ** Refer to comments in the unixClose() function and the lengthy comment
 35915  ** describing "Posix Advisory Locking" at the start of this file for 
 35916  ** further details. Also, ticket #4018.
 35917  **
 35918  ** If a suitable file descriptor is found, then it is returned. If no
 35919  ** such file descriptor is located, -1 is returned.
 35920  */
 35921  static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
 35922    UnixUnusedFd *pUnused = 0;
 35923  
 35924    /* Do not search for an unused file descriptor on vxworks. Not because
 35925    ** vxworks would not benefit from the change (it might, we're not sure),
 35926    ** but because no way to test it is currently available. It is better 
 35927    ** not to risk breaking vxworks support for the sake of such an obscure 
 35928    ** feature.  */
 35929  #if !OS_VXWORKS
 35930    struct stat sStat;                   /* Results of stat() call */
 35931  
 35932    unixEnterMutex();
 35933  
 35934    /* A stat() call may fail for various reasons. If this happens, it is
 35935    ** almost certain that an open() call on the same path will also fail.
 35936    ** For this reason, if an error occurs in the stat() call here, it is
 35937    ** ignored and -1 is returned. The caller will try to open a new file
 35938    ** descriptor on the same path, fail, and return an error to SQLite.
 35939    **
 35940    ** Even if a subsequent open() call does succeed, the consequences of
 35941    ** not searching for a reusable file descriptor are not dire.  */
 35942    if( nUnusedFd>0 && 0==osStat(zPath, &sStat) ){
 35943      unixInodeInfo *pInode;
 35944  
 35945      pInode = inodeList;
 35946      while( pInode && (pInode->fileId.dev!=sStat.st_dev
 35947                       || pInode->fileId.ino!=(u64)sStat.st_ino) ){
 35948         pInode = pInode->pNext;
 35949      }
 35950      if( pInode ){
 35951        UnixUnusedFd **pp;
 35952        for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
 35953        pUnused = *pp;
 35954        if( pUnused ){
 35955          nUnusedFd--;
 35956          *pp = pUnused->pNext;
 35957        }
 35958      }
 35959    }
 35960    unixLeaveMutex();
 35961  #endif    /* if !OS_VXWORKS */
 35962    return pUnused;
 35963  }
 35964  
 35965  /*
 35966  ** Find the mode, uid and gid of file zFile. 
 35967  */
 35968  static int getFileMode(
 35969    const char *zFile,              /* File name */
 35970    mode_t *pMode,                  /* OUT: Permissions of zFile */
 35971    uid_t *pUid,                    /* OUT: uid of zFile. */
 35972    gid_t *pGid                     /* OUT: gid of zFile. */
 35973  ){
 35974    struct stat sStat;              /* Output of stat() on database file */
 35975    int rc = SQLITE_OK;
 35976    if( 0==osStat(zFile, &sStat) ){
 35977      *pMode = sStat.st_mode & 0777;
 35978      *pUid = sStat.st_uid;
 35979      *pGid = sStat.st_gid;
 35980    }else{
 35981      rc = SQLITE_IOERR_FSTAT;
 35982    }
 35983    return rc;
 35984  }
 35985  
 35986  /*
 35987  ** This function is called by unixOpen() to determine the unix permissions
 35988  ** to create new files with. If no error occurs, then SQLITE_OK is returned
 35989  ** and a value suitable for passing as the third argument to open(2) is
 35990  ** written to *pMode. If an IO error occurs, an SQLite error code is 
 35991  ** returned and the value of *pMode is not modified.
 35992  **
 35993  ** In most cases, this routine sets *pMode to 0, which will become
 35994  ** an indication to robust_open() to create the file using
 35995  ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
 35996  ** But if the file being opened is a WAL or regular journal file, then 
 35997  ** this function queries the file-system for the permissions on the 
 35998  ** corresponding database file and sets *pMode to this value. Whenever 
 35999  ** possible, WAL and journal files are created using the same permissions 
 36000  ** as the associated database file.
 36001  **
 36002  ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
 36003  ** original filename is unavailable.  But 8_3_NAMES is only used for
 36004  ** FAT filesystems and permissions do not matter there, so just use
 36005  ** the default permissions.
 36006  */
 36007  static int findCreateFileMode(
 36008    const char *zPath,              /* Path of file (possibly) being created */
 36009    int flags,                      /* Flags passed as 4th argument to xOpen() */
 36010    mode_t *pMode,                  /* OUT: Permissions to open file with */
 36011    uid_t *pUid,                    /* OUT: uid to set on the file */
 36012    gid_t *pGid                     /* OUT: gid to set on the file */
 36013  ){
 36014    int rc = SQLITE_OK;             /* Return Code */
 36015    *pMode = 0;
 36016    *pUid = 0;
 36017    *pGid = 0;
 36018    if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
 36019      char zDb[MAX_PATHNAME+1];     /* Database file path */
 36020      int nDb;                      /* Number of valid bytes in zDb */
 36021  
 36022      /* zPath is a path to a WAL or journal file. The following block derives
 36023      ** the path to the associated database file from zPath. This block handles
 36024      ** the following naming conventions:
 36025      **
 36026      **   "<path to db>-journal"
 36027      **   "<path to db>-wal"
 36028      **   "<path to db>-journalNN"
 36029      **   "<path to db>-walNN"
 36030      **
 36031      ** where NN is a decimal number. The NN naming schemes are 
 36032      ** used by the test_multiplex.c module.
 36033      */
 36034      nDb = sqlite3Strlen30(zPath) - 1; 
 36035      while( zPath[nDb]!='-' ){
 36036        /* In normal operation, the journal file name will always contain
 36037        ** a '-' character.  However in 8+3 filename mode, or if a corrupt
 36038        ** rollback journal specifies a master journal with a goofy name, then
 36039        ** the '-' might be missing. */
 36040        if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
 36041        nDb--;
 36042      }
 36043      memcpy(zDb, zPath, nDb);
 36044      zDb[nDb] = '\0';
 36045  
 36046      rc = getFileMode(zDb, pMode, pUid, pGid);
 36047    }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
 36048      *pMode = 0600;
 36049    }else if( flags & SQLITE_OPEN_URI ){
 36050      /* If this is a main database file and the file was opened using a URI
 36051      ** filename, check for the "modeof" parameter. If present, interpret
 36052      ** its value as a filename and try to copy the mode, uid and gid from
 36053      ** that file.  */
 36054      const char *z = sqlite3_uri_parameter(zPath, "modeof");
 36055      if( z ){
 36056        rc = getFileMode(z, pMode, pUid, pGid);
 36057      }
 36058    }
 36059    return rc;
 36060  }
 36061  
 36062  /*
 36063  ** Open the file zPath.
 36064  ** 
 36065  ** Previously, the SQLite OS layer used three functions in place of this
 36066  ** one:
 36067  **
 36068  **     sqlite3OsOpenReadWrite();
 36069  **     sqlite3OsOpenReadOnly();
 36070  **     sqlite3OsOpenExclusive();
 36071  **
 36072  ** These calls correspond to the following combinations of flags:
 36073  **
 36074  **     ReadWrite() ->     (READWRITE | CREATE)
 36075  **     ReadOnly()  ->     (READONLY) 
 36076  **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
 36077  **
 36078  ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
 36079  ** true, the file was configured to be automatically deleted when the
 36080  ** file handle closed. To achieve the same effect using this new 
 36081  ** interface, add the DELETEONCLOSE flag to those specified above for 
 36082  ** OpenExclusive().
 36083  */
 36084  static int unixOpen(
 36085    sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
 36086    const char *zPath,           /* Pathname of file to be opened */
 36087    sqlite3_file *pFile,         /* The file descriptor to be filled in */
 36088    int flags,                   /* Input flags to control the opening */
 36089    int *pOutFlags               /* Output flags returned to SQLite core */
 36090  ){
 36091    unixFile *p = (unixFile *)pFile;
 36092    int fd = -1;                   /* File descriptor returned by open() */
 36093    int openFlags = 0;             /* Flags to pass to open() */
 36094    int eType = flags&0xFFFFFF00;  /* Type of file to open */
 36095    int noLock;                    /* True to omit locking primitives */
 36096    int rc = SQLITE_OK;            /* Function Return Code */
 36097    int ctrlFlags = 0;             /* UNIXFILE_* flags */
 36098  
 36099    int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
 36100    int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
 36101    int isCreate     = (flags & SQLITE_OPEN_CREATE);
 36102    int isReadonly   = (flags & SQLITE_OPEN_READONLY);
 36103    int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
 36104  #if SQLITE_ENABLE_LOCKING_STYLE
 36105    int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
 36106  #endif
 36107  #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
 36108    struct statfs fsInfo;
 36109  #endif
 36110  
 36111    /* If creating a master or main-file journal, this function will open
 36112    ** a file-descriptor on the directory too. The first time unixSync()
 36113    ** is called the directory file descriptor will be fsync()ed and close()d.
 36114    */
 36115    int syncDir = (isCreate && (
 36116          eType==SQLITE_OPEN_MASTER_JOURNAL 
 36117       || eType==SQLITE_OPEN_MAIN_JOURNAL 
 36118       || eType==SQLITE_OPEN_WAL
 36119    ));
 36120  
 36121    /* If argument zPath is a NULL pointer, this function is required to open
 36122    ** a temporary file. Use this buffer to store the file name in.
 36123    */
 36124    char zTmpname[MAX_PATHNAME+2];
 36125    const char *zName = zPath;
 36126  
 36127    /* Check the following statements are true: 
 36128    **
 36129    **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
 36130    **   (b) if CREATE is set, then READWRITE must also be set, and
 36131    **   (c) if EXCLUSIVE is set, then CREATE must also be set.
 36132    **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
 36133    */
 36134    assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
 36135    assert(isCreate==0 || isReadWrite);
 36136    assert(isExclusive==0 || isCreate);
 36137    assert(isDelete==0 || isCreate);
 36138  
 36139    /* The main DB, main journal, WAL file and master journal are never 
 36140    ** automatically deleted. Nor are they ever temporary files.  */
 36141    assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
 36142    assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
 36143    assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
 36144    assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
 36145  
 36146    /* Assert that the upper layer has set one of the "file-type" flags. */
 36147    assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
 36148         || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
 36149         || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
 36150         || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
 36151    );
 36152  
 36153    /* Detect a pid change and reset the PRNG.  There is a race condition
 36154    ** here such that two or more threads all trying to open databases at
 36155    ** the same instant might all reset the PRNG.  But multiple resets
 36156    ** are harmless.
 36157    */
 36158    if( randomnessPid!=osGetpid(0) ){
 36159      randomnessPid = osGetpid(0);
 36160      sqlite3_randomness(0,0);
 36161    }
 36162  
 36163    memset(p, 0, sizeof(unixFile));
 36164  
 36165    if( eType==SQLITE_OPEN_MAIN_DB ){
 36166      UnixUnusedFd *pUnused;
 36167      pUnused = findReusableFd(zName, flags);
 36168      if( pUnused ){
 36169        fd = pUnused->fd;
 36170      }else{
 36171        pUnused = sqlite3_malloc64(sizeof(*pUnused));
 36172        if( !pUnused ){
 36173          return SQLITE_NOMEM_BKPT;
 36174        }
 36175      }
 36176      p->pPreallocatedUnused = pUnused;
 36177  
 36178      /* Database filenames are double-zero terminated if they are not
 36179      ** URIs with parameters.  Hence, they can always be passed into
 36180      ** sqlite3_uri_parameter(). */
 36181      assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
 36182  
 36183    }else if( !zName ){
 36184      /* If zName is NULL, the upper layer is requesting a temp file. */
 36185      assert(isDelete && !syncDir);
 36186      rc = unixGetTempname(pVfs->mxPathname, zTmpname);
 36187      if( rc!=SQLITE_OK ){
 36188        return rc;
 36189      }
 36190      zName = zTmpname;
 36191  
 36192      /* Generated temporary filenames are always double-zero terminated
 36193      ** for use by sqlite3_uri_parameter(). */
 36194      assert( zName[strlen(zName)+1]==0 );
 36195    }
 36196  
 36197    /* Determine the value of the flags parameter passed to POSIX function
 36198    ** open(). These must be calculated even if open() is not called, as
 36199    ** they may be stored as part of the file handle and used by the 
 36200    ** 'conch file' locking functions later on.  */
 36201    if( isReadonly )  openFlags |= O_RDONLY;
 36202    if( isReadWrite ) openFlags |= O_RDWR;
 36203    if( isCreate )    openFlags |= O_CREAT;
 36204    if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
 36205    openFlags |= (O_LARGEFILE|O_BINARY);
 36206  
 36207    if( fd<0 ){
 36208      mode_t openMode;              /* Permissions to create file with */
 36209      uid_t uid;                    /* Userid for the file */
 36210      gid_t gid;                    /* Groupid for the file */
 36211      rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
 36212      if( rc!=SQLITE_OK ){
 36213        assert( !p->pPreallocatedUnused );
 36214        assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
 36215        return rc;
 36216      }
 36217      fd = robust_open(zName, openFlags, openMode);
 36218      OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
 36219      assert( !isExclusive || (openFlags & O_CREAT)!=0 );
 36220      if( fd<0 && errno!=EISDIR && isReadWrite ){
 36221        /* Failed to open the file for read/write access. Try read-only. */
 36222        flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
 36223        openFlags &= ~(O_RDWR|O_CREAT);
 36224        flags |= SQLITE_OPEN_READONLY;
 36225        openFlags |= O_RDONLY;
 36226        isReadonly = 1;
 36227        fd = robust_open(zName, openFlags, openMode);
 36228      }
 36229      if( fd<0 ){
 36230        rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
 36231        goto open_finished;
 36232      }
 36233  
 36234      /* If this process is running as root and if creating a new rollback
 36235      ** journal or WAL file, set the ownership of the journal or WAL to be
 36236      ** the same as the original database.
 36237      */
 36238      if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
 36239        robustFchown(fd, uid, gid);
 36240      }
 36241    }
 36242    assert( fd>=0 );
 36243    if( pOutFlags ){
 36244      *pOutFlags = flags;
 36245    }
 36246  
 36247    if( p->pPreallocatedUnused ){
 36248      p->pPreallocatedUnused->fd = fd;
 36249      p->pPreallocatedUnused->flags = flags;
 36250    }
 36251  
 36252    if( isDelete ){
 36253  #if OS_VXWORKS
 36254      zPath = zName;
 36255  #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
 36256      zPath = sqlite3_mprintf("%s", zName);
 36257      if( zPath==0 ){
 36258        robust_close(p, fd, __LINE__);
 36259        return SQLITE_NOMEM_BKPT;
 36260      }
 36261  #else
 36262      osUnlink(zName);
 36263  #endif
 36264    }
 36265  #if SQLITE_ENABLE_LOCKING_STYLE
 36266    else{
 36267      p->openFlags = openFlags;
 36268    }
 36269  #endif
 36270    
 36271  #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
 36272    if( fstatfs(fd, &fsInfo) == -1 ){
 36273      storeLastErrno(p, errno);
 36274      robust_close(p, fd, __LINE__);
 36275      return SQLITE_IOERR_ACCESS;
 36276    }
 36277    if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
 36278      ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
 36279    }
 36280    if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
 36281      ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
 36282    }
 36283  #endif
 36284  
 36285    /* Set up appropriate ctrlFlags */
 36286    if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
 36287    if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
 36288    noLock = eType!=SQLITE_OPEN_MAIN_DB;
 36289    if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
 36290    if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
 36291    if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
 36292  
 36293  #if SQLITE_ENABLE_LOCKING_STYLE
 36294  #if SQLITE_PREFER_PROXY_LOCKING
 36295    isAutoProxy = 1;
 36296  #endif
 36297    if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
 36298      char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
 36299      int useProxy = 0;
 36300  
 36301      /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
 36302      ** never use proxy, NULL means use proxy for non-local files only.  */
 36303      if( envforce!=NULL ){
 36304        useProxy = atoi(envforce)>0;
 36305      }else{
 36306        useProxy = !(fsInfo.f_flags&MNT_LOCAL);
 36307      }
 36308      if( useProxy ){
 36309        rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
 36310        if( rc==SQLITE_OK ){
 36311          rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
 36312          if( rc!=SQLITE_OK ){
 36313            /* Use unixClose to clean up the resources added in fillInUnixFile 
 36314            ** and clear all the structure's references.  Specifically, 
 36315            ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 
 36316            */
 36317            unixClose(pFile);
 36318            return rc;
 36319          }
 36320        }
 36321        goto open_finished;
 36322      }
 36323    }
 36324  #endif
 36325    
 36326    assert( zPath==0 || zPath[0]=='/' 
 36327        || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL 
 36328    );
 36329    rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
 36330  
 36331  open_finished:
 36332    if( rc!=SQLITE_OK ){
 36333      sqlite3_free(p->pPreallocatedUnused);
 36334    }
 36335    return rc;
 36336  }
 36337  
 36338  
 36339  /*
 36340  ** Delete the file at zPath. If the dirSync argument is true, fsync()
 36341  ** the directory after deleting the file.
 36342  */
 36343  static int unixDelete(
 36344    sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
 36345    const char *zPath,        /* Name of file to be deleted */
 36346    int dirSync               /* If true, fsync() directory after deleting file */
 36347  ){
 36348    int rc = SQLITE_OK;
 36349    UNUSED_PARAMETER(NotUsed);
 36350    SimulateIOError(return SQLITE_IOERR_DELETE);
 36351    if( osUnlink(zPath)==(-1) ){
 36352      if( errno==ENOENT
 36353  #if OS_VXWORKS
 36354          || osAccess(zPath,0)!=0
 36355  #endif
 36356      ){
 36357        rc = SQLITE_IOERR_DELETE_NOENT;
 36358      }else{
 36359        rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
 36360      }
 36361      return rc;
 36362    }
 36363  #ifndef SQLITE_DISABLE_DIRSYNC
 36364    if( (dirSync & 1)!=0 ){
 36365      int fd;
 36366      rc = osOpenDirectory(zPath, &fd);
 36367      if( rc==SQLITE_OK ){
 36368        if( full_fsync(fd,0,0) ){
 36369          rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
 36370        }
 36371        robust_close(0, fd, __LINE__);
 36372      }else{
 36373        assert( rc==SQLITE_CANTOPEN );
 36374        rc = SQLITE_OK;
 36375      }
 36376    }
 36377  #endif
 36378    return rc;
 36379  }
 36380  
 36381  /*
 36382  ** Test the existence of or access permissions of file zPath. The
 36383  ** test performed depends on the value of flags:
 36384  **
 36385  **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
 36386  **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
 36387  **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
 36388  **
 36389  ** Otherwise return 0.
 36390  */
 36391  static int unixAccess(
 36392    sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
 36393    const char *zPath,      /* Path of the file to examine */
 36394    int flags,              /* What do we want to learn about the zPath file? */
 36395    int *pResOut            /* Write result boolean here */
 36396  ){
 36397    UNUSED_PARAMETER(NotUsed);
 36398    SimulateIOError( return SQLITE_IOERR_ACCESS; );
 36399    assert( pResOut!=0 );
 36400  
 36401    /* The spec says there are three possible values for flags.  But only
 36402    ** two of them are actually used */
 36403    assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
 36404  
 36405    if( flags==SQLITE_ACCESS_EXISTS ){
 36406      struct stat buf;
 36407      *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
 36408    }else{
 36409      *pResOut = osAccess(zPath, W_OK|R_OK)==0;
 36410    }
 36411    return SQLITE_OK;
 36412  }
 36413  
 36414  /*
 36415  **
 36416  */
 36417  static int mkFullPathname(
 36418    const char *zPath,              /* Input path */
 36419    char *zOut,                     /* Output buffer */
 36420    int nOut                        /* Allocated size of buffer zOut */
 36421  ){
 36422    int nPath = sqlite3Strlen30(zPath);
 36423    int iOff = 0;
 36424    if( zPath[0]!='/' ){
 36425      if( osGetcwd(zOut, nOut-2)==0 ){
 36426        return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
 36427      }
 36428      iOff = sqlite3Strlen30(zOut);
 36429      zOut[iOff++] = '/';
 36430    }
 36431    if( (iOff+nPath+1)>nOut ){
 36432      /* SQLite assumes that xFullPathname() nul-terminates the output buffer
 36433      ** even if it returns an error.  */
 36434      zOut[iOff] = '\0';
 36435      return SQLITE_CANTOPEN_BKPT;
 36436    }
 36437    sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
 36438    return SQLITE_OK;
 36439  }
 36440  
 36441  /*
 36442  ** Turn a relative pathname into a full pathname. The relative path
 36443  ** is stored as a nul-terminated string in the buffer pointed to by
 36444  ** zPath. 
 36445  **
 36446  ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
 36447  ** (in this case, MAX_PATHNAME bytes). The full-path is written to
 36448  ** this buffer before returning.
 36449  */
 36450  static int unixFullPathname(
 36451    sqlite3_vfs *pVfs,            /* Pointer to vfs object */
 36452    const char *zPath,            /* Possibly relative input path */
 36453    int nOut,                     /* Size of output buffer in bytes */
 36454    char *zOut                    /* Output buffer */
 36455  ){
 36456  #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
 36457    return mkFullPathname(zPath, zOut, nOut);
 36458  #else
 36459    int rc = SQLITE_OK;
 36460    int nByte;
 36461    int nLink = 1;                /* Number of symbolic links followed so far */
 36462    const char *zIn = zPath;      /* Input path for each iteration of loop */
 36463    char *zDel = 0;
 36464  
 36465    assert( pVfs->mxPathname==MAX_PATHNAME );
 36466    UNUSED_PARAMETER(pVfs);
 36467  
 36468    /* It's odd to simulate an io-error here, but really this is just
 36469    ** using the io-error infrastructure to test that SQLite handles this
 36470    ** function failing. This function could fail if, for example, the
 36471    ** current working directory has been unlinked.
 36472    */
 36473    SimulateIOError( return SQLITE_ERROR );
 36474  
 36475    do {
 36476  
 36477      /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
 36478      ** link, or false otherwise.  */
 36479      int bLink = 0;
 36480      struct stat buf;
 36481      if( osLstat(zIn, &buf)!=0 ){
 36482        if( errno!=ENOENT ){
 36483          rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
 36484        }
 36485      }else{
 36486        bLink = S_ISLNK(buf.st_mode);
 36487      }
 36488  
 36489      if( bLink ){
 36490        if( zDel==0 ){
 36491          zDel = sqlite3_malloc(nOut);
 36492          if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
 36493        }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
 36494          rc = SQLITE_CANTOPEN_BKPT;
 36495        }
 36496  
 36497        if( rc==SQLITE_OK ){
 36498          nByte = osReadlink(zIn, zDel, nOut-1);
 36499          if( nByte<0 ){
 36500            rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
 36501          }else{
 36502            if( zDel[0]!='/' ){
 36503              int n;
 36504              for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
 36505              if( nByte+n+1>nOut ){
 36506                rc = SQLITE_CANTOPEN_BKPT;
 36507              }else{
 36508                memmove(&zDel[n], zDel, nByte+1);
 36509                memcpy(zDel, zIn, n);
 36510                nByte += n;
 36511              }
 36512            }
 36513            zDel[nByte] = '\0';
 36514          }
 36515        }
 36516  
 36517        zIn = zDel;
 36518      }
 36519  
 36520      assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
 36521      if( rc==SQLITE_OK && zIn!=zOut ){
 36522        rc = mkFullPathname(zIn, zOut, nOut);
 36523      }
 36524      if( bLink==0 ) break;
 36525      zIn = zOut;
 36526    }while( rc==SQLITE_OK );
 36527  
 36528    sqlite3_free(zDel);
 36529    return rc;
 36530  #endif   /* HAVE_READLINK && HAVE_LSTAT */
 36531  }
 36532  
 36533  
 36534  #ifndef SQLITE_OMIT_LOAD_EXTENSION
 36535  /*
 36536  ** Interfaces for opening a shared library, finding entry points
 36537  ** within the shared library, and closing the shared library.
 36538  */
 36539  #include <dlfcn.h>
 36540  static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
 36541    UNUSED_PARAMETER(NotUsed);
 36542    return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
 36543  }
 36544  
 36545  /*
 36546  ** SQLite calls this function immediately after a call to unixDlSym() or
 36547  ** unixDlOpen() fails (returns a null pointer). If a more detailed error
 36548  ** message is available, it is written to zBufOut. If no error message
 36549  ** is available, zBufOut is left unmodified and SQLite uses a default
 36550  ** error message.
 36551  */
 36552  static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
 36553    const char *zErr;
 36554    UNUSED_PARAMETER(NotUsed);
 36555    unixEnterMutex();
 36556    zErr = dlerror();
 36557    if( zErr ){
 36558      sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
 36559    }
 36560    unixLeaveMutex();
 36561  }
 36562  static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
 36563    /* 
 36564    ** GCC with -pedantic-errors says that C90 does not allow a void* to be
 36565    ** cast into a pointer to a function.  And yet the library dlsym() routine
 36566    ** returns a void* which is really a pointer to a function.  So how do we
 36567    ** use dlsym() with -pedantic-errors?
 36568    **
 36569    ** Variable x below is defined to be a pointer to a function taking
 36570    ** parameters void* and const char* and returning a pointer to a function.
 36571    ** We initialize x by assigning it a pointer to the dlsym() function.
 36572    ** (That assignment requires a cast.)  Then we call the function that
 36573    ** x points to.  
 36574    **
 36575    ** This work-around is unlikely to work correctly on any system where
 36576    ** you really cannot cast a function pointer into void*.  But then, on the
 36577    ** other hand, dlsym() will not work on such a system either, so we have
 36578    ** not really lost anything.
 36579    */
 36580    void (*(*x)(void*,const char*))(void);
 36581    UNUSED_PARAMETER(NotUsed);
 36582    x = (void(*(*)(void*,const char*))(void))dlsym;
 36583    return (*x)(p, zSym);
 36584  }
 36585  static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
 36586    UNUSED_PARAMETER(NotUsed);
 36587    dlclose(pHandle);
 36588  }
 36589  #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
 36590    #define unixDlOpen  0
 36591    #define unixDlError 0
 36592    #define unixDlSym   0
 36593    #define unixDlClose 0
 36594  #endif
 36595  
 36596  /*
 36597  ** Write nBuf bytes of random data to the supplied buffer zBuf.
 36598  */
 36599  static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
 36600    UNUSED_PARAMETER(NotUsed);
 36601    assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
 36602  
 36603    /* We have to initialize zBuf to prevent valgrind from reporting
 36604    ** errors.  The reports issued by valgrind are incorrect - we would
 36605    ** prefer that the randomness be increased by making use of the
 36606    ** uninitialized space in zBuf - but valgrind errors tend to worry
 36607    ** some users.  Rather than argue, it seems easier just to initialize
 36608    ** the whole array and silence valgrind, even if that means less randomness
 36609    ** in the random seed.
 36610    **
 36611    ** When testing, initializing zBuf[] to zero is all we do.  That means
 36612    ** that we always use the same random number sequence.  This makes the
 36613    ** tests repeatable.
 36614    */
 36615    memset(zBuf, 0, nBuf);
 36616    randomnessPid = osGetpid(0);  
 36617  #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
 36618    {
 36619      int fd, got;
 36620      fd = robust_open("/dev/urandom", O_RDONLY, 0);
 36621      if( fd<0 ){
 36622        time_t t;
 36623        time(&t);
 36624        memcpy(zBuf, &t, sizeof(t));
 36625        memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
 36626        assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
 36627        nBuf = sizeof(t) + sizeof(randomnessPid);
 36628      }else{
 36629        do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
 36630        robust_close(0, fd, __LINE__);
 36631      }
 36632    }
 36633  #endif
 36634    return nBuf;
 36635  }
 36636  
 36637  
 36638  /*
 36639  ** Sleep for a little while.  Return the amount of time slept.
 36640  ** The argument is the number of microseconds we want to sleep.
 36641  ** The return value is the number of microseconds of sleep actually
 36642  ** requested from the underlying operating system, a number which
 36643  ** might be greater than or equal to the argument, but not less
 36644  ** than the argument.
 36645  */
 36646  static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
 36647  #if OS_VXWORKS
 36648    struct timespec sp;
 36649  
 36650    sp.tv_sec = microseconds / 1000000;
 36651    sp.tv_nsec = (microseconds % 1000000) * 1000;
 36652    nanosleep(&sp, NULL);
 36653    UNUSED_PARAMETER(NotUsed);
 36654    return microseconds;
 36655  #elif defined(HAVE_USLEEP) && HAVE_USLEEP
 36656    usleep(microseconds);
 36657    UNUSED_PARAMETER(NotUsed);
 36658    return microseconds;
 36659  #else
 36660    int seconds = (microseconds+999999)/1000000;
 36661    sleep(seconds);
 36662    UNUSED_PARAMETER(NotUsed);
 36663    return seconds*1000000;
 36664  #endif
 36665  }
 36666  
 36667  /*
 36668  ** The following variable, if set to a non-zero value, is interpreted as
 36669  ** the number of seconds since 1970 and is used to set the result of
 36670  ** sqlite3OsCurrentTime() during testing.
 36671  */
 36672  #ifdef SQLITE_TEST
 36673  SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
 36674  #endif
 36675  
 36676  /*
 36677  ** Find the current time (in Universal Coordinated Time).  Write into *piNow
 36678  ** the current time and date as a Julian Day number times 86_400_000.  In
 36679  ** other words, write into *piNow the number of milliseconds since the Julian
 36680  ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
 36681  ** proleptic Gregorian calendar.
 36682  **
 36683  ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date 
 36684  ** cannot be found.
 36685  */
 36686  static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
 36687    static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
 36688    int rc = SQLITE_OK;
 36689  #if defined(NO_GETTOD)
 36690    time_t t;
 36691    time(&t);
 36692    *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
 36693  #elif OS_VXWORKS
 36694    struct timespec sNow;
 36695    clock_gettime(CLOCK_REALTIME, &sNow);
 36696    *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
 36697  #else
 36698    struct timeval sNow;
 36699    (void)gettimeofday(&sNow, 0);  /* Cannot fail given valid arguments */
 36700    *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
 36701  #endif
 36702  
 36703  #ifdef SQLITE_TEST
 36704    if( sqlite3_current_time ){
 36705      *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
 36706    }
 36707  #endif
 36708    UNUSED_PARAMETER(NotUsed);
 36709    return rc;
 36710  }
 36711  
 36712  #ifndef SQLITE_OMIT_DEPRECATED
 36713  /*
 36714  ** Find the current time (in Universal Coordinated Time).  Write the
 36715  ** current time and date as a Julian Day number into *prNow and
 36716  ** return 0.  Return 1 if the time and date cannot be found.
 36717  */
 36718  static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
 36719    sqlite3_int64 i = 0;
 36720    int rc;
 36721    UNUSED_PARAMETER(NotUsed);
 36722    rc = unixCurrentTimeInt64(0, &i);
 36723    *prNow = i/86400000.0;
 36724    return rc;
 36725  }
 36726  #else
 36727  # define unixCurrentTime 0
 36728  #endif
 36729  
 36730  /*
 36731  ** The xGetLastError() method is designed to return a better
 36732  ** low-level error message when operating-system problems come up
 36733  ** during SQLite operation.  Only the integer return code is currently
 36734  ** used.
 36735  */
 36736  static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
 36737    UNUSED_PARAMETER(NotUsed);
 36738    UNUSED_PARAMETER(NotUsed2);
 36739    UNUSED_PARAMETER(NotUsed3);
 36740    return errno;
 36741  }
 36742  
 36743  
 36744  /*
 36745  ************************ End of sqlite3_vfs methods ***************************
 36746  ******************************************************************************/
 36747  
 36748  /******************************************************************************
 36749  ************************** Begin Proxy Locking ********************************
 36750  **
 36751  ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
 36752  ** other locking methods on secondary lock files.  Proxy locking is a
 36753  ** meta-layer over top of the primitive locking implemented above.  For
 36754  ** this reason, the division that implements of proxy locking is deferred
 36755  ** until late in the file (here) after all of the other I/O methods have
 36756  ** been defined - so that the primitive locking methods are available
 36757  ** as services to help with the implementation of proxy locking.
 36758  **
 36759  ****
 36760  **
 36761  ** The default locking schemes in SQLite use byte-range locks on the
 36762  ** database file to coordinate safe, concurrent access by multiple readers
 36763  ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
 36764  ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
 36765  ** as POSIX read & write locks over fixed set of locations (via fsctl),
 36766  ** on AFP and SMB only exclusive byte-range locks are available via fsctl
 36767  ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
 36768  ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
 36769  ** address in the shared range is taken for a SHARED lock, the entire
 36770  ** shared range is taken for an EXCLUSIVE lock):
 36771  **
 36772  **      PENDING_BYTE        0x40000000
 36773  **      RESERVED_BYTE       0x40000001
 36774  **      SHARED_RANGE        0x40000002 -> 0x40000200
 36775  **
 36776  ** This works well on the local file system, but shows a nearly 100x
 36777  ** slowdown in read performance on AFP because the AFP client disables
 36778  ** the read cache when byte-range locks are present.  Enabling the read
 36779  ** cache exposes a cache coherency problem that is present on all OS X
 36780  ** supported network file systems.  NFS and AFP both observe the
 36781  ** close-to-open semantics for ensuring cache coherency
 36782  ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
 36783  ** address the requirements for concurrent database access by multiple
 36784  ** readers and writers
 36785  ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
 36786  **
 36787  ** To address the performance and cache coherency issues, proxy file locking
 36788  ** changes the way database access is controlled by limiting access to a
 36789  ** single host at a time and moving file locks off of the database file
 36790  ** and onto a proxy file on the local file system.  
 36791  **
 36792  **
 36793  ** Using proxy locks
 36794  ** -----------------
 36795  **
 36796  ** C APIs
 36797  **
 36798  **  sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
 36799  **                       <proxy_path> | ":auto:");
 36800  **  sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
 36801  **                       &<proxy_path>);
 36802  **
 36803  **
 36804  ** SQL pragmas
 36805  **
 36806  **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
 36807  **  PRAGMA [database.]lock_proxy_file
 36808  **
 36809  ** Specifying ":auto:" means that if there is a conch file with a matching
 36810  ** host ID in it, the proxy path in the conch file will be used, otherwise
 36811  ** a proxy path based on the user's temp dir
 36812  ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
 36813  ** actual proxy file name is generated from the name and path of the
 36814  ** database file.  For example:
 36815  **
 36816  **       For database path "/Users/me/foo.db" 
 36817  **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
 36818  **
 36819  ** Once a lock proxy is configured for a database connection, it can not
 36820  ** be removed, however it may be switched to a different proxy path via
 36821  ** the above APIs (assuming the conch file is not being held by another
 36822  ** connection or process). 
 36823  **
 36824  **
 36825  ** How proxy locking works
 36826  ** -----------------------
 36827  **
 36828  ** Proxy file locking relies primarily on two new supporting files: 
 36829  **
 36830  **   *  conch file to limit access to the database file to a single host
 36831  **      at a time
 36832  **
 36833  **   *  proxy file to act as a proxy for the advisory locks normally
 36834  **      taken on the database
 36835  **
 36836  ** The conch file - to use a proxy file, sqlite must first "hold the conch"
 36837  ** by taking an sqlite-style shared lock on the conch file, reading the
 36838  ** contents and comparing the host's unique host ID (see below) and lock
 36839  ** proxy path against the values stored in the conch.  The conch file is
 36840  ** stored in the same directory as the database file and the file name
 36841  ** is patterned after the database file name as ".<databasename>-conch".
 36842  ** If the conch file does not exist, or its contents do not match the
 36843  ** host ID and/or proxy path, then the lock is escalated to an exclusive
 36844  ** lock and the conch file contents is updated with the host ID and proxy
 36845  ** path and the lock is downgraded to a shared lock again.  If the conch
 36846  ** is held by another process (with a shared lock), the exclusive lock
 36847  ** will fail and SQLITE_BUSY is returned.
 36848  **
 36849  ** The proxy file - a single-byte file used for all advisory file locks
 36850  ** normally taken on the database file.   This allows for safe sharing
 36851  ** of the database file for multiple readers and writers on the same
 36852  ** host (the conch ensures that they all use the same local lock file).
 36853  **
 36854  ** Requesting the lock proxy does not immediately take the conch, it is
 36855  ** only taken when the first request to lock database file is made.  
 36856  ** This matches the semantics of the traditional locking behavior, where
 36857  ** opening a connection to a database file does not take a lock on it.
 36858  ** The shared lock and an open file descriptor are maintained until 
 36859  ** the connection to the database is closed. 
 36860  **
 36861  ** The proxy file and the lock file are never deleted so they only need
 36862  ** to be created the first time they are used.
 36863  **
 36864  ** Configuration options
 36865  ** ---------------------
 36866  **
 36867  **  SQLITE_PREFER_PROXY_LOCKING
 36868  **
 36869  **       Database files accessed on non-local file systems are
 36870  **       automatically configured for proxy locking, lock files are
 36871  **       named automatically using the same logic as
 36872  **       PRAGMA lock_proxy_file=":auto:"
 36873  **    
 36874  **  SQLITE_PROXY_DEBUG
 36875  **
 36876  **       Enables the logging of error messages during host id file
 36877  **       retrieval and creation
 36878  **
 36879  **  LOCKPROXYDIR
 36880  **
 36881  **       Overrides the default directory used for lock proxy files that
 36882  **       are named automatically via the ":auto:" setting
 36883  **
 36884  **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
 36885  **
 36886  **       Permissions to use when creating a directory for storing the
 36887  **       lock proxy files, only used when LOCKPROXYDIR is not set.
 36888  **    
 36889  **    
 36890  ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
 36891  ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
 36892  ** force proxy locking to be used for every database file opened, and 0
 36893  ** will force automatic proxy locking to be disabled for all database
 36894  ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
 36895  ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
 36896  */
 36897  
 36898  /*
 36899  ** Proxy locking is only available on MacOSX 
 36900  */
 36901  #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 36902  
 36903  /*
 36904  ** The proxyLockingContext has the path and file structures for the remote 
 36905  ** and local proxy files in it
 36906  */
 36907  typedef struct proxyLockingContext proxyLockingContext;
 36908  struct proxyLockingContext {
 36909    unixFile *conchFile;         /* Open conch file */
 36910    char *conchFilePath;         /* Name of the conch file */
 36911    unixFile *lockProxy;         /* Open proxy lock file */
 36912    char *lockProxyPath;         /* Name of the proxy lock file */
 36913    char *dbPath;                /* Name of the open file */
 36914    int conchHeld;               /* 1 if the conch is held, -1 if lockless */
 36915    int nFails;                  /* Number of conch taking failures */
 36916    void *oldLockingContext;     /* Original lockingcontext to restore on close */
 36917    sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
 36918  };
 36919  
 36920  /* 
 36921  ** The proxy lock file path for the database at dbPath is written into lPath, 
 36922  ** which must point to valid, writable memory large enough for a maxLen length
 36923  ** file path. 
 36924  */
 36925  static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
 36926    int len;
 36927    int dbLen;
 36928    int i;
 36929  
 36930  #ifdef LOCKPROXYDIR
 36931    len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
 36932  #else
 36933  # ifdef _CS_DARWIN_USER_TEMP_DIR
 36934    {
 36935      if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
 36936        OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
 36937                 lPath, errno, osGetpid(0)));
 36938        return SQLITE_IOERR_LOCK;
 36939      }
 36940      len = strlcat(lPath, "sqliteplocks", maxLen);    
 36941    }
 36942  # else
 36943    len = strlcpy(lPath, "/tmp/", maxLen);
 36944  # endif
 36945  #endif
 36946  
 36947    if( lPath[len-1]!='/' ){
 36948      len = strlcat(lPath, "/", maxLen);
 36949    }
 36950    
 36951    /* transform the db path to a unique cache name */
 36952    dbLen = (int)strlen(dbPath);
 36953    for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
 36954      char c = dbPath[i];
 36955      lPath[i+len] = (c=='/')?'_':c;
 36956    }
 36957    lPath[i+len]='\0';
 36958    strlcat(lPath, ":auto:", maxLen);
 36959    OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
 36960    return SQLITE_OK;
 36961  }
 36962  
 36963  /* 
 36964   ** Creates the lock file and any missing directories in lockPath
 36965   */
 36966  static int proxyCreateLockPath(const char *lockPath){
 36967    int i, len;
 36968    char buf[MAXPATHLEN];
 36969    int start = 0;
 36970    
 36971    assert(lockPath!=NULL);
 36972    /* try to create all the intermediate directories */
 36973    len = (int)strlen(lockPath);
 36974    buf[0] = lockPath[0];
 36975    for( i=1; i<len; i++ ){
 36976      if( lockPath[i] == '/' && (i - start > 0) ){
 36977        /* only mkdir if leaf dir != "." or "/" or ".." */
 36978        if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
 36979           || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
 36980          buf[i]='\0';
 36981          if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
 36982            int err=errno;
 36983            if( err!=EEXIST ) {
 36984              OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
 36985                       "'%s' proxy lock path=%s pid=%d\n",
 36986                       buf, strerror(err), lockPath, osGetpid(0)));
 36987              return err;
 36988            }
 36989          }
 36990        }
 36991        start=i+1;
 36992      }
 36993      buf[i] = lockPath[i];
 36994    }
 36995    OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
 36996    return 0;
 36997  }
 36998  
 36999  /*
 37000  ** Create a new VFS file descriptor (stored in memory obtained from
 37001  ** sqlite3_malloc) and open the file named "path" in the file descriptor.
 37002  **
 37003  ** The caller is responsible not only for closing the file descriptor
 37004  ** but also for freeing the memory associated with the file descriptor.
 37005  */
 37006  static int proxyCreateUnixFile(
 37007      const char *path,        /* path for the new unixFile */
 37008      unixFile **ppFile,       /* unixFile created and returned by ref */
 37009      int islockfile           /* if non zero missing dirs will be created */
 37010  ) {
 37011    int fd = -1;
 37012    unixFile *pNew;
 37013    int rc = SQLITE_OK;
 37014    int openFlags = O_RDWR | O_CREAT;
 37015    sqlite3_vfs dummyVfs;
 37016    int terrno = 0;
 37017    UnixUnusedFd *pUnused = NULL;
 37018  
 37019    /* 1. first try to open/create the file
 37020    ** 2. if that fails, and this is a lock file (not-conch), try creating
 37021    ** the parent directories and then try again.
 37022    ** 3. if that fails, try to open the file read-only
 37023    ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
 37024    */
 37025    pUnused = findReusableFd(path, openFlags);
 37026    if( pUnused ){
 37027      fd = pUnused->fd;
 37028    }else{
 37029      pUnused = sqlite3_malloc64(sizeof(*pUnused));
 37030      if( !pUnused ){
 37031        return SQLITE_NOMEM_BKPT;
 37032      }
 37033    }
 37034    if( fd<0 ){
 37035      fd = robust_open(path, openFlags, 0);
 37036      terrno = errno;
 37037      if( fd<0 && errno==ENOENT && islockfile ){
 37038        if( proxyCreateLockPath(path) == SQLITE_OK ){
 37039          fd = robust_open(path, openFlags, 0);
 37040        }
 37041      }
 37042    }
 37043    if( fd<0 ){
 37044      openFlags = O_RDONLY;
 37045      fd = robust_open(path, openFlags, 0);
 37046      terrno = errno;
 37047    }
 37048    if( fd<0 ){
 37049      if( islockfile ){
 37050        return SQLITE_BUSY;
 37051      }
 37052      switch (terrno) {
 37053        case EACCES:
 37054          return SQLITE_PERM;
 37055        case EIO: 
 37056          return SQLITE_IOERR_LOCK; /* even though it is the conch */
 37057        default:
 37058          return SQLITE_CANTOPEN_BKPT;
 37059      }
 37060    }
 37061    
 37062    pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
 37063    if( pNew==NULL ){
 37064      rc = SQLITE_NOMEM_BKPT;
 37065      goto end_create_proxy;
 37066    }
 37067    memset(pNew, 0, sizeof(unixFile));
 37068    pNew->openFlags = openFlags;
 37069    memset(&dummyVfs, 0, sizeof(dummyVfs));
 37070    dummyVfs.pAppData = (void*)&autolockIoFinder;
 37071    dummyVfs.zName = "dummy";
 37072    pUnused->fd = fd;
 37073    pUnused->flags = openFlags;
 37074    pNew->pPreallocatedUnused = pUnused;
 37075    
 37076    rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
 37077    if( rc==SQLITE_OK ){
 37078      *ppFile = pNew;
 37079      return SQLITE_OK;
 37080    }
 37081  end_create_proxy:    
 37082    robust_close(pNew, fd, __LINE__);
 37083    sqlite3_free(pNew);
 37084    sqlite3_free(pUnused);
 37085    return rc;
 37086  }
 37087  
 37088  #ifdef SQLITE_TEST
 37089  /* simulate multiple hosts by creating unique hostid file paths */
 37090  SQLITE_API int sqlite3_hostid_num = 0;
 37091  #endif
 37092  
 37093  #define PROXY_HOSTIDLEN    16  /* conch file host id length */
 37094  
 37095  #ifdef HAVE_GETHOSTUUID
 37096  /* Not always defined in the headers as it ought to be */
 37097  extern int gethostuuid(uuid_t id, const struct timespec *wait);
 37098  #endif
 37099  
 37100  /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
 37101  ** bytes of writable memory.
 37102  */
 37103  static int proxyGetHostID(unsigned char *pHostID, int *pError){
 37104    assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
 37105    memset(pHostID, 0, PROXY_HOSTIDLEN);
 37106  #ifdef HAVE_GETHOSTUUID
 37107    {
 37108      struct timespec timeout = {1, 0}; /* 1 sec timeout */
 37109      if( gethostuuid(pHostID, &timeout) ){
 37110        int err = errno;
 37111        if( pError ){
 37112          *pError = err;
 37113        }
 37114        return SQLITE_IOERR;
 37115      }
 37116    }
 37117  #else
 37118    UNUSED_PARAMETER(pError);
 37119  #endif
 37120  #ifdef SQLITE_TEST
 37121    /* simulate multiple hosts by creating unique hostid file paths */
 37122    if( sqlite3_hostid_num != 0){
 37123      pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
 37124    }
 37125  #endif
 37126    
 37127    return SQLITE_OK;
 37128  }
 37129  
 37130  /* The conch file contains the header, host id and lock file path
 37131   */
 37132  #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
 37133  #define PROXY_HEADERLEN    1   /* conch file header length */
 37134  #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
 37135  #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
 37136  
 37137  /* 
 37138  ** Takes an open conch file, copies the contents to a new path and then moves 
 37139  ** it back.  The newly created file's file descriptor is assigned to the
 37140  ** conch file structure and finally the original conch file descriptor is 
 37141  ** closed.  Returns zero if successful.
 37142  */
 37143  static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
 37144    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
 37145    unixFile *conchFile = pCtx->conchFile;
 37146    char tPath[MAXPATHLEN];
 37147    char buf[PROXY_MAXCONCHLEN];
 37148    char *cPath = pCtx->conchFilePath;
 37149    size_t readLen = 0;
 37150    size_t pathLen = 0;
 37151    char errmsg[64] = "";
 37152    int fd = -1;
 37153    int rc = -1;
 37154    UNUSED_PARAMETER(myHostID);
 37155  
 37156    /* create a new path by replace the trailing '-conch' with '-break' */
 37157    pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
 37158    if( pathLen>MAXPATHLEN || pathLen<6 || 
 37159       (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
 37160      sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
 37161      goto end_breaklock;
 37162    }
 37163    /* read the conch content */
 37164    readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
 37165    if( readLen<PROXY_PATHINDEX ){
 37166      sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
 37167      goto end_breaklock;
 37168    }
 37169    /* write it out to the temporary break file */
 37170    fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
 37171    if( fd<0 ){
 37172      sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
 37173      goto end_breaklock;
 37174    }
 37175    if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
 37176      sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
 37177      goto end_breaklock;
 37178    }
 37179    if( rename(tPath, cPath) ){
 37180      sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
 37181      goto end_breaklock;
 37182    }
 37183    rc = 0;
 37184    fprintf(stderr, "broke stale lock on %s\n", cPath);
 37185    robust_close(pFile, conchFile->h, __LINE__);
 37186    conchFile->h = fd;
 37187    conchFile->openFlags = O_RDWR | O_CREAT;
 37188  
 37189  end_breaklock:
 37190    if( rc ){
 37191      if( fd>=0 ){
 37192        osUnlink(tPath);
 37193        robust_close(pFile, fd, __LINE__);
 37194      }
 37195      fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
 37196    }
 37197    return rc;
 37198  }
 37199  
 37200  /* Take the requested lock on the conch file and break a stale lock if the 
 37201  ** host id matches.
 37202  */
 37203  static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
 37204    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
 37205    unixFile *conchFile = pCtx->conchFile;
 37206    int rc = SQLITE_OK;
 37207    int nTries = 0;
 37208    struct timespec conchModTime;
 37209    
 37210    memset(&conchModTime, 0, sizeof(conchModTime));
 37211    do {
 37212      rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
 37213      nTries ++;
 37214      if( rc==SQLITE_BUSY ){
 37215        /* If the lock failed (busy):
 37216         * 1st try: get the mod time of the conch, wait 0.5s and try again. 
 37217         * 2nd try: fail if the mod time changed or host id is different, wait 
 37218         *           10 sec and try again
 37219         * 3rd try: break the lock unless the mod time has changed.
 37220         */
 37221        struct stat buf;
 37222        if( osFstat(conchFile->h, &buf) ){
 37223          storeLastErrno(pFile, errno);
 37224          return SQLITE_IOERR_LOCK;
 37225        }
 37226        
 37227        if( nTries==1 ){
 37228          conchModTime = buf.st_mtimespec;
 37229          usleep(500000); /* wait 0.5 sec and try the lock again*/
 37230          continue;  
 37231        }
 37232  
 37233        assert( nTries>1 );
 37234        if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
 37235           conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
 37236          return SQLITE_BUSY;
 37237        }
 37238        
 37239        if( nTries==2 ){  
 37240          char tBuf[PROXY_MAXCONCHLEN];
 37241          int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
 37242          if( len<0 ){
 37243            storeLastErrno(pFile, errno);
 37244            return SQLITE_IOERR_LOCK;
 37245          }
 37246          if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
 37247            /* don't break the lock if the host id doesn't match */
 37248            if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
 37249              return SQLITE_BUSY;
 37250            }
 37251          }else{
 37252            /* don't break the lock on short read or a version mismatch */
 37253            return SQLITE_BUSY;
 37254          }
 37255          usleep(10000000); /* wait 10 sec and try the lock again */
 37256          continue; 
 37257        }
 37258        
 37259        assert( nTries==3 );
 37260        if( 0==proxyBreakConchLock(pFile, myHostID) ){
 37261          rc = SQLITE_OK;
 37262          if( lockType==EXCLUSIVE_LOCK ){
 37263            rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
 37264          }
 37265          if( !rc ){
 37266            rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
 37267          }
 37268        }
 37269      }
 37270    } while( rc==SQLITE_BUSY && nTries<3 );
 37271    
 37272    return rc;
 37273  }
 37274  
 37275  /* Takes the conch by taking a shared lock and read the contents conch, if 
 37276  ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
 37277  ** lockPath means that the lockPath in the conch file will be used if the 
 37278  ** host IDs match, or a new lock path will be generated automatically 
 37279  ** and written to the conch file.
 37280  */
 37281  static int proxyTakeConch(unixFile *pFile){
 37282    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
 37283    
 37284    if( pCtx->conchHeld!=0 ){
 37285      return SQLITE_OK;
 37286    }else{
 37287      unixFile *conchFile = pCtx->conchFile;
 37288      uuid_t myHostID;
 37289      int pError = 0;
 37290      char readBuf[PROXY_MAXCONCHLEN];
 37291      char lockPath[MAXPATHLEN];
 37292      char *tempLockPath = NULL;
 37293      int rc = SQLITE_OK;
 37294      int createConch = 0;
 37295      int hostIdMatch = 0;
 37296      int readLen = 0;
 37297      int tryOldLockPath = 0;
 37298      int forceNewLockPath = 0;
 37299      
 37300      OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
 37301               (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
 37302               osGetpid(0)));
 37303  
 37304      rc = proxyGetHostID(myHostID, &pError);
 37305      if( (rc&0xff)==SQLITE_IOERR ){
 37306        storeLastErrno(pFile, pError);
 37307        goto end_takeconch;
 37308      }
 37309      rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
 37310      if( rc!=SQLITE_OK ){
 37311        goto end_takeconch;
 37312      }
 37313      /* read the existing conch file */
 37314      readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
 37315      if( readLen<0 ){
 37316        /* I/O error: lastErrno set by seekAndRead */
 37317        storeLastErrno(pFile, conchFile->lastErrno);
 37318        rc = SQLITE_IOERR_READ;
 37319        goto end_takeconch;
 37320      }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
 37321               readBuf[0]!=(char)PROXY_CONCHVERSION ){
 37322        /* a short read or version format mismatch means we need to create a new 
 37323        ** conch file. 
 37324        */
 37325        createConch = 1;
 37326      }
 37327      /* if the host id matches and the lock path already exists in the conch
 37328      ** we'll try to use the path there, if we can't open that path, we'll 
 37329      ** retry with a new auto-generated path 
 37330      */
 37331      do { /* in case we need to try again for an :auto: named lock file */
 37332  
 37333        if( !createConch && !forceNewLockPath ){
 37334          hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
 37335                                    PROXY_HOSTIDLEN);
 37336          /* if the conch has data compare the contents */
 37337          if( !pCtx->lockProxyPath ){
 37338            /* for auto-named local lock file, just check the host ID and we'll
 37339             ** use the local lock file path that's already in there
 37340             */
 37341            if( hostIdMatch ){
 37342              size_t pathLen = (readLen - PROXY_PATHINDEX);
 37343              
 37344              if( pathLen>=MAXPATHLEN ){
 37345                pathLen=MAXPATHLEN-1;
 37346              }
 37347              memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
 37348              lockPath[pathLen] = 0;
 37349              tempLockPath = lockPath;
 37350              tryOldLockPath = 1;
 37351              /* create a copy of the lock path if the conch is taken */
 37352              goto end_takeconch;
 37353            }
 37354          }else if( hostIdMatch
 37355                 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
 37356                             readLen-PROXY_PATHINDEX)
 37357          ){
 37358            /* conch host and lock path match */
 37359            goto end_takeconch; 
 37360          }
 37361        }
 37362        
 37363        /* if the conch isn't writable and doesn't match, we can't take it */
 37364        if( (conchFile->openFlags&O_RDWR) == 0 ){
 37365          rc = SQLITE_BUSY;
 37366          goto end_takeconch;
 37367        }
 37368        
 37369        /* either the conch didn't match or we need to create a new one */
 37370        if( !pCtx->lockProxyPath ){
 37371          proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
 37372          tempLockPath = lockPath;
 37373          /* create a copy of the lock path _only_ if the conch is taken */
 37374        }
 37375        
 37376        /* update conch with host and path (this will fail if other process
 37377        ** has a shared lock already), if the host id matches, use the big
 37378        ** stick.
 37379        */
 37380        futimes(conchFile->h, NULL);
 37381        if( hostIdMatch && !createConch ){
 37382          if( conchFile->pInode && conchFile->pInode->nShared>1 ){
 37383            /* We are trying for an exclusive lock but another thread in this
 37384             ** same process is still holding a shared lock. */
 37385            rc = SQLITE_BUSY;
 37386          } else {          
 37387            rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
 37388          }
 37389        }else{
 37390          rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
 37391        }
 37392        if( rc==SQLITE_OK ){
 37393          char writeBuffer[PROXY_MAXCONCHLEN];
 37394          int writeSize = 0;
 37395          
 37396          writeBuffer[0] = (char)PROXY_CONCHVERSION;
 37397          memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
 37398          if( pCtx->lockProxyPath!=NULL ){
 37399            strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
 37400                    MAXPATHLEN);
 37401          }else{
 37402            strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
 37403          }
 37404          writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
 37405          robust_ftruncate(conchFile->h, writeSize);
 37406          rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
 37407          full_fsync(conchFile->h,0,0);
 37408          /* If we created a new conch file (not just updated the contents of a 
 37409           ** valid conch file), try to match the permissions of the database 
 37410           */
 37411          if( rc==SQLITE_OK && createConch ){
 37412            struct stat buf;
 37413            int err = osFstat(pFile->h, &buf);
 37414            if( err==0 ){
 37415              mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
 37416                                          S_IROTH|S_IWOTH);
 37417              /* try to match the database file R/W permissions, ignore failure */
 37418  #ifndef SQLITE_PROXY_DEBUG
 37419              osFchmod(conchFile->h, cmode);
 37420  #else
 37421              do{
 37422                rc = osFchmod(conchFile->h, cmode);
 37423              }while( rc==(-1) && errno==EINTR );
 37424              if( rc!=0 ){
 37425                int code = errno;
 37426                fprintf(stderr, "fchmod %o FAILED with %d %s\n",
 37427                        cmode, code, strerror(code));
 37428              } else {
 37429                fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
 37430              }
 37431            }else{
 37432              int code = errno;
 37433              fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
 37434                      err, code, strerror(code));
 37435  #endif
 37436            }
 37437          }
 37438        }
 37439        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
 37440        
 37441      end_takeconch:
 37442        OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
 37443        if( rc==SQLITE_OK && pFile->openFlags ){
 37444          int fd;
 37445          if( pFile->h>=0 ){
 37446            robust_close(pFile, pFile->h, __LINE__);
 37447          }
 37448          pFile->h = -1;
 37449          fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
 37450          OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
 37451          if( fd>=0 ){
 37452            pFile->h = fd;
 37453          }else{
 37454            rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
 37455             during locking */
 37456          }
 37457        }
 37458        if( rc==SQLITE_OK && !pCtx->lockProxy ){
 37459          char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
 37460          rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
 37461          if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
 37462            /* we couldn't create the proxy lock file with the old lock file path
 37463             ** so try again via auto-naming 
 37464             */
 37465            forceNewLockPath = 1;
 37466            tryOldLockPath = 0;
 37467            continue; /* go back to the do {} while start point, try again */
 37468          }
 37469        }
 37470        if( rc==SQLITE_OK ){
 37471          /* Need to make a copy of path if we extracted the value
 37472           ** from the conch file or the path was allocated on the stack
 37473           */
 37474          if( tempLockPath ){
 37475            pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
 37476            if( !pCtx->lockProxyPath ){
 37477              rc = SQLITE_NOMEM_BKPT;
 37478            }
 37479          }
 37480        }
 37481        if( rc==SQLITE_OK ){
 37482          pCtx->conchHeld = 1;
 37483          
 37484          if( pCtx->lockProxy->pMethod == &afpIoMethods ){
 37485            afpLockingContext *afpCtx;
 37486            afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
 37487            afpCtx->dbPath = pCtx->lockProxyPath;
 37488          }
 37489        } else {
 37490          conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
 37491        }
 37492        OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
 37493                 rc==SQLITE_OK?"ok":"failed"));
 37494        return rc;
 37495      } while (1); /* in case we need to retry the :auto: lock file - 
 37496                   ** we should never get here except via the 'continue' call. */
 37497    }
 37498  }
 37499  
 37500  /*
 37501  ** If pFile holds a lock on a conch file, then release that lock.
 37502  */
 37503  static int proxyReleaseConch(unixFile *pFile){
 37504    int rc = SQLITE_OK;         /* Subroutine return code */
 37505    proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
 37506    unixFile *conchFile;        /* Name of the conch file */
 37507  
 37508    pCtx = (proxyLockingContext *)pFile->lockingContext;
 37509    conchFile = pCtx->conchFile;
 37510    OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
 37511             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
 37512             osGetpid(0)));
 37513    if( pCtx->conchHeld>0 ){
 37514      rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
 37515    }
 37516    pCtx->conchHeld = 0;
 37517    OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
 37518             (rc==SQLITE_OK ? "ok" : "failed")));
 37519    return rc;
 37520  }
 37521  
 37522  /*
 37523  ** Given the name of a database file, compute the name of its conch file.
 37524  ** Store the conch filename in memory obtained from sqlite3_malloc64().
 37525  ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
 37526  ** or SQLITE_NOMEM if unable to obtain memory.
 37527  **
 37528  ** The caller is responsible for ensuring that the allocated memory
 37529  ** space is eventually freed.
 37530  **
 37531  ** *pConchPath is set to NULL if a memory allocation error occurs.
 37532  */
 37533  static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
 37534    int i;                        /* Loop counter */
 37535    int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
 37536    char *conchPath;              /* buffer in which to construct conch name */
 37537  
 37538    /* Allocate space for the conch filename and initialize the name to
 37539    ** the name of the original database file. */  
 37540    *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
 37541    if( conchPath==0 ){
 37542      return SQLITE_NOMEM_BKPT;
 37543    }
 37544    memcpy(conchPath, dbPath, len+1);
 37545    
 37546    /* now insert a "." before the last / character */
 37547    for( i=(len-1); i>=0; i-- ){
 37548      if( conchPath[i]=='/' ){
 37549        i++;
 37550        break;
 37551      }
 37552    }
 37553    conchPath[i]='.';
 37554    while ( i<len ){
 37555      conchPath[i+1]=dbPath[i];
 37556      i++;
 37557    }
 37558  
 37559    /* append the "-conch" suffix to the file */
 37560    memcpy(&conchPath[i+1], "-conch", 7);
 37561    assert( (int)strlen(conchPath) == len+7 );
 37562  
 37563    return SQLITE_OK;
 37564  }
 37565  
 37566  
 37567  /* Takes a fully configured proxy locking-style unix file and switches
 37568  ** the local lock file path 
 37569  */
 37570  static int switchLockProxyPath(unixFile *pFile, const char *path) {
 37571    proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
 37572    char *oldPath = pCtx->lockProxyPath;
 37573    int rc = SQLITE_OK;
 37574  
 37575    if( pFile->eFileLock!=NO_LOCK ){
 37576      return SQLITE_BUSY;
 37577    }  
 37578  
 37579    /* nothing to do if the path is NULL, :auto: or matches the existing path */
 37580    if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
 37581      (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
 37582      return SQLITE_OK;
 37583    }else{
 37584      unixFile *lockProxy = pCtx->lockProxy;
 37585      pCtx->lockProxy=NULL;
 37586      pCtx->conchHeld = 0;
 37587      if( lockProxy!=NULL ){
 37588        rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
 37589        if( rc ) return rc;
 37590        sqlite3_free(lockProxy);
 37591      }
 37592      sqlite3_free(oldPath);
 37593      pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
 37594    }
 37595    
 37596    return rc;
 37597  }
 37598  
 37599  /*
 37600  ** pFile is a file that has been opened by a prior xOpen call.  dbPath
 37601  ** is a string buffer at least MAXPATHLEN+1 characters in size.
 37602  **
 37603  ** This routine find the filename associated with pFile and writes it
 37604  ** int dbPath.
 37605  */
 37606  static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
 37607  #if defined(__APPLE__)
 37608    if( pFile->pMethod == &afpIoMethods ){
 37609      /* afp style keeps a reference to the db path in the filePath field 
 37610      ** of the struct */
 37611      assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
 37612      strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
 37613              MAXPATHLEN);
 37614    } else
 37615  #endif
 37616    if( pFile->pMethod == &dotlockIoMethods ){
 37617      /* dot lock style uses the locking context to store the dot lock
 37618      ** file path */
 37619      int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
 37620      memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
 37621    }else{
 37622      /* all other styles use the locking context to store the db file path */
 37623      assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
 37624      strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
 37625    }
 37626    return SQLITE_OK;
 37627  }
 37628  
 37629  /*
 37630  ** Takes an already filled in unix file and alters it so all file locking 
 37631  ** will be performed on the local proxy lock file.  The following fields
 37632  ** are preserved in the locking context so that they can be restored and 
 37633  ** the unix structure properly cleaned up at close time:
 37634  **  ->lockingContext
 37635  **  ->pMethod
 37636  */
 37637  static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
 37638    proxyLockingContext *pCtx;
 37639    char dbPath[MAXPATHLEN+1];       /* Name of the database file */
 37640    char *lockPath=NULL;
 37641    int rc = SQLITE_OK;
 37642    
 37643    if( pFile->eFileLock!=NO_LOCK ){
 37644      return SQLITE_BUSY;
 37645    }
 37646    proxyGetDbPathForUnixFile(pFile, dbPath);
 37647    if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
 37648      lockPath=NULL;
 37649    }else{
 37650      lockPath=(char *)path;
 37651    }
 37652    
 37653    OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
 37654             (lockPath ? lockPath : ":auto:"), osGetpid(0)));
 37655  
 37656    pCtx = sqlite3_malloc64( sizeof(*pCtx) );
 37657    if( pCtx==0 ){
 37658      return SQLITE_NOMEM_BKPT;
 37659    }
 37660    memset(pCtx, 0, sizeof(*pCtx));
 37661  
 37662    rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
 37663    if( rc==SQLITE_OK ){
 37664      rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
 37665      if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
 37666        /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
 37667        ** (c) the file system is read-only, then enable no-locking access.
 37668        ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
 37669        ** that openFlags will have only one of O_RDONLY or O_RDWR.
 37670        */
 37671        struct statfs fsInfo;
 37672        struct stat conchInfo;
 37673        int goLockless = 0;
 37674  
 37675        if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
 37676          int err = errno;
 37677          if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
 37678            goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
 37679          }
 37680        }
 37681        if( goLockless ){
 37682          pCtx->conchHeld = -1; /* read only FS/ lockless */
 37683          rc = SQLITE_OK;
 37684        }
 37685      }
 37686    }  
 37687    if( rc==SQLITE_OK && lockPath ){
 37688      pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
 37689    }
 37690  
 37691    if( rc==SQLITE_OK ){
 37692      pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
 37693      if( pCtx->dbPath==NULL ){
 37694        rc = SQLITE_NOMEM_BKPT;
 37695      }
 37696    }
 37697    if( rc==SQLITE_OK ){
 37698      /* all memory is allocated, proxys are created and assigned, 
 37699      ** switch the locking context and pMethod then return.
 37700      */
 37701      pCtx->oldLockingContext = pFile->lockingContext;
 37702      pFile->lockingContext = pCtx;
 37703      pCtx->pOldMethod = pFile->pMethod;
 37704      pFile->pMethod = &proxyIoMethods;
 37705    }else{
 37706      if( pCtx->conchFile ){ 
 37707        pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
 37708        sqlite3_free(pCtx->conchFile);
 37709      }
 37710      sqlite3DbFree(0, pCtx->lockProxyPath);
 37711      sqlite3_free(pCtx->conchFilePath); 
 37712      sqlite3_free(pCtx);
 37713    }
 37714    OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
 37715             (rc==SQLITE_OK ? "ok" : "failed")));
 37716    return rc;
 37717  }
 37718  
 37719  
 37720  /*
 37721  ** This routine handles sqlite3_file_control() calls that are specific
 37722  ** to proxy locking.
 37723  */
 37724  static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
 37725    switch( op ){
 37726      case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
 37727        unixFile *pFile = (unixFile*)id;
 37728        if( pFile->pMethod == &proxyIoMethods ){
 37729          proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
 37730          proxyTakeConch(pFile);
 37731          if( pCtx->lockProxyPath ){
 37732            *(const char **)pArg = pCtx->lockProxyPath;
 37733          }else{
 37734            *(const char **)pArg = ":auto: (not held)";
 37735          }
 37736        } else {
 37737          *(const char **)pArg = NULL;
 37738        }
 37739        return SQLITE_OK;
 37740      }
 37741      case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
 37742        unixFile *pFile = (unixFile*)id;
 37743        int rc = SQLITE_OK;
 37744        int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
 37745        if( pArg==NULL || (const char *)pArg==0 ){
 37746          if( isProxyStyle ){
 37747            /* turn off proxy locking - not supported.  If support is added for
 37748            ** switching proxy locking mode off then it will need to fail if
 37749            ** the journal mode is WAL mode. 
 37750            */
 37751            rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
 37752          }else{
 37753            /* turn off proxy locking - already off - NOOP */
 37754            rc = SQLITE_OK;
 37755          }
 37756        }else{
 37757          const char *proxyPath = (const char *)pArg;
 37758          if( isProxyStyle ){
 37759            proxyLockingContext *pCtx = 
 37760              (proxyLockingContext*)pFile->lockingContext;
 37761            if( !strcmp(pArg, ":auto:") 
 37762             || (pCtx->lockProxyPath &&
 37763                 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
 37764            ){
 37765              rc = SQLITE_OK;
 37766            }else{
 37767              rc = switchLockProxyPath(pFile, proxyPath);
 37768            }
 37769          }else{
 37770            /* turn on proxy file locking */
 37771            rc = proxyTransformUnixFile(pFile, proxyPath);
 37772          }
 37773        }
 37774        return rc;
 37775      }
 37776      default: {
 37777        assert( 0 );  /* The call assures that only valid opcodes are sent */
 37778      }
 37779    }
 37780    /*NOTREACHED*/
 37781    return SQLITE_ERROR;
 37782  }
 37783  
 37784  /*
 37785  ** Within this division (the proxying locking implementation) the procedures
 37786  ** above this point are all utilities.  The lock-related methods of the
 37787  ** proxy-locking sqlite3_io_method object follow.
 37788  */
 37789  
 37790  
 37791  /*
 37792  ** This routine checks if there is a RESERVED lock held on the specified
 37793  ** file by this or any other process. If such a lock is held, set *pResOut
 37794  ** to a non-zero value otherwise *pResOut is set to zero.  The return value
 37795  ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
 37796  */
 37797  static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
 37798    unixFile *pFile = (unixFile*)id;
 37799    int rc = proxyTakeConch(pFile);
 37800    if( rc==SQLITE_OK ){
 37801      proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
 37802      if( pCtx->conchHeld>0 ){
 37803        unixFile *proxy = pCtx->lockProxy;
 37804        return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
 37805      }else{ /* conchHeld < 0 is lockless */
 37806        pResOut=0;
 37807      }
 37808    }
 37809    return rc;
 37810  }
 37811  
 37812  /*
 37813  ** Lock the file with the lock specified by parameter eFileLock - one
 37814  ** of the following:
 37815  **
 37816  **     (1) SHARED_LOCK
 37817  **     (2) RESERVED_LOCK
 37818  **     (3) PENDING_LOCK
 37819  **     (4) EXCLUSIVE_LOCK
 37820  **
 37821  ** Sometimes when requesting one lock state, additional lock states
 37822  ** are inserted in between.  The locking might fail on one of the later
 37823  ** transitions leaving the lock state different from what it started but
 37824  ** still short of its goal.  The following chart shows the allowed
 37825  ** transitions and the inserted intermediate states:
 37826  **
 37827  **    UNLOCKED -> SHARED
 37828  **    SHARED -> RESERVED
 37829  **    SHARED -> (PENDING) -> EXCLUSIVE
 37830  **    RESERVED -> (PENDING) -> EXCLUSIVE
 37831  **    PENDING -> EXCLUSIVE
 37832  **
 37833  ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
 37834  ** routine to lower a locking level.
 37835  */
 37836  static int proxyLock(sqlite3_file *id, int eFileLock) {
 37837    unixFile *pFile = (unixFile*)id;
 37838    int rc = proxyTakeConch(pFile);
 37839    if( rc==SQLITE_OK ){
 37840      proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
 37841      if( pCtx->conchHeld>0 ){
 37842        unixFile *proxy = pCtx->lockProxy;
 37843        rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
 37844        pFile->eFileLock = proxy->eFileLock;
 37845      }else{
 37846        /* conchHeld < 0 is lockless */
 37847      }
 37848    }
 37849    return rc;
 37850  }
 37851  
 37852  
 37853  /*
 37854  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 37855  ** must be either NO_LOCK or SHARED_LOCK.
 37856  **
 37857  ** If the locking level of the file descriptor is already at or below
 37858  ** the requested locking level, this routine is a no-op.
 37859  */
 37860  static int proxyUnlock(sqlite3_file *id, int eFileLock) {
 37861    unixFile *pFile = (unixFile*)id;
 37862    int rc = proxyTakeConch(pFile);
 37863    if( rc==SQLITE_OK ){
 37864      proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
 37865      if( pCtx->conchHeld>0 ){
 37866        unixFile *proxy = pCtx->lockProxy;
 37867        rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
 37868        pFile->eFileLock = proxy->eFileLock;
 37869      }else{
 37870        /* conchHeld < 0 is lockless */
 37871      }
 37872    }
 37873    return rc;
 37874  }
 37875  
 37876  /*
 37877  ** Close a file that uses proxy locks.
 37878  */
 37879  static int proxyClose(sqlite3_file *id) {
 37880    if( ALWAYS(id) ){
 37881      unixFile *pFile = (unixFile*)id;
 37882      proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
 37883      unixFile *lockProxy = pCtx->lockProxy;
 37884      unixFile *conchFile = pCtx->conchFile;
 37885      int rc = SQLITE_OK;
 37886      
 37887      if( lockProxy ){
 37888        rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
 37889        if( rc ) return rc;
 37890        rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
 37891        if( rc ) return rc;
 37892        sqlite3_free(lockProxy);
 37893        pCtx->lockProxy = 0;
 37894      }
 37895      if( conchFile ){
 37896        if( pCtx->conchHeld ){
 37897          rc = proxyReleaseConch(pFile);
 37898          if( rc ) return rc;
 37899        }
 37900        rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
 37901        if( rc ) return rc;
 37902        sqlite3_free(conchFile);
 37903      }
 37904      sqlite3DbFree(0, pCtx->lockProxyPath);
 37905      sqlite3_free(pCtx->conchFilePath);
 37906      sqlite3DbFree(0, pCtx->dbPath);
 37907      /* restore the original locking context and pMethod then close it */
 37908      pFile->lockingContext = pCtx->oldLockingContext;
 37909      pFile->pMethod = pCtx->pOldMethod;
 37910      sqlite3_free(pCtx);
 37911      return pFile->pMethod->xClose(id);
 37912    }
 37913    return SQLITE_OK;
 37914  }
 37915  
 37916  
 37917  
 37918  #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
 37919  /*
 37920  ** The proxy locking style is intended for use with AFP filesystems.
 37921  ** And since AFP is only supported on MacOSX, the proxy locking is also
 37922  ** restricted to MacOSX.
 37923  ** 
 37924  **
 37925  ******************* End of the proxy lock implementation **********************
 37926  ******************************************************************************/
 37927  
 37928  /*
 37929  ** Initialize the operating system interface.
 37930  **
 37931  ** This routine registers all VFS implementations for unix-like operating
 37932  ** systems.  This routine, and the sqlite3_os_end() routine that follows,
 37933  ** should be the only routines in this file that are visible from other
 37934  ** files.
 37935  **
 37936  ** This routine is called once during SQLite initialization and by a
 37937  ** single thread.  The memory allocation and mutex subsystems have not
 37938  ** necessarily been initialized when this routine is called, and so they
 37939  ** should not be used.
 37940  */
 37941  SQLITE_API int sqlite3_os_init(void){ 
 37942    /* 
 37943    ** The following macro defines an initializer for an sqlite3_vfs object.
 37944    ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
 37945    ** to the "finder" function.  (pAppData is a pointer to a pointer because
 37946    ** silly C90 rules prohibit a void* from being cast to a function pointer
 37947    ** and so we have to go through the intermediate pointer to avoid problems
 37948    ** when compiling with -pedantic-errors on GCC.)
 37949    **
 37950    ** The FINDER parameter to this macro is the name of the pointer to the
 37951    ** finder-function.  The finder-function returns a pointer to the
 37952    ** sqlite_io_methods object that implements the desired locking
 37953    ** behaviors.  See the division above that contains the IOMETHODS
 37954    ** macro for addition information on finder-functions.
 37955    **
 37956    ** Most finders simply return a pointer to a fixed sqlite3_io_methods
 37957    ** object.  But the "autolockIoFinder" available on MacOSX does a little
 37958    ** more than that; it looks at the filesystem type that hosts the 
 37959    ** database file and tries to choose an locking method appropriate for
 37960    ** that filesystem time.
 37961    */
 37962    #define UNIXVFS(VFSNAME, FINDER) {                        \
 37963      3,                    /* iVersion */                    \
 37964      sizeof(unixFile),     /* szOsFile */                    \
 37965      MAX_PATHNAME,         /* mxPathname */                  \
 37966      0,                    /* pNext */                       \
 37967      VFSNAME,              /* zName */                       \
 37968      (void*)&FINDER,       /* pAppData */                    \
 37969      unixOpen,             /* xOpen */                       \
 37970      unixDelete,           /* xDelete */                     \
 37971      unixAccess,           /* xAccess */                     \
 37972      unixFullPathname,     /* xFullPathname */               \
 37973      unixDlOpen,           /* xDlOpen */                     \
 37974      unixDlError,          /* xDlError */                    \
 37975      unixDlSym,            /* xDlSym */                      \
 37976      unixDlClose,          /* xDlClose */                    \
 37977      unixRandomness,       /* xRandomness */                 \
 37978      unixSleep,            /* xSleep */                      \
 37979      unixCurrentTime,      /* xCurrentTime */                \
 37980      unixGetLastError,     /* xGetLastError */               \
 37981      unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
 37982      unixSetSystemCall,    /* xSetSystemCall */              \
 37983      unixGetSystemCall,    /* xGetSystemCall */              \
 37984      unixNextSystemCall,   /* xNextSystemCall */             \
 37985    }
 37986  
 37987    /*
 37988    ** All default VFSes for unix are contained in the following array.
 37989    **
 37990    ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
 37991    ** by the SQLite core when the VFS is registered.  So the following
 37992    ** array cannot be const.
 37993    */
 37994    static sqlite3_vfs aVfs[] = {
 37995  #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
 37996      UNIXVFS("unix",          autolockIoFinder ),
 37997  #elif OS_VXWORKS
 37998      UNIXVFS("unix",          vxworksIoFinder ),
 37999  #else
 38000      UNIXVFS("unix",          posixIoFinder ),
 38001  #endif
 38002      UNIXVFS("unix-none",     nolockIoFinder ),
 38003      UNIXVFS("unix-dotfile",  dotlockIoFinder ),
 38004      UNIXVFS("unix-excl",     posixIoFinder ),
 38005  #if OS_VXWORKS
 38006      UNIXVFS("unix-namedsem", semIoFinder ),
 38007  #endif
 38008  #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
 38009      UNIXVFS("unix-posix",    posixIoFinder ),
 38010  #endif
 38011  #if SQLITE_ENABLE_LOCKING_STYLE
 38012      UNIXVFS("unix-flock",    flockIoFinder ),
 38013  #endif
 38014  #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
 38015      UNIXVFS("unix-afp",      afpIoFinder ),
 38016      UNIXVFS("unix-nfs",      nfsIoFinder ),
 38017      UNIXVFS("unix-proxy",    proxyIoFinder ),
 38018  #endif
 38019    };
 38020    unsigned int i;          /* Loop counter */
 38021  
 38022    /* Double-check that the aSyscall[] array has been constructed
 38023    ** correctly.  See ticket [bb3a86e890c8e96ab] */
 38024    assert( ArraySize(aSyscall)==29 );
 38025  
 38026    /* Register all VFSes defined in the aVfs[] array */
 38027    for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
 38028      sqlite3_vfs_register(&aVfs[i], i==0);
 38029    }
 38030    return SQLITE_OK; 
 38031  }
 38032  
 38033  /*
 38034  ** Shutdown the operating system interface.
 38035  **
 38036  ** Some operating systems might need to do some cleanup in this routine,
 38037  ** to release dynamically allocated objects.  But not on unix.
 38038  ** This routine is a no-op for unix.
 38039  */
 38040  SQLITE_API int sqlite3_os_end(void){ 
 38041    return SQLITE_OK; 
 38042  }
 38043   
 38044  #endif /* SQLITE_OS_UNIX */
 38045  
 38046  /************** End of os_unix.c *********************************************/
 38047  /************** Begin file os_win.c ******************************************/
 38048  /*
 38049  ** 2004 May 22
 38050  **
 38051  ** The author disclaims copyright to this source code.  In place of
 38052  ** a legal notice, here is a blessing:
 38053  **
 38054  **    May you do good and not evil.
 38055  **    May you find forgiveness for yourself and forgive others.
 38056  **    May you share freely, never taking more than you give.
 38057  **
 38058  ******************************************************************************
 38059  **
 38060  ** This file contains code that is specific to Windows.
 38061  */
 38062  /* #include "sqliteInt.h" */
 38063  #if SQLITE_OS_WIN               /* This file is used for Windows only */
 38064  
 38065  /*
 38066  ** Include code that is common to all os_*.c files
 38067  */
 38068  /************** Include os_common.h in the middle of os_win.c ****************/
 38069  /************** Begin file os_common.h ***************************************/
 38070  /*
 38071  ** 2004 May 22
 38072  **
 38073  ** The author disclaims copyright to this source code.  In place of
 38074  ** a legal notice, here is a blessing:
 38075  **
 38076  **    May you do good and not evil.
 38077  **    May you find forgiveness for yourself and forgive others.
 38078  **    May you share freely, never taking more than you give.
 38079  **
 38080  ******************************************************************************
 38081  **
 38082  ** This file contains macros and a little bit of code that is common to
 38083  ** all of the platform-specific files (os_*.c) and is #included into those
 38084  ** files.
 38085  **
 38086  ** This file should be #included by the os_*.c files only.  It is not a
 38087  ** general purpose header file.
 38088  */
 38089  #ifndef _OS_COMMON_H_
 38090  #define _OS_COMMON_H_
 38091  
 38092  /*
 38093  ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
 38094  ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
 38095  ** switch.  The following code should catch this problem at compile-time.
 38096  */
 38097  #ifdef MEMORY_DEBUG
 38098  # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
 38099  #endif
 38100  
 38101  /*
 38102  ** Macros for performance tracing.  Normally turned off.  Only works
 38103  ** on i486 hardware.
 38104  */
 38105  #ifdef SQLITE_PERFORMANCE_TRACE
 38106  
 38107  /*
 38108  ** hwtime.h contains inline assembler code for implementing
 38109  ** high-performance timing routines.
 38110  */
 38111  /************** Include hwtime.h in the middle of os_common.h ****************/
 38112  /************** Begin file hwtime.h ******************************************/
 38113  /*
 38114  ** 2008 May 27
 38115  **
 38116  ** The author disclaims copyright to this source code.  In place of
 38117  ** a legal notice, here is a blessing:
 38118  **
 38119  **    May you do good and not evil.
 38120  **    May you find forgiveness for yourself and forgive others.
 38121  **    May you share freely, never taking more than you give.
 38122  **
 38123  ******************************************************************************
 38124  **
 38125  ** This file contains inline asm code for retrieving "high-performance"
 38126  ** counters for x86 class CPUs.
 38127  */
 38128  #ifndef SQLITE_HWTIME_H
 38129  #define SQLITE_HWTIME_H
 38130  
 38131  /*
 38132  ** The following routine only works on pentium-class (or newer) processors.
 38133  ** It uses the RDTSC opcode to read the cycle count value out of the
 38134  ** processor and returns that value.  This can be used for high-res
 38135  ** profiling.
 38136  */
 38137  #if (defined(__GNUC__) || defined(_MSC_VER)) && \
 38138        (defined(i386) || defined(__i386__) || defined(_M_IX86))
 38139  
 38140    #if defined(__GNUC__)
 38141  
 38142    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 38143       unsigned int lo, hi;
 38144       __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
 38145       return (sqlite_uint64)hi << 32 | lo;
 38146    }
 38147  
 38148    #elif defined(_MSC_VER)
 38149  
 38150    __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
 38151       __asm {
 38152          rdtsc
 38153          ret       ; return value at EDX:EAX
 38154       }
 38155    }
 38156  
 38157    #endif
 38158  
 38159  #elif (defined(__GNUC__) && defined(__x86_64__))
 38160  
 38161    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 38162        unsigned long val;
 38163        __asm__ __volatile__ ("rdtsc" : "=A" (val));
 38164        return val;
 38165    }
 38166   
 38167  #elif (defined(__GNUC__) && defined(__ppc__))
 38168  
 38169    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 38170        unsigned long long retval;
 38171        unsigned long junk;
 38172        __asm__ __volatile__ ("\n\
 38173            1:      mftbu   %1\n\
 38174                    mftb    %L0\n\
 38175                    mftbu   %0\n\
 38176                    cmpw    %0,%1\n\
 38177                    bne     1b"
 38178                    : "=r" (retval), "=r" (junk));
 38179        return retval;
 38180    }
 38181  
 38182  #else
 38183  
 38184    #error Need implementation of sqlite3Hwtime() for your platform.
 38185  
 38186    /*
 38187    ** To compile without implementing sqlite3Hwtime() for your platform,
 38188    ** you can remove the above #error and use the following
 38189    ** stub function.  You will lose timing support for many
 38190    ** of the debugging and testing utilities, but it should at
 38191    ** least compile and run.
 38192    */
 38193  SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
 38194  
 38195  #endif
 38196  
 38197  #endif /* !defined(SQLITE_HWTIME_H) */
 38198  
 38199  /************** End of hwtime.h **********************************************/
 38200  /************** Continuing where we left off in os_common.h ******************/
 38201  
 38202  static sqlite_uint64 g_start;
 38203  static sqlite_uint64 g_elapsed;
 38204  #define TIMER_START       g_start=sqlite3Hwtime()
 38205  #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
 38206  #define TIMER_ELAPSED     g_elapsed
 38207  #else
 38208  #define TIMER_START
 38209  #define TIMER_END
 38210  #define TIMER_ELAPSED     ((sqlite_uint64)0)
 38211  #endif
 38212  
 38213  /*
 38214  ** If we compile with the SQLITE_TEST macro set, then the following block
 38215  ** of code will give us the ability to simulate a disk I/O error.  This
 38216  ** is used for testing the I/O recovery logic.
 38217  */
 38218  #if defined(SQLITE_TEST)
 38219  SQLITE_API extern int sqlite3_io_error_hit;
 38220  SQLITE_API extern int sqlite3_io_error_hardhit;
 38221  SQLITE_API extern int sqlite3_io_error_pending;
 38222  SQLITE_API extern int sqlite3_io_error_persist;
 38223  SQLITE_API extern int sqlite3_io_error_benign;
 38224  SQLITE_API extern int sqlite3_diskfull_pending;
 38225  SQLITE_API extern int sqlite3_diskfull;
 38226  #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
 38227  #define SimulateIOError(CODE)  \
 38228    if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
 38229         || sqlite3_io_error_pending-- == 1 )  \
 38230                { local_ioerr(); CODE; }
 38231  static void local_ioerr(){
 38232    IOTRACE(("IOERR\n"));
 38233    sqlite3_io_error_hit++;
 38234    if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
 38235  }
 38236  #define SimulateDiskfullError(CODE) \
 38237     if( sqlite3_diskfull_pending ){ \
 38238       if( sqlite3_diskfull_pending == 1 ){ \
 38239         local_ioerr(); \
 38240         sqlite3_diskfull = 1; \
 38241         sqlite3_io_error_hit = 1; \
 38242         CODE; \
 38243       }else{ \
 38244         sqlite3_diskfull_pending--; \
 38245       } \
 38246     }
 38247  #else
 38248  #define SimulateIOErrorBenign(X)
 38249  #define SimulateIOError(A)
 38250  #define SimulateDiskfullError(A)
 38251  #endif /* defined(SQLITE_TEST) */
 38252  
 38253  /*
 38254  ** When testing, keep a count of the number of open files.
 38255  */
 38256  #if defined(SQLITE_TEST)
 38257  SQLITE_API extern int sqlite3_open_file_count;
 38258  #define OpenCounter(X)  sqlite3_open_file_count+=(X)
 38259  #else
 38260  #define OpenCounter(X)
 38261  #endif /* defined(SQLITE_TEST) */
 38262  
 38263  #endif /* !defined(_OS_COMMON_H_) */
 38264  
 38265  /************** End of os_common.h *******************************************/
 38266  /************** Continuing where we left off in os_win.c *********************/
 38267  
 38268  /*
 38269  ** Include the header file for the Windows VFS.
 38270  */
 38271  /* #include "os_win.h" */
 38272  
 38273  /*
 38274  ** Compiling and using WAL mode requires several APIs that are only
 38275  ** available in Windows platforms based on the NT kernel.
 38276  */
 38277  #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
 38278  #  error "WAL mode requires support from the Windows NT kernel, compile\
 38279   with SQLITE_OMIT_WAL."
 38280  #endif
 38281  
 38282  #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
 38283  #  error "Memory mapped files require support from the Windows NT kernel,\
 38284   compile with SQLITE_MAX_MMAP_SIZE=0."
 38285  #endif
 38286  
 38287  /*
 38288  ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
 38289  ** based on the sub-platform)?
 38290  */
 38291  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
 38292  #  define SQLITE_WIN32_HAS_ANSI
 38293  #endif
 38294  
 38295  /*
 38296  ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
 38297  ** based on the sub-platform)?
 38298  */
 38299  #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
 38300      !defined(SQLITE_WIN32_NO_WIDE)
 38301  #  define SQLITE_WIN32_HAS_WIDE
 38302  #endif
 38303  
 38304  /*
 38305  ** Make sure at least one set of Win32 APIs is available.
 38306  */
 38307  #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
 38308  #  error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
 38309   must be defined."
 38310  #endif
 38311  
 38312  /*
 38313  ** Define the required Windows SDK version constants if they are not
 38314  ** already available.
 38315  */
 38316  #ifndef NTDDI_WIN8
 38317  #  define NTDDI_WIN8                        0x06020000
 38318  #endif
 38319  
 38320  #ifndef NTDDI_WINBLUE
 38321  #  define NTDDI_WINBLUE                     0x06030000
 38322  #endif
 38323  
 38324  #ifndef NTDDI_WINTHRESHOLD
 38325  #  define NTDDI_WINTHRESHOLD                0x06040000
 38326  #endif
 38327  
 38328  /*
 38329  ** Check to see if the GetVersionEx[AW] functions are deprecated on the
 38330  ** target system.  GetVersionEx was first deprecated in Win8.1.
 38331  */
 38332  #ifndef SQLITE_WIN32_GETVERSIONEX
 38333  #  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
 38334  #    define SQLITE_WIN32_GETVERSIONEX   0   /* GetVersionEx() is deprecated */
 38335  #  else
 38336  #    define SQLITE_WIN32_GETVERSIONEX   1   /* GetVersionEx() is current */
 38337  #  endif
 38338  #endif
 38339  
 38340  /*
 38341  ** Check to see if the CreateFileMappingA function is supported on the
 38342  ** target system.  It is unavailable when using "mincore.lib" on Win10.
 38343  ** When compiling for Windows 10, always assume "mincore.lib" is in use.
 38344  */
 38345  #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
 38346  #  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
 38347  #    define SQLITE_WIN32_CREATEFILEMAPPINGA   0
 38348  #  else
 38349  #    define SQLITE_WIN32_CREATEFILEMAPPINGA   1
 38350  #  endif
 38351  #endif
 38352  
 38353  /*
 38354  ** This constant should already be defined (in the "WinDef.h" SDK file).
 38355  */
 38356  #ifndef MAX_PATH
 38357  #  define MAX_PATH                      (260)
 38358  #endif
 38359  
 38360  /*
 38361  ** Maximum pathname length (in chars) for Win32.  This should normally be
 38362  ** MAX_PATH.
 38363  */
 38364  #ifndef SQLITE_WIN32_MAX_PATH_CHARS
 38365  #  define SQLITE_WIN32_MAX_PATH_CHARS   (MAX_PATH)
 38366  #endif
 38367  
 38368  /*
 38369  ** This constant should already be defined (in the "WinNT.h" SDK file).
 38370  */
 38371  #ifndef UNICODE_STRING_MAX_CHARS
 38372  #  define UNICODE_STRING_MAX_CHARS      (32767)
 38373  #endif
 38374  
 38375  /*
 38376  ** Maximum pathname length (in chars) for WinNT.  This should normally be
 38377  ** UNICODE_STRING_MAX_CHARS.
 38378  */
 38379  #ifndef SQLITE_WINNT_MAX_PATH_CHARS
 38380  #  define SQLITE_WINNT_MAX_PATH_CHARS   (UNICODE_STRING_MAX_CHARS)
 38381  #endif
 38382  
 38383  /*
 38384  ** Maximum pathname length (in bytes) for Win32.  The MAX_PATH macro is in
 38385  ** characters, so we allocate 4 bytes per character assuming worst-case of
 38386  ** 4-bytes-per-character for UTF8.
 38387  */
 38388  #ifndef SQLITE_WIN32_MAX_PATH_BYTES
 38389  #  define SQLITE_WIN32_MAX_PATH_BYTES   (SQLITE_WIN32_MAX_PATH_CHARS*4)
 38390  #endif
 38391  
 38392  /*
 38393  ** Maximum pathname length (in bytes) for WinNT.  This should normally be
 38394  ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
 38395  */
 38396  #ifndef SQLITE_WINNT_MAX_PATH_BYTES
 38397  #  define SQLITE_WINNT_MAX_PATH_BYTES   \
 38398                              (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
 38399  #endif
 38400  
 38401  /*
 38402  ** Maximum error message length (in chars) for WinRT.
 38403  */
 38404  #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
 38405  #  define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
 38406  #endif
 38407  
 38408  /*
 38409  ** Returns non-zero if the character should be treated as a directory
 38410  ** separator.
 38411  */
 38412  #ifndef winIsDirSep
 38413  #  define winIsDirSep(a)                (((a) == '/') || ((a) == '\\'))
 38414  #endif
 38415  
 38416  /*
 38417  ** This macro is used when a local variable is set to a value that is
 38418  ** [sometimes] not used by the code (e.g. via conditional compilation).
 38419  */
 38420  #ifndef UNUSED_VARIABLE_VALUE
 38421  #  define UNUSED_VARIABLE_VALUE(x)      (void)(x)
 38422  #endif
 38423  
 38424  /*
 38425  ** Returns the character that should be used as the directory separator.
 38426  */
 38427  #ifndef winGetDirSep
 38428  #  define winGetDirSep()                '\\'
 38429  #endif
 38430  
 38431  /*
 38432  ** Do we need to manually define the Win32 file mapping APIs for use with WAL
 38433  ** mode or memory mapped files (e.g. these APIs are available in the Windows
 38434  ** CE SDK; however, they are not present in the header file)?
 38435  */
 38436  #if SQLITE_WIN32_FILEMAPPING_API && \
 38437          (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
 38438  /*
 38439  ** Two of the file mapping APIs are different under WinRT.  Figure out which
 38440  ** set we need.
 38441  */
 38442  #if SQLITE_OS_WINRT
 38443  WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
 38444          LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
 38445  
 38446  WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
 38447  #else
 38448  #if defined(SQLITE_WIN32_HAS_ANSI)
 38449  WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
 38450          DWORD, DWORD, DWORD, LPCSTR);
 38451  #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
 38452  
 38453  #if defined(SQLITE_WIN32_HAS_WIDE)
 38454  WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
 38455          DWORD, DWORD, DWORD, LPCWSTR);
 38456  #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
 38457  
 38458  WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
 38459  #endif /* SQLITE_OS_WINRT */
 38460  
 38461  /*
 38462  ** These file mapping APIs are common to both Win32 and WinRT.
 38463  */
 38464  
 38465  WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
 38466  WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
 38467  #endif /* SQLITE_WIN32_FILEMAPPING_API */
 38468  
 38469  /*
 38470  ** Some Microsoft compilers lack this definition.
 38471  */
 38472  #ifndef INVALID_FILE_ATTRIBUTES
 38473  # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
 38474  #endif
 38475  
 38476  #ifndef FILE_FLAG_MASK
 38477  # define FILE_FLAG_MASK          (0xFF3C0000)
 38478  #endif
 38479  
 38480  #ifndef FILE_ATTRIBUTE_MASK
 38481  # define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
 38482  #endif
 38483  
 38484  #ifndef SQLITE_OMIT_WAL
 38485  /* Forward references to structures used for WAL */
 38486  typedef struct winShm winShm;           /* A connection to shared-memory */
 38487  typedef struct winShmNode winShmNode;   /* A region of shared-memory */
 38488  #endif
 38489  
 38490  /*
 38491  ** WinCE lacks native support for file locking so we have to fake it
 38492  ** with some code of our own.
 38493  */
 38494  #if SQLITE_OS_WINCE
 38495  typedef struct winceLock {
 38496    int nReaders;       /* Number of reader locks obtained */
 38497    BOOL bPending;      /* Indicates a pending lock has been obtained */
 38498    BOOL bReserved;     /* Indicates a reserved lock has been obtained */
 38499    BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
 38500  } winceLock;
 38501  #endif
 38502  
 38503  /*
 38504  ** The winFile structure is a subclass of sqlite3_file* specific to the win32
 38505  ** portability layer.
 38506  */
 38507  typedef struct winFile winFile;
 38508  struct winFile {
 38509    const sqlite3_io_methods *pMethod; /*** Must be first ***/
 38510    sqlite3_vfs *pVfs;      /* The VFS used to open this file */
 38511    HANDLE h;               /* Handle for accessing the file */
 38512    u8 locktype;            /* Type of lock currently held on this file */
 38513    short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
 38514    u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
 38515    DWORD lastErrno;        /* The Windows errno from the last I/O error */
 38516  #ifndef SQLITE_OMIT_WAL
 38517    winShm *pShm;           /* Instance of shared memory on this file */
 38518  #endif
 38519    const char *zPath;      /* Full pathname of this file */
 38520    int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
 38521  #if SQLITE_OS_WINCE
 38522    LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
 38523    HANDLE hMutex;          /* Mutex used to control access to shared lock */
 38524    HANDLE hShared;         /* Shared memory segment used for locking */
 38525    winceLock local;        /* Locks obtained by this instance of winFile */
 38526    winceLock *shared;      /* Global shared lock memory for the file  */
 38527  #endif
 38528  #if SQLITE_MAX_MMAP_SIZE>0
 38529    int nFetchOut;                /* Number of outstanding xFetch references */
 38530    HANDLE hMap;                  /* Handle for accessing memory mapping */
 38531    void *pMapRegion;             /* Area memory mapped */
 38532    sqlite3_int64 mmapSize;       /* Usable size of mapped region */
 38533    sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
 38534    sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
 38535  #endif
 38536  };
 38537  
 38538  /*
 38539  ** The winVfsAppData structure is used for the pAppData member for all of the
 38540  ** Win32 VFS variants.
 38541  */
 38542  typedef struct winVfsAppData winVfsAppData;
 38543  struct winVfsAppData {
 38544    const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
 38545    void *pAppData;                    /* The extra pAppData, if any. */
 38546    BOOL bNoLock;                      /* Non-zero if locking is disabled. */
 38547  };
 38548  
 38549  /*
 38550  ** Allowed values for winFile.ctrlFlags
 38551  */
 38552  #define WINFILE_RDONLY          0x02   /* Connection is read only */
 38553  #define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
 38554  #define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
 38555  
 38556  /*
 38557   * The size of the buffer used by sqlite3_win32_write_debug().
 38558   */
 38559  #ifndef SQLITE_WIN32_DBG_BUF_SIZE
 38560  #  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
 38561  #endif
 38562  
 38563  /*
 38564   * The value used with sqlite3_win32_set_directory() to specify that
 38565   * the data directory should be changed.
 38566   */
 38567  #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
 38568  #  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
 38569  #endif
 38570  
 38571  /*
 38572   * The value used with sqlite3_win32_set_directory() to specify that
 38573   * the temporary directory should be changed.
 38574   */
 38575  #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
 38576  #  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
 38577  #endif
 38578  
 38579  /*
 38580   * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
 38581   * various Win32 API heap functions instead of our own.
 38582   */
 38583  #ifdef SQLITE_WIN32_MALLOC
 38584  
 38585  /*
 38586   * If this is non-zero, an isolated heap will be created by the native Win32
 38587   * allocator subsystem; otherwise, the default process heap will be used.  This
 38588   * setting has no effect when compiling for WinRT.  By default, this is enabled
 38589   * and an isolated heap will be created to store all allocated data.
 38590   *
 38591   ******************************************************************************
 38592   * WARNING: It is important to note that when this setting is non-zero and the
 38593   *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
 38594   *          function), all data that was allocated using the isolated heap will
 38595   *          be freed immediately and any attempt to access any of that freed
 38596   *          data will almost certainly result in an immediate access violation.
 38597   ******************************************************************************
 38598   */
 38599  #ifndef SQLITE_WIN32_HEAP_CREATE
 38600  #  define SQLITE_WIN32_HEAP_CREATE        (TRUE)
 38601  #endif
 38602  
 38603  /*
 38604   * This is the maximum possible initial size of the Win32-specific heap, in
 38605   * bytes.
 38606   */
 38607  #ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE
 38608  #  define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)
 38609  #endif
 38610  
 38611  /*
 38612   * This is the extra space for the initial size of the Win32-specific heap,
 38613   * in bytes.  This value may be zero.
 38614   */
 38615  #ifndef SQLITE_WIN32_HEAP_INIT_EXTRA
 38616  #  define SQLITE_WIN32_HEAP_INIT_EXTRA  (4194304)
 38617  #endif
 38618  
 38619  /*
 38620   * Calculate the maximum legal cache size, in pages, based on the maximum
 38621   * possible initial heap size and the default page size, setting aside the
 38622   * needed extra space.
 38623   */
 38624  #ifndef SQLITE_WIN32_MAX_CACHE_SIZE
 38625  #  define SQLITE_WIN32_MAX_CACHE_SIZE   (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
 38626                                            (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \
 38627                                           (SQLITE_DEFAULT_PAGE_SIZE))
 38628  #endif
 38629  
 38630  /*
 38631   * This is cache size used in the calculation of the initial size of the
 38632   * Win32-specific heap.  It cannot be negative.
 38633   */
 38634  #ifndef SQLITE_WIN32_CACHE_SIZE
 38635  #  if SQLITE_DEFAULT_CACHE_SIZE>=0
 38636  #    define SQLITE_WIN32_CACHE_SIZE     (SQLITE_DEFAULT_CACHE_SIZE)
 38637  #  else
 38638  #    define SQLITE_WIN32_CACHE_SIZE     (-(SQLITE_DEFAULT_CACHE_SIZE))
 38639  #  endif
 38640  #endif
 38641  
 38642  /*
 38643   * Make sure that the calculated cache size, in pages, cannot cause the
 38644   * initial size of the Win32-specific heap to exceed the maximum amount
 38645   * of memory that can be specified in the call to HeapCreate.
 38646   */
 38647  #if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE
 38648  #  undef SQLITE_WIN32_CACHE_SIZE
 38649  #  define SQLITE_WIN32_CACHE_SIZE       (2000)
 38650  #endif
 38651  
 38652  /*
 38653   * The initial size of the Win32-specific heap.  This value may be zero.
 38654   */
 38655  #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
 38656  #  define SQLITE_WIN32_HEAP_INIT_SIZE   ((SQLITE_WIN32_CACHE_SIZE) * \
 38657                                           (SQLITE_DEFAULT_PAGE_SIZE) + \
 38658                                           (SQLITE_WIN32_HEAP_INIT_EXTRA))
 38659  #endif
 38660  
 38661  /*
 38662   * The maximum size of the Win32-specific heap.  This value may be zero.
 38663   */
 38664  #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
 38665  #  define SQLITE_WIN32_HEAP_MAX_SIZE    (0)
 38666  #endif
 38667  
 38668  /*
 38669   * The extra flags to use in calls to the Win32 heap APIs.  This value may be
 38670   * zero for the default behavior.
 38671   */
 38672  #ifndef SQLITE_WIN32_HEAP_FLAGS
 38673  #  define SQLITE_WIN32_HEAP_FLAGS       (0)
 38674  #endif
 38675  
 38676  
 38677  /*
 38678  ** The winMemData structure stores information required by the Win32-specific
 38679  ** sqlite3_mem_methods implementation.
 38680  */
 38681  typedef struct winMemData winMemData;
 38682  struct winMemData {
 38683  #ifndef NDEBUG
 38684    u32 magic1;   /* Magic number to detect structure corruption. */
 38685  #endif
 38686    HANDLE hHeap; /* The handle to our heap. */
 38687    BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
 38688  #ifndef NDEBUG
 38689    u32 magic2;   /* Magic number to detect structure corruption. */
 38690  #endif
 38691  };
 38692  
 38693  #ifndef NDEBUG
 38694  #define WINMEM_MAGIC1     0x42b2830b
 38695  #define WINMEM_MAGIC2     0xbd4d7cf4
 38696  #endif
 38697  
 38698  static struct winMemData win_mem_data = {
 38699  #ifndef NDEBUG
 38700    WINMEM_MAGIC1,
 38701  #endif
 38702    NULL, FALSE
 38703  #ifndef NDEBUG
 38704    ,WINMEM_MAGIC2
 38705  #endif
 38706  };
 38707  
 38708  #ifndef NDEBUG
 38709  #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
 38710  #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
 38711  #define winMemAssertMagic()  winMemAssertMagic1(); winMemAssertMagic2();
 38712  #else
 38713  #define winMemAssertMagic()
 38714  #endif
 38715  
 38716  #define winMemGetDataPtr()  &win_mem_data
 38717  #define winMemGetHeap()     win_mem_data.hHeap
 38718  #define winMemGetOwned()    win_mem_data.bOwned
 38719  
 38720  static void *winMemMalloc(int nBytes);
 38721  static void winMemFree(void *pPrior);
 38722  static void *winMemRealloc(void *pPrior, int nBytes);
 38723  static int winMemSize(void *p);
 38724  static int winMemRoundup(int n);
 38725  static int winMemInit(void *pAppData);
 38726  static void winMemShutdown(void *pAppData);
 38727  
 38728  SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
 38729  #endif /* SQLITE_WIN32_MALLOC */
 38730  
 38731  /*
 38732  ** The following variable is (normally) set once and never changes
 38733  ** thereafter.  It records whether the operating system is Win9x
 38734  ** or WinNT.
 38735  **
 38736  ** 0:   Operating system unknown.
 38737  ** 1:   Operating system is Win9x.
 38738  ** 2:   Operating system is WinNT.
 38739  **
 38740  ** In order to facilitate testing on a WinNT system, the test fixture
 38741  ** can manually set this value to 1 to emulate Win98 behavior.
 38742  */
 38743  #ifdef SQLITE_TEST
 38744  SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
 38745  #else
 38746  static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
 38747  #endif
 38748  
 38749  #ifndef SYSCALL
 38750  #  define SYSCALL sqlite3_syscall_ptr
 38751  #endif
 38752  
 38753  /*
 38754  ** This function is not available on Windows CE or WinRT.
 38755   */
 38756  
 38757  #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
 38758  #  define osAreFileApisANSI()       1
 38759  #endif
 38760  
 38761  /*
 38762  ** Many system calls are accessed through pointer-to-functions so that
 38763  ** they may be overridden at runtime to facilitate fault injection during
 38764  ** testing and sandboxing.  The following array holds the names and pointers
 38765  ** to all overrideable system calls.
 38766  */
 38767  static struct win_syscall {
 38768    const char *zName;            /* Name of the system call */
 38769    sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
 38770    sqlite3_syscall_ptr pDefault; /* Default value */
 38771  } aSyscall[] = {
 38772  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
 38773    { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
 38774  #else
 38775    { "AreFileApisANSI",         (SYSCALL)0,                       0 },
 38776  #endif
 38777  
 38778  #ifndef osAreFileApisANSI
 38779  #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
 38780  #endif
 38781  
 38782  #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
 38783    { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
 38784  #else
 38785    { "CharLowerW",              (SYSCALL)0,                       0 },
 38786  #endif
 38787  
 38788  #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
 38789  
 38790  #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
 38791    { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
 38792  #else
 38793    { "CharUpperW",              (SYSCALL)0,                       0 },
 38794  #endif
 38795  
 38796  #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
 38797  
 38798    { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
 38799  
 38800  #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
 38801  
 38802  #if defined(SQLITE_WIN32_HAS_ANSI)
 38803    { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
 38804  #else
 38805    { "CreateFileA",             (SYSCALL)0,                       0 },
 38806  #endif
 38807  
 38808  #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
 38809          LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
 38810  
 38811  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
 38812    { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
 38813  #else
 38814    { "CreateFileW",             (SYSCALL)0,                       0 },
 38815  #endif
 38816  
 38817  #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
 38818          LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
 38819  
 38820  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
 38821          (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
 38822          SQLITE_WIN32_CREATEFILEMAPPINGA
 38823    { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
 38824  #else
 38825    { "CreateFileMappingA",      (SYSCALL)0,                       0 },
 38826  #endif
 38827  
 38828  #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
 38829          DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
 38830  
 38831  #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
 38832          (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
 38833    { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
 38834  #else
 38835    { "CreateFileMappingW",      (SYSCALL)0,                       0 },
 38836  #endif
 38837  
 38838  #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
 38839          DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
 38840  
 38841  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
 38842    { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
 38843  #else
 38844    { "CreateMutexW",            (SYSCALL)0,                       0 },
 38845  #endif
 38846  
 38847  #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
 38848          LPCWSTR))aSyscall[8].pCurrent)
 38849  
 38850  #if defined(SQLITE_WIN32_HAS_ANSI)
 38851    { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
 38852  #else
 38853    { "DeleteFileA",             (SYSCALL)0,                       0 },
 38854  #endif
 38855  
 38856  #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
 38857  
 38858  #if defined(SQLITE_WIN32_HAS_WIDE)
 38859    { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
 38860  #else
 38861    { "DeleteFileW",             (SYSCALL)0,                       0 },
 38862  #endif
 38863  
 38864  #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
 38865  
 38866  #if SQLITE_OS_WINCE
 38867    { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
 38868  #else
 38869    { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
 38870  #endif
 38871  
 38872  #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
 38873          LPFILETIME))aSyscall[11].pCurrent)
 38874  
 38875  #if SQLITE_OS_WINCE
 38876    { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
 38877  #else
 38878    { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
 38879  #endif
 38880  
 38881  #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
 38882          LPSYSTEMTIME))aSyscall[12].pCurrent)
 38883  
 38884    { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
 38885  
 38886  #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
 38887  
 38888  #if defined(SQLITE_WIN32_HAS_ANSI)
 38889    { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
 38890  #else
 38891    { "FormatMessageA",          (SYSCALL)0,                       0 },
 38892  #endif
 38893  
 38894  #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
 38895          DWORD,va_list*))aSyscall[14].pCurrent)
 38896  
 38897  #if defined(SQLITE_WIN32_HAS_WIDE)
 38898    { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
 38899  #else
 38900    { "FormatMessageW",          (SYSCALL)0,                       0 },
 38901  #endif
 38902  
 38903  #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
 38904          DWORD,va_list*))aSyscall[15].pCurrent)
 38905  
 38906  #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
 38907    { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
 38908  #else
 38909    { "FreeLibrary",             (SYSCALL)0,                       0 },
 38910  #endif
 38911  
 38912  #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
 38913  
 38914    { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
 38915  
 38916  #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
 38917  
 38918  #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
 38919    { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
 38920  #else
 38921    { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
 38922  #endif
 38923  
 38924  #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
 38925          LPDWORD))aSyscall[18].pCurrent)
 38926  
 38927  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
 38928    { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
 38929  #else
 38930    { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
 38931  #endif
 38932  
 38933  #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
 38934          LPDWORD))aSyscall[19].pCurrent)
 38935  
 38936  #if defined(SQLITE_WIN32_HAS_ANSI)
 38937    { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
 38938  #else
 38939    { "GetFileAttributesA",      (SYSCALL)0,                       0 },
 38940  #endif
 38941  
 38942  #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
 38943  
 38944  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
 38945    { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
 38946  #else
 38947    { "GetFileAttributesW",      (SYSCALL)0,                       0 },
 38948  #endif
 38949  
 38950  #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
 38951  
 38952  #if defined(SQLITE_WIN32_HAS_WIDE)
 38953    { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
 38954  #else
 38955    { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
 38956  #endif
 38957  
 38958  #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
 38959          LPVOID))aSyscall[22].pCurrent)
 38960  
 38961  #if !SQLITE_OS_WINRT
 38962    { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
 38963  #else
 38964    { "GetFileSize",             (SYSCALL)0,                       0 },
 38965  #endif
 38966  
 38967  #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
 38968  
 38969  #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
 38970    { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
 38971  #else
 38972    { "GetFullPathNameA",        (SYSCALL)0,                       0 },
 38973  #endif
 38974  
 38975  #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
 38976          LPSTR*))aSyscall[24].pCurrent)
 38977  
 38978  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
 38979    { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
 38980  #else
 38981    { "GetFullPathNameW",        (SYSCALL)0,                       0 },
 38982  #endif
 38983  
 38984  #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
 38985          LPWSTR*))aSyscall[25].pCurrent)
 38986  
 38987    { "GetLastError",            (SYSCALL)GetLastError,            0 },
 38988  
 38989  #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
 38990  
 38991  #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
 38992  #if SQLITE_OS_WINCE
 38993    /* The GetProcAddressA() routine is only available on Windows CE. */
 38994    { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
 38995  #else
 38996    /* All other Windows platforms expect GetProcAddress() to take
 38997    ** an ANSI string regardless of the _UNICODE setting */
 38998    { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
 38999  #endif
 39000  #else
 39001    { "GetProcAddressA",         (SYSCALL)0,                       0 },
 39002  #endif
 39003  
 39004  #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
 39005          LPCSTR))aSyscall[27].pCurrent)
 39006  
 39007  #if !SQLITE_OS_WINRT
 39008    { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
 39009  #else
 39010    { "GetSystemInfo",           (SYSCALL)0,                       0 },
 39011  #endif
 39012  
 39013  #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
 39014  
 39015    { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
 39016  
 39017  #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
 39018  
 39019  #if !SQLITE_OS_WINCE
 39020    { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
 39021  #else
 39022    { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
 39023  #endif
 39024  
 39025  #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
 39026          LPFILETIME))aSyscall[30].pCurrent)
 39027  
 39028  #if defined(SQLITE_WIN32_HAS_ANSI)
 39029    { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
 39030  #else
 39031    { "GetTempPathA",            (SYSCALL)0,                       0 },
 39032  #endif
 39033  
 39034  #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
 39035  
 39036  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
 39037    { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
 39038  #else
 39039    { "GetTempPathW",            (SYSCALL)0,                       0 },
 39040  #endif
 39041  
 39042  #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
 39043  
 39044  #if !SQLITE_OS_WINRT
 39045    { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
 39046  #else
 39047    { "GetTickCount",            (SYSCALL)0,                       0 },
 39048  #endif
 39049  
 39050  #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
 39051  
 39052  #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
 39053    { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
 39054  #else
 39055    { "GetVersionExA",           (SYSCALL)0,                       0 },
 39056  #endif
 39057  
 39058  #define osGetVersionExA ((BOOL(WINAPI*)( \
 39059          LPOSVERSIONINFOA))aSyscall[34].pCurrent)
 39060  
 39061  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
 39062          SQLITE_WIN32_GETVERSIONEX
 39063    { "GetVersionExW",           (SYSCALL)GetVersionExW,           0 },
 39064  #else
 39065    { "GetVersionExW",           (SYSCALL)0,                       0 },
 39066  #endif
 39067  
 39068  #define osGetVersionExW ((BOOL(WINAPI*)( \
 39069          LPOSVERSIONINFOW))aSyscall[35].pCurrent)
 39070  
 39071    { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
 39072  
 39073  #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
 39074          SIZE_T))aSyscall[36].pCurrent)
 39075  
 39076  #if !SQLITE_OS_WINRT
 39077    { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
 39078  #else
 39079    { "HeapCreate",              (SYSCALL)0,                       0 },
 39080  #endif
 39081  
 39082  #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
 39083          SIZE_T))aSyscall[37].pCurrent)
 39084  
 39085  #if !SQLITE_OS_WINRT
 39086    { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
 39087  #else
 39088    { "HeapDestroy",             (SYSCALL)0,                       0 },
 39089  #endif
 39090  
 39091  #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
 39092  
 39093    { "HeapFree",                (SYSCALL)HeapFree,                0 },
 39094  
 39095  #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
 39096  
 39097    { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
 39098  
 39099  #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
 39100          SIZE_T))aSyscall[40].pCurrent)
 39101  
 39102    { "HeapSize",                (SYSCALL)HeapSize,                0 },
 39103  
 39104  #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
 39105          LPCVOID))aSyscall[41].pCurrent)
 39106  
 39107  #if !SQLITE_OS_WINRT
 39108    { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
 39109  #else
 39110    { "HeapValidate",            (SYSCALL)0,                       0 },
 39111  #endif
 39112  
 39113  #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
 39114          LPCVOID))aSyscall[42].pCurrent)
 39115  
 39116  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
 39117    { "HeapCompact",             (SYSCALL)HeapCompact,             0 },
 39118  #else
 39119    { "HeapCompact",             (SYSCALL)0,                       0 },
 39120  #endif
 39121  
 39122  #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
 39123  
 39124  #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
 39125    { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
 39126  #else
 39127    { "LoadLibraryA",            (SYSCALL)0,                       0 },
 39128  #endif
 39129  
 39130  #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
 39131  
 39132  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
 39133          !defined(SQLITE_OMIT_LOAD_EXTENSION)
 39134    { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
 39135  #else
 39136    { "LoadLibraryW",            (SYSCALL)0,                       0 },
 39137  #endif
 39138  
 39139  #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
 39140  
 39141  #if !SQLITE_OS_WINRT
 39142    { "LocalFree",               (SYSCALL)LocalFree,               0 },
 39143  #else
 39144    { "LocalFree",               (SYSCALL)0,                       0 },
 39145  #endif
 39146  
 39147  #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
 39148  
 39149  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
 39150    { "LockFile",                (SYSCALL)LockFile,                0 },
 39151  #else
 39152    { "LockFile",                (SYSCALL)0,                       0 },
 39153  #endif
 39154  
 39155  #ifndef osLockFile
 39156  #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
 39157          DWORD))aSyscall[47].pCurrent)
 39158  #endif
 39159  
 39160  #if !SQLITE_OS_WINCE
 39161    { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
 39162  #else
 39163    { "LockFileEx",              (SYSCALL)0,                       0 },
 39164  #endif
 39165  
 39166  #ifndef osLockFileEx
 39167  #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
 39168          LPOVERLAPPED))aSyscall[48].pCurrent)
 39169  #endif
 39170  
 39171  #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
 39172          (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
 39173    { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
 39174  #else
 39175    { "MapViewOfFile",           (SYSCALL)0,                       0 },
 39176  #endif
 39177  
 39178  #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
 39179          SIZE_T))aSyscall[49].pCurrent)
 39180  
 39181    { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
 39182  
 39183  #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
 39184          int))aSyscall[50].pCurrent)
 39185  
 39186    { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
 39187  
 39188  #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
 39189          LARGE_INTEGER*))aSyscall[51].pCurrent)
 39190  
 39191    { "ReadFile",                (SYSCALL)ReadFile,                0 },
 39192  
 39193  #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
 39194          LPOVERLAPPED))aSyscall[52].pCurrent)
 39195  
 39196    { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
 39197  
 39198  #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
 39199  
 39200  #if !SQLITE_OS_WINRT
 39201    { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
 39202  #else
 39203    { "SetFilePointer",          (SYSCALL)0,                       0 },
 39204  #endif
 39205  
 39206  #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
 39207          DWORD))aSyscall[54].pCurrent)
 39208  
 39209  #if !SQLITE_OS_WINRT
 39210    { "Sleep",                   (SYSCALL)Sleep,                   0 },
 39211  #else
 39212    { "Sleep",                   (SYSCALL)0,                       0 },
 39213  #endif
 39214  
 39215  #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
 39216  
 39217    { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
 39218  
 39219  #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
 39220          LPFILETIME))aSyscall[56].pCurrent)
 39221  
 39222  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
 39223    { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
 39224  #else
 39225    { "UnlockFile",              (SYSCALL)0,                       0 },
 39226  #endif
 39227  
 39228  #ifndef osUnlockFile
 39229  #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
 39230          DWORD))aSyscall[57].pCurrent)
 39231  #endif
 39232  
 39233  #if !SQLITE_OS_WINCE
 39234    { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
 39235  #else
 39236    { "UnlockFileEx",            (SYSCALL)0,                       0 },
 39237  #endif
 39238  
 39239  #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
 39240          LPOVERLAPPED))aSyscall[58].pCurrent)
 39241  
 39242  #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
 39243    { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
 39244  #else
 39245    { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
 39246  #endif
 39247  
 39248  #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
 39249  
 39250    { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
 39251  
 39252  #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
 39253          LPCSTR,LPBOOL))aSyscall[60].pCurrent)
 39254  
 39255    { "WriteFile",               (SYSCALL)WriteFile,               0 },
 39256  
 39257  #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
 39258          LPOVERLAPPED))aSyscall[61].pCurrent)
 39259  
 39260  #if SQLITE_OS_WINRT
 39261    { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
 39262  #else
 39263    { "CreateEventExW",          (SYSCALL)0,                       0 },
 39264  #endif
 39265  
 39266  #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
 39267          DWORD,DWORD))aSyscall[62].pCurrent)
 39268  
 39269  #if !SQLITE_OS_WINRT
 39270    { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
 39271  #else
 39272    { "WaitForSingleObject",     (SYSCALL)0,                       0 },
 39273  #endif
 39274  
 39275  #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
 39276          DWORD))aSyscall[63].pCurrent)
 39277  
 39278  #if !SQLITE_OS_WINCE
 39279    { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
 39280  #else
 39281    { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
 39282  #endif
 39283  
 39284  #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
 39285          BOOL))aSyscall[64].pCurrent)
 39286  
 39287  #if SQLITE_OS_WINRT
 39288    { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
 39289  #else
 39290    { "SetFilePointerEx",        (SYSCALL)0,                       0 },
 39291  #endif
 39292  
 39293  #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
 39294          PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
 39295  
 39296  #if SQLITE_OS_WINRT
 39297    { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
 39298  #else
 39299    { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
 39300  #endif
 39301  
 39302  #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
 39303          FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
 39304  
 39305  #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
 39306    { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
 39307  #else
 39308    { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
 39309  #endif
 39310  
 39311  #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
 39312          SIZE_T))aSyscall[67].pCurrent)
 39313  
 39314  #if SQLITE_OS_WINRT
 39315    { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
 39316  #else
 39317    { "CreateFile2",             (SYSCALL)0,                       0 },
 39318  #endif
 39319  
 39320  #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
 39321          LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
 39322  
 39323  #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
 39324    { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
 39325  #else
 39326    { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
 39327  #endif
 39328  
 39329  #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
 39330          DWORD))aSyscall[69].pCurrent)
 39331  
 39332  #if SQLITE_OS_WINRT
 39333    { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
 39334  #else
 39335    { "GetTickCount64",          (SYSCALL)0,                       0 },
 39336  #endif
 39337  
 39338  #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
 39339  
 39340  #if SQLITE_OS_WINRT
 39341    { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
 39342  #else
 39343    { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
 39344  #endif
 39345  
 39346  #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
 39347          LPSYSTEM_INFO))aSyscall[71].pCurrent)
 39348  
 39349  #if defined(SQLITE_WIN32_HAS_ANSI)
 39350    { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
 39351  #else
 39352    { "OutputDebugStringA",      (SYSCALL)0,                       0 },
 39353  #endif
 39354  
 39355  #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
 39356  
 39357  #if defined(SQLITE_WIN32_HAS_WIDE)
 39358    { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
 39359  #else
 39360    { "OutputDebugStringW",      (SYSCALL)0,                       0 },
 39361  #endif
 39362  
 39363  #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
 39364  
 39365    { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
 39366  
 39367  #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
 39368  
 39369  #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
 39370    { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
 39371  #else
 39372    { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
 39373  #endif
 39374  
 39375  #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
 39376          LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
 39377  
 39378  /*
 39379  ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
 39380  **       is really just a macro that uses a compiler intrinsic (e.g. x64).
 39381  **       So do not try to make this is into a redefinable interface.
 39382  */
 39383  #if defined(InterlockedCompareExchange)
 39384    { "InterlockedCompareExchange", (SYSCALL)0,                    0 },
 39385  
 39386  #define osInterlockedCompareExchange InterlockedCompareExchange
 39387  #else
 39388    { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
 39389  
 39390  #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
 39391          SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
 39392  #endif /* defined(InterlockedCompareExchange) */
 39393  
 39394  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
 39395    { "UuidCreate",               (SYSCALL)UuidCreate,             0 },
 39396  #else
 39397    { "UuidCreate",               (SYSCALL)0,                      0 },
 39398  #endif
 39399  
 39400  #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
 39401  
 39402  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
 39403    { "UuidCreateSequential",     (SYSCALL)UuidCreateSequential,   0 },
 39404  #else
 39405    { "UuidCreateSequential",     (SYSCALL)0,                      0 },
 39406  #endif
 39407  
 39408  #define osUuidCreateSequential \
 39409          ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
 39410  
 39411  #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
 39412    { "FlushViewOfFile",          (SYSCALL)FlushViewOfFile,        0 },
 39413  #else
 39414    { "FlushViewOfFile",          (SYSCALL)0,                      0 },
 39415  #endif
 39416  
 39417  #define osFlushViewOfFile \
 39418          ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
 39419  
 39420  }; /* End of the overrideable system calls */
 39421  
 39422  /*
 39423  ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
 39424  ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
 39425  ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
 39426  ** system call named zName.
 39427  */
 39428  static int winSetSystemCall(
 39429    sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
 39430    const char *zName,            /* Name of system call to override */
 39431    sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
 39432  ){
 39433    unsigned int i;
 39434    int rc = SQLITE_NOTFOUND;
 39435  
 39436    UNUSED_PARAMETER(pNotUsed);
 39437    if( zName==0 ){
 39438      /* If no zName is given, restore all system calls to their default
 39439      ** settings and return NULL
 39440      */
 39441      rc = SQLITE_OK;
 39442      for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
 39443        if( aSyscall[i].pDefault ){
 39444          aSyscall[i].pCurrent = aSyscall[i].pDefault;
 39445        }
 39446      }
 39447    }else{
 39448      /* If zName is specified, operate on only the one system call
 39449      ** specified.
 39450      */
 39451      for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
 39452        if( strcmp(zName, aSyscall[i].zName)==0 ){
 39453          if( aSyscall[i].pDefault==0 ){
 39454            aSyscall[i].pDefault = aSyscall[i].pCurrent;
 39455          }
 39456          rc = SQLITE_OK;
 39457          if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
 39458          aSyscall[i].pCurrent = pNewFunc;
 39459          break;
 39460        }
 39461      }
 39462    }
 39463    return rc;
 39464  }
 39465  
 39466  /*
 39467  ** Return the value of a system call.  Return NULL if zName is not a
 39468  ** recognized system call name.  NULL is also returned if the system call
 39469  ** is currently undefined.
 39470  */
 39471  static sqlite3_syscall_ptr winGetSystemCall(
 39472    sqlite3_vfs *pNotUsed,
 39473    const char *zName
 39474  ){
 39475    unsigned int i;
 39476  
 39477    UNUSED_PARAMETER(pNotUsed);
 39478    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
 39479      if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
 39480    }
 39481    return 0;
 39482  }
 39483  
 39484  /*
 39485  ** Return the name of the first system call after zName.  If zName==NULL
 39486  ** then return the name of the first system call.  Return NULL if zName
 39487  ** is the last system call or if zName is not the name of a valid
 39488  ** system call.
 39489  */
 39490  static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
 39491    int i = -1;
 39492  
 39493    UNUSED_PARAMETER(p);
 39494    if( zName ){
 39495      for(i=0; i<ArraySize(aSyscall)-1; i++){
 39496        if( strcmp(zName, aSyscall[i].zName)==0 ) break;
 39497      }
 39498    }
 39499    for(i++; i<ArraySize(aSyscall); i++){
 39500      if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
 39501    }
 39502    return 0;
 39503  }
 39504  
 39505  #ifdef SQLITE_WIN32_MALLOC
 39506  /*
 39507  ** If a Win32 native heap has been configured, this function will attempt to
 39508  ** compact it.  Upon success, SQLITE_OK will be returned.  Upon failure, one
 39509  ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned.  The
 39510  ** "pnLargest" argument, if non-zero, will be used to return the size of the
 39511  ** largest committed free block in the heap, in bytes.
 39512  */
 39513  SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
 39514    int rc = SQLITE_OK;
 39515    UINT nLargest = 0;
 39516    HANDLE hHeap;
 39517  
 39518    winMemAssertMagic();
 39519    hHeap = winMemGetHeap();
 39520    assert( hHeap!=0 );
 39521    assert( hHeap!=INVALID_HANDLE_VALUE );
 39522  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
 39523    assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
 39524  #endif
 39525  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
 39526    if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
 39527      DWORD lastErrno = osGetLastError();
 39528      if( lastErrno==NO_ERROR ){
 39529        sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
 39530                    (void*)hHeap);
 39531        rc = SQLITE_NOMEM_BKPT;
 39532      }else{
 39533        sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
 39534                    osGetLastError(), (void*)hHeap);
 39535        rc = SQLITE_ERROR;
 39536      }
 39537    }
 39538  #else
 39539    sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
 39540                (void*)hHeap);
 39541    rc = SQLITE_NOTFOUND;
 39542  #endif
 39543    if( pnLargest ) *pnLargest = nLargest;
 39544    return rc;
 39545  }
 39546  
 39547  /*
 39548  ** If a Win32 native heap has been configured, this function will attempt to
 39549  ** destroy and recreate it.  If the Win32 native heap is not isolated and/or
 39550  ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
 39551  ** be returned and no changes will be made to the Win32 native heap.
 39552  */
 39553  SQLITE_API int sqlite3_win32_reset_heap(){
 39554    int rc;
 39555    MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
 39556    MUTEX_LOGIC( sqlite3_mutex *pMem; )    /* The memsys static mutex */
 39557    MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
 39558    MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
 39559    sqlite3_mutex_enter(pMaster);
 39560    sqlite3_mutex_enter(pMem);
 39561    winMemAssertMagic();
 39562    if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
 39563      /*
 39564      ** At this point, there should be no outstanding memory allocations on
 39565      ** the heap.  Also, since both the master and memsys locks are currently
 39566      ** being held by us, no other function (i.e. from another thread) should
 39567      ** be able to even access the heap.  Attempt to destroy and recreate our
 39568      ** isolated Win32 native heap now.
 39569      */
 39570      assert( winMemGetHeap()!=NULL );
 39571      assert( winMemGetOwned() );
 39572      assert( sqlite3_memory_used()==0 );
 39573      winMemShutdown(winMemGetDataPtr());
 39574      assert( winMemGetHeap()==NULL );
 39575      assert( !winMemGetOwned() );
 39576      assert( sqlite3_memory_used()==0 );
 39577      rc = winMemInit(winMemGetDataPtr());
 39578      assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
 39579      assert( rc!=SQLITE_OK || winMemGetOwned() );
 39580      assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
 39581    }else{
 39582      /*
 39583      ** The Win32 native heap cannot be modified because it may be in use.
 39584      */
 39585      rc = SQLITE_BUSY;
 39586    }
 39587    sqlite3_mutex_leave(pMem);
 39588    sqlite3_mutex_leave(pMaster);
 39589    return rc;
 39590  }
 39591  #endif /* SQLITE_WIN32_MALLOC */
 39592  
 39593  /*
 39594  ** This function outputs the specified (ANSI) string to the Win32 debugger
 39595  ** (if available).
 39596  */
 39597  
 39598  SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
 39599    char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
 39600    int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
 39601    if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
 39602    assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
 39603  #ifdef SQLITE_ENABLE_API_ARMOR
 39604    if( !zBuf ){
 39605      (void)SQLITE_MISUSE_BKPT;
 39606      return;
 39607    }
 39608  #endif
 39609  #if defined(SQLITE_WIN32_HAS_ANSI)
 39610    if( nMin>0 ){
 39611      memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
 39612      memcpy(zDbgBuf, zBuf, nMin);
 39613      osOutputDebugStringA(zDbgBuf);
 39614    }else{
 39615      osOutputDebugStringA(zBuf);
 39616    }
 39617  #elif defined(SQLITE_WIN32_HAS_WIDE)
 39618    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
 39619    if ( osMultiByteToWideChar(
 39620            osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
 39621            nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
 39622      return;
 39623    }
 39624    osOutputDebugStringW((LPCWSTR)zDbgBuf);
 39625  #else
 39626    if( nMin>0 ){
 39627      memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
 39628      memcpy(zDbgBuf, zBuf, nMin);
 39629      fprintf(stderr, "%s", zDbgBuf);
 39630    }else{
 39631      fprintf(stderr, "%s", zBuf);
 39632    }
 39633  #endif
 39634  }
 39635  
 39636  /*
 39637  ** The following routine suspends the current thread for at least ms
 39638  ** milliseconds.  This is equivalent to the Win32 Sleep() interface.
 39639  */
 39640  #if SQLITE_OS_WINRT
 39641  static HANDLE sleepObj = NULL;
 39642  #endif
 39643  
 39644  SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
 39645  #if SQLITE_OS_WINRT
 39646    if ( sleepObj==NULL ){
 39647      sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
 39648                                  SYNCHRONIZE);
 39649    }
 39650    assert( sleepObj!=NULL );
 39651    osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
 39652  #else
 39653    osSleep(milliseconds);
 39654  #endif
 39655  }
 39656  
 39657  #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
 39658          SQLITE_THREADSAFE>0
 39659  SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
 39660    DWORD rc;
 39661    while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
 39662                                         TRUE))==WAIT_IO_COMPLETION ){}
 39663    return rc;
 39664  }
 39665  #endif
 39666  
 39667  /*
 39668  ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
 39669  ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
 39670  **
 39671  ** Here is an interesting observation:  Win95, Win98, and WinME lack
 39672  ** the LockFileEx() API.  But we can still statically link against that
 39673  ** API as long as we don't call it when running Win95/98/ME.  A call to
 39674  ** this routine is used to determine if the host is Win95/98/ME or
 39675  ** WinNT/2K/XP so that we will know whether or not we can safely call
 39676  ** the LockFileEx() API.
 39677  */
 39678  
 39679  #if !SQLITE_WIN32_GETVERSIONEX
 39680  # define osIsNT()  (1)
 39681  #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
 39682  # define osIsNT()  (1)
 39683  #elif !defined(SQLITE_WIN32_HAS_WIDE)
 39684  # define osIsNT()  (0)
 39685  #else
 39686  # define osIsNT()  ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
 39687  #endif
 39688  
 39689  /*
 39690  ** This function determines if the machine is running a version of Windows
 39691  ** based on the NT kernel.
 39692  */
 39693  SQLITE_API int sqlite3_win32_is_nt(void){
 39694  #if SQLITE_OS_WINRT
 39695    /*
 39696    ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
 39697    **       kernel.
 39698    */
 39699    return 1;
 39700  #elif SQLITE_WIN32_GETVERSIONEX
 39701    if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
 39702  #if defined(SQLITE_WIN32_HAS_ANSI)
 39703      OSVERSIONINFOA sInfo;
 39704      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
 39705      osGetVersionExA(&sInfo);
 39706      osInterlockedCompareExchange(&sqlite3_os_type,
 39707          (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
 39708  #elif defined(SQLITE_WIN32_HAS_WIDE)
 39709      OSVERSIONINFOW sInfo;
 39710      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
 39711      osGetVersionExW(&sInfo);
 39712      osInterlockedCompareExchange(&sqlite3_os_type,
 39713          (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
 39714  #endif
 39715    }
 39716    return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
 39717  #elif SQLITE_TEST
 39718    return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
 39719  #else
 39720    /*
 39721    ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
 39722    **       deprecated are always assumed to be based on the NT kernel.
 39723    */
 39724    return 1;
 39725  #endif
 39726  }
 39727  
 39728  #ifdef SQLITE_WIN32_MALLOC
 39729  /*
 39730  ** Allocate nBytes of memory.
 39731  */
 39732  static void *winMemMalloc(int nBytes){
 39733    HANDLE hHeap;
 39734    void *p;
 39735  
 39736    winMemAssertMagic();
 39737    hHeap = winMemGetHeap();
 39738    assert( hHeap!=0 );
 39739    assert( hHeap!=INVALID_HANDLE_VALUE );
 39740  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
 39741    assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
 39742  #endif
 39743    assert( nBytes>=0 );
 39744    p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
 39745    if( !p ){
 39746      sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
 39747                  nBytes, osGetLastError(), (void*)hHeap);
 39748    }
 39749    return p;
 39750  }
 39751  
 39752  /*
 39753  ** Free memory.
 39754  */
 39755  static void winMemFree(void *pPrior){
 39756    HANDLE hHeap;
 39757  
 39758    winMemAssertMagic();
 39759    hHeap = winMemGetHeap();
 39760    assert( hHeap!=0 );
 39761    assert( hHeap!=INVALID_HANDLE_VALUE );
 39762  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
 39763    assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
 39764  #endif
 39765    if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
 39766    if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
 39767      sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
 39768                  pPrior, osGetLastError(), (void*)hHeap);
 39769    }
 39770  }
 39771  
 39772  /*
 39773  ** Change the size of an existing memory allocation
 39774  */
 39775  static void *winMemRealloc(void *pPrior, int nBytes){
 39776    HANDLE hHeap;
 39777    void *p;
 39778  
 39779    winMemAssertMagic();
 39780    hHeap = winMemGetHeap();
 39781    assert( hHeap!=0 );
 39782    assert( hHeap!=INVALID_HANDLE_VALUE );
 39783  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
 39784    assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
 39785  #endif
 39786    assert( nBytes>=0 );
 39787    if( !pPrior ){
 39788      p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
 39789    }else{
 39790      p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
 39791    }
 39792    if( !p ){
 39793      sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
 39794                  pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
 39795                  (void*)hHeap);
 39796    }
 39797    return p;
 39798  }
 39799  
 39800  /*
 39801  ** Return the size of an outstanding allocation, in bytes.
 39802  */
 39803  static int winMemSize(void *p){
 39804    HANDLE hHeap;
 39805    SIZE_T n;
 39806  
 39807    winMemAssertMagic();
 39808    hHeap = winMemGetHeap();
 39809    assert( hHeap!=0 );
 39810    assert( hHeap!=INVALID_HANDLE_VALUE );
 39811  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
 39812    assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
 39813  #endif
 39814    if( !p ) return 0;
 39815    n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
 39816    if( n==(SIZE_T)-1 ){
 39817      sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
 39818                  p, osGetLastError(), (void*)hHeap);
 39819      return 0;
 39820    }
 39821    return (int)n;
 39822  }
 39823  
 39824  /*
 39825  ** Round up a request size to the next valid allocation size.
 39826  */
 39827  static int winMemRoundup(int n){
 39828    return n;
 39829  }
 39830  
 39831  /*
 39832  ** Initialize this module.
 39833  */
 39834  static int winMemInit(void *pAppData){
 39835    winMemData *pWinMemData = (winMemData *)pAppData;
 39836  
 39837    if( !pWinMemData ) return SQLITE_ERROR;
 39838    assert( pWinMemData->magic1==WINMEM_MAGIC1 );
 39839    assert( pWinMemData->magic2==WINMEM_MAGIC2 );
 39840  
 39841  #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
 39842    if( !pWinMemData->hHeap ){
 39843      DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
 39844      DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
 39845      if( dwMaximumSize==0 ){
 39846        dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
 39847      }else if( dwInitialSize>dwMaximumSize ){
 39848        dwInitialSize = dwMaximumSize;
 39849      }
 39850      pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
 39851                                        dwInitialSize, dwMaximumSize);
 39852      if( !pWinMemData->hHeap ){
 39853        sqlite3_log(SQLITE_NOMEM,
 39854            "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
 39855            osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
 39856            dwMaximumSize);
 39857        return SQLITE_NOMEM_BKPT;
 39858      }
 39859      pWinMemData->bOwned = TRUE;
 39860      assert( pWinMemData->bOwned );
 39861    }
 39862  #else
 39863    pWinMemData->hHeap = osGetProcessHeap();
 39864    if( !pWinMemData->hHeap ){
 39865      sqlite3_log(SQLITE_NOMEM,
 39866          "failed to GetProcessHeap (%lu)", osGetLastError());
 39867      return SQLITE_NOMEM_BKPT;
 39868    }
 39869    pWinMemData->bOwned = FALSE;
 39870    assert( !pWinMemData->bOwned );
 39871  #endif
 39872    assert( pWinMemData->hHeap!=0 );
 39873    assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
 39874  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
 39875    assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
 39876  #endif
 39877    return SQLITE_OK;
 39878  }
 39879  
 39880  /*
 39881  ** Deinitialize this module.
 39882  */
 39883  static void winMemShutdown(void *pAppData){
 39884    winMemData *pWinMemData = (winMemData *)pAppData;
 39885  
 39886    if( !pWinMemData ) return;
 39887    assert( pWinMemData->magic1==WINMEM_MAGIC1 );
 39888    assert( pWinMemData->magic2==WINMEM_MAGIC2 );
 39889  
 39890    if( pWinMemData->hHeap ){
 39891      assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
 39892  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
 39893      assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
 39894  #endif
 39895      if( pWinMemData->bOwned ){
 39896        if( !osHeapDestroy(pWinMemData->hHeap) ){
 39897          sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
 39898                      osGetLastError(), (void*)pWinMemData->hHeap);
 39899        }
 39900        pWinMemData->bOwned = FALSE;
 39901      }
 39902      pWinMemData->hHeap = NULL;
 39903    }
 39904  }
 39905  
 39906  /*
 39907  ** Populate the low-level memory allocation function pointers in
 39908  ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
 39909  ** arguments specify the block of memory to manage.
 39910  **
 39911  ** This routine is only called by sqlite3_config(), and therefore
 39912  ** is not required to be threadsafe (it is not).
 39913  */
 39914  SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
 39915    static const sqlite3_mem_methods winMemMethods = {
 39916      winMemMalloc,
 39917      winMemFree,
 39918      winMemRealloc,
 39919      winMemSize,
 39920      winMemRoundup,
 39921      winMemInit,
 39922      winMemShutdown,
 39923      &win_mem_data
 39924    };
 39925    return &winMemMethods;
 39926  }
 39927  
 39928  SQLITE_PRIVATE void sqlite3MemSetDefault(void){
 39929    sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
 39930  }
 39931  #endif /* SQLITE_WIN32_MALLOC */
 39932  
 39933  /*
 39934  ** Convert a UTF-8 string to Microsoft Unicode.
 39935  **
 39936  ** Space to hold the returned string is obtained from sqlite3_malloc().
 39937  */
 39938  static LPWSTR winUtf8ToUnicode(const char *zText){
 39939    int nChar;
 39940    LPWSTR zWideText;
 39941  
 39942    nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
 39943    if( nChar==0 ){
 39944      return 0;
 39945    }
 39946    zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
 39947    if( zWideText==0 ){
 39948      return 0;
 39949    }
 39950    nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
 39951                                  nChar);
 39952    if( nChar==0 ){
 39953      sqlite3_free(zWideText);
 39954      zWideText = 0;
 39955    }
 39956    return zWideText;
 39957  }
 39958  
 39959  /*
 39960  ** Convert a Microsoft Unicode string to UTF-8.
 39961  **
 39962  ** Space to hold the returned string is obtained from sqlite3_malloc().
 39963  */
 39964  static char *winUnicodeToUtf8(LPCWSTR zWideText){
 39965    int nByte;
 39966    char *zText;
 39967  
 39968    nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
 39969    if( nByte == 0 ){
 39970      return 0;
 39971    }
 39972    zText = sqlite3MallocZero( nByte );
 39973    if( zText==0 ){
 39974      return 0;
 39975    }
 39976    nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
 39977                                  0, 0);
 39978    if( nByte == 0 ){
 39979      sqlite3_free(zText);
 39980      zText = 0;
 39981    }
 39982    return zText;
 39983  }
 39984  
 39985  /*
 39986  ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
 39987  ** code page.
 39988  **
 39989  ** Space to hold the returned string is obtained from sqlite3_malloc().
 39990  */
 39991  static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
 39992    int nByte;
 39993    LPWSTR zMbcsText;
 39994    int codepage = useAnsi ? CP_ACP : CP_OEMCP;
 39995  
 39996    nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
 39997                                  0)*sizeof(WCHAR);
 39998    if( nByte==0 ){
 39999      return 0;
 40000    }
 40001    zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
 40002    if( zMbcsText==0 ){
 40003      return 0;
 40004    }
 40005    nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
 40006                                  nByte);
 40007    if( nByte==0 ){
 40008      sqlite3_free(zMbcsText);
 40009      zMbcsText = 0;
 40010    }
 40011    return zMbcsText;
 40012  }
 40013  
 40014  /*
 40015  ** Convert a Microsoft Unicode string to a multi-byte character string,
 40016  ** using the ANSI or OEM code page.
 40017  **
 40018  ** Space to hold the returned string is obtained from sqlite3_malloc().
 40019  */
 40020  static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
 40021    int nByte;
 40022    char *zText;
 40023    int codepage = useAnsi ? CP_ACP : CP_OEMCP;
 40024  
 40025    nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
 40026    if( nByte == 0 ){
 40027      return 0;
 40028    }
 40029    zText = sqlite3MallocZero( nByte );
 40030    if( zText==0 ){
 40031      return 0;
 40032    }
 40033    nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
 40034                                  nByte, 0, 0);
 40035    if( nByte == 0 ){
 40036      sqlite3_free(zText);
 40037      zText = 0;
 40038    }
 40039    return zText;
 40040  }
 40041  
 40042  /*
 40043  ** Convert a multi-byte character string to UTF-8.
 40044  **
 40045  ** Space to hold the returned string is obtained from sqlite3_malloc().
 40046  */
 40047  static char *winMbcsToUtf8(const char *zText, int useAnsi){
 40048    char *zTextUtf8;
 40049    LPWSTR zTmpWide;
 40050  
 40051    zTmpWide = winMbcsToUnicode(zText, useAnsi);
 40052    if( zTmpWide==0 ){
 40053      return 0;
 40054    }
 40055    zTextUtf8 = winUnicodeToUtf8(zTmpWide);
 40056    sqlite3_free(zTmpWide);
 40057    return zTextUtf8;
 40058  }
 40059  
 40060  /*
 40061  ** Convert a UTF-8 string to a multi-byte character string.
 40062  **
 40063  ** Space to hold the returned string is obtained from sqlite3_malloc().
 40064  */
 40065  static char *winUtf8ToMbcs(const char *zText, int useAnsi){
 40066    char *zTextMbcs;
 40067    LPWSTR zTmpWide;
 40068  
 40069    zTmpWide = winUtf8ToUnicode(zText);
 40070    if( zTmpWide==0 ){
 40071      return 0;
 40072    }
 40073    zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
 40074    sqlite3_free(zTmpWide);
 40075    return zTextMbcs;
 40076  }
 40077  
 40078  /*
 40079  ** This is a public wrapper for the winUtf8ToUnicode() function.
 40080  */
 40081  SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
 40082  #ifdef SQLITE_ENABLE_API_ARMOR
 40083    if( !zText ){
 40084      (void)SQLITE_MISUSE_BKPT;
 40085      return 0;
 40086    }
 40087  #endif
 40088  #ifndef SQLITE_OMIT_AUTOINIT
 40089    if( sqlite3_initialize() ) return 0;
 40090  #endif
 40091    return winUtf8ToUnicode(zText);
 40092  }
 40093  
 40094  /*
 40095  ** This is a public wrapper for the winUnicodeToUtf8() function.
 40096  */
 40097  SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
 40098  #ifdef SQLITE_ENABLE_API_ARMOR
 40099    if( !zWideText ){
 40100      (void)SQLITE_MISUSE_BKPT;
 40101      return 0;
 40102    }
 40103  #endif
 40104  #ifndef SQLITE_OMIT_AUTOINIT
 40105    if( sqlite3_initialize() ) return 0;
 40106  #endif
 40107    return winUnicodeToUtf8(zWideText);
 40108  }
 40109  
 40110  /*
 40111  ** This is a public wrapper for the winMbcsToUtf8() function.
 40112  */
 40113  SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){
 40114  #ifdef SQLITE_ENABLE_API_ARMOR
 40115    if( !zText ){
 40116      (void)SQLITE_MISUSE_BKPT;
 40117      return 0;
 40118    }
 40119  #endif
 40120  #ifndef SQLITE_OMIT_AUTOINIT
 40121    if( sqlite3_initialize() ) return 0;
 40122  #endif
 40123    return winMbcsToUtf8(zText, osAreFileApisANSI());
 40124  }
 40125  
 40126  /*
 40127  ** This is a public wrapper for the winMbcsToUtf8() function.
 40128  */
 40129  SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
 40130  #ifdef SQLITE_ENABLE_API_ARMOR
 40131    if( !zText ){
 40132      (void)SQLITE_MISUSE_BKPT;
 40133      return 0;
 40134    }
 40135  #endif
 40136  #ifndef SQLITE_OMIT_AUTOINIT
 40137    if( sqlite3_initialize() ) return 0;
 40138  #endif
 40139    return winMbcsToUtf8(zText, useAnsi);
 40140  }
 40141  
 40142  /*
 40143  ** This is a public wrapper for the winUtf8ToMbcs() function.
 40144  */
 40145  SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){
 40146  #ifdef SQLITE_ENABLE_API_ARMOR
 40147    if( !zText ){
 40148      (void)SQLITE_MISUSE_BKPT;
 40149      return 0;
 40150    }
 40151  #endif
 40152  #ifndef SQLITE_OMIT_AUTOINIT
 40153    if( sqlite3_initialize() ) return 0;
 40154  #endif
 40155    return winUtf8ToMbcs(zText, osAreFileApisANSI());
 40156  }
 40157  
 40158  /*
 40159  ** This is a public wrapper for the winUtf8ToMbcs() function.
 40160  */
 40161  SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
 40162  #ifdef SQLITE_ENABLE_API_ARMOR
 40163    if( !zText ){
 40164      (void)SQLITE_MISUSE_BKPT;
 40165      return 0;
 40166    }
 40167  #endif
 40168  #ifndef SQLITE_OMIT_AUTOINIT
 40169    if( sqlite3_initialize() ) return 0;
 40170  #endif
 40171    return winUtf8ToMbcs(zText, useAnsi);
 40172  }
 40173  
 40174  /*
 40175  ** This function sets the data directory or the temporary directory based on
 40176  ** the provided arguments.  The type argument must be 1 in order to set the
 40177  ** data directory or 2 in order to set the temporary directory.  The zValue
 40178  ** argument is the name of the directory to use.  The return value will be
 40179  ** SQLITE_OK if successful.
 40180  */
 40181  SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
 40182    char **ppDirectory = 0;
 40183  #ifndef SQLITE_OMIT_AUTOINIT
 40184    int rc = sqlite3_initialize();
 40185    if( rc ) return rc;
 40186  #endif
 40187    if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
 40188      ppDirectory = &sqlite3_data_directory;
 40189    }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
 40190      ppDirectory = &sqlite3_temp_directory;
 40191    }
 40192    assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
 40193            || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
 40194    );
 40195    assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
 40196    if( ppDirectory ){
 40197      char *zValueUtf8 = 0;
 40198      if( zValue && zValue[0] ){
 40199        zValueUtf8 = winUnicodeToUtf8(zValue);
 40200        if ( zValueUtf8==0 ){
 40201          return SQLITE_NOMEM_BKPT;
 40202        }
 40203      }
 40204      sqlite3_free(*ppDirectory);
 40205      *ppDirectory = zValueUtf8;
 40206      return SQLITE_OK;
 40207    }
 40208    return SQLITE_ERROR;
 40209  }
 40210  
 40211  /*
 40212  ** The return value of winGetLastErrorMsg
 40213  ** is zero if the error message fits in the buffer, or non-zero
 40214  ** otherwise (if the message was truncated).
 40215  */
 40216  static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
 40217    /* FormatMessage returns 0 on failure.  Otherwise it
 40218    ** returns the number of TCHARs written to the output
 40219    ** buffer, excluding the terminating null char.
 40220    */
 40221    DWORD dwLen = 0;
 40222    char *zOut = 0;
 40223  
 40224    if( osIsNT() ){
 40225  #if SQLITE_OS_WINRT
 40226      WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
 40227      dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
 40228                               FORMAT_MESSAGE_IGNORE_INSERTS,
 40229                               NULL,
 40230                               lastErrno,
 40231                               0,
 40232                               zTempWide,
 40233                               SQLITE_WIN32_MAX_ERRMSG_CHARS,
 40234                               0);
 40235  #else
 40236      LPWSTR zTempWide = NULL;
 40237      dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
 40238                               FORMAT_MESSAGE_FROM_SYSTEM |
 40239                               FORMAT_MESSAGE_IGNORE_INSERTS,
 40240                               NULL,
 40241                               lastErrno,
 40242                               0,
 40243                               (LPWSTR) &zTempWide,
 40244                               0,
 40245                               0);
 40246  #endif
 40247      if( dwLen > 0 ){
 40248        /* allocate a buffer and convert to UTF8 */
 40249        sqlite3BeginBenignMalloc();
 40250        zOut = winUnicodeToUtf8(zTempWide);
 40251        sqlite3EndBenignMalloc();
 40252  #if !SQLITE_OS_WINRT
 40253        /* free the system buffer allocated by FormatMessage */
 40254        osLocalFree(zTempWide);
 40255  #endif
 40256      }
 40257    }
 40258  #ifdef SQLITE_WIN32_HAS_ANSI
 40259    else{
 40260      char *zTemp = NULL;
 40261      dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
 40262                               FORMAT_MESSAGE_FROM_SYSTEM |
 40263                               FORMAT_MESSAGE_IGNORE_INSERTS,
 40264                               NULL,
 40265                               lastErrno,
 40266                               0,
 40267                               (LPSTR) &zTemp,
 40268                               0,
 40269                               0);
 40270      if( dwLen > 0 ){
 40271        /* allocate a buffer and convert to UTF8 */
 40272        sqlite3BeginBenignMalloc();
 40273        zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
 40274        sqlite3EndBenignMalloc();
 40275        /* free the system buffer allocated by FormatMessage */
 40276        osLocalFree(zTemp);
 40277      }
 40278    }
 40279  #endif
 40280    if( 0 == dwLen ){
 40281      sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
 40282    }else{
 40283      /* copy a maximum of nBuf chars to output buffer */
 40284      sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
 40285      /* free the UTF8 buffer */
 40286      sqlite3_free(zOut);
 40287    }
 40288    return 0;
 40289  }
 40290  
 40291  /*
 40292  **
 40293  ** This function - winLogErrorAtLine() - is only ever called via the macro
 40294  ** winLogError().
 40295  **
 40296  ** This routine is invoked after an error occurs in an OS function.
 40297  ** It logs a message using sqlite3_log() containing the current value of
 40298  ** error code and, if possible, the human-readable equivalent from
 40299  ** FormatMessage.
 40300  **
 40301  ** The first argument passed to the macro should be the error code that
 40302  ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
 40303  ** The two subsequent arguments should be the name of the OS function that
 40304  ** failed and the associated file-system path, if any.
 40305  */
 40306  #define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
 40307  static int winLogErrorAtLine(
 40308    int errcode,                    /* SQLite error code */
 40309    DWORD lastErrno,                /* Win32 last error */
 40310    const char *zFunc,              /* Name of OS function that failed */
 40311    const char *zPath,              /* File path associated with error */
 40312    int iLine                       /* Source line number where error occurred */
 40313  ){
 40314    char zMsg[500];                 /* Human readable error text */
 40315    int i;                          /* Loop counter */
 40316  
 40317    zMsg[0] = 0;
 40318    winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
 40319    assert( errcode!=SQLITE_OK );
 40320    if( zPath==0 ) zPath = "";
 40321    for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
 40322    zMsg[i] = 0;
 40323    sqlite3_log(errcode,
 40324        "os_win.c:%d: (%lu) %s(%s) - %s",
 40325        iLine, lastErrno, zFunc, zPath, zMsg
 40326    );
 40327  
 40328    return errcode;
 40329  }
 40330  
 40331  /*
 40332  ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
 40333  ** will be retried following a locking error - probably caused by
 40334  ** antivirus software.  Also the initial delay before the first retry.
 40335  ** The delay increases linearly with each retry.
 40336  */
 40337  #ifndef SQLITE_WIN32_IOERR_RETRY
 40338  # define SQLITE_WIN32_IOERR_RETRY 10
 40339  #endif
 40340  #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
 40341  # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
 40342  #endif
 40343  static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
 40344  static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
 40345  
 40346  /*
 40347  ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
 40348  ** error code obtained via GetLastError() is eligible to be retried.  It
 40349  ** must accept the error code DWORD as its only argument and should return
 40350  ** non-zero if the error code is transient in nature and the operation
 40351  ** responsible for generating the original error might succeed upon being
 40352  ** retried.  The argument to this macro should be a variable.
 40353  **
 40354  ** Additionally, a macro named "winIoerrCanRetry2" may be defined.  If it
 40355  ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
 40356  ** returns zero.  The "winIoerrCanRetry2" macro is completely optional and
 40357  ** may be used to include additional error codes in the set that should
 40358  ** result in the failing I/O operation being retried by the caller.  If
 40359  ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
 40360  ** identical to those of the "winIoerrCanRetry1" macro.
 40361  */
 40362  #if !defined(winIoerrCanRetry1)
 40363  #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED)        || \
 40364                                ((a)==ERROR_SHARING_VIOLATION)    || \
 40365                                ((a)==ERROR_LOCK_VIOLATION)       || \
 40366                                ((a)==ERROR_DEV_NOT_EXIST)        || \
 40367                                ((a)==ERROR_NETNAME_DELETED)      || \
 40368                                ((a)==ERROR_SEM_TIMEOUT)          || \
 40369                                ((a)==ERROR_NETWORK_UNREACHABLE))
 40370  #endif
 40371  
 40372  /*
 40373  ** If a ReadFile() or WriteFile() error occurs, invoke this routine
 40374  ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
 40375  ** to give up with an error.
 40376  */
 40377  static int winRetryIoerr(int *pnRetry, DWORD *pError){
 40378    DWORD e = osGetLastError();
 40379    if( *pnRetry>=winIoerrRetry ){
 40380      if( pError ){
 40381        *pError = e;
 40382      }
 40383      return 0;
 40384    }
 40385    if( winIoerrCanRetry1(e) ){
 40386      sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
 40387      ++*pnRetry;
 40388      return 1;
 40389    }
 40390  #if defined(winIoerrCanRetry2)
 40391    else if( winIoerrCanRetry2(e) ){
 40392      sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
 40393      ++*pnRetry;
 40394      return 1;
 40395    }
 40396  #endif
 40397    if( pError ){
 40398      *pError = e;
 40399    }
 40400    return 0;
 40401  }
 40402  
 40403  /*
 40404  ** Log a I/O error retry episode.
 40405  */
 40406  static void winLogIoerr(int nRetry, int lineno){
 40407    if( nRetry ){
 40408      sqlite3_log(SQLITE_NOTICE,
 40409        "delayed %dms for lock/sharing conflict at line %d",
 40410        winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
 40411      );
 40412    }
 40413  }
 40414  
 40415  /*
 40416  ** This #if does not rely on the SQLITE_OS_WINCE define because the
 40417  ** corresponding section in "date.c" cannot use it.
 40418  */
 40419  #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
 40420      (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
 40421  /*
 40422  ** The MSVC CRT on Windows CE may not have a localtime() function.
 40423  ** So define a substitute.
 40424  */
 40425  /* #  include <time.h> */
 40426  struct tm *__cdecl localtime(const time_t *t)
 40427  {
 40428    static struct tm y;
 40429    FILETIME uTm, lTm;
 40430    SYSTEMTIME pTm;
 40431    sqlite3_int64 t64;
 40432    t64 = *t;
 40433    t64 = (t64 + 11644473600)*10000000;
 40434    uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
 40435    uTm.dwHighDateTime= (DWORD)(t64 >> 32);
 40436    osFileTimeToLocalFileTime(&uTm,&lTm);
 40437    osFileTimeToSystemTime(&lTm,&pTm);
 40438    y.tm_year = pTm.wYear - 1900;
 40439    y.tm_mon = pTm.wMonth - 1;
 40440    y.tm_wday = pTm.wDayOfWeek;
 40441    y.tm_mday = pTm.wDay;
 40442    y.tm_hour = pTm.wHour;
 40443    y.tm_min = pTm.wMinute;
 40444    y.tm_sec = pTm.wSecond;
 40445    return &y;
 40446  }
 40447  #endif
 40448  
 40449  #if SQLITE_OS_WINCE
 40450  /*************************************************************************
 40451  ** This section contains code for WinCE only.
 40452  */
 40453  #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
 40454  
 40455  /*
 40456  ** Acquire a lock on the handle h
 40457  */
 40458  static void winceMutexAcquire(HANDLE h){
 40459     DWORD dwErr;
 40460     do {
 40461       dwErr = osWaitForSingleObject(h, INFINITE);
 40462     } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
 40463  }
 40464  /*
 40465  ** Release a lock acquired by winceMutexAcquire()
 40466  */
 40467  #define winceMutexRelease(h) ReleaseMutex(h)
 40468  
 40469  /*
 40470  ** Create the mutex and shared memory used for locking in the file
 40471  ** descriptor pFile
 40472  */
 40473  static int winceCreateLock(const char *zFilename, winFile *pFile){
 40474    LPWSTR zTok;
 40475    LPWSTR zName;
 40476    DWORD lastErrno;
 40477    BOOL bLogged = FALSE;
 40478    BOOL bInit = TRUE;
 40479  
 40480    zName = winUtf8ToUnicode(zFilename);
 40481    if( zName==0 ){
 40482      /* out of memory */
 40483      return SQLITE_IOERR_NOMEM_BKPT;
 40484    }
 40485  
 40486    /* Initialize the local lockdata */
 40487    memset(&pFile->local, 0, sizeof(pFile->local));
 40488  
 40489    /* Replace the backslashes from the filename and lowercase it
 40490    ** to derive a mutex name. */
 40491    zTok = osCharLowerW(zName);
 40492    for (;*zTok;zTok++){
 40493      if (*zTok == '\\') *zTok = '_';
 40494    }
 40495  
 40496    /* Create/open the named mutex */
 40497    pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
 40498    if (!pFile->hMutex){
 40499      pFile->lastErrno = osGetLastError();
 40500      sqlite3_free(zName);
 40501      return winLogError(SQLITE_IOERR, pFile->lastErrno,
 40502                         "winceCreateLock1", zFilename);
 40503    }
 40504  
 40505    /* Acquire the mutex before continuing */
 40506    winceMutexAcquire(pFile->hMutex);
 40507  
 40508    /* Since the names of named mutexes, semaphores, file mappings etc are
 40509    ** case-sensitive, take advantage of that by uppercasing the mutex name
 40510    ** and using that as the shared filemapping name.
 40511    */
 40512    osCharUpperW(zName);
 40513    pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
 40514                                          PAGE_READWRITE, 0, sizeof(winceLock),
 40515                                          zName);
 40516  
 40517    /* Set a flag that indicates we're the first to create the memory so it
 40518    ** must be zero-initialized */
 40519    lastErrno = osGetLastError();
 40520    if (lastErrno == ERROR_ALREADY_EXISTS){
 40521      bInit = FALSE;
 40522    }
 40523  
 40524    sqlite3_free(zName);
 40525  
 40526    /* If we succeeded in making the shared memory handle, map it. */
 40527    if( pFile->hShared ){
 40528      pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
 40529               FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
 40530      /* If mapping failed, close the shared memory handle and erase it */
 40531      if( !pFile->shared ){
 40532        pFile->lastErrno = osGetLastError();
 40533        winLogError(SQLITE_IOERR, pFile->lastErrno,
 40534                    "winceCreateLock2", zFilename);
 40535        bLogged = TRUE;
 40536        osCloseHandle(pFile->hShared);
 40537        pFile->hShared = NULL;
 40538      }
 40539    }
 40540  
 40541    /* If shared memory could not be created, then close the mutex and fail */
 40542    if( pFile->hShared==NULL ){
 40543      if( !bLogged ){
 40544        pFile->lastErrno = lastErrno;
 40545        winLogError(SQLITE_IOERR, pFile->lastErrno,
 40546                    "winceCreateLock3", zFilename);
 40547        bLogged = TRUE;
 40548      }
 40549      winceMutexRelease(pFile->hMutex);
 40550      osCloseHandle(pFile->hMutex);
 40551      pFile->hMutex = NULL;
 40552      return SQLITE_IOERR;
 40553    }
 40554  
 40555    /* Initialize the shared memory if we're supposed to */
 40556    if( bInit ){
 40557      memset(pFile->shared, 0, sizeof(winceLock));
 40558    }
 40559  
 40560    winceMutexRelease(pFile->hMutex);
 40561    return SQLITE_OK;
 40562  }
 40563  
 40564  /*
 40565  ** Destroy the part of winFile that deals with wince locks
 40566  */
 40567  static void winceDestroyLock(winFile *pFile){
 40568    if (pFile->hMutex){
 40569      /* Acquire the mutex */
 40570      winceMutexAcquire(pFile->hMutex);
 40571  
 40572      /* The following blocks should probably assert in debug mode, but they
 40573         are to cleanup in case any locks remained open */
 40574      if (pFile->local.nReaders){
 40575        pFile->shared->nReaders --;
 40576      }
 40577      if (pFile->local.bReserved){
 40578        pFile->shared->bReserved = FALSE;
 40579      }
 40580      if (pFile->local.bPending){
 40581        pFile->shared->bPending = FALSE;
 40582      }
 40583      if (pFile->local.bExclusive){
 40584        pFile->shared->bExclusive = FALSE;
 40585      }
 40586  
 40587      /* De-reference and close our copy of the shared memory handle */
 40588      osUnmapViewOfFile(pFile->shared);
 40589      osCloseHandle(pFile->hShared);
 40590  
 40591      /* Done with the mutex */
 40592      winceMutexRelease(pFile->hMutex);
 40593      osCloseHandle(pFile->hMutex);
 40594      pFile->hMutex = NULL;
 40595    }
 40596  }
 40597  
 40598  /*
 40599  ** An implementation of the LockFile() API of Windows for CE
 40600  */
 40601  static BOOL winceLockFile(
 40602    LPHANDLE phFile,
 40603    DWORD dwFileOffsetLow,
 40604    DWORD dwFileOffsetHigh,
 40605    DWORD nNumberOfBytesToLockLow,
 40606    DWORD nNumberOfBytesToLockHigh
 40607  ){
 40608    winFile *pFile = HANDLE_TO_WINFILE(phFile);
 40609    BOOL bReturn = FALSE;
 40610  
 40611    UNUSED_PARAMETER(dwFileOffsetHigh);
 40612    UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
 40613  
 40614    if (!pFile->hMutex) return TRUE;
 40615    winceMutexAcquire(pFile->hMutex);
 40616  
 40617    /* Wanting an exclusive lock? */
 40618    if (dwFileOffsetLow == (DWORD)SHARED_FIRST
 40619         && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
 40620      if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
 40621         pFile->shared->bExclusive = TRUE;
 40622         pFile->local.bExclusive = TRUE;
 40623         bReturn = TRUE;
 40624      }
 40625    }
 40626  
 40627    /* Want a read-only lock? */
 40628    else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
 40629             nNumberOfBytesToLockLow == 1){
 40630      if (pFile->shared->bExclusive == 0){
 40631        pFile->local.nReaders ++;
 40632        if (pFile->local.nReaders == 1){
 40633          pFile->shared->nReaders ++;
 40634        }
 40635        bReturn = TRUE;
 40636      }
 40637    }
 40638  
 40639    /* Want a pending lock? */
 40640    else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
 40641             && nNumberOfBytesToLockLow == 1){
 40642      /* If no pending lock has been acquired, then acquire it */
 40643      if (pFile->shared->bPending == 0) {
 40644        pFile->shared->bPending = TRUE;
 40645        pFile->local.bPending = TRUE;
 40646        bReturn = TRUE;
 40647      }
 40648    }
 40649  
 40650    /* Want a reserved lock? */
 40651    else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
 40652             && nNumberOfBytesToLockLow == 1){
 40653      if (pFile->shared->bReserved == 0) {
 40654        pFile->shared->bReserved = TRUE;
 40655        pFile->local.bReserved = TRUE;
 40656        bReturn = TRUE;
 40657      }
 40658    }
 40659  
 40660    winceMutexRelease(pFile->hMutex);
 40661    return bReturn;
 40662  }
 40663  
 40664  /*
 40665  ** An implementation of the UnlockFile API of Windows for CE
 40666  */
 40667  static BOOL winceUnlockFile(
 40668    LPHANDLE phFile,
 40669    DWORD dwFileOffsetLow,
 40670    DWORD dwFileOffsetHigh,
 40671    DWORD nNumberOfBytesToUnlockLow,
 40672    DWORD nNumberOfBytesToUnlockHigh
 40673  ){
 40674    winFile *pFile = HANDLE_TO_WINFILE(phFile);
 40675    BOOL bReturn = FALSE;
 40676  
 40677    UNUSED_PARAMETER(dwFileOffsetHigh);
 40678    UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
 40679  
 40680    if (!pFile->hMutex) return TRUE;
 40681    winceMutexAcquire(pFile->hMutex);
 40682  
 40683    /* Releasing a reader lock or an exclusive lock */
 40684    if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
 40685      /* Did we have an exclusive lock? */
 40686      if (pFile->local.bExclusive){
 40687        assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
 40688        pFile->local.bExclusive = FALSE;
 40689        pFile->shared->bExclusive = FALSE;
 40690        bReturn = TRUE;
 40691      }
 40692  
 40693      /* Did we just have a reader lock? */
 40694      else if (pFile->local.nReaders){
 40695        assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
 40696               || nNumberOfBytesToUnlockLow == 1);
 40697        pFile->local.nReaders --;
 40698        if (pFile->local.nReaders == 0)
 40699        {
 40700          pFile->shared->nReaders --;
 40701        }
 40702        bReturn = TRUE;
 40703      }
 40704    }
 40705  
 40706    /* Releasing a pending lock */
 40707    else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
 40708             && nNumberOfBytesToUnlockLow == 1){
 40709      if (pFile->local.bPending){
 40710        pFile->local.bPending = FALSE;
 40711        pFile->shared->bPending = FALSE;
 40712        bReturn = TRUE;
 40713      }
 40714    }
 40715    /* Releasing a reserved lock */
 40716    else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
 40717             && nNumberOfBytesToUnlockLow == 1){
 40718      if (pFile->local.bReserved) {
 40719        pFile->local.bReserved = FALSE;
 40720        pFile->shared->bReserved = FALSE;
 40721        bReturn = TRUE;
 40722      }
 40723    }
 40724  
 40725    winceMutexRelease(pFile->hMutex);
 40726    return bReturn;
 40727  }
 40728  /*
 40729  ** End of the special code for wince
 40730  *****************************************************************************/
 40731  #endif /* SQLITE_OS_WINCE */
 40732  
 40733  /*
 40734  ** Lock a file region.
 40735  */
 40736  static BOOL winLockFile(
 40737    LPHANDLE phFile,
 40738    DWORD flags,
 40739    DWORD offsetLow,
 40740    DWORD offsetHigh,
 40741    DWORD numBytesLow,
 40742    DWORD numBytesHigh
 40743  ){
 40744  #if SQLITE_OS_WINCE
 40745    /*
 40746    ** NOTE: Windows CE is handled differently here due its lack of the Win32
 40747    **       API LockFile.
 40748    */
 40749    return winceLockFile(phFile, offsetLow, offsetHigh,
 40750                         numBytesLow, numBytesHigh);
 40751  #else
 40752    if( osIsNT() ){
 40753      OVERLAPPED ovlp;
 40754      memset(&ovlp, 0, sizeof(OVERLAPPED));
 40755      ovlp.Offset = offsetLow;
 40756      ovlp.OffsetHigh = offsetHigh;
 40757      return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
 40758    }else{
 40759      return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
 40760                        numBytesHigh);
 40761    }
 40762  #endif
 40763  }
 40764  
 40765  /*
 40766  ** Unlock a file region.
 40767   */
 40768  static BOOL winUnlockFile(
 40769    LPHANDLE phFile,
 40770    DWORD offsetLow,
 40771    DWORD offsetHigh,
 40772    DWORD numBytesLow,
 40773    DWORD numBytesHigh
 40774  ){
 40775  #if SQLITE_OS_WINCE
 40776    /*
 40777    ** NOTE: Windows CE is handled differently here due its lack of the Win32
 40778    **       API UnlockFile.
 40779    */
 40780    return winceUnlockFile(phFile, offsetLow, offsetHigh,
 40781                           numBytesLow, numBytesHigh);
 40782  #else
 40783    if( osIsNT() ){
 40784      OVERLAPPED ovlp;
 40785      memset(&ovlp, 0, sizeof(OVERLAPPED));
 40786      ovlp.Offset = offsetLow;
 40787      ovlp.OffsetHigh = offsetHigh;
 40788      return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
 40789    }else{
 40790      return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
 40791                          numBytesHigh);
 40792    }
 40793  #endif
 40794  }
 40795  
 40796  /*****************************************************************************
 40797  ** The next group of routines implement the I/O methods specified
 40798  ** by the sqlite3_io_methods object.
 40799  ******************************************************************************/
 40800  
 40801  /*
 40802  ** Some Microsoft compilers lack this definition.
 40803  */
 40804  #ifndef INVALID_SET_FILE_POINTER
 40805  # define INVALID_SET_FILE_POINTER ((DWORD)-1)
 40806  #endif
 40807  
 40808  /*
 40809  ** Move the current position of the file handle passed as the first
 40810  ** argument to offset iOffset within the file. If successful, return 0.
 40811  ** Otherwise, set pFile->lastErrno and return non-zero.
 40812  */
 40813  static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
 40814  #if !SQLITE_OS_WINRT
 40815    LONG upperBits;                 /* Most sig. 32 bits of new offset */
 40816    LONG lowerBits;                 /* Least sig. 32 bits of new offset */
 40817    DWORD dwRet;                    /* Value returned by SetFilePointer() */
 40818    DWORD lastErrno;                /* Value returned by GetLastError() */
 40819  
 40820    OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
 40821  
 40822    upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
 40823    lowerBits = (LONG)(iOffset & 0xffffffff);
 40824  
 40825    /* API oddity: If successful, SetFilePointer() returns a dword
 40826    ** containing the lower 32-bits of the new file-offset. Or, if it fails,
 40827    ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
 40828    ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
 40829    ** whether an error has actually occurred, it is also necessary to call
 40830    ** GetLastError().
 40831    */
 40832    dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
 40833  
 40834    if( (dwRet==INVALID_SET_FILE_POINTER
 40835        && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
 40836      pFile->lastErrno = lastErrno;
 40837      winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
 40838                  "winSeekFile", pFile->zPath);
 40839      OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
 40840      return 1;
 40841    }
 40842  
 40843    OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
 40844    return 0;
 40845  #else
 40846    /*
 40847    ** Same as above, except that this implementation works for WinRT.
 40848    */
 40849  
 40850    LARGE_INTEGER x;                /* The new offset */
 40851    BOOL bRet;                      /* Value returned by SetFilePointerEx() */
 40852  
 40853    x.QuadPart = iOffset;
 40854    bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
 40855  
 40856    if(!bRet){
 40857      pFile->lastErrno = osGetLastError();
 40858      winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
 40859                  "winSeekFile", pFile->zPath);
 40860      OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
 40861      return 1;
 40862    }
 40863  
 40864    OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
 40865    return 0;
 40866  #endif
 40867  }
 40868  
 40869  #if SQLITE_MAX_MMAP_SIZE>0
 40870  /* Forward references to VFS helper methods used for memory mapped files */
 40871  static int winMapfile(winFile*, sqlite3_int64);
 40872  static int winUnmapfile(winFile*);
 40873  #endif
 40874  
 40875  /*
 40876  ** Close a file.
 40877  **
 40878  ** It is reported that an attempt to close a handle might sometimes
 40879  ** fail.  This is a very unreasonable result, but Windows is notorious
 40880  ** for being unreasonable so I do not doubt that it might happen.  If
 40881  ** the close fails, we pause for 100 milliseconds and try again.  As
 40882  ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
 40883  ** giving up and returning an error.
 40884  */
 40885  #define MX_CLOSE_ATTEMPT 3
 40886  static int winClose(sqlite3_file *id){
 40887    int rc, cnt = 0;
 40888    winFile *pFile = (winFile*)id;
 40889  
 40890    assert( id!=0 );
 40891  #ifndef SQLITE_OMIT_WAL
 40892    assert( pFile->pShm==0 );
 40893  #endif
 40894    assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
 40895    OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
 40896             osGetCurrentProcessId(), pFile, pFile->h));
 40897  
 40898  #if SQLITE_MAX_MMAP_SIZE>0
 40899    winUnmapfile(pFile);
 40900  #endif
 40901  
 40902    do{
 40903      rc = osCloseHandle(pFile->h);
 40904      /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
 40905    }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
 40906  #if SQLITE_OS_WINCE
 40907  #define WINCE_DELETION_ATTEMPTS 3
 40908    {
 40909      winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
 40910      if( pAppData==NULL || !pAppData->bNoLock ){
 40911        winceDestroyLock(pFile);
 40912      }
 40913    }
 40914    if( pFile->zDeleteOnClose ){
 40915      int cnt = 0;
 40916      while(
 40917             osDeleteFileW(pFile->zDeleteOnClose)==0
 40918          && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
 40919          && cnt++ < WINCE_DELETION_ATTEMPTS
 40920      ){
 40921         sqlite3_win32_sleep(100);  /* Wait a little before trying again */
 40922      }
 40923      sqlite3_free(pFile->zDeleteOnClose);
 40924    }
 40925  #endif
 40926    if( rc ){
 40927      pFile->h = NULL;
 40928    }
 40929    OpenCounter(-1);
 40930    OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
 40931             osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
 40932    return rc ? SQLITE_OK
 40933              : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
 40934                            "winClose", pFile->zPath);
 40935  }
 40936  
 40937  /*
 40938  ** Read data from a file into a buffer.  Return SQLITE_OK if all
 40939  ** bytes were read successfully and SQLITE_IOERR if anything goes
 40940  ** wrong.
 40941  */
 40942  static int winRead(
 40943    sqlite3_file *id,          /* File to read from */
 40944    void *pBuf,                /* Write content into this buffer */
 40945    int amt,                   /* Number of bytes to read */
 40946    sqlite3_int64 offset       /* Begin reading at this offset */
 40947  ){
 40948  #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
 40949    OVERLAPPED overlapped;          /* The offset for ReadFile. */
 40950  #endif
 40951    winFile *pFile = (winFile*)id;  /* file handle */
 40952    DWORD nRead;                    /* Number of bytes actually read from file */
 40953    int nRetry = 0;                 /* Number of retrys */
 40954  
 40955    assert( id!=0 );
 40956    assert( amt>0 );
 40957    assert( offset>=0 );
 40958    SimulateIOError(return SQLITE_IOERR_READ);
 40959    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
 40960             "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
 40961             pFile->h, pBuf, amt, offset, pFile->locktype));
 40962  
 40963  #if SQLITE_MAX_MMAP_SIZE>0
 40964    /* Deal with as much of this read request as possible by transfering
 40965    ** data from the memory mapping using memcpy().  */
 40966    if( offset<pFile->mmapSize ){
 40967      if( offset+amt <= pFile->mmapSize ){
 40968        memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
 40969        OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
 40970                 osGetCurrentProcessId(), pFile, pFile->h));
 40971        return SQLITE_OK;
 40972      }else{
 40973        int nCopy = (int)(pFile->mmapSize - offset);
 40974        memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
 40975        pBuf = &((u8 *)pBuf)[nCopy];
 40976        amt -= nCopy;
 40977        offset += nCopy;
 40978      }
 40979    }
 40980  #endif
 40981  
 40982  #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
 40983    if( winSeekFile(pFile, offset) ){
 40984      OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
 40985               osGetCurrentProcessId(), pFile, pFile->h));
 40986      return SQLITE_FULL;
 40987    }
 40988    while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
 40989  #else
 40990    memset(&overlapped, 0, sizeof(OVERLAPPED));
 40991    overlapped.Offset = (LONG)(offset & 0xffffffff);
 40992    overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
 40993    while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
 40994           osGetLastError()!=ERROR_HANDLE_EOF ){
 40995  #endif
 40996      DWORD lastErrno;
 40997      if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
 40998      pFile->lastErrno = lastErrno;
 40999      OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
 41000               osGetCurrentProcessId(), pFile, pFile->h));
 41001      return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
 41002                         "winRead", pFile->zPath);
 41003    }
 41004    winLogIoerr(nRetry, __LINE__);
 41005    if( nRead<(DWORD)amt ){
 41006      /* Unread parts of the buffer must be zero-filled */
 41007      memset(&((char*)pBuf)[nRead], 0, amt-nRead);
 41008      OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
 41009               osGetCurrentProcessId(), pFile, pFile->h));
 41010      return SQLITE_IOERR_SHORT_READ;
 41011    }
 41012  
 41013    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
 41014             osGetCurrentProcessId(), pFile, pFile->h));
 41015    return SQLITE_OK;
 41016  }
 41017  
 41018  /*
 41019  ** Write data from a buffer into a file.  Return SQLITE_OK on success
 41020  ** or some other error code on failure.
 41021  */
 41022  static int winWrite(
 41023    sqlite3_file *id,               /* File to write into */
 41024    const void *pBuf,               /* The bytes to be written */
 41025    int amt,                        /* Number of bytes to write */
 41026    sqlite3_int64 offset            /* Offset into the file to begin writing at */
 41027  ){
 41028    int rc = 0;                     /* True if error has occurred, else false */
 41029    winFile *pFile = (winFile*)id;  /* File handle */
 41030    int nRetry = 0;                 /* Number of retries */
 41031  
 41032    assert( amt>0 );
 41033    assert( pFile );
 41034    SimulateIOError(return SQLITE_IOERR_WRITE);
 41035    SimulateDiskfullError(return SQLITE_FULL);
 41036  
 41037    OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
 41038             "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
 41039             pFile->h, pBuf, amt, offset, pFile->locktype));
 41040  
 41041  #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
 41042    /* Deal with as much of this write request as possible by transfering
 41043    ** data from the memory mapping using memcpy().  */
 41044    if( offset<pFile->mmapSize ){
 41045      if( offset+amt <= pFile->mmapSize ){
 41046        memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
 41047        OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
 41048                 osGetCurrentProcessId(), pFile, pFile->h));
 41049        return SQLITE_OK;
 41050      }else{
 41051        int nCopy = (int)(pFile->mmapSize - offset);
 41052        memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
 41053        pBuf = &((u8 *)pBuf)[nCopy];
 41054        amt -= nCopy;
 41055        offset += nCopy;
 41056      }
 41057    }
 41058  #endif
 41059  
 41060  #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
 41061    rc = winSeekFile(pFile, offset);
 41062    if( rc==0 ){
 41063  #else
 41064    {
 41065  #endif
 41066  #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
 41067      OVERLAPPED overlapped;        /* The offset for WriteFile. */
 41068  #endif
 41069      u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
 41070      int nRem = amt;               /* Number of bytes yet to be written */
 41071      DWORD nWrite;                 /* Bytes written by each WriteFile() call */
 41072      DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
 41073  
 41074  #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
 41075      memset(&overlapped, 0, sizeof(OVERLAPPED));
 41076      overlapped.Offset = (LONG)(offset & 0xffffffff);
 41077      overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
 41078  #endif
 41079  
 41080      while( nRem>0 ){
 41081  #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
 41082        if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
 41083  #else
 41084        if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
 41085  #endif
 41086          if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
 41087          break;
 41088        }
 41089        assert( nWrite==0 || nWrite<=(DWORD)nRem );
 41090        if( nWrite==0 || nWrite>(DWORD)nRem ){
 41091          lastErrno = osGetLastError();
 41092          break;
 41093        }
 41094  #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
 41095        offset += nWrite;
 41096        overlapped.Offset = (LONG)(offset & 0xffffffff);
 41097        overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
 41098  #endif
 41099        aRem += nWrite;
 41100        nRem -= nWrite;
 41101      }
 41102      if( nRem>0 ){
 41103        pFile->lastErrno = lastErrno;
 41104        rc = 1;
 41105      }
 41106    }
 41107  
 41108    if( rc ){
 41109      if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
 41110         || ( pFile->lastErrno==ERROR_DISK_FULL )){
 41111        OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
 41112                 osGetCurrentProcessId(), pFile, pFile->h));
 41113        return winLogError(SQLITE_FULL, pFile->lastErrno,
 41114                           "winWrite1", pFile->zPath);
 41115      }
 41116      OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
 41117               osGetCurrentProcessId(), pFile, pFile->h));
 41118      return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
 41119                         "winWrite2", pFile->zPath);
 41120    }else{
 41121      winLogIoerr(nRetry, __LINE__);
 41122    }
 41123    OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
 41124             osGetCurrentProcessId(), pFile, pFile->h));
 41125    return SQLITE_OK;
 41126  }
 41127  
 41128  /*
 41129  ** Truncate an open file to a specified size
 41130  */
 41131  static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
 41132    winFile *pFile = (winFile*)id;  /* File handle object */
 41133    int rc = SQLITE_OK;             /* Return code for this function */
 41134    DWORD lastErrno;
 41135  
 41136    assert( pFile );
 41137    SimulateIOError(return SQLITE_IOERR_TRUNCATE);
 41138    OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
 41139             osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
 41140  
 41141    /* If the user has configured a chunk-size for this file, truncate the
 41142    ** file so that it consists of an integer number of chunks (i.e. the
 41143    ** actual file size after the operation may be larger than the requested
 41144    ** size).
 41145    */
 41146    if( pFile->szChunk>0 ){
 41147      nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
 41148    }
 41149  
 41150    /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
 41151    if( winSeekFile(pFile, nByte) ){
 41152      rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
 41153                       "winTruncate1", pFile->zPath);
 41154    }else if( 0==osSetEndOfFile(pFile->h) &&
 41155              ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
 41156      pFile->lastErrno = lastErrno;
 41157      rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
 41158                       "winTruncate2", pFile->zPath);
 41159    }
 41160  
 41161  #if SQLITE_MAX_MMAP_SIZE>0
 41162    /* If the file was truncated to a size smaller than the currently
 41163    ** mapped region, reduce the effective mapping size as well. SQLite will
 41164    ** use read() and write() to access data beyond this point from now on.
 41165    */
 41166    if( pFile->pMapRegion && nByte<pFile->mmapSize ){
 41167      pFile->mmapSize = nByte;
 41168    }
 41169  #endif
 41170  
 41171    OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
 41172             osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
 41173    return rc;
 41174  }
 41175  
 41176  #ifdef SQLITE_TEST
 41177  /*
 41178  ** Count the number of fullsyncs and normal syncs.  This is used to test
 41179  ** that syncs and fullsyncs are occuring at the right times.
 41180  */
 41181  SQLITE_API int sqlite3_sync_count = 0;
 41182  SQLITE_API int sqlite3_fullsync_count = 0;
 41183  #endif
 41184  
 41185  /*
 41186  ** Make sure all writes to a particular file are committed to disk.
 41187  */
 41188  static int winSync(sqlite3_file *id, int flags){
 41189  #ifndef SQLITE_NO_SYNC
 41190    /*
 41191    ** Used only when SQLITE_NO_SYNC is not defined.
 41192     */
 41193    BOOL rc;
 41194  #endif
 41195  #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
 41196      defined(SQLITE_HAVE_OS_TRACE)
 41197    /*
 41198    ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
 41199    ** OSTRACE() macros.
 41200     */
 41201    winFile *pFile = (winFile*)id;
 41202  #else
 41203    UNUSED_PARAMETER(id);
 41204  #endif
 41205  
 41206    assert( pFile );
 41207    /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
 41208    assert((flags&0x0F)==SQLITE_SYNC_NORMAL
 41209        || (flags&0x0F)==SQLITE_SYNC_FULL
 41210    );
 41211  
 41212    /* Unix cannot, but some systems may return SQLITE_FULL from here. This
 41213    ** line is to test that doing so does not cause any problems.
 41214    */
 41215    SimulateDiskfullError( return SQLITE_FULL );
 41216  
 41217    OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
 41218             osGetCurrentProcessId(), pFile, pFile->h, flags,
 41219             pFile->locktype));
 41220  
 41221  #ifndef SQLITE_TEST
 41222    UNUSED_PARAMETER(flags);
 41223  #else
 41224    if( (flags&0x0F)==SQLITE_SYNC_FULL ){
 41225      sqlite3_fullsync_count++;
 41226    }
 41227    sqlite3_sync_count++;
 41228  #endif
 41229  
 41230    /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
 41231    ** no-op
 41232    */
 41233  #ifdef SQLITE_NO_SYNC
 41234    OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
 41235             osGetCurrentProcessId(), pFile, pFile->h));
 41236    return SQLITE_OK;
 41237  #else
 41238  #if SQLITE_MAX_MMAP_SIZE>0
 41239    if( pFile->pMapRegion ){
 41240      if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
 41241        OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
 41242                 "rc=SQLITE_OK\n", osGetCurrentProcessId(),
 41243                 pFile, pFile->pMapRegion));
 41244      }else{
 41245        pFile->lastErrno = osGetLastError();
 41246        OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
 41247                 "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
 41248                 pFile, pFile->pMapRegion));
 41249        return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
 41250                           "winSync1", pFile->zPath);
 41251      }
 41252    }
 41253  #endif
 41254    rc = osFlushFileBuffers(pFile->h);
 41255    SimulateIOError( rc=FALSE );
 41256    if( rc ){
 41257      OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
 41258               osGetCurrentProcessId(), pFile, pFile->h));
 41259      return SQLITE_OK;
 41260    }else{
 41261      pFile->lastErrno = osGetLastError();
 41262      OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
 41263               osGetCurrentProcessId(), pFile, pFile->h));
 41264      return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
 41265                         "winSync2", pFile->zPath);
 41266    }
 41267  #endif
 41268  }
 41269  
 41270  /*
 41271  ** Determine the current size of a file in bytes
 41272  */
 41273  static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
 41274    winFile *pFile = (winFile*)id;
 41275    int rc = SQLITE_OK;
 41276  
 41277    assert( id!=0 );
 41278    assert( pSize!=0 );
 41279    SimulateIOError(return SQLITE_IOERR_FSTAT);
 41280    OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
 41281  
 41282  #if SQLITE_OS_WINRT
 41283    {
 41284      FILE_STANDARD_INFO info;
 41285      if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
 41286                                       &info, sizeof(info)) ){
 41287        *pSize = info.EndOfFile.QuadPart;
 41288      }else{
 41289        pFile->lastErrno = osGetLastError();
 41290        rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
 41291                         "winFileSize", pFile->zPath);
 41292      }
 41293    }
 41294  #else
 41295    {
 41296      DWORD upperBits;
 41297      DWORD lowerBits;
 41298      DWORD lastErrno;
 41299  
 41300      lowerBits = osGetFileSize(pFile->h, &upperBits);
 41301      *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
 41302      if(   (lowerBits == INVALID_FILE_SIZE)
 41303         && ((lastErrno = osGetLastError())!=NO_ERROR) ){
 41304        pFile->lastErrno = lastErrno;
 41305        rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
 41306                         "winFileSize", pFile->zPath);
 41307      }
 41308    }
 41309  #endif
 41310    OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
 41311             pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
 41312    return rc;
 41313  }
 41314  
 41315  /*
 41316  ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
 41317  */
 41318  #ifndef LOCKFILE_FAIL_IMMEDIATELY
 41319  # define LOCKFILE_FAIL_IMMEDIATELY 1
 41320  #endif
 41321  
 41322  #ifndef LOCKFILE_EXCLUSIVE_LOCK
 41323  # define LOCKFILE_EXCLUSIVE_LOCK 2
 41324  #endif
 41325  
 41326  /*
 41327  ** Historically, SQLite has used both the LockFile and LockFileEx functions.
 41328  ** When the LockFile function was used, it was always expected to fail
 41329  ** immediately if the lock could not be obtained.  Also, it always expected to
 41330  ** obtain an exclusive lock.  These flags are used with the LockFileEx function
 41331  ** and reflect those expectations; therefore, they should not be changed.
 41332  */
 41333  #ifndef SQLITE_LOCKFILE_FLAGS
 41334  # define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
 41335                                    LOCKFILE_EXCLUSIVE_LOCK)
 41336  #endif
 41337  
 41338  /*
 41339  ** Currently, SQLite never calls the LockFileEx function without wanting the
 41340  ** call to fail immediately if the lock cannot be obtained.
 41341  */
 41342  #ifndef SQLITE_LOCKFILEEX_FLAGS
 41343  # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
 41344  #endif
 41345  
 41346  /*
 41347  ** Acquire a reader lock.
 41348  ** Different API routines are called depending on whether or not this
 41349  ** is Win9x or WinNT.
 41350  */
 41351  static int winGetReadLock(winFile *pFile){
 41352    int res;
 41353    OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
 41354    if( osIsNT() ){
 41355  #if SQLITE_OS_WINCE
 41356      /*
 41357      ** NOTE: Windows CE is handled differently here due its lack of the Win32
 41358      **       API LockFileEx.
 41359      */
 41360      res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
 41361  #else
 41362      res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
 41363                        SHARED_SIZE, 0);
 41364  #endif
 41365    }
 41366  #ifdef SQLITE_WIN32_HAS_ANSI
 41367    else{
 41368      int lk;
 41369      sqlite3_randomness(sizeof(lk), &lk);
 41370      pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
 41371      res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
 41372                        SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
 41373    }
 41374  #endif
 41375    if( res == 0 ){
 41376      pFile->lastErrno = osGetLastError();
 41377      /* No need to log a failure to lock */
 41378    }
 41379    OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
 41380    return res;
 41381  }
 41382  
 41383  /*
 41384  ** Undo a readlock
 41385  */
 41386  static int winUnlockReadLock(winFile *pFile){
 41387    int res;
 41388    DWORD lastErrno;
 41389    OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
 41390    if( osIsNT() ){
 41391      res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
 41392    }
 41393  #ifdef SQLITE_WIN32_HAS_ANSI
 41394    else{
 41395      res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
 41396    }
 41397  #endif
 41398    if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
 41399      pFile->lastErrno = lastErrno;
 41400      winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
 41401                  "winUnlockReadLock", pFile->zPath);
 41402    }
 41403    OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
 41404    return res;
 41405  }
 41406  
 41407  /*
 41408  ** Lock the file with the lock specified by parameter locktype - one
 41409  ** of the following:
 41410  **
 41411  **     (1) SHARED_LOCK
 41412  **     (2) RESERVED_LOCK
 41413  **     (3) PENDING_LOCK
 41414  **     (4) EXCLUSIVE_LOCK
 41415  **
 41416  ** Sometimes when requesting one lock state, additional lock states
 41417  ** are inserted in between.  The locking might fail on one of the later
 41418  ** transitions leaving the lock state different from what it started but
 41419  ** still short of its goal.  The following chart shows the allowed
 41420  ** transitions and the inserted intermediate states:
 41421  **
 41422  **    UNLOCKED -> SHARED
 41423  **    SHARED -> RESERVED
 41424  **    SHARED -> (PENDING) -> EXCLUSIVE
 41425  **    RESERVED -> (PENDING) -> EXCLUSIVE
 41426  **    PENDING -> EXCLUSIVE
 41427  **
 41428  ** This routine will only increase a lock.  The winUnlock() routine
 41429  ** erases all locks at once and returns us immediately to locking level 0.
 41430  ** It is not possible to lower the locking level one step at a time.  You
 41431  ** must go straight to locking level 0.
 41432  */
 41433  static int winLock(sqlite3_file *id, int locktype){
 41434    int rc = SQLITE_OK;    /* Return code from subroutines */
 41435    int res = 1;           /* Result of a Windows lock call */
 41436    int newLocktype;       /* Set pFile->locktype to this value before exiting */
 41437    int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
 41438    winFile *pFile = (winFile*)id;
 41439    DWORD lastErrno = NO_ERROR;
 41440  
 41441    assert( id!=0 );
 41442    OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
 41443             pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
 41444  
 41445    /* If there is already a lock of this type or more restrictive on the
 41446    ** OsFile, do nothing. Don't use the end_lock: exit path, as
 41447    ** sqlite3OsEnterMutex() hasn't been called yet.
 41448    */
 41449    if( pFile->locktype>=locktype ){
 41450      OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
 41451      return SQLITE_OK;
 41452    }
 41453  
 41454    /* Do not allow any kind of write-lock on a read-only database
 41455    */
 41456    if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
 41457      return SQLITE_IOERR_LOCK;
 41458    }
 41459  
 41460    /* Make sure the locking sequence is correct
 41461    */
 41462    assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
 41463    assert( locktype!=PENDING_LOCK );
 41464    assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
 41465  
 41466    /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
 41467    ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
 41468    ** the PENDING_LOCK byte is temporary.
 41469    */
 41470    newLocktype = pFile->locktype;
 41471    if( pFile->locktype==NO_LOCK
 41472     || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
 41473    ){
 41474      int cnt = 3;
 41475      while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
 41476                                           PENDING_BYTE, 0, 1, 0))==0 ){
 41477        /* Try 3 times to get the pending lock.  This is needed to work
 41478        ** around problems caused by indexing and/or anti-virus software on
 41479        ** Windows systems.
 41480        ** If you are using this code as a model for alternative VFSes, do not
 41481        ** copy this retry logic.  It is a hack intended for Windows only.
 41482        */
 41483        lastErrno = osGetLastError();
 41484        OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
 41485                 pFile->h, cnt, res));
 41486        if( lastErrno==ERROR_INVALID_HANDLE ){
 41487          pFile->lastErrno = lastErrno;
 41488          rc = SQLITE_IOERR_LOCK;
 41489          OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
 41490                   pFile->h, cnt, sqlite3ErrName(rc)));
 41491          return rc;
 41492        }
 41493        if( cnt ) sqlite3_win32_sleep(1);
 41494      }
 41495      gotPendingLock = res;
 41496      if( !res ){
 41497        lastErrno = osGetLastError();
 41498      }
 41499    }
 41500  
 41501    /* Acquire a shared lock
 41502    */
 41503    if( locktype==SHARED_LOCK && res ){
 41504      assert( pFile->locktype==NO_LOCK );
 41505      res = winGetReadLock(pFile);
 41506      if( res ){
 41507        newLocktype = SHARED_LOCK;
 41508      }else{
 41509        lastErrno = osGetLastError();
 41510      }
 41511    }
 41512  
 41513    /* Acquire a RESERVED lock
 41514    */
 41515    if( locktype==RESERVED_LOCK && res ){
 41516      assert( pFile->locktype==SHARED_LOCK );
 41517      res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
 41518      if( res ){
 41519        newLocktype = RESERVED_LOCK;
 41520      }else{
 41521        lastErrno = osGetLastError();
 41522      }
 41523    }
 41524  
 41525    /* Acquire a PENDING lock
 41526    */
 41527    if( locktype==EXCLUSIVE_LOCK && res ){
 41528      newLocktype = PENDING_LOCK;
 41529      gotPendingLock = 0;
 41530    }
 41531  
 41532    /* Acquire an EXCLUSIVE lock
 41533    */
 41534    if( locktype==EXCLUSIVE_LOCK && res ){
 41535      assert( pFile->locktype>=SHARED_LOCK );
 41536      res = winUnlockReadLock(pFile);
 41537      res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
 41538                        SHARED_SIZE, 0);
 41539      if( res ){
 41540        newLocktype = EXCLUSIVE_LOCK;
 41541      }else{
 41542        lastErrno = osGetLastError();
 41543        winGetReadLock(pFile);
 41544      }
 41545    }
 41546  
 41547    /* If we are holding a PENDING lock that ought to be released, then
 41548    ** release it now.
 41549    */
 41550    if( gotPendingLock && locktype==SHARED_LOCK ){
 41551      winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
 41552    }
 41553  
 41554    /* Update the state of the lock has held in the file descriptor then
 41555    ** return the appropriate result code.
 41556    */
 41557    if( res ){
 41558      rc = SQLITE_OK;
 41559    }else{
 41560      pFile->lastErrno = lastErrno;
 41561      rc = SQLITE_BUSY;
 41562      OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
 41563               pFile->h, locktype, newLocktype));
 41564    }
 41565    pFile->locktype = (u8)newLocktype;
 41566    OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
 41567             pFile->h, pFile->locktype, sqlite3ErrName(rc)));
 41568    return rc;
 41569  }
 41570  
 41571  /*
 41572  ** This routine checks if there is a RESERVED lock held on the specified
 41573  ** file by this or any other process. If such a lock is held, return
 41574  ** non-zero, otherwise zero.
 41575  */
 41576  static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
 41577    int res;
 41578    winFile *pFile = (winFile*)id;
 41579  
 41580    SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
 41581    OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
 41582  
 41583    assert( id!=0 );
 41584    if( pFile->locktype>=RESERVED_LOCK ){
 41585      res = 1;
 41586      OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
 41587    }else{
 41588      res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
 41589      if( res ){
 41590        winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
 41591      }
 41592      res = !res;
 41593      OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
 41594    }
 41595    *pResOut = res;
 41596    OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
 41597             pFile->h, pResOut, *pResOut));
 41598    return SQLITE_OK;
 41599  }
 41600  
 41601  /*
 41602  ** Lower the locking level on file descriptor id to locktype.  locktype
 41603  ** must be either NO_LOCK or SHARED_LOCK.
 41604  **
 41605  ** If the locking level of the file descriptor is already at or below
 41606  ** the requested locking level, this routine is a no-op.
 41607  **
 41608  ** It is not possible for this routine to fail if the second argument
 41609  ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
 41610  ** might return SQLITE_IOERR;
 41611  */
 41612  static int winUnlock(sqlite3_file *id, int locktype){
 41613    int type;
 41614    winFile *pFile = (winFile*)id;
 41615    int rc = SQLITE_OK;
 41616    assert( pFile!=0 );
 41617    assert( locktype<=SHARED_LOCK );
 41618    OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
 41619             pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
 41620    type = pFile->locktype;
 41621    if( type>=EXCLUSIVE_LOCK ){
 41622      winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
 41623      if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
 41624        /* This should never happen.  We should always be able to
 41625        ** reacquire the read lock */
 41626        rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
 41627                         "winUnlock", pFile->zPath);
 41628      }
 41629    }
 41630    if( type>=RESERVED_LOCK ){
 41631      winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
 41632    }
 41633    if( locktype==NO_LOCK && type>=SHARED_LOCK ){
 41634      winUnlockReadLock(pFile);
 41635    }
 41636    if( type>=PENDING_LOCK ){
 41637      winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
 41638    }
 41639    pFile->locktype = (u8)locktype;
 41640    OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
 41641             pFile->h, pFile->locktype, sqlite3ErrName(rc)));
 41642    return rc;
 41643  }
 41644  
 41645  /******************************************************************************
 41646  ****************************** No-op Locking **********************************
 41647  **
 41648  ** Of the various locking implementations available, this is by far the
 41649  ** simplest:  locking is ignored.  No attempt is made to lock the database
 41650  ** file for reading or writing.
 41651  **
 41652  ** This locking mode is appropriate for use on read-only databases
 41653  ** (ex: databases that are burned into CD-ROM, for example.)  It can
 41654  ** also be used if the application employs some external mechanism to
 41655  ** prevent simultaneous access of the same database by two or more
 41656  ** database connections.  But there is a serious risk of database
 41657  ** corruption if this locking mode is used in situations where multiple
 41658  ** database connections are accessing the same database file at the same
 41659  ** time and one or more of those connections are writing.
 41660  */
 41661  
 41662  static int winNolockLock(sqlite3_file *id, int locktype){
 41663    UNUSED_PARAMETER(id);
 41664    UNUSED_PARAMETER(locktype);
 41665    return SQLITE_OK;
 41666  }
 41667  
 41668  static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
 41669    UNUSED_PARAMETER(id);
 41670    UNUSED_PARAMETER(pResOut);
 41671    return SQLITE_OK;
 41672  }
 41673  
 41674  static int winNolockUnlock(sqlite3_file *id, int locktype){
 41675    UNUSED_PARAMETER(id);
 41676    UNUSED_PARAMETER(locktype);
 41677    return SQLITE_OK;
 41678  }
 41679  
 41680  /******************* End of the no-op lock implementation *********************
 41681  ******************************************************************************/
 41682  
 41683  /*
 41684  ** If *pArg is initially negative then this is a query.  Set *pArg to
 41685  ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
 41686  **
 41687  ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
 41688  */
 41689  static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
 41690    if( *pArg<0 ){
 41691      *pArg = (pFile->ctrlFlags & mask)!=0;
 41692    }else if( (*pArg)==0 ){
 41693      pFile->ctrlFlags &= ~mask;
 41694    }else{
 41695      pFile->ctrlFlags |= mask;
 41696    }
 41697  }
 41698  
 41699  /* Forward references to VFS helper methods used for temporary files */
 41700  static int winGetTempname(sqlite3_vfs *, char **);
 41701  static int winIsDir(const void *);
 41702  static BOOL winIsDriveLetterAndColon(const char *);
 41703  
 41704  /*
 41705  ** Control and query of the open file handle.
 41706  */
 41707  static int winFileControl(sqlite3_file *id, int op, void *pArg){
 41708    winFile *pFile = (winFile*)id;
 41709    OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
 41710    switch( op ){
 41711      case SQLITE_FCNTL_LOCKSTATE: {
 41712        *(int*)pArg = pFile->locktype;
 41713        OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 41714        return SQLITE_OK;
 41715      }
 41716      case SQLITE_FCNTL_LAST_ERRNO: {
 41717        *(int*)pArg = (int)pFile->lastErrno;
 41718        OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 41719        return SQLITE_OK;
 41720      }
 41721      case SQLITE_FCNTL_CHUNK_SIZE: {
 41722        pFile->szChunk = *(int *)pArg;
 41723        OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 41724        return SQLITE_OK;
 41725      }
 41726      case SQLITE_FCNTL_SIZE_HINT: {
 41727        if( pFile->szChunk>0 ){
 41728          sqlite3_int64 oldSz;
 41729          int rc = winFileSize(id, &oldSz);
 41730          if( rc==SQLITE_OK ){
 41731            sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
 41732            if( newSz>oldSz ){
 41733              SimulateIOErrorBenign(1);
 41734              rc = winTruncate(id, newSz);
 41735              SimulateIOErrorBenign(0);
 41736            }
 41737          }
 41738          OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
 41739          return rc;
 41740        }
 41741        OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 41742        return SQLITE_OK;
 41743      }
 41744      case SQLITE_FCNTL_PERSIST_WAL: {
 41745        winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
 41746        OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 41747        return SQLITE_OK;
 41748      }
 41749      case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
 41750        winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
 41751        OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 41752        return SQLITE_OK;
 41753      }
 41754      case SQLITE_FCNTL_VFSNAME: {
 41755        *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
 41756        OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 41757        return SQLITE_OK;
 41758      }
 41759      case SQLITE_FCNTL_WIN32_AV_RETRY: {
 41760        int *a = (int*)pArg;
 41761        if( a[0]>0 ){
 41762          winIoerrRetry = a[0];
 41763        }else{
 41764          a[0] = winIoerrRetry;
 41765        }
 41766        if( a[1]>0 ){
 41767          winIoerrRetryDelay = a[1];
 41768        }else{
 41769          a[1] = winIoerrRetryDelay;
 41770        }
 41771        OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 41772        return SQLITE_OK;
 41773      }
 41774      case SQLITE_FCNTL_WIN32_GET_HANDLE: {
 41775        LPHANDLE phFile = (LPHANDLE)pArg;
 41776        *phFile = pFile->h;
 41777        OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 41778        return SQLITE_OK;
 41779      }
 41780  #ifdef SQLITE_TEST
 41781      case SQLITE_FCNTL_WIN32_SET_HANDLE: {
 41782        LPHANDLE phFile = (LPHANDLE)pArg;
 41783        HANDLE hOldFile = pFile->h;
 41784        pFile->h = *phFile;
 41785        *phFile = hOldFile;
 41786        OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
 41787                 hOldFile, pFile->h));
 41788        return SQLITE_OK;
 41789      }
 41790  #endif
 41791      case SQLITE_FCNTL_TEMPFILENAME: {
 41792        char *zTFile = 0;
 41793        int rc = winGetTempname(pFile->pVfs, &zTFile);
 41794        if( rc==SQLITE_OK ){
 41795          *(char**)pArg = zTFile;
 41796        }
 41797        OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
 41798        return rc;
 41799      }
 41800  #if SQLITE_MAX_MMAP_SIZE>0
 41801      case SQLITE_FCNTL_MMAP_SIZE: {
 41802        i64 newLimit = *(i64*)pArg;
 41803        int rc = SQLITE_OK;
 41804        if( newLimit>sqlite3GlobalConfig.mxMmap ){
 41805          newLimit = sqlite3GlobalConfig.mxMmap;
 41806        }
 41807  
 41808        /* The value of newLimit may be eventually cast to (SIZE_T) and passed
 41809        ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at
 41810        ** least a 64-bit type. */
 41811        if( newLimit>0 && sizeof(SIZE_T)<8 ){
 41812          newLimit = (newLimit & 0x7FFFFFFF);
 41813        }
 41814  
 41815        *(i64*)pArg = pFile->mmapSizeMax;
 41816        if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
 41817          pFile->mmapSizeMax = newLimit;
 41818          if( pFile->mmapSize>0 ){
 41819            winUnmapfile(pFile);
 41820            rc = winMapfile(pFile, -1);
 41821          }
 41822        }
 41823        OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
 41824        return rc;
 41825      }
 41826  #endif
 41827    }
 41828    OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
 41829    return SQLITE_NOTFOUND;
 41830  }
 41831  
 41832  /*
 41833  ** Return the sector size in bytes of the underlying block device for
 41834  ** the specified file. This is almost always 512 bytes, but may be
 41835  ** larger for some devices.
 41836  **
 41837  ** SQLite code assumes this function cannot fail. It also assumes that
 41838  ** if two files are created in the same file-system directory (i.e.
 41839  ** a database and its journal file) that the sector size will be the
 41840  ** same for both.
 41841  */
 41842  static int winSectorSize(sqlite3_file *id){
 41843    (void)id;
 41844    return SQLITE_DEFAULT_SECTOR_SIZE;
 41845  }
 41846  
 41847  /*
 41848  ** Return a vector of device characteristics.
 41849  */
 41850  static int winDeviceCharacteristics(sqlite3_file *id){
 41851    winFile *p = (winFile*)id;
 41852    return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
 41853           ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
 41854  }
 41855  
 41856  /*
 41857  ** Windows will only let you create file view mappings
 41858  ** on allocation size granularity boundaries.
 41859  ** During sqlite3_os_init() we do a GetSystemInfo()
 41860  ** to get the granularity size.
 41861  */
 41862  static SYSTEM_INFO winSysInfo;
 41863  
 41864  #ifndef SQLITE_OMIT_WAL
 41865  
 41866  /*
 41867  ** Helper functions to obtain and relinquish the global mutex. The
 41868  ** global mutex is used to protect the winLockInfo objects used by
 41869  ** this file, all of which may be shared by multiple threads.
 41870  **
 41871  ** Function winShmMutexHeld() is used to assert() that the global mutex
 41872  ** is held when required. This function is only used as part of assert()
 41873  ** statements. e.g.
 41874  **
 41875  **   winShmEnterMutex()
 41876  **     assert( winShmMutexHeld() );
 41877  **   winShmLeaveMutex()
 41878  */
 41879  static void winShmEnterMutex(void){
 41880    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
 41881  }
 41882  static void winShmLeaveMutex(void){
 41883    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
 41884  }
 41885  #ifndef NDEBUG
 41886  static int winShmMutexHeld(void) {
 41887    return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
 41888  }
 41889  #endif
 41890  
 41891  /*
 41892  ** Object used to represent a single file opened and mmapped to provide
 41893  ** shared memory.  When multiple threads all reference the same
 41894  ** log-summary, each thread has its own winFile object, but they all
 41895  ** point to a single instance of this object.  In other words, each
 41896  ** log-summary is opened only once per process.
 41897  **
 41898  ** winShmMutexHeld() must be true when creating or destroying
 41899  ** this object or while reading or writing the following fields:
 41900  **
 41901  **      nRef
 41902  **      pNext
 41903  **
 41904  ** The following fields are read-only after the object is created:
 41905  **
 41906  **      fid
 41907  **      zFilename
 41908  **
 41909  ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
 41910  ** winShmMutexHeld() is true when reading or writing any other field
 41911  ** in this structure.
 41912  **
 41913  */
 41914  struct winShmNode {
 41915    sqlite3_mutex *mutex;      /* Mutex to access this object */
 41916    char *zFilename;           /* Name of the file */
 41917    winFile hFile;             /* File handle from winOpen */
 41918  
 41919    int szRegion;              /* Size of shared-memory regions */
 41920    int nRegion;               /* Size of array apRegion */
 41921    struct ShmRegion {
 41922      HANDLE hMap;             /* File handle from CreateFileMapping */
 41923      void *pMap;
 41924    } *aRegion;
 41925    DWORD lastErrno;           /* The Windows errno from the last I/O error */
 41926  
 41927    int nRef;                  /* Number of winShm objects pointing to this */
 41928    winShm *pFirst;            /* All winShm objects pointing to this */
 41929    winShmNode *pNext;         /* Next in list of all winShmNode objects */
 41930  #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
 41931    u8 nextShmId;              /* Next available winShm.id value */
 41932  #endif
 41933  };
 41934  
 41935  /*
 41936  ** A global array of all winShmNode objects.
 41937  **
 41938  ** The winShmMutexHeld() must be true while reading or writing this list.
 41939  */
 41940  static winShmNode *winShmNodeList = 0;
 41941  
 41942  /*
 41943  ** Structure used internally by this VFS to record the state of an
 41944  ** open shared memory connection.
 41945  **
 41946  ** The following fields are initialized when this object is created and
 41947  ** are read-only thereafter:
 41948  **
 41949  **    winShm.pShmNode
 41950  **    winShm.id
 41951  **
 41952  ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
 41953  ** while accessing any read/write fields.
 41954  */
 41955  struct winShm {
 41956    winShmNode *pShmNode;      /* The underlying winShmNode object */
 41957    winShm *pNext;             /* Next winShm with the same winShmNode */
 41958    u8 hasMutex;               /* True if holding the winShmNode mutex */
 41959    u16 sharedMask;            /* Mask of shared locks held */
 41960    u16 exclMask;              /* Mask of exclusive locks held */
 41961  #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
 41962    u8 id;                     /* Id of this connection with its winShmNode */
 41963  #endif
 41964  };
 41965  
 41966  /*
 41967  ** Constants used for locking
 41968  */
 41969  #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
 41970  #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
 41971  
 41972  /*
 41973  ** Apply advisory locks for all n bytes beginning at ofst.
 41974  */
 41975  #define WINSHM_UNLCK  1
 41976  #define WINSHM_RDLCK  2
 41977  #define WINSHM_WRLCK  3
 41978  static int winShmSystemLock(
 41979    winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
 41980    int lockType,         /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
 41981    int ofst,             /* Offset to first byte to be locked/unlocked */
 41982    int nByte             /* Number of bytes to lock or unlock */
 41983  ){
 41984    int rc = 0;           /* Result code form Lock/UnlockFileEx() */
 41985  
 41986    /* Access to the winShmNode object is serialized by the caller */
 41987    assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
 41988  
 41989    OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
 41990             pFile->hFile.h, lockType, ofst, nByte));
 41991  
 41992    /* Release/Acquire the system-level lock */
 41993    if( lockType==WINSHM_UNLCK ){
 41994      rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
 41995    }else{
 41996      /* Initialize the locking parameters */
 41997      DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
 41998      if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
 41999      rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
 42000    }
 42001  
 42002    if( rc!= 0 ){
 42003      rc = SQLITE_OK;
 42004    }else{
 42005      pFile->lastErrno =  osGetLastError();
 42006      rc = SQLITE_BUSY;
 42007    }
 42008  
 42009    OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
 42010             pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
 42011             "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
 42012  
 42013    return rc;
 42014  }
 42015  
 42016  /* Forward references to VFS methods */
 42017  static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
 42018  static int winDelete(sqlite3_vfs *,const char*,int);
 42019  
 42020  /*
 42021  ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
 42022  **
 42023  ** This is not a VFS shared-memory method; it is a utility function called
 42024  ** by VFS shared-memory methods.
 42025  */
 42026  static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
 42027    winShmNode **pp;
 42028    winShmNode *p;
 42029    assert( winShmMutexHeld() );
 42030    OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
 42031             osGetCurrentProcessId(), deleteFlag));
 42032    pp = &winShmNodeList;
 42033    while( (p = *pp)!=0 ){
 42034      if( p->nRef==0 ){
 42035        int i;
 42036        if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
 42037        for(i=0; i<p->nRegion; i++){
 42038          BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
 42039          OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
 42040                   osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
 42041          UNUSED_VARIABLE_VALUE(bRc);
 42042          bRc = osCloseHandle(p->aRegion[i].hMap);
 42043          OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
 42044                   osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
 42045          UNUSED_VARIABLE_VALUE(bRc);
 42046        }
 42047        if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
 42048          SimulateIOErrorBenign(1);
 42049          winClose((sqlite3_file *)&p->hFile);
 42050          SimulateIOErrorBenign(0);
 42051        }
 42052        if( deleteFlag ){
 42053          SimulateIOErrorBenign(1);
 42054          sqlite3BeginBenignMalloc();
 42055          winDelete(pVfs, p->zFilename, 0);
 42056          sqlite3EndBenignMalloc();
 42057          SimulateIOErrorBenign(0);
 42058        }
 42059        *pp = p->pNext;
 42060        sqlite3_free(p->aRegion);
 42061        sqlite3_free(p);
 42062      }else{
 42063        pp = &p->pNext;
 42064      }
 42065    }
 42066  }
 42067  
 42068  /*
 42069  ** Open the shared-memory area associated with database file pDbFd.
 42070  **
 42071  ** When opening a new shared-memory file, if no other instances of that
 42072  ** file are currently open, in this process or in other processes, then
 42073  ** the file must be truncated to zero length or have its header cleared.
 42074  */
 42075  static int winOpenSharedMemory(winFile *pDbFd){
 42076    struct winShm *p;                  /* The connection to be opened */
 42077    struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
 42078    int rc;                            /* Result code */
 42079    struct winShmNode *pNew;           /* Newly allocated winShmNode */
 42080    int nName;                         /* Size of zName in bytes */
 42081  
 42082    assert( pDbFd->pShm==0 );    /* Not previously opened */
 42083  
 42084    /* Allocate space for the new sqlite3_shm object.  Also speculatively
 42085    ** allocate space for a new winShmNode and filename.
 42086    */
 42087    p = sqlite3MallocZero( sizeof(*p) );
 42088    if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
 42089    nName = sqlite3Strlen30(pDbFd->zPath);
 42090    pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
 42091    if( pNew==0 ){
 42092      sqlite3_free(p);
 42093      return SQLITE_IOERR_NOMEM_BKPT;
 42094    }
 42095    pNew->zFilename = (char*)&pNew[1];
 42096    sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
 42097    sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
 42098  
 42099    /* Look to see if there is an existing winShmNode that can be used.
 42100    ** If no matching winShmNode currently exists, create a new one.
 42101    */
 42102    winShmEnterMutex();
 42103    for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
 42104      /* TBD need to come up with better match here.  Perhaps
 42105      ** use FILE_ID_BOTH_DIR_INFO Structure.
 42106      */
 42107      if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
 42108    }
 42109    if( pShmNode ){
 42110      sqlite3_free(pNew);
 42111    }else{
 42112      pShmNode = pNew;
 42113      pNew = 0;
 42114      ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
 42115      pShmNode->pNext = winShmNodeList;
 42116      winShmNodeList = pShmNode;
 42117  
 42118      if( sqlite3GlobalConfig.bCoreMutex ){
 42119        pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
 42120        if( pShmNode->mutex==0 ){
 42121          rc = SQLITE_IOERR_NOMEM_BKPT;
 42122          goto shm_open_err;
 42123        }
 42124      }
 42125  
 42126      rc = winOpen(pDbFd->pVfs,
 42127                   pShmNode->zFilename,             /* Name of the file (UTF-8) */
 42128                   (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
 42129                   SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
 42130                   0);
 42131      if( SQLITE_OK!=rc ){
 42132        goto shm_open_err;
 42133      }
 42134  
 42135      /* Check to see if another process is holding the dead-man switch.
 42136      ** If not, truncate the file to zero length.
 42137      */
 42138      if( winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
 42139        rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
 42140        if( rc!=SQLITE_OK ){
 42141          rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
 42142                           "winOpenShm", pDbFd->zPath);
 42143        }
 42144      }
 42145      if( rc==SQLITE_OK ){
 42146        winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
 42147        rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
 42148      }
 42149      if( rc ) goto shm_open_err;
 42150    }
 42151  
 42152    /* Make the new connection a child of the winShmNode */
 42153    p->pShmNode = pShmNode;
 42154  #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
 42155    p->id = pShmNode->nextShmId++;
 42156  #endif
 42157    pShmNode->nRef++;
 42158    pDbFd->pShm = p;
 42159    winShmLeaveMutex();
 42160  
 42161    /* The reference count on pShmNode has already been incremented under
 42162    ** the cover of the winShmEnterMutex() mutex and the pointer from the
 42163    ** new (struct winShm) object to the pShmNode has been set. All that is
 42164    ** left to do is to link the new object into the linked list starting
 42165    ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
 42166    ** mutex.
 42167    */
 42168    sqlite3_mutex_enter(pShmNode->mutex);
 42169    p->pNext = pShmNode->pFirst;
 42170    pShmNode->pFirst = p;
 42171    sqlite3_mutex_leave(pShmNode->mutex);
 42172    return SQLITE_OK;
 42173  
 42174    /* Jump here on any error */
 42175  shm_open_err:
 42176    winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
 42177    winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
 42178    sqlite3_free(p);
 42179    sqlite3_free(pNew);
 42180    winShmLeaveMutex();
 42181    return rc;
 42182  }
 42183  
 42184  /*
 42185  ** Close a connection to shared-memory.  Delete the underlying
 42186  ** storage if deleteFlag is true.
 42187  */
 42188  static int winShmUnmap(
 42189    sqlite3_file *fd,          /* Database holding shared memory */
 42190    int deleteFlag             /* Delete after closing if true */
 42191  ){
 42192    winFile *pDbFd;       /* Database holding shared-memory */
 42193    winShm *p;            /* The connection to be closed */
 42194    winShmNode *pShmNode; /* The underlying shared-memory file */
 42195    winShm **pp;          /* For looping over sibling connections */
 42196  
 42197    pDbFd = (winFile*)fd;
 42198    p = pDbFd->pShm;
 42199    if( p==0 ) return SQLITE_OK;
 42200    pShmNode = p->pShmNode;
 42201  
 42202    /* Remove connection p from the set of connections associated
 42203    ** with pShmNode */
 42204    sqlite3_mutex_enter(pShmNode->mutex);
 42205    for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
 42206    *pp = p->pNext;
 42207  
 42208    /* Free the connection p */
 42209    sqlite3_free(p);
 42210    pDbFd->pShm = 0;
 42211    sqlite3_mutex_leave(pShmNode->mutex);
 42212  
 42213    /* If pShmNode->nRef has reached 0, then close the underlying
 42214    ** shared-memory file, too */
 42215    winShmEnterMutex();
 42216    assert( pShmNode->nRef>0 );
 42217    pShmNode->nRef--;
 42218    if( pShmNode->nRef==0 ){
 42219      winShmPurge(pDbFd->pVfs, deleteFlag);
 42220    }
 42221    winShmLeaveMutex();
 42222  
 42223    return SQLITE_OK;
 42224  }
 42225  
 42226  /*
 42227  ** Change the lock state for a shared-memory segment.
 42228  */
 42229  static int winShmLock(
 42230    sqlite3_file *fd,          /* Database file holding the shared memory */
 42231    int ofst,                  /* First lock to acquire or release */
 42232    int n,                     /* Number of locks to acquire or release */
 42233    int flags                  /* What to do with the lock */
 42234  ){
 42235    winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
 42236    winShm *p = pDbFd->pShm;              /* The shared memory being locked */
 42237    winShm *pX;                           /* For looping over all siblings */
 42238    winShmNode *pShmNode = p->pShmNode;
 42239    int rc = SQLITE_OK;                   /* Result code */
 42240    u16 mask;                             /* Mask of locks to take or release */
 42241  
 42242    assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
 42243    assert( n>=1 );
 42244    assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
 42245         || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
 42246         || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
 42247         || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
 42248    assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
 42249  
 42250    mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
 42251    assert( n>1 || mask==(1<<ofst) );
 42252    sqlite3_mutex_enter(pShmNode->mutex);
 42253    if( flags & SQLITE_SHM_UNLOCK ){
 42254      u16 allMask = 0; /* Mask of locks held by siblings */
 42255  
 42256      /* See if any siblings hold this same lock */
 42257      for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
 42258        if( pX==p ) continue;
 42259        assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
 42260        allMask |= pX->sharedMask;
 42261      }
 42262  
 42263      /* Unlock the system-level locks */
 42264      if( (mask & allMask)==0 ){
 42265        rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
 42266      }else{
 42267        rc = SQLITE_OK;
 42268      }
 42269  
 42270      /* Undo the local locks */
 42271      if( rc==SQLITE_OK ){
 42272        p->exclMask &= ~mask;
 42273        p->sharedMask &= ~mask;
 42274      }
 42275    }else if( flags & SQLITE_SHM_SHARED ){
 42276      u16 allShared = 0;  /* Union of locks held by connections other than "p" */
 42277  
 42278      /* Find out which shared locks are already held by sibling connections.
 42279      ** If any sibling already holds an exclusive lock, go ahead and return
 42280      ** SQLITE_BUSY.
 42281      */
 42282      for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
 42283        if( (pX->exclMask & mask)!=0 ){
 42284          rc = SQLITE_BUSY;
 42285          break;
 42286        }
 42287        allShared |= pX->sharedMask;
 42288      }
 42289  
 42290      /* Get shared locks at the system level, if necessary */
 42291      if( rc==SQLITE_OK ){
 42292        if( (allShared & mask)==0 ){
 42293          rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
 42294        }else{
 42295          rc = SQLITE_OK;
 42296        }
 42297      }
 42298  
 42299      /* Get the local shared locks */
 42300      if( rc==SQLITE_OK ){
 42301        p->sharedMask |= mask;
 42302      }
 42303    }else{
 42304      /* Make sure no sibling connections hold locks that will block this
 42305      ** lock.  If any do, return SQLITE_BUSY right away.
 42306      */
 42307      for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
 42308        if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
 42309          rc = SQLITE_BUSY;
 42310          break;
 42311        }
 42312      }
 42313  
 42314      /* Get the exclusive locks at the system level.  Then if successful
 42315      ** also mark the local connection as being locked.
 42316      */
 42317      if( rc==SQLITE_OK ){
 42318        rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
 42319        if( rc==SQLITE_OK ){
 42320          assert( (p->sharedMask & mask)==0 );
 42321          p->exclMask |= mask;
 42322        }
 42323      }
 42324    }
 42325    sqlite3_mutex_leave(pShmNode->mutex);
 42326    OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
 42327             osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
 42328             sqlite3ErrName(rc)));
 42329    return rc;
 42330  }
 42331  
 42332  /*
 42333  ** Implement a memory barrier or memory fence on shared memory.
 42334  **
 42335  ** All loads and stores begun before the barrier must complete before
 42336  ** any load or store begun after the barrier.
 42337  */
 42338  static void winShmBarrier(
 42339    sqlite3_file *fd          /* Database holding the shared memory */
 42340  ){
 42341    UNUSED_PARAMETER(fd);
 42342    sqlite3MemoryBarrier();   /* compiler-defined memory barrier */
 42343    winShmEnterMutex();       /* Also mutex, for redundancy */
 42344    winShmLeaveMutex();
 42345  }
 42346  
 42347  /*
 42348  ** This function is called to obtain a pointer to region iRegion of the
 42349  ** shared-memory associated with the database file fd. Shared-memory regions
 42350  ** are numbered starting from zero. Each shared-memory region is szRegion
 42351  ** bytes in size.
 42352  **
 42353  ** If an error occurs, an error code is returned and *pp is set to NULL.
 42354  **
 42355  ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
 42356  ** region has not been allocated (by any client, including one running in a
 42357  ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
 42358  ** isWrite is non-zero and the requested shared-memory region has not yet
 42359  ** been allocated, it is allocated by this function.
 42360  **
 42361  ** If the shared-memory region has already been allocated or is allocated by
 42362  ** this call as described above, then it is mapped into this processes
 42363  ** address space (if it is not already), *pp is set to point to the mapped
 42364  ** memory and SQLITE_OK returned.
 42365  */
 42366  static int winShmMap(
 42367    sqlite3_file *fd,               /* Handle open on database file */
 42368    int iRegion,                    /* Region to retrieve */
 42369    int szRegion,                   /* Size of regions */
 42370    int isWrite,                    /* True to extend file if necessary */
 42371    void volatile **pp              /* OUT: Mapped memory */
 42372  ){
 42373    winFile *pDbFd = (winFile*)fd;
 42374    winShm *pShm = pDbFd->pShm;
 42375    winShmNode *pShmNode;
 42376    int rc = SQLITE_OK;
 42377  
 42378    if( !pShm ){
 42379      rc = winOpenSharedMemory(pDbFd);
 42380      if( rc!=SQLITE_OK ) return rc;
 42381      pShm = pDbFd->pShm;
 42382    }
 42383    pShmNode = pShm->pShmNode;
 42384  
 42385    sqlite3_mutex_enter(pShmNode->mutex);
 42386    assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
 42387  
 42388    if( pShmNode->nRegion<=iRegion ){
 42389      struct ShmRegion *apNew;           /* New aRegion[] array */
 42390      int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
 42391      sqlite3_int64 sz;                  /* Current size of wal-index file */
 42392  
 42393      pShmNode->szRegion = szRegion;
 42394  
 42395      /* The requested region is not mapped into this processes address space.
 42396      ** Check to see if it has been allocated (i.e. if the wal-index file is
 42397      ** large enough to contain the requested region).
 42398      */
 42399      rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
 42400      if( rc!=SQLITE_OK ){
 42401        rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
 42402                         "winShmMap1", pDbFd->zPath);
 42403        goto shmpage_out;
 42404      }
 42405  
 42406      if( sz<nByte ){
 42407        /* The requested memory region does not exist. If isWrite is set to
 42408        ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
 42409        **
 42410        ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
 42411        ** the requested memory region.
 42412        */
 42413        if( !isWrite ) goto shmpage_out;
 42414        rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
 42415        if( rc!=SQLITE_OK ){
 42416          rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
 42417                           "winShmMap2", pDbFd->zPath);
 42418          goto shmpage_out;
 42419        }
 42420      }
 42421  
 42422      /* Map the requested memory region into this processes address space. */
 42423      apNew = (struct ShmRegion *)sqlite3_realloc64(
 42424          pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
 42425      );
 42426      if( !apNew ){
 42427        rc = SQLITE_IOERR_NOMEM_BKPT;
 42428        goto shmpage_out;
 42429      }
 42430      pShmNode->aRegion = apNew;
 42431  
 42432      while( pShmNode->nRegion<=iRegion ){
 42433        HANDLE hMap = NULL;         /* file-mapping handle */
 42434        void *pMap = 0;             /* Mapped memory region */
 42435  
 42436  #if SQLITE_OS_WINRT
 42437        hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
 42438            NULL, PAGE_READWRITE, nByte, NULL
 42439        );
 42440  #elif defined(SQLITE_WIN32_HAS_WIDE)
 42441        hMap = osCreateFileMappingW(pShmNode->hFile.h,
 42442            NULL, PAGE_READWRITE, 0, nByte, NULL
 42443        );
 42444  #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
 42445        hMap = osCreateFileMappingA(pShmNode->hFile.h,
 42446            NULL, PAGE_READWRITE, 0, nByte, NULL
 42447        );
 42448  #endif
 42449        OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
 42450                 osGetCurrentProcessId(), pShmNode->nRegion, nByte,
 42451                 hMap ? "ok" : "failed"));
 42452        if( hMap ){
 42453          int iOffset = pShmNode->nRegion*szRegion;
 42454          int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
 42455  #if SQLITE_OS_WINRT
 42456          pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
 42457              iOffset - iOffsetShift, szRegion + iOffsetShift
 42458          );
 42459  #else
 42460          pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
 42461              0, iOffset - iOffsetShift, szRegion + iOffsetShift
 42462          );
 42463  #endif
 42464          OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
 42465                   osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
 42466                   szRegion, pMap ? "ok" : "failed"));
 42467        }
 42468        if( !pMap ){
 42469          pShmNode->lastErrno = osGetLastError();
 42470          rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
 42471                           "winShmMap3", pDbFd->zPath);
 42472          if( hMap ) osCloseHandle(hMap);
 42473          goto shmpage_out;
 42474        }
 42475  
 42476        pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
 42477        pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
 42478        pShmNode->nRegion++;
 42479      }
 42480    }
 42481  
 42482  shmpage_out:
 42483    if( pShmNode->nRegion>iRegion ){
 42484      int iOffset = iRegion*szRegion;
 42485      int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
 42486      char *p = (char *)pShmNode->aRegion[iRegion].pMap;
 42487      *pp = (void *)&p[iOffsetShift];
 42488    }else{
 42489      *pp = 0;
 42490    }
 42491    sqlite3_mutex_leave(pShmNode->mutex);
 42492    return rc;
 42493  }
 42494  
 42495  #else
 42496  # define winShmMap     0
 42497  # define winShmLock    0
 42498  # define winShmBarrier 0
 42499  # define winShmUnmap   0
 42500  #endif /* #ifndef SQLITE_OMIT_WAL */
 42501  
 42502  /*
 42503  ** Cleans up the mapped region of the specified file, if any.
 42504  */
 42505  #if SQLITE_MAX_MMAP_SIZE>0
 42506  static int winUnmapfile(winFile *pFile){
 42507    assert( pFile!=0 );
 42508    OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
 42509             "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
 42510             osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
 42511             pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
 42512    if( pFile->pMapRegion ){
 42513      if( !osUnmapViewOfFile(pFile->pMapRegion) ){
 42514        pFile->lastErrno = osGetLastError();
 42515        OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
 42516                 "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
 42517                 pFile->pMapRegion));
 42518        return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
 42519                           "winUnmapfile1", pFile->zPath);
 42520      }
 42521      pFile->pMapRegion = 0;
 42522      pFile->mmapSize = 0;
 42523      pFile->mmapSizeActual = 0;
 42524    }
 42525    if( pFile->hMap!=NULL ){
 42526      if( !osCloseHandle(pFile->hMap) ){
 42527        pFile->lastErrno = osGetLastError();
 42528        OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
 42529                 osGetCurrentProcessId(), pFile, pFile->hMap));
 42530        return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
 42531                           "winUnmapfile2", pFile->zPath);
 42532      }
 42533      pFile->hMap = NULL;
 42534    }
 42535    OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
 42536             osGetCurrentProcessId(), pFile));
 42537    return SQLITE_OK;
 42538  }
 42539  
 42540  /*
 42541  ** Memory map or remap the file opened by file-descriptor pFd (if the file
 42542  ** is already mapped, the existing mapping is replaced by the new). Or, if
 42543  ** there already exists a mapping for this file, and there are still
 42544  ** outstanding xFetch() references to it, this function is a no-op.
 42545  **
 42546  ** If parameter nByte is non-negative, then it is the requested size of
 42547  ** the mapping to create. Otherwise, if nByte is less than zero, then the
 42548  ** requested size is the size of the file on disk. The actual size of the
 42549  ** created mapping is either the requested size or the value configured
 42550  ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
 42551  **
 42552  ** SQLITE_OK is returned if no error occurs (even if the mapping is not
 42553  ** recreated as a result of outstanding references) or an SQLite error
 42554  ** code otherwise.
 42555  */
 42556  static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
 42557    sqlite3_int64 nMap = nByte;
 42558    int rc;
 42559  
 42560    assert( nMap>=0 || pFd->nFetchOut==0 );
 42561    OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
 42562             osGetCurrentProcessId(), pFd, nByte));
 42563  
 42564    if( pFd->nFetchOut>0 ) return SQLITE_OK;
 42565  
 42566    if( nMap<0 ){
 42567      rc = winFileSize((sqlite3_file*)pFd, &nMap);
 42568      if( rc ){
 42569        OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
 42570                 osGetCurrentProcessId(), pFd));
 42571        return SQLITE_IOERR_FSTAT;
 42572      }
 42573    }
 42574    if( nMap>pFd->mmapSizeMax ){
 42575      nMap = pFd->mmapSizeMax;
 42576    }
 42577    nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
 42578  
 42579    if( nMap==0 && pFd->mmapSize>0 ){
 42580      winUnmapfile(pFd);
 42581    }
 42582    if( nMap!=pFd->mmapSize ){
 42583      void *pNew = 0;
 42584      DWORD protect = PAGE_READONLY;
 42585      DWORD flags = FILE_MAP_READ;
 42586  
 42587      winUnmapfile(pFd);
 42588  #ifdef SQLITE_MMAP_READWRITE
 42589      if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
 42590        protect = PAGE_READWRITE;
 42591        flags |= FILE_MAP_WRITE;
 42592      }
 42593  #endif
 42594  #if SQLITE_OS_WINRT
 42595      pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
 42596  #elif defined(SQLITE_WIN32_HAS_WIDE)
 42597      pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
 42598                                  (DWORD)((nMap>>32) & 0xffffffff),
 42599                                  (DWORD)(nMap & 0xffffffff), NULL);
 42600  #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
 42601      pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
 42602                                  (DWORD)((nMap>>32) & 0xffffffff),
 42603                                  (DWORD)(nMap & 0xffffffff), NULL);
 42604  #endif
 42605      if( pFd->hMap==NULL ){
 42606        pFd->lastErrno = osGetLastError();
 42607        rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
 42608                         "winMapfile1", pFd->zPath);
 42609        /* Log the error, but continue normal operation using xRead/xWrite */
 42610        OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
 42611                 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
 42612        return SQLITE_OK;
 42613      }
 42614      assert( (nMap % winSysInfo.dwPageSize)==0 );
 42615      assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
 42616  #if SQLITE_OS_WINRT
 42617      pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
 42618  #else
 42619      pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
 42620  #endif
 42621      if( pNew==NULL ){
 42622        osCloseHandle(pFd->hMap);
 42623        pFd->hMap = NULL;
 42624        pFd->lastErrno = osGetLastError();
 42625        rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
 42626                         "winMapfile2", pFd->zPath);
 42627        /* Log the error, but continue normal operation using xRead/xWrite */
 42628        OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
 42629                 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
 42630        return SQLITE_OK;
 42631      }
 42632      pFd->pMapRegion = pNew;
 42633      pFd->mmapSize = nMap;
 42634      pFd->mmapSizeActual = nMap;
 42635    }
 42636  
 42637    OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
 42638             osGetCurrentProcessId(), pFd));
 42639    return SQLITE_OK;
 42640  }
 42641  #endif /* SQLITE_MAX_MMAP_SIZE>0 */
 42642  
 42643  /*
 42644  ** If possible, return a pointer to a mapping of file fd starting at offset
 42645  ** iOff. The mapping must be valid for at least nAmt bytes.
 42646  **
 42647  ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
 42648  ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
 42649  ** Finally, if an error does occur, return an SQLite error code. The final
 42650  ** value of *pp is undefined in this case.
 42651  **
 42652  ** If this function does return a pointer, the caller must eventually
 42653  ** release the reference by calling winUnfetch().
 42654  */
 42655  static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
 42656  #if SQLITE_MAX_MMAP_SIZE>0
 42657    winFile *pFd = (winFile*)fd;   /* The underlying database file */
 42658  #endif
 42659    *pp = 0;
 42660  
 42661    OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
 42662             osGetCurrentProcessId(), fd, iOff, nAmt, pp));
 42663  
 42664  #if SQLITE_MAX_MMAP_SIZE>0
 42665    if( pFd->mmapSizeMax>0 ){
 42666      if( pFd->pMapRegion==0 ){
 42667        int rc = winMapfile(pFd, -1);
 42668        if( rc!=SQLITE_OK ){
 42669          OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
 42670                   osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
 42671          return rc;
 42672        }
 42673      }
 42674      if( pFd->mmapSize >= iOff+nAmt ){
 42675        *pp = &((u8 *)pFd->pMapRegion)[iOff];
 42676        pFd->nFetchOut++;
 42677      }
 42678    }
 42679  #endif
 42680  
 42681    OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
 42682             osGetCurrentProcessId(), fd, pp, *pp));
 42683    return SQLITE_OK;
 42684  }
 42685  
 42686  /*
 42687  ** If the third argument is non-NULL, then this function releases a
 42688  ** reference obtained by an earlier call to winFetch(). The second
 42689  ** argument passed to this function must be the same as the corresponding
 42690  ** argument that was passed to the winFetch() invocation.
 42691  **
 42692  ** Or, if the third argument is NULL, then this function is being called
 42693  ** to inform the VFS layer that, according to POSIX, any existing mapping
 42694  ** may now be invalid and should be unmapped.
 42695  */
 42696  static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
 42697  #if SQLITE_MAX_MMAP_SIZE>0
 42698    winFile *pFd = (winFile*)fd;   /* The underlying database file */
 42699  
 42700    /* If p==0 (unmap the entire file) then there must be no outstanding
 42701    ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
 42702    ** then there must be at least one outstanding.  */
 42703    assert( (p==0)==(pFd->nFetchOut==0) );
 42704  
 42705    /* If p!=0, it must match the iOff value. */
 42706    assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
 42707  
 42708    OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
 42709             osGetCurrentProcessId(), pFd, iOff, p));
 42710  
 42711    if( p ){
 42712      pFd->nFetchOut--;
 42713    }else{
 42714      /* FIXME:  If Windows truly always prevents truncating or deleting a
 42715      ** file while a mapping is held, then the following winUnmapfile() call
 42716      ** is unnecessary can be omitted - potentially improving
 42717      ** performance.  */
 42718      winUnmapfile(pFd);
 42719    }
 42720  
 42721    assert( pFd->nFetchOut>=0 );
 42722  #endif
 42723  
 42724    OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
 42725             osGetCurrentProcessId(), fd));
 42726    return SQLITE_OK;
 42727  }
 42728  
 42729  /*
 42730  ** Here ends the implementation of all sqlite3_file methods.
 42731  **
 42732  ********************** End sqlite3_file Methods *******************************
 42733  ******************************************************************************/
 42734  
 42735  /*
 42736  ** This vector defines all the methods that can operate on an
 42737  ** sqlite3_file for win32.
 42738  */
 42739  static const sqlite3_io_methods winIoMethod = {
 42740    3,                              /* iVersion */
 42741    winClose,                       /* xClose */
 42742    winRead,                        /* xRead */
 42743    winWrite,                       /* xWrite */
 42744    winTruncate,                    /* xTruncate */
 42745    winSync,                        /* xSync */
 42746    winFileSize,                    /* xFileSize */
 42747    winLock,                        /* xLock */
 42748    winUnlock,                      /* xUnlock */
 42749    winCheckReservedLock,           /* xCheckReservedLock */
 42750    winFileControl,                 /* xFileControl */
 42751    winSectorSize,                  /* xSectorSize */
 42752    winDeviceCharacteristics,       /* xDeviceCharacteristics */
 42753    winShmMap,                      /* xShmMap */
 42754    winShmLock,                     /* xShmLock */
 42755    winShmBarrier,                  /* xShmBarrier */
 42756    winShmUnmap,                    /* xShmUnmap */
 42757    winFetch,                       /* xFetch */
 42758    winUnfetch                      /* xUnfetch */
 42759  };
 42760  
 42761  /*
 42762  ** This vector defines all the methods that can operate on an
 42763  ** sqlite3_file for win32 without performing any locking.
 42764  */
 42765  static const sqlite3_io_methods winIoNolockMethod = {
 42766    3,                              /* iVersion */
 42767    winClose,                       /* xClose */
 42768    winRead,                        /* xRead */
 42769    winWrite,                       /* xWrite */
 42770    winTruncate,                    /* xTruncate */
 42771    winSync,                        /* xSync */
 42772    winFileSize,                    /* xFileSize */
 42773    winNolockLock,                  /* xLock */
 42774    winNolockUnlock,                /* xUnlock */
 42775    winNolockCheckReservedLock,     /* xCheckReservedLock */
 42776    winFileControl,                 /* xFileControl */
 42777    winSectorSize,                  /* xSectorSize */
 42778    winDeviceCharacteristics,       /* xDeviceCharacteristics */
 42779    winShmMap,                      /* xShmMap */
 42780    winShmLock,                     /* xShmLock */
 42781    winShmBarrier,                  /* xShmBarrier */
 42782    winShmUnmap,                    /* xShmUnmap */
 42783    winFetch,                       /* xFetch */
 42784    winUnfetch                      /* xUnfetch */
 42785  };
 42786  
 42787  static winVfsAppData winAppData = {
 42788    &winIoMethod,       /* pMethod */
 42789    0,                  /* pAppData */
 42790    0                   /* bNoLock */
 42791  };
 42792  
 42793  static winVfsAppData winNolockAppData = {
 42794    &winIoNolockMethod, /* pMethod */
 42795    0,                  /* pAppData */
 42796    1                   /* bNoLock */
 42797  };
 42798  
 42799  /****************************************************************************
 42800  **************************** sqlite3_vfs methods ****************************
 42801  **
 42802  ** This division contains the implementation of methods on the
 42803  ** sqlite3_vfs object.
 42804  */
 42805  
 42806  #if defined(__CYGWIN__)
 42807  /*
 42808  ** Convert a filename from whatever the underlying operating system
 42809  ** supports for filenames into UTF-8.  Space to hold the result is
 42810  ** obtained from malloc and must be freed by the calling function.
 42811  */
 42812  static char *winConvertToUtf8Filename(const void *zFilename){
 42813    char *zConverted = 0;
 42814    if( osIsNT() ){
 42815      zConverted = winUnicodeToUtf8(zFilename);
 42816    }
 42817  #ifdef SQLITE_WIN32_HAS_ANSI
 42818    else{
 42819      zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
 42820    }
 42821  #endif
 42822    /* caller will handle out of memory */
 42823    return zConverted;
 42824  }
 42825  #endif
 42826  
 42827  /*
 42828  ** Convert a UTF-8 filename into whatever form the underlying
 42829  ** operating system wants filenames in.  Space to hold the result
 42830  ** is obtained from malloc and must be freed by the calling
 42831  ** function.
 42832  */
 42833  static void *winConvertFromUtf8Filename(const char *zFilename){
 42834    void *zConverted = 0;
 42835    if( osIsNT() ){
 42836      zConverted = winUtf8ToUnicode(zFilename);
 42837    }
 42838  #ifdef SQLITE_WIN32_HAS_ANSI
 42839    else{
 42840      zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
 42841    }
 42842  #endif
 42843    /* caller will handle out of memory */
 42844    return zConverted;
 42845  }
 42846  
 42847  /*
 42848  ** This function returns non-zero if the specified UTF-8 string buffer
 42849  ** ends with a directory separator character or one was successfully
 42850  ** added to it.
 42851  */
 42852  static int winMakeEndInDirSep(int nBuf, char *zBuf){
 42853    if( zBuf ){
 42854      int nLen = sqlite3Strlen30(zBuf);
 42855      if( nLen>0 ){
 42856        if( winIsDirSep(zBuf[nLen-1]) ){
 42857          return 1;
 42858        }else if( nLen+1<nBuf ){
 42859          zBuf[nLen] = winGetDirSep();
 42860          zBuf[nLen+1] = '\0';
 42861          return 1;
 42862        }
 42863      }
 42864    }
 42865    return 0;
 42866  }
 42867  
 42868  /*
 42869  ** Create a temporary file name and store the resulting pointer into pzBuf.
 42870  ** The pointer returned in pzBuf must be freed via sqlite3_free().
 42871  */
 42872  static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
 42873    static char zChars[] =
 42874      "abcdefghijklmnopqrstuvwxyz"
 42875      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 42876      "0123456789";
 42877    size_t i, j;
 42878    int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
 42879    int nMax, nBuf, nDir, nLen;
 42880    char *zBuf;
 42881  
 42882    /* It's odd to simulate an io-error here, but really this is just
 42883    ** using the io-error infrastructure to test that SQLite handles this
 42884    ** function failing.
 42885    */
 42886    SimulateIOError( return SQLITE_IOERR );
 42887  
 42888    /* Allocate a temporary buffer to store the fully qualified file
 42889    ** name for the temporary file.  If this fails, we cannot continue.
 42890    */
 42891    nMax = pVfs->mxPathname; nBuf = nMax + 2;
 42892    zBuf = sqlite3MallocZero( nBuf );
 42893    if( !zBuf ){
 42894      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 42895      return SQLITE_IOERR_NOMEM_BKPT;
 42896    }
 42897  
 42898    /* Figure out the effective temporary directory.  First, check if one
 42899    ** has been explicitly set by the application; otherwise, use the one
 42900    ** configured by the operating system.
 42901    */
 42902    nDir = nMax - (nPre + 15);
 42903    assert( nDir>0 );
 42904    if( sqlite3_temp_directory ){
 42905      int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
 42906      if( nDirLen>0 ){
 42907        if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
 42908          nDirLen++;
 42909        }
 42910        if( nDirLen>nDir ){
 42911          sqlite3_free(zBuf);
 42912          OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
 42913          return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
 42914        }
 42915        sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
 42916      }
 42917    }
 42918  #if defined(__CYGWIN__)
 42919    else{
 42920      static const char *azDirs[] = {
 42921         0, /* getenv("SQLITE_TMPDIR") */
 42922         0, /* getenv("TMPDIR") */
 42923         0, /* getenv("TMP") */
 42924         0, /* getenv("TEMP") */
 42925         0, /* getenv("USERPROFILE") */
 42926         "/var/tmp",
 42927         "/usr/tmp",
 42928         "/tmp",
 42929         ".",
 42930         0        /* List terminator */
 42931      };
 42932      unsigned int i;
 42933      const char *zDir = 0;
 42934  
 42935      if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
 42936      if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
 42937      if( !azDirs[2] ) azDirs[2] = getenv("TMP");
 42938      if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
 42939      if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
 42940      for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
 42941        void *zConverted;
 42942        if( zDir==0 ) continue;
 42943        /* If the path starts with a drive letter followed by the colon
 42944        ** character, assume it is already a native Win32 path; otherwise,
 42945        ** it must be converted to a native Win32 path via the Cygwin API
 42946        ** prior to using it.
 42947        */
 42948        if( winIsDriveLetterAndColon(zDir) ){
 42949          zConverted = winConvertFromUtf8Filename(zDir);
 42950          if( !zConverted ){
 42951            sqlite3_free(zBuf);
 42952            OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 42953            return SQLITE_IOERR_NOMEM_BKPT;
 42954          }
 42955          if( winIsDir(zConverted) ){
 42956            sqlite3_snprintf(nMax, zBuf, "%s", zDir);
 42957            sqlite3_free(zConverted);
 42958            break;
 42959          }
 42960          sqlite3_free(zConverted);
 42961        }else{
 42962          zConverted = sqlite3MallocZero( nMax+1 );
 42963          if( !zConverted ){
 42964            sqlite3_free(zBuf);
 42965            OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 42966            return SQLITE_IOERR_NOMEM_BKPT;
 42967          }
 42968          if( cygwin_conv_path(
 42969                  osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
 42970                  zConverted, nMax+1)<0 ){
 42971            sqlite3_free(zConverted);
 42972            sqlite3_free(zBuf);
 42973            OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
 42974            return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
 42975                               "winGetTempname2", zDir);
 42976          }
 42977          if( winIsDir(zConverted) ){
 42978            /* At this point, we know the candidate directory exists and should
 42979            ** be used.  However, we may need to convert the string containing
 42980            ** its name into UTF-8 (i.e. if it is UTF-16 right now).
 42981            */
 42982            char *zUtf8 = winConvertToUtf8Filename(zConverted);
 42983            if( !zUtf8 ){
 42984              sqlite3_free(zConverted);
 42985              sqlite3_free(zBuf);
 42986              OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 42987              return SQLITE_IOERR_NOMEM_BKPT;
 42988            }
 42989            sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
 42990            sqlite3_free(zUtf8);
 42991            sqlite3_free(zConverted);
 42992            break;
 42993          }
 42994          sqlite3_free(zConverted);
 42995        }
 42996      }
 42997    }
 42998  #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
 42999    else if( osIsNT() ){
 43000      char *zMulti;
 43001      LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
 43002      if( !zWidePath ){
 43003        sqlite3_free(zBuf);
 43004        OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 43005        return SQLITE_IOERR_NOMEM_BKPT;
 43006      }
 43007      if( osGetTempPathW(nMax, zWidePath)==0 ){
 43008        sqlite3_free(zWidePath);
 43009        sqlite3_free(zBuf);
 43010        OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
 43011        return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
 43012                           "winGetTempname2", 0);
 43013      }
 43014      zMulti = winUnicodeToUtf8(zWidePath);
 43015      if( zMulti ){
 43016        sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
 43017        sqlite3_free(zMulti);
 43018        sqlite3_free(zWidePath);
 43019      }else{
 43020        sqlite3_free(zWidePath);
 43021        sqlite3_free(zBuf);
 43022        OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 43023        return SQLITE_IOERR_NOMEM_BKPT;
 43024      }
 43025    }
 43026  #ifdef SQLITE_WIN32_HAS_ANSI
 43027    else{
 43028      char *zUtf8;
 43029      char *zMbcsPath = sqlite3MallocZero( nMax );
 43030      if( !zMbcsPath ){
 43031        sqlite3_free(zBuf);
 43032        OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 43033        return SQLITE_IOERR_NOMEM_BKPT;
 43034      }
 43035      if( osGetTempPathA(nMax, zMbcsPath)==0 ){
 43036        sqlite3_free(zBuf);
 43037        OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
 43038        return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
 43039                           "winGetTempname3", 0);
 43040      }
 43041      zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
 43042      if( zUtf8 ){
 43043        sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
 43044        sqlite3_free(zUtf8);
 43045      }else{
 43046        sqlite3_free(zBuf);
 43047        OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 43048        return SQLITE_IOERR_NOMEM_BKPT;
 43049      }
 43050    }
 43051  #endif /* SQLITE_WIN32_HAS_ANSI */
 43052  #endif /* !SQLITE_OS_WINRT */
 43053  
 43054    /*
 43055    ** Check to make sure the temporary directory ends with an appropriate
 43056    ** separator.  If it does not and there is not enough space left to add
 43057    ** one, fail.
 43058    */
 43059    if( !winMakeEndInDirSep(nDir+1, zBuf) ){
 43060      sqlite3_free(zBuf);
 43061      OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
 43062      return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
 43063    }
 43064  
 43065    /*
 43066    ** Check that the output buffer is large enough for the temporary file
 43067    ** name in the following format:
 43068    **
 43069    **   "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
 43070    **
 43071    ** If not, return SQLITE_ERROR.  The number 17 is used here in order to
 43072    ** account for the space used by the 15 character random suffix and the
 43073    ** two trailing NUL characters.  The final directory separator character
 43074    ** has already added if it was not already present.
 43075    */
 43076    nLen = sqlite3Strlen30(zBuf);
 43077    if( (nLen + nPre + 17) > nBuf ){
 43078      sqlite3_free(zBuf);
 43079      OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
 43080      return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
 43081    }
 43082  
 43083    sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
 43084  
 43085    j = sqlite3Strlen30(zBuf);
 43086    sqlite3_randomness(15, &zBuf[j]);
 43087    for(i=0; i<15; i++, j++){
 43088      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
 43089    }
 43090    zBuf[j] = 0;
 43091    zBuf[j+1] = 0;
 43092    *pzBuf = zBuf;
 43093  
 43094    OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
 43095    return SQLITE_OK;
 43096  }
 43097  
 43098  /*
 43099  ** Return TRUE if the named file is really a directory.  Return false if
 43100  ** it is something other than a directory, or if there is any kind of memory
 43101  ** allocation failure.
 43102  */
 43103  static int winIsDir(const void *zConverted){
 43104    DWORD attr;
 43105    int rc = 0;
 43106    DWORD lastErrno;
 43107  
 43108    if( osIsNT() ){
 43109      int cnt = 0;
 43110      WIN32_FILE_ATTRIBUTE_DATA sAttrData;
 43111      memset(&sAttrData, 0, sizeof(sAttrData));
 43112      while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
 43113                               GetFileExInfoStandard,
 43114                               &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
 43115      if( !rc ){
 43116        return 0; /* Invalid name? */
 43117      }
 43118      attr = sAttrData.dwFileAttributes;
 43119  #if SQLITE_OS_WINCE==0
 43120    }else{
 43121      attr = osGetFileAttributesA((char*)zConverted);
 43122  #endif
 43123    }
 43124    return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
 43125  }
 43126  
 43127  /* forward reference */
 43128  static int winAccess(
 43129    sqlite3_vfs *pVfs,         /* Not used on win32 */
 43130    const char *zFilename,     /* Name of file to check */
 43131    int flags,                 /* Type of test to make on this file */
 43132    int *pResOut               /* OUT: Result */
 43133  );
 43134  
 43135  /*
 43136  ** Open a file.
 43137  */
 43138  static int winOpen(
 43139    sqlite3_vfs *pVfs,        /* Used to get maximum path length and AppData */
 43140    const char *zName,        /* Name of the file (UTF-8) */
 43141    sqlite3_file *id,         /* Write the SQLite file handle here */
 43142    int flags,                /* Open mode flags */
 43143    int *pOutFlags            /* Status return flags */
 43144  ){
 43145    HANDLE h;
 43146    DWORD lastErrno = 0;
 43147    DWORD dwDesiredAccess;
 43148    DWORD dwShareMode;
 43149    DWORD dwCreationDisposition;
 43150    DWORD dwFlagsAndAttributes = 0;
 43151  #if SQLITE_OS_WINCE
 43152    int isTemp = 0;
 43153  #endif
 43154    winVfsAppData *pAppData;
 43155    winFile *pFile = (winFile*)id;
 43156    void *zConverted;              /* Filename in OS encoding */
 43157    const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
 43158    int cnt = 0;
 43159  
 43160    /* If argument zPath is a NULL pointer, this function is required to open
 43161    ** a temporary file. Use this buffer to store the file name in.
 43162    */
 43163    char *zTmpname = 0; /* For temporary filename, if necessary. */
 43164  
 43165    int rc = SQLITE_OK;            /* Function Return Code */
 43166  #if !defined(NDEBUG) || SQLITE_OS_WINCE
 43167    int eType = flags&0xFFFFFF00;  /* Type of file to open */
 43168  #endif
 43169  
 43170    int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
 43171    int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
 43172    int isCreate     = (flags & SQLITE_OPEN_CREATE);
 43173    int isReadonly   = (flags & SQLITE_OPEN_READONLY);
 43174    int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
 43175  
 43176  #ifndef NDEBUG
 43177    int isOpenJournal = (isCreate && (
 43178          eType==SQLITE_OPEN_MASTER_JOURNAL
 43179       || eType==SQLITE_OPEN_MAIN_JOURNAL
 43180       || eType==SQLITE_OPEN_WAL
 43181    ));
 43182  #endif
 43183  
 43184    OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
 43185             zUtf8Name, id, flags, pOutFlags));
 43186  
 43187    /* Check the following statements are true:
 43188    **
 43189    **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
 43190    **   (b) if CREATE is set, then READWRITE must also be set, and
 43191    **   (c) if EXCLUSIVE is set, then CREATE must also be set.
 43192    **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
 43193    */
 43194    assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
 43195    assert(isCreate==0 || isReadWrite);
 43196    assert(isExclusive==0 || isCreate);
 43197    assert(isDelete==0 || isCreate);
 43198  
 43199    /* The main DB, main journal, WAL file and master journal are never
 43200    ** automatically deleted. Nor are they ever temporary files.  */
 43201    assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
 43202    assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
 43203    assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
 43204    assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
 43205  
 43206    /* Assert that the upper layer has set one of the "file-type" flags. */
 43207    assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
 43208         || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
 43209         || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
 43210         || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
 43211    );
 43212  
 43213    assert( pFile!=0 );
 43214    memset(pFile, 0, sizeof(winFile));
 43215    pFile->h = INVALID_HANDLE_VALUE;
 43216  
 43217  #if SQLITE_OS_WINRT
 43218    if( !zUtf8Name && !sqlite3_temp_directory ){
 43219      sqlite3_log(SQLITE_ERROR,
 43220          "sqlite3_temp_directory variable should be set for WinRT");
 43221    }
 43222  #endif
 43223  
 43224    /* If the second argument to this function is NULL, generate a
 43225    ** temporary file name to use
 43226    */
 43227    if( !zUtf8Name ){
 43228      assert( isDelete && !isOpenJournal );
 43229      rc = winGetTempname(pVfs, &zTmpname);
 43230      if( rc!=SQLITE_OK ){
 43231        OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
 43232        return rc;
 43233      }
 43234      zUtf8Name = zTmpname;
 43235    }
 43236  
 43237    /* Database filenames are double-zero terminated if they are not
 43238    ** URIs with parameters.  Hence, they can always be passed into
 43239    ** sqlite3_uri_parameter().
 43240    */
 43241    assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
 43242         zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
 43243  
 43244    /* Convert the filename to the system encoding. */
 43245    zConverted = winConvertFromUtf8Filename(zUtf8Name);
 43246    if( zConverted==0 ){
 43247      sqlite3_free(zTmpname);
 43248      OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
 43249      return SQLITE_IOERR_NOMEM_BKPT;
 43250    }
 43251  
 43252    if( winIsDir(zConverted) ){
 43253      sqlite3_free(zConverted);
 43254      sqlite3_free(zTmpname);
 43255      OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
 43256      return SQLITE_CANTOPEN_ISDIR;
 43257    }
 43258  
 43259    if( isReadWrite ){
 43260      dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
 43261    }else{
 43262      dwDesiredAccess = GENERIC_READ;
 43263    }
 43264  
 43265    /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
 43266    ** created. SQLite doesn't use it to indicate "exclusive access"
 43267    ** as it is usually understood.
 43268    */
 43269    if( isExclusive ){
 43270      /* Creates a new file, only if it does not already exist. */
 43271      /* If the file exists, it fails. */
 43272      dwCreationDisposition = CREATE_NEW;
 43273    }else if( isCreate ){
 43274      /* Open existing file, or create if it doesn't exist */
 43275      dwCreationDisposition = OPEN_ALWAYS;
 43276    }else{
 43277      /* Opens a file, only if it exists. */
 43278      dwCreationDisposition = OPEN_EXISTING;
 43279    }
 43280  
 43281    dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
 43282  
 43283    if( isDelete ){
 43284  #if SQLITE_OS_WINCE
 43285      dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
 43286      isTemp = 1;
 43287  #else
 43288      dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
 43289                                 | FILE_ATTRIBUTE_HIDDEN
 43290                                 | FILE_FLAG_DELETE_ON_CLOSE;
 43291  #endif
 43292    }else{
 43293      dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
 43294    }
 43295    /* Reports from the internet are that performance is always
 43296    ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
 43297  #if SQLITE_OS_WINCE
 43298    dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
 43299  #endif
 43300  
 43301    if( osIsNT() ){
 43302  #if SQLITE_OS_WINRT
 43303      CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
 43304      extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
 43305      extendedParameters.dwFileAttributes =
 43306              dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
 43307      extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
 43308      extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
 43309      extendedParameters.lpSecurityAttributes = NULL;
 43310      extendedParameters.hTemplateFile = NULL;
 43311      do{
 43312        h = osCreateFile2((LPCWSTR)zConverted,
 43313                          dwDesiredAccess,
 43314                          dwShareMode,
 43315                          dwCreationDisposition,
 43316                          &extendedParameters);
 43317        if( h!=INVALID_HANDLE_VALUE ) break;
 43318        if( isReadWrite ){
 43319          int isRO = 0;
 43320          int rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
 43321          if( rc2==SQLITE_OK && isRO ) break;
 43322        }
 43323      }while( winRetryIoerr(&cnt, &lastErrno) );
 43324  #else
 43325      do{
 43326        h = osCreateFileW((LPCWSTR)zConverted,
 43327                          dwDesiredAccess,
 43328                          dwShareMode, NULL,
 43329                          dwCreationDisposition,
 43330                          dwFlagsAndAttributes,
 43331                          NULL);
 43332        if( h!=INVALID_HANDLE_VALUE ) break;
 43333        if( isReadWrite ){
 43334          int isRO = 0;
 43335          int rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
 43336          if( rc2==SQLITE_OK && isRO ) break;
 43337        }
 43338      }while( winRetryIoerr(&cnt, &lastErrno) );
 43339  #endif
 43340    }
 43341  #ifdef SQLITE_WIN32_HAS_ANSI
 43342    else{
 43343      do{
 43344        h = osCreateFileA((LPCSTR)zConverted,
 43345                          dwDesiredAccess,
 43346                          dwShareMode, NULL,
 43347                          dwCreationDisposition,
 43348                          dwFlagsAndAttributes,
 43349                          NULL);
 43350        if( h!=INVALID_HANDLE_VALUE ) break;
 43351        if( isReadWrite ){
 43352          int isRO = 0;
 43353          int rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
 43354          if( rc2==SQLITE_OK && isRO ) break;
 43355        }
 43356      }while( winRetryIoerr(&cnt, &lastErrno) );
 43357    }
 43358  #endif
 43359    winLogIoerr(cnt, __LINE__);
 43360  
 43361    OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
 43362             dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
 43363  
 43364    if( h==INVALID_HANDLE_VALUE ){
 43365      sqlite3_free(zConverted);
 43366      sqlite3_free(zTmpname);
 43367      if( isReadWrite && !isExclusive ){
 43368        return winOpen(pVfs, zName, id,
 43369           ((flags|SQLITE_OPEN_READONLY) &
 43370                       ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
 43371           pOutFlags);
 43372      }else{
 43373        pFile->lastErrno = lastErrno;
 43374        winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
 43375        return SQLITE_CANTOPEN_BKPT;
 43376      }
 43377    }
 43378  
 43379    if( pOutFlags ){
 43380      if( isReadWrite ){
 43381        *pOutFlags = SQLITE_OPEN_READWRITE;
 43382      }else{
 43383        *pOutFlags = SQLITE_OPEN_READONLY;
 43384      }
 43385    }
 43386  
 43387    OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
 43388             "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
 43389             *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
 43390  
 43391    pAppData = (winVfsAppData*)pVfs->pAppData;
 43392  
 43393  #if SQLITE_OS_WINCE
 43394    {
 43395      if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
 43396           && ((pAppData==NULL) || !pAppData->bNoLock)
 43397           && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
 43398      ){
 43399        osCloseHandle(h);
 43400        sqlite3_free(zConverted);
 43401        sqlite3_free(zTmpname);
 43402        OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
 43403        return rc;
 43404      }
 43405    }
 43406    if( isTemp ){
 43407      pFile->zDeleteOnClose = zConverted;
 43408    }else
 43409  #endif
 43410    {
 43411      sqlite3_free(zConverted);
 43412    }
 43413  
 43414    sqlite3_free(zTmpname);
 43415    pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
 43416    pFile->pVfs = pVfs;
 43417    pFile->h = h;
 43418    if( isReadonly ){
 43419      pFile->ctrlFlags |= WINFILE_RDONLY;
 43420    }
 43421    if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
 43422      pFile->ctrlFlags |= WINFILE_PSOW;
 43423    }
 43424    pFile->lastErrno = NO_ERROR;
 43425    pFile->zPath = zName;
 43426  #if SQLITE_MAX_MMAP_SIZE>0
 43427    pFile->hMap = NULL;
 43428    pFile->pMapRegion = 0;
 43429    pFile->mmapSize = 0;
 43430    pFile->mmapSizeActual = 0;
 43431    pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
 43432  #endif
 43433  
 43434    OpenCounter(+1);
 43435    return rc;
 43436  }
 43437  
 43438  /*
 43439  ** Delete the named file.
 43440  **
 43441  ** Note that Windows does not allow a file to be deleted if some other
 43442  ** process has it open.  Sometimes a virus scanner or indexing program
 43443  ** will open a journal file shortly after it is created in order to do
 43444  ** whatever it does.  While this other process is holding the
 43445  ** file open, we will be unable to delete it.  To work around this
 43446  ** problem, we delay 100 milliseconds and try to delete again.  Up
 43447  ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
 43448  ** up and returning an error.
 43449  */
 43450  static int winDelete(
 43451    sqlite3_vfs *pVfs,          /* Not used on win32 */
 43452    const char *zFilename,      /* Name of file to delete */
 43453    int syncDir                 /* Not used on win32 */
 43454  ){
 43455    int cnt = 0;
 43456    int rc;
 43457    DWORD attr;
 43458    DWORD lastErrno = 0;
 43459    void *zConverted;
 43460    UNUSED_PARAMETER(pVfs);
 43461    UNUSED_PARAMETER(syncDir);
 43462  
 43463    SimulateIOError(return SQLITE_IOERR_DELETE);
 43464    OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
 43465  
 43466    zConverted = winConvertFromUtf8Filename(zFilename);
 43467    if( zConverted==0 ){
 43468      OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
 43469      return SQLITE_IOERR_NOMEM_BKPT;
 43470    }
 43471    if( osIsNT() ){
 43472      do {
 43473  #if SQLITE_OS_WINRT
 43474        WIN32_FILE_ATTRIBUTE_DATA sAttrData;
 43475        memset(&sAttrData, 0, sizeof(sAttrData));
 43476        if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
 43477                                    &sAttrData) ){
 43478          attr = sAttrData.dwFileAttributes;
 43479        }else{
 43480          lastErrno = osGetLastError();
 43481          if( lastErrno==ERROR_FILE_NOT_FOUND
 43482           || lastErrno==ERROR_PATH_NOT_FOUND ){
 43483            rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
 43484          }else{
 43485            rc = SQLITE_ERROR;
 43486          }
 43487          break;
 43488        }
 43489  #else
 43490        attr = osGetFileAttributesW(zConverted);
 43491  #endif
 43492        if ( attr==INVALID_FILE_ATTRIBUTES ){
 43493          lastErrno = osGetLastError();
 43494          if( lastErrno==ERROR_FILE_NOT_FOUND
 43495           || lastErrno==ERROR_PATH_NOT_FOUND ){
 43496            rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
 43497          }else{
 43498            rc = SQLITE_ERROR;
 43499          }
 43500          break;
 43501        }
 43502        if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
 43503          rc = SQLITE_ERROR; /* Files only. */
 43504          break;
 43505        }
 43506        if ( osDeleteFileW(zConverted) ){
 43507          rc = SQLITE_OK; /* Deleted OK. */
 43508          break;
 43509        }
 43510        if ( !winRetryIoerr(&cnt, &lastErrno) ){
 43511          rc = SQLITE_ERROR; /* No more retries. */
 43512          break;
 43513        }
 43514      } while(1);
 43515    }
 43516  #ifdef SQLITE_WIN32_HAS_ANSI
 43517    else{
 43518      do {
 43519        attr = osGetFileAttributesA(zConverted);
 43520        if ( attr==INVALID_FILE_ATTRIBUTES ){
 43521          lastErrno = osGetLastError();
 43522          if( lastErrno==ERROR_FILE_NOT_FOUND
 43523           || lastErrno==ERROR_PATH_NOT_FOUND ){
 43524            rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
 43525          }else{
 43526            rc = SQLITE_ERROR;
 43527          }
 43528          break;
 43529        }
 43530        if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
 43531          rc = SQLITE_ERROR; /* Files only. */
 43532          break;
 43533        }
 43534        if ( osDeleteFileA(zConverted) ){
 43535          rc = SQLITE_OK; /* Deleted OK. */
 43536          break;
 43537        }
 43538        if ( !winRetryIoerr(&cnt, &lastErrno) ){
 43539          rc = SQLITE_ERROR; /* No more retries. */
 43540          break;
 43541        }
 43542      } while(1);
 43543    }
 43544  #endif
 43545    if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
 43546      rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
 43547    }else{
 43548      winLogIoerr(cnt, __LINE__);
 43549    }
 43550    sqlite3_free(zConverted);
 43551    OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
 43552    return rc;
 43553  }
 43554  
 43555  /*
 43556  ** Check the existence and status of a file.
 43557  */
 43558  static int winAccess(
 43559    sqlite3_vfs *pVfs,         /* Not used on win32 */
 43560    const char *zFilename,     /* Name of file to check */
 43561    int flags,                 /* Type of test to make on this file */
 43562    int *pResOut               /* OUT: Result */
 43563  ){
 43564    DWORD attr;
 43565    int rc = 0;
 43566    DWORD lastErrno = 0;
 43567    void *zConverted;
 43568    UNUSED_PARAMETER(pVfs);
 43569  
 43570    SimulateIOError( return SQLITE_IOERR_ACCESS; );
 43571    OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
 43572             zFilename, flags, pResOut));
 43573  
 43574    zConverted = winConvertFromUtf8Filename(zFilename);
 43575    if( zConverted==0 ){
 43576      OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
 43577      return SQLITE_IOERR_NOMEM_BKPT;
 43578    }
 43579    if( osIsNT() ){
 43580      int cnt = 0;
 43581      WIN32_FILE_ATTRIBUTE_DATA sAttrData;
 43582      memset(&sAttrData, 0, sizeof(sAttrData));
 43583      while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
 43584                               GetFileExInfoStandard,
 43585                               &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
 43586      if( rc ){
 43587        /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
 43588        ** as if it does not exist.
 43589        */
 43590        if(    flags==SQLITE_ACCESS_EXISTS
 43591            && sAttrData.nFileSizeHigh==0
 43592            && sAttrData.nFileSizeLow==0 ){
 43593          attr = INVALID_FILE_ATTRIBUTES;
 43594        }else{
 43595          attr = sAttrData.dwFileAttributes;
 43596        }
 43597      }else{
 43598        winLogIoerr(cnt, __LINE__);
 43599        if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
 43600          sqlite3_free(zConverted);
 43601          return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
 43602                             zFilename);
 43603        }else{
 43604          attr = INVALID_FILE_ATTRIBUTES;
 43605        }
 43606      }
 43607    }
 43608  #ifdef SQLITE_WIN32_HAS_ANSI
 43609    else{
 43610      attr = osGetFileAttributesA((char*)zConverted);
 43611    }
 43612  #endif
 43613    sqlite3_free(zConverted);
 43614    switch( flags ){
 43615      case SQLITE_ACCESS_READ:
 43616      case SQLITE_ACCESS_EXISTS:
 43617        rc = attr!=INVALID_FILE_ATTRIBUTES;
 43618        break;
 43619      case SQLITE_ACCESS_READWRITE:
 43620        rc = attr!=INVALID_FILE_ATTRIBUTES &&
 43621               (attr & FILE_ATTRIBUTE_READONLY)==0;
 43622        break;
 43623      default:
 43624        assert(!"Invalid flags argument");
 43625    }
 43626    *pResOut = rc;
 43627    OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
 43628             zFilename, pResOut, *pResOut));
 43629    return SQLITE_OK;
 43630  }
 43631  
 43632  /*
 43633  ** Returns non-zero if the specified path name starts with a drive letter
 43634  ** followed by a colon character.
 43635  */
 43636  static BOOL winIsDriveLetterAndColon(
 43637    const char *zPathname
 43638  ){
 43639    return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
 43640  }
 43641  
 43642  /*
 43643  ** Returns non-zero if the specified path name should be used verbatim.  If
 43644  ** non-zero is returned from this function, the calling function must simply
 43645  ** use the provided path name verbatim -OR- resolve it into a full path name
 43646  ** using the GetFullPathName Win32 API function (if available).
 43647  */
 43648  static BOOL winIsVerbatimPathname(
 43649    const char *zPathname
 43650  ){
 43651    /*
 43652    ** If the path name starts with a forward slash or a backslash, it is either
 43653    ** a legal UNC name, a volume relative path, or an absolute path name in the
 43654    ** "Unix" format on Windows.  There is no easy way to differentiate between
 43655    ** the final two cases; therefore, we return the safer return value of TRUE
 43656    ** so that callers of this function will simply use it verbatim.
 43657    */
 43658    if ( winIsDirSep(zPathname[0]) ){
 43659      return TRUE;
 43660    }
 43661  
 43662    /*
 43663    ** If the path name starts with a letter and a colon it is either a volume
 43664    ** relative path or an absolute path.  Callers of this function must not
 43665    ** attempt to treat it as a relative path name (i.e. they should simply use
 43666    ** it verbatim).
 43667    */
 43668    if ( winIsDriveLetterAndColon(zPathname) ){
 43669      return TRUE;
 43670    }
 43671  
 43672    /*
 43673    ** If we get to this point, the path name should almost certainly be a purely
 43674    ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
 43675    */
 43676    return FALSE;
 43677  }
 43678  
 43679  /*
 43680  ** Turn a relative pathname into a full pathname.  Write the full
 43681  ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
 43682  ** bytes in size.
 43683  */
 43684  static int winFullPathname(
 43685    sqlite3_vfs *pVfs,            /* Pointer to vfs object */
 43686    const char *zRelative,        /* Possibly relative input path */
 43687    int nFull,                    /* Size of output buffer in bytes */
 43688    char *zFull                   /* Output buffer */
 43689  ){
 43690  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
 43691    DWORD nByte;
 43692    void *zConverted;
 43693    char *zOut;
 43694  #endif
 43695  
 43696    /* If this path name begins with "/X:", where "X" is any alphabetic
 43697    ** character, discard the initial "/" from the pathname.
 43698    */
 43699    if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
 43700      zRelative++;
 43701    }
 43702  
 43703  #if defined(__CYGWIN__)
 43704    SimulateIOError( return SQLITE_ERROR );
 43705    UNUSED_PARAMETER(nFull);
 43706    assert( nFull>=pVfs->mxPathname );
 43707    if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
 43708      /*
 43709      ** NOTE: We are dealing with a relative path name and the data
 43710      **       directory has been set.  Therefore, use it as the basis
 43711      **       for converting the relative path name to an absolute
 43712      **       one by prepending the data directory and a slash.
 43713      */
 43714      char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
 43715      if( !zOut ){
 43716        return SQLITE_IOERR_NOMEM_BKPT;
 43717      }
 43718      if( cygwin_conv_path(
 43719              (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
 43720              CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
 43721        sqlite3_free(zOut);
 43722        return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
 43723                           "winFullPathname1", zRelative);
 43724      }else{
 43725        char *zUtf8 = winConvertToUtf8Filename(zOut);
 43726        if( !zUtf8 ){
 43727          sqlite3_free(zOut);
 43728          return SQLITE_IOERR_NOMEM_BKPT;
 43729        }
 43730        sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
 43731                         sqlite3_data_directory, winGetDirSep(), zUtf8);
 43732        sqlite3_free(zUtf8);
 43733        sqlite3_free(zOut);
 43734      }
 43735    }else{
 43736      char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
 43737      if( !zOut ){
 43738        return SQLITE_IOERR_NOMEM_BKPT;
 43739      }
 43740      if( cygwin_conv_path(
 43741              (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
 43742              zRelative, zOut, pVfs->mxPathname+1)<0 ){
 43743        sqlite3_free(zOut);
 43744        return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
 43745                           "winFullPathname2", zRelative);
 43746      }else{
 43747        char *zUtf8 = winConvertToUtf8Filename(zOut);
 43748        if( !zUtf8 ){
 43749          sqlite3_free(zOut);
 43750          return SQLITE_IOERR_NOMEM_BKPT;
 43751        }
 43752        sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
 43753        sqlite3_free(zUtf8);
 43754        sqlite3_free(zOut);
 43755      }
 43756    }
 43757    return SQLITE_OK;
 43758  #endif
 43759  
 43760  #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
 43761    SimulateIOError( return SQLITE_ERROR );
 43762    /* WinCE has no concept of a relative pathname, or so I am told. */
 43763    /* WinRT has no way to convert a relative path to an absolute one. */
 43764    if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
 43765      /*
 43766      ** NOTE: We are dealing with a relative path name and the data
 43767      **       directory has been set.  Therefore, use it as the basis
 43768      **       for converting the relative path name to an absolute
 43769      **       one by prepending the data directory and a backslash.
 43770      */
 43771      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
 43772                       sqlite3_data_directory, winGetDirSep(), zRelative);
 43773    }else{
 43774      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
 43775    }
 43776    return SQLITE_OK;
 43777  #endif
 43778  
 43779  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
 43780    /* It's odd to simulate an io-error here, but really this is just
 43781    ** using the io-error infrastructure to test that SQLite handles this
 43782    ** function failing. This function could fail if, for example, the
 43783    ** current working directory has been unlinked.
 43784    */
 43785    SimulateIOError( return SQLITE_ERROR );
 43786    if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
 43787      /*
 43788      ** NOTE: We are dealing with a relative path name and the data
 43789      **       directory has been set.  Therefore, use it as the basis
 43790      **       for converting the relative path name to an absolute
 43791      **       one by prepending the data directory and a backslash.
 43792      */
 43793      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
 43794                       sqlite3_data_directory, winGetDirSep(), zRelative);
 43795      return SQLITE_OK;
 43796    }
 43797    zConverted = winConvertFromUtf8Filename(zRelative);
 43798    if( zConverted==0 ){
 43799      return SQLITE_IOERR_NOMEM_BKPT;
 43800    }
 43801    if( osIsNT() ){
 43802      LPWSTR zTemp;
 43803      nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
 43804      if( nByte==0 ){
 43805        sqlite3_free(zConverted);
 43806        return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
 43807                           "winFullPathname1", zRelative);
 43808      }
 43809      nByte += 3;
 43810      zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
 43811      if( zTemp==0 ){
 43812        sqlite3_free(zConverted);
 43813        return SQLITE_IOERR_NOMEM_BKPT;
 43814      }
 43815      nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
 43816      if( nByte==0 ){
 43817        sqlite3_free(zConverted);
 43818        sqlite3_free(zTemp);
 43819        return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
 43820                           "winFullPathname2", zRelative);
 43821      }
 43822      sqlite3_free(zConverted);
 43823      zOut = winUnicodeToUtf8(zTemp);
 43824      sqlite3_free(zTemp);
 43825    }
 43826  #ifdef SQLITE_WIN32_HAS_ANSI
 43827    else{
 43828      char *zTemp;
 43829      nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
 43830      if( nByte==0 ){
 43831        sqlite3_free(zConverted);
 43832        return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
 43833                           "winFullPathname3", zRelative);
 43834      }
 43835      nByte += 3;
 43836      zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
 43837      if( zTemp==0 ){
 43838        sqlite3_free(zConverted);
 43839        return SQLITE_IOERR_NOMEM_BKPT;
 43840      }
 43841      nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
 43842      if( nByte==0 ){
 43843        sqlite3_free(zConverted);
 43844        sqlite3_free(zTemp);
 43845        return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
 43846                           "winFullPathname4", zRelative);
 43847      }
 43848      sqlite3_free(zConverted);
 43849      zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
 43850      sqlite3_free(zTemp);
 43851    }
 43852  #endif
 43853    if( zOut ){
 43854      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
 43855      sqlite3_free(zOut);
 43856      return SQLITE_OK;
 43857    }else{
 43858      return SQLITE_IOERR_NOMEM_BKPT;
 43859    }
 43860  #endif
 43861  }
 43862  
 43863  #ifndef SQLITE_OMIT_LOAD_EXTENSION
 43864  /*
 43865  ** Interfaces for opening a shared library, finding entry points
 43866  ** within the shared library, and closing the shared library.
 43867  */
 43868  static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
 43869    HANDLE h;
 43870  #if defined(__CYGWIN__)
 43871    int nFull = pVfs->mxPathname+1;
 43872    char *zFull = sqlite3MallocZero( nFull );
 43873    void *zConverted = 0;
 43874    if( zFull==0 ){
 43875      OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
 43876      return 0;
 43877    }
 43878    if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
 43879      sqlite3_free(zFull);
 43880      OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
 43881      return 0;
 43882    }
 43883    zConverted = winConvertFromUtf8Filename(zFull);
 43884    sqlite3_free(zFull);
 43885  #else
 43886    void *zConverted = winConvertFromUtf8Filename(zFilename);
 43887    UNUSED_PARAMETER(pVfs);
 43888  #endif
 43889    if( zConverted==0 ){
 43890      OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
 43891      return 0;
 43892    }
 43893    if( osIsNT() ){
 43894  #if SQLITE_OS_WINRT
 43895      h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
 43896  #else
 43897      h = osLoadLibraryW((LPCWSTR)zConverted);
 43898  #endif
 43899    }
 43900  #ifdef SQLITE_WIN32_HAS_ANSI
 43901    else{
 43902      h = osLoadLibraryA((char*)zConverted);
 43903    }
 43904  #endif
 43905    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
 43906    sqlite3_free(zConverted);
 43907    return (void*)h;
 43908  }
 43909  static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
 43910    UNUSED_PARAMETER(pVfs);
 43911    winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
 43912  }
 43913  static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
 43914    FARPROC proc;
 43915    UNUSED_PARAMETER(pVfs);
 43916    proc = osGetProcAddressA((HANDLE)pH, zSym);
 43917    OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
 43918             (void*)pH, zSym, (void*)proc));
 43919    return (void(*)(void))proc;
 43920  }
 43921  static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
 43922    UNUSED_PARAMETER(pVfs);
 43923    osFreeLibrary((HANDLE)pHandle);
 43924    OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
 43925  }
 43926  #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
 43927    #define winDlOpen  0
 43928    #define winDlError 0
 43929    #define winDlSym   0
 43930    #define winDlClose 0
 43931  #endif
 43932  
 43933  /* State information for the randomness gatherer. */
 43934  typedef struct EntropyGatherer EntropyGatherer;
 43935  struct EntropyGatherer {
 43936    unsigned char *a;   /* Gather entropy into this buffer */
 43937    int na;             /* Size of a[] in bytes */
 43938    int i;              /* XOR next input into a[i] */
 43939    int nXor;           /* Number of XOR operations done */
 43940  };
 43941  
 43942  #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
 43943  /* Mix sz bytes of entropy into p. */
 43944  static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
 43945    int j, k;
 43946    for(j=0, k=p->i; j<sz; j++){
 43947      p->a[k++] ^= x[j];
 43948      if( k>=p->na ) k = 0;
 43949    }
 43950    p->i = k;
 43951    p->nXor += sz;
 43952  }
 43953  #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
 43954  
 43955  /*
 43956  ** Write up to nBuf bytes of randomness into zBuf.
 43957  */
 43958  static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
 43959  #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
 43960    UNUSED_PARAMETER(pVfs);
 43961    memset(zBuf, 0, nBuf);
 43962    return nBuf;
 43963  #else
 43964    EntropyGatherer e;
 43965    UNUSED_PARAMETER(pVfs);
 43966    memset(zBuf, 0, nBuf);
 43967    e.a = (unsigned char*)zBuf;
 43968    e.na = nBuf;
 43969    e.nXor = 0;
 43970    e.i = 0;
 43971    {
 43972      SYSTEMTIME x;
 43973      osGetSystemTime(&x);
 43974      xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
 43975    }
 43976    {
 43977      DWORD pid = osGetCurrentProcessId();
 43978      xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
 43979    }
 43980  #if SQLITE_OS_WINRT
 43981    {
 43982      ULONGLONG cnt = osGetTickCount64();
 43983      xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
 43984    }
 43985  #else
 43986    {
 43987      DWORD cnt = osGetTickCount();
 43988      xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
 43989    }
 43990  #endif /* SQLITE_OS_WINRT */
 43991    {
 43992      LARGE_INTEGER i;
 43993      osQueryPerformanceCounter(&i);
 43994      xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
 43995    }
 43996  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
 43997    {
 43998      UUID id;
 43999      memset(&id, 0, sizeof(UUID));
 44000      osUuidCreate(&id);
 44001      xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
 44002      memset(&id, 0, sizeof(UUID));
 44003      osUuidCreateSequential(&id);
 44004      xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
 44005    }
 44006  #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
 44007    return e.nXor>nBuf ? nBuf : e.nXor;
 44008  #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
 44009  }
 44010  
 44011  
 44012  /*
 44013  ** Sleep for a little while.  Return the amount of time slept.
 44014  */
 44015  static int winSleep(sqlite3_vfs *pVfs, int microsec){
 44016    sqlite3_win32_sleep((microsec+999)/1000);
 44017    UNUSED_PARAMETER(pVfs);
 44018    return ((microsec+999)/1000)*1000;
 44019  }
 44020  
 44021  /*
 44022  ** The following variable, if set to a non-zero value, is interpreted as
 44023  ** the number of seconds since 1970 and is used to set the result of
 44024  ** sqlite3OsCurrentTime() during testing.
 44025  */
 44026  #ifdef SQLITE_TEST
 44027  SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
 44028  #endif
 44029  
 44030  /*
 44031  ** Find the current time (in Universal Coordinated Time).  Write into *piNow
 44032  ** the current time and date as a Julian Day number times 86_400_000.  In
 44033  ** other words, write into *piNow the number of milliseconds since the Julian
 44034  ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
 44035  ** proleptic Gregorian calendar.
 44036  **
 44037  ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
 44038  ** cannot be found.
 44039  */
 44040  static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
 44041    /* FILETIME structure is a 64-bit value representing the number of
 44042       100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
 44043    */
 44044    FILETIME ft;
 44045    static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
 44046  #ifdef SQLITE_TEST
 44047    static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
 44048  #endif
 44049    /* 2^32 - to avoid use of LL and warnings in gcc */
 44050    static const sqlite3_int64 max32BitValue =
 44051        (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
 44052        (sqlite3_int64)294967296;
 44053  
 44054  #if SQLITE_OS_WINCE
 44055    SYSTEMTIME time;
 44056    osGetSystemTime(&time);
 44057    /* if SystemTimeToFileTime() fails, it returns zero. */
 44058    if (!osSystemTimeToFileTime(&time,&ft)){
 44059      return SQLITE_ERROR;
 44060    }
 44061  #else
 44062    osGetSystemTimeAsFileTime( &ft );
 44063  #endif
 44064  
 44065    *piNow = winFiletimeEpoch +
 44066              ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
 44067                 (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
 44068  
 44069  #ifdef SQLITE_TEST
 44070    if( sqlite3_current_time ){
 44071      *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
 44072    }
 44073  #endif
 44074    UNUSED_PARAMETER(pVfs);
 44075    return SQLITE_OK;
 44076  }
 44077  
 44078  /*
 44079  ** Find the current time (in Universal Coordinated Time).  Write the
 44080  ** current time and date as a Julian Day number into *prNow and
 44081  ** return 0.  Return 1 if the time and date cannot be found.
 44082  */
 44083  static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
 44084    int rc;
 44085    sqlite3_int64 i;
 44086    rc = winCurrentTimeInt64(pVfs, &i);
 44087    if( !rc ){
 44088      *prNow = i/86400000.0;
 44089    }
 44090    return rc;
 44091  }
 44092  
 44093  /*
 44094  ** The idea is that this function works like a combination of
 44095  ** GetLastError() and FormatMessage() on Windows (or errno and
 44096  ** strerror_r() on Unix). After an error is returned by an OS
 44097  ** function, SQLite calls this function with zBuf pointing to
 44098  ** a buffer of nBuf bytes. The OS layer should populate the
 44099  ** buffer with a nul-terminated UTF-8 encoded error message
 44100  ** describing the last IO error to have occurred within the calling
 44101  ** thread.
 44102  **
 44103  ** If the error message is too large for the supplied buffer,
 44104  ** it should be truncated. The return value of xGetLastError
 44105  ** is zero if the error message fits in the buffer, or non-zero
 44106  ** otherwise (if the message was truncated). If non-zero is returned,
 44107  ** then it is not necessary to include the nul-terminator character
 44108  ** in the output buffer.
 44109  **
 44110  ** Not supplying an error message will have no adverse effect
 44111  ** on SQLite. It is fine to have an implementation that never
 44112  ** returns an error message:
 44113  **
 44114  **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
 44115  **     assert(zBuf[0]=='\0');
 44116  **     return 0;
 44117  **   }
 44118  **
 44119  ** However if an error message is supplied, it will be incorporated
 44120  ** by sqlite into the error message available to the user using
 44121  ** sqlite3_errmsg(), possibly making IO errors easier to debug.
 44122  */
 44123  static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
 44124    DWORD e = osGetLastError();
 44125    UNUSED_PARAMETER(pVfs);
 44126    if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
 44127    return e;
 44128  }
 44129  
 44130  /*
 44131  ** Initialize and deinitialize the operating system interface.
 44132  */
 44133  SQLITE_API int sqlite3_os_init(void){
 44134    static sqlite3_vfs winVfs = {
 44135      3,                     /* iVersion */
 44136      sizeof(winFile),       /* szOsFile */
 44137      SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
 44138      0,                     /* pNext */
 44139      "win32",               /* zName */
 44140      &winAppData,           /* pAppData */
 44141      winOpen,               /* xOpen */
 44142      winDelete,             /* xDelete */
 44143      winAccess,             /* xAccess */
 44144      winFullPathname,       /* xFullPathname */
 44145      winDlOpen,             /* xDlOpen */
 44146      winDlError,            /* xDlError */
 44147      winDlSym,              /* xDlSym */
 44148      winDlClose,            /* xDlClose */
 44149      winRandomness,         /* xRandomness */
 44150      winSleep,              /* xSleep */
 44151      winCurrentTime,        /* xCurrentTime */
 44152      winGetLastError,       /* xGetLastError */
 44153      winCurrentTimeInt64,   /* xCurrentTimeInt64 */
 44154      winSetSystemCall,      /* xSetSystemCall */
 44155      winGetSystemCall,      /* xGetSystemCall */
 44156      winNextSystemCall,     /* xNextSystemCall */
 44157    };
 44158  #if defined(SQLITE_WIN32_HAS_WIDE)
 44159    static sqlite3_vfs winLongPathVfs = {
 44160      3,                     /* iVersion */
 44161      sizeof(winFile),       /* szOsFile */
 44162      SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
 44163      0,                     /* pNext */
 44164      "win32-longpath",      /* zName */
 44165      &winAppData,           /* pAppData */
 44166      winOpen,               /* xOpen */
 44167      winDelete,             /* xDelete */
 44168      winAccess,             /* xAccess */
 44169      winFullPathname,       /* xFullPathname */
 44170      winDlOpen,             /* xDlOpen */
 44171      winDlError,            /* xDlError */
 44172      winDlSym,              /* xDlSym */
 44173      winDlClose,            /* xDlClose */
 44174      winRandomness,         /* xRandomness */
 44175      winSleep,              /* xSleep */
 44176      winCurrentTime,        /* xCurrentTime */
 44177      winGetLastError,       /* xGetLastError */
 44178      winCurrentTimeInt64,   /* xCurrentTimeInt64 */
 44179      winSetSystemCall,      /* xSetSystemCall */
 44180      winGetSystemCall,      /* xGetSystemCall */
 44181      winNextSystemCall,     /* xNextSystemCall */
 44182    };
 44183  #endif
 44184    static sqlite3_vfs winNolockVfs = {
 44185      3,                     /* iVersion */
 44186      sizeof(winFile),       /* szOsFile */
 44187      SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
 44188      0,                     /* pNext */
 44189      "win32-none",          /* zName */
 44190      &winNolockAppData,     /* pAppData */
 44191      winOpen,               /* xOpen */
 44192      winDelete,             /* xDelete */
 44193      winAccess,             /* xAccess */
 44194      winFullPathname,       /* xFullPathname */
 44195      winDlOpen,             /* xDlOpen */
 44196      winDlError,            /* xDlError */
 44197      winDlSym,              /* xDlSym */
 44198      winDlClose,            /* xDlClose */
 44199      winRandomness,         /* xRandomness */
 44200      winSleep,              /* xSleep */
 44201      winCurrentTime,        /* xCurrentTime */
 44202      winGetLastError,       /* xGetLastError */
 44203      winCurrentTimeInt64,   /* xCurrentTimeInt64 */
 44204      winSetSystemCall,      /* xSetSystemCall */
 44205      winGetSystemCall,      /* xGetSystemCall */
 44206      winNextSystemCall,     /* xNextSystemCall */
 44207    };
 44208  #if defined(SQLITE_WIN32_HAS_WIDE)
 44209    static sqlite3_vfs winLongPathNolockVfs = {
 44210      3,                     /* iVersion */
 44211      sizeof(winFile),       /* szOsFile */
 44212      SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
 44213      0,                     /* pNext */
 44214      "win32-longpath-none", /* zName */
 44215      &winNolockAppData,     /* pAppData */
 44216      winOpen,               /* xOpen */
 44217      winDelete,             /* xDelete */
 44218      winAccess,             /* xAccess */
 44219      winFullPathname,       /* xFullPathname */
 44220      winDlOpen,             /* xDlOpen */
 44221      winDlError,            /* xDlError */
 44222      winDlSym,              /* xDlSym */
 44223      winDlClose,            /* xDlClose */
 44224      winRandomness,         /* xRandomness */
 44225      winSleep,              /* xSleep */
 44226      winCurrentTime,        /* xCurrentTime */
 44227      winGetLastError,       /* xGetLastError */
 44228      winCurrentTimeInt64,   /* xCurrentTimeInt64 */
 44229      winSetSystemCall,      /* xSetSystemCall */
 44230      winGetSystemCall,      /* xGetSystemCall */
 44231      winNextSystemCall,     /* xNextSystemCall */
 44232    };
 44233  #endif
 44234  
 44235    /* Double-check that the aSyscall[] array has been constructed
 44236    ** correctly.  See ticket [bb3a86e890c8e96ab] */
 44237    assert( ArraySize(aSyscall)==80 );
 44238  
 44239    /* get memory map allocation granularity */
 44240    memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
 44241  #if SQLITE_OS_WINRT
 44242    osGetNativeSystemInfo(&winSysInfo);
 44243  #else
 44244    osGetSystemInfo(&winSysInfo);
 44245  #endif
 44246    assert( winSysInfo.dwAllocationGranularity>0 );
 44247    assert( winSysInfo.dwPageSize>0 );
 44248  
 44249    sqlite3_vfs_register(&winVfs, 1);
 44250  
 44251  #if defined(SQLITE_WIN32_HAS_WIDE)
 44252    sqlite3_vfs_register(&winLongPathVfs, 0);
 44253  #endif
 44254  
 44255    sqlite3_vfs_register(&winNolockVfs, 0);
 44256  
 44257  #if defined(SQLITE_WIN32_HAS_WIDE)
 44258    sqlite3_vfs_register(&winLongPathNolockVfs, 0);
 44259  #endif
 44260  
 44261    return SQLITE_OK;
 44262  }
 44263  
 44264  SQLITE_API int sqlite3_os_end(void){
 44265  #if SQLITE_OS_WINRT
 44266    if( sleepObj!=NULL ){
 44267      osCloseHandle(sleepObj);
 44268      sleepObj = NULL;
 44269    }
 44270  #endif
 44271    return SQLITE_OK;
 44272  }
 44273  
 44274  #endif /* SQLITE_OS_WIN */
 44275  
 44276  /************** End of os_win.c **********************************************/
 44277  /************** Begin file bitvec.c ******************************************/
 44278  /*
 44279  ** 2008 February 16
 44280  **
 44281  ** The author disclaims copyright to this source code.  In place of
 44282  ** a legal notice, here is a blessing:
 44283  **
 44284  **    May you do good and not evil.
 44285  **    May you find forgiveness for yourself and forgive others.
 44286  **    May you share freely, never taking more than you give.
 44287  **
 44288  *************************************************************************
 44289  ** This file implements an object that represents a fixed-length
 44290  ** bitmap.  Bits are numbered starting with 1.
 44291  **
 44292  ** A bitmap is used to record which pages of a database file have been
 44293  ** journalled during a transaction, or which pages have the "dont-write"
 44294  ** property.  Usually only a few pages are meet either condition.
 44295  ** So the bitmap is usually sparse and has low cardinality.
 44296  ** But sometimes (for example when during a DROP of a large table) most
 44297  ** or all of the pages in a database can get journalled.  In those cases, 
 44298  ** the bitmap becomes dense with high cardinality.  The algorithm needs 
 44299  ** to handle both cases well.
 44300  **
 44301  ** The size of the bitmap is fixed when the object is created.
 44302  **
 44303  ** All bits are clear when the bitmap is created.  Individual bits
 44304  ** may be set or cleared one at a time.
 44305  **
 44306  ** Test operations are about 100 times more common that set operations.
 44307  ** Clear operations are exceedingly rare.  There are usually between
 44308  ** 5 and 500 set operations per Bitvec object, though the number of sets can
 44309  ** sometimes grow into tens of thousands or larger.  The size of the
 44310  ** Bitvec object is the number of pages in the database file at the
 44311  ** start of a transaction, and is thus usually less than a few thousand,
 44312  ** but can be as large as 2 billion for a really big database.
 44313  */
 44314  /* #include "sqliteInt.h" */
 44315  
 44316  /* Size of the Bitvec structure in bytes. */
 44317  #define BITVEC_SZ        512
 44318  
 44319  /* Round the union size down to the nearest pointer boundary, since that's how 
 44320  ** it will be aligned within the Bitvec struct. */
 44321  #define BITVEC_USIZE \
 44322      (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
 44323  
 44324  /* Type of the array "element" for the bitmap representation. 
 44325  ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
 44326  ** Setting this to the "natural word" size of your CPU may improve
 44327  ** performance. */
 44328  #define BITVEC_TELEM     u8
 44329  /* Size, in bits, of the bitmap element. */
 44330  #define BITVEC_SZELEM    8
 44331  /* Number of elements in a bitmap array. */
 44332  #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
 44333  /* Number of bits in the bitmap array. */
 44334  #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
 44335  
 44336  /* Number of u32 values in hash table. */
 44337  #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
 44338  /* Maximum number of entries in hash table before 
 44339  ** sub-dividing and re-hashing. */
 44340  #define BITVEC_MXHASH    (BITVEC_NINT/2)
 44341  /* Hashing function for the aHash representation.
 44342  ** Empirical testing showed that the *37 multiplier 
 44343  ** (an arbitrary prime)in the hash function provided 
 44344  ** no fewer collisions than the no-op *1. */
 44345  #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
 44346  
 44347  #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
 44348  
 44349  
 44350  /*
 44351  ** A bitmap is an instance of the following structure.
 44352  **
 44353  ** This bitmap records the existence of zero or more bits
 44354  ** with values between 1 and iSize, inclusive.
 44355  **
 44356  ** There are three possible representations of the bitmap.
 44357  ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
 44358  ** bitmap.  The least significant bit is bit 1.
 44359  **
 44360  ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
 44361  ** a hash table that will hold up to BITVEC_MXHASH distinct values.
 44362  **
 44363  ** Otherwise, the value i is redirected into one of BITVEC_NPTR
 44364  ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
 44365  ** handles up to iDivisor separate values of i.  apSub[0] holds
 44366  ** values between 1 and iDivisor.  apSub[1] holds values between
 44367  ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
 44368  ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
 44369  ** to hold deal with values between 1 and iDivisor.
 44370  */
 44371  struct Bitvec {
 44372    u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
 44373    u32 nSet;       /* Number of bits that are set - only valid for aHash
 44374                    ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
 44375                    ** this would be 125. */
 44376    u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
 44377                    /* Should >=0 for apSub element. */
 44378                    /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
 44379                    /* For a BITVEC_SZ of 512, this would be 34,359,739. */
 44380    union {
 44381      BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
 44382      u32 aHash[BITVEC_NINT];      /* Hash table representation */
 44383      Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
 44384    } u;
 44385  };
 44386  
 44387  /*
 44388  ** Create a new bitmap object able to handle bits between 0 and iSize,
 44389  ** inclusive.  Return a pointer to the new object.  Return NULL if 
 44390  ** malloc fails.
 44391  */
 44392  SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
 44393    Bitvec *p;
 44394    assert( sizeof(*p)==BITVEC_SZ );
 44395    p = sqlite3MallocZero( sizeof(*p) );
 44396    if( p ){
 44397      p->iSize = iSize;
 44398    }
 44399    return p;
 44400  }
 44401  
 44402  /*
 44403  ** Check to see if the i-th bit is set.  Return true or false.
 44404  ** If p is NULL (if the bitmap has not been created) or if
 44405  ** i is out of range, then return false.
 44406  */
 44407  SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
 44408    assert( p!=0 );
 44409    i--;
 44410    if( i>=p->iSize ) return 0;
 44411    while( p->iDivisor ){
 44412      u32 bin = i/p->iDivisor;
 44413      i = i%p->iDivisor;
 44414      p = p->u.apSub[bin];
 44415      if (!p) {
 44416        return 0;
 44417      }
 44418    }
 44419    if( p->iSize<=BITVEC_NBIT ){
 44420      return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
 44421    } else{
 44422      u32 h = BITVEC_HASH(i++);
 44423      while( p->u.aHash[h] ){
 44424        if( p->u.aHash[h]==i ) return 1;
 44425        h = (h+1) % BITVEC_NINT;
 44426      }
 44427      return 0;
 44428    }
 44429  }
 44430  SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
 44431    return p!=0 && sqlite3BitvecTestNotNull(p,i);
 44432  }
 44433  
 44434  /*
 44435  ** Set the i-th bit.  Return 0 on success and an error code if
 44436  ** anything goes wrong.
 44437  **
 44438  ** This routine might cause sub-bitmaps to be allocated.  Failing
 44439  ** to get the memory needed to hold the sub-bitmap is the only
 44440  ** that can go wrong with an insert, assuming p and i are valid.
 44441  **
 44442  ** The calling function must ensure that p is a valid Bitvec object
 44443  ** and that the value for "i" is within range of the Bitvec object.
 44444  ** Otherwise the behavior is undefined.
 44445  */
 44446  SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
 44447    u32 h;
 44448    if( p==0 ) return SQLITE_OK;
 44449    assert( i>0 );
 44450    assert( i<=p->iSize );
 44451    i--;
 44452    while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
 44453      u32 bin = i/p->iDivisor;
 44454      i = i%p->iDivisor;
 44455      if( p->u.apSub[bin]==0 ){
 44456        p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
 44457        if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
 44458      }
 44459      p = p->u.apSub[bin];
 44460    }
 44461    if( p->iSize<=BITVEC_NBIT ){
 44462      p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
 44463      return SQLITE_OK;
 44464    }
 44465    h = BITVEC_HASH(i++);
 44466    /* if there wasn't a hash collision, and this doesn't */
 44467    /* completely fill the hash, then just add it without */
 44468    /* worring about sub-dividing and re-hashing. */
 44469    if( !p->u.aHash[h] ){
 44470      if (p->nSet<(BITVEC_NINT-1)) {
 44471        goto bitvec_set_end;
 44472      } else {
 44473        goto bitvec_set_rehash;
 44474      }
 44475    }
 44476    /* there was a collision, check to see if it's already */
 44477    /* in hash, if not, try to find a spot for it */
 44478    do {
 44479      if( p->u.aHash[h]==i ) return SQLITE_OK;
 44480      h++;
 44481      if( h>=BITVEC_NINT ) h = 0;
 44482    } while( p->u.aHash[h] );
 44483    /* we didn't find it in the hash.  h points to the first */
 44484    /* available free spot. check to see if this is going to */
 44485    /* make our hash too "full".  */
 44486  bitvec_set_rehash:
 44487    if( p->nSet>=BITVEC_MXHASH ){
 44488      unsigned int j;
 44489      int rc;
 44490      u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
 44491      if( aiValues==0 ){
 44492        return SQLITE_NOMEM_BKPT;
 44493      }else{
 44494        memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
 44495        memset(p->u.apSub, 0, sizeof(p->u.apSub));
 44496        p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
 44497        rc = sqlite3BitvecSet(p, i);
 44498        for(j=0; j<BITVEC_NINT; j++){
 44499          if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
 44500        }
 44501        sqlite3StackFree(0, aiValues);
 44502        return rc;
 44503      }
 44504    }
 44505  bitvec_set_end:
 44506    p->nSet++;
 44507    p->u.aHash[h] = i;
 44508    return SQLITE_OK;
 44509  }
 44510  
 44511  /*
 44512  ** Clear the i-th bit.
 44513  **
 44514  ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
 44515  ** that BitvecClear can use to rebuilt its hash table.
 44516  */
 44517  SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
 44518    if( p==0 ) return;
 44519    assert( i>0 );
 44520    i--;
 44521    while( p->iDivisor ){
 44522      u32 bin = i/p->iDivisor;
 44523      i = i%p->iDivisor;
 44524      p = p->u.apSub[bin];
 44525      if (!p) {
 44526        return;
 44527      }
 44528    }
 44529    if( p->iSize<=BITVEC_NBIT ){
 44530      p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
 44531    }else{
 44532      unsigned int j;
 44533      u32 *aiValues = pBuf;
 44534      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
 44535      memset(p->u.aHash, 0, sizeof(p->u.aHash));
 44536      p->nSet = 0;
 44537      for(j=0; j<BITVEC_NINT; j++){
 44538        if( aiValues[j] && aiValues[j]!=(i+1) ){
 44539          u32 h = BITVEC_HASH(aiValues[j]-1);
 44540          p->nSet++;
 44541          while( p->u.aHash[h] ){
 44542            h++;
 44543            if( h>=BITVEC_NINT ) h = 0;
 44544          }
 44545          p->u.aHash[h] = aiValues[j];
 44546        }
 44547      }
 44548    }
 44549  }
 44550  
 44551  /*
 44552  ** Destroy a bitmap object.  Reclaim all memory used.
 44553  */
 44554  SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
 44555    if( p==0 ) return;
 44556    if( p->iDivisor ){
 44557      unsigned int i;
 44558      for(i=0; i<BITVEC_NPTR; i++){
 44559        sqlite3BitvecDestroy(p->u.apSub[i]);
 44560      }
 44561    }
 44562    sqlite3_free(p);
 44563  }
 44564  
 44565  /*
 44566  ** Return the value of the iSize parameter specified when Bitvec *p
 44567  ** was created.
 44568  */
 44569  SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
 44570    return p->iSize;
 44571  }
 44572  
 44573  #ifndef SQLITE_UNTESTABLE
 44574  /*
 44575  ** Let V[] be an array of unsigned characters sufficient to hold
 44576  ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
 44577  ** Then the following macros can be used to set, clear, or test
 44578  ** individual bits within V.
 44579  */
 44580  #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
 44581  #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
 44582  #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
 44583  
 44584  /*
 44585  ** This routine runs an extensive test of the Bitvec code.
 44586  **
 44587  ** The input is an array of integers that acts as a program
 44588  ** to test the Bitvec.  The integers are opcodes followed
 44589  ** by 0, 1, or 3 operands, depending on the opcode.  Another
 44590  ** opcode follows immediately after the last operand.
 44591  **
 44592  ** There are 6 opcodes numbered from 0 through 5.  0 is the
 44593  ** "halt" opcode and causes the test to end.
 44594  **
 44595  **    0          Halt and return the number of errors
 44596  **    1 N S X    Set N bits beginning with S and incrementing by X
 44597  **    2 N S X    Clear N bits beginning with S and incrementing by X
 44598  **    3 N        Set N randomly chosen bits
 44599  **    4 N        Clear N randomly chosen bits
 44600  **    5 N S X    Set N bits from S increment X in array only, not in bitvec
 44601  **
 44602  ** The opcodes 1 through 4 perform set and clear operations are performed
 44603  ** on both a Bitvec object and on a linear array of bits obtained from malloc.
 44604  ** Opcode 5 works on the linear array only, not on the Bitvec.
 44605  ** Opcode 5 is used to deliberately induce a fault in order to
 44606  ** confirm that error detection works.
 44607  **
 44608  ** At the conclusion of the test the linear array is compared
 44609  ** against the Bitvec object.  If there are any differences,
 44610  ** an error is returned.  If they are the same, zero is returned.
 44611  **
 44612  ** If a memory allocation error occurs, return -1.
 44613  */
 44614  SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
 44615    Bitvec *pBitvec = 0;
 44616    unsigned char *pV = 0;
 44617    int rc = -1;
 44618    int i, nx, pc, op;
 44619    void *pTmpSpace;
 44620  
 44621    /* Allocate the Bitvec to be tested and a linear array of
 44622    ** bits to act as the reference */
 44623    pBitvec = sqlite3BitvecCreate( sz );
 44624    pV = sqlite3MallocZero( (sz+7)/8 + 1 );
 44625    pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
 44626    if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
 44627  
 44628    /* NULL pBitvec tests */
 44629    sqlite3BitvecSet(0, 1);
 44630    sqlite3BitvecClear(0, 1, pTmpSpace);
 44631  
 44632    /* Run the program */
 44633    pc = 0;
 44634    while( (op = aOp[pc])!=0 ){
 44635      switch( op ){
 44636        case 1:
 44637        case 2:
 44638        case 5: {
 44639          nx = 4;
 44640          i = aOp[pc+2] - 1;
 44641          aOp[pc+2] += aOp[pc+3];
 44642          break;
 44643        }
 44644        case 3:
 44645        case 4: 
 44646        default: {
 44647          nx = 2;
 44648          sqlite3_randomness(sizeof(i), &i);
 44649          break;
 44650        }
 44651      }
 44652      if( (--aOp[pc+1]) > 0 ) nx = 0;
 44653      pc += nx;
 44654      i = (i & 0x7fffffff)%sz;
 44655      if( (op & 1)!=0 ){
 44656        SETBIT(pV, (i+1));
 44657        if( op!=5 ){
 44658          if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
 44659        }
 44660      }else{
 44661        CLEARBIT(pV, (i+1));
 44662        sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
 44663      }
 44664    }
 44665  
 44666    /* Test to make sure the linear array exactly matches the
 44667    ** Bitvec object.  Start with the assumption that they do
 44668    ** match (rc==0).  Change rc to non-zero if a discrepancy
 44669    ** is found.
 44670    */
 44671    rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
 44672            + sqlite3BitvecTest(pBitvec, 0)
 44673            + (sqlite3BitvecSize(pBitvec) - sz);
 44674    for(i=1; i<=sz; i++){
 44675      if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
 44676        rc = i;
 44677        break;
 44678      }
 44679    }
 44680  
 44681    /* Free allocated structure */
 44682  bitvec_end:
 44683    sqlite3_free(pTmpSpace);
 44684    sqlite3_free(pV);
 44685    sqlite3BitvecDestroy(pBitvec);
 44686    return rc;
 44687  }
 44688  #endif /* SQLITE_UNTESTABLE */
 44689  
 44690  /************** End of bitvec.c **********************************************/
 44691  /************** Begin file pcache.c ******************************************/
 44692  /*
 44693  ** 2008 August 05
 44694  **
 44695  ** The author disclaims copyright to this source code.  In place of
 44696  ** a legal notice, here is a blessing:
 44697  **
 44698  **    May you do good and not evil.
 44699  **    May you find forgiveness for yourself and forgive others.
 44700  **    May you share freely, never taking more than you give.
 44701  **
 44702  *************************************************************************
 44703  ** This file implements that page cache.
 44704  */
 44705  /* #include "sqliteInt.h" */
 44706  
 44707  /*
 44708  ** A complete page cache is an instance of this structure.  Every
 44709  ** entry in the cache holds a single page of the database file.  The
 44710  ** btree layer only operates on the cached copy of the database pages.
 44711  **
 44712  ** A page cache entry is "clean" if it exactly matches what is currently
 44713  ** on disk.  A page is "dirty" if it has been modified and needs to be
 44714  ** persisted to disk.
 44715  **
 44716  ** pDirty, pDirtyTail, pSynced:
 44717  **   All dirty pages are linked into the doubly linked list using
 44718  **   PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
 44719  **   such that p was added to the list more recently than p->pDirtyNext.
 44720  **   PCache.pDirty points to the first (newest) element in the list and
 44721  **   pDirtyTail to the last (oldest).
 44722  **
 44723  **   The PCache.pSynced variable is used to optimize searching for a dirty
 44724  **   page to eject from the cache mid-transaction. It is better to eject
 44725  **   a page that does not require a journal sync than one that does. 
 44726  **   Therefore, pSynced is maintained to that it *almost* always points
 44727  **   to either the oldest page in the pDirty/pDirtyTail list that has a
 44728  **   clear PGHDR_NEED_SYNC flag or to a page that is older than this one
 44729  **   (so that the right page to eject can be found by following pDirtyPrev
 44730  **   pointers).
 44731  */
 44732  struct PCache {
 44733    PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
 44734    PgHdr *pSynced;                     /* Last synced page in dirty page list */
 44735    int nRefSum;                        /* Sum of ref counts over all pages */
 44736    int szCache;                        /* Configured cache size */
 44737    int szSpill;                        /* Size before spilling occurs */
 44738    int szPage;                         /* Size of every page in this cache */
 44739    int szExtra;                        /* Size of extra space for each page */
 44740    u8 bPurgeable;                      /* True if pages are on backing store */
 44741    u8 eCreate;                         /* eCreate value for for xFetch() */
 44742    int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
 44743    void *pStress;                      /* Argument to xStress */
 44744    sqlite3_pcache *pCache;             /* Pluggable cache module */
 44745  };
 44746  
 44747  /********************************** Test and Debug Logic **********************/
 44748  /*
 44749  ** Debug tracing macros.  Enable by by changing the "0" to "1" and
 44750  ** recompiling.
 44751  **
 44752  ** When sqlite3PcacheTrace is 1, single line trace messages are issued.
 44753  ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
 44754  ** is displayed for many operations, resulting in a lot of output.
 44755  */
 44756  #if defined(SQLITE_DEBUG) && 0
 44757    int sqlite3PcacheTrace = 2;       /* 0: off  1: simple  2: cache dumps */
 44758    int sqlite3PcacheMxDump = 9999;   /* Max cache entries for pcacheDump() */
 44759  # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
 44760    void pcacheDump(PCache *pCache){
 44761      int N;
 44762      int i, j;
 44763      sqlite3_pcache_page *pLower;
 44764      PgHdr *pPg;
 44765      unsigned char *a;
 44766    
 44767      if( sqlite3PcacheTrace<2 ) return;
 44768      if( pCache->pCache==0 ) return;
 44769      N = sqlite3PcachePagecount(pCache);
 44770      if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
 44771      for(i=1; i<=N; i++){
 44772         pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
 44773         if( pLower==0 ) continue;
 44774         pPg = (PgHdr*)pLower->pExtra;
 44775         printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
 44776         a = (unsigned char *)pLower->pBuf;
 44777         for(j=0; j<12; j++) printf("%02x", a[j]);
 44778         printf("\n");
 44779         if( pPg->pPage==0 ){
 44780           sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
 44781         }
 44782      }
 44783    }
 44784    #else
 44785  # define pcacheTrace(X)
 44786  # define pcacheDump(X)
 44787  #endif
 44788  
 44789  /*
 44790  ** Check invariants on a PgHdr entry.  Return true if everything is OK.
 44791  ** Return false if any invariant is violated.
 44792  **
 44793  ** This routine is for use inside of assert() statements only.  For
 44794  ** example:
 44795  **
 44796  **          assert( sqlite3PcachePageSanity(pPg) );
 44797  */
 44798  #ifdef SQLITE_DEBUG
 44799  SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
 44800    PCache *pCache;
 44801    assert( pPg!=0 );
 44802    assert( pPg->pgno>0 || pPg->pPager==0 );    /* Page number is 1 or more */
 44803    pCache = pPg->pCache;
 44804    assert( pCache!=0 );      /* Every page has an associated PCache */
 44805    if( pPg->flags & PGHDR_CLEAN ){
 44806      assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
 44807      assert( pCache->pDirty!=pPg );          /* CLEAN pages not on dirty list */
 44808      assert( pCache->pDirtyTail!=pPg );
 44809    }
 44810    /* WRITEABLE pages must also be DIRTY */
 44811    if( pPg->flags & PGHDR_WRITEABLE ){
 44812      assert( pPg->flags & PGHDR_DIRTY );     /* WRITEABLE implies DIRTY */
 44813    }
 44814    /* NEED_SYNC can be set independently of WRITEABLE.  This can happen,
 44815    ** for example, when using the sqlite3PagerDontWrite() optimization:
 44816    **    (1)  Page X is journalled, and gets WRITEABLE and NEED_SEEK.
 44817    **    (2)  Page X moved to freelist, WRITEABLE is cleared
 44818    **    (3)  Page X reused, WRITEABLE is set again
 44819    ** If NEED_SYNC had been cleared in step 2, then it would not be reset
 44820    ** in step 3, and page might be written into the database without first
 44821    ** syncing the rollback journal, which might cause corruption on a power
 44822    ** loss.
 44823    **
 44824    ** Another example is when the database page size is smaller than the
 44825    ** disk sector size.  When any page of a sector is journalled, all pages
 44826    ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
 44827    ** in case they are later modified, since all pages in the same sector
 44828    ** must be journalled and synced before any of those pages can be safely
 44829    ** written.
 44830    */
 44831    return 1;
 44832  }
 44833  #endif /* SQLITE_DEBUG */
 44834  
 44835  
 44836  /********************************** Linked List Management ********************/
 44837  
 44838  /* Allowed values for second argument to pcacheManageDirtyList() */
 44839  #define PCACHE_DIRTYLIST_REMOVE   1    /* Remove pPage from dirty list */
 44840  #define PCACHE_DIRTYLIST_ADD      2    /* Add pPage to the dirty list */
 44841  #define PCACHE_DIRTYLIST_FRONT    3    /* Move pPage to the front of the list */
 44842  
 44843  /*
 44844  ** Manage pPage's participation on the dirty list.  Bits of the addRemove
 44845  ** argument determines what operation to do.  The 0x01 bit means first
 44846  ** remove pPage from the dirty list.  The 0x02 means add pPage back to
 44847  ** the dirty list.  Doing both moves pPage to the front of the dirty list.
 44848  */
 44849  static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
 44850    PCache *p = pPage->pCache;
 44851  
 44852    pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
 44853                  addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
 44854                  pPage->pgno));
 44855    if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
 44856      assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
 44857      assert( pPage->pDirtyPrev || pPage==p->pDirty );
 44858    
 44859      /* Update the PCache1.pSynced variable if necessary. */
 44860      if( p->pSynced==pPage ){
 44861        p->pSynced = pPage->pDirtyPrev;
 44862      }
 44863    
 44864      if( pPage->pDirtyNext ){
 44865        pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
 44866      }else{
 44867        assert( pPage==p->pDirtyTail );
 44868        p->pDirtyTail = pPage->pDirtyPrev;
 44869      }
 44870      if( pPage->pDirtyPrev ){
 44871        pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
 44872      }else{
 44873        /* If there are now no dirty pages in the cache, set eCreate to 2. 
 44874        ** This is an optimization that allows sqlite3PcacheFetch() to skip
 44875        ** searching for a dirty page to eject from the cache when it might
 44876        ** otherwise have to.  */
 44877        assert( pPage==p->pDirty );
 44878        p->pDirty = pPage->pDirtyNext;
 44879        assert( p->bPurgeable || p->eCreate==2 );
 44880        if( p->pDirty==0 ){         /*OPTIMIZATION-IF-TRUE*/
 44881          assert( p->bPurgeable==0 || p->eCreate==1 );
 44882          p->eCreate = 2;
 44883        }
 44884      }
 44885    }
 44886    if( addRemove & PCACHE_DIRTYLIST_ADD ){
 44887      pPage->pDirtyPrev = 0;
 44888      pPage->pDirtyNext = p->pDirty;
 44889      if( pPage->pDirtyNext ){
 44890        assert( pPage->pDirtyNext->pDirtyPrev==0 );
 44891        pPage->pDirtyNext->pDirtyPrev = pPage;
 44892      }else{
 44893        p->pDirtyTail = pPage;
 44894        if( p->bPurgeable ){
 44895          assert( p->eCreate==2 );
 44896          p->eCreate = 1;
 44897        }
 44898      }
 44899      p->pDirty = pPage;
 44900  
 44901      /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
 44902      ** pSynced to point to it. Checking the NEED_SYNC flag is an 
 44903      ** optimization, as if pSynced points to a page with the NEED_SYNC
 44904      ** flag set sqlite3PcacheFetchStress() searches through all newer 
 44905      ** entries of the dirty-list for a page with NEED_SYNC clear anyway.  */
 44906      if( !p->pSynced 
 44907       && 0==(pPage->flags&PGHDR_NEED_SYNC)   /*OPTIMIZATION-IF-FALSE*/
 44908      ){
 44909        p->pSynced = pPage;
 44910      }
 44911    }
 44912    pcacheDump(p);
 44913  }
 44914  
 44915  /*
 44916  ** Wrapper around the pluggable caches xUnpin method. If the cache is
 44917  ** being used for an in-memory database, this function is a no-op.
 44918  */
 44919  static void pcacheUnpin(PgHdr *p){
 44920    if( p->pCache->bPurgeable ){
 44921      pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
 44922      sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
 44923      pcacheDump(p->pCache);
 44924    }
 44925  }
 44926  
 44927  /*
 44928  ** Compute the number of pages of cache requested.   p->szCache is the
 44929  ** cache size requested by the "PRAGMA cache_size" statement.
 44930  */
 44931  static int numberOfCachePages(PCache *p){
 44932    if( p->szCache>=0 ){
 44933      /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
 44934      ** suggested cache size is set to N. */
 44935      return p->szCache;
 44936    }else{
 44937      /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
 44938      ** the number of cache pages is adjusted to use approximately abs(N*1024)
 44939      ** bytes of memory. */
 44940      return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
 44941    }
 44942  }
 44943  
 44944  /*************************************************** General Interfaces ******
 44945  **
 44946  ** Initialize and shutdown the page cache subsystem. Neither of these 
 44947  ** functions are threadsafe.
 44948  */
 44949  SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
 44950    if( sqlite3GlobalConfig.pcache2.xInit==0 ){
 44951      /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
 44952      ** built-in default page cache is used instead of the application defined
 44953      ** page cache. */
 44954      sqlite3PCacheSetDefault();
 44955    }
 44956    return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
 44957  }
 44958  SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
 44959    if( sqlite3GlobalConfig.pcache2.xShutdown ){
 44960      /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
 44961      sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
 44962    }
 44963  }
 44964  
 44965  /*
 44966  ** Return the size in bytes of a PCache object.
 44967  */
 44968  SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
 44969  
 44970  /*
 44971  ** Create a new PCache object. Storage space to hold the object
 44972  ** has already been allocated and is passed in as the p pointer. 
 44973  ** The caller discovers how much space needs to be allocated by 
 44974  ** calling sqlite3PcacheSize().
 44975  **
 44976  ** szExtra is some extra space allocated for each page.  The first
 44977  ** 8 bytes of the extra space will be zeroed as the page is allocated,
 44978  ** but remaining content will be uninitialized.  Though it is opaque
 44979  ** to this module, the extra space really ends up being the MemPage
 44980  ** structure in the pager.
 44981  */
 44982  SQLITE_PRIVATE int sqlite3PcacheOpen(
 44983    int szPage,                  /* Size of every page */
 44984    int szExtra,                 /* Extra space associated with each page */
 44985    int bPurgeable,              /* True if pages are on backing store */
 44986    int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
 44987    void *pStress,               /* Argument to xStress */
 44988    PCache *p                    /* Preallocated space for the PCache */
 44989  ){
 44990    memset(p, 0, sizeof(PCache));
 44991    p->szPage = 1;
 44992    p->szExtra = szExtra;
 44993    assert( szExtra>=8 );  /* First 8 bytes will be zeroed */
 44994    p->bPurgeable = bPurgeable;
 44995    p->eCreate = 2;
 44996    p->xStress = xStress;
 44997    p->pStress = pStress;
 44998    p->szCache = 100;
 44999    p->szSpill = 1;
 45000    pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
 45001    return sqlite3PcacheSetPageSize(p, szPage);
 45002  }
 45003  
 45004  /*
 45005  ** Change the page size for PCache object. The caller must ensure that there
 45006  ** are no outstanding page references when this function is called.
 45007  */
 45008  SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
 45009    assert( pCache->nRefSum==0 && pCache->pDirty==0 );
 45010    if( pCache->szPage ){
 45011      sqlite3_pcache *pNew;
 45012      pNew = sqlite3GlobalConfig.pcache2.xCreate(
 45013                  szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
 45014                  pCache->bPurgeable
 45015      );
 45016      if( pNew==0 ) return SQLITE_NOMEM_BKPT;
 45017      sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
 45018      if( pCache->pCache ){
 45019        sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
 45020      }
 45021      pCache->pCache = pNew;
 45022      pCache->szPage = szPage;
 45023      pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
 45024    }
 45025    return SQLITE_OK;
 45026  }
 45027  
 45028  /*
 45029  ** Try to obtain a page from the cache.
 45030  **
 45031  ** This routine returns a pointer to an sqlite3_pcache_page object if
 45032  ** such an object is already in cache, or if a new one is created.
 45033  ** This routine returns a NULL pointer if the object was not in cache
 45034  ** and could not be created.
 45035  **
 45036  ** The createFlags should be 0 to check for existing pages and should
 45037  ** be 3 (not 1, but 3) to try to create a new page.
 45038  **
 45039  ** If the createFlag is 0, then NULL is always returned if the page
 45040  ** is not already in the cache.  If createFlag is 1, then a new page
 45041  ** is created only if that can be done without spilling dirty pages
 45042  ** and without exceeding the cache size limit.
 45043  **
 45044  ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
 45045  ** initialize the sqlite3_pcache_page object and convert it into a
 45046  ** PgHdr object.  The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
 45047  ** routines are split this way for performance reasons. When separated
 45048  ** they can both (usually) operate without having to push values to
 45049  ** the stack on entry and pop them back off on exit, which saves a
 45050  ** lot of pushing and popping.
 45051  */
 45052  SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
 45053    PCache *pCache,       /* Obtain the page from this cache */
 45054    Pgno pgno,            /* Page number to obtain */
 45055    int createFlag        /* If true, create page if it does not exist already */
 45056  ){
 45057    int eCreate;
 45058    sqlite3_pcache_page *pRes;
 45059  
 45060    assert( pCache!=0 );
 45061    assert( pCache->pCache!=0 );
 45062    assert( createFlag==3 || createFlag==0 );
 45063    assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
 45064  
 45065    /* eCreate defines what to do if the page does not exist.
 45066    **    0     Do not allocate a new page.  (createFlag==0)
 45067    **    1     Allocate a new page if doing so is inexpensive.
 45068    **          (createFlag==1 AND bPurgeable AND pDirty)
 45069    **    2     Allocate a new page even it doing so is difficult.
 45070    **          (createFlag==1 AND !(bPurgeable AND pDirty)
 45071    */
 45072    eCreate = createFlag & pCache->eCreate;
 45073    assert( eCreate==0 || eCreate==1 || eCreate==2 );
 45074    assert( createFlag==0 || pCache->eCreate==eCreate );
 45075    assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
 45076    pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
 45077    pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
 45078                 createFlag?" create":"",pRes));
 45079    return pRes;
 45080  }
 45081  
 45082  /*
 45083  ** If the sqlite3PcacheFetch() routine is unable to allocate a new
 45084  ** page because no clean pages are available for reuse and the cache
 45085  ** size limit has been reached, then this routine can be invoked to 
 45086  ** try harder to allocate a page.  This routine might invoke the stress
 45087  ** callback to spill dirty pages to the journal.  It will then try to
 45088  ** allocate the new page and will only fail to allocate a new page on
 45089  ** an OOM error.
 45090  **
 45091  ** This routine should be invoked only after sqlite3PcacheFetch() fails.
 45092  */
 45093  SQLITE_PRIVATE int sqlite3PcacheFetchStress(
 45094    PCache *pCache,                 /* Obtain the page from this cache */
 45095    Pgno pgno,                      /* Page number to obtain */
 45096    sqlite3_pcache_page **ppPage    /* Write result here */
 45097  ){
 45098    PgHdr *pPg;
 45099    if( pCache->eCreate==2 ) return 0;
 45100  
 45101    if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
 45102      /* Find a dirty page to write-out and recycle. First try to find a 
 45103      ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
 45104      ** cleared), but if that is not possible settle for any other 
 45105      ** unreferenced dirty page.
 45106      **
 45107      ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
 45108      ** flag is currently referenced, then the following may leave pSynced
 45109      ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
 45110      ** cleared). This is Ok, as pSynced is just an optimization.  */
 45111      for(pPg=pCache->pSynced; 
 45112          pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
 45113          pPg=pPg->pDirtyPrev
 45114      );
 45115      pCache->pSynced = pPg;
 45116      if( !pPg ){
 45117        for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
 45118      }
 45119      if( pPg ){
 45120        int rc;
 45121  #ifdef SQLITE_LOG_CACHE_SPILL
 45122        sqlite3_log(SQLITE_FULL, 
 45123                    "spill page %d making room for %d - cache used: %d/%d",
 45124                    pPg->pgno, pgno,
 45125                    sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
 45126                  numberOfCachePages(pCache));
 45127  #endif
 45128        pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
 45129        rc = pCache->xStress(pCache->pStress, pPg);
 45130        pcacheDump(pCache);
 45131        if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
 45132          return rc;
 45133        }
 45134      }
 45135    }
 45136    *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
 45137    return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
 45138  }
 45139  
 45140  /*
 45141  ** This is a helper routine for sqlite3PcacheFetchFinish()
 45142  **
 45143  ** In the uncommon case where the page being fetched has not been
 45144  ** initialized, this routine is invoked to do the initialization.
 45145  ** This routine is broken out into a separate function since it
 45146  ** requires extra stack manipulation that can be avoided in the common
 45147  ** case.
 45148  */
 45149  static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
 45150    PCache *pCache,             /* Obtain the page from this cache */
 45151    Pgno pgno,                  /* Page number obtained */
 45152    sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
 45153  ){
 45154    PgHdr *pPgHdr;
 45155    assert( pPage!=0 );
 45156    pPgHdr = (PgHdr*)pPage->pExtra;
 45157    assert( pPgHdr->pPage==0 );
 45158    memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
 45159    pPgHdr->pPage = pPage;
 45160    pPgHdr->pData = pPage->pBuf;
 45161    pPgHdr->pExtra = (void *)&pPgHdr[1];
 45162    memset(pPgHdr->pExtra, 0, 8);
 45163    pPgHdr->pCache = pCache;
 45164    pPgHdr->pgno = pgno;
 45165    pPgHdr->flags = PGHDR_CLEAN;
 45166    return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
 45167  }
 45168  
 45169  /*
 45170  ** This routine converts the sqlite3_pcache_page object returned by
 45171  ** sqlite3PcacheFetch() into an initialized PgHdr object.  This routine
 45172  ** must be called after sqlite3PcacheFetch() in order to get a usable
 45173  ** result.
 45174  */
 45175  SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
 45176    PCache *pCache,             /* Obtain the page from this cache */
 45177    Pgno pgno,                  /* Page number obtained */
 45178    sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
 45179  ){
 45180    PgHdr *pPgHdr;
 45181  
 45182    assert( pPage!=0 );
 45183    pPgHdr = (PgHdr *)pPage->pExtra;
 45184  
 45185    if( !pPgHdr->pPage ){
 45186      return pcacheFetchFinishWithInit(pCache, pgno, pPage);
 45187    }
 45188    pCache->nRefSum++;
 45189    pPgHdr->nRef++;
 45190    assert( sqlite3PcachePageSanity(pPgHdr) );
 45191    return pPgHdr;
 45192  }
 45193  
 45194  /*
 45195  ** Decrement the reference count on a page. If the page is clean and the
 45196  ** reference count drops to 0, then it is made eligible for recycling.
 45197  */
 45198  SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
 45199    assert( p->nRef>0 );
 45200    p->pCache->nRefSum--;
 45201    if( (--p->nRef)==0 ){
 45202      if( p->flags&PGHDR_CLEAN ){
 45203        pcacheUnpin(p);
 45204      }else{
 45205        pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
 45206      }
 45207    }
 45208  }
 45209  
 45210  /*
 45211  ** Increase the reference count of a supplied page by 1.
 45212  */
 45213  SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
 45214    assert(p->nRef>0);
 45215    assert( sqlite3PcachePageSanity(p) );
 45216    p->nRef++;
 45217    p->pCache->nRefSum++;
 45218  }
 45219  
 45220  /*
 45221  ** Drop a page from the cache. There must be exactly one reference to the
 45222  ** page. This function deletes that reference, so after it returns the
 45223  ** page pointed to by p is invalid.
 45224  */
 45225  SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
 45226    assert( p->nRef==1 );
 45227    assert( sqlite3PcachePageSanity(p) );
 45228    if( p->flags&PGHDR_DIRTY ){
 45229      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
 45230    }
 45231    p->pCache->nRefSum--;
 45232    sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
 45233  }
 45234  
 45235  /*
 45236  ** Make sure the page is marked as dirty. If it isn't dirty already,
 45237  ** make it so.
 45238  */
 45239  SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
 45240    assert( p->nRef>0 );
 45241    assert( sqlite3PcachePageSanity(p) );
 45242    if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){    /*OPTIMIZATION-IF-FALSE*/
 45243      p->flags &= ~PGHDR_DONT_WRITE;
 45244      if( p->flags & PGHDR_CLEAN ){
 45245        p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
 45246        pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
 45247        assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
 45248        pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
 45249      }
 45250      assert( sqlite3PcachePageSanity(p) );
 45251    }
 45252  }
 45253  
 45254  /*
 45255  ** Make sure the page is marked as clean. If it isn't clean already,
 45256  ** make it so.
 45257  */
 45258  SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
 45259    assert( sqlite3PcachePageSanity(p) );
 45260    if( ALWAYS((p->flags & PGHDR_DIRTY)!=0) ){
 45261      assert( (p->flags & PGHDR_CLEAN)==0 );
 45262      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
 45263      p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
 45264      p->flags |= PGHDR_CLEAN;
 45265      pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
 45266      assert( sqlite3PcachePageSanity(p) );
 45267      if( p->nRef==0 ){
 45268        pcacheUnpin(p);
 45269      }
 45270    }
 45271  }
 45272  
 45273  /*
 45274  ** Make every page in the cache clean.
 45275  */
 45276  SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
 45277    PgHdr *p;
 45278    pcacheTrace(("%p.CLEAN-ALL\n",pCache));
 45279    while( (p = pCache->pDirty)!=0 ){
 45280      sqlite3PcacheMakeClean(p);
 45281    }
 45282  }
 45283  
 45284  /*
 45285  ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
 45286  */
 45287  SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
 45288    PgHdr *p;
 45289    pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
 45290    for(p=pCache->pDirty; p; p=p->pDirtyNext){
 45291      p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
 45292    }
 45293    pCache->pSynced = pCache->pDirtyTail;
 45294  }
 45295  
 45296  /*
 45297  ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
 45298  */
 45299  SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
 45300    PgHdr *p;
 45301    for(p=pCache->pDirty; p; p=p->pDirtyNext){
 45302      p->flags &= ~PGHDR_NEED_SYNC;
 45303    }
 45304    pCache->pSynced = pCache->pDirtyTail;
 45305  }
 45306  
 45307  /*
 45308  ** Change the page number of page p to newPgno. 
 45309  */
 45310  SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
 45311    PCache *pCache = p->pCache;
 45312    assert( p->nRef>0 );
 45313    assert( newPgno>0 );
 45314    assert( sqlite3PcachePageSanity(p) );
 45315    pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
 45316    sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
 45317    p->pgno = newPgno;
 45318    if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
 45319      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
 45320    }
 45321  }
 45322  
 45323  /*
 45324  ** Drop every cache entry whose page number is greater than "pgno". The
 45325  ** caller must ensure that there are no outstanding references to any pages
 45326  ** other than page 1 with a page number greater than pgno.
 45327  **
 45328  ** If there is a reference to page 1 and the pgno parameter passed to this
 45329  ** function is 0, then the data area associated with page 1 is zeroed, but
 45330  ** the page object is not dropped.
 45331  */
 45332  SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
 45333    if( pCache->pCache ){
 45334      PgHdr *p;
 45335      PgHdr *pNext;
 45336      pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
 45337      for(p=pCache->pDirty; p; p=pNext){
 45338        pNext = p->pDirtyNext;
 45339        /* This routine never gets call with a positive pgno except right
 45340        ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
 45341        ** it must be that pgno==0.
 45342        */
 45343        assert( p->pgno>0 );
 45344        if( p->pgno>pgno ){
 45345          assert( p->flags&PGHDR_DIRTY );
 45346          sqlite3PcacheMakeClean(p);
 45347        }
 45348      }
 45349      if( pgno==0 && pCache->nRefSum ){
 45350        sqlite3_pcache_page *pPage1;
 45351        pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
 45352        if( ALWAYS(pPage1) ){  /* Page 1 is always available in cache, because
 45353                               ** pCache->nRefSum>0 */
 45354          memset(pPage1->pBuf, 0, pCache->szPage);
 45355          pgno = 1;
 45356        }
 45357      }
 45358      sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
 45359    }
 45360  }
 45361  
 45362  /*
 45363  ** Close a cache.
 45364  */
 45365  SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
 45366    assert( pCache->pCache!=0 );
 45367    pcacheTrace(("%p.CLOSE\n",pCache));
 45368    sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
 45369  }
 45370  
 45371  /* 
 45372  ** Discard the contents of the cache.
 45373  */
 45374  SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
 45375    sqlite3PcacheTruncate(pCache, 0);
 45376  }
 45377  
 45378  /*
 45379  ** Merge two lists of pages connected by pDirty and in pgno order.
 45380  ** Do not bother fixing the pDirtyPrev pointers.
 45381  */
 45382  static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
 45383    PgHdr result, *pTail;
 45384    pTail = &result;
 45385    assert( pA!=0 && pB!=0 );
 45386    for(;;){
 45387      if( pA->pgno<pB->pgno ){
 45388        pTail->pDirty = pA;
 45389        pTail = pA;
 45390        pA = pA->pDirty;
 45391        if( pA==0 ){
 45392          pTail->pDirty = pB;
 45393          break;
 45394        }
 45395      }else{
 45396        pTail->pDirty = pB;
 45397        pTail = pB;
 45398        pB = pB->pDirty;
 45399        if( pB==0 ){
 45400          pTail->pDirty = pA;
 45401          break;
 45402        }
 45403      }
 45404    }
 45405    return result.pDirty;
 45406  }
 45407  
 45408  /*
 45409  ** Sort the list of pages in accending order by pgno.  Pages are
 45410  ** connected by pDirty pointers.  The pDirtyPrev pointers are
 45411  ** corrupted by this sort.
 45412  **
 45413  ** Since there cannot be more than 2^31 distinct pages in a database,
 45414  ** there cannot be more than 31 buckets required by the merge sorter.
 45415  ** One extra bucket is added to catch overflow in case something
 45416  ** ever changes to make the previous sentence incorrect.
 45417  */
 45418  #define N_SORT_BUCKET  32
 45419  static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
 45420    PgHdr *a[N_SORT_BUCKET], *p;
 45421    int i;
 45422    memset(a, 0, sizeof(a));
 45423    while( pIn ){
 45424      p = pIn;
 45425      pIn = p->pDirty;
 45426      p->pDirty = 0;
 45427      for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
 45428        if( a[i]==0 ){
 45429          a[i] = p;
 45430          break;
 45431        }else{
 45432          p = pcacheMergeDirtyList(a[i], p);
 45433          a[i] = 0;
 45434        }
 45435      }
 45436      if( NEVER(i==N_SORT_BUCKET-1) ){
 45437        /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
 45438        ** the input list.  But that is impossible.
 45439        */
 45440        a[i] = pcacheMergeDirtyList(a[i], p);
 45441      }
 45442    }
 45443    p = a[0];
 45444    for(i=1; i<N_SORT_BUCKET; i++){
 45445      if( a[i]==0 ) continue;
 45446      p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
 45447    }
 45448    return p;
 45449  }
 45450  
 45451  /*
 45452  ** Return a list of all dirty pages in the cache, sorted by page number.
 45453  */
 45454  SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
 45455    PgHdr *p;
 45456    for(p=pCache->pDirty; p; p=p->pDirtyNext){
 45457      p->pDirty = p->pDirtyNext;
 45458    }
 45459    return pcacheSortDirtyList(pCache->pDirty);
 45460  }
 45461  
 45462  /* 
 45463  ** Return the total number of references to all pages held by the cache.
 45464  **
 45465  ** This is not the total number of pages referenced, but the sum of the
 45466  ** reference count for all pages.
 45467  */
 45468  SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
 45469    return pCache->nRefSum;
 45470  }
 45471  
 45472  /*
 45473  ** Return the number of references to the page supplied as an argument.
 45474  */
 45475  SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
 45476    return p->nRef;
 45477  }
 45478  
 45479  /* 
 45480  ** Return the total number of pages in the cache.
 45481  */
 45482  SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
 45483    assert( pCache->pCache!=0 );
 45484    return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
 45485  }
 45486  
 45487  #ifdef SQLITE_TEST
 45488  /*
 45489  ** Get the suggested cache-size value.
 45490  */
 45491  SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
 45492    return numberOfCachePages(pCache);
 45493  }
 45494  #endif
 45495  
 45496  /*
 45497  ** Set the suggested cache-size value.
 45498  */
 45499  SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
 45500    assert( pCache->pCache!=0 );
 45501    pCache->szCache = mxPage;
 45502    sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
 45503                                           numberOfCachePages(pCache));
 45504  }
 45505  
 45506  /*
 45507  ** Set the suggested cache-spill value.  Make no changes if if the
 45508  ** argument is zero.  Return the effective cache-spill size, which will
 45509  ** be the larger of the szSpill and szCache.
 45510  */
 45511  SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
 45512    int res;
 45513    assert( p->pCache!=0 );
 45514    if( mxPage ){
 45515      if( mxPage<0 ){
 45516        mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
 45517      }
 45518      p->szSpill = mxPage;
 45519    }
 45520    res = numberOfCachePages(p);
 45521    if( res<p->szSpill ) res = p->szSpill; 
 45522    return res;
 45523  }
 45524  
 45525  /*
 45526  ** Free up as much memory as possible from the page cache.
 45527  */
 45528  SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
 45529    assert( pCache->pCache!=0 );
 45530    sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
 45531  }
 45532  
 45533  /*
 45534  ** Return the size of the header added by this middleware layer
 45535  ** in the page-cache hierarchy.
 45536  */
 45537  SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
 45538  
 45539  /*
 45540  ** Return the number of dirty pages currently in the cache, as a percentage
 45541  ** of the configured cache size.
 45542  */
 45543  SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
 45544    PgHdr *pDirty;
 45545    int nDirty = 0;
 45546    int nCache = numberOfCachePages(pCache);
 45547    for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
 45548    return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
 45549  }
 45550  
 45551  #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
 45552  /*
 45553  ** For all dirty pages currently in the cache, invoke the specified
 45554  ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
 45555  ** defined.
 45556  */
 45557  SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
 45558    PgHdr *pDirty;
 45559    for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
 45560      xIter(pDirty);
 45561    }
 45562  }
 45563  #endif
 45564  
 45565  /************** End of pcache.c **********************************************/
 45566  /************** Begin file pcache1.c *****************************************/
 45567  /*
 45568  ** 2008 November 05
 45569  **
 45570  ** The author disclaims copyright to this source code.  In place of
 45571  ** a legal notice, here is a blessing:
 45572  **
 45573  **    May you do good and not evil.
 45574  **    May you find forgiveness for yourself and forgive others.
 45575  **    May you share freely, never taking more than you give.
 45576  **
 45577  *************************************************************************
 45578  **
 45579  ** This file implements the default page cache implementation (the
 45580  ** sqlite3_pcache interface). It also contains part of the implementation
 45581  ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
 45582  ** If the default page cache implementation is overridden, then neither of
 45583  ** these two features are available.
 45584  **
 45585  ** A Page cache line looks like this:
 45586  **
 45587  **  -------------------------------------------------------------
 45588  **  |  database page content   |  PgHdr1  |  MemPage  |  PgHdr  |
 45589  **  -------------------------------------------------------------
 45590  **
 45591  ** The database page content is up front (so that buffer overreads tend to
 45592  ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions).   MemPage
 45593  ** is the extension added by the btree.c module containing information such
 45594  ** as the database page number and how that database page is used.  PgHdr
 45595  ** is added by the pcache.c layer and contains information used to keep track
 45596  ** of which pages are "dirty".  PgHdr1 is an extension added by this
 45597  ** module (pcache1.c).  The PgHdr1 header is a subclass of sqlite3_pcache_page.
 45598  ** PgHdr1 contains information needed to look up a page by its page number.
 45599  ** The superclass sqlite3_pcache_page.pBuf points to the start of the
 45600  ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
 45601  **
 45602  ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
 45603  ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size).  The
 45604  ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
 45605  ** size can vary according to architecture, compile-time options, and
 45606  ** SQLite library version number.
 45607  **
 45608  ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
 45609  ** using a separate memory allocation from the database page content.  This
 45610  ** seeks to overcome the "clownshoe" problem (also called "internal
 45611  ** fragmentation" in academic literature) of allocating a few bytes more
 45612  ** than a power of two with the memory allocator rounding up to the next
 45613  ** power of two, and leaving the rounded-up space unused.
 45614  **
 45615  ** This module tracks pointers to PgHdr1 objects.  Only pcache.c communicates
 45616  ** with this module.  Information is passed back and forth as PgHdr1 pointers.
 45617  **
 45618  ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
 45619  ** The btree.c module deals with pointers to MemPage objects.
 45620  **
 45621  ** SOURCE OF PAGE CACHE MEMORY:
 45622  **
 45623  ** Memory for a page might come from any of three sources:
 45624  **
 45625  **    (1)  The general-purpose memory allocator - sqlite3Malloc()
 45626  **    (2)  Global page-cache memory provided using sqlite3_config() with
 45627  **         SQLITE_CONFIG_PAGECACHE.
 45628  **    (3)  PCache-local bulk allocation.
 45629  **
 45630  ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
 45631  ** that is allocated when the page cache is created.  The size of the local
 45632  ** bulk allocation can be adjusted using 
 45633  **
 45634  **     sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
 45635  **
 45636  ** If N is positive, then N pages worth of memory are allocated using a single
 45637  ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
 45638  ** Or if N is negative, then -1024*N bytes of memory are allocated and used
 45639  ** for as many pages as can be accomodated.
 45640  **
 45641  ** Only one of (2) or (3) can be used.  Once the memory available to (2) or
 45642  ** (3) is exhausted, subsequent allocations fail over to the general-purpose
 45643  ** memory allocator (1).
 45644  **
 45645  ** Earlier versions of SQLite used only methods (1) and (2).  But experiments
 45646  ** show that method (3) with N==100 provides about a 5% performance boost for
 45647  ** common workloads.
 45648  */
 45649  /* #include "sqliteInt.h" */
 45650  
 45651  typedef struct PCache1 PCache1;
 45652  typedef struct PgHdr1 PgHdr1;
 45653  typedef struct PgFreeslot PgFreeslot;
 45654  typedef struct PGroup PGroup;
 45655  
 45656  /*
 45657  ** Each cache entry is represented by an instance of the following 
 45658  ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
 45659  ** PgHdr1.pCache->szPage bytes is allocated directly before this structure 
 45660  ** in memory.
 45661  */
 45662  struct PgHdr1 {
 45663    sqlite3_pcache_page page;      /* Base class. Must be first. pBuf & pExtra */
 45664    unsigned int iKey;             /* Key value (page number) */
 45665    u8 isBulkLocal;                /* This page from bulk local storage */
 45666    u8 isAnchor;                   /* This is the PGroup.lru element */
 45667    PgHdr1 *pNext;                 /* Next in hash table chain */
 45668    PCache1 *pCache;               /* Cache that currently owns this page */
 45669    PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
 45670    PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
 45671  };
 45672  
 45673  /*
 45674  ** A page is pinned if it is no on the LRU list
 45675  */
 45676  #define PAGE_IS_PINNED(p)    ((p)->pLruNext==0)
 45677  #define PAGE_IS_UNPINNED(p)  ((p)->pLruNext!=0)
 45678  
 45679  /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set 
 45680  ** of one or more PCaches that are able to recycle each other's unpinned
 45681  ** pages when they are under memory pressure.  A PGroup is an instance of
 45682  ** the following object.
 45683  **
 45684  ** This page cache implementation works in one of two modes:
 45685  **
 45686  **   (1)  Every PCache is the sole member of its own PGroup.  There is
 45687  **        one PGroup per PCache.
 45688  **
 45689  **   (2)  There is a single global PGroup that all PCaches are a member
 45690  **        of.
 45691  **
 45692  ** Mode 1 uses more memory (since PCache instances are not able to rob
 45693  ** unused pages from other PCaches) but it also operates without a mutex,
 45694  ** and is therefore often faster.  Mode 2 requires a mutex in order to be
 45695  ** threadsafe, but recycles pages more efficiently.
 45696  **
 45697  ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
 45698  ** PGroup which is the pcache1.grp global variable and its mutex is
 45699  ** SQLITE_MUTEX_STATIC_LRU.
 45700  */
 45701  struct PGroup {
 45702    sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
 45703    unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
 45704    unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
 45705    unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
 45706    unsigned int nPurgeable;       /* Number of purgeable pages allocated */
 45707    PgHdr1 lru;                    /* The beginning and end of the LRU list */
 45708  };
 45709  
 45710  /* Each page cache is an instance of the following object.  Every
 45711  ** open database file (including each in-memory database and each
 45712  ** temporary or transient database) has a single page cache which
 45713  ** is an instance of this object.
 45714  **
 45715  ** Pointers to structures of this type are cast and returned as 
 45716  ** opaque sqlite3_pcache* handles.
 45717  */
 45718  struct PCache1 {
 45719    /* Cache configuration parameters. Page size (szPage) and the purgeable
 45720    ** flag (bPurgeable) and the pnPurgeable pointer are all set when the
 45721    ** cache is created and are never changed thereafter. nMax may be 
 45722    ** modified at any time by a call to the pcache1Cachesize() method.
 45723    ** The PGroup mutex must be held when accessing nMax.
 45724    */
 45725    PGroup *pGroup;                     /* PGroup this cache belongs to */
 45726    unsigned int *pnPurgeable;          /* Pointer to pGroup->nPurgeable */
 45727    int szPage;                         /* Size of database content section */
 45728    int szExtra;                        /* sizeof(MemPage)+sizeof(PgHdr) */
 45729    int szAlloc;                        /* Total size of one pcache line */
 45730    int bPurgeable;                     /* True if cache is purgeable */
 45731    unsigned int nMin;                  /* Minimum number of pages reserved */
 45732    unsigned int nMax;                  /* Configured "cache_size" value */
 45733    unsigned int n90pct;                /* nMax*9/10 */
 45734    unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
 45735  
 45736    /* Hash table of all pages. The following variables may only be accessed
 45737    ** when the accessor is holding the PGroup mutex.
 45738    */
 45739    unsigned int nRecyclable;           /* Number of pages in the LRU list */
 45740    unsigned int nPage;                 /* Total number of pages in apHash */
 45741    unsigned int nHash;                 /* Number of slots in apHash[] */
 45742    PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
 45743    PgHdr1 *pFree;                      /* List of unused pcache-local pages */
 45744    void *pBulk;                        /* Bulk memory used by pcache-local */
 45745  };
 45746  
 45747  /*
 45748  ** Free slots in the allocator used to divide up the global page cache
 45749  ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
 45750  */
 45751  struct PgFreeslot {
 45752    PgFreeslot *pNext;  /* Next free slot */
 45753  };
 45754  
 45755  /*
 45756  ** Global data used by this cache.
 45757  */
 45758  static SQLITE_WSD struct PCacheGlobal {
 45759    PGroup grp;                    /* The global PGroup for mode (2) */
 45760  
 45761    /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
 45762    ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
 45763    ** fixed at sqlite3_initialize() time and do not require mutex protection.
 45764    ** The nFreeSlot and pFree values do require mutex protection.
 45765    */
 45766    int isInit;                    /* True if initialized */
 45767    int separateCache;             /* Use a new PGroup for each PCache */
 45768    int nInitPage;                 /* Initial bulk allocation size */   
 45769    int szSlot;                    /* Size of each free slot */
 45770    int nSlot;                     /* The number of pcache slots */
 45771    int nReserve;                  /* Try to keep nFreeSlot above this */
 45772    void *pStart, *pEnd;           /* Bounds of global page cache memory */
 45773    /* Above requires no mutex.  Use mutex below for variable that follow. */
 45774    sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
 45775    PgFreeslot *pFree;             /* Free page blocks */
 45776    int nFreeSlot;                 /* Number of unused pcache slots */
 45777    /* The following value requires a mutex to change.  We skip the mutex on
 45778    ** reading because (1) most platforms read a 32-bit integer atomically and
 45779    ** (2) even if an incorrect value is read, no great harm is done since this
 45780    ** is really just an optimization. */
 45781    int bUnderPressure;            /* True if low on PAGECACHE memory */
 45782  } pcache1_g;
 45783  
 45784  /*
 45785  ** All code in this file should access the global structure above via the
 45786  ** alias "pcache1". This ensures that the WSD emulation is used when
 45787  ** compiling for systems that do not support real WSD.
 45788  */
 45789  #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
 45790  
 45791  /*
 45792  ** Macros to enter and leave the PCache LRU mutex.
 45793  */
 45794  #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
 45795  # define pcache1EnterMutex(X)  assert((X)->mutex==0)
 45796  # define pcache1LeaveMutex(X)  assert((X)->mutex==0)
 45797  # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
 45798  #else
 45799  # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
 45800  # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
 45801  # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
 45802  #endif
 45803  
 45804  /******************************************************************************/
 45805  /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
 45806  
 45807  
 45808  /*
 45809  ** This function is called during initialization if a static buffer is 
 45810  ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
 45811  ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
 45812  ** enough to contain 'n' buffers of 'sz' bytes each.
 45813  **
 45814  ** This routine is called from sqlite3_initialize() and so it is guaranteed
 45815  ** to be serialized already.  There is no need for further mutexing.
 45816  */
 45817  SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
 45818    if( pcache1.isInit ){
 45819      PgFreeslot *p;
 45820      if( pBuf==0 ) sz = n = 0;
 45821      if( n==0 ) sz = 0;
 45822      sz = ROUNDDOWN8(sz);
 45823      pcache1.szSlot = sz;
 45824      pcache1.nSlot = pcache1.nFreeSlot = n;
 45825      pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
 45826      pcache1.pStart = pBuf;
 45827      pcache1.pFree = 0;
 45828      pcache1.bUnderPressure = 0;
 45829      while( n-- ){
 45830        p = (PgFreeslot*)pBuf;
 45831        p->pNext = pcache1.pFree;
 45832        pcache1.pFree = p;
 45833        pBuf = (void*)&((char*)pBuf)[sz];
 45834      }
 45835      pcache1.pEnd = pBuf;
 45836    }
 45837  }
 45838  
 45839  /*
 45840  ** Try to initialize the pCache->pFree and pCache->pBulk fields.  Return
 45841  ** true if pCache->pFree ends up containing one or more free pages.
 45842  */
 45843  static int pcache1InitBulk(PCache1 *pCache){
 45844    i64 szBulk;
 45845    char *zBulk;
 45846    if( pcache1.nInitPage==0 ) return 0;
 45847    /* Do not bother with a bulk allocation if the cache size very small */
 45848    if( pCache->nMax<3 ) return 0;
 45849    sqlite3BeginBenignMalloc();
 45850    if( pcache1.nInitPage>0 ){
 45851      szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
 45852    }else{
 45853      szBulk = -1024 * (i64)pcache1.nInitPage;
 45854    }
 45855    if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
 45856      szBulk = pCache->szAlloc*(i64)pCache->nMax;
 45857    }
 45858    zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
 45859    sqlite3EndBenignMalloc();
 45860    if( zBulk ){
 45861      int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
 45862      do{
 45863        PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
 45864        pX->page.pBuf = zBulk;
 45865        pX->page.pExtra = &pX[1];
 45866        pX->isBulkLocal = 1;
 45867        pX->isAnchor = 0;
 45868        pX->pNext = pCache->pFree;
 45869        pCache->pFree = pX;
 45870        zBulk += pCache->szAlloc;
 45871      }while( --nBulk );
 45872    }
 45873    return pCache->pFree!=0;
 45874  }
 45875  
 45876  /*
 45877  ** Malloc function used within this file to allocate space from the buffer
 45878  ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
 45879  ** such buffer exists or there is no space left in it, this function falls 
 45880  ** back to sqlite3Malloc().
 45881  **
 45882  ** Multiple threads can run this routine at the same time.  Global variables
 45883  ** in pcache1 need to be protected via mutex.
 45884  */
 45885  static void *pcache1Alloc(int nByte){
 45886    void *p = 0;
 45887    assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
 45888    if( nByte<=pcache1.szSlot ){
 45889      sqlite3_mutex_enter(pcache1.mutex);
 45890      p = (PgHdr1 *)pcache1.pFree;
 45891      if( p ){
 45892        pcache1.pFree = pcache1.pFree->pNext;
 45893        pcache1.nFreeSlot--;
 45894        pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
 45895        assert( pcache1.nFreeSlot>=0 );
 45896        sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
 45897        sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
 45898      }
 45899      sqlite3_mutex_leave(pcache1.mutex);
 45900    }
 45901    if( p==0 ){
 45902      /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
 45903      ** it from sqlite3Malloc instead.
 45904      */
 45905      p = sqlite3Malloc(nByte);
 45906  #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
 45907      if( p ){
 45908        int sz = sqlite3MallocSize(p);
 45909        sqlite3_mutex_enter(pcache1.mutex);
 45910        sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
 45911        sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
 45912        sqlite3_mutex_leave(pcache1.mutex);
 45913      }
 45914  #endif
 45915      sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
 45916    }
 45917    return p;
 45918  }
 45919  
 45920  /*
 45921  ** Free an allocated buffer obtained from pcache1Alloc().
 45922  */
 45923  static void pcache1Free(void *p){
 45924    if( p==0 ) return;
 45925    if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
 45926      PgFreeslot *pSlot;
 45927      sqlite3_mutex_enter(pcache1.mutex);
 45928      sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
 45929      pSlot = (PgFreeslot*)p;
 45930      pSlot->pNext = pcache1.pFree;
 45931      pcache1.pFree = pSlot;
 45932      pcache1.nFreeSlot++;
 45933      pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
 45934      assert( pcache1.nFreeSlot<=pcache1.nSlot );
 45935      sqlite3_mutex_leave(pcache1.mutex);
 45936    }else{
 45937      assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
 45938      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
 45939  #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
 45940      {
 45941        int nFreed = 0;
 45942        nFreed = sqlite3MallocSize(p);
 45943        sqlite3_mutex_enter(pcache1.mutex);
 45944        sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
 45945        sqlite3_mutex_leave(pcache1.mutex);
 45946      }
 45947  #endif
 45948      sqlite3_free(p);
 45949    }
 45950  }
 45951  
 45952  #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
 45953  /*
 45954  ** Return the size of a pcache allocation
 45955  */
 45956  static int pcache1MemSize(void *p){
 45957    if( p>=pcache1.pStart && p<pcache1.pEnd ){
 45958      return pcache1.szSlot;
 45959    }else{
 45960      int iSize;
 45961      assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
 45962      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
 45963      iSize = sqlite3MallocSize(p);
 45964      sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
 45965      return iSize;
 45966    }
 45967  }
 45968  #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
 45969  
 45970  /*
 45971  ** Allocate a new page object initially associated with cache pCache.
 45972  */
 45973  static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
 45974    PgHdr1 *p = 0;
 45975    void *pPg;
 45976  
 45977    assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
 45978    if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
 45979      p = pCache->pFree;
 45980      pCache->pFree = p->pNext;
 45981      p->pNext = 0;
 45982    }else{
 45983  #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
 45984      /* The group mutex must be released before pcache1Alloc() is called. This
 45985      ** is because it might call sqlite3_release_memory(), which assumes that 
 45986      ** this mutex is not held. */
 45987      assert( pcache1.separateCache==0 );
 45988      assert( pCache->pGroup==&pcache1.grp );
 45989      pcache1LeaveMutex(pCache->pGroup);
 45990  #endif
 45991      if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
 45992  #ifdef SQLITE_PCACHE_SEPARATE_HEADER
 45993      pPg = pcache1Alloc(pCache->szPage);
 45994      p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
 45995      if( !pPg || !p ){
 45996        pcache1Free(pPg);
 45997        sqlite3_free(p);
 45998        pPg = 0;
 45999      }
 46000  #else
 46001      pPg = pcache1Alloc(pCache->szAlloc);
 46002      p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
 46003  #endif
 46004      if( benignMalloc ){ sqlite3EndBenignMalloc(); }
 46005  #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
 46006      pcache1EnterMutex(pCache->pGroup);
 46007  #endif
 46008      if( pPg==0 ) return 0;
 46009      p->page.pBuf = pPg;
 46010      p->page.pExtra = &p[1];
 46011      p->isBulkLocal = 0;
 46012      p->isAnchor = 0;
 46013    }
 46014    (*pCache->pnPurgeable)++;
 46015    return p;
 46016  }
 46017  
 46018  /*
 46019  ** Free a page object allocated by pcache1AllocPage().
 46020  */
 46021  static void pcache1FreePage(PgHdr1 *p){
 46022    PCache1 *pCache;
 46023    assert( p!=0 );
 46024    pCache = p->pCache;
 46025    assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
 46026    if( p->isBulkLocal ){
 46027      p->pNext = pCache->pFree;
 46028      pCache->pFree = p;
 46029    }else{
 46030      pcache1Free(p->page.pBuf);
 46031  #ifdef SQLITE_PCACHE_SEPARATE_HEADER
 46032      sqlite3_free(p);
 46033  #endif
 46034    }
 46035    (*pCache->pnPurgeable)--;
 46036  }
 46037  
 46038  /*
 46039  ** Malloc function used by SQLite to obtain space from the buffer configured
 46040  ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
 46041  ** exists, this function falls back to sqlite3Malloc().
 46042  */
 46043  SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
 46044    return pcache1Alloc(sz);
 46045  }
 46046  
 46047  /*
 46048  ** Free an allocated buffer obtained from sqlite3PageMalloc().
 46049  */
 46050  SQLITE_PRIVATE void sqlite3PageFree(void *p){
 46051    pcache1Free(p);
 46052  }
 46053  
 46054  
 46055  /*
 46056  ** Return true if it desirable to avoid allocating a new page cache
 46057  ** entry.
 46058  **
 46059  ** If memory was allocated specifically to the page cache using
 46060  ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
 46061  ** it is desirable to avoid allocating a new page cache entry because
 46062  ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
 46063  ** for all page cache needs and we should not need to spill the
 46064  ** allocation onto the heap.
 46065  **
 46066  ** Or, the heap is used for all page cache memory but the heap is
 46067  ** under memory pressure, then again it is desirable to avoid
 46068  ** allocating a new page cache entry in order to avoid stressing
 46069  ** the heap even further.
 46070  */
 46071  static int pcache1UnderMemoryPressure(PCache1 *pCache){
 46072    if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
 46073      return pcache1.bUnderPressure;
 46074    }else{
 46075      return sqlite3HeapNearlyFull();
 46076    }
 46077  }
 46078  
 46079  /******************************************************************************/
 46080  /******** General Implementation Functions ************************************/
 46081  
 46082  /*
 46083  ** This function is used to resize the hash table used by the cache passed
 46084  ** as the first argument.
 46085  **
 46086  ** The PCache mutex must be held when this function is called.
 46087  */
 46088  static void pcache1ResizeHash(PCache1 *p){
 46089    PgHdr1 **apNew;
 46090    unsigned int nNew;
 46091    unsigned int i;
 46092  
 46093    assert( sqlite3_mutex_held(p->pGroup->mutex) );
 46094  
 46095    nNew = p->nHash*2;
 46096    if( nNew<256 ){
 46097      nNew = 256;
 46098    }
 46099  
 46100    pcache1LeaveMutex(p->pGroup);
 46101    if( p->nHash ){ sqlite3BeginBenignMalloc(); }
 46102    apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
 46103    if( p->nHash ){ sqlite3EndBenignMalloc(); }
 46104    pcache1EnterMutex(p->pGroup);
 46105    if( apNew ){
 46106      for(i=0; i<p->nHash; i++){
 46107        PgHdr1 *pPage;
 46108        PgHdr1 *pNext = p->apHash[i];
 46109        while( (pPage = pNext)!=0 ){
 46110          unsigned int h = pPage->iKey % nNew;
 46111          pNext = pPage->pNext;
 46112          pPage->pNext = apNew[h];
 46113          apNew[h] = pPage;
 46114        }
 46115      }
 46116      sqlite3_free(p->apHash);
 46117      p->apHash = apNew;
 46118      p->nHash = nNew;
 46119    }
 46120  }
 46121  
 46122  /*
 46123  ** This function is used internally to remove the page pPage from the 
 46124  ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
 46125  ** LRU list, then this function is a no-op.
 46126  **
 46127  ** The PGroup mutex must be held when this function is called.
 46128  */
 46129  static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
 46130    assert( pPage!=0 );
 46131    assert( PAGE_IS_UNPINNED(pPage) );
 46132    assert( pPage->pLruNext );
 46133    assert( pPage->pLruPrev );
 46134    assert( sqlite3_mutex_held(pPage->pCache->pGroup->mutex) );
 46135    pPage->pLruPrev->pLruNext = pPage->pLruNext;
 46136    pPage->pLruNext->pLruPrev = pPage->pLruPrev;
 46137    pPage->pLruNext = 0;
 46138    pPage->pLruPrev = 0;
 46139    assert( pPage->isAnchor==0 );
 46140    assert( pPage->pCache->pGroup->lru.isAnchor==1 );
 46141    pPage->pCache->nRecyclable--;
 46142    return pPage;
 46143  }
 46144  
 46145  
 46146  /*
 46147  ** Remove the page supplied as an argument from the hash table 
 46148  ** (PCache1.apHash structure) that it is currently stored in.
 46149  ** Also free the page if freePage is true.
 46150  **
 46151  ** The PGroup mutex must be held when this function is called.
 46152  */
 46153  static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
 46154    unsigned int h;
 46155    PCache1 *pCache = pPage->pCache;
 46156    PgHdr1 **pp;
 46157  
 46158    assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
 46159    h = pPage->iKey % pCache->nHash;
 46160    for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
 46161    *pp = (*pp)->pNext;
 46162  
 46163    pCache->nPage--;
 46164    if( freeFlag ) pcache1FreePage(pPage);
 46165  }
 46166  
 46167  /*
 46168  ** If there are currently more than nMaxPage pages allocated, try
 46169  ** to recycle pages to reduce the number allocated to nMaxPage.
 46170  */
 46171  static void pcache1EnforceMaxPage(PCache1 *pCache){
 46172    PGroup *pGroup = pCache->pGroup;
 46173    PgHdr1 *p;
 46174    assert( sqlite3_mutex_held(pGroup->mutex) );
 46175    while( pGroup->nPurgeable>pGroup->nMaxPage
 46176        && (p=pGroup->lru.pLruPrev)->isAnchor==0
 46177    ){
 46178      assert( p->pCache->pGroup==pGroup );
 46179      assert( PAGE_IS_UNPINNED(p) );
 46180      pcache1PinPage(p);
 46181      pcache1RemoveFromHash(p, 1);
 46182    }
 46183    if( pCache->nPage==0 && pCache->pBulk ){
 46184      sqlite3_free(pCache->pBulk);
 46185      pCache->pBulk = pCache->pFree = 0;
 46186    }
 46187  }
 46188  
 46189  /*
 46190  ** Discard all pages from cache pCache with a page number (key value) 
 46191  ** greater than or equal to iLimit. Any pinned pages that meet this 
 46192  ** criteria are unpinned before they are discarded.
 46193  **
 46194  ** The PCache mutex must be held when this function is called.
 46195  */
 46196  static void pcache1TruncateUnsafe(
 46197    PCache1 *pCache,             /* The cache to truncate */
 46198    unsigned int iLimit          /* Drop pages with this pgno or larger */
 46199  ){
 46200    TESTONLY( int nPage = 0; )  /* To assert pCache->nPage is correct */
 46201    unsigned int h, iStop;
 46202    assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
 46203    assert( pCache->iMaxKey >= iLimit );
 46204    assert( pCache->nHash > 0 );
 46205    if( pCache->iMaxKey - iLimit < pCache->nHash ){
 46206      /* If we are just shaving the last few pages off the end of the
 46207      ** cache, then there is no point in scanning the entire hash table.
 46208      ** Only scan those hash slots that might contain pages that need to
 46209      ** be removed. */
 46210      h = iLimit % pCache->nHash;
 46211      iStop = pCache->iMaxKey % pCache->nHash;
 46212      TESTONLY( nPage = -10; )  /* Disable the pCache->nPage validity check */
 46213    }else{
 46214      /* This is the general case where many pages are being removed.
 46215      ** It is necessary to scan the entire hash table */
 46216      h = pCache->nHash/2;
 46217      iStop = h - 1;
 46218    }
 46219    for(;;){
 46220      PgHdr1 **pp;
 46221      PgHdr1 *pPage;
 46222      assert( h<pCache->nHash );
 46223      pp = &pCache->apHash[h]; 
 46224      while( (pPage = *pp)!=0 ){
 46225        if( pPage->iKey>=iLimit ){
 46226          pCache->nPage--;
 46227          *pp = pPage->pNext;
 46228          if( PAGE_IS_UNPINNED(pPage) ) pcache1PinPage(pPage);
 46229          pcache1FreePage(pPage);
 46230        }else{
 46231          pp = &pPage->pNext;
 46232          TESTONLY( if( nPage>=0 ) nPage++; )
 46233        }
 46234      }
 46235      if( h==iStop ) break;
 46236      h = (h+1) % pCache->nHash;
 46237    }
 46238    assert( nPage<0 || pCache->nPage==(unsigned)nPage );
 46239  }
 46240  
 46241  /******************************************************************************/
 46242  /******** sqlite3_pcache Methods **********************************************/
 46243  
 46244  /*
 46245  ** Implementation of the sqlite3_pcache.xInit method.
 46246  */
 46247  static int pcache1Init(void *NotUsed){
 46248    UNUSED_PARAMETER(NotUsed);
 46249    assert( pcache1.isInit==0 );
 46250    memset(&pcache1, 0, sizeof(pcache1));
 46251  
 46252  
 46253    /*
 46254    ** The pcache1.separateCache variable is true if each PCache has its own
 46255    ** private PGroup (mode-1).  pcache1.separateCache is false if the single
 46256    ** PGroup in pcache1.grp is used for all page caches (mode-2).
 46257    **
 46258    **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
 46259    **
 46260    **   *  Use a unified cache in single-threaded applications that have
 46261    **      configured a start-time buffer for use as page-cache memory using
 46262    **      sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL 
 46263    **      pBuf argument.
 46264    **
 46265    **   *  Otherwise use separate caches (mode-1)
 46266    */
 46267  #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
 46268    pcache1.separateCache = 0;
 46269  #elif SQLITE_THREADSAFE
 46270    pcache1.separateCache = sqlite3GlobalConfig.pPage==0
 46271                            || sqlite3GlobalConfig.bCoreMutex>0;
 46272  #else
 46273    pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
 46274  #endif
 46275  
 46276  #if SQLITE_THREADSAFE
 46277    if( sqlite3GlobalConfig.bCoreMutex ){
 46278      pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
 46279      pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
 46280    }
 46281  #endif
 46282    if( pcache1.separateCache
 46283     && sqlite3GlobalConfig.nPage!=0
 46284     && sqlite3GlobalConfig.pPage==0
 46285    ){
 46286      pcache1.nInitPage = sqlite3GlobalConfig.nPage;
 46287    }else{
 46288      pcache1.nInitPage = 0;
 46289    }
 46290    pcache1.grp.mxPinned = 10;
 46291    pcache1.isInit = 1;
 46292    return SQLITE_OK;
 46293  }
 46294  
 46295  /*
 46296  ** Implementation of the sqlite3_pcache.xShutdown method.
 46297  ** Note that the static mutex allocated in xInit does 
 46298  ** not need to be freed.
 46299  */
 46300  static void pcache1Shutdown(void *NotUsed){
 46301    UNUSED_PARAMETER(NotUsed);
 46302    assert( pcache1.isInit!=0 );
 46303    memset(&pcache1, 0, sizeof(pcache1));
 46304  }
 46305  
 46306  /* forward declaration */
 46307  static void pcache1Destroy(sqlite3_pcache *p);
 46308  
 46309  /*
 46310  ** Implementation of the sqlite3_pcache.xCreate method.
 46311  **
 46312  ** Allocate a new cache.
 46313  */
 46314  static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
 46315    PCache1 *pCache;      /* The newly created page cache */
 46316    PGroup *pGroup;       /* The group the new page cache will belong to */
 46317    int sz;               /* Bytes of memory required to allocate the new cache */
 46318  
 46319    assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
 46320    assert( szExtra < 300 );
 46321  
 46322    sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
 46323    pCache = (PCache1 *)sqlite3MallocZero(sz);
 46324    if( pCache ){
 46325      if( pcache1.separateCache ){
 46326        pGroup = (PGroup*)&pCache[1];
 46327        pGroup->mxPinned = 10;
 46328      }else{
 46329        pGroup = &pcache1.grp;
 46330      }
 46331      if( pGroup->lru.isAnchor==0 ){
 46332        pGroup->lru.isAnchor = 1;
 46333        pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
 46334      }
 46335      pCache->pGroup = pGroup;
 46336      pCache->szPage = szPage;
 46337      pCache->szExtra = szExtra;
 46338      pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
 46339      pCache->bPurgeable = (bPurgeable ? 1 : 0);
 46340      pcache1EnterMutex(pGroup);
 46341      pcache1ResizeHash(pCache);
 46342      if( bPurgeable ){
 46343        pCache->nMin = 10;
 46344        pGroup->nMinPage += pCache->nMin;
 46345        pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
 46346        pCache->pnPurgeable = &pGroup->nPurgeable;
 46347      }else{
 46348        static unsigned int dummyCurrentPage;
 46349        pCache->pnPurgeable = &dummyCurrentPage;
 46350      }
 46351      pcache1LeaveMutex(pGroup);
 46352      if( pCache->nHash==0 ){
 46353        pcache1Destroy((sqlite3_pcache*)pCache);
 46354        pCache = 0;
 46355      }
 46356    }
 46357    return (sqlite3_pcache *)pCache;
 46358  }
 46359  
 46360  /*
 46361  ** Implementation of the sqlite3_pcache.xCachesize method. 
 46362  **
 46363  ** Configure the cache_size limit for a cache.
 46364  */
 46365  static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
 46366    PCache1 *pCache = (PCache1 *)p;
 46367    if( pCache->bPurgeable ){
 46368      PGroup *pGroup = pCache->pGroup;
 46369      pcache1EnterMutex(pGroup);
 46370      pGroup->nMaxPage += (nMax - pCache->nMax);
 46371      pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
 46372      pCache->nMax = nMax;
 46373      pCache->n90pct = pCache->nMax*9/10;
 46374      pcache1EnforceMaxPage(pCache);
 46375      pcache1LeaveMutex(pGroup);
 46376    }
 46377  }
 46378  
 46379  /*
 46380  ** Implementation of the sqlite3_pcache.xShrink method. 
 46381  **
 46382  ** Free up as much memory as possible.
 46383  */
 46384  static void pcache1Shrink(sqlite3_pcache *p){
 46385    PCache1 *pCache = (PCache1*)p;
 46386    if( pCache->bPurgeable ){
 46387      PGroup *pGroup = pCache->pGroup;
 46388      int savedMaxPage;
 46389      pcache1EnterMutex(pGroup);
 46390      savedMaxPage = pGroup->nMaxPage;
 46391      pGroup->nMaxPage = 0;
 46392      pcache1EnforceMaxPage(pCache);
 46393      pGroup->nMaxPage = savedMaxPage;
 46394      pcache1LeaveMutex(pGroup);
 46395    }
 46396  }
 46397  
 46398  /*
 46399  ** Implementation of the sqlite3_pcache.xPagecount method. 
 46400  */
 46401  static int pcache1Pagecount(sqlite3_pcache *p){
 46402    int n;
 46403    PCache1 *pCache = (PCache1*)p;
 46404    pcache1EnterMutex(pCache->pGroup);
 46405    n = pCache->nPage;
 46406    pcache1LeaveMutex(pCache->pGroup);
 46407    return n;
 46408  }
 46409  
 46410  
 46411  /*
 46412  ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
 46413  ** in the header of the pcache1Fetch() procedure.
 46414  **
 46415  ** This steps are broken out into a separate procedure because they are
 46416  ** usually not needed, and by avoiding the stack initialization required
 46417  ** for these steps, the main pcache1Fetch() procedure can run faster.
 46418  */
 46419  static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
 46420    PCache1 *pCache, 
 46421    unsigned int iKey, 
 46422    int createFlag
 46423  ){
 46424    unsigned int nPinned;
 46425    PGroup *pGroup = pCache->pGroup;
 46426    PgHdr1 *pPage = 0;
 46427  
 46428    /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
 46429    assert( pCache->nPage >= pCache->nRecyclable );
 46430    nPinned = pCache->nPage - pCache->nRecyclable;
 46431    assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
 46432    assert( pCache->n90pct == pCache->nMax*9/10 );
 46433    if( createFlag==1 && (
 46434          nPinned>=pGroup->mxPinned
 46435       || nPinned>=pCache->n90pct
 46436       || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
 46437    )){
 46438      return 0;
 46439    }
 46440  
 46441    if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
 46442    assert( pCache->nHash>0 && pCache->apHash );
 46443  
 46444    /* Step 4. Try to recycle a page. */
 46445    if( pCache->bPurgeable
 46446     && !pGroup->lru.pLruPrev->isAnchor
 46447     && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
 46448    ){
 46449      PCache1 *pOther;
 46450      pPage = pGroup->lru.pLruPrev;
 46451      assert( PAGE_IS_UNPINNED(pPage) );
 46452      pcache1RemoveFromHash(pPage, 0);
 46453      pcache1PinPage(pPage);
 46454      pOther = pPage->pCache;
 46455      if( pOther->szAlloc != pCache->szAlloc ){
 46456        pcache1FreePage(pPage);
 46457        pPage = 0;
 46458      }else{
 46459        pGroup->nPurgeable -= (pOther->bPurgeable - pCache->bPurgeable);
 46460      }
 46461    }
 46462  
 46463    /* Step 5. If a usable page buffer has still not been found, 
 46464    ** attempt to allocate a new one. 
 46465    */
 46466    if( !pPage ){
 46467      pPage = pcache1AllocPage(pCache, createFlag==1);
 46468    }
 46469  
 46470    if( pPage ){
 46471      unsigned int h = iKey % pCache->nHash;
 46472      pCache->nPage++;
 46473      pPage->iKey = iKey;
 46474      pPage->pNext = pCache->apHash[h];
 46475      pPage->pCache = pCache;
 46476      pPage->pLruPrev = 0;
 46477      pPage->pLruNext = 0;
 46478      *(void **)pPage->page.pExtra = 0;
 46479      pCache->apHash[h] = pPage;
 46480      if( iKey>pCache->iMaxKey ){
 46481        pCache->iMaxKey = iKey;
 46482      }
 46483    }
 46484    return pPage;
 46485  }
 46486  
 46487  /*
 46488  ** Implementation of the sqlite3_pcache.xFetch method. 
 46489  **
 46490  ** Fetch a page by key value.
 46491  **
 46492  ** Whether or not a new page may be allocated by this function depends on
 46493  ** the value of the createFlag argument.  0 means do not allocate a new
 46494  ** page.  1 means allocate a new page if space is easily available.  2 
 46495  ** means to try really hard to allocate a new page.
 46496  **
 46497  ** For a non-purgeable cache (a cache used as the storage for an in-memory
 46498  ** database) there is really no difference between createFlag 1 and 2.  So
 46499  ** the calling function (pcache.c) will never have a createFlag of 1 on
 46500  ** a non-purgeable cache.
 46501  **
 46502  ** There are three different approaches to obtaining space for a page,
 46503  ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
 46504  **
 46505  **   1. Regardless of the value of createFlag, the cache is searched for a 
 46506  **      copy of the requested page. If one is found, it is returned.
 46507  **
 46508  **   2. If createFlag==0 and the page is not already in the cache, NULL is
 46509  **      returned.
 46510  **
 46511  **   3. If createFlag is 1, and the page is not already in the cache, then
 46512  **      return NULL (do not allocate a new page) if any of the following
 46513  **      conditions are true:
 46514  **
 46515  **       (a) the number of pages pinned by the cache is greater than
 46516  **           PCache1.nMax, or
 46517  **
 46518  **       (b) the number of pages pinned by the cache is greater than
 46519  **           the sum of nMax for all purgeable caches, less the sum of 
 46520  **           nMin for all other purgeable caches, or
 46521  **
 46522  **   4. If none of the first three conditions apply and the cache is marked
 46523  **      as purgeable, and if one of the following is true:
 46524  **
 46525  **       (a) The number of pages allocated for the cache is already 
 46526  **           PCache1.nMax, or
 46527  **
 46528  **       (b) The number of pages allocated for all purgeable caches is
 46529  **           already equal to or greater than the sum of nMax for all
 46530  **           purgeable caches,
 46531  **
 46532  **       (c) The system is under memory pressure and wants to avoid
 46533  **           unnecessary pages cache entry allocations
 46534  **
 46535  **      then attempt to recycle a page from the LRU list. If it is the right
 46536  **      size, return the recycled buffer. Otherwise, free the buffer and
 46537  **      proceed to step 5. 
 46538  **
 46539  **   5. Otherwise, allocate and return a new page buffer.
 46540  **
 46541  ** There are two versions of this routine.  pcache1FetchWithMutex() is
 46542  ** the general case.  pcache1FetchNoMutex() is a faster implementation for
 46543  ** the common case where pGroup->mutex is NULL.  The pcache1Fetch() wrapper
 46544  ** invokes the appropriate routine.
 46545  */
 46546  static PgHdr1 *pcache1FetchNoMutex(
 46547    sqlite3_pcache *p, 
 46548    unsigned int iKey, 
 46549    int createFlag
 46550  ){
 46551    PCache1 *pCache = (PCache1 *)p;
 46552    PgHdr1 *pPage = 0;
 46553  
 46554    /* Step 1: Search the hash table for an existing entry. */
 46555    pPage = pCache->apHash[iKey % pCache->nHash];
 46556    while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
 46557  
 46558    /* Step 2: If the page was found in the hash table, then return it.
 46559    ** If the page was not in the hash table and createFlag is 0, abort.
 46560    ** Otherwise (page not in hash and createFlag!=0) continue with
 46561    ** subsequent steps to try to create the page. */
 46562    if( pPage ){
 46563      if( PAGE_IS_UNPINNED(pPage) ){
 46564        return pcache1PinPage(pPage);
 46565      }else{
 46566        return pPage;
 46567      }
 46568    }else if( createFlag ){
 46569      /* Steps 3, 4, and 5 implemented by this subroutine */
 46570      return pcache1FetchStage2(pCache, iKey, createFlag);
 46571    }else{
 46572      return 0;
 46573    }
 46574  }
 46575  #if PCACHE1_MIGHT_USE_GROUP_MUTEX
 46576  static PgHdr1 *pcache1FetchWithMutex(
 46577    sqlite3_pcache *p, 
 46578    unsigned int iKey, 
 46579    int createFlag
 46580  ){
 46581    PCache1 *pCache = (PCache1 *)p;
 46582    PgHdr1 *pPage;
 46583  
 46584    pcache1EnterMutex(pCache->pGroup);
 46585    pPage = pcache1FetchNoMutex(p, iKey, createFlag);
 46586    assert( pPage==0 || pCache->iMaxKey>=iKey );
 46587    pcache1LeaveMutex(pCache->pGroup);
 46588    return pPage;
 46589  }
 46590  #endif
 46591  static sqlite3_pcache_page *pcache1Fetch(
 46592    sqlite3_pcache *p, 
 46593    unsigned int iKey, 
 46594    int createFlag
 46595  ){
 46596  #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
 46597    PCache1 *pCache = (PCache1 *)p;
 46598  #endif
 46599  
 46600    assert( offsetof(PgHdr1,page)==0 );
 46601    assert( pCache->bPurgeable || createFlag!=1 );
 46602    assert( pCache->bPurgeable || pCache->nMin==0 );
 46603    assert( pCache->bPurgeable==0 || pCache->nMin==10 );
 46604    assert( pCache->nMin==0 || pCache->bPurgeable );
 46605    assert( pCache->nHash>0 );
 46606  #if PCACHE1_MIGHT_USE_GROUP_MUTEX
 46607    if( pCache->pGroup->mutex ){
 46608      return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
 46609    }else
 46610  #endif
 46611    {
 46612      return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
 46613    }
 46614  }
 46615  
 46616  
 46617  /*
 46618  ** Implementation of the sqlite3_pcache.xUnpin method.
 46619  **
 46620  ** Mark a page as unpinned (eligible for asynchronous recycling).
 46621  */
 46622  static void pcache1Unpin(
 46623    sqlite3_pcache *p, 
 46624    sqlite3_pcache_page *pPg, 
 46625    int reuseUnlikely
 46626  ){
 46627    PCache1 *pCache = (PCache1 *)p;
 46628    PgHdr1 *pPage = (PgHdr1 *)pPg;
 46629    PGroup *pGroup = pCache->pGroup;
 46630   
 46631    assert( pPage->pCache==pCache );
 46632    pcache1EnterMutex(pGroup);
 46633  
 46634    /* It is an error to call this function if the page is already 
 46635    ** part of the PGroup LRU list.
 46636    */
 46637    assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
 46638    assert( PAGE_IS_PINNED(pPage) );
 46639  
 46640    if( reuseUnlikely || pGroup->nPurgeable>pGroup->nMaxPage ){
 46641      pcache1RemoveFromHash(pPage, 1);
 46642    }else{
 46643      /* Add the page to the PGroup LRU list. */
 46644      PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
 46645      pPage->pLruPrev = &pGroup->lru;
 46646      (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
 46647      *ppFirst = pPage;
 46648      pCache->nRecyclable++;
 46649    }
 46650  
 46651    pcache1LeaveMutex(pCache->pGroup);
 46652  }
 46653  
 46654  /*
 46655  ** Implementation of the sqlite3_pcache.xRekey method. 
 46656  */
 46657  static void pcache1Rekey(
 46658    sqlite3_pcache *p,
 46659    sqlite3_pcache_page *pPg,
 46660    unsigned int iOld,
 46661    unsigned int iNew
 46662  ){
 46663    PCache1 *pCache = (PCache1 *)p;
 46664    PgHdr1 *pPage = (PgHdr1 *)pPg;
 46665    PgHdr1 **pp;
 46666    unsigned int h; 
 46667    assert( pPage->iKey==iOld );
 46668    assert( pPage->pCache==pCache );
 46669  
 46670    pcache1EnterMutex(pCache->pGroup);
 46671  
 46672    h = iOld%pCache->nHash;
 46673    pp = &pCache->apHash[h];
 46674    while( (*pp)!=pPage ){
 46675      pp = &(*pp)->pNext;
 46676    }
 46677    *pp = pPage->pNext;
 46678  
 46679    h = iNew%pCache->nHash;
 46680    pPage->iKey = iNew;
 46681    pPage->pNext = pCache->apHash[h];
 46682    pCache->apHash[h] = pPage;
 46683    if( iNew>pCache->iMaxKey ){
 46684      pCache->iMaxKey = iNew;
 46685    }
 46686  
 46687    pcache1LeaveMutex(pCache->pGroup);
 46688  }
 46689  
 46690  /*
 46691  ** Implementation of the sqlite3_pcache.xTruncate method. 
 46692  **
 46693  ** Discard all unpinned pages in the cache with a page number equal to
 46694  ** or greater than parameter iLimit. Any pinned pages with a page number
 46695  ** equal to or greater than iLimit are implicitly unpinned.
 46696  */
 46697  static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
 46698    PCache1 *pCache = (PCache1 *)p;
 46699    pcache1EnterMutex(pCache->pGroup);
 46700    if( iLimit<=pCache->iMaxKey ){
 46701      pcache1TruncateUnsafe(pCache, iLimit);
 46702      pCache->iMaxKey = iLimit-1;
 46703    }
 46704    pcache1LeaveMutex(pCache->pGroup);
 46705  }
 46706  
 46707  /*
 46708  ** Implementation of the sqlite3_pcache.xDestroy method. 
 46709  **
 46710  ** Destroy a cache allocated using pcache1Create().
 46711  */
 46712  static void pcache1Destroy(sqlite3_pcache *p){
 46713    PCache1 *pCache = (PCache1 *)p;
 46714    PGroup *pGroup = pCache->pGroup;
 46715    assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
 46716    pcache1EnterMutex(pGroup);
 46717    if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
 46718    assert( pGroup->nMaxPage >= pCache->nMax );
 46719    pGroup->nMaxPage -= pCache->nMax;
 46720    assert( pGroup->nMinPage >= pCache->nMin );
 46721    pGroup->nMinPage -= pCache->nMin;
 46722    pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
 46723    pcache1EnforceMaxPage(pCache);
 46724    pcache1LeaveMutex(pGroup);
 46725    sqlite3_free(pCache->pBulk);
 46726    sqlite3_free(pCache->apHash);
 46727    sqlite3_free(pCache);
 46728  }
 46729  
 46730  /*
 46731  ** This function is called during initialization (sqlite3_initialize()) to
 46732  ** install the default pluggable cache module, assuming the user has not
 46733  ** already provided an alternative.
 46734  */
 46735  SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
 46736    static const sqlite3_pcache_methods2 defaultMethods = {
 46737      1,                       /* iVersion */
 46738      0,                       /* pArg */
 46739      pcache1Init,             /* xInit */
 46740      pcache1Shutdown,         /* xShutdown */
 46741      pcache1Create,           /* xCreate */
 46742      pcache1Cachesize,        /* xCachesize */
 46743      pcache1Pagecount,        /* xPagecount */
 46744      pcache1Fetch,            /* xFetch */
 46745      pcache1Unpin,            /* xUnpin */
 46746      pcache1Rekey,            /* xRekey */
 46747      pcache1Truncate,         /* xTruncate */
 46748      pcache1Destroy,          /* xDestroy */
 46749      pcache1Shrink            /* xShrink */
 46750    };
 46751    sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
 46752  }
 46753  
 46754  /*
 46755  ** Return the size of the header on each page of this PCACHE implementation.
 46756  */
 46757  SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
 46758  
 46759  /*
 46760  ** Return the global mutex used by this PCACHE implementation.  The
 46761  ** sqlite3_status() routine needs access to this mutex.
 46762  */
 46763  SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
 46764    return pcache1.mutex;
 46765  }
 46766  
 46767  #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
 46768  /*
 46769  ** This function is called to free superfluous dynamically allocated memory
 46770  ** held by the pager system. Memory in use by any SQLite pager allocated
 46771  ** by the current thread may be sqlite3_free()ed.
 46772  **
 46773  ** nReq is the number of bytes of memory required. Once this much has
 46774  ** been released, the function returns. The return value is the total number 
 46775  ** of bytes of memory released.
 46776  */
 46777  SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
 46778    int nFree = 0;
 46779    assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
 46780    assert( sqlite3_mutex_notheld(pcache1.mutex) );
 46781    if( sqlite3GlobalConfig.pPage==0 ){
 46782      PgHdr1 *p;
 46783      pcache1EnterMutex(&pcache1.grp);
 46784      while( (nReq<0 || nFree<nReq)
 46785         &&  (p=pcache1.grp.lru.pLruPrev)!=0
 46786         &&  p->isAnchor==0
 46787      ){
 46788        nFree += pcache1MemSize(p->page.pBuf);
 46789  #ifdef SQLITE_PCACHE_SEPARATE_HEADER
 46790        nFree += sqlite3MemSize(p);
 46791  #endif
 46792        assert( PAGE_IS_UNPINNED(p) );
 46793        pcache1PinPage(p);
 46794        pcache1RemoveFromHash(p, 1);
 46795      }
 46796      pcache1LeaveMutex(&pcache1.grp);
 46797    }
 46798    return nFree;
 46799  }
 46800  #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
 46801  
 46802  #ifdef SQLITE_TEST
 46803  /*
 46804  ** This function is used by test procedures to inspect the internal state
 46805  ** of the global cache.
 46806  */
 46807  SQLITE_PRIVATE void sqlite3PcacheStats(
 46808    int *pnCurrent,      /* OUT: Total number of pages cached */
 46809    int *pnMax,          /* OUT: Global maximum cache size */
 46810    int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
 46811    int *pnRecyclable    /* OUT: Total number of pages available for recycling */
 46812  ){
 46813    PgHdr1 *p;
 46814    int nRecyclable = 0;
 46815    for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
 46816      assert( PAGE_IS_UNPINNED(p) );
 46817      nRecyclable++;
 46818    }
 46819    *pnCurrent = pcache1.grp.nPurgeable;
 46820    *pnMax = (int)pcache1.grp.nMaxPage;
 46821    *pnMin = (int)pcache1.grp.nMinPage;
 46822    *pnRecyclable = nRecyclable;
 46823  }
 46824  #endif
 46825  
 46826  /************** End of pcache1.c *********************************************/
 46827  /************** Begin file rowset.c ******************************************/
 46828  /*
 46829  ** 2008 December 3
 46830  **
 46831  ** The author disclaims copyright to this source code.  In place of
 46832  ** a legal notice, here is a blessing:
 46833  **
 46834  **    May you do good and not evil.
 46835  **    May you find forgiveness for yourself and forgive others.
 46836  **    May you share freely, never taking more than you give.
 46837  **
 46838  *************************************************************************
 46839  **
 46840  ** This module implements an object we call a "RowSet".
 46841  **
 46842  ** The RowSet object is a collection of rowids.  Rowids
 46843  ** are inserted into the RowSet in an arbitrary order.  Inserts
 46844  ** can be intermixed with tests to see if a given rowid has been
 46845  ** previously inserted into the RowSet.
 46846  **
 46847  ** After all inserts are finished, it is possible to extract the
 46848  ** elements of the RowSet in sorted order.  Once this extraction
 46849  ** process has started, no new elements may be inserted.
 46850  **
 46851  ** Hence, the primitive operations for a RowSet are:
 46852  **
 46853  **    CREATE
 46854  **    INSERT
 46855  **    TEST
 46856  **    SMALLEST
 46857  **    DESTROY
 46858  **
 46859  ** The CREATE and DESTROY primitives are the constructor and destructor,
 46860  ** obviously.  The INSERT primitive adds a new element to the RowSet.
 46861  ** TEST checks to see if an element is already in the RowSet.  SMALLEST
 46862  ** extracts the least value from the RowSet.
 46863  **
 46864  ** The INSERT primitive might allocate additional memory.  Memory is
 46865  ** allocated in chunks so most INSERTs do no allocation.  There is an 
 46866  ** upper bound on the size of allocated memory.  No memory is freed
 46867  ** until DESTROY.
 46868  **
 46869  ** The TEST primitive includes a "batch" number.  The TEST primitive
 46870  ** will only see elements that were inserted before the last change
 46871  ** in the batch number.  In other words, if an INSERT occurs between
 46872  ** two TESTs where the TESTs have the same batch nubmer, then the
 46873  ** value added by the INSERT will not be visible to the second TEST.
 46874  ** The initial batch number is zero, so if the very first TEST contains
 46875  ** a non-zero batch number, it will see all prior INSERTs.
 46876  **
 46877  ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
 46878  ** that is attempted.
 46879  **
 46880  ** The cost of an INSERT is roughly constant.  (Sometimes new memory
 46881  ** has to be allocated on an INSERT.)  The cost of a TEST with a new
 46882  ** batch number is O(NlogN) where N is the number of elements in the RowSet.
 46883  ** The cost of a TEST using the same batch number is O(logN).  The cost
 46884  ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
 46885  ** primitives are constant time.  The cost of DESTROY is O(N).
 46886  **
 46887  ** TEST and SMALLEST may not be used by the same RowSet.  This used to
 46888  ** be possible, but the feature was not used, so it was removed in order
 46889  ** to simplify the code.
 46890  */
 46891  /* #include "sqliteInt.h" */
 46892  
 46893  
 46894  /*
 46895  ** Target size for allocation chunks.
 46896  */
 46897  #define ROWSET_ALLOCATION_SIZE 1024
 46898  
 46899  /*
 46900  ** The number of rowset entries per allocation chunk.
 46901  */
 46902  #define ROWSET_ENTRY_PER_CHUNK  \
 46903                         ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
 46904  
 46905  /*
 46906  ** Each entry in a RowSet is an instance of the following object.
 46907  **
 46908  ** This same object is reused to store a linked list of trees of RowSetEntry
 46909  ** objects.  In that alternative use, pRight points to the next entry
 46910  ** in the list, pLeft points to the tree, and v is unused.  The
 46911  ** RowSet.pForest value points to the head of this forest list.
 46912  */
 46913  struct RowSetEntry {            
 46914    i64 v;                        /* ROWID value for this entry */
 46915    struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
 46916    struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
 46917  };
 46918  
 46919  /*
 46920  ** RowSetEntry objects are allocated in large chunks (instances of the
 46921  ** following structure) to reduce memory allocation overhead.  The
 46922  ** chunks are kept on a linked list so that they can be deallocated
 46923  ** when the RowSet is destroyed.
 46924  */
 46925  struct RowSetChunk {
 46926    struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
 46927    struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
 46928  };
 46929  
 46930  /*
 46931  ** A RowSet in an instance of the following structure.
 46932  **
 46933  ** A typedef of this structure if found in sqliteInt.h.
 46934  */
 46935  struct RowSet {
 46936    struct RowSetChunk *pChunk;    /* List of all chunk allocations */
 46937    sqlite3 *db;                   /* The database connection */
 46938    struct RowSetEntry *pEntry;    /* List of entries using pRight */
 46939    struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
 46940    struct RowSetEntry *pFresh;    /* Source of new entry objects */
 46941    struct RowSetEntry *pForest;   /* List of binary trees of entries */
 46942    u16 nFresh;                    /* Number of objects on pFresh */
 46943    u16 rsFlags;                   /* Various flags */
 46944    int iBatch;                    /* Current insert batch */
 46945  };
 46946  
 46947  /*
 46948  ** Allowed values for RowSet.rsFlags
 46949  */
 46950  #define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
 46951  #define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
 46952  
 46953  /*
 46954  ** Turn bulk memory into a RowSet object.  N bytes of memory
 46955  ** are available at pSpace.  The db pointer is used as a memory context
 46956  ** for any subsequent allocations that need to occur.
 46957  ** Return a pointer to the new RowSet object.
 46958  **
 46959  ** It must be the case that N is sufficient to make a Rowset.  If not
 46960  ** an assertion fault occurs.
 46961  ** 
 46962  ** If N is larger than the minimum, use the surplus as an initial
 46963  ** allocation of entries available to be filled.
 46964  */
 46965  SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
 46966    RowSet *p;
 46967    assert( N >= ROUND8(sizeof(*p)) );
 46968    p = pSpace;
 46969    p->pChunk = 0;
 46970    p->db = db;
 46971    p->pEntry = 0;
 46972    p->pLast = 0;
 46973    p->pForest = 0;
 46974    p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
 46975    p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
 46976    p->rsFlags = ROWSET_SORTED;
 46977    p->iBatch = 0;
 46978    return p;
 46979  }
 46980  
 46981  /*
 46982  ** Deallocate all chunks from a RowSet.  This frees all memory that
 46983  ** the RowSet has allocated over its lifetime.  This routine is
 46984  ** the destructor for the RowSet.
 46985  */
 46986  SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
 46987    struct RowSetChunk *pChunk, *pNextChunk;
 46988    for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
 46989      pNextChunk = pChunk->pNextChunk;
 46990      sqlite3DbFree(p->db, pChunk);
 46991    }
 46992    p->pChunk = 0;
 46993    p->nFresh = 0;
 46994    p->pEntry = 0;
 46995    p->pLast = 0;
 46996    p->pForest = 0;
 46997    p->rsFlags = ROWSET_SORTED;
 46998  }
 46999  
 47000  /*
 47001  ** Allocate a new RowSetEntry object that is associated with the
 47002  ** given RowSet.  Return a pointer to the new and completely uninitialized
 47003  ** objected.
 47004  **
 47005  ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
 47006  ** routine returns NULL.
 47007  */
 47008  static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
 47009    assert( p!=0 );
 47010    if( p->nFresh==0 ){  /*OPTIMIZATION-IF-FALSE*/
 47011      /* We could allocate a fresh RowSetEntry each time one is needed, but it
 47012      ** is more efficient to pull a preallocated entry from the pool */
 47013      struct RowSetChunk *pNew;
 47014      pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
 47015      if( pNew==0 ){
 47016        return 0;
 47017      }
 47018      pNew->pNextChunk = p->pChunk;
 47019      p->pChunk = pNew;
 47020      p->pFresh = pNew->aEntry;
 47021      p->nFresh = ROWSET_ENTRY_PER_CHUNK;
 47022    }
 47023    p->nFresh--;
 47024    return p->pFresh++;
 47025  }
 47026  
 47027  /*
 47028  ** Insert a new value into a RowSet.
 47029  **
 47030  ** The mallocFailed flag of the database connection is set if a
 47031  ** memory allocation fails.
 47032  */
 47033  SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
 47034    struct RowSetEntry *pEntry;  /* The new entry */
 47035    struct RowSetEntry *pLast;   /* The last prior entry */
 47036  
 47037    /* This routine is never called after sqlite3RowSetNext() */
 47038    assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
 47039  
 47040    pEntry = rowSetEntryAlloc(p);
 47041    if( pEntry==0 ) return;
 47042    pEntry->v = rowid;
 47043    pEntry->pRight = 0;
 47044    pLast = p->pLast;
 47045    if( pLast ){
 47046      if( rowid<=pLast->v ){  /*OPTIMIZATION-IF-FALSE*/
 47047        /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
 47048        ** where possible */
 47049        p->rsFlags &= ~ROWSET_SORTED;
 47050      }
 47051      pLast->pRight = pEntry;
 47052    }else{
 47053      p->pEntry = pEntry;
 47054    }
 47055    p->pLast = pEntry;
 47056  }
 47057  
 47058  /*
 47059  ** Merge two lists of RowSetEntry objects.  Remove duplicates.
 47060  **
 47061  ** The input lists are connected via pRight pointers and are 
 47062  ** assumed to each already be in sorted order.
 47063  */
 47064  static struct RowSetEntry *rowSetEntryMerge(
 47065    struct RowSetEntry *pA,    /* First sorted list to be merged */
 47066    struct RowSetEntry *pB     /* Second sorted list to be merged */
 47067  ){
 47068    struct RowSetEntry head;
 47069    struct RowSetEntry *pTail;
 47070  
 47071    pTail = &head;
 47072    assert( pA!=0 && pB!=0 );
 47073    for(;;){
 47074      assert( pA->pRight==0 || pA->v<=pA->pRight->v );
 47075      assert( pB->pRight==0 || pB->v<=pB->pRight->v );
 47076      if( pA->v<=pB->v ){
 47077        if( pA->v<pB->v ) pTail = pTail->pRight = pA;
 47078        pA = pA->pRight;
 47079        if( pA==0 ){
 47080          pTail->pRight = pB;
 47081          break;
 47082        }
 47083      }else{
 47084        pTail = pTail->pRight = pB;
 47085        pB = pB->pRight;
 47086        if( pB==0 ){
 47087          pTail->pRight = pA;
 47088          break;
 47089        }
 47090      }
 47091    }
 47092    return head.pRight;
 47093  }
 47094  
 47095  /*
 47096  ** Sort all elements on the list of RowSetEntry objects into order of
 47097  ** increasing v.
 47098  */ 
 47099  static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
 47100    unsigned int i;
 47101    struct RowSetEntry *pNext, *aBucket[40];
 47102  
 47103    memset(aBucket, 0, sizeof(aBucket));
 47104    while( pIn ){
 47105      pNext = pIn->pRight;
 47106      pIn->pRight = 0;
 47107      for(i=0; aBucket[i]; i++){
 47108        pIn = rowSetEntryMerge(aBucket[i], pIn);
 47109        aBucket[i] = 0;
 47110      }
 47111      aBucket[i] = pIn;
 47112      pIn = pNext;
 47113    }
 47114    pIn = aBucket[0];
 47115    for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
 47116      if( aBucket[i]==0 ) continue;
 47117      pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
 47118    }
 47119    return pIn;
 47120  }
 47121  
 47122  
 47123  /*
 47124  ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
 47125  ** Convert this tree into a linked list connected by the pRight pointers
 47126  ** and return pointers to the first and last elements of the new list.
 47127  */
 47128  static void rowSetTreeToList(
 47129    struct RowSetEntry *pIn,         /* Root of the input tree */
 47130    struct RowSetEntry **ppFirst,    /* Write head of the output list here */
 47131    struct RowSetEntry **ppLast      /* Write tail of the output list here */
 47132  ){
 47133    assert( pIn!=0 );
 47134    if( pIn->pLeft ){
 47135      struct RowSetEntry *p;
 47136      rowSetTreeToList(pIn->pLeft, ppFirst, &p);
 47137      p->pRight = pIn;
 47138    }else{
 47139      *ppFirst = pIn;
 47140    }
 47141    if( pIn->pRight ){
 47142      rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
 47143    }else{
 47144      *ppLast = pIn;
 47145    }
 47146    assert( (*ppLast)->pRight==0 );
 47147  }
 47148  
 47149  
 47150  /*
 47151  ** Convert a sorted list of elements (connected by pRight) into a binary
 47152  ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
 47153  ** node taken from the head of *ppList.  A depth of 2 means a tree with
 47154  ** three nodes.  And so forth.
 47155  **
 47156  ** Use as many entries from the input list as required and update the
 47157  ** *ppList to point to the unused elements of the list.  If the input
 47158  ** list contains too few elements, then construct an incomplete tree
 47159  ** and leave *ppList set to NULL.
 47160  **
 47161  ** Return a pointer to the root of the constructed binary tree.
 47162  */
 47163  static struct RowSetEntry *rowSetNDeepTree(
 47164    struct RowSetEntry **ppList,
 47165    int iDepth
 47166  ){
 47167    struct RowSetEntry *p;         /* Root of the new tree */
 47168    struct RowSetEntry *pLeft;     /* Left subtree */
 47169    if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
 47170      /* Prevent unnecessary deep recursion when we run out of entries */
 47171      return 0; 
 47172    }
 47173    if( iDepth>1 ){   /*OPTIMIZATION-IF-TRUE*/
 47174      /* This branch causes a *balanced* tree to be generated.  A valid tree
 47175      ** is still generated without this branch, but the tree is wildly
 47176      ** unbalanced and inefficient. */
 47177      pLeft = rowSetNDeepTree(ppList, iDepth-1);
 47178      p = *ppList;
 47179      if( p==0 ){     /*OPTIMIZATION-IF-FALSE*/
 47180        /* It is safe to always return here, but the resulting tree
 47181        ** would be unbalanced */
 47182        return pLeft;
 47183      }
 47184      p->pLeft = pLeft;
 47185      *ppList = p->pRight;
 47186      p->pRight = rowSetNDeepTree(ppList, iDepth-1);
 47187    }else{
 47188      p = *ppList;
 47189      *ppList = p->pRight;
 47190      p->pLeft = p->pRight = 0;
 47191    }
 47192    return p;
 47193  }
 47194  
 47195  /*
 47196  ** Convert a sorted list of elements into a binary tree. Make the tree
 47197  ** as deep as it needs to be in order to contain the entire list.
 47198  */
 47199  static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
 47200    int iDepth;           /* Depth of the tree so far */
 47201    struct RowSetEntry *p;       /* Current tree root */
 47202    struct RowSetEntry *pLeft;   /* Left subtree */
 47203  
 47204    assert( pList!=0 );
 47205    p = pList;
 47206    pList = p->pRight;
 47207    p->pLeft = p->pRight = 0;
 47208    for(iDepth=1; pList; iDepth++){
 47209      pLeft = p;
 47210      p = pList;
 47211      pList = p->pRight;
 47212      p->pLeft = pLeft;
 47213      p->pRight = rowSetNDeepTree(&pList, iDepth);
 47214    }
 47215    return p;
 47216  }
 47217  
 47218  /*
 47219  ** Extract the smallest element from the RowSet.
 47220  ** Write the element into *pRowid.  Return 1 on success.  Return
 47221  ** 0 if the RowSet is already empty.
 47222  **
 47223  ** After this routine has been called, the sqlite3RowSetInsert()
 47224  ** routine may not be called again.
 47225  **
 47226  ** This routine may not be called after sqlite3RowSetTest() has
 47227  ** been used.  Older versions of RowSet allowed that, but as the
 47228  ** capability was not used by the code generator, it was removed
 47229  ** for code economy.
 47230  */
 47231  SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
 47232    assert( p!=0 );
 47233    assert( p->pForest==0 );  /* Cannot be used with sqlite3RowSetText() */
 47234  
 47235    /* Merge the forest into a single sorted list on first call */
 47236    if( (p->rsFlags & ROWSET_NEXT)==0 ){  /*OPTIMIZATION-IF-FALSE*/
 47237      if( (p->rsFlags & ROWSET_SORTED)==0 ){  /*OPTIMIZATION-IF-FALSE*/
 47238        p->pEntry = rowSetEntrySort(p->pEntry);
 47239      }
 47240      p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
 47241    }
 47242  
 47243    /* Return the next entry on the list */
 47244    if( p->pEntry ){
 47245      *pRowid = p->pEntry->v;
 47246      p->pEntry = p->pEntry->pRight;
 47247      if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
 47248        /* Free memory immediately, rather than waiting on sqlite3_finalize() */
 47249        sqlite3RowSetClear(p);
 47250      }
 47251      return 1;
 47252    }else{
 47253      return 0;
 47254    }
 47255  }
 47256  
 47257  /*
 47258  ** Check to see if element iRowid was inserted into the rowset as
 47259  ** part of any insert batch prior to iBatch.  Return 1 or 0.
 47260  **
 47261  ** If this is the first test of a new batch and if there exist entries
 47262  ** on pRowSet->pEntry, then sort those entries into the forest at
 47263  ** pRowSet->pForest so that they can be tested.
 47264  */
 47265  SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
 47266    struct RowSetEntry *p, *pTree;
 47267  
 47268    /* This routine is never called after sqlite3RowSetNext() */
 47269    assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
 47270  
 47271    /* Sort entries into the forest on the first test of a new batch.
 47272    ** To save unnecessary work, only do this when the batch number changes.
 47273    */
 47274    if( iBatch!=pRowSet->iBatch ){  /*OPTIMIZATION-IF-FALSE*/
 47275      p = pRowSet->pEntry;
 47276      if( p ){
 47277        struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
 47278        if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
 47279          /* Only sort the current set of entiries if they need it */
 47280          p = rowSetEntrySort(p);
 47281        }
 47282        for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
 47283          ppPrevTree = &pTree->pRight;
 47284          if( pTree->pLeft==0 ){
 47285            pTree->pLeft = rowSetListToTree(p);
 47286            break;
 47287          }else{
 47288            struct RowSetEntry *pAux, *pTail;
 47289            rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
 47290            pTree->pLeft = 0;
 47291            p = rowSetEntryMerge(pAux, p);
 47292          }
 47293        }
 47294        if( pTree==0 ){
 47295          *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
 47296          if( pTree ){
 47297            pTree->v = 0;
 47298            pTree->pRight = 0;
 47299            pTree->pLeft = rowSetListToTree(p);
 47300          }
 47301        }
 47302        pRowSet->pEntry = 0;
 47303        pRowSet->pLast = 0;
 47304        pRowSet->rsFlags |= ROWSET_SORTED;
 47305      }
 47306      pRowSet->iBatch = iBatch;
 47307    }
 47308  
 47309    /* Test to see if the iRowid value appears anywhere in the forest.
 47310    ** Return 1 if it does and 0 if not.
 47311    */
 47312    for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
 47313      p = pTree->pLeft;
 47314      while( p ){
 47315        if( p->v<iRowid ){
 47316          p = p->pRight;
 47317        }else if( p->v>iRowid ){
 47318          p = p->pLeft;
 47319        }else{
 47320          return 1;
 47321        }
 47322      }
 47323    }
 47324    return 0;
 47325  }
 47326  
 47327  /************** End of rowset.c **********************************************/
 47328  /************** Begin file pager.c *******************************************/
 47329  /*
 47330  ** 2001 September 15
 47331  **
 47332  ** The author disclaims copyright to this source code.  In place of
 47333  ** a legal notice, here is a blessing:
 47334  **
 47335  **    May you do good and not evil.
 47336  **    May you find forgiveness for yourself and forgive others.
 47337  **    May you share freely, never taking more than you give.
 47338  **
 47339  *************************************************************************
 47340  ** This is the implementation of the page cache subsystem or "pager".
 47341  ** 
 47342  ** The pager is used to access a database disk file.  It implements
 47343  ** atomic commit and rollback through the use of a journal file that
 47344  ** is separate from the database file.  The pager also implements file
 47345  ** locking to prevent two processes from writing the same database
 47346  ** file simultaneously, or one process from reading the database while
 47347  ** another is writing.
 47348  */
 47349  #ifndef SQLITE_OMIT_DISKIO
 47350  /* #include "sqliteInt.h" */
 47351  /************** Include wal.h in the middle of pager.c ***********************/
 47352  /************** Begin file wal.h *********************************************/
 47353  /*
 47354  ** 2010 February 1
 47355  **
 47356  ** The author disclaims copyright to this source code.  In place of
 47357  ** a legal notice, here is a blessing:
 47358  **
 47359  **    May you do good and not evil.
 47360  **    May you find forgiveness for yourself and forgive others.
 47361  **    May you share freely, never taking more than you give.
 47362  **
 47363  *************************************************************************
 47364  ** This header file defines the interface to the write-ahead logging 
 47365  ** system. Refer to the comments below and the header comment attached to 
 47366  ** the implementation of each function in log.c for further details.
 47367  */
 47368  
 47369  #ifndef SQLITE_WAL_H
 47370  #define SQLITE_WAL_H
 47371  
 47372  /* #include "sqliteInt.h" */
 47373  
 47374  /* Macros for extracting appropriate sync flags for either transaction
 47375  ** commits (WAL_SYNC_FLAGS(X)) or for checkpoint ops (CKPT_SYNC_FLAGS(X)):
 47376  */
 47377  #define WAL_SYNC_FLAGS(X)   ((X)&0x03)
 47378  #define CKPT_SYNC_FLAGS(X)  (((X)>>2)&0x03)
 47379  
 47380  #ifdef SQLITE_OMIT_WAL
 47381  # define sqlite3WalOpen(x,y,z)                   0
 47382  # define sqlite3WalLimit(x,y)
 47383  # define sqlite3WalClose(v,w,x,y,z)              0
 47384  # define sqlite3WalBeginReadTransaction(y,z)     0
 47385  # define sqlite3WalEndReadTransaction(z)
 47386  # define sqlite3WalDbsize(y)                     0
 47387  # define sqlite3WalBeginWriteTransaction(y)      0
 47388  # define sqlite3WalEndWriteTransaction(x)        0
 47389  # define sqlite3WalUndo(x,y,z)                   0
 47390  # define sqlite3WalSavepoint(y,z)
 47391  # define sqlite3WalSavepointUndo(y,z)            0
 47392  # define sqlite3WalFrames(u,v,w,x,y,z)           0
 47393  # define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0
 47394  # define sqlite3WalCallback(z)                   0
 47395  # define sqlite3WalExclusiveMode(y,z)            0
 47396  # define sqlite3WalHeapMemory(z)                 0
 47397  # define sqlite3WalFramesize(z)                  0
 47398  # define sqlite3WalFindFrame(x,y,z)              0
 47399  # define sqlite3WalFile(x)                       0
 47400  #else
 47401  
 47402  #define WAL_SAVEPOINT_NDATA 4
 47403  
 47404  /* Connection to a write-ahead log (WAL) file. 
 47405  ** There is one object of this type for each pager. 
 47406  */
 47407  typedef struct Wal Wal;
 47408  
 47409  /* Open and close a connection to a write-ahead log. */
 47410  SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
 47411  SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *);
 47412  
 47413  /* Set the limiting size of a WAL file. */
 47414  SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
 47415  
 47416  /* Used by readers to open (lock) and close (unlock) a snapshot.  A 
 47417  ** snapshot is like a read-transaction.  It is the state of the database
 47418  ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
 47419  ** preserves the current state even if the other threads or processes
 47420  ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
 47421  ** transaction and releases the lock.
 47422  */
 47423  SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
 47424  SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
 47425  
 47426  /* Read a page from the write-ahead log, if it is present. */
 47427  SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
 47428  SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
 47429  
 47430  /* If the WAL is not empty, return the size of the database. */
 47431  SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
 47432  
 47433  /* Obtain or release the WRITER lock. */
 47434  SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
 47435  SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
 47436  
 47437  /* Undo any frames written (but not committed) to the log */
 47438  SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
 47439  
 47440  /* Return an integer that records the current (uncommitted) write
 47441  ** position in the WAL */
 47442  SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
 47443  
 47444  /* Move the write position of the WAL back to iFrame.  Called in
 47445  ** response to a ROLLBACK TO command. */
 47446  SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
 47447  
 47448  /* Write a frame or frames to the log. */
 47449  SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
 47450  
 47451  /* Copy pages from the log to the database file */ 
 47452  SQLITE_PRIVATE int sqlite3WalCheckpoint(
 47453    Wal *pWal,                      /* Write-ahead log connection */
 47454    sqlite3 *db,                    /* Check this handle's interrupt flag */
 47455    int eMode,                      /* One of PASSIVE, FULL and RESTART */
 47456    int (*xBusy)(void*),            /* Function to call when busy */
 47457    void *pBusyArg,                 /* Context argument for xBusyHandler */
 47458    int sync_flags,                 /* Flags to sync db file with (or 0) */
 47459    int nBuf,                       /* Size of buffer nBuf */
 47460    u8 *zBuf,                       /* Temporary buffer to use */
 47461    int *pnLog,                     /* OUT: Number of frames in WAL */
 47462    int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
 47463  );
 47464  
 47465  /* Return the value to pass to a sqlite3_wal_hook callback, the
 47466  ** number of frames in the WAL at the point of the last commit since
 47467  ** sqlite3WalCallback() was called.  If no commits have occurred since
 47468  ** the last call, then return 0.
 47469  */
 47470  SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
 47471  
 47472  /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
 47473  ** by the pager layer on the database file.
 47474  */
 47475  SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
 47476  
 47477  /* Return true if the argument is non-NULL and the WAL module is using
 47478  ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
 47479  ** WAL module is using shared-memory, return false. 
 47480  */
 47481  SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
 47482  
 47483  #ifdef SQLITE_ENABLE_SNAPSHOT
 47484  SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
 47485  SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
 47486  SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal);
 47487  #endif
 47488  
 47489  #ifdef SQLITE_ENABLE_ZIPVFS
 47490  /* If the WAL file is not empty, return the number of bytes of content
 47491  ** stored in each frame (i.e. the db page-size when the WAL was created).
 47492  */
 47493  SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
 47494  #endif
 47495  
 47496  /* Return the sqlite3_file object for the WAL file */
 47497  SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
 47498  
 47499  #endif /* ifndef SQLITE_OMIT_WAL */
 47500  #endif /* SQLITE_WAL_H */
 47501  
 47502  /************** End of wal.h *************************************************/
 47503  /************** Continuing where we left off in pager.c **********************/
 47504  
 47505  
 47506  /******************* NOTES ON THE DESIGN OF THE PAGER ************************
 47507  **
 47508  ** This comment block describes invariants that hold when using a rollback
 47509  ** journal.  These invariants do not apply for journal_mode=WAL,
 47510  ** journal_mode=MEMORY, or journal_mode=OFF.
 47511  **
 47512  ** Within this comment block, a page is deemed to have been synced
 47513  ** automatically as soon as it is written when PRAGMA synchronous=OFF.
 47514  ** Otherwise, the page is not synced until the xSync method of the VFS
 47515  ** is called successfully on the file containing the page.
 47516  **
 47517  ** Definition:  A page of the database file is said to be "overwriteable" if
 47518  ** one or more of the following are true about the page:
 47519  ** 
 47520  **     (a)  The original content of the page as it was at the beginning of
 47521  **          the transaction has been written into the rollback journal and
 47522  **          synced.
 47523  ** 
 47524  **     (b)  The page was a freelist leaf page at the start of the transaction.
 47525  ** 
 47526  **     (c)  The page number is greater than the largest page that existed in
 47527  **          the database file at the start of the transaction.
 47528  ** 
 47529  ** (1) A page of the database file is never overwritten unless one of the
 47530  **     following are true:
 47531  ** 
 47532  **     (a) The page and all other pages on the same sector are overwriteable.
 47533  ** 
 47534  **     (b) The atomic page write optimization is enabled, and the entire
 47535  **         transaction other than the update of the transaction sequence
 47536  **         number consists of a single page change.
 47537  ** 
 47538  ** (2) The content of a page written into the rollback journal exactly matches
 47539  **     both the content in the database when the rollback journal was written
 47540  **     and the content in the database at the beginning of the current
 47541  **     transaction.
 47542  ** 
 47543  ** (3) Writes to the database file are an integer multiple of the page size
 47544  **     in length and are aligned on a page boundary.
 47545  ** 
 47546  ** (4) Reads from the database file are either aligned on a page boundary and
 47547  **     an integer multiple of the page size in length or are taken from the
 47548  **     first 100 bytes of the database file.
 47549  ** 
 47550  ** (5) All writes to the database file are synced prior to the rollback journal
 47551  **     being deleted, truncated, or zeroed.
 47552  ** 
 47553  ** (6) If a master journal file is used, then all writes to the database file
 47554  **     are synced prior to the master journal being deleted.
 47555  ** 
 47556  ** Definition: Two databases (or the same database at two points it time)
 47557  ** are said to be "logically equivalent" if they give the same answer to
 47558  ** all queries.  Note in particular the content of freelist leaf
 47559  ** pages can be changed arbitrarily without affecting the logical equivalence
 47560  ** of the database.
 47561  ** 
 47562  ** (7) At any time, if any subset, including the empty set and the total set,
 47563  **     of the unsynced changes to a rollback journal are removed and the 
 47564  **     journal is rolled back, the resulting database file will be logically
 47565  **     equivalent to the database file at the beginning of the transaction.
 47566  ** 
 47567  ** (8) When a transaction is rolled back, the xTruncate method of the VFS
 47568  **     is called to restore the database file to the same size it was at
 47569  **     the beginning of the transaction.  (In some VFSes, the xTruncate
 47570  **     method is a no-op, but that does not change the fact the SQLite will
 47571  **     invoke it.)
 47572  ** 
 47573  ** (9) Whenever the database file is modified, at least one bit in the range
 47574  **     of bytes from 24 through 39 inclusive will be changed prior to releasing
 47575  **     the EXCLUSIVE lock, thus signaling other connections on the same
 47576  **     database to flush their caches.
 47577  **
 47578  ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
 47579  **      than one billion transactions.
 47580  **
 47581  ** (11) A database file is well-formed at the beginning and at the conclusion
 47582  **      of every transaction.
 47583  **
 47584  ** (12) An EXCLUSIVE lock is held on the database file when writing to
 47585  **      the database file.
 47586  **
 47587  ** (13) A SHARED lock is held on the database file while reading any
 47588  **      content out of the database file.
 47589  **
 47590  ******************************************************************************/
 47591  
 47592  /*
 47593  ** Macros for troubleshooting.  Normally turned off
 47594  */
 47595  #if 0
 47596  int sqlite3PagerTrace=1;  /* True to enable tracing */
 47597  #define sqlite3DebugPrintf printf
 47598  #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
 47599  #else
 47600  #define PAGERTRACE(X)
 47601  #endif
 47602  
 47603  /*
 47604  ** The following two macros are used within the PAGERTRACE() macros above
 47605  ** to print out file-descriptors. 
 47606  **
 47607  ** PAGERID() takes a pointer to a Pager struct as its argument. The
 47608  ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
 47609  ** struct as its argument.
 47610  */
 47611  #define PAGERID(p) (SQLITE_PTR_TO_INT(p->fd))
 47612  #define FILEHANDLEID(fd) (SQLITE_PTR_TO_INT(fd))
 47613  
 47614  /*
 47615  ** The Pager.eState variable stores the current 'state' of a pager. A
 47616  ** pager may be in any one of the seven states shown in the following
 47617  ** state diagram.
 47618  **
 47619  **                            OPEN <------+------+
 47620  **                              |         |      |
 47621  **                              V         |      |
 47622  **               +---------> READER-------+      |
 47623  **               |              |                |
 47624  **               |              V                |
 47625  **               |<-------WRITER_LOCKED------> ERROR
 47626  **               |              |                ^  
 47627  **               |              V                |
 47628  **               |<------WRITER_CACHEMOD-------->|
 47629  **               |              |                |
 47630  **               |              V                |
 47631  **               |<-------WRITER_DBMOD---------->|
 47632  **               |              |                |
 47633  **               |              V                |
 47634  **               +<------WRITER_FINISHED-------->+
 47635  **
 47636  **
 47637  ** List of state transitions and the C [function] that performs each:
 47638  ** 
 47639  **   OPEN              -> READER              [sqlite3PagerSharedLock]
 47640  **   READER            -> OPEN                [pager_unlock]
 47641  **
 47642  **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
 47643  **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
 47644  **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
 47645  **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
 47646  **   WRITER_***        -> READER              [pager_end_transaction]
 47647  **
 47648  **   WRITER_***        -> ERROR               [pager_error]
 47649  **   ERROR             -> OPEN                [pager_unlock]
 47650  ** 
 47651  **
 47652  **  OPEN:
 47653  **
 47654  **    The pager starts up in this state. Nothing is guaranteed in this
 47655  **    state - the file may or may not be locked and the database size is
 47656  **    unknown. The database may not be read or written.
 47657  **
 47658  **    * No read or write transaction is active.
 47659  **    * Any lock, or no lock at all, may be held on the database file.
 47660  **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
 47661  **
 47662  **  READER:
 47663  **
 47664  **    In this state all the requirements for reading the database in 
 47665  **    rollback (non-WAL) mode are met. Unless the pager is (or recently
 47666  **    was) in exclusive-locking mode, a user-level read transaction is 
 47667  **    open. The database size is known in this state.
 47668  **
 47669  **    A connection running with locking_mode=normal enters this state when
 47670  **    it opens a read-transaction on the database and returns to state
 47671  **    OPEN after the read-transaction is completed. However a connection
 47672  **    running in locking_mode=exclusive (including temp databases) remains in
 47673  **    this state even after the read-transaction is closed. The only way
 47674  **    a locking_mode=exclusive connection can transition from READER to OPEN
 47675  **    is via the ERROR state (see below).
 47676  ** 
 47677  **    * A read transaction may be active (but a write-transaction cannot).
 47678  **    * A SHARED or greater lock is held on the database file.
 47679  **    * The dbSize variable may be trusted (even if a user-level read 
 47680  **      transaction is not active). The dbOrigSize and dbFileSize variables
 47681  **      may not be trusted at this point.
 47682  **    * If the database is a WAL database, then the WAL connection is open.
 47683  **    * Even if a read-transaction is not open, it is guaranteed that 
 47684  **      there is no hot-journal in the file-system.
 47685  **
 47686  **  WRITER_LOCKED:
 47687  **
 47688  **    The pager moves to this state from READER when a write-transaction
 47689  **    is first opened on the database. In WRITER_LOCKED state, all locks 
 47690  **    required to start a write-transaction are held, but no actual 
 47691  **    modifications to the cache or database have taken place.
 47692  **
 47693  **    In rollback mode, a RESERVED or (if the transaction was opened with 
 47694  **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
 47695  **    moving to this state, but the journal file is not written to or opened 
 47696  **    to in this state. If the transaction is committed or rolled back while 
 47697  **    in WRITER_LOCKED state, all that is required is to unlock the database 
 47698  **    file.
 47699  **
 47700  **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
 47701  **    If the connection is running with locking_mode=exclusive, an attempt
 47702  **    is made to obtain an EXCLUSIVE lock on the database file.
 47703  **
 47704  **    * A write transaction is active.
 47705  **    * If the connection is open in rollback-mode, a RESERVED or greater 
 47706  **      lock is held on the database file.
 47707  **    * If the connection is open in WAL-mode, a WAL write transaction
 47708  **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
 47709  **      called).
 47710  **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
 47711  **    * The contents of the pager cache have not been modified.
 47712  **    * The journal file may or may not be open.
 47713  **    * Nothing (not even the first header) has been written to the journal.
 47714  **
 47715  **  WRITER_CACHEMOD:
 47716  **
 47717  **    A pager moves from WRITER_LOCKED state to this state when a page is
 47718  **    first modified by the upper layer. In rollback mode the journal file
 47719  **    is opened (if it is not already open) and a header written to the
 47720  **    start of it. The database file on disk has not been modified.
 47721  **
 47722  **    * A write transaction is active.
 47723  **    * A RESERVED or greater lock is held on the database file.
 47724  **    * The journal file is open and the first header has been written 
 47725  **      to it, but the header has not been synced to disk.
 47726  **    * The contents of the page cache have been modified.
 47727  **
 47728  **  WRITER_DBMOD:
 47729  **
 47730  **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
 47731  **    when it modifies the contents of the database file. WAL connections
 47732  **    never enter this state (since they do not modify the database file,
 47733  **    just the log file).
 47734  **
 47735  **    * A write transaction is active.
 47736  **    * An EXCLUSIVE or greater lock is held on the database file.
 47737  **    * The journal file is open and the first header has been written 
 47738  **      and synced to disk.
 47739  **    * The contents of the page cache have been modified (and possibly
 47740  **      written to disk).
 47741  **
 47742  **  WRITER_FINISHED:
 47743  **
 47744  **    It is not possible for a WAL connection to enter this state.
 47745  **
 47746  **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
 47747  **    state after the entire transaction has been successfully written into the
 47748  **    database file. In this state the transaction may be committed simply
 47749  **    by finalizing the journal file. Once in WRITER_FINISHED state, it is 
 47750  **    not possible to modify the database further. At this point, the upper 
 47751  **    layer must either commit or rollback the transaction.
 47752  **
 47753  **    * A write transaction is active.
 47754  **    * An EXCLUSIVE or greater lock is held on the database file.
 47755  **    * All writing and syncing of journal and database data has finished.
 47756  **      If no error occurred, all that remains is to finalize the journal to
 47757  **      commit the transaction. If an error did occur, the caller will need
 47758  **      to rollback the transaction. 
 47759  **
 47760  **  ERROR:
 47761  **
 47762  **    The ERROR state is entered when an IO or disk-full error (including
 47763  **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it 
 47764  **    difficult to be sure that the in-memory pager state (cache contents, 
 47765  **    db size etc.) are consistent with the contents of the file-system.
 47766  **
 47767  **    Temporary pager files may enter the ERROR state, but in-memory pagers
 47768  **    cannot.
 47769  **
 47770  **    For example, if an IO error occurs while performing a rollback, 
 47771  **    the contents of the page-cache may be left in an inconsistent state.
 47772  **    At this point it would be dangerous to change back to READER state
 47773  **    (as usually happens after a rollback). Any subsequent readers might
 47774  **    report database corruption (due to the inconsistent cache), and if
 47775  **    they upgrade to writers, they may inadvertently corrupt the database
 47776  **    file. To avoid this hazard, the pager switches into the ERROR state
 47777  **    instead of READER following such an error.
 47778  **
 47779  **    Once it has entered the ERROR state, any attempt to use the pager
 47780  **    to read or write data returns an error. Eventually, once all 
 47781  **    outstanding transactions have been abandoned, the pager is able to
 47782  **    transition back to OPEN state, discarding the contents of the 
 47783  **    page-cache and any other in-memory state at the same time. Everything
 47784  **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
 47785  **    when a read-transaction is next opened on the pager (transitioning
 47786  **    the pager into READER state). At that point the system has recovered 
 47787  **    from the error.
 47788  **
 47789  **    Specifically, the pager jumps into the ERROR state if:
 47790  **
 47791  **      1. An error occurs while attempting a rollback. This happens in
 47792  **         function sqlite3PagerRollback().
 47793  **
 47794  **      2. An error occurs while attempting to finalize a journal file
 47795  **         following a commit in function sqlite3PagerCommitPhaseTwo().
 47796  **
 47797  **      3. An error occurs while attempting to write to the journal or
 47798  **         database file in function pagerStress() in order to free up
 47799  **         memory.
 47800  **
 47801  **    In other cases, the error is returned to the b-tree layer. The b-tree
 47802  **    layer then attempts a rollback operation. If the error condition 
 47803  **    persists, the pager enters the ERROR state via condition (1) above.
 47804  **
 47805  **    Condition (3) is necessary because it can be triggered by a read-only
 47806  **    statement executed within a transaction. In this case, if the error
 47807  **    code were simply returned to the user, the b-tree layer would not
 47808  **    automatically attempt a rollback, as it assumes that an error in a
 47809  **    read-only statement cannot leave the pager in an internally inconsistent 
 47810  **    state.
 47811  **
 47812  **    * The Pager.errCode variable is set to something other than SQLITE_OK.
 47813  **    * There are one or more outstanding references to pages (after the
 47814  **      last reference is dropped the pager should move back to OPEN state).
 47815  **    * The pager is not an in-memory pager.
 47816  **    
 47817  **
 47818  ** Notes:
 47819  **
 47820  **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
 47821  **     connection is open in WAL mode. A WAL connection is always in one
 47822  **     of the first four states.
 47823  **
 47824  **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
 47825  **     state. There are two exceptions: immediately after exclusive-mode has
 47826  **     been turned on (and before any read or write transactions are 
 47827  **     executed), and when the pager is leaving the "error state".
 47828  **
 47829  **   * See also: assert_pager_state().
 47830  */
 47831  #define PAGER_OPEN                  0
 47832  #define PAGER_READER                1
 47833  #define PAGER_WRITER_LOCKED         2
 47834  #define PAGER_WRITER_CACHEMOD       3
 47835  #define PAGER_WRITER_DBMOD          4
 47836  #define PAGER_WRITER_FINISHED       5
 47837  #define PAGER_ERROR                 6
 47838  
 47839  /*
 47840  ** The Pager.eLock variable is almost always set to one of the 
 47841  ** following locking-states, according to the lock currently held on
 47842  ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
 47843  ** This variable is kept up to date as locks are taken and released by
 47844  ** the pagerLockDb() and pagerUnlockDb() wrappers.
 47845  **
 47846  ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
 47847  ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
 47848  ** the operation was successful. In these circumstances pagerLockDb() and
 47849  ** pagerUnlockDb() take a conservative approach - eLock is always updated
 47850  ** when unlocking the file, and only updated when locking the file if the
 47851  ** VFS call is successful. This way, the Pager.eLock variable may be set
 47852  ** to a less exclusive (lower) value than the lock that is actually held
 47853  ** at the system level, but it is never set to a more exclusive value.
 47854  **
 47855  ** This is usually safe. If an xUnlock fails or appears to fail, there may 
 47856  ** be a few redundant xLock() calls or a lock may be held for longer than
 47857  ** required, but nothing really goes wrong.
 47858  **
 47859  ** The exception is when the database file is unlocked as the pager moves
 47860  ** from ERROR to OPEN state. At this point there may be a hot-journal file 
 47861  ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
 47862  ** transition, by the same pager or any other). If the call to xUnlock()
 47863  ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
 47864  ** can confuse the call to xCheckReservedLock() call made later as part
 47865  ** of hot-journal detection.
 47866  **
 47867  ** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
 47868  ** lock held by this process or any others". So xCheckReservedLock may 
 47869  ** return true because the caller itself is holding an EXCLUSIVE lock (but
 47870  ** doesn't know it because of a previous error in xUnlock). If this happens
 47871  ** a hot-journal may be mistaken for a journal being created by an active
 47872  ** transaction in another process, causing SQLite to read from the database
 47873  ** without rolling it back.
 47874  **
 47875  ** To work around this, if a call to xUnlock() fails when unlocking the
 47876  ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
 47877  ** is only changed back to a real locking state after a successful call
 47878  ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
 47879  ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
 47880  ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
 47881  ** lock on the database file before attempting to roll it back. See function
 47882  ** PagerSharedLock() for more detail.
 47883  **
 47884  ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
 47885  ** PAGER_OPEN state.
 47886  */
 47887  #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
 47888  
 47889  /*
 47890  ** A macro used for invoking the codec if there is one
 47891  */
 47892  #ifdef SQLITE_HAS_CODEC
 47893  # define CODEC1(P,D,N,X,E) \
 47894      if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
 47895  # define CODEC2(P,D,N,X,E,O) \
 47896      if( P->xCodec==0 ){ O=(char*)D; }else \
 47897      if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
 47898  #else
 47899  # define CODEC1(P,D,N,X,E)   /* NO-OP */
 47900  # define CODEC2(P,D,N,X,E,O) O=(char*)D
 47901  #endif
 47902  
 47903  /*
 47904  ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
 47905  ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
 47906  ** This could conceivably cause corruption following a power failure on
 47907  ** such a system. This is currently an undocumented limit.
 47908  */
 47909  #define MAX_SECTOR_SIZE 0x10000
 47910  
 47911  
 47912  /*
 47913  ** An instance of the following structure is allocated for each active
 47914  ** savepoint and statement transaction in the system. All such structures
 47915  ** are stored in the Pager.aSavepoint[] array, which is allocated and
 47916  ** resized using sqlite3Realloc().
 47917  **
 47918  ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
 47919  ** set to 0. If a journal-header is written into the main journal while
 47920  ** the savepoint is active, then iHdrOffset is set to the byte offset 
 47921  ** immediately following the last journal record written into the main
 47922  ** journal before the journal-header. This is required during savepoint
 47923  ** rollback (see pagerPlaybackSavepoint()).
 47924  */
 47925  typedef struct PagerSavepoint PagerSavepoint;
 47926  struct PagerSavepoint {
 47927    i64 iOffset;                 /* Starting offset in main journal */
 47928    i64 iHdrOffset;              /* See above */
 47929    Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
 47930    Pgno nOrig;                  /* Original number of pages in file */
 47931    Pgno iSubRec;                /* Index of first record in sub-journal */
 47932  #ifndef SQLITE_OMIT_WAL
 47933    u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
 47934  #endif
 47935  };
 47936  
 47937  /*
 47938  ** Bits of the Pager.doNotSpill flag.  See further description below.
 47939  */
 47940  #define SPILLFLAG_OFF         0x01 /* Never spill cache.  Set via pragma */
 47941  #define SPILLFLAG_ROLLBACK    0x02 /* Current rolling back, so do not spill */
 47942  #define SPILLFLAG_NOSYNC      0x04 /* Spill is ok, but do not sync */
 47943  
 47944  /*
 47945  ** An open page cache is an instance of struct Pager. A description of
 47946  ** some of the more important member variables follows:
 47947  **
 47948  ** eState
 47949  **
 47950  **   The current 'state' of the pager object. See the comment and state
 47951  **   diagram above for a description of the pager state.
 47952  **
 47953  ** eLock
 47954  **
 47955  **   For a real on-disk database, the current lock held on the database file -
 47956  **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
 47957  **
 47958  **   For a temporary or in-memory database (neither of which require any
 47959  **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
 47960  **   databases always have Pager.exclusiveMode==1, this tricks the pager
 47961  **   logic into thinking that it already has all the locks it will ever
 47962  **   need (and no reason to release them).
 47963  **
 47964  **   In some (obscure) circumstances, this variable may also be set to
 47965  **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
 47966  **   details.
 47967  **
 47968  ** changeCountDone
 47969  **
 47970  **   This boolean variable is used to make sure that the change-counter 
 47971  **   (the 4-byte header field at byte offset 24 of the database file) is 
 47972  **   not updated more often than necessary. 
 47973  **
 47974  **   It is set to true when the change-counter field is updated, which 
 47975  **   can only happen if an exclusive lock is held on the database file.
 47976  **   It is cleared (set to false) whenever an exclusive lock is 
 47977  **   relinquished on the database file. Each time a transaction is committed,
 47978  **   The changeCountDone flag is inspected. If it is true, the work of
 47979  **   updating the change-counter is omitted for the current transaction.
 47980  **
 47981  **   This mechanism means that when running in exclusive mode, a connection 
 47982  **   need only update the change-counter once, for the first transaction
 47983  **   committed.
 47984  **
 47985  ** setMaster
 47986  **
 47987  **   When PagerCommitPhaseOne() is called to commit a transaction, it may
 47988  **   (or may not) specify a master-journal name to be written into the 
 47989  **   journal file before it is synced to disk.
 47990  **
 47991  **   Whether or not a journal file contains a master-journal pointer affects 
 47992  **   the way in which the journal file is finalized after the transaction is 
 47993  **   committed or rolled back when running in "journal_mode=PERSIST" mode.
 47994  **   If a journal file does not contain a master-journal pointer, it is
 47995  **   finalized by overwriting the first journal header with zeroes. If
 47996  **   it does contain a master-journal pointer the journal file is finalized 
 47997  **   by truncating it to zero bytes, just as if the connection were 
 47998  **   running in "journal_mode=truncate" mode.
 47999  **
 48000  **   Journal files that contain master journal pointers cannot be finalized
 48001  **   simply by overwriting the first journal-header with zeroes, as the
 48002  **   master journal pointer could interfere with hot-journal rollback of any
 48003  **   subsequently interrupted transaction that reuses the journal file.
 48004  **
 48005  **   The flag is cleared as soon as the journal file is finalized (either
 48006  **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
 48007  **   journal file from being successfully finalized, the setMaster flag
 48008  **   is cleared anyway (and the pager will move to ERROR state).
 48009  **
 48010  ** doNotSpill
 48011  **
 48012  **   This variables control the behavior of cache-spills  (calls made by
 48013  **   the pcache module to the pagerStress() routine to write cached data
 48014  **   to the file-system in order to free up memory).
 48015  **
 48016  **   When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
 48017  **   writing to the database from pagerStress() is disabled altogether.
 48018  **   The SPILLFLAG_ROLLBACK case is done in a very obscure case that
 48019  **   comes up during savepoint rollback that requires the pcache module
 48020  **   to allocate a new page to prevent the journal file from being written
 48021  **   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF
 48022  **   case is a user preference.
 48023  ** 
 48024  **   If the SPILLFLAG_NOSYNC bit is set, writing to the database from
 48025  **   pagerStress() is permitted, but syncing the journal file is not.
 48026  **   This flag is set by sqlite3PagerWrite() when the file-system sector-size
 48027  **   is larger than the database page-size in order to prevent a journal sync
 48028  **   from happening in between the journalling of two pages on the same sector. 
 48029  **
 48030  ** subjInMemory
 48031  **
 48032  **   This is a boolean variable. If true, then any required sub-journal
 48033  **   is opened as an in-memory journal file. If false, then in-memory
 48034  **   sub-journals are only used for in-memory pager files.
 48035  **
 48036  **   This variable is updated by the upper layer each time a new 
 48037  **   write-transaction is opened.
 48038  **
 48039  ** dbSize, dbOrigSize, dbFileSize
 48040  **
 48041  **   Variable dbSize is set to the number of pages in the database file.
 48042  **   It is valid in PAGER_READER and higher states (all states except for
 48043  **   OPEN and ERROR). 
 48044  **
 48045  **   dbSize is set based on the size of the database file, which may be 
 48046  **   larger than the size of the database (the value stored at offset
 48047  **   28 of the database header by the btree). If the size of the file
 48048  **   is not an integer multiple of the page-size, the value stored in
 48049  **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
 48050  **   Except, any file that is greater than 0 bytes in size is considered
 48051  **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
 48052  **   to dbSize==1).
 48053  **
 48054  **   During a write-transaction, if pages with page-numbers greater than
 48055  **   dbSize are modified in the cache, dbSize is updated accordingly.
 48056  **   Similarly, if the database is truncated using PagerTruncateImage(), 
 48057  **   dbSize is updated.
 48058  **
 48059  **   Variables dbOrigSize and dbFileSize are valid in states 
 48060  **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
 48061  **   variable at the start of the transaction. It is used during rollback,
 48062  **   and to determine whether or not pages need to be journalled before
 48063  **   being modified.
 48064  **
 48065  **   Throughout a write-transaction, dbFileSize contains the size of
 48066  **   the file on disk in pages. It is set to a copy of dbSize when the
 48067  **   write-transaction is first opened, and updated when VFS calls are made
 48068  **   to write or truncate the database file on disk. 
 48069  **
 48070  **   The only reason the dbFileSize variable is required is to suppress 
 48071  **   unnecessary calls to xTruncate() after committing a transaction. If, 
 48072  **   when a transaction is committed, the dbFileSize variable indicates 
 48073  **   that the database file is larger than the database image (Pager.dbSize), 
 48074  **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
 48075  **   to measure the database file on disk, and then truncates it if required.
 48076  **   dbFileSize is not used when rolling back a transaction. In this case
 48077  **   pager_truncate() is called unconditionally (which means there may be
 48078  **   a call to xFilesize() that is not strictly required). In either case,
 48079  **   pager_truncate() may cause the file to become smaller or larger.
 48080  **
 48081  ** dbHintSize
 48082  **
 48083  **   The dbHintSize variable is used to limit the number of calls made to
 48084  **   the VFS xFileControl(FCNTL_SIZE_HINT) method. 
 48085  **
 48086  **   dbHintSize is set to a copy of the dbSize variable when a
 48087  **   write-transaction is opened (at the same time as dbFileSize and
 48088  **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
 48089  **   dbHintSize is increased to the number of pages that correspond to the
 48090  **   size-hint passed to the method call. See pager_write_pagelist() for 
 48091  **   details.
 48092  **
 48093  ** errCode
 48094  **
 48095  **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
 48096  **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode 
 48097  **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX 
 48098  **   sub-codes.
 48099  **
 48100  ** syncFlags, walSyncFlags
 48101  **
 48102  **   syncFlags is either SQLITE_SYNC_NORMAL (0x02) or SQLITE_SYNC_FULL (0x03).
 48103  **   syncFlags is used for rollback mode.  walSyncFlags is used for WAL mode
 48104  **   and contains the flags used to sync the checkpoint operations in the
 48105  **   lower two bits, and sync flags used for transaction commits in the WAL
 48106  **   file in bits 0x04 and 0x08.  In other words, to get the correct sync flags
 48107  **   for checkpoint operations, use (walSyncFlags&0x03) and to get the correct
 48108  **   sync flags for transaction commit, use ((walSyncFlags>>2)&0x03).  Note
 48109  **   that with synchronous=NORMAL in WAL mode, transaction commit is not synced
 48110  **   meaning that the 0x04 and 0x08 bits are both zero.
 48111  */
 48112  struct Pager {
 48113    sqlite3_vfs *pVfs;          /* OS functions to use for IO */
 48114    u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
 48115    u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
 48116    u8 useJournal;              /* Use a rollback journal on this file */
 48117    u8 noSync;                  /* Do not sync the journal if true */
 48118    u8 fullSync;                /* Do extra syncs of the journal for robustness */
 48119    u8 extraSync;               /* sync directory after journal delete */
 48120    u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
 48121    u8 walSyncFlags;            /* See description above */
 48122    u8 tempFile;                /* zFilename is a temporary or immutable file */
 48123    u8 noLock;                  /* Do not lock (except in WAL mode) */
 48124    u8 readOnly;                /* True for a read-only database */
 48125    u8 memDb;                   /* True to inhibit all file I/O */
 48126  
 48127    /**************************************************************************
 48128    ** The following block contains those class members that change during
 48129    ** routine operation.  Class members not in this block are either fixed
 48130    ** when the pager is first created or else only change when there is a
 48131    ** significant mode change (such as changing the page_size, locking_mode,
 48132    ** or the journal_mode).  From another view, these class members describe
 48133    ** the "state" of the pager, while other class members describe the
 48134    ** "configuration" of the pager.
 48135    */
 48136    u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
 48137    u8 eLock;                   /* Current lock held on database file */
 48138    u8 changeCountDone;         /* Set after incrementing the change-counter */
 48139    u8 setMaster;               /* True if a m-j name has been written to jrnl */
 48140    u8 doNotSpill;              /* Do not spill the cache when non-zero */
 48141    u8 subjInMemory;            /* True to use in-memory sub-journals */
 48142    u8 bUseFetch;               /* True to use xFetch() */
 48143    u8 hasHeldSharedLock;       /* True if a shared lock has ever been held */
 48144    Pgno dbSize;                /* Number of pages in the database */
 48145    Pgno dbOrigSize;            /* dbSize before the current transaction */
 48146    Pgno dbFileSize;            /* Number of pages in the database file */
 48147    Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
 48148    int errCode;                /* One of several kinds of errors */
 48149    int nRec;                   /* Pages journalled since last j-header written */
 48150    u32 cksumInit;              /* Quasi-random value added to every checksum */
 48151    u32 nSubRec;                /* Number of records written to sub-journal */
 48152    Bitvec *pInJournal;         /* One bit for each page in the database file */
 48153    sqlite3_file *fd;           /* File descriptor for database */
 48154    sqlite3_file *jfd;          /* File descriptor for main journal */
 48155    sqlite3_file *sjfd;         /* File descriptor for sub-journal */
 48156    i64 journalOff;             /* Current write offset in the journal file */
 48157    i64 journalHdr;             /* Byte offset to previous journal header */
 48158    sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
 48159    PagerSavepoint *aSavepoint; /* Array of active savepoints */
 48160    int nSavepoint;             /* Number of elements in aSavepoint[] */
 48161    u32 iDataVersion;           /* Changes whenever database content changes */
 48162    char dbFileVers[16];        /* Changes whenever database file changes */
 48163  
 48164    int nMmapOut;               /* Number of mmap pages currently outstanding */
 48165    sqlite3_int64 szMmap;       /* Desired maximum mmap size */
 48166    PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
 48167    /*
 48168    ** End of the routinely-changing class members
 48169    ***************************************************************************/
 48170  
 48171    u16 nExtra;                 /* Add this many bytes to each in-memory page */
 48172    i16 nReserve;               /* Number of unused bytes at end of each page */
 48173    u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
 48174    u32 sectorSize;             /* Assumed sector size during rollback */
 48175    int pageSize;               /* Number of bytes in a page */
 48176    Pgno mxPgno;                /* Maximum allowed size of the database */
 48177    i64 journalSizeLimit;       /* Size limit for persistent journal files */
 48178    char *zFilename;            /* Name of the database file */
 48179    char *zJournal;             /* Name of the journal file */
 48180    int (*xBusyHandler)(void*); /* Function to call when busy */
 48181    void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
 48182    int aStat[3];               /* Total cache hits, misses and writes */
 48183  #ifdef SQLITE_TEST
 48184    int nRead;                  /* Database pages read */
 48185  #endif
 48186    void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
 48187    int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */
 48188  #ifdef SQLITE_HAS_CODEC
 48189    void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
 48190    void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
 48191    void (*xCodecFree)(void*);             /* Destructor for the codec */
 48192    void *pCodec;               /* First argument to xCodec... methods */
 48193  #endif
 48194    char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
 48195    PCache *pPCache;            /* Pointer to page cache object */
 48196  #ifndef SQLITE_OMIT_WAL
 48197    Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
 48198    char *zWal;                 /* File name for write-ahead log */
 48199  #endif
 48200  };
 48201  
 48202  /*
 48203  ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
 48204  ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS 
 48205  ** or CACHE_WRITE to sqlite3_db_status().
 48206  */
 48207  #define PAGER_STAT_HIT   0
 48208  #define PAGER_STAT_MISS  1
 48209  #define PAGER_STAT_WRITE 2
 48210  
 48211  /*
 48212  ** The following global variables hold counters used for
 48213  ** testing purposes only.  These variables do not exist in
 48214  ** a non-testing build.  These variables are not thread-safe.
 48215  */
 48216  #ifdef SQLITE_TEST
 48217  SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
 48218  SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
 48219  SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
 48220  # define PAGER_INCR(v)  v++
 48221  #else
 48222  # define PAGER_INCR(v)
 48223  #endif
 48224  
 48225  
 48226  
 48227  /*
 48228  ** Journal files begin with the following magic string.  The data
 48229  ** was obtained from /dev/random.  It is used only as a sanity check.
 48230  **
 48231  ** Since version 2.8.0, the journal format contains additional sanity
 48232  ** checking information.  If the power fails while the journal is being
 48233  ** written, semi-random garbage data might appear in the journal
 48234  ** file after power is restored.  If an attempt is then made
 48235  ** to roll the journal back, the database could be corrupted.  The additional
 48236  ** sanity checking data is an attempt to discover the garbage in the
 48237  ** journal and ignore it.
 48238  **
 48239  ** The sanity checking information for the new journal format consists
 48240  ** of a 32-bit checksum on each page of data.  The checksum covers both
 48241  ** the page number and the pPager->pageSize bytes of data for the page.
 48242  ** This cksum is initialized to a 32-bit random value that appears in the
 48243  ** journal file right after the header.  The random initializer is important,
 48244  ** because garbage data that appears at the end of a journal is likely
 48245  ** data that was once in other files that have now been deleted.  If the
 48246  ** garbage data came from an obsolete journal file, the checksums might
 48247  ** be correct.  But by initializing the checksum to random value which
 48248  ** is different for every journal, we minimize that risk.
 48249  */
 48250  static const unsigned char aJournalMagic[] = {
 48251    0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
 48252  };
 48253  
 48254  /*
 48255  ** The size of the of each page record in the journal is given by
 48256  ** the following macro.
 48257  */
 48258  #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
 48259  
 48260  /*
 48261  ** The journal header size for this pager. This is usually the same 
 48262  ** size as a single disk sector. See also setSectorSize().
 48263  */
 48264  #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
 48265  
 48266  /*
 48267  ** The macro MEMDB is true if we are dealing with an in-memory database.
 48268  ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
 48269  ** the value of MEMDB will be a constant and the compiler will optimize
 48270  ** out code that would never execute.
 48271  */
 48272  #ifdef SQLITE_OMIT_MEMORYDB
 48273  # define MEMDB 0
 48274  #else
 48275  # define MEMDB pPager->memDb
 48276  #endif
 48277  
 48278  /*
 48279  ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
 48280  ** interfaces to access the database using memory-mapped I/O.
 48281  */
 48282  #if SQLITE_MAX_MMAP_SIZE>0
 48283  # define USEFETCH(x) ((x)->bUseFetch)
 48284  #else
 48285  # define USEFETCH(x) 0
 48286  #endif
 48287  
 48288  /*
 48289  ** The maximum legal page number is (2^31 - 1).
 48290  */
 48291  #define PAGER_MAX_PGNO 2147483647
 48292  
 48293  /*
 48294  ** The argument to this macro is a file descriptor (type sqlite3_file*).
 48295  ** Return 0 if it is not open, or non-zero (but not 1) if it is.
 48296  **
 48297  ** This is so that expressions can be written as:
 48298  **
 48299  **   if( isOpen(pPager->jfd) ){ ...
 48300  **
 48301  ** instead of
 48302  **
 48303  **   if( pPager->jfd->pMethods ){ ...
 48304  */
 48305  #define isOpen(pFd) ((pFd)->pMethods!=0)
 48306  
 48307  /*
 48308  ** Return true if this pager uses a write-ahead log to read page pgno.
 48309  ** Return false if the pager reads pgno directly from the database.
 48310  */
 48311  #if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_DIRECT_OVERFLOW_READ)
 48312  SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager, Pgno pgno){
 48313    u32 iRead = 0;
 48314    int rc;
 48315    if( pPager->pWal==0 ) return 0;
 48316    rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
 48317    return rc || iRead;
 48318  }
 48319  #endif
 48320  #ifndef SQLITE_OMIT_WAL
 48321  # define pagerUseWal(x) ((x)->pWal!=0)
 48322  #else
 48323  # define pagerUseWal(x) 0
 48324  # define pagerRollbackWal(x) 0
 48325  # define pagerWalFrames(v,w,x,y) 0
 48326  # define pagerOpenWalIfPresent(z) SQLITE_OK
 48327  # define pagerBeginReadTransaction(z) SQLITE_OK
 48328  #endif
 48329  
 48330  #ifndef NDEBUG 
 48331  /*
 48332  ** Usage:
 48333  **
 48334  **   assert( assert_pager_state(pPager) );
 48335  **
 48336  ** This function runs many asserts to try to find inconsistencies in
 48337  ** the internal state of the Pager object.
 48338  */
 48339  static int assert_pager_state(Pager *p){
 48340    Pager *pPager = p;
 48341  
 48342    /* State must be valid. */
 48343    assert( p->eState==PAGER_OPEN
 48344         || p->eState==PAGER_READER
 48345         || p->eState==PAGER_WRITER_LOCKED
 48346         || p->eState==PAGER_WRITER_CACHEMOD
 48347         || p->eState==PAGER_WRITER_DBMOD
 48348         || p->eState==PAGER_WRITER_FINISHED
 48349         || p->eState==PAGER_ERROR
 48350    );
 48351  
 48352    /* Regardless of the current state, a temp-file connection always behaves
 48353    ** as if it has an exclusive lock on the database file. It never updates
 48354    ** the change-counter field, so the changeCountDone flag is always set.
 48355    */
 48356    assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
 48357    assert( p->tempFile==0 || pPager->changeCountDone );
 48358  
 48359    /* If the useJournal flag is clear, the journal-mode must be "OFF". 
 48360    ** And if the journal-mode is "OFF", the journal file must not be open.
 48361    */
 48362    assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
 48363    assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
 48364  
 48365    /* Check that MEMDB implies noSync. And an in-memory journal. Since 
 48366    ** this means an in-memory pager performs no IO at all, it cannot encounter 
 48367    ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing 
 48368    ** a journal file. (although the in-memory journal implementation may 
 48369    ** return SQLITE_IOERR_NOMEM while the journal file is being written). It 
 48370    ** is therefore not possible for an in-memory pager to enter the ERROR 
 48371    ** state.
 48372    */
 48373    if( MEMDB ){
 48374      assert( !isOpen(p->fd) );
 48375      assert( p->noSync );
 48376      assert( p->journalMode==PAGER_JOURNALMODE_OFF 
 48377           || p->journalMode==PAGER_JOURNALMODE_MEMORY 
 48378      );
 48379      assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
 48380      assert( pagerUseWal(p)==0 );
 48381    }
 48382  
 48383    /* If changeCountDone is set, a RESERVED lock or greater must be held
 48384    ** on the file.
 48385    */
 48386    assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
 48387    assert( p->eLock!=PENDING_LOCK );
 48388  
 48389    switch( p->eState ){
 48390      case PAGER_OPEN:
 48391        assert( !MEMDB );
 48392        assert( pPager->errCode==SQLITE_OK );
 48393        assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
 48394        break;
 48395  
 48396      case PAGER_READER:
 48397        assert( pPager->errCode==SQLITE_OK );
 48398        assert( p->eLock!=UNKNOWN_LOCK );
 48399        assert( p->eLock>=SHARED_LOCK );
 48400        break;
 48401  
 48402      case PAGER_WRITER_LOCKED:
 48403        assert( p->eLock!=UNKNOWN_LOCK );
 48404        assert( pPager->errCode==SQLITE_OK );
 48405        if( !pagerUseWal(pPager) ){
 48406          assert( p->eLock>=RESERVED_LOCK );
 48407        }
 48408        assert( pPager->dbSize==pPager->dbOrigSize );
 48409        assert( pPager->dbOrigSize==pPager->dbFileSize );
 48410        assert( pPager->dbOrigSize==pPager->dbHintSize );
 48411        assert( pPager->setMaster==0 );
 48412        break;
 48413  
 48414      case PAGER_WRITER_CACHEMOD:
 48415        assert( p->eLock!=UNKNOWN_LOCK );
 48416        assert( pPager->errCode==SQLITE_OK );
 48417        if( !pagerUseWal(pPager) ){
 48418          /* It is possible that if journal_mode=wal here that neither the
 48419          ** journal file nor the WAL file are open. This happens during
 48420          ** a rollback transaction that switches from journal_mode=off
 48421          ** to journal_mode=wal.
 48422          */
 48423          assert( p->eLock>=RESERVED_LOCK );
 48424          assert( isOpen(p->jfd) 
 48425               || p->journalMode==PAGER_JOURNALMODE_OFF 
 48426               || p->journalMode==PAGER_JOURNALMODE_WAL 
 48427          );
 48428        }
 48429        assert( pPager->dbOrigSize==pPager->dbFileSize );
 48430        assert( pPager->dbOrigSize==pPager->dbHintSize );
 48431        break;
 48432  
 48433      case PAGER_WRITER_DBMOD:
 48434        assert( p->eLock==EXCLUSIVE_LOCK );
 48435        assert( pPager->errCode==SQLITE_OK );
 48436        assert( !pagerUseWal(pPager) );
 48437        assert( p->eLock>=EXCLUSIVE_LOCK );
 48438        assert( isOpen(p->jfd) 
 48439             || p->journalMode==PAGER_JOURNALMODE_OFF 
 48440             || p->journalMode==PAGER_JOURNALMODE_WAL 
 48441             || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
 48442        );
 48443        assert( pPager->dbOrigSize<=pPager->dbHintSize );
 48444        break;
 48445  
 48446      case PAGER_WRITER_FINISHED:
 48447        assert( p->eLock==EXCLUSIVE_LOCK );
 48448        assert( pPager->errCode==SQLITE_OK );
 48449        assert( !pagerUseWal(pPager) );
 48450        assert( isOpen(p->jfd) 
 48451             || p->journalMode==PAGER_JOURNALMODE_OFF 
 48452             || p->journalMode==PAGER_JOURNALMODE_WAL 
 48453             || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
 48454        );
 48455        break;
 48456  
 48457      case PAGER_ERROR:
 48458        /* There must be at least one outstanding reference to the pager if
 48459        ** in ERROR state. Otherwise the pager should have already dropped
 48460        ** back to OPEN state.
 48461        */
 48462        assert( pPager->errCode!=SQLITE_OK );
 48463        assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
 48464        break;
 48465    }
 48466  
 48467    return 1;
 48468  }
 48469  #endif /* ifndef NDEBUG */
 48470  
 48471  #ifdef SQLITE_DEBUG 
 48472  /*
 48473  ** Return a pointer to a human readable string in a static buffer
 48474  ** containing the state of the Pager object passed as an argument. This
 48475  ** is intended to be used within debuggers. For example, as an alternative
 48476  ** to "print *pPager" in gdb:
 48477  **
 48478  ** (gdb) printf "%s", print_pager_state(pPager)
 48479  */
 48480  static char *print_pager_state(Pager *p){
 48481    static char zRet[1024];
 48482  
 48483    sqlite3_snprintf(1024, zRet,
 48484        "Filename:      %s\n"
 48485        "State:         %s errCode=%d\n"
 48486        "Lock:          %s\n"
 48487        "Locking mode:  locking_mode=%s\n"
 48488        "Journal mode:  journal_mode=%s\n"
 48489        "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
 48490        "Journal:       journalOff=%lld journalHdr=%lld\n"
 48491        "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
 48492        , p->zFilename
 48493        , p->eState==PAGER_OPEN            ? "OPEN" :
 48494          p->eState==PAGER_READER          ? "READER" :
 48495          p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
 48496          p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
 48497          p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
 48498          p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
 48499          p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
 48500        , (int)p->errCode
 48501        , p->eLock==NO_LOCK         ? "NO_LOCK" :
 48502          p->eLock==RESERVED_LOCK   ? "RESERVED" :
 48503          p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
 48504          p->eLock==SHARED_LOCK     ? "SHARED" :
 48505          p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
 48506        , p->exclusiveMode ? "exclusive" : "normal"
 48507        , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
 48508          p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
 48509          p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
 48510          p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
 48511          p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
 48512          p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
 48513        , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
 48514        , p->journalOff, p->journalHdr
 48515        , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
 48516    );
 48517  
 48518    return zRet;
 48519  }
 48520  #endif
 48521  
 48522  /* Forward references to the various page getters */
 48523  static int getPageNormal(Pager*,Pgno,DbPage**,int);
 48524  static int getPageError(Pager*,Pgno,DbPage**,int);
 48525  #if SQLITE_MAX_MMAP_SIZE>0
 48526  static int getPageMMap(Pager*,Pgno,DbPage**,int);
 48527  #endif
 48528  
 48529  /*
 48530  ** Set the Pager.xGet method for the appropriate routine used to fetch
 48531  ** content from the pager.
 48532  */
 48533  static void setGetterMethod(Pager *pPager){
 48534    if( pPager->errCode ){
 48535      pPager->xGet = getPageError;
 48536  #if SQLITE_MAX_MMAP_SIZE>0
 48537    }else if( USEFETCH(pPager)
 48538  #ifdef SQLITE_HAS_CODEC
 48539     && pPager->xCodec==0
 48540  #endif
 48541    ){
 48542      pPager->xGet = getPageMMap;
 48543  #endif /* SQLITE_MAX_MMAP_SIZE>0 */
 48544    }else{
 48545      pPager->xGet = getPageNormal;
 48546    }
 48547  }
 48548  
 48549  /*
 48550  ** Return true if it is necessary to write page *pPg into the sub-journal.
 48551  ** A page needs to be written into the sub-journal if there exists one
 48552  ** or more open savepoints for which:
 48553  **
 48554  **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
 48555  **   * The bit corresponding to the page-number is not set in
 48556  **     PagerSavepoint.pInSavepoint.
 48557  */
 48558  static int subjRequiresPage(PgHdr *pPg){
 48559    Pager *pPager = pPg->pPager;
 48560    PagerSavepoint *p;
 48561    Pgno pgno = pPg->pgno;
 48562    int i;
 48563    for(i=0; i<pPager->nSavepoint; i++){
 48564      p = &pPager->aSavepoint[i];
 48565      if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
 48566        return 1;
 48567      }
 48568    }
 48569    return 0;
 48570  }
 48571  
 48572  #ifdef SQLITE_DEBUG
 48573  /*
 48574  ** Return true if the page is already in the journal file.
 48575  */
 48576  static int pageInJournal(Pager *pPager, PgHdr *pPg){
 48577    return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
 48578  }
 48579  #endif
 48580  
 48581  /*
 48582  ** Read a 32-bit integer from the given file descriptor.  Store the integer
 48583  ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
 48584  ** error code is something goes wrong.
 48585  **
 48586  ** All values are stored on disk as big-endian.
 48587  */
 48588  static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
 48589    unsigned char ac[4];
 48590    int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
 48591    if( rc==SQLITE_OK ){
 48592      *pRes = sqlite3Get4byte(ac);
 48593    }
 48594    return rc;
 48595  }
 48596  
 48597  /*
 48598  ** Write a 32-bit integer into a string buffer in big-endian byte order.
 48599  */
 48600  #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
 48601  
 48602  
 48603  /*
 48604  ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
 48605  ** on success or an error code is something goes wrong.
 48606  */
 48607  static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
 48608    char ac[4];
 48609    put32bits(ac, val);
 48610    return sqlite3OsWrite(fd, ac, 4, offset);
 48611  }
 48612  
 48613  /*
 48614  ** Unlock the database file to level eLock, which must be either NO_LOCK
 48615  ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
 48616  ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
 48617  **
 48618  ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
 48619  ** called, do not modify it. See the comment above the #define of 
 48620  ** UNKNOWN_LOCK for an explanation of this.
 48621  */
 48622  static int pagerUnlockDb(Pager *pPager, int eLock){
 48623    int rc = SQLITE_OK;
 48624  
 48625    assert( !pPager->exclusiveMode || pPager->eLock==eLock );
 48626    assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
 48627    assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
 48628    if( isOpen(pPager->fd) ){
 48629      assert( pPager->eLock>=eLock );
 48630      rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
 48631      if( pPager->eLock!=UNKNOWN_LOCK ){
 48632        pPager->eLock = (u8)eLock;
 48633      }
 48634      IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
 48635    }
 48636    return rc;
 48637  }
 48638  
 48639  /*
 48640  ** Lock the database file to level eLock, which must be either SHARED_LOCK,
 48641  ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
 48642  ** Pager.eLock variable to the new locking state. 
 48643  **
 48644  ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is 
 48645  ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. 
 48646  ** See the comment above the #define of UNKNOWN_LOCK for an explanation 
 48647  ** of this.
 48648  */
 48649  static int pagerLockDb(Pager *pPager, int eLock){
 48650    int rc = SQLITE_OK;
 48651  
 48652    assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
 48653    if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
 48654      rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
 48655      if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
 48656        pPager->eLock = (u8)eLock;
 48657        IOTRACE(("LOCK %p %d\n", pPager, eLock))
 48658      }
 48659    }
 48660    return rc;
 48661  }
 48662  
 48663  /*
 48664  ** This function determines whether or not the atomic-write or
 48665  ** atomic-batch-write optimizations can be used with this pager. The
 48666  ** atomic-write optimization can be used if:
 48667  **
 48668  **  (a) the value returned by OsDeviceCharacteristics() indicates that
 48669  **      a database page may be written atomically, and
 48670  **  (b) the value returned by OsSectorSize() is less than or equal
 48671  **      to the page size.
 48672  **
 48673  ** If it can be used, then the value returned is the size of the journal 
 48674  ** file when it contains rollback data for exactly one page.
 48675  **
 48676  ** The atomic-batch-write optimization can be used if OsDeviceCharacteristics()
 48677  ** returns a value with the SQLITE_IOCAP_BATCH_ATOMIC bit set. -1 is
 48678  ** returned in this case.
 48679  **
 48680  ** If neither optimization can be used, 0 is returned.
 48681  */
 48682  static int jrnlBufferSize(Pager *pPager){
 48683    assert( !MEMDB );
 48684  
 48685  #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
 48686   || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
 48687    int dc;                           /* Device characteristics */
 48688  
 48689    assert( isOpen(pPager->fd) );
 48690    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
 48691  #else
 48692    UNUSED_PARAMETER(pPager);
 48693  #endif
 48694  
 48695  #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
 48696    if( dc&SQLITE_IOCAP_BATCH_ATOMIC ){
 48697      return -1;
 48698    }
 48699  #endif
 48700  
 48701  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
 48702    {
 48703      int nSector = pPager->sectorSize;
 48704      int szPage = pPager->pageSize;
 48705  
 48706      assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
 48707      assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
 48708      if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
 48709        return 0;
 48710      }
 48711    }
 48712  
 48713    return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
 48714  #endif
 48715  
 48716    return 0;
 48717  }
 48718  
 48719  /*
 48720  ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
 48721  ** on the cache using a hash function.  This is used for testing
 48722  ** and debugging only.
 48723  */
 48724  #ifdef SQLITE_CHECK_PAGES
 48725  /*
 48726  ** Return a 32-bit hash of the page data for pPage.
 48727  */
 48728  static u32 pager_datahash(int nByte, unsigned char *pData){
 48729    u32 hash = 0;
 48730    int i;
 48731    for(i=0; i<nByte; i++){
 48732      hash = (hash*1039) + pData[i];
 48733    }
 48734    return hash;
 48735  }
 48736  static u32 pager_pagehash(PgHdr *pPage){
 48737    return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
 48738  }
 48739  static void pager_set_pagehash(PgHdr *pPage){
 48740    pPage->pageHash = pager_pagehash(pPage);
 48741  }
 48742  
 48743  /*
 48744  ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
 48745  ** is defined, and NDEBUG is not defined, an assert() statement checks
 48746  ** that the page is either dirty or still matches the calculated page-hash.
 48747  */
 48748  #define CHECK_PAGE(x) checkPage(x)
 48749  static void checkPage(PgHdr *pPg){
 48750    Pager *pPager = pPg->pPager;
 48751    assert( pPager->eState!=PAGER_ERROR );
 48752    assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
 48753  }
 48754  
 48755  #else
 48756  #define pager_datahash(X,Y)  0
 48757  #define pager_pagehash(X)  0
 48758  #define pager_set_pagehash(X)
 48759  #define CHECK_PAGE(x)
 48760  #endif  /* SQLITE_CHECK_PAGES */
 48761  
 48762  /*
 48763  ** When this is called the journal file for pager pPager must be open.
 48764  ** This function attempts to read a master journal file name from the 
 48765  ** end of the file and, if successful, copies it into memory supplied 
 48766  ** by the caller. See comments above writeMasterJournal() for the format
 48767  ** used to store a master journal file name at the end of a journal file.
 48768  **
 48769  ** zMaster must point to a buffer of at least nMaster bytes allocated by
 48770  ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
 48771  ** enough space to write the master journal name). If the master journal
 48772  ** name in the journal is longer than nMaster bytes (including a
 48773  ** nul-terminator), then this is handled as if no master journal name
 48774  ** were present in the journal.
 48775  **
 48776  ** If a master journal file name is present at the end of the journal
 48777  ** file, then it is copied into the buffer pointed to by zMaster. A
 48778  ** nul-terminator byte is appended to the buffer following the master
 48779  ** journal file name.
 48780  **
 48781  ** If it is determined that no master journal file name is present 
 48782  ** zMaster[0] is set to 0 and SQLITE_OK returned.
 48783  **
 48784  ** If an error occurs while reading from the journal file, an SQLite
 48785  ** error code is returned.
 48786  */
 48787  static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
 48788    int rc;                    /* Return code */
 48789    u32 len;                   /* Length in bytes of master journal name */
 48790    i64 szJ;                   /* Total size in bytes of journal file pJrnl */
 48791    u32 cksum;                 /* MJ checksum value read from journal */
 48792    u32 u;                     /* Unsigned loop counter */
 48793    unsigned char aMagic[8];   /* A buffer to hold the magic header */
 48794    zMaster[0] = '\0';
 48795  
 48796    if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
 48797     || szJ<16
 48798     || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
 48799     || len>=nMaster 
 48800     || len>szJ-16
 48801     || len==0 
 48802     || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
 48803     || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
 48804     || memcmp(aMagic, aJournalMagic, 8)
 48805     || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
 48806    ){
 48807      return rc;
 48808    }
 48809  
 48810    /* See if the checksum matches the master journal name */
 48811    for(u=0; u<len; u++){
 48812      cksum -= zMaster[u];
 48813    }
 48814    if( cksum ){
 48815      /* If the checksum doesn't add up, then one or more of the disk sectors
 48816      ** containing the master journal filename is corrupted. This means
 48817      ** definitely roll back, so just return SQLITE_OK and report a (nul)
 48818      ** master-journal filename.
 48819      */
 48820      len = 0;
 48821    }
 48822    zMaster[len] = '\0';
 48823     
 48824    return SQLITE_OK;
 48825  }
 48826  
 48827  /*
 48828  ** Return the offset of the sector boundary at or immediately 
 48829  ** following the value in pPager->journalOff, assuming a sector 
 48830  ** size of pPager->sectorSize bytes.
 48831  **
 48832  ** i.e for a sector size of 512:
 48833  **
 48834  **   Pager.journalOff          Return value
 48835  **   ---------------------------------------
 48836  **   0                         0
 48837  **   512                       512
 48838  **   100                       512
 48839  **   2000                      2048
 48840  ** 
 48841  */
 48842  static i64 journalHdrOffset(Pager *pPager){
 48843    i64 offset = 0;
 48844    i64 c = pPager->journalOff;
 48845    if( c ){
 48846      offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
 48847    }
 48848    assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
 48849    assert( offset>=c );
 48850    assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
 48851    return offset;
 48852  }
 48853  
 48854  /*
 48855  ** The journal file must be open when this function is called.
 48856  **
 48857  ** This function is a no-op if the journal file has not been written to
 48858  ** within the current transaction (i.e. if Pager.journalOff==0).
 48859  **
 48860  ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
 48861  ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
 48862  ** zero the 28-byte header at the start of the journal file. In either case, 
 48863  ** if the pager is not in no-sync mode, sync the journal file immediately 
 48864  ** after writing or truncating it.
 48865  **
 48866  ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
 48867  ** following the truncation or zeroing described above the size of the 
 48868  ** journal file in bytes is larger than this value, then truncate the
 48869  ** journal file to Pager.journalSizeLimit bytes. The journal file does
 48870  ** not need to be synced following this operation.
 48871  **
 48872  ** If an IO error occurs, abandon processing and return the IO error code.
 48873  ** Otherwise, return SQLITE_OK.
 48874  */
 48875  static int zeroJournalHdr(Pager *pPager, int doTruncate){
 48876    int rc = SQLITE_OK;                               /* Return code */
 48877    assert( isOpen(pPager->jfd) );
 48878    assert( !sqlite3JournalIsInMemory(pPager->jfd) );
 48879    if( pPager->journalOff ){
 48880      const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
 48881  
 48882      IOTRACE(("JZEROHDR %p\n", pPager))
 48883      if( doTruncate || iLimit==0 ){
 48884        rc = sqlite3OsTruncate(pPager->jfd, 0);
 48885      }else{
 48886        static const char zeroHdr[28] = {0};
 48887        rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
 48888      }
 48889      if( rc==SQLITE_OK && !pPager->noSync ){
 48890        rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
 48891      }
 48892  
 48893      /* At this point the transaction is committed but the write lock 
 48894      ** is still held on the file. If there is a size limit configured for 
 48895      ** the persistent journal and the journal file currently consumes more
 48896      ** space than that limit allows for, truncate it now. There is no need
 48897      ** to sync the file following this operation.
 48898      */
 48899      if( rc==SQLITE_OK && iLimit>0 ){
 48900        i64 sz;
 48901        rc = sqlite3OsFileSize(pPager->jfd, &sz);
 48902        if( rc==SQLITE_OK && sz>iLimit ){
 48903          rc = sqlite3OsTruncate(pPager->jfd, iLimit);
 48904        }
 48905      }
 48906    }
 48907    return rc;
 48908  }
 48909  
 48910  /*
 48911  ** The journal file must be open when this routine is called. A journal
 48912  ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
 48913  ** current location.
 48914  **
 48915  ** The format for the journal header is as follows:
 48916  ** - 8 bytes: Magic identifying journal format.
 48917  ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
 48918  ** - 4 bytes: Random number used for page hash.
 48919  ** - 4 bytes: Initial database page count.
 48920  ** - 4 bytes: Sector size used by the process that wrote this journal.
 48921  ** - 4 bytes: Database page size.
 48922  ** 
 48923  ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
 48924  */
 48925  static int writeJournalHdr(Pager *pPager){
 48926    int rc = SQLITE_OK;                 /* Return code */
 48927    char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
 48928    u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
 48929    u32 nWrite;                         /* Bytes of header sector written */
 48930    int ii;                             /* Loop counter */
 48931  
 48932    assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
 48933  
 48934    if( nHeader>JOURNAL_HDR_SZ(pPager) ){
 48935      nHeader = JOURNAL_HDR_SZ(pPager);
 48936    }
 48937  
 48938    /* If there are active savepoints and any of them were created 
 48939    ** since the most recent journal header was written, update the 
 48940    ** PagerSavepoint.iHdrOffset fields now.
 48941    */
 48942    for(ii=0; ii<pPager->nSavepoint; ii++){
 48943      if( pPager->aSavepoint[ii].iHdrOffset==0 ){
 48944        pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
 48945      }
 48946    }
 48947  
 48948    pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
 48949  
 48950    /* 
 48951    ** Write the nRec Field - the number of page records that follow this
 48952    ** journal header. Normally, zero is written to this value at this time.
 48953    ** After the records are added to the journal (and the journal synced, 
 48954    ** if in full-sync mode), the zero is overwritten with the true number
 48955    ** of records (see syncJournal()).
 48956    **
 48957    ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
 48958    ** reading the journal this value tells SQLite to assume that the
 48959    ** rest of the journal file contains valid page records. This assumption
 48960    ** is dangerous, as if a failure occurred whilst writing to the journal
 48961    ** file it may contain some garbage data. There are two scenarios
 48962    ** where this risk can be ignored:
 48963    **
 48964    **   * When the pager is in no-sync mode. Corruption can follow a
 48965    **     power failure in this case anyway.
 48966    **
 48967    **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
 48968    **     that garbage data is never appended to the journal file.
 48969    */
 48970    assert( isOpen(pPager->fd) || pPager->noSync );
 48971    if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
 48972     || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
 48973    ){
 48974      memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
 48975      put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
 48976    }else{
 48977      memset(zHeader, 0, sizeof(aJournalMagic)+4);
 48978    }
 48979  
 48980    /* The random check-hash initializer */ 
 48981    sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
 48982    put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
 48983    /* The initial database size */
 48984    put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
 48985    /* The assumed sector size for this process */
 48986    put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
 48987  
 48988    /* The page size */
 48989    put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
 48990  
 48991    /* Initializing the tail of the buffer is not necessary.  Everything
 48992    ** works find if the following memset() is omitted.  But initializing
 48993    ** the memory prevents valgrind from complaining, so we are willing to
 48994    ** take the performance hit.
 48995    */
 48996    memset(&zHeader[sizeof(aJournalMagic)+20], 0,
 48997           nHeader-(sizeof(aJournalMagic)+20));
 48998  
 48999    /* In theory, it is only necessary to write the 28 bytes that the 
 49000    ** journal header consumes to the journal file here. Then increment the 
 49001    ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
 49002    ** record is written to the following sector (leaving a gap in the file
 49003    ** that will be implicitly filled in by the OS).
 49004    **
 49005    ** However it has been discovered that on some systems this pattern can 
 49006    ** be significantly slower than contiguously writing data to the file,
 49007    ** even if that means explicitly writing data to the block of 
 49008    ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
 49009    ** is done. 
 49010    **
 49011    ** The loop is required here in case the sector-size is larger than the 
 49012    ** database page size. Since the zHeader buffer is only Pager.pageSize
 49013    ** bytes in size, more than one call to sqlite3OsWrite() may be required
 49014    ** to populate the entire journal header sector.
 49015    */ 
 49016    for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
 49017      IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
 49018      rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
 49019      assert( pPager->journalHdr <= pPager->journalOff );
 49020      pPager->journalOff += nHeader;
 49021    }
 49022  
 49023    return rc;
 49024  }
 49025  
 49026  /*
 49027  ** The journal file must be open when this is called. A journal header file
 49028  ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
 49029  ** file. The current location in the journal file is given by
 49030  ** pPager->journalOff. See comments above function writeJournalHdr() for
 49031  ** a description of the journal header format.
 49032  **
 49033  ** If the header is read successfully, *pNRec is set to the number of
 49034  ** page records following this header and *pDbSize is set to the size of the
 49035  ** database before the transaction began, in pages. Also, pPager->cksumInit
 49036  ** is set to the value read from the journal header. SQLITE_OK is returned
 49037  ** in this case.
 49038  **
 49039  ** If the journal header file appears to be corrupted, SQLITE_DONE is
 49040  ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
 49041  ** cannot be read from the journal file an error code is returned.
 49042  */
 49043  static int readJournalHdr(
 49044    Pager *pPager,               /* Pager object */
 49045    int isHot,
 49046    i64 journalSize,             /* Size of the open journal file in bytes */
 49047    u32 *pNRec,                  /* OUT: Value read from the nRec field */
 49048    u32 *pDbSize                 /* OUT: Value of original database size field */
 49049  ){
 49050    int rc;                      /* Return code */
 49051    unsigned char aMagic[8];     /* A buffer to hold the magic header */
 49052    i64 iHdrOff;                 /* Offset of journal header being read */
 49053  
 49054    assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
 49055  
 49056    /* Advance Pager.journalOff to the start of the next sector. If the
 49057    ** journal file is too small for there to be a header stored at this
 49058    ** point, return SQLITE_DONE.
 49059    */
 49060    pPager->journalOff = journalHdrOffset(pPager);
 49061    if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
 49062      return SQLITE_DONE;
 49063    }
 49064    iHdrOff = pPager->journalOff;
 49065  
 49066    /* Read in the first 8 bytes of the journal header. If they do not match
 49067    ** the  magic string found at the start of each journal header, return
 49068    ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
 49069    ** proceed.
 49070    */
 49071    if( isHot || iHdrOff!=pPager->journalHdr ){
 49072      rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
 49073      if( rc ){
 49074        return rc;
 49075      }
 49076      if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
 49077        return SQLITE_DONE;
 49078      }
 49079    }
 49080  
 49081    /* Read the first three 32-bit fields of the journal header: The nRec
 49082    ** field, the checksum-initializer and the database size at the start
 49083    ** of the transaction. Return an error code if anything goes wrong.
 49084    */
 49085    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
 49086     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
 49087     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
 49088    ){
 49089      return rc;
 49090    }
 49091  
 49092    if( pPager->journalOff==0 ){
 49093      u32 iPageSize;               /* Page-size field of journal header */
 49094      u32 iSectorSize;             /* Sector-size field of journal header */
 49095  
 49096      /* Read the page-size and sector-size journal header fields. */
 49097      if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
 49098       || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
 49099      ){
 49100        return rc;
 49101      }
 49102  
 49103      /* Versions of SQLite prior to 3.5.8 set the page-size field of the
 49104      ** journal header to zero. In this case, assume that the Pager.pageSize
 49105      ** variable is already set to the correct page size.
 49106      */
 49107      if( iPageSize==0 ){
 49108        iPageSize = pPager->pageSize;
 49109      }
 49110  
 49111      /* Check that the values read from the page-size and sector-size fields
 49112      ** are within range. To be 'in range', both values need to be a power
 49113      ** of two greater than or equal to 512 or 32, and not greater than their 
 49114      ** respective compile time maximum limits.
 49115      */
 49116      if( iPageSize<512                  || iSectorSize<32
 49117       || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
 49118       || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
 49119      ){
 49120        /* If the either the page-size or sector-size in the journal-header is 
 49121        ** invalid, then the process that wrote the journal-header must have 
 49122        ** crashed before the header was synced. In this case stop reading 
 49123        ** the journal file here.
 49124        */
 49125        return SQLITE_DONE;
 49126      }
 49127  
 49128      /* Update the page-size to match the value read from the journal. 
 49129      ** Use a testcase() macro to make sure that malloc failure within 
 49130      ** PagerSetPagesize() is tested.
 49131      */
 49132      rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
 49133      testcase( rc!=SQLITE_OK );
 49134  
 49135      /* Update the assumed sector-size to match the value used by 
 49136      ** the process that created this journal. If this journal was
 49137      ** created by a process other than this one, then this routine
 49138      ** is being called from within pager_playback(). The local value
 49139      ** of Pager.sectorSize is restored at the end of that routine.
 49140      */
 49141      pPager->sectorSize = iSectorSize;
 49142    }
 49143  
 49144    pPager->journalOff += JOURNAL_HDR_SZ(pPager);
 49145    return rc;
 49146  }
 49147  
 49148  
 49149  /*
 49150  ** Write the supplied master journal name into the journal file for pager
 49151  ** pPager at the current location. The master journal name must be the last
 49152  ** thing written to a journal file. If the pager is in full-sync mode, the
 49153  ** journal file descriptor is advanced to the next sector boundary before
 49154  ** anything is written. The format is:
 49155  **
 49156  **   + 4 bytes: PAGER_MJ_PGNO.
 49157  **   + N bytes: Master journal filename in utf-8.
 49158  **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
 49159  **   + 4 bytes: Master journal name checksum.
 49160  **   + 8 bytes: aJournalMagic[].
 49161  **
 49162  ** The master journal page checksum is the sum of the bytes in the master
 49163  ** journal name, where each byte is interpreted as a signed 8-bit integer.
 49164  **
 49165  ** If zMaster is a NULL pointer (occurs for a single database transaction), 
 49166  ** this call is a no-op.
 49167  */
 49168  static int writeMasterJournal(Pager *pPager, const char *zMaster){
 49169    int rc;                          /* Return code */
 49170    int nMaster;                     /* Length of string zMaster */
 49171    i64 iHdrOff;                     /* Offset of header in journal file */
 49172    i64 jrnlSize;                    /* Size of journal file on disk */
 49173    u32 cksum = 0;                   /* Checksum of string zMaster */
 49174  
 49175    assert( pPager->setMaster==0 );
 49176    assert( !pagerUseWal(pPager) );
 49177  
 49178    if( !zMaster 
 49179     || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
 49180     || !isOpen(pPager->jfd)
 49181    ){
 49182      return SQLITE_OK;
 49183    }
 49184    pPager->setMaster = 1;
 49185    assert( pPager->journalHdr <= pPager->journalOff );
 49186  
 49187    /* Calculate the length in bytes and the checksum of zMaster */
 49188    for(nMaster=0; zMaster[nMaster]; nMaster++){
 49189      cksum += zMaster[nMaster];
 49190    }
 49191  
 49192    /* If in full-sync mode, advance to the next disk sector before writing
 49193    ** the master journal name. This is in case the previous page written to
 49194    ** the journal has already been synced.
 49195    */
 49196    if( pPager->fullSync ){
 49197      pPager->journalOff = journalHdrOffset(pPager);
 49198    }
 49199    iHdrOff = pPager->journalOff;
 49200  
 49201    /* Write the master journal data to the end of the journal file. If
 49202    ** an error occurs, return the error code to the caller.
 49203    */
 49204    if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
 49205     || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
 49206     || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
 49207     || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
 49208     || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
 49209                                   iHdrOff+4+nMaster+8)))
 49210    ){
 49211      return rc;
 49212    }
 49213    pPager->journalOff += (nMaster+20);
 49214  
 49215    /* If the pager is in peristent-journal mode, then the physical 
 49216    ** journal-file may extend past the end of the master-journal name
 49217    ** and 8 bytes of magic data just written to the file. This is 
 49218    ** dangerous because the code to rollback a hot-journal file
 49219    ** will not be able to find the master-journal name to determine 
 49220    ** whether or not the journal is hot. 
 49221    **
 49222    ** Easiest thing to do in this scenario is to truncate the journal 
 49223    ** file to the required size.
 49224    */ 
 49225    if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
 49226     && jrnlSize>pPager->journalOff
 49227    ){
 49228      rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
 49229    }
 49230    return rc;
 49231  }
 49232  
 49233  /*
 49234  ** Discard the entire contents of the in-memory page-cache.
 49235  */
 49236  static void pager_reset(Pager *pPager){
 49237    pPager->iDataVersion++;
 49238    sqlite3BackupRestart(pPager->pBackup);
 49239    sqlite3PcacheClear(pPager->pPCache);
 49240  }
 49241  
 49242  /*
 49243  ** Return the pPager->iDataVersion value
 49244  */
 49245  SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
 49246    assert( pPager->eState>PAGER_OPEN );
 49247    return pPager->iDataVersion;
 49248  }
 49249  
 49250  /*
 49251  ** Free all structures in the Pager.aSavepoint[] array and set both
 49252  ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
 49253  ** if it is open and the pager is not in exclusive mode.
 49254  */
 49255  static void releaseAllSavepoints(Pager *pPager){
 49256    int ii;               /* Iterator for looping through Pager.aSavepoint */
 49257    for(ii=0; ii<pPager->nSavepoint; ii++){
 49258      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
 49259    }
 49260    if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
 49261      sqlite3OsClose(pPager->sjfd);
 49262    }
 49263    sqlite3_free(pPager->aSavepoint);
 49264    pPager->aSavepoint = 0;
 49265    pPager->nSavepoint = 0;
 49266    pPager->nSubRec = 0;
 49267  }
 49268  
 49269  /*
 49270  ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
 49271  ** bitvecs of all open savepoints. Return SQLITE_OK if successful
 49272  ** or SQLITE_NOMEM if a malloc failure occurs.
 49273  */
 49274  static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
 49275    int ii;                   /* Loop counter */
 49276    int rc = SQLITE_OK;       /* Result code */
 49277  
 49278    for(ii=0; ii<pPager->nSavepoint; ii++){
 49279      PagerSavepoint *p = &pPager->aSavepoint[ii];
 49280      if( pgno<=p->nOrig ){
 49281        rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
 49282        testcase( rc==SQLITE_NOMEM );
 49283        assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
 49284      }
 49285    }
 49286    return rc;
 49287  }
 49288  
 49289  /*
 49290  ** This function is a no-op if the pager is in exclusive mode and not
 49291  ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
 49292  ** state.
 49293  **
 49294  ** If the pager is not in exclusive-access mode, the database file is
 49295  ** completely unlocked. If the file is unlocked and the file-system does
 49296  ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
 49297  ** closed (if it is open).
 49298  **
 49299  ** If the pager is in ERROR state when this function is called, the 
 49300  ** contents of the pager cache are discarded before switching back to 
 49301  ** the OPEN state. Regardless of whether the pager is in exclusive-mode
 49302  ** or not, any journal file left in the file-system will be treated
 49303  ** as a hot-journal and rolled back the next time a read-transaction
 49304  ** is opened (by this or by any other connection).
 49305  */
 49306  static void pager_unlock(Pager *pPager){
 49307  
 49308    assert( pPager->eState==PAGER_READER 
 49309         || pPager->eState==PAGER_OPEN 
 49310         || pPager->eState==PAGER_ERROR 
 49311    );
 49312  
 49313    sqlite3BitvecDestroy(pPager->pInJournal);
 49314    pPager->pInJournal = 0;
 49315    releaseAllSavepoints(pPager);
 49316  
 49317    if( pagerUseWal(pPager) ){
 49318      assert( !isOpen(pPager->jfd) );
 49319      sqlite3WalEndReadTransaction(pPager->pWal);
 49320      pPager->eState = PAGER_OPEN;
 49321    }else if( !pPager->exclusiveMode ){
 49322      int rc;                       /* Error code returned by pagerUnlockDb() */
 49323      int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
 49324  
 49325      /* If the operating system support deletion of open files, then
 49326      ** close the journal file when dropping the database lock.  Otherwise
 49327      ** another connection with journal_mode=delete might delete the file
 49328      ** out from under us.
 49329      */
 49330      assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
 49331      assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
 49332      assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
 49333      assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
 49334      assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
 49335      assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
 49336      if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
 49337       || 1!=(pPager->journalMode & 5)
 49338      ){
 49339        sqlite3OsClose(pPager->jfd);
 49340      }
 49341  
 49342      /* If the pager is in the ERROR state and the call to unlock the database
 49343      ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
 49344      ** above the #define for UNKNOWN_LOCK for an explanation of why this
 49345      ** is necessary.
 49346      */
 49347      rc = pagerUnlockDb(pPager, NO_LOCK);
 49348      if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
 49349        pPager->eLock = UNKNOWN_LOCK;
 49350      }
 49351  
 49352      /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
 49353      ** without clearing the error code. This is intentional - the error
 49354      ** code is cleared and the cache reset in the block below.
 49355      */
 49356      assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
 49357      pPager->changeCountDone = 0;
 49358      pPager->eState = PAGER_OPEN;
 49359    }
 49360  
 49361    /* If Pager.errCode is set, the contents of the pager cache cannot be
 49362    ** trusted. Now that there are no outstanding references to the pager,
 49363    ** it can safely move back to PAGER_OPEN state. This happens in both
 49364    ** normal and exclusive-locking mode.
 49365    */
 49366    assert( pPager->errCode==SQLITE_OK || !MEMDB );
 49367    if( pPager->errCode ){
 49368      if( pPager->tempFile==0 ){
 49369        pager_reset(pPager);
 49370        pPager->changeCountDone = 0;
 49371        pPager->eState = PAGER_OPEN;
 49372      }else{
 49373        pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
 49374      }
 49375      if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
 49376      pPager->errCode = SQLITE_OK;
 49377      setGetterMethod(pPager);
 49378    }
 49379  
 49380    pPager->journalOff = 0;
 49381    pPager->journalHdr = 0;
 49382    pPager->setMaster = 0;
 49383  }
 49384  
 49385  /*
 49386  ** This function is called whenever an IOERR or FULL error that requires
 49387  ** the pager to transition into the ERROR state may ahve occurred.
 49388  ** The first argument is a pointer to the pager structure, the second 
 49389  ** the error-code about to be returned by a pager API function. The 
 49390  ** value returned is a copy of the second argument to this function. 
 49391  **
 49392  ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
 49393  ** IOERR sub-codes, the pager enters the ERROR state and the error code
 49394  ** is stored in Pager.errCode. While the pager remains in the ERROR state,
 49395  ** all major API calls on the Pager will immediately return Pager.errCode.
 49396  **
 49397  ** The ERROR state indicates that the contents of the pager-cache 
 49398  ** cannot be trusted. This state can be cleared by completely discarding 
 49399  ** the contents of the pager-cache. If a transaction was active when
 49400  ** the persistent error occurred, then the rollback journal may need
 49401  ** to be replayed to restore the contents of the database file (as if
 49402  ** it were a hot-journal).
 49403  */
 49404  static int pager_error(Pager *pPager, int rc){
 49405    int rc2 = rc & 0xff;
 49406    assert( rc==SQLITE_OK || !MEMDB );
 49407    assert(
 49408         pPager->errCode==SQLITE_FULL ||
 49409         pPager->errCode==SQLITE_OK ||
 49410         (pPager->errCode & 0xff)==SQLITE_IOERR
 49411    );
 49412    if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
 49413      pPager->errCode = rc;
 49414      pPager->eState = PAGER_ERROR;
 49415      setGetterMethod(pPager);
 49416    }
 49417    return rc;
 49418  }
 49419  
 49420  static int pager_truncate(Pager *pPager, Pgno nPage);
 49421  
 49422  /*
 49423  ** The write transaction open on pPager is being committed (bCommit==1)
 49424  ** or rolled back (bCommit==0).
 49425  **
 49426  ** Return TRUE if and only if all dirty pages should be flushed to disk.
 49427  **
 49428  ** Rules:
 49429  **
 49430  **   *  For non-TEMP databases, always sync to disk.  This is necessary
 49431  **      for transactions to be durable.
 49432  **
 49433  **   *  Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
 49434  **      file has been created already (via a spill on pagerStress()) and
 49435  **      when the number of dirty pages in memory exceeds 25% of the total
 49436  **      cache size.
 49437  */
 49438  static int pagerFlushOnCommit(Pager *pPager, int bCommit){
 49439    if( pPager->tempFile==0 ) return 1;
 49440    if( !bCommit ) return 0;
 49441    if( !isOpen(pPager->fd) ) return 0;
 49442    return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
 49443  }
 49444  
 49445  /*
 49446  ** This routine ends a transaction. A transaction is usually ended by 
 49447  ** either a COMMIT or a ROLLBACK operation. This routine may be called 
 49448  ** after rollback of a hot-journal, or if an error occurs while opening
 49449  ** the journal file or writing the very first journal-header of a
 49450  ** database transaction.
 49451  ** 
 49452  ** This routine is never called in PAGER_ERROR state. If it is called
 49453  ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
 49454  ** exclusive than a RESERVED lock, it is a no-op.
 49455  **
 49456  ** Otherwise, any active savepoints are released.
 49457  **
 49458  ** If the journal file is open, then it is "finalized". Once a journal 
 49459  ** file has been finalized it is not possible to use it to roll back a 
 49460  ** transaction. Nor will it be considered to be a hot-journal by this
 49461  ** or any other database connection. Exactly how a journal is finalized
 49462  ** depends on whether or not the pager is running in exclusive mode and
 49463  ** the current journal-mode (Pager.journalMode value), as follows:
 49464  **
 49465  **   journalMode==MEMORY
 49466  **     Journal file descriptor is simply closed. This destroys an 
 49467  **     in-memory journal.
 49468  **
 49469  **   journalMode==TRUNCATE
 49470  **     Journal file is truncated to zero bytes in size.
 49471  **
 49472  **   journalMode==PERSIST
 49473  **     The first 28 bytes of the journal file are zeroed. This invalidates
 49474  **     the first journal header in the file, and hence the entire journal
 49475  **     file. An invalid journal file cannot be rolled back.
 49476  **
 49477  **   journalMode==DELETE
 49478  **     The journal file is closed and deleted using sqlite3OsDelete().
 49479  **
 49480  **     If the pager is running in exclusive mode, this method of finalizing
 49481  **     the journal file is never used. Instead, if the journalMode is
 49482  **     DELETE and the pager is in exclusive mode, the method described under
 49483  **     journalMode==PERSIST is used instead.
 49484  **
 49485  ** After the journal is finalized, the pager moves to PAGER_READER state.
 49486  ** If running in non-exclusive rollback mode, the lock on the file is 
 49487  ** downgraded to a SHARED_LOCK.
 49488  **
 49489  ** SQLITE_OK is returned if no error occurs. If an error occurs during
 49490  ** any of the IO operations to finalize the journal file or unlock the
 49491  ** database then the IO error code is returned to the user. If the 
 49492  ** operation to finalize the journal file fails, then the code still
 49493  ** tries to unlock the database file if not in exclusive mode. If the
 49494  ** unlock operation fails as well, then the first error code related
 49495  ** to the first error encountered (the journal finalization one) is
 49496  ** returned.
 49497  */
 49498  static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
 49499    int rc = SQLITE_OK;      /* Error code from journal finalization operation */
 49500    int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
 49501  
 49502    /* Do nothing if the pager does not have an open write transaction
 49503    ** or at least a RESERVED lock. This function may be called when there
 49504    ** is no write-transaction active but a RESERVED or greater lock is
 49505    ** held under two circumstances:
 49506    **
 49507    **   1. After a successful hot-journal rollback, it is called with
 49508    **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
 49509    **
 49510    **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE 
 49511    **      lock switches back to locking_mode=normal and then executes a
 49512    **      read-transaction, this function is called with eState==PAGER_READER 
 49513    **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
 49514    */
 49515    assert( assert_pager_state(pPager) );
 49516    assert( pPager->eState!=PAGER_ERROR );
 49517    if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
 49518      return SQLITE_OK;
 49519    }
 49520  
 49521    releaseAllSavepoints(pPager);
 49522    assert( isOpen(pPager->jfd) || pPager->pInJournal==0 
 49523        || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
 49524    );
 49525    if( isOpen(pPager->jfd) ){
 49526      assert( !pagerUseWal(pPager) );
 49527  
 49528      /* Finalize the journal file. */
 49529      if( sqlite3JournalIsInMemory(pPager->jfd) ){
 49530        /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
 49531        sqlite3OsClose(pPager->jfd);
 49532      }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
 49533        if( pPager->journalOff==0 ){
 49534          rc = SQLITE_OK;
 49535        }else{
 49536          rc = sqlite3OsTruncate(pPager->jfd, 0);
 49537          if( rc==SQLITE_OK && pPager->fullSync ){
 49538            /* Make sure the new file size is written into the inode right away.
 49539            ** Otherwise the journal might resurrect following a power loss and
 49540            ** cause the last transaction to roll back.  See
 49541            ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
 49542            */
 49543            rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
 49544          }
 49545        }
 49546        pPager->journalOff = 0;
 49547      }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
 49548        || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
 49549      ){
 49550        rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
 49551        pPager->journalOff = 0;
 49552      }else{
 49553        /* This branch may be executed with Pager.journalMode==MEMORY if
 49554        ** a hot-journal was just rolled back. In this case the journal
 49555        ** file should be closed and deleted. If this connection writes to
 49556        ** the database file, it will do so using an in-memory journal.
 49557        */
 49558        int bDelete = !pPager->tempFile;
 49559        assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
 49560        assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
 49561             || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
 49562             || pPager->journalMode==PAGER_JOURNALMODE_WAL 
 49563        );
 49564        sqlite3OsClose(pPager->jfd);
 49565        if( bDelete ){
 49566          rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
 49567        }
 49568      }
 49569    }
 49570  
 49571  #ifdef SQLITE_CHECK_PAGES
 49572    sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
 49573    if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
 49574      PgHdr *p = sqlite3PagerLookup(pPager, 1);
 49575      if( p ){
 49576        p->pageHash = 0;
 49577        sqlite3PagerUnrefNotNull(p);
 49578      }
 49579    }
 49580  #endif
 49581  
 49582    sqlite3BitvecDestroy(pPager->pInJournal);
 49583    pPager->pInJournal = 0;
 49584    pPager->nRec = 0;
 49585    if( rc==SQLITE_OK ){
 49586      if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){
 49587        sqlite3PcacheCleanAll(pPager->pPCache);
 49588      }else{
 49589        sqlite3PcacheClearWritable(pPager->pPCache);
 49590      }
 49591      sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
 49592    }
 49593  
 49594    if( pagerUseWal(pPager) ){
 49595      /* Drop the WAL write-lock, if any. Also, if the connection was in 
 49596      ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE 
 49597      ** lock held on the database file.
 49598      */
 49599      rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
 49600      assert( rc2==SQLITE_OK );
 49601    }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
 49602      /* This branch is taken when committing a transaction in rollback-journal
 49603      ** mode if the database file on disk is larger than the database image.
 49604      ** At this point the journal has been finalized and the transaction 
 49605      ** successfully committed, but the EXCLUSIVE lock is still held on the
 49606      ** file. So it is safe to truncate the database file to its minimum
 49607      ** required size.  */
 49608      assert( pPager->eLock==EXCLUSIVE_LOCK );
 49609      rc = pager_truncate(pPager, pPager->dbSize);
 49610    }
 49611  
 49612    if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
 49613      rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
 49614      if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
 49615    }
 49616  
 49617    if( !pPager->exclusiveMode 
 49618     && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
 49619    ){
 49620      rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
 49621      pPager->changeCountDone = 0;
 49622    }
 49623    pPager->eState = PAGER_READER;
 49624    pPager->setMaster = 0;
 49625  
 49626    return (rc==SQLITE_OK?rc2:rc);
 49627  }
 49628  
 49629  /*
 49630  ** Execute a rollback if a transaction is active and unlock the 
 49631  ** database file. 
 49632  **
 49633  ** If the pager has already entered the ERROR state, do not attempt 
 49634  ** the rollback at this time. Instead, pager_unlock() is called. The
 49635  ** call to pager_unlock() will discard all in-memory pages, unlock
 49636  ** the database file and move the pager back to OPEN state. If this 
 49637  ** means that there is a hot-journal left in the file-system, the next 
 49638  ** connection to obtain a shared lock on the pager (which may be this one) 
 49639  ** will roll it back.
 49640  **
 49641  ** If the pager has not already entered the ERROR state, but an IO or
 49642  ** malloc error occurs during a rollback, then this will itself cause 
 49643  ** the pager to enter the ERROR state. Which will be cleared by the
 49644  ** call to pager_unlock(), as described above.
 49645  */
 49646  static void pagerUnlockAndRollback(Pager *pPager){
 49647    if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
 49648      assert( assert_pager_state(pPager) );
 49649      if( pPager->eState>=PAGER_WRITER_LOCKED ){
 49650        sqlite3BeginBenignMalloc();
 49651        sqlite3PagerRollback(pPager);
 49652        sqlite3EndBenignMalloc();
 49653      }else if( !pPager->exclusiveMode ){
 49654        assert( pPager->eState==PAGER_READER );
 49655        pager_end_transaction(pPager, 0, 0);
 49656      }
 49657    }
 49658    pager_unlock(pPager);
 49659  }
 49660  
 49661  /*
 49662  ** Parameter aData must point to a buffer of pPager->pageSize bytes
 49663  ** of data. Compute and return a checksum based ont the contents of the 
 49664  ** page of data and the current value of pPager->cksumInit.
 49665  **
 49666  ** This is not a real checksum. It is really just the sum of the 
 49667  ** random initial value (pPager->cksumInit) and every 200th byte
 49668  ** of the page data, starting with byte offset (pPager->pageSize%200).
 49669  ** Each byte is interpreted as an 8-bit unsigned integer.
 49670  **
 49671  ** Changing the formula used to compute this checksum results in an
 49672  ** incompatible journal file format.
 49673  **
 49674  ** If journal corruption occurs due to a power failure, the most likely 
 49675  ** scenario is that one end or the other of the record will be changed. 
 49676  ** It is much less likely that the two ends of the journal record will be
 49677  ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
 49678  ** though fast and simple, catches the mostly likely kind of corruption.
 49679  */
 49680  static u32 pager_cksum(Pager *pPager, const u8 *aData){
 49681    u32 cksum = pPager->cksumInit;         /* Checksum value to return */
 49682    int i = pPager->pageSize-200;          /* Loop counter */
 49683    while( i>0 ){
 49684      cksum += aData[i];
 49685      i -= 200;
 49686    }
 49687    return cksum;
 49688  }
 49689  
 49690  /*
 49691  ** Report the current page size and number of reserved bytes back
 49692  ** to the codec.
 49693  */
 49694  #ifdef SQLITE_HAS_CODEC
 49695  static void pagerReportSize(Pager *pPager){
 49696    if( pPager->xCodecSizeChng ){
 49697      pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
 49698                             (int)pPager->nReserve);
 49699    }
 49700  }
 49701  #else
 49702  # define pagerReportSize(X)     /* No-op if we do not support a codec */
 49703  #endif
 49704  
 49705  #ifdef SQLITE_HAS_CODEC
 49706  /*
 49707  ** Make sure the number of reserved bits is the same in the destination
 49708  ** pager as it is in the source.  This comes up when a VACUUM changes the
 49709  ** number of reserved bits to the "optimal" amount.
 49710  */
 49711  SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
 49712    if( pDest->nReserve!=pSrc->nReserve ){
 49713      pDest->nReserve = pSrc->nReserve;
 49714      pagerReportSize(pDest);
 49715    }
 49716  }
 49717  #endif
 49718  
 49719  /*
 49720  ** Read a single page from either the journal file (if isMainJrnl==1) or
 49721  ** from the sub-journal (if isMainJrnl==0) and playback that page.
 49722  ** The page begins at offset *pOffset into the file. The *pOffset
 49723  ** value is increased to the start of the next page in the journal.
 49724  **
 49725  ** The main rollback journal uses checksums - the statement journal does 
 49726  ** not.
 49727  **
 49728  ** If the page number of the page record read from the (sub-)journal file
 49729  ** is greater than the current value of Pager.dbSize, then playback is
 49730  ** skipped and SQLITE_OK is returned.
 49731  **
 49732  ** If pDone is not NULL, then it is a record of pages that have already
 49733  ** been played back.  If the page at *pOffset has already been played back
 49734  ** (if the corresponding pDone bit is set) then skip the playback.
 49735  ** Make sure the pDone bit corresponding to the *pOffset page is set
 49736  ** prior to returning.
 49737  **
 49738  ** If the page record is successfully read from the (sub-)journal file
 49739  ** and played back, then SQLITE_OK is returned. If an IO error occurs
 49740  ** while reading the record from the (sub-)journal file or while writing
 49741  ** to the database file, then the IO error code is returned. If data
 49742  ** is successfully read from the (sub-)journal file but appears to be
 49743  ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
 49744  ** two circumstances:
 49745  ** 
 49746  **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
 49747  **   * If the record is being rolled back from the main journal file
 49748  **     and the checksum field does not match the record content.
 49749  **
 49750  ** Neither of these two scenarios are possible during a savepoint rollback.
 49751  **
 49752  ** If this is a savepoint rollback, then memory may have to be dynamically
 49753  ** allocated by this function. If this is the case and an allocation fails,
 49754  ** SQLITE_NOMEM is returned.
 49755  */
 49756  static int pager_playback_one_page(
 49757    Pager *pPager,                /* The pager being played back */
 49758    i64 *pOffset,                 /* Offset of record to playback */
 49759    Bitvec *pDone,                /* Bitvec of pages already played back */
 49760    int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
 49761    int isSavepnt                 /* True for a savepoint rollback */
 49762  ){
 49763    int rc;
 49764    PgHdr *pPg;                   /* An existing page in the cache */
 49765    Pgno pgno;                    /* The page number of a page in journal */
 49766    u32 cksum;                    /* Checksum used for sanity checking */
 49767    char *aData;                  /* Temporary storage for the page */
 49768    sqlite3_file *jfd;            /* The file descriptor for the journal file */
 49769    int isSynced;                 /* True if journal page is synced */
 49770  #ifdef SQLITE_HAS_CODEC
 49771    /* The jrnlEnc flag is true if Journal pages should be passed through
 49772    ** the codec.  It is false for pure in-memory journals. */
 49773    const int jrnlEnc = (isMainJrnl || pPager->subjInMemory==0);
 49774  #endif
 49775  
 49776    assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
 49777    assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
 49778    assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
 49779    assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
 49780  
 49781    aData = pPager->pTmpSpace;
 49782    assert( aData );         /* Temp storage must have already been allocated */
 49783    assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
 49784  
 49785    /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction 
 49786    ** or savepoint rollback done at the request of the caller) or this is
 49787    ** a hot-journal rollback. If it is a hot-journal rollback, the pager
 49788    ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
 49789    ** only reads from the main journal, not the sub-journal.
 49790    */
 49791    assert( pPager->eState>=PAGER_WRITER_CACHEMOD
 49792         || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
 49793    );
 49794    assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
 49795  
 49796    /* Read the page number and page data from the journal or sub-journal
 49797    ** file. Return an error code to the caller if an IO error occurs.
 49798    */
 49799    jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
 49800    rc = read32bits(jfd, *pOffset, &pgno);
 49801    if( rc!=SQLITE_OK ) return rc;
 49802    rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
 49803    if( rc!=SQLITE_OK ) return rc;
 49804    *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
 49805  
 49806    /* Sanity checking on the page.  This is more important that I originally
 49807    ** thought.  If a power failure occurs while the journal is being written,
 49808    ** it could cause invalid data to be written into the journal.  We need to
 49809    ** detect this invalid data (with high probability) and ignore it.
 49810    */
 49811    if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
 49812      assert( !isSavepnt );
 49813      return SQLITE_DONE;
 49814    }
 49815    if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
 49816      return SQLITE_OK;
 49817    }
 49818    if( isMainJrnl ){
 49819      rc = read32bits(jfd, (*pOffset)-4, &cksum);
 49820      if( rc ) return rc;
 49821      if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
 49822        return SQLITE_DONE;
 49823      }
 49824    }
 49825  
 49826    /* If this page has already been played back before during the current
 49827    ** rollback, then don't bother to play it back again.
 49828    */
 49829    if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
 49830      return rc;
 49831    }
 49832  
 49833    /* When playing back page 1, restore the nReserve setting
 49834    */
 49835    if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
 49836      pPager->nReserve = ((u8*)aData)[20];
 49837      pagerReportSize(pPager);
 49838    }
 49839  
 49840    /* If the pager is in CACHEMOD state, then there must be a copy of this
 49841    ** page in the pager cache. In this case just update the pager cache,
 49842    ** not the database file. The page is left marked dirty in this case.
 49843    **
 49844    ** An exception to the above rule: If the database is in no-sync mode
 49845    ** and a page is moved during an incremental vacuum then the page may
 49846    ** not be in the pager cache. Later: if a malloc() or IO error occurs
 49847    ** during a Movepage() call, then the page may not be in the cache
 49848    ** either. So the condition described in the above paragraph is not
 49849    ** assert()able.
 49850    **
 49851    ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
 49852    ** pager cache if it exists and the main file. The page is then marked 
 49853    ** not dirty. Since this code is only executed in PAGER_OPEN state for
 49854    ** a hot-journal rollback, it is guaranteed that the page-cache is empty
 49855    ** if the pager is in OPEN state.
 49856    **
 49857    ** Ticket #1171:  The statement journal might contain page content that is
 49858    ** different from the page content at the start of the transaction.
 49859    ** This occurs when a page is changed prior to the start of a statement
 49860    ** then changed again within the statement.  When rolling back such a
 49861    ** statement we must not write to the original database unless we know
 49862    ** for certain that original page contents are synced into the main rollback
 49863    ** journal.  Otherwise, a power loss might leave modified data in the
 49864    ** database file without an entry in the rollback journal that can
 49865    ** restore the database to its original form.  Two conditions must be
 49866    ** met before writing to the database files. (1) the database must be
 49867    ** locked.  (2) we know that the original page content is fully synced
 49868    ** in the main journal either because the page is not in cache or else
 49869    ** the page is marked as needSync==0.
 49870    **
 49871    ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
 49872    ** is possible to fail a statement on a database that does not yet exist.
 49873    ** Do not attempt to write if database file has never been opened.
 49874    */
 49875    if( pagerUseWal(pPager) ){
 49876      pPg = 0;
 49877    }else{
 49878      pPg = sqlite3PagerLookup(pPager, pgno);
 49879    }
 49880    assert( pPg || !MEMDB );
 49881    assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
 49882    PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
 49883             PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
 49884             (isMainJrnl?"main-journal":"sub-journal")
 49885    ));
 49886    if( isMainJrnl ){
 49887      isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
 49888    }else{
 49889      isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
 49890    }
 49891    if( isOpen(pPager->fd)
 49892     && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
 49893     && isSynced
 49894    ){
 49895      i64 ofst = (pgno-1)*(i64)pPager->pageSize;
 49896      testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
 49897      assert( !pagerUseWal(pPager) );
 49898  
 49899      /* Write the data read from the journal back into the database file.
 49900      ** This is usually safe even for an encrypted database - as the data
 49901      ** was encrypted before it was written to the journal file. The exception
 49902      ** is if the data was just read from an in-memory sub-journal. In that
 49903      ** case it must be encrypted here before it is copied into the database
 49904      ** file.  */
 49905  #ifdef SQLITE_HAS_CODEC
 49906      if( !jrnlEnc ){
 49907        CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
 49908        rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
 49909        CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
 49910      }else
 49911  #endif
 49912      rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
 49913  
 49914      if( pgno>pPager->dbFileSize ){
 49915        pPager->dbFileSize = pgno;
 49916      }
 49917      if( pPager->pBackup ){
 49918  #ifdef SQLITE_HAS_CODEC
 49919        if( jrnlEnc ){
 49920          CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
 49921          sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
 49922          CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT,aData);
 49923        }else
 49924  #endif
 49925        sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
 49926      }
 49927    }else if( !isMainJrnl && pPg==0 ){
 49928      /* If this is a rollback of a savepoint and data was not written to
 49929      ** the database and the page is not in-memory, there is a potential
 49930      ** problem. When the page is next fetched by the b-tree layer, it 
 49931      ** will be read from the database file, which may or may not be 
 49932      ** current. 
 49933      **
 49934      ** There are a couple of different ways this can happen. All are quite
 49935      ** obscure. When running in synchronous mode, this can only happen 
 49936      ** if the page is on the free-list at the start of the transaction, then
 49937      ** populated, then moved using sqlite3PagerMovepage().
 49938      **
 49939      ** The solution is to add an in-memory page to the cache containing
 49940      ** the data just read from the sub-journal. Mark the page as dirty 
 49941      ** and if the pager requires a journal-sync, then mark the page as 
 49942      ** requiring a journal-sync before it is written.
 49943      */
 49944      assert( isSavepnt );
 49945      assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
 49946      pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
 49947      rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
 49948      assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
 49949      pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
 49950      if( rc!=SQLITE_OK ) return rc;
 49951      sqlite3PcacheMakeDirty(pPg);
 49952    }
 49953    if( pPg ){
 49954      /* No page should ever be explicitly rolled back that is in use, except
 49955      ** for page 1 which is held in use in order to keep the lock on the
 49956      ** database active. However such a page may be rolled back as a result
 49957      ** of an internal error resulting in an automatic call to
 49958      ** sqlite3PagerRollback().
 49959      */
 49960      void *pData;
 49961      pData = pPg->pData;
 49962      memcpy(pData, (u8*)aData, pPager->pageSize);
 49963      pPager->xReiniter(pPg);
 49964      /* It used to be that sqlite3PcacheMakeClean(pPg) was called here.  But
 49965      ** that call was dangerous and had no detectable benefit since the cache
 49966      ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
 49967      ** has been removed. */
 49968      pager_set_pagehash(pPg);
 49969  
 49970      /* If this was page 1, then restore the value of Pager.dbFileVers.
 49971      ** Do this before any decoding. */
 49972      if( pgno==1 ){
 49973        memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
 49974      }
 49975  
 49976      /* Decode the page just read from disk */
 49977  #if SQLITE_HAS_CODEC
 49978      if( jrnlEnc ){ CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT); }
 49979  #endif
 49980      sqlite3PcacheRelease(pPg);
 49981    }
 49982    return rc;
 49983  }
 49984  
 49985  /*
 49986  ** Parameter zMaster is the name of a master journal file. A single journal
 49987  ** file that referred to the master journal file has just been rolled back.
 49988  ** This routine checks if it is possible to delete the master journal file,
 49989  ** and does so if it is.
 49990  **
 49991  ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
 49992  ** available for use within this function.
 49993  **
 49994  ** When a master journal file is created, it is populated with the names 
 49995  ** of all of its child journals, one after another, formatted as utf-8 
 49996  ** encoded text. The end of each child journal file is marked with a 
 49997  ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
 49998  ** file for a transaction involving two databases might be:
 49999  **
 50000  **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
 50001  **
 50002  ** A master journal file may only be deleted once all of its child 
 50003  ** journals have been rolled back.
 50004  **
 50005  ** This function reads the contents of the master-journal file into 
 50006  ** memory and loops through each of the child journal names. For
 50007  ** each child journal, it checks if:
 50008  **
 50009  **   * if the child journal exists, and if so
 50010  **   * if the child journal contains a reference to master journal 
 50011  **     file zMaster
 50012  **
 50013  ** If a child journal can be found that matches both of the criteria
 50014  ** above, this function returns without doing anything. Otherwise, if
 50015  ** no such child journal can be found, file zMaster is deleted from
 50016  ** the file-system using sqlite3OsDelete().
 50017  **
 50018  ** If an IO error within this function, an error code is returned. This
 50019  ** function allocates memory by calling sqlite3Malloc(). If an allocation
 50020  ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
 50021  ** occur, SQLITE_OK is returned.
 50022  **
 50023  ** TODO: This function allocates a single block of memory to load
 50024  ** the entire contents of the master journal file. This could be
 50025  ** a couple of kilobytes or so - potentially larger than the page 
 50026  ** size.
 50027  */
 50028  static int pager_delmaster(Pager *pPager, const char *zMaster){
 50029    sqlite3_vfs *pVfs = pPager->pVfs;
 50030    int rc;                   /* Return code */
 50031    sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
 50032    sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
 50033    char *zMasterJournal = 0; /* Contents of master journal file */
 50034    i64 nMasterJournal;       /* Size of master journal file */
 50035    char *zJournal;           /* Pointer to one journal within MJ file */
 50036    char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
 50037    int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
 50038  
 50039    /* Allocate space for both the pJournal and pMaster file descriptors.
 50040    ** If successful, open the master journal file for reading.
 50041    */
 50042    pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
 50043    pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
 50044    if( !pMaster ){
 50045      rc = SQLITE_NOMEM_BKPT;
 50046    }else{
 50047      const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
 50048      rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
 50049    }
 50050    if( rc!=SQLITE_OK ) goto delmaster_out;
 50051  
 50052    /* Load the entire master journal file into space obtained from
 50053    ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
 50054    ** sufficient space (in zMasterPtr) to hold the names of master
 50055    ** journal files extracted from regular rollback-journals.
 50056    */
 50057    rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
 50058    if( rc!=SQLITE_OK ) goto delmaster_out;
 50059    nMasterPtr = pVfs->mxPathname+1;
 50060    zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
 50061    if( !zMasterJournal ){
 50062      rc = SQLITE_NOMEM_BKPT;
 50063      goto delmaster_out;
 50064    }
 50065    zMasterPtr = &zMasterJournal[nMasterJournal+1];
 50066    rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
 50067    if( rc!=SQLITE_OK ) goto delmaster_out;
 50068    zMasterJournal[nMasterJournal] = 0;
 50069  
 50070    zJournal = zMasterJournal;
 50071    while( (zJournal-zMasterJournal)<nMasterJournal ){
 50072      int exists;
 50073      rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
 50074      if( rc!=SQLITE_OK ){
 50075        goto delmaster_out;
 50076      }
 50077      if( exists ){
 50078        /* One of the journals pointed to by the master journal exists.
 50079        ** Open it and check if it points at the master journal. If
 50080        ** so, return without deleting the master journal file.
 50081        */
 50082        int c;
 50083        int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
 50084        rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
 50085        if( rc!=SQLITE_OK ){
 50086          goto delmaster_out;
 50087        }
 50088  
 50089        rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
 50090        sqlite3OsClose(pJournal);
 50091        if( rc!=SQLITE_OK ){
 50092          goto delmaster_out;
 50093        }
 50094  
 50095        c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
 50096        if( c ){
 50097          /* We have a match. Do not delete the master journal file. */
 50098          goto delmaster_out;
 50099        }
 50100      }
 50101      zJournal += (sqlite3Strlen30(zJournal)+1);
 50102    }
 50103   
 50104    sqlite3OsClose(pMaster);
 50105    rc = sqlite3OsDelete(pVfs, zMaster, 0);
 50106  
 50107  delmaster_out:
 50108    sqlite3_free(zMasterJournal);
 50109    if( pMaster ){
 50110      sqlite3OsClose(pMaster);
 50111      assert( !isOpen(pJournal) );
 50112      sqlite3_free(pMaster);
 50113    }
 50114    return rc;
 50115  }
 50116  
 50117  
 50118  /*
 50119  ** This function is used to change the actual size of the database 
 50120  ** file in the file-system. This only happens when committing a transaction,
 50121  ** or rolling back a transaction (including rolling back a hot-journal).
 50122  **
 50123  ** If the main database file is not open, or the pager is not in either
 50124  ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size 
 50125  ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). 
 50126  ** If the file on disk is currently larger than nPage pages, then use the VFS
 50127  ** xTruncate() method to truncate it.
 50128  **
 50129  ** Or, it might be the case that the file on disk is smaller than 
 50130  ** nPage pages. Some operating system implementations can get confused if 
 50131  ** you try to truncate a file to some size that is larger than it 
 50132  ** currently is, so detect this case and write a single zero byte to 
 50133  ** the end of the new file instead.
 50134  **
 50135  ** If successful, return SQLITE_OK. If an IO error occurs while modifying
 50136  ** the database file, return the error code to the caller.
 50137  */
 50138  static int pager_truncate(Pager *pPager, Pgno nPage){
 50139    int rc = SQLITE_OK;
 50140    assert( pPager->eState!=PAGER_ERROR );
 50141    assert( pPager->eState!=PAGER_READER );
 50142    
 50143    if( isOpen(pPager->fd) 
 50144     && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) 
 50145    ){
 50146      i64 currentSize, newSize;
 50147      int szPage = pPager->pageSize;
 50148      assert( pPager->eLock==EXCLUSIVE_LOCK );
 50149      /* TODO: Is it safe to use Pager.dbFileSize here? */
 50150      rc = sqlite3OsFileSize(pPager->fd, &currentSize);
 50151      newSize = szPage*(i64)nPage;
 50152      if( rc==SQLITE_OK && currentSize!=newSize ){
 50153        if( currentSize>newSize ){
 50154          rc = sqlite3OsTruncate(pPager->fd, newSize);
 50155        }else if( (currentSize+szPage)<=newSize ){
 50156          char *pTmp = pPager->pTmpSpace;
 50157          memset(pTmp, 0, szPage);
 50158          testcase( (newSize-szPage) == currentSize );
 50159          testcase( (newSize-szPage) >  currentSize );
 50160          rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
 50161        }
 50162        if( rc==SQLITE_OK ){
 50163          pPager->dbFileSize = nPage;
 50164        }
 50165      }
 50166    }
 50167    return rc;
 50168  }
 50169  
 50170  /*
 50171  ** Return a sanitized version of the sector-size of OS file pFile. The
 50172  ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
 50173  */
 50174  SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
 50175    int iRet = sqlite3OsSectorSize(pFile);
 50176    if( iRet<32 ){
 50177      iRet = 512;
 50178    }else if( iRet>MAX_SECTOR_SIZE ){
 50179      assert( MAX_SECTOR_SIZE>=512 );
 50180      iRet = MAX_SECTOR_SIZE;
 50181    }
 50182    return iRet;
 50183  }
 50184  
 50185  /*
 50186  ** Set the value of the Pager.sectorSize variable for the given
 50187  ** pager based on the value returned by the xSectorSize method
 50188  ** of the open database file. The sector size will be used 
 50189  ** to determine the size and alignment of journal header and 
 50190  ** master journal pointers within created journal files.
 50191  **
 50192  ** For temporary files the effective sector size is always 512 bytes.
 50193  **
 50194  ** Otherwise, for non-temporary files, the effective sector size is
 50195  ** the value returned by the xSectorSize() method rounded up to 32 if
 50196  ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
 50197  ** is greater than MAX_SECTOR_SIZE.
 50198  **
 50199  ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
 50200  ** the effective sector size to its minimum value (512).  The purpose of
 50201  ** pPager->sectorSize is to define the "blast radius" of bytes that
 50202  ** might change if a crash occurs while writing to a single byte in
 50203  ** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
 50204  ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
 50205  ** size.  For backwards compatibility of the rollback journal file format,
 50206  ** we cannot reduce the effective sector size below 512.
 50207  */
 50208  static void setSectorSize(Pager *pPager){
 50209    assert( isOpen(pPager->fd) || pPager->tempFile );
 50210  
 50211    if( pPager->tempFile
 50212     || (sqlite3OsDeviceCharacteristics(pPager->fd) & 
 50213                SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
 50214    ){
 50215      /* Sector size doesn't matter for temporary files. Also, the file
 50216      ** may not have been opened yet, in which case the OsSectorSize()
 50217      ** call will segfault. */
 50218      pPager->sectorSize = 512;
 50219    }else{
 50220      pPager->sectorSize = sqlite3SectorSize(pPager->fd);
 50221    }
 50222  }
 50223  
 50224  /*
 50225  ** Playback the journal and thus restore the database file to
 50226  ** the state it was in before we started making changes.  
 50227  **
 50228  ** The journal file format is as follows: 
 50229  **
 50230  **  (1)  8 byte prefix.  A copy of aJournalMagic[].
 50231  **  (2)  4 byte big-endian integer which is the number of valid page records
 50232  **       in the journal.  If this value is 0xffffffff, then compute the
 50233  **       number of page records from the journal size.
 50234  **  (3)  4 byte big-endian integer which is the initial value for the 
 50235  **       sanity checksum.
 50236  **  (4)  4 byte integer which is the number of pages to truncate the
 50237  **       database to during a rollback.
 50238  **  (5)  4 byte big-endian integer which is the sector size.  The header
 50239  **       is this many bytes in size.
 50240  **  (6)  4 byte big-endian integer which is the page size.
 50241  **  (7)  zero padding out to the next sector size.
 50242  **  (8)  Zero or more pages instances, each as follows:
 50243  **        +  4 byte page number.
 50244  **        +  pPager->pageSize bytes of data.
 50245  **        +  4 byte checksum
 50246  **
 50247  ** When we speak of the journal header, we mean the first 7 items above.
 50248  ** Each entry in the journal is an instance of the 8th item.
 50249  **
 50250  ** Call the value from the second bullet "nRec".  nRec is the number of
 50251  ** valid page entries in the journal.  In most cases, you can compute the
 50252  ** value of nRec from the size of the journal file.  But if a power
 50253  ** failure occurred while the journal was being written, it could be the
 50254  ** case that the size of the journal file had already been increased but
 50255  ** the extra entries had not yet made it safely to disk.  In such a case,
 50256  ** the value of nRec computed from the file size would be too large.  For
 50257  ** that reason, we always use the nRec value in the header.
 50258  **
 50259  ** If the nRec value is 0xffffffff it means that nRec should be computed
 50260  ** from the file size.  This value is used when the user selects the
 50261  ** no-sync option for the journal.  A power failure could lead to corruption
 50262  ** in this case.  But for things like temporary table (which will be
 50263  ** deleted when the power is restored) we don't care.  
 50264  **
 50265  ** If the file opened as the journal file is not a well-formed
 50266  ** journal file then all pages up to the first corrupted page are rolled
 50267  ** back (or no pages if the journal header is corrupted). The journal file
 50268  ** is then deleted and SQLITE_OK returned, just as if no corruption had
 50269  ** been encountered.
 50270  **
 50271  ** If an I/O or malloc() error occurs, the journal-file is not deleted
 50272  ** and an error code is returned.
 50273  **
 50274  ** The isHot parameter indicates that we are trying to rollback a journal
 50275  ** that might be a hot journal.  Or, it could be that the journal is 
 50276  ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
 50277  ** If the journal really is hot, reset the pager cache prior rolling
 50278  ** back any content.  If the journal is merely persistent, no reset is
 50279  ** needed.
 50280  */
 50281  static int pager_playback(Pager *pPager, int isHot){
 50282    sqlite3_vfs *pVfs = pPager->pVfs;
 50283    i64 szJ;                 /* Size of the journal file in bytes */
 50284    u32 nRec;                /* Number of Records in the journal */
 50285    u32 u;                   /* Unsigned loop counter */
 50286    Pgno mxPg = 0;           /* Size of the original file in pages */
 50287    int rc;                  /* Result code of a subroutine */
 50288    int res = 1;             /* Value returned by sqlite3OsAccess() */
 50289    char *zMaster = 0;       /* Name of master journal file if any */
 50290    int needPagerReset;      /* True to reset page prior to first page rollback */
 50291    int nPlayback = 0;       /* Total number of pages restored from journal */
 50292    u32 savedPageSize = pPager->pageSize;
 50293  
 50294    /* Figure out how many records are in the journal.  Abort early if
 50295    ** the journal is empty.
 50296    */
 50297    assert( isOpen(pPager->jfd) );
 50298    rc = sqlite3OsFileSize(pPager->jfd, &szJ);
 50299    if( rc!=SQLITE_OK ){
 50300      goto end_playback;
 50301    }
 50302  
 50303    /* Read the master journal name from the journal, if it is present.
 50304    ** If a master journal file name is specified, but the file is not
 50305    ** present on disk, then the journal is not hot and does not need to be
 50306    ** played back.
 50307    **
 50308    ** TODO: Technically the following is an error because it assumes that
 50309    ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
 50310    ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
 50311    ** mxPathname is 512, which is the same as the minimum allowable value
 50312    ** for pageSize.
 50313    */
 50314    zMaster = pPager->pTmpSpace;
 50315    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
 50316    if( rc==SQLITE_OK && zMaster[0] ){
 50317      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
 50318    }
 50319    zMaster = 0;
 50320    if( rc!=SQLITE_OK || !res ){
 50321      goto end_playback;
 50322    }
 50323    pPager->journalOff = 0;
 50324    needPagerReset = isHot;
 50325  
 50326    /* This loop terminates either when a readJournalHdr() or 
 50327    ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
 50328    ** occurs. 
 50329    */
 50330    while( 1 ){
 50331      /* Read the next journal header from the journal file.  If there are
 50332      ** not enough bytes left in the journal file for a complete header, or
 50333      ** it is corrupted, then a process must have failed while writing it.
 50334      ** This indicates nothing more needs to be rolled back.
 50335      */
 50336      rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
 50337      if( rc!=SQLITE_OK ){ 
 50338        if( rc==SQLITE_DONE ){
 50339          rc = SQLITE_OK;
 50340        }
 50341        goto end_playback;
 50342      }
 50343  
 50344      /* If nRec is 0xffffffff, then this journal was created by a process
 50345      ** working in no-sync mode. This means that the rest of the journal
 50346      ** file consists of pages, there are no more journal headers. Compute
 50347      ** the value of nRec based on this assumption.
 50348      */
 50349      if( nRec==0xffffffff ){
 50350        assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
 50351        nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
 50352      }
 50353  
 50354      /* If nRec is 0 and this rollback is of a transaction created by this
 50355      ** process and if this is the final header in the journal, then it means
 50356      ** that this part of the journal was being filled but has not yet been
 50357      ** synced to disk.  Compute the number of pages based on the remaining
 50358      ** size of the file.
 50359      **
 50360      ** The third term of the test was added to fix ticket #2565.
 50361      ** When rolling back a hot journal, nRec==0 always means that the next
 50362      ** chunk of the journal contains zero pages to be rolled back.  But
 50363      ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
 50364      ** the journal, it means that the journal might contain additional
 50365      ** pages that need to be rolled back and that the number of pages 
 50366      ** should be computed based on the journal file size.
 50367      */
 50368      if( nRec==0 && !isHot &&
 50369          pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
 50370        nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
 50371      }
 50372  
 50373      /* If this is the first header read from the journal, truncate the
 50374      ** database file back to its original size.
 50375      */
 50376      if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
 50377        rc = pager_truncate(pPager, mxPg);
 50378        if( rc!=SQLITE_OK ){
 50379          goto end_playback;
 50380        }
 50381        pPager->dbSize = mxPg;
 50382      }
 50383  
 50384      /* Copy original pages out of the journal and back into the 
 50385      ** database file and/or page cache.
 50386      */
 50387      for(u=0; u<nRec; u++){
 50388        if( needPagerReset ){
 50389          pager_reset(pPager);
 50390          needPagerReset = 0;
 50391        }
 50392        rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
 50393        if( rc==SQLITE_OK ){
 50394          nPlayback++;
 50395        }else{
 50396          if( rc==SQLITE_DONE ){
 50397            pPager->journalOff = szJ;
 50398            break;
 50399          }else if( rc==SQLITE_IOERR_SHORT_READ ){
 50400            /* If the journal has been truncated, simply stop reading and
 50401            ** processing the journal. This might happen if the journal was
 50402            ** not completely written and synced prior to a crash.  In that
 50403            ** case, the database should have never been written in the
 50404            ** first place so it is OK to simply abandon the rollback. */
 50405            rc = SQLITE_OK;
 50406            goto end_playback;
 50407          }else{
 50408            /* If we are unable to rollback, quit and return the error
 50409            ** code.  This will cause the pager to enter the error state
 50410            ** so that no further harm will be done.  Perhaps the next
 50411            ** process to come along will be able to rollback the database.
 50412            */
 50413            goto end_playback;
 50414          }
 50415        }
 50416      }
 50417    }
 50418    /*NOTREACHED*/
 50419    assert( 0 );
 50420  
 50421  end_playback:
 50422    if( rc==SQLITE_OK ){
 50423      rc = sqlite3PagerSetPagesize(pPager, &savedPageSize, -1);
 50424    }
 50425    /* Following a rollback, the database file should be back in its original
 50426    ** state prior to the start of the transaction, so invoke the
 50427    ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
 50428    ** assertion that the transaction counter was modified.
 50429    */
 50430  #ifdef SQLITE_DEBUG
 50431    if( pPager->fd->pMethods ){
 50432      sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
 50433    }
 50434  #endif
 50435  
 50436    /* If this playback is happening automatically as a result of an IO or 
 50437    ** malloc error that occurred after the change-counter was updated but 
 50438    ** before the transaction was committed, then the change-counter 
 50439    ** modification may just have been reverted. If this happens in exclusive 
 50440    ** mode, then subsequent transactions performed by the connection will not
 50441    ** update the change-counter at all. This may lead to cache inconsistency
 50442    ** problems for other processes at some point in the future. So, just
 50443    ** in case this has happened, clear the changeCountDone flag now.
 50444    */
 50445    pPager->changeCountDone = pPager->tempFile;
 50446  
 50447    if( rc==SQLITE_OK ){
 50448      zMaster = pPager->pTmpSpace;
 50449      rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
 50450      testcase( rc!=SQLITE_OK );
 50451    }
 50452    if( rc==SQLITE_OK
 50453     && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
 50454    ){
 50455      rc = sqlite3PagerSync(pPager, 0);
 50456    }
 50457    if( rc==SQLITE_OK ){
 50458      rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
 50459      testcase( rc!=SQLITE_OK );
 50460    }
 50461    if( rc==SQLITE_OK && zMaster[0] && res ){
 50462      /* If there was a master journal and this routine will return success,
 50463      ** see if it is possible to delete the master journal.
 50464      */
 50465      rc = pager_delmaster(pPager, zMaster);
 50466      testcase( rc!=SQLITE_OK );
 50467    }
 50468    if( isHot && nPlayback ){
 50469      sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
 50470                  nPlayback, pPager->zJournal);
 50471    }
 50472  
 50473    /* The Pager.sectorSize variable may have been updated while rolling
 50474    ** back a journal created by a process with a different sector size
 50475    ** value. Reset it to the correct value for this process.
 50476    */
 50477    setSectorSize(pPager);
 50478    return rc;
 50479  }
 50480  
 50481  
 50482  /*
 50483  ** Read the content for page pPg out of the database file (or out of
 50484  ** the WAL if that is where the most recent copy if found) into 
 50485  ** pPg->pData. A shared lock or greater must be held on the database
 50486  ** file before this function is called.
 50487  **
 50488  ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
 50489  ** the value read from the database file.
 50490  **
 50491  ** If an IO error occurs, then the IO error is returned to the caller.
 50492  ** Otherwise, SQLITE_OK is returned.
 50493  */
 50494  static int readDbPage(PgHdr *pPg){
 50495    Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
 50496    int rc = SQLITE_OK;          /* Return code */
 50497  
 50498  #ifndef SQLITE_OMIT_WAL
 50499    u32 iFrame = 0;              /* Frame of WAL containing pgno */
 50500  
 50501    assert( pPager->eState>=PAGER_READER && !MEMDB );
 50502    assert( isOpen(pPager->fd) );
 50503  
 50504    if( pagerUseWal(pPager) ){
 50505      rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
 50506      if( rc ) return rc;
 50507    }
 50508    if( iFrame ){
 50509      rc = sqlite3WalReadFrame(pPager->pWal, iFrame,pPager->pageSize,pPg->pData);
 50510    }else
 50511  #endif
 50512    {
 50513      i64 iOffset = (pPg->pgno-1)*(i64)pPager->pageSize;
 50514      rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
 50515      if( rc==SQLITE_IOERR_SHORT_READ ){
 50516        rc = SQLITE_OK;
 50517      }
 50518    }
 50519  
 50520    if( pPg->pgno==1 ){
 50521      if( rc ){
 50522        /* If the read is unsuccessful, set the dbFileVers[] to something
 50523        ** that will never be a valid file version.  dbFileVers[] is a copy
 50524        ** of bytes 24..39 of the database.  Bytes 28..31 should always be
 50525        ** zero or the size of the database in page. Bytes 32..35 and 35..39
 50526        ** should be page numbers which are never 0xffffffff.  So filling
 50527        ** pPager->dbFileVers[] with all 0xff bytes should suffice.
 50528        **
 50529        ** For an encrypted database, the situation is more complex:  bytes
 50530        ** 24..39 of the database are white noise.  But the probability of
 50531        ** white noise equaling 16 bytes of 0xff is vanishingly small so
 50532        ** we should still be ok.
 50533        */
 50534        memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
 50535      }else{
 50536        u8 *dbFileVers = &((u8*)pPg->pData)[24];
 50537        memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
 50538      }
 50539    }
 50540    CODEC1(pPager, pPg->pData, pPg->pgno, 3, rc = SQLITE_NOMEM_BKPT);
 50541  
 50542    PAGER_INCR(sqlite3_pager_readdb_count);
 50543    PAGER_INCR(pPager->nRead);
 50544    IOTRACE(("PGIN %p %d\n", pPager, pPg->pgno));
 50545    PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
 50546                 PAGERID(pPager), pPg->pgno, pager_pagehash(pPg)));
 50547  
 50548    return rc;
 50549  }
 50550  
 50551  /*
 50552  ** Update the value of the change-counter at offsets 24 and 92 in
 50553  ** the header and the sqlite version number at offset 96.
 50554  **
 50555  ** This is an unconditional update.  See also the pager_incr_changecounter()
 50556  ** routine which only updates the change-counter if the update is actually
 50557  ** needed, as determined by the pPager->changeCountDone state variable.
 50558  */
 50559  static void pager_write_changecounter(PgHdr *pPg){
 50560    u32 change_counter;
 50561  
 50562    /* Increment the value just read and write it back to byte 24. */
 50563    change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
 50564    put32bits(((char*)pPg->pData)+24, change_counter);
 50565  
 50566    /* Also store the SQLite version number in bytes 96..99 and in
 50567    ** bytes 92..95 store the change counter for which the version number
 50568    ** is valid. */
 50569    put32bits(((char*)pPg->pData)+92, change_counter);
 50570    put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
 50571  }
 50572  
 50573  #ifndef SQLITE_OMIT_WAL
 50574  /*
 50575  ** This function is invoked once for each page that has already been 
 50576  ** written into the log file when a WAL transaction is rolled back.
 50577  ** Parameter iPg is the page number of said page. The pCtx argument 
 50578  ** is actually a pointer to the Pager structure.
 50579  **
 50580  ** If page iPg is present in the cache, and has no outstanding references,
 50581  ** it is discarded. Otherwise, if there are one or more outstanding
 50582  ** references, the page content is reloaded from the database. If the
 50583  ** attempt to reload content from the database is required and fails, 
 50584  ** return an SQLite error code. Otherwise, SQLITE_OK.
 50585  */
 50586  static int pagerUndoCallback(void *pCtx, Pgno iPg){
 50587    int rc = SQLITE_OK;
 50588    Pager *pPager = (Pager *)pCtx;
 50589    PgHdr *pPg;
 50590  
 50591    assert( pagerUseWal(pPager) );
 50592    pPg = sqlite3PagerLookup(pPager, iPg);
 50593    if( pPg ){
 50594      if( sqlite3PcachePageRefcount(pPg)==1 ){
 50595        sqlite3PcacheDrop(pPg);
 50596      }else{
 50597        rc = readDbPage(pPg);
 50598        if( rc==SQLITE_OK ){
 50599          pPager->xReiniter(pPg);
 50600        }
 50601        sqlite3PagerUnrefNotNull(pPg);
 50602      }
 50603    }
 50604  
 50605    /* Normally, if a transaction is rolled back, any backup processes are
 50606    ** updated as data is copied out of the rollback journal and into the
 50607    ** database. This is not generally possible with a WAL database, as
 50608    ** rollback involves simply truncating the log file. Therefore, if one
 50609    ** or more frames have already been written to the log (and therefore 
 50610    ** also copied into the backup databases) as part of this transaction,
 50611    ** the backups must be restarted.
 50612    */
 50613    sqlite3BackupRestart(pPager->pBackup);
 50614  
 50615    return rc;
 50616  }
 50617  
 50618  /*
 50619  ** This function is called to rollback a transaction on a WAL database.
 50620  */
 50621  static int pagerRollbackWal(Pager *pPager){
 50622    int rc;                         /* Return Code */
 50623    PgHdr *pList;                   /* List of dirty pages to revert */
 50624  
 50625    /* For all pages in the cache that are currently dirty or have already
 50626    ** been written (but not committed) to the log file, do one of the 
 50627    ** following:
 50628    **
 50629    **   + Discard the cached page (if refcount==0), or
 50630    **   + Reload page content from the database (if refcount>0).
 50631    */
 50632    pPager->dbSize = pPager->dbOrigSize;
 50633    rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
 50634    pList = sqlite3PcacheDirtyList(pPager->pPCache);
 50635    while( pList && rc==SQLITE_OK ){
 50636      PgHdr *pNext = pList->pDirty;
 50637      rc = pagerUndoCallback((void *)pPager, pList->pgno);
 50638      pList = pNext;
 50639    }
 50640  
 50641    return rc;
 50642  }
 50643  
 50644  /*
 50645  ** This function is a wrapper around sqlite3WalFrames(). As well as logging
 50646  ** the contents of the list of pages headed by pList (connected by pDirty),
 50647  ** this function notifies any active backup processes that the pages have
 50648  ** changed. 
 50649  **
 50650  ** The list of pages passed into this routine is always sorted by page number.
 50651  ** Hence, if page 1 appears anywhere on the list, it will be the first page.
 50652  */ 
 50653  static int pagerWalFrames(
 50654    Pager *pPager,                  /* Pager object */
 50655    PgHdr *pList,                   /* List of frames to log */
 50656    Pgno nTruncate,                 /* Database size after this commit */
 50657    int isCommit                    /* True if this is a commit */
 50658  ){
 50659    int rc;                         /* Return code */
 50660    int nList;                      /* Number of pages in pList */
 50661    PgHdr *p;                       /* For looping over pages */
 50662  
 50663    assert( pPager->pWal );
 50664    assert( pList );
 50665  #ifdef SQLITE_DEBUG
 50666    /* Verify that the page list is in accending order */
 50667    for(p=pList; p && p->pDirty; p=p->pDirty){
 50668      assert( p->pgno < p->pDirty->pgno );
 50669    }
 50670  #endif
 50671  
 50672    assert( pList->pDirty==0 || isCommit );
 50673    if( isCommit ){
 50674      /* If a WAL transaction is being committed, there is no point in writing
 50675      ** any pages with page numbers greater than nTruncate into the WAL file.
 50676      ** They will never be read by any client. So remove them from the pDirty
 50677      ** list here. */
 50678      PgHdr **ppNext = &pList;
 50679      nList = 0;
 50680      for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
 50681        if( p->pgno<=nTruncate ){
 50682          ppNext = &p->pDirty;
 50683          nList++;
 50684        }
 50685      }
 50686      assert( pList );
 50687    }else{
 50688      nList = 1;
 50689    }
 50690    pPager->aStat[PAGER_STAT_WRITE] += nList;
 50691  
 50692    if( pList->pgno==1 ) pager_write_changecounter(pList);
 50693    rc = sqlite3WalFrames(pPager->pWal, 
 50694        pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
 50695    );
 50696    if( rc==SQLITE_OK && pPager->pBackup ){
 50697      for(p=pList; p; p=p->pDirty){
 50698        sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
 50699      }
 50700    }
 50701  
 50702  #ifdef SQLITE_CHECK_PAGES
 50703    pList = sqlite3PcacheDirtyList(pPager->pPCache);
 50704    for(p=pList; p; p=p->pDirty){
 50705      pager_set_pagehash(p);
 50706    }
 50707  #endif
 50708  
 50709    return rc;
 50710  }
 50711  
 50712  /*
 50713  ** Begin a read transaction on the WAL.
 50714  **
 50715  ** This routine used to be called "pagerOpenSnapshot()" because it essentially
 50716  ** makes a snapshot of the database at the current point in time and preserves
 50717  ** that snapshot for use by the reader in spite of concurrently changes by
 50718  ** other writers or checkpointers.
 50719  */
 50720  static int pagerBeginReadTransaction(Pager *pPager){
 50721    int rc;                         /* Return code */
 50722    int changed = 0;                /* True if cache must be reset */
 50723  
 50724    assert( pagerUseWal(pPager) );
 50725    assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
 50726  
 50727    /* sqlite3WalEndReadTransaction() was not called for the previous
 50728    ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
 50729    ** are in locking_mode=NORMAL and EndRead() was previously called,
 50730    ** the duplicate call is harmless.
 50731    */
 50732    sqlite3WalEndReadTransaction(pPager->pWal);
 50733  
 50734    rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
 50735    if( rc!=SQLITE_OK || changed ){
 50736      pager_reset(pPager);
 50737      if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
 50738    }
 50739  
 50740    return rc;
 50741  }
 50742  #endif
 50743  
 50744  /*
 50745  ** This function is called as part of the transition from PAGER_OPEN
 50746  ** to PAGER_READER state to determine the size of the database file
 50747  ** in pages (assuming the page size currently stored in Pager.pageSize).
 50748  **
 50749  ** If no error occurs, SQLITE_OK is returned and the size of the database
 50750  ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
 50751  ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
 50752  */
 50753  static int pagerPagecount(Pager *pPager, Pgno *pnPage){
 50754    Pgno nPage;                     /* Value to return via *pnPage */
 50755  
 50756    /* Query the WAL sub-system for the database size. The WalDbsize()
 50757    ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
 50758    ** if the database size is not available. The database size is not
 50759    ** available from the WAL sub-system if the log file is empty or
 50760    ** contains no valid committed transactions.
 50761    */
 50762    assert( pPager->eState==PAGER_OPEN );
 50763    assert( pPager->eLock>=SHARED_LOCK );
 50764    assert( isOpen(pPager->fd) );
 50765    assert( pPager->tempFile==0 );
 50766    nPage = sqlite3WalDbsize(pPager->pWal);
 50767  
 50768    /* If the number of pages in the database is not available from the
 50769    ** WAL sub-system, determine the page count based on the size of
 50770    ** the database file.  If the size of the database file is not an
 50771    ** integer multiple of the page-size, round up the result.
 50772    */
 50773    if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
 50774      i64 n = 0;                    /* Size of db file in bytes */
 50775      int rc = sqlite3OsFileSize(pPager->fd, &n);
 50776      if( rc!=SQLITE_OK ){
 50777        return rc;
 50778      }
 50779      nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
 50780    }
 50781  
 50782    /* If the current number of pages in the file is greater than the
 50783    ** configured maximum pager number, increase the allowed limit so
 50784    ** that the file can be read.
 50785    */
 50786    if( nPage>pPager->mxPgno ){
 50787      pPager->mxPgno = (Pgno)nPage;
 50788    }
 50789  
 50790    *pnPage = nPage;
 50791    return SQLITE_OK;
 50792  }
 50793  
 50794  #ifndef SQLITE_OMIT_WAL
 50795  /*
 50796  ** Check if the *-wal file that corresponds to the database opened by pPager
 50797  ** exists if the database is not empy, or verify that the *-wal file does
 50798  ** not exist (by deleting it) if the database file is empty.
 50799  **
 50800  ** If the database is not empty and the *-wal file exists, open the pager
 50801  ** in WAL mode.  If the database is empty or if no *-wal file exists and
 50802  ** if no error occurs, make sure Pager.journalMode is not set to
 50803  ** PAGER_JOURNALMODE_WAL.
 50804  **
 50805  ** Return SQLITE_OK or an error code.
 50806  **
 50807  ** The caller must hold a SHARED lock on the database file to call this
 50808  ** function. Because an EXCLUSIVE lock on the db file is required to delete 
 50809  ** a WAL on a none-empty database, this ensures there is no race condition 
 50810  ** between the xAccess() below and an xDelete() being executed by some 
 50811  ** other connection.
 50812  */
 50813  static int pagerOpenWalIfPresent(Pager *pPager){
 50814    int rc = SQLITE_OK;
 50815    assert( pPager->eState==PAGER_OPEN );
 50816    assert( pPager->eLock>=SHARED_LOCK );
 50817  
 50818    if( !pPager->tempFile ){
 50819      int isWal;                    /* True if WAL file exists */
 50820      rc = sqlite3OsAccess(
 50821          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
 50822      );
 50823      if( rc==SQLITE_OK ){
 50824        if( isWal ){
 50825          Pgno nPage;                   /* Size of the database file */
 50826  
 50827          rc = pagerPagecount(pPager, &nPage);
 50828          if( rc ) return rc;
 50829          if( nPage==0 ){
 50830            rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
 50831          }else{
 50832            testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
 50833            rc = sqlite3PagerOpenWal(pPager, 0);
 50834          }
 50835        }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
 50836          pPager->journalMode = PAGER_JOURNALMODE_DELETE;
 50837        }
 50838      }
 50839    }
 50840    return rc;
 50841  }
 50842  #endif
 50843  
 50844  /*
 50845  ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
 50846  ** the entire master journal file. The case pSavepoint==NULL occurs when 
 50847  ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
 50848  ** savepoint.
 50849  **
 50850  ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
 50851  ** being rolled back), then the rollback consists of up to three stages,
 50852  ** performed in the order specified:
 50853  **
 50854  **   * Pages are played back from the main journal starting at byte
 50855  **     offset PagerSavepoint.iOffset and continuing to 
 50856  **     PagerSavepoint.iHdrOffset, or to the end of the main journal
 50857  **     file if PagerSavepoint.iHdrOffset is zero.
 50858  **
 50859  **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
 50860  **     back starting from the journal header immediately following 
 50861  **     PagerSavepoint.iHdrOffset to the end of the main journal file.
 50862  **
 50863  **   * Pages are then played back from the sub-journal file, starting
 50864  **     with the PagerSavepoint.iSubRec and continuing to the end of
 50865  **     the journal file.
 50866  **
 50867  ** Throughout the rollback process, each time a page is rolled back, the
 50868  ** corresponding bit is set in a bitvec structure (variable pDone in the
 50869  ** implementation below). This is used to ensure that a page is only
 50870  ** rolled back the first time it is encountered in either journal.
 50871  **
 50872  ** If pSavepoint is NULL, then pages are only played back from the main
 50873  ** journal file. There is no need for a bitvec in this case.
 50874  **
 50875  ** In either case, before playback commences the Pager.dbSize variable
 50876  ** is reset to the value that it held at the start of the savepoint 
 50877  ** (or transaction). No page with a page-number greater than this value
 50878  ** is played back. If one is encountered it is simply skipped.
 50879  */
 50880  static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
 50881    i64 szJ;                 /* Effective size of the main journal */
 50882    i64 iHdrOff;             /* End of first segment of main-journal records */
 50883    int rc = SQLITE_OK;      /* Return code */
 50884    Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
 50885  
 50886    assert( pPager->eState!=PAGER_ERROR );
 50887    assert( pPager->eState>=PAGER_WRITER_LOCKED );
 50888  
 50889    /* Allocate a bitvec to use to store the set of pages rolled back */
 50890    if( pSavepoint ){
 50891      pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
 50892      if( !pDone ){
 50893        return SQLITE_NOMEM_BKPT;
 50894      }
 50895    }
 50896  
 50897    /* Set the database size back to the value it was before the savepoint 
 50898    ** being reverted was opened.
 50899    */
 50900    pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
 50901    pPager->changeCountDone = pPager->tempFile;
 50902  
 50903    if( !pSavepoint && pagerUseWal(pPager) ){
 50904      return pagerRollbackWal(pPager);
 50905    }
 50906  
 50907    /* Use pPager->journalOff as the effective size of the main rollback
 50908    ** journal.  The actual file might be larger than this in
 50909    ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
 50910    ** past pPager->journalOff is off-limits to us.
 50911    */
 50912    szJ = pPager->journalOff;
 50913    assert( pagerUseWal(pPager)==0 || szJ==0 );
 50914  
 50915    /* Begin by rolling back records from the main journal starting at
 50916    ** PagerSavepoint.iOffset and continuing to the next journal header.
 50917    ** There might be records in the main journal that have a page number
 50918    ** greater than the current database size (pPager->dbSize) but those
 50919    ** will be skipped automatically.  Pages are added to pDone as they
 50920    ** are played back.
 50921    */
 50922    if( pSavepoint && !pagerUseWal(pPager) ){
 50923      iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
 50924      pPager->journalOff = pSavepoint->iOffset;
 50925      while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
 50926        rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
 50927      }
 50928      assert( rc!=SQLITE_DONE );
 50929    }else{
 50930      pPager->journalOff = 0;
 50931    }
 50932  
 50933    /* Continue rolling back records out of the main journal starting at
 50934    ** the first journal header seen and continuing until the effective end
 50935    ** of the main journal file.  Continue to skip out-of-range pages and
 50936    ** continue adding pages rolled back to pDone.
 50937    */
 50938    while( rc==SQLITE_OK && pPager->journalOff<szJ ){
 50939      u32 ii;            /* Loop counter */
 50940      u32 nJRec = 0;     /* Number of Journal Records */
 50941      u32 dummy;
 50942      rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
 50943      assert( rc!=SQLITE_DONE );
 50944  
 50945      /*
 50946      ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
 50947      ** test is related to ticket #2565.  See the discussion in the
 50948      ** pager_playback() function for additional information.
 50949      */
 50950      if( nJRec==0 
 50951       && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
 50952      ){
 50953        nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
 50954      }
 50955      for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
 50956        rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
 50957      }
 50958      assert( rc!=SQLITE_DONE );
 50959    }
 50960    assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
 50961  
 50962    /* Finally,  rollback pages from the sub-journal.  Page that were
 50963    ** previously rolled back out of the main journal (and are hence in pDone)
 50964    ** will be skipped.  Out-of-range pages are also skipped.
 50965    */
 50966    if( pSavepoint ){
 50967      u32 ii;            /* Loop counter */
 50968      i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
 50969  
 50970      if( pagerUseWal(pPager) ){
 50971        rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
 50972      }
 50973      for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
 50974        assert( offset==(i64)ii*(4+pPager->pageSize) );
 50975        rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
 50976      }
 50977      assert( rc!=SQLITE_DONE );
 50978    }
 50979  
 50980    sqlite3BitvecDestroy(pDone);
 50981    if( rc==SQLITE_OK ){
 50982      pPager->journalOff = szJ;
 50983    }
 50984  
 50985    return rc;
 50986  }
 50987  
 50988  /*
 50989  ** Change the maximum number of in-memory pages that are allowed
 50990  ** before attempting to recycle clean and unused pages.
 50991  */
 50992  SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
 50993    sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
 50994  }
 50995  
 50996  /*
 50997  ** Change the maximum number of in-memory pages that are allowed
 50998  ** before attempting to spill pages to journal.
 50999  */
 51000  SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
 51001    return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
 51002  }
 51003  
 51004  /*
 51005  ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
 51006  */
 51007  static void pagerFixMaplimit(Pager *pPager){
 51008  #if SQLITE_MAX_MMAP_SIZE>0
 51009    sqlite3_file *fd = pPager->fd;
 51010    if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
 51011      sqlite3_int64 sz;
 51012      sz = pPager->szMmap;
 51013      pPager->bUseFetch = (sz>0);
 51014      setGetterMethod(pPager);
 51015      sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
 51016    }
 51017  #endif
 51018  }
 51019  
 51020  /*
 51021  ** Change the maximum size of any memory mapping made of the database file.
 51022  */
 51023  SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
 51024    pPager->szMmap = szMmap;
 51025    pagerFixMaplimit(pPager);
 51026  }
 51027  
 51028  /*
 51029  ** Free as much memory as possible from the pager.
 51030  */
 51031  SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
 51032    sqlite3PcacheShrink(pPager->pPCache);
 51033  }
 51034  
 51035  /*
 51036  ** Adjust settings of the pager to those specified in the pgFlags parameter.
 51037  **
 51038  ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
 51039  ** of the database to damage due to OS crashes or power failures by
 51040  ** changing the number of syncs()s when writing the journals.
 51041  ** There are four levels:
 51042  **
 51043  **    OFF       sqlite3OsSync() is never called.  This is the default
 51044  **              for temporary and transient files.
 51045  **
 51046  **    NORMAL    The journal is synced once before writes begin on the
 51047  **              database.  This is normally adequate protection, but
 51048  **              it is theoretically possible, though very unlikely,
 51049  **              that an inopertune power failure could leave the journal
 51050  **              in a state which would cause damage to the database
 51051  **              when it is rolled back.
 51052  **
 51053  **    FULL      The journal is synced twice before writes begin on the
 51054  **              database (with some additional information - the nRec field
 51055  **              of the journal header - being written in between the two
 51056  **              syncs).  If we assume that writing a
 51057  **              single disk sector is atomic, then this mode provides
 51058  **              assurance that the journal will not be corrupted to the
 51059  **              point of causing damage to the database during rollback.
 51060  **
 51061  **    EXTRA     This is like FULL except that is also syncs the directory
 51062  **              that contains the rollback journal after the rollback
 51063  **              journal is unlinked.
 51064  **
 51065  ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
 51066  ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
 51067  ** prior to the start of checkpoint and that the database file is synced
 51068  ** at the conclusion of the checkpoint if the entire content of the WAL
 51069  ** was written back into the database.  But no sync operations occur for
 51070  ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
 51071  ** file is synced following each commit operation, in addition to the
 51072  ** syncs associated with NORMAL.  There is no difference between FULL
 51073  ** and EXTRA for WAL mode.
 51074  **
 51075  ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
 51076  ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
 51077  ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
 51078  ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
 51079  ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
 51080  ** synchronous=FULL versus synchronous=NORMAL setting determines when
 51081  ** the xSync primitive is called and is relevant to all platforms.
 51082  **
 51083  ** Numeric values associated with these states are OFF==1, NORMAL=2,
 51084  ** and FULL=3.
 51085  */
 51086  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
 51087  SQLITE_PRIVATE void sqlite3PagerSetFlags(
 51088    Pager *pPager,        /* The pager to set safety level for */
 51089    unsigned pgFlags      /* Various flags */
 51090  ){
 51091    unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
 51092    if( pPager->tempFile ){
 51093      pPager->noSync = 1;
 51094      pPager->fullSync = 0;
 51095      pPager->extraSync = 0;
 51096    }else{
 51097      pPager->noSync =  level==PAGER_SYNCHRONOUS_OFF ?1:0;
 51098      pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
 51099      pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
 51100    }
 51101    if( pPager->noSync ){
 51102      pPager->syncFlags = 0;
 51103    }else if( pgFlags & PAGER_FULLFSYNC ){
 51104      pPager->syncFlags = SQLITE_SYNC_FULL;
 51105    }else{
 51106      pPager->syncFlags = SQLITE_SYNC_NORMAL;
 51107    }
 51108    pPager->walSyncFlags = (pPager->syncFlags<<2);
 51109    if( pPager->fullSync ){
 51110      pPager->walSyncFlags |= pPager->syncFlags;
 51111    }
 51112    if( (pgFlags & PAGER_CKPT_FULLFSYNC) && !pPager->noSync ){
 51113      pPager->walSyncFlags |= (SQLITE_SYNC_FULL<<2);
 51114    }
 51115    if( pgFlags & PAGER_CACHESPILL ){
 51116      pPager->doNotSpill &= ~SPILLFLAG_OFF;
 51117    }else{
 51118      pPager->doNotSpill |= SPILLFLAG_OFF;
 51119    }
 51120  }
 51121  #endif
 51122  
 51123  /*
 51124  ** The following global variable is incremented whenever the library
 51125  ** attempts to open a temporary file.  This information is used for
 51126  ** testing and analysis only.  
 51127  */
 51128  #ifdef SQLITE_TEST
 51129  SQLITE_API int sqlite3_opentemp_count = 0;
 51130  #endif
 51131  
 51132  /*
 51133  ** Open a temporary file.
 51134  **
 51135  ** Write the file descriptor into *pFile. Return SQLITE_OK on success 
 51136  ** or some other error code if we fail. The OS will automatically 
 51137  ** delete the temporary file when it is closed.
 51138  **
 51139  ** The flags passed to the VFS layer xOpen() call are those specified
 51140  ** by parameter vfsFlags ORed with the following:
 51141  **
 51142  **     SQLITE_OPEN_READWRITE
 51143  **     SQLITE_OPEN_CREATE
 51144  **     SQLITE_OPEN_EXCLUSIVE
 51145  **     SQLITE_OPEN_DELETEONCLOSE
 51146  */
 51147  static int pagerOpentemp(
 51148    Pager *pPager,        /* The pager object */
 51149    sqlite3_file *pFile,  /* Write the file descriptor here */
 51150    int vfsFlags          /* Flags passed through to the VFS */
 51151  ){
 51152    int rc;               /* Return code */
 51153  
 51154  #ifdef SQLITE_TEST
 51155    sqlite3_opentemp_count++;  /* Used for testing and analysis only */
 51156  #endif
 51157  
 51158    vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
 51159              SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
 51160    rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
 51161    assert( rc!=SQLITE_OK || isOpen(pFile) );
 51162    return rc;
 51163  }
 51164  
 51165  /*
 51166  ** Set the busy handler function.
 51167  **
 51168  ** The pager invokes the busy-handler if sqlite3OsLock() returns 
 51169  ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
 51170  ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
 51171  ** lock. It does *not* invoke the busy handler when upgrading from
 51172  ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
 51173  ** (which occurs during hot-journal rollback). Summary:
 51174  **
 51175  **   Transition                        | Invokes xBusyHandler
 51176  **   --------------------------------------------------------
 51177  **   NO_LOCK       -> SHARED_LOCK      | Yes
 51178  **   SHARED_LOCK   -> RESERVED_LOCK    | No
 51179  **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
 51180  **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
 51181  **
 51182  ** If the busy-handler callback returns non-zero, the lock is 
 51183  ** retried. If it returns zero, then the SQLITE_BUSY error is
 51184  ** returned to the caller of the pager API function.
 51185  */
 51186  SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
 51187    Pager *pPager,                       /* Pager object */
 51188    int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
 51189    void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
 51190  ){
 51191    pPager->xBusyHandler = xBusyHandler;
 51192    pPager->pBusyHandlerArg = pBusyHandlerArg;
 51193  
 51194    if( isOpen(pPager->fd) ){
 51195      void **ap = (void **)&pPager->xBusyHandler;
 51196      assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
 51197      assert( ap[1]==pBusyHandlerArg );
 51198      sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
 51199    }
 51200  }
 51201  
 51202  /*
 51203  ** Change the page size used by the Pager object. The new page size 
 51204  ** is passed in *pPageSize.
 51205  **
 51206  ** If the pager is in the error state when this function is called, it
 51207  ** is a no-op. The value returned is the error state error code (i.e. 
 51208  ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
 51209  **
 51210  ** Otherwise, if all of the following are true:
 51211  **
 51212  **   * the new page size (value of *pPageSize) is valid (a power 
 51213  **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
 51214  **
 51215  **   * there are no outstanding page references, and
 51216  **
 51217  **   * the database is either not an in-memory database or it is
 51218  **     an in-memory database that currently consists of zero pages.
 51219  **
 51220  ** then the pager object page size is set to *pPageSize.
 51221  **
 51222  ** If the page size is changed, then this function uses sqlite3PagerMalloc() 
 51223  ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
 51224  ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
 51225  ** In all other cases, SQLITE_OK is returned.
 51226  **
 51227  ** If the page size is not changed, either because one of the enumerated
 51228  ** conditions above is not true, the pager was in error state when this
 51229  ** function was called, or because the memory allocation attempt failed, 
 51230  ** then *pPageSize is set to the old, retained page size before returning.
 51231  */
 51232  SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
 51233    int rc = SQLITE_OK;
 51234  
 51235    /* It is not possible to do a full assert_pager_state() here, as this
 51236    ** function may be called from within PagerOpen(), before the state
 51237    ** of the Pager object is internally consistent.
 51238    **
 51239    ** At one point this function returned an error if the pager was in 
 51240    ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
 51241    ** there is at least one outstanding page reference, this function
 51242    ** is a no-op for that case anyhow.
 51243    */
 51244  
 51245    u32 pageSize = *pPageSize;
 51246    assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
 51247    if( (pPager->memDb==0 || pPager->dbSize==0)
 51248     && sqlite3PcacheRefCount(pPager->pPCache)==0 
 51249     && pageSize && pageSize!=(u32)pPager->pageSize 
 51250    ){
 51251      char *pNew = NULL;             /* New temp space */
 51252      i64 nByte = 0;
 51253  
 51254      if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
 51255        rc = sqlite3OsFileSize(pPager->fd, &nByte);
 51256      }
 51257      if( rc==SQLITE_OK ){
 51258        pNew = (char *)sqlite3PageMalloc(pageSize);
 51259        if( !pNew ) rc = SQLITE_NOMEM_BKPT;
 51260      }
 51261  
 51262      if( rc==SQLITE_OK ){
 51263        pager_reset(pPager);
 51264        rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
 51265      }
 51266      if( rc==SQLITE_OK ){
 51267        sqlite3PageFree(pPager->pTmpSpace);
 51268        pPager->pTmpSpace = pNew;
 51269        pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
 51270        pPager->pageSize = pageSize;
 51271      }else{
 51272        sqlite3PageFree(pNew);
 51273      }
 51274    }
 51275  
 51276    *pPageSize = pPager->pageSize;
 51277    if( rc==SQLITE_OK ){
 51278      if( nReserve<0 ) nReserve = pPager->nReserve;
 51279      assert( nReserve>=0 && nReserve<1000 );
 51280      pPager->nReserve = (i16)nReserve;
 51281      pagerReportSize(pPager);
 51282      pagerFixMaplimit(pPager);
 51283    }
 51284    return rc;
 51285  }
 51286  
 51287  /*
 51288  ** Return a pointer to the "temporary page" buffer held internally
 51289  ** by the pager.  This is a buffer that is big enough to hold the
 51290  ** entire content of a database page.  This buffer is used internally
 51291  ** during rollback and will be overwritten whenever a rollback
 51292  ** occurs.  But other modules are free to use it too, as long as
 51293  ** no rollbacks are happening.
 51294  */
 51295  SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
 51296    return pPager->pTmpSpace;
 51297  }
 51298  
 51299  /*
 51300  ** Attempt to set the maximum database page count if mxPage is positive. 
 51301  ** Make no changes if mxPage is zero or negative.  And never reduce the
 51302  ** maximum page count below the current size of the database.
 51303  **
 51304  ** Regardless of mxPage, return the current maximum page count.
 51305  */
 51306  SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
 51307    if( mxPage>0 ){
 51308      pPager->mxPgno = mxPage;
 51309    }
 51310    assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
 51311    assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
 51312    return pPager->mxPgno;
 51313  }
 51314  
 51315  /*
 51316  ** The following set of routines are used to disable the simulated
 51317  ** I/O error mechanism.  These routines are used to avoid simulated
 51318  ** errors in places where we do not care about errors.
 51319  **
 51320  ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
 51321  ** and generate no code.
 51322  */
 51323  #ifdef SQLITE_TEST
 51324  SQLITE_API extern int sqlite3_io_error_pending;
 51325  SQLITE_API extern int sqlite3_io_error_hit;
 51326  static int saved_cnt;
 51327  void disable_simulated_io_errors(void){
 51328    saved_cnt = sqlite3_io_error_pending;
 51329    sqlite3_io_error_pending = -1;
 51330  }
 51331  void enable_simulated_io_errors(void){
 51332    sqlite3_io_error_pending = saved_cnt;
 51333  }
 51334  #else
 51335  # define disable_simulated_io_errors()
 51336  # define enable_simulated_io_errors()
 51337  #endif
 51338  
 51339  /*
 51340  ** Read the first N bytes from the beginning of the file into memory
 51341  ** that pDest points to. 
 51342  **
 51343  ** If the pager was opened on a transient file (zFilename==""), or
 51344  ** opened on a file less than N bytes in size, the output buffer is
 51345  ** zeroed and SQLITE_OK returned. The rationale for this is that this 
 51346  ** function is used to read database headers, and a new transient or
 51347  ** zero sized database has a header than consists entirely of zeroes.
 51348  **
 51349  ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
 51350  ** the error code is returned to the caller and the contents of the
 51351  ** output buffer undefined.
 51352  */
 51353  SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
 51354    int rc = SQLITE_OK;
 51355    memset(pDest, 0, N);
 51356    assert( isOpen(pPager->fd) || pPager->tempFile );
 51357  
 51358    /* This routine is only called by btree immediately after creating
 51359    ** the Pager object.  There has not been an opportunity to transition
 51360    ** to WAL mode yet.
 51361    */
 51362    assert( !pagerUseWal(pPager) );
 51363  
 51364    if( isOpen(pPager->fd) ){
 51365      IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
 51366      rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
 51367      if( rc==SQLITE_IOERR_SHORT_READ ){
 51368        rc = SQLITE_OK;
 51369      }
 51370    }
 51371    return rc;
 51372  }
 51373  
 51374  /*
 51375  ** This function may only be called when a read-transaction is open on
 51376  ** the pager. It returns the total number of pages in the database.
 51377  **
 51378  ** However, if the file is between 1 and <page-size> bytes in size, then 
 51379  ** this is considered a 1 page file.
 51380  */
 51381  SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
 51382    assert( pPager->eState>=PAGER_READER );
 51383    assert( pPager->eState!=PAGER_WRITER_FINISHED );
 51384    *pnPage = (int)pPager->dbSize;
 51385  }
 51386  
 51387  
 51388  /*
 51389  ** Try to obtain a lock of type locktype on the database file. If
 51390  ** a similar or greater lock is already held, this function is a no-op
 51391  ** (returning SQLITE_OK immediately).
 51392  **
 51393  ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
 51394  ** the busy callback if the lock is currently not available. Repeat 
 51395  ** until the busy callback returns false or until the attempt to 
 51396  ** obtain the lock succeeds.
 51397  **
 51398  ** Return SQLITE_OK on success and an error code if we cannot obtain
 51399  ** the lock. If the lock is obtained successfully, set the Pager.state 
 51400  ** variable to locktype before returning.
 51401  */
 51402  static int pager_wait_on_lock(Pager *pPager, int locktype){
 51403    int rc;                              /* Return code */
 51404  
 51405    /* Check that this is either a no-op (because the requested lock is 
 51406    ** already held), or one of the transitions that the busy-handler
 51407    ** may be invoked during, according to the comment above
 51408    ** sqlite3PagerSetBusyhandler().
 51409    */
 51410    assert( (pPager->eLock>=locktype)
 51411         || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
 51412         || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
 51413    );
 51414  
 51415    do {
 51416      rc = pagerLockDb(pPager, locktype);
 51417    }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
 51418    return rc;
 51419  }
 51420  
 51421  /*
 51422  ** Function assertTruncateConstraint(pPager) checks that one of the 
 51423  ** following is true for all dirty pages currently in the page-cache:
 51424  **
 51425  **   a) The page number is less than or equal to the size of the 
 51426  **      current database image, in pages, OR
 51427  **
 51428  **   b) if the page content were written at this time, it would not
 51429  **      be necessary to write the current content out to the sub-journal
 51430  **      (as determined by function subjRequiresPage()).
 51431  **
 51432  ** If the condition asserted by this function were not true, and the
 51433  ** dirty page were to be discarded from the cache via the pagerStress()
 51434  ** routine, pagerStress() would not write the current page content to
 51435  ** the database file. If a savepoint transaction were rolled back after
 51436  ** this happened, the correct behavior would be to restore the current
 51437  ** content of the page. However, since this content is not present in either
 51438  ** the database file or the portion of the rollback journal and 
 51439  ** sub-journal rolled back the content could not be restored and the
 51440  ** database image would become corrupt. It is therefore fortunate that 
 51441  ** this circumstance cannot arise.
 51442  */
 51443  #if defined(SQLITE_DEBUG)
 51444  static void assertTruncateConstraintCb(PgHdr *pPg){
 51445    assert( pPg->flags&PGHDR_DIRTY );
 51446    assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
 51447  }
 51448  static void assertTruncateConstraint(Pager *pPager){
 51449    sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
 51450  }
 51451  #else
 51452  # define assertTruncateConstraint(pPager)
 51453  #endif
 51454  
 51455  /*
 51456  ** Truncate the in-memory database file image to nPage pages. This 
 51457  ** function does not actually modify the database file on disk. It 
 51458  ** just sets the internal state of the pager object so that the 
 51459  ** truncation will be done when the current transaction is committed.
 51460  **
 51461  ** This function is only called right before committing a transaction.
 51462  ** Once this function has been called, the transaction must either be
 51463  ** rolled back or committed. It is not safe to call this function and
 51464  ** then continue writing to the database.
 51465  */
 51466  SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
 51467    assert( pPager->dbSize>=nPage );
 51468    assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
 51469    pPager->dbSize = nPage;
 51470  
 51471    /* At one point the code here called assertTruncateConstraint() to
 51472    ** ensure that all pages being truncated away by this operation are,
 51473    ** if one or more savepoints are open, present in the savepoint 
 51474    ** journal so that they can be restored if the savepoint is rolled
 51475    ** back. This is no longer necessary as this function is now only
 51476    ** called right before committing a transaction. So although the 
 51477    ** Pager object may still have open savepoints (Pager.nSavepoint!=0), 
 51478    ** they cannot be rolled back. So the assertTruncateConstraint() call
 51479    ** is no longer correct. */
 51480  }
 51481  
 51482  
 51483  /*
 51484  ** This function is called before attempting a hot-journal rollback. It
 51485  ** syncs the journal file to disk, then sets pPager->journalHdr to the
 51486  ** size of the journal file so that the pager_playback() routine knows
 51487  ** that the entire journal file has been synced.
 51488  **
 51489  ** Syncing a hot-journal to disk before attempting to roll it back ensures 
 51490  ** that if a power-failure occurs during the rollback, the process that
 51491  ** attempts rollback following system recovery sees the same journal
 51492  ** content as this process.
 51493  **
 51494  ** If everything goes as planned, SQLITE_OK is returned. Otherwise, 
 51495  ** an SQLite error code.
 51496  */
 51497  static int pagerSyncHotJournal(Pager *pPager){
 51498    int rc = SQLITE_OK;
 51499    if( !pPager->noSync ){
 51500      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
 51501    }
 51502    if( rc==SQLITE_OK ){
 51503      rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
 51504    }
 51505    return rc;
 51506  }
 51507  
 51508  #if SQLITE_MAX_MMAP_SIZE>0
 51509  /*
 51510  ** Obtain a reference to a memory mapped page object for page number pgno. 
 51511  ** The new object will use the pointer pData, obtained from xFetch().
 51512  ** If successful, set *ppPage to point to the new page reference
 51513  ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
 51514  ** *ppPage to zero.
 51515  **
 51516  ** Page references obtained by calling this function should be released
 51517  ** by calling pagerReleaseMapPage().
 51518  */
 51519  static int pagerAcquireMapPage(
 51520    Pager *pPager,                  /* Pager object */
 51521    Pgno pgno,                      /* Page number */
 51522    void *pData,                    /* xFetch()'d data for this page */
 51523    PgHdr **ppPage                  /* OUT: Acquired page object */
 51524  ){
 51525    PgHdr *p;                       /* Memory mapped page to return */
 51526    
 51527    if( pPager->pMmapFreelist ){
 51528      *ppPage = p = pPager->pMmapFreelist;
 51529      pPager->pMmapFreelist = p->pDirty;
 51530      p->pDirty = 0;
 51531      assert( pPager->nExtra>=8 );
 51532      memset(p->pExtra, 0, 8);
 51533    }else{
 51534      *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
 51535      if( p==0 ){
 51536        sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
 51537        return SQLITE_NOMEM_BKPT;
 51538      }
 51539      p->pExtra = (void *)&p[1];
 51540      p->flags = PGHDR_MMAP;
 51541      p->nRef = 1;
 51542      p->pPager = pPager;
 51543    }
 51544  
 51545    assert( p->pExtra==(void *)&p[1] );
 51546    assert( p->pPage==0 );
 51547    assert( p->flags==PGHDR_MMAP );
 51548    assert( p->pPager==pPager );
 51549    assert( p->nRef==1 );
 51550  
 51551    p->pgno = pgno;
 51552    p->pData = pData;
 51553    pPager->nMmapOut++;
 51554  
 51555    return SQLITE_OK;
 51556  }
 51557  #endif
 51558  
 51559  /*
 51560  ** Release a reference to page pPg. pPg must have been returned by an 
 51561  ** earlier call to pagerAcquireMapPage().
 51562  */
 51563  static void pagerReleaseMapPage(PgHdr *pPg){
 51564    Pager *pPager = pPg->pPager;
 51565    pPager->nMmapOut--;
 51566    pPg->pDirty = pPager->pMmapFreelist;
 51567    pPager->pMmapFreelist = pPg;
 51568  
 51569    assert( pPager->fd->pMethods->iVersion>=3 );
 51570    sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
 51571  }
 51572  
 51573  /*
 51574  ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
 51575  */
 51576  static void pagerFreeMapHdrs(Pager *pPager){
 51577    PgHdr *p;
 51578    PgHdr *pNext;
 51579    for(p=pPager->pMmapFreelist; p; p=pNext){
 51580      pNext = p->pDirty;
 51581      sqlite3_free(p);
 51582    }
 51583  }
 51584  
 51585  
 51586  /*
 51587  ** Shutdown the page cache.  Free all memory and close all files.
 51588  **
 51589  ** If a transaction was in progress when this routine is called, that
 51590  ** transaction is rolled back.  All outstanding pages are invalidated
 51591  ** and their memory is freed.  Any attempt to use a page associated
 51592  ** with this page cache after this function returns will likely
 51593  ** result in a coredump.
 51594  **
 51595  ** This function always succeeds. If a transaction is active an attempt
 51596  ** is made to roll it back. If an error occurs during the rollback 
 51597  ** a hot journal may be left in the filesystem but no error is returned
 51598  ** to the caller.
 51599  */
 51600  SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){
 51601    u8 *pTmp = (u8 *)pPager->pTmpSpace;
 51602  
 51603    assert( db || pagerUseWal(pPager)==0 );
 51604    assert( assert_pager_state(pPager) );
 51605    disable_simulated_io_errors();
 51606    sqlite3BeginBenignMalloc();
 51607    pagerFreeMapHdrs(pPager);
 51608    /* pPager->errCode = 0; */
 51609    pPager->exclusiveMode = 0;
 51610  #ifndef SQLITE_OMIT_WAL
 51611    assert( db || pPager->pWal==0 );
 51612    sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize,
 51613        (db && (db->flags & SQLITE_NoCkptOnClose) ? 0 : pTmp)
 51614    );
 51615    pPager->pWal = 0;
 51616  #endif
 51617    pager_reset(pPager);
 51618    if( MEMDB ){
 51619      pager_unlock(pPager);
 51620    }else{
 51621      /* If it is open, sync the journal file before calling UnlockAndRollback.
 51622      ** If this is not done, then an unsynced portion of the open journal 
 51623      ** file may be played back into the database. If a power failure occurs 
 51624      ** while this is happening, the database could become corrupt.
 51625      **
 51626      ** If an error occurs while trying to sync the journal, shift the pager
 51627      ** into the ERROR state. This causes UnlockAndRollback to unlock the
 51628      ** database and close the journal file without attempting to roll it
 51629      ** back or finalize it. The next database user will have to do hot-journal
 51630      ** rollback before accessing the database file.
 51631      */
 51632      if( isOpen(pPager->jfd) ){
 51633        pager_error(pPager, pagerSyncHotJournal(pPager));
 51634      }
 51635      pagerUnlockAndRollback(pPager);
 51636    }
 51637    sqlite3EndBenignMalloc();
 51638    enable_simulated_io_errors();
 51639    PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
 51640    IOTRACE(("CLOSE %p\n", pPager))
 51641    sqlite3OsClose(pPager->jfd);
 51642    sqlite3OsClose(pPager->fd);
 51643    sqlite3PageFree(pTmp);
 51644    sqlite3PcacheClose(pPager->pPCache);
 51645  
 51646  #ifdef SQLITE_HAS_CODEC
 51647    if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
 51648  #endif
 51649  
 51650    assert( !pPager->aSavepoint && !pPager->pInJournal );
 51651    assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
 51652  
 51653    sqlite3_free(pPager);
 51654    return SQLITE_OK;
 51655  }
 51656  
 51657  #if !defined(NDEBUG) || defined(SQLITE_TEST)
 51658  /*
 51659  ** Return the page number for page pPg.
 51660  */
 51661  SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
 51662    return pPg->pgno;
 51663  }
 51664  #endif
 51665  
 51666  /*
 51667  ** Increment the reference count for page pPg.
 51668  */
 51669  SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
 51670    sqlite3PcacheRef(pPg);
 51671  }
 51672  
 51673  /*
 51674  ** Sync the journal. In other words, make sure all the pages that have
 51675  ** been written to the journal have actually reached the surface of the
 51676  ** disk and can be restored in the event of a hot-journal rollback.
 51677  **
 51678  ** If the Pager.noSync flag is set, then this function is a no-op.
 51679  ** Otherwise, the actions required depend on the journal-mode and the 
 51680  ** device characteristics of the file-system, as follows:
 51681  **
 51682  **   * If the journal file is an in-memory journal file, no action need
 51683  **     be taken.
 51684  **
 51685  **   * Otherwise, if the device does not support the SAFE_APPEND property,
 51686  **     then the nRec field of the most recently written journal header
 51687  **     is updated to contain the number of journal records that have
 51688  **     been written following it. If the pager is operating in full-sync
 51689  **     mode, then the journal file is synced before this field is updated.
 51690  **
 51691  **   * If the device does not support the SEQUENTIAL property, then 
 51692  **     journal file is synced.
 51693  **
 51694  ** Or, in pseudo-code:
 51695  **
 51696  **   if( NOT <in-memory journal> ){
 51697  **     if( NOT SAFE_APPEND ){
 51698  **       if( <full-sync mode> ) xSync(<journal file>);
 51699  **       <update nRec field>
 51700  **     } 
 51701  **     if( NOT SEQUENTIAL ) xSync(<journal file>);
 51702  **   }
 51703  **
 51704  ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
 51705  ** page currently held in memory before returning SQLITE_OK. If an IO
 51706  ** error is encountered, then the IO error code is returned to the caller.
 51707  */
 51708  static int syncJournal(Pager *pPager, int newHdr){
 51709    int rc;                         /* Return code */
 51710  
 51711    assert( pPager->eState==PAGER_WRITER_CACHEMOD
 51712         || pPager->eState==PAGER_WRITER_DBMOD
 51713    );
 51714    assert( assert_pager_state(pPager) );
 51715    assert( !pagerUseWal(pPager) );
 51716  
 51717    rc = sqlite3PagerExclusiveLock(pPager);
 51718    if( rc!=SQLITE_OK ) return rc;
 51719  
 51720    if( !pPager->noSync ){
 51721      assert( !pPager->tempFile );
 51722      if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
 51723        const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
 51724        assert( isOpen(pPager->jfd) );
 51725  
 51726        if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
 51727          /* This block deals with an obscure problem. If the last connection
 51728          ** that wrote to this database was operating in persistent-journal
 51729          ** mode, then the journal file may at this point actually be larger
 51730          ** than Pager.journalOff bytes. If the next thing in the journal
 51731          ** file happens to be a journal-header (written as part of the
 51732          ** previous connection's transaction), and a crash or power-failure 
 51733          ** occurs after nRec is updated but before this connection writes 
 51734          ** anything else to the journal file (or commits/rolls back its 
 51735          ** transaction), then SQLite may become confused when doing the 
 51736          ** hot-journal rollback following recovery. It may roll back all
 51737          ** of this connections data, then proceed to rolling back the old,
 51738          ** out-of-date data that follows it. Database corruption.
 51739          **
 51740          ** To work around this, if the journal file does appear to contain
 51741          ** a valid header following Pager.journalOff, then write a 0x00
 51742          ** byte to the start of it to prevent it from being recognized.
 51743          **
 51744          ** Variable iNextHdrOffset is set to the offset at which this
 51745          ** problematic header will occur, if it exists. aMagic is used 
 51746          ** as a temporary buffer to inspect the first couple of bytes of
 51747          ** the potential journal header.
 51748          */
 51749          i64 iNextHdrOffset;
 51750          u8 aMagic[8];
 51751          u8 zHeader[sizeof(aJournalMagic)+4];
 51752  
 51753          memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
 51754          put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
 51755  
 51756          iNextHdrOffset = journalHdrOffset(pPager);
 51757          rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
 51758          if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
 51759            static const u8 zerobyte = 0;
 51760            rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
 51761          }
 51762          if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
 51763            return rc;
 51764          }
 51765  
 51766          /* Write the nRec value into the journal file header. If in
 51767          ** full-synchronous mode, sync the journal first. This ensures that
 51768          ** all data has really hit the disk before nRec is updated to mark
 51769          ** it as a candidate for rollback.
 51770          **
 51771          ** This is not required if the persistent media supports the
 51772          ** SAFE_APPEND property. Because in this case it is not possible 
 51773          ** for garbage data to be appended to the file, the nRec field
 51774          ** is populated with 0xFFFFFFFF when the journal header is written
 51775          ** and never needs to be updated.
 51776          */
 51777          if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
 51778            PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
 51779            IOTRACE(("JSYNC %p\n", pPager))
 51780            rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
 51781            if( rc!=SQLITE_OK ) return rc;
 51782          }
 51783          IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
 51784          rc = sqlite3OsWrite(
 51785              pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
 51786          );
 51787          if( rc!=SQLITE_OK ) return rc;
 51788        }
 51789        if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
 51790          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
 51791          IOTRACE(("JSYNC %p\n", pPager))
 51792          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| 
 51793            (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
 51794          );
 51795          if( rc!=SQLITE_OK ) return rc;
 51796        }
 51797  
 51798        pPager->journalHdr = pPager->journalOff;
 51799        if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
 51800          pPager->nRec = 0;
 51801          rc = writeJournalHdr(pPager);
 51802          if( rc!=SQLITE_OK ) return rc;
 51803        }
 51804      }else{
 51805        pPager->journalHdr = pPager->journalOff;
 51806      }
 51807    }
 51808  
 51809    /* Unless the pager is in noSync mode, the journal file was just 
 51810    ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on 
 51811    ** all pages.
 51812    */
 51813    sqlite3PcacheClearSyncFlags(pPager->pPCache);
 51814    pPager->eState = PAGER_WRITER_DBMOD;
 51815    assert( assert_pager_state(pPager) );
 51816    return SQLITE_OK;
 51817  }
 51818  
 51819  /*
 51820  ** The argument is the first in a linked list of dirty pages connected
 51821  ** by the PgHdr.pDirty pointer. This function writes each one of the
 51822  ** in-memory pages in the list to the database file. The argument may
 51823  ** be NULL, representing an empty list. In this case this function is
 51824  ** a no-op.
 51825  **
 51826  ** The pager must hold at least a RESERVED lock when this function
 51827  ** is called. Before writing anything to the database file, this lock
 51828  ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
 51829  ** SQLITE_BUSY is returned and no data is written to the database file.
 51830  ** 
 51831  ** If the pager is a temp-file pager and the actual file-system file
 51832  ** is not yet open, it is created and opened before any data is 
 51833  ** written out.
 51834  **
 51835  ** Once the lock has been upgraded and, if necessary, the file opened,
 51836  ** the pages are written out to the database file in list order. Writing
 51837  ** a page is skipped if it meets either of the following criteria:
 51838  **
 51839  **   * The page number is greater than Pager.dbSize, or
 51840  **   * The PGHDR_DONT_WRITE flag is set on the page.
 51841  **
 51842  ** If writing out a page causes the database file to grow, Pager.dbFileSize
 51843  ** is updated accordingly. If page 1 is written out, then the value cached
 51844  ** in Pager.dbFileVers[] is updated to match the new value stored in
 51845  ** the database file.
 51846  **
 51847  ** If everything is successful, SQLITE_OK is returned. If an IO error 
 51848  ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
 51849  ** be obtained, SQLITE_BUSY is returned.
 51850  */
 51851  static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
 51852    int rc = SQLITE_OK;                  /* Return code */
 51853  
 51854    /* This function is only called for rollback pagers in WRITER_DBMOD state. */
 51855    assert( !pagerUseWal(pPager) );
 51856    assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
 51857    assert( pPager->eLock==EXCLUSIVE_LOCK );
 51858    assert( isOpen(pPager->fd) || pList->pDirty==0 );
 51859  
 51860    /* If the file is a temp-file has not yet been opened, open it now. It
 51861    ** is not possible for rc to be other than SQLITE_OK if this branch
 51862    ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
 51863    */
 51864    if( !isOpen(pPager->fd) ){
 51865      assert( pPager->tempFile && rc==SQLITE_OK );
 51866      rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
 51867    }
 51868  
 51869    /* Before the first write, give the VFS a hint of what the final
 51870    ** file size will be.
 51871    */
 51872    assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
 51873    if( rc==SQLITE_OK 
 51874     && pPager->dbHintSize<pPager->dbSize
 51875     && (pList->pDirty || pList->pgno>pPager->dbHintSize)
 51876    ){
 51877      sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
 51878      sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
 51879      pPager->dbHintSize = pPager->dbSize;
 51880    }
 51881  
 51882    while( rc==SQLITE_OK && pList ){
 51883      Pgno pgno = pList->pgno;
 51884  
 51885      /* If there are dirty pages in the page cache with page numbers greater
 51886      ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
 51887      ** make the file smaller (presumably by auto-vacuum code). Do not write
 51888      ** any such pages to the file.
 51889      **
 51890      ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
 51891      ** set (set by sqlite3PagerDontWrite()).
 51892      */
 51893      if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
 51894        i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
 51895        char *pData;                                   /* Data to write */    
 51896  
 51897        assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
 51898        if( pList->pgno==1 ) pager_write_changecounter(pList);
 51899  
 51900        /* Encode the database */
 51901        CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
 51902  
 51903        /* Write out the page data. */
 51904        rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
 51905  
 51906        /* If page 1 was just written, update Pager.dbFileVers to match
 51907        ** the value now stored in the database file. If writing this 
 51908        ** page caused the database file to grow, update dbFileSize. 
 51909        */
 51910        if( pgno==1 ){
 51911          memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
 51912        }
 51913        if( pgno>pPager->dbFileSize ){
 51914          pPager->dbFileSize = pgno;
 51915        }
 51916        pPager->aStat[PAGER_STAT_WRITE]++;
 51917  
 51918        /* Update any backup objects copying the contents of this pager. */
 51919        sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
 51920  
 51921        PAGERTRACE(("STORE %d page %d hash(%08x)\n",
 51922                     PAGERID(pPager), pgno, pager_pagehash(pList)));
 51923        IOTRACE(("PGOUT %p %d\n", pPager, pgno));
 51924        PAGER_INCR(sqlite3_pager_writedb_count);
 51925      }else{
 51926        PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
 51927      }
 51928      pager_set_pagehash(pList);
 51929      pList = pList->pDirty;
 51930    }
 51931  
 51932    return rc;
 51933  }
 51934  
 51935  /*
 51936  ** Ensure that the sub-journal file is open. If it is already open, this 
 51937  ** function is a no-op.
 51938  **
 51939  ** SQLITE_OK is returned if everything goes according to plan. An 
 51940  ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() 
 51941  ** fails.
 51942  */
 51943  static int openSubJournal(Pager *pPager){
 51944    int rc = SQLITE_OK;
 51945    if( !isOpen(pPager->sjfd) ){
 51946      const int flags =  SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE 
 51947        | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE 
 51948        | SQLITE_OPEN_DELETEONCLOSE;
 51949      int nStmtSpill = sqlite3Config.nStmtSpill;
 51950      if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
 51951        nStmtSpill = -1;
 51952      }
 51953      rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
 51954    }
 51955    return rc;
 51956  }
 51957  
 51958  /*
 51959  ** Append a record of the current state of page pPg to the sub-journal. 
 51960  **
 51961  ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
 51962  ** for all open savepoints before returning.
 51963  **
 51964  ** This function returns SQLITE_OK if everything is successful, an IO
 51965  ** error code if the attempt to write to the sub-journal fails, or 
 51966  ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
 51967  ** bitvec.
 51968  */
 51969  static int subjournalPage(PgHdr *pPg){
 51970    int rc = SQLITE_OK;
 51971    Pager *pPager = pPg->pPager;
 51972    if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
 51973  
 51974      /* Open the sub-journal, if it has not already been opened */
 51975      assert( pPager->useJournal );
 51976      assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
 51977      assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
 51978      assert( pagerUseWal(pPager) 
 51979           || pageInJournal(pPager, pPg) 
 51980           || pPg->pgno>pPager->dbOrigSize 
 51981      );
 51982      rc = openSubJournal(pPager);
 51983  
 51984      /* If the sub-journal was opened successfully (or was already open),
 51985      ** write the journal record into the file.  */
 51986      if( rc==SQLITE_OK ){
 51987        void *pData = pPg->pData;
 51988        i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
 51989        char *pData2;
 51990  
 51991  #if SQLITE_HAS_CODEC   
 51992        if( !pPager->subjInMemory ){
 51993          CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
 51994        }else
 51995  #endif
 51996        pData2 = pData;
 51997        PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
 51998        rc = write32bits(pPager->sjfd, offset, pPg->pgno);
 51999        if( rc==SQLITE_OK ){
 52000          rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
 52001        }
 52002      }
 52003    }
 52004    if( rc==SQLITE_OK ){
 52005      pPager->nSubRec++;
 52006      assert( pPager->nSavepoint>0 );
 52007      rc = addToSavepointBitvecs(pPager, pPg->pgno);
 52008    }
 52009    return rc;
 52010  }
 52011  static int subjournalPageIfRequired(PgHdr *pPg){
 52012    if( subjRequiresPage(pPg) ){
 52013      return subjournalPage(pPg);
 52014    }else{
 52015      return SQLITE_OK;
 52016    }
 52017  }
 52018  
 52019  /*
 52020  ** This function is called by the pcache layer when it has reached some
 52021  ** soft memory limit. The first argument is a pointer to a Pager object
 52022  ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
 52023  ** database). The second argument is a reference to a page that is 
 52024  ** currently dirty but has no outstanding references. The page
 52025  ** is always associated with the Pager object passed as the first 
 52026  ** argument.
 52027  **
 52028  ** The job of this function is to make pPg clean by writing its contents
 52029  ** out to the database file, if possible. This may involve syncing the
 52030  ** journal file. 
 52031  **
 52032  ** If successful, sqlite3PcacheMakeClean() is called on the page and
 52033  ** SQLITE_OK returned. If an IO error occurs while trying to make the
 52034  ** page clean, the IO error code is returned. If the page cannot be
 52035  ** made clean for some other reason, but no error occurs, then SQLITE_OK
 52036  ** is returned by sqlite3PcacheMakeClean() is not called.
 52037  */
 52038  static int pagerStress(void *p, PgHdr *pPg){
 52039    Pager *pPager = (Pager *)p;
 52040    int rc = SQLITE_OK;
 52041  
 52042    assert( pPg->pPager==pPager );
 52043    assert( pPg->flags&PGHDR_DIRTY );
 52044  
 52045    /* The doNotSpill NOSYNC bit is set during times when doing a sync of
 52046    ** journal (and adding a new header) is not allowed.  This occurs
 52047    ** during calls to sqlite3PagerWrite() while trying to journal multiple
 52048    ** pages belonging to the same sector.
 52049    **
 52050    ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
 52051    ** regardless of whether or not a sync is required.  This is set during
 52052    ** a rollback or by user request, respectively.
 52053    **
 52054    ** Spilling is also prohibited when in an error state since that could
 52055    ** lead to database corruption.   In the current implementation it 
 52056    ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
 52057    ** while in the error state, hence it is impossible for this routine to
 52058    ** be called in the error state.  Nevertheless, we include a NEVER()
 52059    ** test for the error state as a safeguard against future changes.
 52060    */
 52061    if( NEVER(pPager->errCode) ) return SQLITE_OK;
 52062    testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
 52063    testcase( pPager->doNotSpill & SPILLFLAG_OFF );
 52064    testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
 52065    if( pPager->doNotSpill
 52066     && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
 52067        || (pPg->flags & PGHDR_NEED_SYNC)!=0)
 52068    ){
 52069      return SQLITE_OK;
 52070    }
 52071  
 52072    pPg->pDirty = 0;
 52073    if( pagerUseWal(pPager) ){
 52074      /* Write a single frame for this page to the log. */
 52075      rc = subjournalPageIfRequired(pPg); 
 52076      if( rc==SQLITE_OK ){
 52077        rc = pagerWalFrames(pPager, pPg, 0, 0);
 52078      }
 52079    }else{
 52080      
 52081  #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
 52082      if( pPager->tempFile==0 ){
 52083        rc = sqlite3JournalCreate(pPager->jfd);
 52084        if( rc!=SQLITE_OK ) return pager_error(pPager, rc);
 52085      }
 52086  #endif
 52087    
 52088      /* Sync the journal file if required. */
 52089      if( pPg->flags&PGHDR_NEED_SYNC 
 52090       || pPager->eState==PAGER_WRITER_CACHEMOD
 52091      ){
 52092        rc = syncJournal(pPager, 1);
 52093      }
 52094    
 52095      /* Write the contents of the page out to the database file. */
 52096      if( rc==SQLITE_OK ){
 52097        assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
 52098        rc = pager_write_pagelist(pPager, pPg);
 52099      }
 52100    }
 52101  
 52102    /* Mark the page as clean. */
 52103    if( rc==SQLITE_OK ){
 52104      PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
 52105      sqlite3PcacheMakeClean(pPg);
 52106    }
 52107  
 52108    return pager_error(pPager, rc); 
 52109  }
 52110  
 52111  /*
 52112  ** Flush all unreferenced dirty pages to disk.
 52113  */
 52114  SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
 52115    int rc = pPager->errCode;
 52116    if( !MEMDB ){
 52117      PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
 52118      assert( assert_pager_state(pPager) );
 52119      while( rc==SQLITE_OK && pList ){
 52120        PgHdr *pNext = pList->pDirty;
 52121        if( pList->nRef==0 ){
 52122          rc = pagerStress((void*)pPager, pList);
 52123        }
 52124        pList = pNext;
 52125      }
 52126    }
 52127  
 52128    return rc;
 52129  }
 52130  
 52131  /*
 52132  ** Allocate and initialize a new Pager object and put a pointer to it
 52133  ** in *ppPager. The pager should eventually be freed by passing it
 52134  ** to sqlite3PagerClose().
 52135  **
 52136  ** The zFilename argument is the path to the database file to open.
 52137  ** If zFilename is NULL then a randomly-named temporary file is created
 52138  ** and used as the file to be cached. Temporary files are be deleted
 52139  ** automatically when they are closed. If zFilename is ":memory:" then 
 52140  ** all information is held in cache. It is never written to disk. 
 52141  ** This can be used to implement an in-memory database.
 52142  **
 52143  ** The nExtra parameter specifies the number of bytes of space allocated
 52144  ** along with each page reference. This space is available to the user
 52145  ** via the sqlite3PagerGetExtra() API.  When a new page is allocated, the
 52146  ** first 8 bytes of this space are zeroed but the remainder is uninitialized.
 52147  ** (The extra space is used by btree as the MemPage object.)
 52148  **
 52149  ** The flags argument is used to specify properties that affect the
 52150  ** operation of the pager. It should be passed some bitwise combination
 52151  ** of the PAGER_* flags.
 52152  **
 52153  ** The vfsFlags parameter is a bitmask to pass to the flags parameter
 52154  ** of the xOpen() method of the supplied VFS when opening files. 
 52155  **
 52156  ** If the pager object is allocated and the specified file opened 
 52157  ** successfully, SQLITE_OK is returned and *ppPager set to point to
 52158  ** the new pager object. If an error occurs, *ppPager is set to NULL
 52159  ** and error code returned. This function may return SQLITE_NOMEM
 52160  ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
 52161  ** various SQLITE_IO_XXX errors.
 52162  */
 52163  SQLITE_PRIVATE int sqlite3PagerOpen(
 52164    sqlite3_vfs *pVfs,       /* The virtual file system to use */
 52165    Pager **ppPager,         /* OUT: Return the Pager structure here */
 52166    const char *zFilename,   /* Name of the database file to open */
 52167    int nExtra,              /* Extra bytes append to each in-memory page */
 52168    int flags,               /* flags controlling this file */
 52169    int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
 52170    void (*xReinit)(DbPage*) /* Function to reinitialize pages */
 52171  ){
 52172    u8 *pPtr;
 52173    Pager *pPager = 0;       /* Pager object to allocate and return */
 52174    int rc = SQLITE_OK;      /* Return code */
 52175    int tempFile = 0;        /* True for temp files (incl. in-memory files) */
 52176    int memDb = 0;           /* True if this is an in-memory file */
 52177    int readOnly = 0;        /* True if this is a read-only file */
 52178    int journalFileSize;     /* Bytes to allocate for each journal fd */
 52179    char *zPathname = 0;     /* Full path to database file */
 52180    int nPathname = 0;       /* Number of bytes in zPathname */
 52181    int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
 52182    int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
 52183    u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
 52184    const char *zUri = 0;    /* URI args to copy */
 52185    int nUri = 0;            /* Number of bytes of URI args at *zUri */
 52186  
 52187    /* Figure out how much space is required for each journal file-handle
 52188    ** (there are two of them, the main journal and the sub-journal).  */
 52189    journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
 52190  
 52191    /* Set the output variable to NULL in case an error occurs. */
 52192    *ppPager = 0;
 52193  
 52194  #ifndef SQLITE_OMIT_MEMORYDB
 52195    if( flags & PAGER_MEMORY ){
 52196      memDb = 1;
 52197      if( zFilename && zFilename[0] ){
 52198        zPathname = sqlite3DbStrDup(0, zFilename);
 52199        if( zPathname==0  ) return SQLITE_NOMEM_BKPT;
 52200        nPathname = sqlite3Strlen30(zPathname);
 52201        zFilename = 0;
 52202      }
 52203    }
 52204  #endif
 52205  
 52206    /* Compute and store the full pathname in an allocated buffer pointed
 52207    ** to by zPathname, length nPathname. Or, if this is a temporary file,
 52208    ** leave both nPathname and zPathname set to 0.
 52209    */
 52210    if( zFilename && zFilename[0] ){
 52211      const char *z;
 52212      nPathname = pVfs->mxPathname+1;
 52213      zPathname = sqlite3DbMallocRaw(0, nPathname*2);
 52214      if( zPathname==0 ){
 52215        return SQLITE_NOMEM_BKPT;
 52216      }
 52217      zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
 52218      rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
 52219      nPathname = sqlite3Strlen30(zPathname);
 52220      z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
 52221      while( *z ){
 52222        z += sqlite3Strlen30(z)+1;
 52223        z += sqlite3Strlen30(z)+1;
 52224      }
 52225      nUri = (int)(&z[1] - zUri);
 52226      assert( nUri>=0 );
 52227      if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
 52228        /* This branch is taken when the journal path required by
 52229        ** the database being opened will be more than pVfs->mxPathname
 52230        ** bytes in length. This means the database cannot be opened,
 52231        ** as it will not be possible to open the journal file or even
 52232        ** check for a hot-journal before reading.
 52233        */
 52234        rc = SQLITE_CANTOPEN_BKPT;
 52235      }
 52236      if( rc!=SQLITE_OK ){
 52237        sqlite3DbFree(0, zPathname);
 52238        return rc;
 52239      }
 52240    }
 52241  
 52242    /* Allocate memory for the Pager structure, PCache object, the
 52243    ** three file descriptors, the database file name and the journal 
 52244    ** file name. The layout in memory is as follows:
 52245    **
 52246    **     Pager object                    (sizeof(Pager) bytes)
 52247    **     PCache object                   (sqlite3PcacheSize() bytes)
 52248    **     Database file handle            (pVfs->szOsFile bytes)
 52249    **     Sub-journal file handle         (journalFileSize bytes)
 52250    **     Main journal file handle        (journalFileSize bytes)
 52251    **     Database file name              (nPathname+1 bytes)
 52252    **     Journal file name               (nPathname+8+1 bytes)
 52253    */
 52254    pPtr = (u8 *)sqlite3MallocZero(
 52255      ROUND8(sizeof(*pPager)) +      /* Pager structure */
 52256      ROUND8(pcacheSize) +           /* PCache object */
 52257      ROUND8(pVfs->szOsFile) +       /* The main db file */
 52258      journalFileSize * 2 +          /* The two journal files */ 
 52259      nPathname + 1 + nUri +         /* zFilename */
 52260      nPathname + 8 + 2              /* zJournal */
 52261  #ifndef SQLITE_OMIT_WAL
 52262      + nPathname + 4 + 2            /* zWal */
 52263  #endif
 52264    );
 52265    assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
 52266    if( !pPtr ){
 52267      sqlite3DbFree(0, zPathname);
 52268      return SQLITE_NOMEM_BKPT;
 52269    }
 52270    pPager =              (Pager*)(pPtr);
 52271    pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
 52272    pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
 52273    pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
 52274    pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
 52275    pPager->zFilename =    (char*)(pPtr += journalFileSize);
 52276    assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
 52277  
 52278    /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
 52279    if( zPathname ){
 52280      assert( nPathname>0 );
 52281      pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
 52282      memcpy(pPager->zFilename, zPathname, nPathname);
 52283      if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
 52284      memcpy(pPager->zJournal, zPathname, nPathname);
 52285      memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
 52286      sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
 52287  #ifndef SQLITE_OMIT_WAL
 52288      pPager->zWal = &pPager->zJournal[nPathname+8+1];
 52289      memcpy(pPager->zWal, zPathname, nPathname);
 52290      memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
 52291      sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
 52292  #endif
 52293      sqlite3DbFree(0, zPathname);
 52294    }
 52295    pPager->pVfs = pVfs;
 52296    pPager->vfsFlags = vfsFlags;
 52297  
 52298    /* Open the pager file.
 52299    */
 52300    if( zFilename && zFilename[0] ){
 52301      int fout = 0;                    /* VFS flags returned by xOpen() */
 52302      rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
 52303      assert( !memDb );
 52304      readOnly = (fout&SQLITE_OPEN_READONLY);
 52305  
 52306      /* If the file was successfully opened for read/write access,
 52307      ** choose a default page size in case we have to create the
 52308      ** database file. The default page size is the maximum of:
 52309      **
 52310      **    + SQLITE_DEFAULT_PAGE_SIZE,
 52311      **    + The value returned by sqlite3OsSectorSize()
 52312      **    + The largest page size that can be written atomically.
 52313      */
 52314      if( rc==SQLITE_OK ){
 52315        int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
 52316        if( !readOnly ){
 52317          setSectorSize(pPager);
 52318          assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
 52319          if( szPageDflt<pPager->sectorSize ){
 52320            if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
 52321              szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
 52322            }else{
 52323              szPageDflt = (u32)pPager->sectorSize;
 52324            }
 52325          }
 52326  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
 52327          {
 52328            int ii;
 52329            assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
 52330            assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
 52331            assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
 52332            for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
 52333              if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
 52334                szPageDflt = ii;
 52335              }
 52336            }
 52337          }
 52338  #endif
 52339        }
 52340        pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
 52341        if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
 52342         || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
 52343            vfsFlags |= SQLITE_OPEN_READONLY;
 52344            goto act_like_temp_file;
 52345        }
 52346      }
 52347    }else{
 52348      /* If a temporary file is requested, it is not opened immediately.
 52349      ** In this case we accept the default page size and delay actually
 52350      ** opening the file until the first call to OsWrite().
 52351      **
 52352      ** This branch is also run for an in-memory database. An in-memory
 52353      ** database is the same as a temp-file that is never written out to
 52354      ** disk and uses an in-memory rollback journal.
 52355      **
 52356      ** This branch also runs for files marked as immutable.
 52357      */ 
 52358  act_like_temp_file:
 52359      tempFile = 1;
 52360      pPager->eState = PAGER_READER;     /* Pretend we already have a lock */
 52361      pPager->eLock = EXCLUSIVE_LOCK;    /* Pretend we are in EXCLUSIVE mode */
 52362      pPager->noLock = 1;                /* Do no locking */
 52363      readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
 52364    }
 52365  
 52366    /* The following call to PagerSetPagesize() serves to set the value of 
 52367    ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
 52368    */
 52369    if( rc==SQLITE_OK ){
 52370      assert( pPager->memDb==0 );
 52371      rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
 52372      testcase( rc!=SQLITE_OK );
 52373    }
 52374  
 52375    /* Initialize the PCache object. */
 52376    if( rc==SQLITE_OK ){
 52377      nExtra = ROUND8(nExtra);
 52378      assert( nExtra>=8 && nExtra<1000 );
 52379      rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
 52380                         !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
 52381    }
 52382  
 52383    /* If an error occurred above, free the  Pager structure and close the file.
 52384    */
 52385    if( rc!=SQLITE_OK ){
 52386      sqlite3OsClose(pPager->fd);
 52387      sqlite3PageFree(pPager->pTmpSpace);
 52388      sqlite3_free(pPager);
 52389      return rc;
 52390    }
 52391  
 52392    PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
 52393    IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
 52394  
 52395    pPager->useJournal = (u8)useJournal;
 52396    /* pPager->stmtOpen = 0; */
 52397    /* pPager->stmtInUse = 0; */
 52398    /* pPager->nRef = 0; */
 52399    /* pPager->stmtSize = 0; */
 52400    /* pPager->stmtJSize = 0; */
 52401    /* pPager->nPage = 0; */
 52402    pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
 52403    /* pPager->state = PAGER_UNLOCK; */
 52404    /* pPager->errMask = 0; */
 52405    pPager->tempFile = (u8)tempFile;
 52406    assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
 52407            || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
 52408    assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
 52409    pPager->exclusiveMode = (u8)tempFile; 
 52410    pPager->changeCountDone = pPager->tempFile;
 52411    pPager->memDb = (u8)memDb;
 52412    pPager->readOnly = (u8)readOnly;
 52413    assert( useJournal || pPager->tempFile );
 52414    pPager->noSync = pPager->tempFile;
 52415    if( pPager->noSync ){
 52416      assert( pPager->fullSync==0 );
 52417      assert( pPager->extraSync==0 );
 52418      assert( pPager->syncFlags==0 );
 52419      assert( pPager->walSyncFlags==0 );
 52420    }else{
 52421      pPager->fullSync = 1;
 52422      pPager->extraSync = 0;
 52423      pPager->syncFlags = SQLITE_SYNC_NORMAL;
 52424      pPager->walSyncFlags = SQLITE_SYNC_NORMAL | (SQLITE_SYNC_NORMAL<<2);
 52425    }
 52426    /* pPager->pFirst = 0; */
 52427    /* pPager->pFirstSynced = 0; */
 52428    /* pPager->pLast = 0; */
 52429    pPager->nExtra = (u16)nExtra;
 52430    pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
 52431    assert( isOpen(pPager->fd) || tempFile );
 52432    setSectorSize(pPager);
 52433    if( !useJournal ){
 52434      pPager->journalMode = PAGER_JOURNALMODE_OFF;
 52435    }else if( memDb ){
 52436      pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
 52437    }
 52438    /* pPager->xBusyHandler = 0; */
 52439    /* pPager->pBusyHandlerArg = 0; */
 52440    pPager->xReiniter = xReinit;
 52441    setGetterMethod(pPager);
 52442    /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
 52443    /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
 52444  
 52445    *ppPager = pPager;
 52446    return SQLITE_OK;
 52447  }
 52448  
 52449  
 52450  /* Verify that the database file has not be deleted or renamed out from
 52451  ** under the pager.  Return SQLITE_OK if the database is still were it ought
 52452  ** to be on disk.  Return non-zero (SQLITE_READONLY_DBMOVED or some other error
 52453  ** code from sqlite3OsAccess()) if the database has gone missing.
 52454  */
 52455  static int databaseIsUnmoved(Pager *pPager){
 52456    int bHasMoved = 0;
 52457    int rc;
 52458  
 52459    if( pPager->tempFile ) return SQLITE_OK;
 52460    if( pPager->dbSize==0 ) return SQLITE_OK;
 52461    assert( pPager->zFilename && pPager->zFilename[0] );
 52462    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
 52463    if( rc==SQLITE_NOTFOUND ){
 52464      /* If the HAS_MOVED file-control is unimplemented, assume that the file
 52465      ** has not been moved.  That is the historical behavior of SQLite: prior to
 52466      ** version 3.8.3, it never checked */
 52467      rc = SQLITE_OK;
 52468    }else if( rc==SQLITE_OK && bHasMoved ){
 52469      rc = SQLITE_READONLY_DBMOVED;
 52470    }
 52471    return rc;
 52472  }
 52473  
 52474  
 52475  /*
 52476  ** This function is called after transitioning from PAGER_UNLOCK to
 52477  ** PAGER_SHARED state. It tests if there is a hot journal present in
 52478  ** the file-system for the given pager. A hot journal is one that 
 52479  ** needs to be played back. According to this function, a hot-journal
 52480  ** file exists if the following criteria are met:
 52481  **
 52482  **   * The journal file exists in the file system, and
 52483  **   * No process holds a RESERVED or greater lock on the database file, and
 52484  **   * The database file itself is greater than 0 bytes in size, and
 52485  **   * The first byte of the journal file exists and is not 0x00.
 52486  **
 52487  ** If the current size of the database file is 0 but a journal file
 52488  ** exists, that is probably an old journal left over from a prior
 52489  ** database with the same name. In this case the journal file is
 52490  ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
 52491  ** is returned.
 52492  **
 52493  ** This routine does not check if there is a master journal filename
 52494  ** at the end of the file. If there is, and that master journal file
 52495  ** does not exist, then the journal file is not really hot. In this
 52496  ** case this routine will return a false-positive. The pager_playback()
 52497  ** routine will discover that the journal file is not really hot and 
 52498  ** will not roll it back. 
 52499  **
 52500  ** If a hot-journal file is found to exist, *pExists is set to 1 and 
 52501  ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
 52502  ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
 52503  ** to determine whether or not a hot-journal file exists, the IO error
 52504  ** code is returned and the value of *pExists is undefined.
 52505  */
 52506  static int hasHotJournal(Pager *pPager, int *pExists){
 52507    sqlite3_vfs * const pVfs = pPager->pVfs;
 52508    int rc = SQLITE_OK;           /* Return code */
 52509    int exists = 1;               /* True if a journal file is present */
 52510    int jrnlOpen = !!isOpen(pPager->jfd);
 52511  
 52512    assert( pPager->useJournal );
 52513    assert( isOpen(pPager->fd) );
 52514    assert( pPager->eState==PAGER_OPEN );
 52515  
 52516    assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
 52517      SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
 52518    ));
 52519  
 52520    *pExists = 0;
 52521    if( !jrnlOpen ){
 52522      rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
 52523    }
 52524    if( rc==SQLITE_OK && exists ){
 52525      int locked = 0;             /* True if some process holds a RESERVED lock */
 52526  
 52527      /* Race condition here:  Another process might have been holding the
 52528      ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
 52529      ** call above, but then delete the journal and drop the lock before
 52530      ** we get to the following sqlite3OsCheckReservedLock() call.  If that
 52531      ** is the case, this routine might think there is a hot journal when
 52532      ** in fact there is none.  This results in a false-positive which will
 52533      ** be dealt with by the playback routine.  Ticket #3883.
 52534      */
 52535      rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
 52536      if( rc==SQLITE_OK && !locked ){
 52537        Pgno nPage;                 /* Number of pages in database file */
 52538  
 52539        assert( pPager->tempFile==0 );
 52540        rc = pagerPagecount(pPager, &nPage);
 52541        if( rc==SQLITE_OK ){
 52542          /* If the database is zero pages in size, that means that either (1) the
 52543          ** journal is a remnant from a prior database with the same name where
 52544          ** the database file but not the journal was deleted, or (2) the initial
 52545          ** transaction that populates a new database is being rolled back.
 52546          ** In either case, the journal file can be deleted.  However, take care
 52547          ** not to delete the journal file if it is already open due to
 52548          ** journal_mode=PERSIST.
 52549          */
 52550          if( nPage==0 && !jrnlOpen ){
 52551            sqlite3BeginBenignMalloc();
 52552            if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
 52553              sqlite3OsDelete(pVfs, pPager->zJournal, 0);
 52554              if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
 52555            }
 52556            sqlite3EndBenignMalloc();
 52557          }else{
 52558            /* The journal file exists and no other connection has a reserved
 52559            ** or greater lock on the database file. Now check that there is
 52560            ** at least one non-zero bytes at the start of the journal file.
 52561            ** If there is, then we consider this journal to be hot. If not, 
 52562            ** it can be ignored.
 52563            */
 52564            if( !jrnlOpen ){
 52565              int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
 52566              rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
 52567            }
 52568            if( rc==SQLITE_OK ){
 52569              u8 first = 0;
 52570              rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
 52571              if( rc==SQLITE_IOERR_SHORT_READ ){
 52572                rc = SQLITE_OK;
 52573              }
 52574              if( !jrnlOpen ){
 52575                sqlite3OsClose(pPager->jfd);
 52576              }
 52577              *pExists = (first!=0);
 52578            }else if( rc==SQLITE_CANTOPEN ){
 52579              /* If we cannot open the rollback journal file in order to see if
 52580              ** it has a zero header, that might be due to an I/O error, or
 52581              ** it might be due to the race condition described above and in
 52582              ** ticket #3883.  Either way, assume that the journal is hot.
 52583              ** This might be a false positive.  But if it is, then the
 52584              ** automatic journal playback and recovery mechanism will deal
 52585              ** with it under an EXCLUSIVE lock where we do not need to
 52586              ** worry so much with race conditions.
 52587              */
 52588              *pExists = 1;
 52589              rc = SQLITE_OK;
 52590            }
 52591          }
 52592        }
 52593      }
 52594    }
 52595  
 52596    return rc;
 52597  }
 52598  
 52599  /*
 52600  ** This function is called to obtain a shared lock on the database file.
 52601  ** It is illegal to call sqlite3PagerGet() until after this function
 52602  ** has been successfully called. If a shared-lock is already held when
 52603  ** this function is called, it is a no-op.
 52604  **
 52605  ** The following operations are also performed by this function.
 52606  **
 52607  **   1) If the pager is currently in PAGER_OPEN state (no lock held
 52608  **      on the database file), then an attempt is made to obtain a
 52609  **      SHARED lock on the database file. Immediately after obtaining
 52610  **      the SHARED lock, the file-system is checked for a hot-journal,
 52611  **      which is played back if present. Following any hot-journal 
 52612  **      rollback, the contents of the cache are validated by checking
 52613  **      the 'change-counter' field of the database file header and
 52614  **      discarded if they are found to be invalid.
 52615  **
 52616  **   2) If the pager is running in exclusive-mode, and there are currently
 52617  **      no outstanding references to any pages, and is in the error state,
 52618  **      then an attempt is made to clear the error state by discarding
 52619  **      the contents of the page cache and rolling back any open journal
 52620  **      file.
 52621  **
 52622  ** If everything is successful, SQLITE_OK is returned. If an IO error 
 52623  ** occurs while locking the database, checking for a hot-journal file or 
 52624  ** rolling back a journal file, the IO error code is returned.
 52625  */
 52626  SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
 52627    int rc = SQLITE_OK;                /* Return code */
 52628  
 52629    /* This routine is only called from b-tree and only when there are no
 52630    ** outstanding pages. This implies that the pager state should either
 52631    ** be OPEN or READER. READER is only possible if the pager is or was in 
 52632    ** exclusive access mode.  */
 52633    assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
 52634    assert( assert_pager_state(pPager) );
 52635    assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
 52636    assert( pPager->errCode==SQLITE_OK );
 52637  
 52638    if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
 52639      int bHotJournal = 1;          /* True if there exists a hot journal-file */
 52640  
 52641      assert( !MEMDB );
 52642      assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
 52643  
 52644      rc = pager_wait_on_lock(pPager, SHARED_LOCK);
 52645      if( rc!=SQLITE_OK ){
 52646        assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
 52647        goto failed;
 52648      }
 52649  
 52650      /* If a journal file exists, and there is no RESERVED lock on the
 52651      ** database file, then it either needs to be played back or deleted.
 52652      */
 52653      if( pPager->eLock<=SHARED_LOCK ){
 52654        rc = hasHotJournal(pPager, &bHotJournal);
 52655      }
 52656      if( rc!=SQLITE_OK ){
 52657        goto failed;
 52658      }
 52659      if( bHotJournal ){
 52660        if( pPager->readOnly ){
 52661          rc = SQLITE_READONLY_ROLLBACK;
 52662          goto failed;
 52663        }
 52664  
 52665        /* Get an EXCLUSIVE lock on the database file. At this point it is
 52666        ** important that a RESERVED lock is not obtained on the way to the
 52667        ** EXCLUSIVE lock. If it were, another process might open the
 52668        ** database file, detect the RESERVED lock, and conclude that the
 52669        ** database is safe to read while this process is still rolling the 
 52670        ** hot-journal back.
 52671        ** 
 52672        ** Because the intermediate RESERVED lock is not requested, any
 52673        ** other process attempting to access the database file will get to 
 52674        ** this point in the code and fail to obtain its own EXCLUSIVE lock 
 52675        ** on the database file.
 52676        **
 52677        ** Unless the pager is in locking_mode=exclusive mode, the lock is
 52678        ** downgraded to SHARED_LOCK before this function returns.
 52679        */
 52680        rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
 52681        if( rc!=SQLITE_OK ){
 52682          goto failed;
 52683        }
 52684   
 52685        /* If it is not already open and the file exists on disk, open the 
 52686        ** journal for read/write access. Write access is required because 
 52687        ** in exclusive-access mode the file descriptor will be kept open 
 52688        ** and possibly used for a transaction later on. Also, write-access 
 52689        ** is usually required to finalize the journal in journal_mode=persist 
 52690        ** mode (and also for journal_mode=truncate on some systems).
 52691        **
 52692        ** If the journal does not exist, it usually means that some 
 52693        ** other connection managed to get in and roll it back before 
 52694        ** this connection obtained the exclusive lock above. Or, it 
 52695        ** may mean that the pager was in the error-state when this
 52696        ** function was called and the journal file does not exist.
 52697        */
 52698        if( !isOpen(pPager->jfd) ){
 52699          sqlite3_vfs * const pVfs = pPager->pVfs;
 52700          int bExists;              /* True if journal file exists */
 52701          rc = sqlite3OsAccess(
 52702              pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
 52703          if( rc==SQLITE_OK && bExists ){
 52704            int fout = 0;
 52705            int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
 52706            assert( !pPager->tempFile );
 52707            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
 52708            assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
 52709            if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
 52710              rc = SQLITE_CANTOPEN_BKPT;
 52711              sqlite3OsClose(pPager->jfd);
 52712            }
 52713          }
 52714        }
 52715   
 52716        /* Playback and delete the journal.  Drop the database write
 52717        ** lock and reacquire the read lock. Purge the cache before
 52718        ** playing back the hot-journal so that we don't end up with
 52719        ** an inconsistent cache.  Sync the hot journal before playing
 52720        ** it back since the process that crashed and left the hot journal
 52721        ** probably did not sync it and we are required to always sync
 52722        ** the journal before playing it back.
 52723        */
 52724        if( isOpen(pPager->jfd) ){
 52725          assert( rc==SQLITE_OK );
 52726          rc = pagerSyncHotJournal(pPager);
 52727          if( rc==SQLITE_OK ){
 52728            rc = pager_playback(pPager, !pPager->tempFile);
 52729            pPager->eState = PAGER_OPEN;
 52730          }
 52731        }else if( !pPager->exclusiveMode ){
 52732          pagerUnlockDb(pPager, SHARED_LOCK);
 52733        }
 52734  
 52735        if( rc!=SQLITE_OK ){
 52736          /* This branch is taken if an error occurs while trying to open
 52737          ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
 52738          ** pager_unlock() routine will be called before returning to unlock
 52739          ** the file. If the unlock attempt fails, then Pager.eLock must be
 52740          ** set to UNKNOWN_LOCK (see the comment above the #define for 
 52741          ** UNKNOWN_LOCK above for an explanation). 
 52742          **
 52743          ** In order to get pager_unlock() to do this, set Pager.eState to
 52744          ** PAGER_ERROR now. This is not actually counted as a transition
 52745          ** to ERROR state in the state diagram at the top of this file,
 52746          ** since we know that the same call to pager_unlock() will very
 52747          ** shortly transition the pager object to the OPEN state. Calling
 52748          ** assert_pager_state() would fail now, as it should not be possible
 52749          ** to be in ERROR state when there are zero outstanding page 
 52750          ** references.
 52751          */
 52752          pager_error(pPager, rc);
 52753          goto failed;
 52754        }
 52755  
 52756        assert( pPager->eState==PAGER_OPEN );
 52757        assert( (pPager->eLock==SHARED_LOCK)
 52758             || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
 52759        );
 52760      }
 52761  
 52762      if( !pPager->tempFile && pPager->hasHeldSharedLock ){
 52763        /* The shared-lock has just been acquired then check to
 52764        ** see if the database has been modified.  If the database has changed,
 52765        ** flush the cache.  The hasHeldSharedLock flag prevents this from
 52766        ** occurring on the very first access to a file, in order to save a
 52767        ** single unnecessary sqlite3OsRead() call at the start-up.
 52768        **
 52769        ** Database changes are detected by looking at 15 bytes beginning
 52770        ** at offset 24 into the file.  The first 4 of these 16 bytes are
 52771        ** a 32-bit counter that is incremented with each change.  The
 52772        ** other bytes change randomly with each file change when
 52773        ** a codec is in use.
 52774        ** 
 52775        ** There is a vanishingly small chance that a change will not be 
 52776        ** detected.  The chance of an undetected change is so small that
 52777        ** it can be neglected.
 52778        */
 52779        char dbFileVers[sizeof(pPager->dbFileVers)];
 52780  
 52781        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
 52782        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
 52783        if( rc!=SQLITE_OK ){
 52784          if( rc!=SQLITE_IOERR_SHORT_READ ){
 52785            goto failed;
 52786          }
 52787          memset(dbFileVers, 0, sizeof(dbFileVers));
 52788        }
 52789  
 52790        if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
 52791          pager_reset(pPager);
 52792  
 52793          /* Unmap the database file. It is possible that external processes
 52794          ** may have truncated the database file and then extended it back
 52795          ** to its original size while this process was not holding a lock.
 52796          ** In this case there may exist a Pager.pMap mapping that appears
 52797          ** to be the right size but is not actually valid. Avoid this
 52798          ** possibility by unmapping the db here. */
 52799          if( USEFETCH(pPager) ){
 52800            sqlite3OsUnfetch(pPager->fd, 0, 0);
 52801          }
 52802        }
 52803      }
 52804  
 52805      /* If there is a WAL file in the file-system, open this database in WAL
 52806      ** mode. Otherwise, the following function call is a no-op.
 52807      */
 52808      rc = pagerOpenWalIfPresent(pPager);
 52809  #ifndef SQLITE_OMIT_WAL
 52810      assert( pPager->pWal==0 || rc==SQLITE_OK );
 52811  #endif
 52812    }
 52813  
 52814    if( pagerUseWal(pPager) ){
 52815      assert( rc==SQLITE_OK );
 52816      rc = pagerBeginReadTransaction(pPager);
 52817    }
 52818  
 52819    if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
 52820      rc = pagerPagecount(pPager, &pPager->dbSize);
 52821    }
 52822  
 52823   failed:
 52824    if( rc!=SQLITE_OK ){
 52825      assert( !MEMDB );
 52826      pager_unlock(pPager);
 52827      assert( pPager->eState==PAGER_OPEN );
 52828    }else{
 52829      pPager->eState = PAGER_READER;
 52830      pPager->hasHeldSharedLock = 1;
 52831    }
 52832    return rc;
 52833  }
 52834  
 52835  /*
 52836  ** If the reference count has reached zero, rollback any active
 52837  ** transaction and unlock the pager.
 52838  **
 52839  ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
 52840  ** the rollback journal, the unlock is not performed and there is
 52841  ** nothing to rollback, so this routine is a no-op.
 52842  */ 
 52843  static void pagerUnlockIfUnused(Pager *pPager){
 52844    if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){
 52845      assert( pPager->nMmapOut==0 ); /* because page1 is never memory mapped */
 52846      pagerUnlockAndRollback(pPager);
 52847    }
 52848  }
 52849  
 52850  /*
 52851  ** The page getter methods each try to acquire a reference to a
 52852  ** page with page number pgno. If the requested reference is 
 52853  ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
 52854  **
 52855  ** There are different implementations of the getter method depending
 52856  ** on the current state of the pager.
 52857  **
 52858  **     getPageNormal()         --  The normal getter
 52859  **     getPageError()          --  Used if the pager is in an error state
 52860  **     getPageMmap()           --  Used if memory-mapped I/O is enabled
 52861  **
 52862  ** If the requested page is already in the cache, it is returned. 
 52863  ** Otherwise, a new page object is allocated and populated with data
 52864  ** read from the database file. In some cases, the pcache module may
 52865  ** choose not to allocate a new page object and may reuse an existing
 52866  ** object with no outstanding references.
 52867  **
 52868  ** The extra data appended to a page is always initialized to zeros the 
 52869  ** first time a page is loaded into memory. If the page requested is 
 52870  ** already in the cache when this function is called, then the extra
 52871  ** data is left as it was when the page object was last used.
 52872  **
 52873  ** If the database image is smaller than the requested page or if 
 52874  ** the flags parameter contains the PAGER_GET_NOCONTENT bit and the 
 52875  ** requested page is not already stored in the cache, then no 
 52876  ** actual disk read occurs. In this case the memory image of the 
 52877  ** page is initialized to all zeros. 
 52878  **
 52879  ** If PAGER_GET_NOCONTENT is true, it means that we do not care about
 52880  ** the contents of the page. This occurs in two scenarios:
 52881  **
 52882  **   a) When reading a free-list leaf page from the database, and
 52883  **
 52884  **   b) When a savepoint is being rolled back and we need to load
 52885  **      a new page into the cache to be filled with the data read
 52886  **      from the savepoint journal.
 52887  **
 52888  ** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead
 52889  ** of being read from the database. Additionally, the bits corresponding
 52890  ** to pgno in Pager.pInJournal (bitvec of pages already written to the
 52891  ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
 52892  ** savepoints are set. This means if the page is made writable at any
 52893  ** point in the future, using a call to sqlite3PagerWrite(), its contents
 52894  ** will not be journaled. This saves IO.
 52895  **
 52896  ** The acquisition might fail for several reasons.  In all cases,
 52897  ** an appropriate error code is returned and *ppPage is set to NULL.
 52898  **
 52899  ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
 52900  ** to find a page in the in-memory cache first.  If the page is not already
 52901  ** in memory, this routine goes to disk to read it in whereas Lookup()
 52902  ** just returns 0.  This routine acquires a read-lock the first time it
 52903  ** has to go to disk, and could also playback an old journal if necessary.
 52904  ** Since Lookup() never goes to disk, it never has to deal with locks
 52905  ** or journal files.
 52906  */
 52907  static int getPageNormal(
 52908    Pager *pPager,      /* The pager open on the database file */
 52909    Pgno pgno,          /* Page number to fetch */
 52910    DbPage **ppPage,    /* Write a pointer to the page here */
 52911    int flags           /* PAGER_GET_XXX flags */
 52912  ){
 52913    int rc = SQLITE_OK;
 52914    PgHdr *pPg;
 52915    u8 noContent;                   /* True if PAGER_GET_NOCONTENT is set */
 52916    sqlite3_pcache_page *pBase;
 52917  
 52918    assert( pPager->errCode==SQLITE_OK );
 52919    assert( pPager->eState>=PAGER_READER );
 52920    assert( assert_pager_state(pPager) );
 52921    assert( pPager->hasHeldSharedLock==1 );
 52922  
 52923    if( pgno==0 ) return SQLITE_CORRUPT_BKPT;
 52924    pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
 52925    if( pBase==0 ){
 52926      pPg = 0;
 52927      rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
 52928      if( rc!=SQLITE_OK ) goto pager_acquire_err;
 52929      if( pBase==0 ){
 52930        rc = SQLITE_NOMEM_BKPT;
 52931        goto pager_acquire_err;
 52932      }
 52933    }
 52934    pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
 52935    assert( pPg==(*ppPage) );
 52936    assert( pPg->pgno==pgno );
 52937    assert( pPg->pPager==pPager || pPg->pPager==0 );
 52938  
 52939    noContent = (flags & PAGER_GET_NOCONTENT)!=0;
 52940    if( pPg->pPager && !noContent ){
 52941      /* In this case the pcache already contains an initialized copy of
 52942      ** the page. Return without further ado.  */
 52943      assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
 52944      pPager->aStat[PAGER_STAT_HIT]++;
 52945      return SQLITE_OK;
 52946  
 52947    }else{
 52948      /* The pager cache has created a new page. Its content needs to 
 52949      ** be initialized. But first some error checks:
 52950      **
 52951      ** (1) The maximum page number is 2^31
 52952      ** (2) Never try to fetch the locking page
 52953      */
 52954      if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
 52955        rc = SQLITE_CORRUPT_BKPT;
 52956        goto pager_acquire_err;
 52957      }
 52958  
 52959      pPg->pPager = pPager;
 52960  
 52961      assert( !isOpen(pPager->fd) || !MEMDB );
 52962      if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
 52963        if( pgno>pPager->mxPgno ){
 52964          rc = SQLITE_FULL;
 52965          goto pager_acquire_err;
 52966        }
 52967        if( noContent ){
 52968          /* Failure to set the bits in the InJournal bit-vectors is benign.
 52969          ** It merely means that we might do some extra work to journal a 
 52970          ** page that does not need to be journaled.  Nevertheless, be sure 
 52971          ** to test the case where a malloc error occurs while trying to set 
 52972          ** a bit in a bit vector.
 52973          */
 52974          sqlite3BeginBenignMalloc();
 52975          if( pgno<=pPager->dbOrigSize ){
 52976            TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
 52977            testcase( rc==SQLITE_NOMEM );
 52978          }
 52979          TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
 52980          testcase( rc==SQLITE_NOMEM );
 52981          sqlite3EndBenignMalloc();
 52982        }
 52983        memset(pPg->pData, 0, pPager->pageSize);
 52984        IOTRACE(("ZERO %p %d\n", pPager, pgno));
 52985      }else{
 52986        assert( pPg->pPager==pPager );
 52987        pPager->aStat[PAGER_STAT_MISS]++;
 52988        rc = readDbPage(pPg);
 52989        if( rc!=SQLITE_OK ){
 52990          goto pager_acquire_err;
 52991        }
 52992      }
 52993      pager_set_pagehash(pPg);
 52994    }
 52995    return SQLITE_OK;
 52996  
 52997  pager_acquire_err:
 52998    assert( rc!=SQLITE_OK );
 52999    if( pPg ){
 53000      sqlite3PcacheDrop(pPg);
 53001    }
 53002    pagerUnlockIfUnused(pPager);
 53003    *ppPage = 0;
 53004    return rc;
 53005  }
 53006  
 53007  #if SQLITE_MAX_MMAP_SIZE>0
 53008  /* The page getter for when memory-mapped I/O is enabled */
 53009  static int getPageMMap(
 53010    Pager *pPager,      /* The pager open on the database file */
 53011    Pgno pgno,          /* Page number to fetch */
 53012    DbPage **ppPage,    /* Write a pointer to the page here */
 53013    int flags           /* PAGER_GET_XXX flags */
 53014  ){
 53015    int rc = SQLITE_OK;
 53016    PgHdr *pPg = 0;
 53017    u32 iFrame = 0;                 /* Frame to read from WAL file */
 53018  
 53019    /* It is acceptable to use a read-only (mmap) page for any page except
 53020    ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
 53021    ** flag was specified by the caller. And so long as the db is not a 
 53022    ** temporary or in-memory database.  */
 53023    const int bMmapOk = (pgno>1
 53024     && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
 53025    );
 53026  
 53027    assert( USEFETCH(pPager) );
 53028  #ifdef SQLITE_HAS_CODEC
 53029    assert( pPager->xCodec==0 );
 53030  #endif
 53031  
 53032    /* Optimization note:  Adding the "pgno<=1" term before "pgno==0" here
 53033    ** allows the compiler optimizer to reuse the results of the "pgno>1"
 53034    ** test in the previous statement, and avoid testing pgno==0 in the
 53035    ** common case where pgno is large. */
 53036    if( pgno<=1 && pgno==0 ){
 53037      return SQLITE_CORRUPT_BKPT;
 53038    }
 53039    assert( pPager->eState>=PAGER_READER );
 53040    assert( assert_pager_state(pPager) );
 53041    assert( pPager->hasHeldSharedLock==1 );
 53042    assert( pPager->errCode==SQLITE_OK );
 53043  
 53044    if( bMmapOk && pagerUseWal(pPager) ){
 53045      rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
 53046      if( rc!=SQLITE_OK ){
 53047        *ppPage = 0;
 53048        return rc;
 53049      }
 53050    }
 53051    if( bMmapOk && iFrame==0 ){
 53052      void *pData = 0;
 53053      rc = sqlite3OsFetch(pPager->fd, 
 53054          (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
 53055      );
 53056      if( rc==SQLITE_OK && pData ){
 53057        if( pPager->eState>PAGER_READER || pPager->tempFile ){
 53058          pPg = sqlite3PagerLookup(pPager, pgno);
 53059        }
 53060        if( pPg==0 ){
 53061          rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
 53062       }else{
 53063          sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
 53064        }
 53065        if( pPg ){
 53066          assert( rc==SQLITE_OK );
 53067          *ppPage = pPg;
 53068          return SQLITE_OK;
 53069        }
 53070      }
 53071      if( rc!=SQLITE_OK ){
 53072        *ppPage = 0;
 53073        return rc;
 53074      }
 53075    }
 53076    return getPageNormal(pPager, pgno, ppPage, flags);
 53077  }
 53078  #endif /* SQLITE_MAX_MMAP_SIZE>0 */
 53079  
 53080  /* The page getter method for when the pager is an error state */
 53081  static int getPageError(
 53082    Pager *pPager,      /* The pager open on the database file */
 53083    Pgno pgno,          /* Page number to fetch */
 53084    DbPage **ppPage,    /* Write a pointer to the page here */
 53085    int flags           /* PAGER_GET_XXX flags */
 53086  ){
 53087    UNUSED_PARAMETER(pgno);
 53088    UNUSED_PARAMETER(flags);
 53089    assert( pPager->errCode!=SQLITE_OK );
 53090    *ppPage = 0;
 53091    return pPager->errCode;
 53092  }
 53093  
 53094  
 53095  /* Dispatch all page fetch requests to the appropriate getter method.
 53096  */
 53097  SQLITE_PRIVATE int sqlite3PagerGet(
 53098    Pager *pPager,      /* The pager open on the database file */
 53099    Pgno pgno,          /* Page number to fetch */
 53100    DbPage **ppPage,    /* Write a pointer to the page here */
 53101    int flags           /* PAGER_GET_XXX flags */
 53102  ){
 53103    return pPager->xGet(pPager, pgno, ppPage, flags);
 53104  }
 53105  
 53106  /*
 53107  ** Acquire a page if it is already in the in-memory cache.  Do
 53108  ** not read the page from disk.  Return a pointer to the page,
 53109  ** or 0 if the page is not in cache. 
 53110  **
 53111  ** See also sqlite3PagerGet().  The difference between this routine
 53112  ** and sqlite3PagerGet() is that _get() will go to the disk and read
 53113  ** in the page if the page is not already in cache.  This routine
 53114  ** returns NULL if the page is not in cache or if a disk I/O error 
 53115  ** has ever happened.
 53116  */
 53117  SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
 53118    sqlite3_pcache_page *pPage;
 53119    assert( pPager!=0 );
 53120    assert( pgno!=0 );
 53121    assert( pPager->pPCache!=0 );
 53122    pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
 53123    assert( pPage==0 || pPager->hasHeldSharedLock );
 53124    if( pPage==0 ) return 0;
 53125    return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
 53126  }
 53127  
 53128  /*
 53129  ** Release a page reference.
 53130  **
 53131  ** The sqlite3PagerUnref() and sqlite3PagerUnrefNotNull() may only be
 53132  ** used if we know that the page being released is not the last page.
 53133  ** The btree layer always holds page1 open until the end, so these first
 53134  ** to routines can be used to release any page other than BtShared.pPage1.
 53135  **
 53136  ** Use sqlite3PagerUnrefPageOne() to release page1.  This latter routine
 53137  ** checks the total number of outstanding pages and if the number of
 53138  ** pages reaches zero it drops the database lock.
 53139  */
 53140  SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
 53141    TESTONLY( Pager *pPager = pPg->pPager; )
 53142    assert( pPg!=0 );
 53143    if( pPg->flags & PGHDR_MMAP ){
 53144      assert( pPg->pgno!=1 );  /* Page1 is never memory mapped */
 53145      pagerReleaseMapPage(pPg);
 53146    }else{
 53147      sqlite3PcacheRelease(pPg);
 53148    }
 53149    /* Do not use this routine to release the last reference to page1 */
 53150    assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
 53151  }
 53152  SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
 53153    if( pPg ) sqlite3PagerUnrefNotNull(pPg);
 53154  }
 53155  SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage *pPg){
 53156    Pager *pPager;
 53157    assert( pPg!=0 );
 53158    assert( pPg->pgno==1 );
 53159    assert( (pPg->flags & PGHDR_MMAP)==0 ); /* Page1 is never memory mapped */
 53160    pPager = pPg->pPager;
 53161    sqlite3PcacheRelease(pPg);
 53162    pagerUnlockIfUnused(pPager);
 53163  }
 53164  
 53165  /*
 53166  ** This function is called at the start of every write transaction.
 53167  ** There must already be a RESERVED or EXCLUSIVE lock on the database 
 53168  ** file when this routine is called.
 53169  **
 53170  ** Open the journal file for pager pPager and write a journal header
 53171  ** to the start of it. If there are active savepoints, open the sub-journal
 53172  ** as well. This function is only used when the journal file is being 
 53173  ** opened to write a rollback log for a transaction. It is not used 
 53174  ** when opening a hot journal file to roll it back.
 53175  **
 53176  ** If the journal file is already open (as it may be in exclusive mode),
 53177  ** then this function just writes a journal header to the start of the
 53178  ** already open file. 
 53179  **
 53180  ** Whether or not the journal file is opened by this function, the
 53181  ** Pager.pInJournal bitvec structure is allocated.
 53182  **
 53183  ** Return SQLITE_OK if everything is successful. Otherwise, return 
 53184  ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
 53185  ** an IO error code if opening or writing the journal file fails.
 53186  */
 53187  static int pager_open_journal(Pager *pPager){
 53188    int rc = SQLITE_OK;                        /* Return code */
 53189    sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
 53190  
 53191    assert( pPager->eState==PAGER_WRITER_LOCKED );
 53192    assert( assert_pager_state(pPager) );
 53193    assert( pPager->pInJournal==0 );
 53194    
 53195    /* If already in the error state, this function is a no-op.  But on
 53196    ** the other hand, this routine is never called if we are already in
 53197    ** an error state. */
 53198    if( NEVER(pPager->errCode) ) return pPager->errCode;
 53199  
 53200    if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
 53201      pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
 53202      if( pPager->pInJournal==0 ){
 53203        return SQLITE_NOMEM_BKPT;
 53204      }
 53205    
 53206      /* Open the journal file if it is not already open. */
 53207      if( !isOpen(pPager->jfd) ){
 53208        if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
 53209          sqlite3MemJournalOpen(pPager->jfd);
 53210        }else{
 53211          int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
 53212          int nSpill;
 53213  
 53214          if( pPager->tempFile ){
 53215            flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
 53216            nSpill = sqlite3Config.nStmtSpill;
 53217          }else{
 53218            flags |= SQLITE_OPEN_MAIN_JOURNAL;
 53219            nSpill = jrnlBufferSize(pPager);
 53220          }
 53221            
 53222          /* Verify that the database still has the same name as it did when
 53223          ** it was originally opened. */
 53224          rc = databaseIsUnmoved(pPager);
 53225          if( rc==SQLITE_OK ){
 53226            rc = sqlite3JournalOpen (
 53227                pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
 53228            );
 53229          }
 53230        }
 53231        assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
 53232      }
 53233    
 53234    
 53235      /* Write the first journal header to the journal file and open 
 53236      ** the sub-journal if necessary.
 53237      */
 53238      if( rc==SQLITE_OK ){
 53239        /* TODO: Check if all of these are really required. */
 53240        pPager->nRec = 0;
 53241        pPager->journalOff = 0;
 53242        pPager->setMaster = 0;
 53243        pPager->journalHdr = 0;
 53244        rc = writeJournalHdr(pPager);
 53245      }
 53246    }
 53247  
 53248    if( rc!=SQLITE_OK ){
 53249      sqlite3BitvecDestroy(pPager->pInJournal);
 53250      pPager->pInJournal = 0;
 53251    }else{
 53252      assert( pPager->eState==PAGER_WRITER_LOCKED );
 53253      pPager->eState = PAGER_WRITER_CACHEMOD;
 53254    }
 53255  
 53256    return rc;
 53257  }
 53258  
 53259  /*
 53260  ** Begin a write-transaction on the specified pager object. If a 
 53261  ** write-transaction has already been opened, this function is a no-op.
 53262  **
 53263  ** If the exFlag argument is false, then acquire at least a RESERVED
 53264  ** lock on the database file. If exFlag is true, then acquire at least
 53265  ** an EXCLUSIVE lock. If such a lock is already held, no locking 
 53266  ** functions need be called.
 53267  **
 53268  ** If the subjInMemory argument is non-zero, then any sub-journal opened
 53269  ** within this transaction will be opened as an in-memory file. This
 53270  ** has no effect if the sub-journal is already opened (as it may be when
 53271  ** running in exclusive mode) or if the transaction does not require a
 53272  ** sub-journal. If the subjInMemory argument is zero, then any required
 53273  ** sub-journal is implemented in-memory if pPager is an in-memory database, 
 53274  ** or using a temporary file otherwise.
 53275  */
 53276  SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
 53277    int rc = SQLITE_OK;
 53278  
 53279    if( pPager->errCode ) return pPager->errCode;
 53280    assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
 53281    pPager->subjInMemory = (u8)subjInMemory;
 53282  
 53283    if( ALWAYS(pPager->eState==PAGER_READER) ){
 53284      assert( pPager->pInJournal==0 );
 53285  
 53286      if( pagerUseWal(pPager) ){
 53287        /* If the pager is configured to use locking_mode=exclusive, and an
 53288        ** exclusive lock on the database is not already held, obtain it now.
 53289        */
 53290        if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
 53291          rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
 53292          if( rc!=SQLITE_OK ){
 53293            return rc;
 53294          }
 53295          (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
 53296        }
 53297  
 53298        /* Grab the write lock on the log file. If successful, upgrade to
 53299        ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
 53300        ** The busy-handler is not invoked if another connection already
 53301        ** holds the write-lock. If possible, the upper layer will call it.
 53302        */
 53303        rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
 53304      }else{
 53305        /* Obtain a RESERVED lock on the database file. If the exFlag parameter
 53306        ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
 53307        ** busy-handler callback can be used when upgrading to the EXCLUSIVE
 53308        ** lock, but not when obtaining the RESERVED lock.
 53309        */
 53310        rc = pagerLockDb(pPager, RESERVED_LOCK);
 53311        if( rc==SQLITE_OK && exFlag ){
 53312          rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
 53313        }
 53314      }
 53315  
 53316      if( rc==SQLITE_OK ){
 53317        /* Change to WRITER_LOCKED state.
 53318        **
 53319        ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
 53320        ** when it has an open transaction, but never to DBMOD or FINISHED.
 53321        ** This is because in those states the code to roll back savepoint 
 53322        ** transactions may copy data from the sub-journal into the database 
 53323        ** file as well as into the page cache. Which would be incorrect in 
 53324        ** WAL mode.
 53325        */
 53326        pPager->eState = PAGER_WRITER_LOCKED;
 53327        pPager->dbHintSize = pPager->dbSize;
 53328        pPager->dbFileSize = pPager->dbSize;
 53329        pPager->dbOrigSize = pPager->dbSize;
 53330        pPager->journalOff = 0;
 53331      }
 53332  
 53333      assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
 53334      assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
 53335      assert( assert_pager_state(pPager) );
 53336    }
 53337  
 53338    PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
 53339    return rc;
 53340  }
 53341  
 53342  /*
 53343  ** Write page pPg onto the end of the rollback journal.
 53344  */
 53345  static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
 53346    Pager *pPager = pPg->pPager;
 53347    int rc;
 53348    u32 cksum;
 53349    char *pData2;
 53350    i64 iOff = pPager->journalOff;
 53351  
 53352    /* We should never write to the journal file the page that
 53353    ** contains the database locks.  The following assert verifies
 53354    ** that we do not. */
 53355    assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
 53356  
 53357    assert( pPager->journalHdr<=pPager->journalOff );
 53358    CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
 53359    cksum = pager_cksum(pPager, (u8*)pData2);
 53360  
 53361    /* Even if an IO or diskfull error occurs while journalling the
 53362    ** page in the block above, set the need-sync flag for the page.
 53363    ** Otherwise, when the transaction is rolled back, the logic in
 53364    ** playback_one_page() will think that the page needs to be restored
 53365    ** in the database file. And if an IO error occurs while doing so,
 53366    ** then corruption may follow.
 53367    */
 53368    pPg->flags |= PGHDR_NEED_SYNC;
 53369  
 53370    rc = write32bits(pPager->jfd, iOff, pPg->pgno);
 53371    if( rc!=SQLITE_OK ) return rc;
 53372    rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
 53373    if( rc!=SQLITE_OK ) return rc;
 53374    rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
 53375    if( rc!=SQLITE_OK ) return rc;
 53376  
 53377    IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
 53378             pPager->journalOff, pPager->pageSize));
 53379    PAGER_INCR(sqlite3_pager_writej_count);
 53380    PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
 53381         PAGERID(pPager), pPg->pgno, 
 53382         ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
 53383  
 53384    pPager->journalOff += 8 + pPager->pageSize;
 53385    pPager->nRec++;
 53386    assert( pPager->pInJournal!=0 );
 53387    rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
 53388    testcase( rc==SQLITE_NOMEM );
 53389    assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
 53390    rc |= addToSavepointBitvecs(pPager, pPg->pgno);
 53391    assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
 53392    return rc;
 53393  }
 53394  
 53395  /*
 53396  ** Mark a single data page as writeable. The page is written into the 
 53397  ** main journal or sub-journal as required. If the page is written into
 53398  ** one of the journals, the corresponding bit is set in the 
 53399  ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
 53400  ** of any open savepoints as appropriate.
 53401  */
 53402  static int pager_write(PgHdr *pPg){
 53403    Pager *pPager = pPg->pPager;
 53404    int rc = SQLITE_OK;
 53405  
 53406    /* This routine is not called unless a write-transaction has already 
 53407    ** been started. The journal file may or may not be open at this point.
 53408    ** It is never called in the ERROR state.
 53409    */
 53410    assert( pPager->eState==PAGER_WRITER_LOCKED
 53411         || pPager->eState==PAGER_WRITER_CACHEMOD
 53412         || pPager->eState==PAGER_WRITER_DBMOD
 53413    );
 53414    assert( assert_pager_state(pPager) );
 53415    assert( pPager->errCode==0 );
 53416    assert( pPager->readOnly==0 );
 53417    CHECK_PAGE(pPg);
 53418  
 53419    /* The journal file needs to be opened. Higher level routines have already
 53420    ** obtained the necessary locks to begin the write-transaction, but the
 53421    ** rollback journal might not yet be open. Open it now if this is the case.
 53422    **
 53423    ** This is done before calling sqlite3PcacheMakeDirty() on the page. 
 53424    ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
 53425    ** an error might occur and the pager would end up in WRITER_LOCKED state
 53426    ** with pages marked as dirty in the cache.
 53427    */
 53428    if( pPager->eState==PAGER_WRITER_LOCKED ){
 53429      rc = pager_open_journal(pPager);
 53430      if( rc!=SQLITE_OK ) return rc;
 53431    }
 53432    assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
 53433    assert( assert_pager_state(pPager) );
 53434  
 53435    /* Mark the page that is about to be modified as dirty. */
 53436    sqlite3PcacheMakeDirty(pPg);
 53437  
 53438    /* If a rollback journal is in use, them make sure the page that is about
 53439    ** to change is in the rollback journal, or if the page is a new page off
 53440    ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
 53441    */
 53442    assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
 53443    if( pPager->pInJournal!=0
 53444     && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
 53445    ){
 53446      assert( pagerUseWal(pPager)==0 );
 53447      if( pPg->pgno<=pPager->dbOrigSize ){
 53448        rc = pagerAddPageToRollbackJournal(pPg);
 53449        if( rc!=SQLITE_OK ){
 53450          return rc;
 53451        }
 53452      }else{
 53453        if( pPager->eState!=PAGER_WRITER_DBMOD ){
 53454          pPg->flags |= PGHDR_NEED_SYNC;
 53455        }
 53456        PAGERTRACE(("APPEND %d page %d needSync=%d\n",
 53457                PAGERID(pPager), pPg->pgno,
 53458               ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
 53459      }
 53460    }
 53461  
 53462    /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
 53463    ** and before writing the page into the rollback journal.  Wait until now,
 53464    ** after the page has been successfully journalled, before setting the
 53465    ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
 53466    */
 53467    pPg->flags |= PGHDR_WRITEABLE;
 53468    
 53469    /* If the statement journal is open and the page is not in it,
 53470    ** then write the page into the statement journal.
 53471    */
 53472    if( pPager->nSavepoint>0 ){
 53473      rc = subjournalPageIfRequired(pPg);
 53474    }
 53475  
 53476    /* Update the database size and return. */
 53477    if( pPager->dbSize<pPg->pgno ){
 53478      pPager->dbSize = pPg->pgno;
 53479    }
 53480    return rc;
 53481  }
 53482  
 53483  /*
 53484  ** This is a variant of sqlite3PagerWrite() that runs when the sector size
 53485  ** is larger than the page size.  SQLite makes the (reasonable) assumption that
 53486  ** all bytes of a sector are written together by hardware.  Hence, all bytes of
 53487  ** a sector need to be journalled in case of a power loss in the middle of
 53488  ** a write.
 53489  **
 53490  ** Usually, the sector size is less than or equal to the page size, in which
 53491  ** case pages can be individually written.  This routine only runs in the
 53492  ** exceptional case where the page size is smaller than the sector size.
 53493  */
 53494  static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
 53495    int rc = SQLITE_OK;          /* Return code */
 53496    Pgno nPageCount;             /* Total number of pages in database file */
 53497    Pgno pg1;                    /* First page of the sector pPg is located on. */
 53498    int nPage = 0;               /* Number of pages starting at pg1 to journal */
 53499    int ii;                      /* Loop counter */
 53500    int needSync = 0;            /* True if any page has PGHDR_NEED_SYNC */
 53501    Pager *pPager = pPg->pPager; /* The pager that owns pPg */
 53502    Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
 53503  
 53504    /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
 53505    ** a journal header to be written between the pages journaled by
 53506    ** this function.
 53507    */
 53508    assert( !MEMDB );
 53509    assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
 53510    pPager->doNotSpill |= SPILLFLAG_NOSYNC;
 53511  
 53512    /* This trick assumes that both the page-size and sector-size are
 53513    ** an integer power of 2. It sets variable pg1 to the identifier
 53514    ** of the first page of the sector pPg is located on.
 53515    */
 53516    pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
 53517  
 53518    nPageCount = pPager->dbSize;
 53519    if( pPg->pgno>nPageCount ){
 53520      nPage = (pPg->pgno - pg1)+1;
 53521    }else if( (pg1+nPagePerSector-1)>nPageCount ){
 53522      nPage = nPageCount+1-pg1;
 53523    }else{
 53524      nPage = nPagePerSector;
 53525    }
 53526    assert(nPage>0);
 53527    assert(pg1<=pPg->pgno);
 53528    assert((pg1+nPage)>pPg->pgno);
 53529  
 53530    for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
 53531      Pgno pg = pg1+ii;
 53532      PgHdr *pPage;
 53533      if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
 53534        if( pg!=PAGER_MJ_PGNO(pPager) ){
 53535          rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
 53536          if( rc==SQLITE_OK ){
 53537            rc = pager_write(pPage);
 53538            if( pPage->flags&PGHDR_NEED_SYNC ){
 53539              needSync = 1;
 53540            }
 53541            sqlite3PagerUnrefNotNull(pPage);
 53542          }
 53543        }
 53544      }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
 53545        if( pPage->flags&PGHDR_NEED_SYNC ){
 53546          needSync = 1;
 53547        }
 53548        sqlite3PagerUnrefNotNull(pPage);
 53549      }
 53550    }
 53551  
 53552    /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
 53553    ** starting at pg1, then it needs to be set for all of them. Because
 53554    ** writing to any of these nPage pages may damage the others, the
 53555    ** journal file must contain sync()ed copies of all of them
 53556    ** before any of them can be written out to the database file.
 53557    */
 53558    if( rc==SQLITE_OK && needSync ){
 53559      assert( !MEMDB );
 53560      for(ii=0; ii<nPage; ii++){
 53561        PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
 53562        if( pPage ){
 53563          pPage->flags |= PGHDR_NEED_SYNC;
 53564          sqlite3PagerUnrefNotNull(pPage);
 53565        }
 53566      }
 53567    }
 53568  
 53569    assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
 53570    pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
 53571    return rc;
 53572  }
 53573  
 53574  /*
 53575  ** Mark a data page as writeable. This routine must be called before 
 53576  ** making changes to a page. The caller must check the return value 
 53577  ** of this function and be careful not to change any page data unless 
 53578  ** this routine returns SQLITE_OK.
 53579  **
 53580  ** The difference between this function and pager_write() is that this
 53581  ** function also deals with the special case where 2 or more pages
 53582  ** fit on a single disk sector. In this case all co-resident pages
 53583  ** must have been written to the journal file before returning.
 53584  **
 53585  ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
 53586  ** as appropriate. Otherwise, SQLITE_OK.
 53587  */
 53588  SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
 53589    Pager *pPager = pPg->pPager;
 53590    assert( (pPg->flags & PGHDR_MMAP)==0 );
 53591    assert( pPager->eState>=PAGER_WRITER_LOCKED );
 53592    assert( assert_pager_state(pPager) );
 53593    if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
 53594      if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
 53595      return SQLITE_OK;
 53596    }else if( pPager->errCode ){
 53597      return pPager->errCode;
 53598    }else if( pPager->sectorSize > (u32)pPager->pageSize ){
 53599      assert( pPager->tempFile==0 );
 53600      return pagerWriteLargeSector(pPg);
 53601    }else{
 53602      return pager_write(pPg);
 53603    }
 53604  }
 53605  
 53606  /*
 53607  ** Return TRUE if the page given in the argument was previously passed
 53608  ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
 53609  ** to change the content of the page.
 53610  */
 53611  #ifndef NDEBUG
 53612  SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
 53613    return pPg->flags & PGHDR_WRITEABLE;
 53614  }
 53615  #endif
 53616  
 53617  /*
 53618  ** A call to this routine tells the pager that it is not necessary to
 53619  ** write the information on page pPg back to the disk, even though
 53620  ** that page might be marked as dirty.  This happens, for example, when
 53621  ** the page has been added as a leaf of the freelist and so its
 53622  ** content no longer matters.
 53623  **
 53624  ** The overlying software layer calls this routine when all of the data
 53625  ** on the given page is unused. The pager marks the page as clean so
 53626  ** that it does not get written to disk.
 53627  **
 53628  ** Tests show that this optimization can quadruple the speed of large 
 53629  ** DELETE operations.
 53630  **
 53631  ** This optimization cannot be used with a temp-file, as the page may
 53632  ** have been dirty at the start of the transaction. In that case, if
 53633  ** memory pressure forces page pPg out of the cache, the data does need 
 53634  ** to be written out to disk so that it may be read back in if the 
 53635  ** current transaction is rolled back.
 53636  */
 53637  SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
 53638    Pager *pPager = pPg->pPager;
 53639    if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
 53640      PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
 53641      IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
 53642      pPg->flags |= PGHDR_DONT_WRITE;
 53643      pPg->flags &= ~PGHDR_WRITEABLE;
 53644      testcase( pPg->flags & PGHDR_NEED_SYNC );
 53645      pager_set_pagehash(pPg);
 53646    }
 53647  }
 53648  
 53649  /*
 53650  ** This routine is called to increment the value of the database file 
 53651  ** change-counter, stored as a 4-byte big-endian integer starting at 
 53652  ** byte offset 24 of the pager file.  The secondary change counter at
 53653  ** 92 is also updated, as is the SQLite version number at offset 96.
 53654  **
 53655  ** But this only happens if the pPager->changeCountDone flag is false.
 53656  ** To avoid excess churning of page 1, the update only happens once.
 53657  ** See also the pager_write_changecounter() routine that does an 
 53658  ** unconditional update of the change counters.
 53659  **
 53660  ** If the isDirectMode flag is zero, then this is done by calling 
 53661  ** sqlite3PagerWrite() on page 1, then modifying the contents of the
 53662  ** page data. In this case the file will be updated when the current
 53663  ** transaction is committed.
 53664  **
 53665  ** The isDirectMode flag may only be non-zero if the library was compiled
 53666  ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
 53667  ** if isDirect is non-zero, then the database file is updated directly
 53668  ** by writing an updated version of page 1 using a call to the 
 53669  ** sqlite3OsWrite() function.
 53670  */
 53671  static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
 53672    int rc = SQLITE_OK;
 53673  
 53674    assert( pPager->eState==PAGER_WRITER_CACHEMOD
 53675         || pPager->eState==PAGER_WRITER_DBMOD
 53676    );
 53677    assert( assert_pager_state(pPager) );
 53678  
 53679    /* Declare and initialize constant integer 'isDirect'. If the
 53680    ** atomic-write optimization is enabled in this build, then isDirect
 53681    ** is initialized to the value passed as the isDirectMode parameter
 53682    ** to this function. Otherwise, it is always set to zero.
 53683    **
 53684    ** The idea is that if the atomic-write optimization is not
 53685    ** enabled at compile time, the compiler can omit the tests of
 53686    ** 'isDirect' below, as well as the block enclosed in the
 53687    ** "if( isDirect )" condition.
 53688    */
 53689  #ifndef SQLITE_ENABLE_ATOMIC_WRITE
 53690  # define DIRECT_MODE 0
 53691    assert( isDirectMode==0 );
 53692    UNUSED_PARAMETER(isDirectMode);
 53693  #else
 53694  # define DIRECT_MODE isDirectMode
 53695  #endif
 53696  
 53697    if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
 53698      PgHdr *pPgHdr;                /* Reference to page 1 */
 53699  
 53700      assert( !pPager->tempFile && isOpen(pPager->fd) );
 53701  
 53702      /* Open page 1 of the file for writing. */
 53703      rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
 53704      assert( pPgHdr==0 || rc==SQLITE_OK );
 53705  
 53706      /* If page one was fetched successfully, and this function is not
 53707      ** operating in direct-mode, make page 1 writable.  When not in 
 53708      ** direct mode, page 1 is always held in cache and hence the PagerGet()
 53709      ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
 53710      */
 53711      if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
 53712        rc = sqlite3PagerWrite(pPgHdr);
 53713      }
 53714  
 53715      if( rc==SQLITE_OK ){
 53716        /* Actually do the update of the change counter */
 53717        pager_write_changecounter(pPgHdr);
 53718  
 53719        /* If running in direct mode, write the contents of page 1 to the file. */
 53720        if( DIRECT_MODE ){
 53721          const void *zBuf;
 53722          assert( pPager->dbFileSize>0 );
 53723          CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
 53724          if( rc==SQLITE_OK ){
 53725            rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
 53726            pPager->aStat[PAGER_STAT_WRITE]++;
 53727          }
 53728          if( rc==SQLITE_OK ){
 53729            /* Update the pager's copy of the change-counter. Otherwise, the
 53730            ** next time a read transaction is opened the cache will be
 53731            ** flushed (as the change-counter values will not match).  */
 53732            const void *pCopy = (const void *)&((const char *)zBuf)[24];
 53733            memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
 53734            pPager->changeCountDone = 1;
 53735          }
 53736        }else{
 53737          pPager->changeCountDone = 1;
 53738        }
 53739      }
 53740  
 53741      /* Release the page reference. */
 53742      sqlite3PagerUnref(pPgHdr);
 53743    }
 53744    return rc;
 53745  }
 53746  
 53747  /*
 53748  ** Sync the database file to disk. This is a no-op for in-memory databases
 53749  ** or pages with the Pager.noSync flag set.
 53750  **
 53751  ** If successful, or if called on a pager for which it is a no-op, this
 53752  ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
 53753  */
 53754  SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
 53755    int rc = SQLITE_OK;
 53756  
 53757    if( isOpen(pPager->fd) ){
 53758      void *pArg = (void*)zMaster;
 53759      rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
 53760      if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
 53761    }
 53762    if( rc==SQLITE_OK && !pPager->noSync ){
 53763      assert( !MEMDB );
 53764      rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
 53765    }
 53766    return rc;
 53767  }
 53768  
 53769  /*
 53770  ** This function may only be called while a write-transaction is active in
 53771  ** rollback. If the connection is in WAL mode, this call is a no-op. 
 53772  ** Otherwise, if the connection does not already have an EXCLUSIVE lock on 
 53773  ** the database file, an attempt is made to obtain one.
 53774  **
 53775  ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
 53776  ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
 53777  ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is 
 53778  ** returned.
 53779  */
 53780  SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
 53781    int rc = pPager->errCode;
 53782    assert( assert_pager_state(pPager) );
 53783    if( rc==SQLITE_OK ){
 53784      assert( pPager->eState==PAGER_WRITER_CACHEMOD 
 53785           || pPager->eState==PAGER_WRITER_DBMOD 
 53786           || pPager->eState==PAGER_WRITER_LOCKED 
 53787      );
 53788      assert( assert_pager_state(pPager) );
 53789      if( 0==pagerUseWal(pPager) ){
 53790        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
 53791      }
 53792    }
 53793    return rc;
 53794  }
 53795  
 53796  /*
 53797  ** Sync the database file for the pager pPager. zMaster points to the name
 53798  ** of a master journal file that should be written into the individual
 53799  ** journal file. zMaster may be NULL, which is interpreted as no master
 53800  ** journal (a single database transaction).
 53801  **
 53802  ** This routine ensures that:
 53803  **
 53804  **   * The database file change-counter is updated,
 53805  **   * the journal is synced (unless the atomic-write optimization is used),
 53806  **   * all dirty pages are written to the database file, 
 53807  **   * the database file is truncated (if required), and
 53808  **   * the database file synced. 
 53809  **
 53810  ** The only thing that remains to commit the transaction is to finalize 
 53811  ** (delete, truncate or zero the first part of) the journal file (or 
 53812  ** delete the master journal file if specified).
 53813  **
 53814  ** Note that if zMaster==NULL, this does not overwrite a previous value
 53815  ** passed to an sqlite3PagerCommitPhaseOne() call.
 53816  **
 53817  ** If the final parameter - noSync - is true, then the database file itself
 53818  ** is not synced. The caller must call sqlite3PagerSync() directly to
 53819  ** sync the database file before calling CommitPhaseTwo() to delete the
 53820  ** journal file in this case.
 53821  */
 53822  SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
 53823    Pager *pPager,                  /* Pager object */
 53824    const char *zMaster,            /* If not NULL, the master journal name */
 53825    int noSync                      /* True to omit the xSync on the db file */
 53826  ){
 53827    int rc = SQLITE_OK;             /* Return code */
 53828  
 53829    assert( pPager->eState==PAGER_WRITER_LOCKED
 53830         || pPager->eState==PAGER_WRITER_CACHEMOD
 53831         || pPager->eState==PAGER_WRITER_DBMOD
 53832         || pPager->eState==PAGER_ERROR
 53833    );
 53834    assert( assert_pager_state(pPager) );
 53835  
 53836    /* If a prior error occurred, report that error again. */
 53837    if( NEVER(pPager->errCode) ) return pPager->errCode;
 53838  
 53839    /* Provide the ability to easily simulate an I/O error during testing */
 53840    if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
 53841  
 53842    PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
 53843        pPager->zFilename, zMaster, pPager->dbSize));
 53844  
 53845    /* If no database changes have been made, return early. */
 53846    if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
 53847  
 53848    assert( MEMDB==0 || pPager->tempFile );
 53849    assert( isOpen(pPager->fd) || pPager->tempFile );
 53850    if( 0==pagerFlushOnCommit(pPager, 1) ){
 53851      /* If this is an in-memory db, or no pages have been written to, or this
 53852      ** function has already been called, it is mostly a no-op.  However, any
 53853      ** backup in progress needs to be restarted.  */
 53854      sqlite3BackupRestart(pPager->pBackup);
 53855    }else{
 53856      if( pagerUseWal(pPager) ){
 53857        PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
 53858        PgHdr *pPageOne = 0;
 53859        if( pList==0 ){
 53860          /* Must have at least one page for the WAL commit flag.
 53861          ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
 53862          rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
 53863          pList = pPageOne;
 53864          pList->pDirty = 0;
 53865        }
 53866        assert( rc==SQLITE_OK );
 53867        if( ALWAYS(pList) ){
 53868          rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
 53869        }
 53870        sqlite3PagerUnref(pPageOne);
 53871        if( rc==SQLITE_OK ){
 53872          sqlite3PcacheCleanAll(pPager->pPCache);
 53873        }
 53874      }else{
 53875        /* The bBatch boolean is true if the batch-atomic-write commit method
 53876        ** should be used.  No rollback journal is created if batch-atomic-write
 53877        ** is enabled.
 53878        */
 53879        sqlite3_file *fd = pPager->fd;
 53880  #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
 53881        const int bBatch = zMaster==0    /* An SQLITE_IOCAP_BATCH_ATOMIC commit */
 53882          && (sqlite3OsDeviceCharacteristics(fd) & SQLITE_IOCAP_BATCH_ATOMIC)
 53883          && !pPager->noSync
 53884          && sqlite3JournalIsInMemory(pPager->jfd);
 53885  #else
 53886  # define bBatch 0
 53887  #endif
 53888  
 53889  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
 53890        /* The following block updates the change-counter. Exactly how it
 53891        ** does this depends on whether or not the atomic-update optimization
 53892        ** was enabled at compile time, and if this transaction meets the 
 53893        ** runtime criteria to use the operation: 
 53894        **
 53895        **    * The file-system supports the atomic-write property for
 53896        **      blocks of size page-size, and 
 53897        **    * This commit is not part of a multi-file transaction, and
 53898        **    * Exactly one page has been modified and store in the journal file.
 53899        **
 53900        ** If the optimization was not enabled at compile time, then the
 53901        ** pager_incr_changecounter() function is called to update the change
 53902        ** counter in 'indirect-mode'. If the optimization is compiled in but
 53903        ** is not applicable to this transaction, call sqlite3JournalCreate()
 53904        ** to make sure the journal file has actually been created, then call
 53905        ** pager_incr_changecounter() to update the change-counter in indirect
 53906        ** mode. 
 53907        **
 53908        ** Otherwise, if the optimization is both enabled and applicable,
 53909        ** then call pager_incr_changecounter() to update the change-counter
 53910        ** in 'direct' mode. In this case the journal file will never be
 53911        ** created for this transaction.
 53912        */
 53913        if( bBatch==0 ){
 53914          PgHdr *pPg;
 53915          assert( isOpen(pPager->jfd) 
 53916              || pPager->journalMode==PAGER_JOURNALMODE_OFF 
 53917              || pPager->journalMode==PAGER_JOURNALMODE_WAL 
 53918              );
 53919          if( !zMaster && isOpen(pPager->jfd) 
 53920           && pPager->journalOff==jrnlBufferSize(pPager) 
 53921           && pPager->dbSize>=pPager->dbOrigSize
 53922           && (!(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
 53923          ){
 53924            /* Update the db file change counter via the direct-write method. The 
 53925            ** following call will modify the in-memory representation of page 1 
 53926            ** to include the updated change counter and then write page 1 
 53927            ** directly to the database file. Because of the atomic-write 
 53928            ** property of the host file-system, this is safe.
 53929            */
 53930            rc = pager_incr_changecounter(pPager, 1);
 53931          }else{
 53932            rc = sqlite3JournalCreate(pPager->jfd);
 53933            if( rc==SQLITE_OK ){
 53934              rc = pager_incr_changecounter(pPager, 0);
 53935            }
 53936          }
 53937        }
 53938  #else 
 53939  #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
 53940        if( zMaster ){
 53941          rc = sqlite3JournalCreate(pPager->jfd);
 53942          if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
 53943        }
 53944  #endif
 53945        rc = pager_incr_changecounter(pPager, 0);
 53946  #endif
 53947        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
 53948    
 53949        /* Write the master journal name into the journal file. If a master 
 53950        ** journal file name has already been written to the journal file, 
 53951        ** or if zMaster is NULL (no master journal), then this call is a no-op.
 53952        */
 53953        rc = writeMasterJournal(pPager, zMaster);
 53954        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
 53955    
 53956        /* Sync the journal file and write all dirty pages to the database.
 53957        ** If the atomic-update optimization is being used, this sync will not 
 53958        ** create the journal file or perform any real IO.
 53959        **
 53960        ** Because the change-counter page was just modified, unless the
 53961        ** atomic-update optimization is used it is almost certain that the
 53962        ** journal requires a sync here. However, in locking_mode=exclusive
 53963        ** on a system under memory pressure it is just possible that this is 
 53964        ** not the case. In this case it is likely enough that the redundant
 53965        ** xSync() call will be changed to a no-op by the OS anyhow. 
 53966        */
 53967        rc = syncJournal(pPager, 0);
 53968        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
 53969  
 53970        if( bBatch ){
 53971          /* The pager is now in DBMOD state. But regardless of what happens
 53972          ** next, attempting to play the journal back into the database would
 53973          ** be unsafe. Close it now to make sure that does not happen.  */
 53974          sqlite3OsClose(pPager->jfd);
 53975          rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_BEGIN_ATOMIC_WRITE, 0);
 53976          if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
 53977        }
 53978        rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
 53979        if( bBatch ){
 53980          if( rc==SQLITE_OK ){
 53981            rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_COMMIT_ATOMIC_WRITE, 0);
 53982          }else{
 53983            sqlite3OsFileControl(fd, SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE, 0);
 53984          }
 53985        }
 53986  
 53987        if( rc!=SQLITE_OK ){
 53988          assert( rc!=SQLITE_IOERR_BLOCKED );
 53989          goto commit_phase_one_exit;
 53990        }
 53991        sqlite3PcacheCleanAll(pPager->pPCache);
 53992  
 53993        /* If the file on disk is smaller than the database image, use 
 53994        ** pager_truncate to grow the file here. This can happen if the database
 53995        ** image was extended as part of the current transaction and then the
 53996        ** last page in the db image moved to the free-list. In this case the
 53997        ** last page is never written out to disk, leaving the database file
 53998        ** undersized. Fix this now if it is the case.  */
 53999        if( pPager->dbSize>pPager->dbFileSize ){
 54000          Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
 54001          assert( pPager->eState==PAGER_WRITER_DBMOD );
 54002          rc = pager_truncate(pPager, nNew);
 54003          if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
 54004        }
 54005    
 54006        /* Finally, sync the database file. */
 54007        if( !noSync ){
 54008          rc = sqlite3PagerSync(pPager, zMaster);
 54009        }
 54010        IOTRACE(("DBSYNC %p\n", pPager))
 54011      }
 54012    }
 54013  
 54014  commit_phase_one_exit:
 54015    if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
 54016      pPager->eState = PAGER_WRITER_FINISHED;
 54017    }
 54018    return rc;
 54019  }
 54020  
 54021  
 54022  /*
 54023  ** When this function is called, the database file has been completely
 54024  ** updated to reflect the changes made by the current transaction and
 54025  ** synced to disk. The journal file still exists in the file-system 
 54026  ** though, and if a failure occurs at this point it will eventually
 54027  ** be used as a hot-journal and the current transaction rolled back.
 54028  **
 54029  ** This function finalizes the journal file, either by deleting, 
 54030  ** truncating or partially zeroing it, so that it cannot be used 
 54031  ** for hot-journal rollback. Once this is done the transaction is
 54032  ** irrevocably committed.
 54033  **
 54034  ** If an error occurs, an IO error code is returned and the pager
 54035  ** moves into the error state. Otherwise, SQLITE_OK is returned.
 54036  */
 54037  SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
 54038    int rc = SQLITE_OK;                  /* Return code */
 54039  
 54040    /* This routine should not be called if a prior error has occurred.
 54041    ** But if (due to a coding error elsewhere in the system) it does get
 54042    ** called, just return the same error code without doing anything. */
 54043    if( NEVER(pPager->errCode) ) return pPager->errCode;
 54044  
 54045    assert( pPager->eState==PAGER_WRITER_LOCKED
 54046         || pPager->eState==PAGER_WRITER_FINISHED
 54047         || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
 54048    );
 54049    assert( assert_pager_state(pPager) );
 54050  
 54051    /* An optimization. If the database was not actually modified during
 54052    ** this transaction, the pager is running in exclusive-mode and is
 54053    ** using persistent journals, then this function is a no-op.
 54054    **
 54055    ** The start of the journal file currently contains a single journal 
 54056    ** header with the nRec field set to 0. If such a journal is used as
 54057    ** a hot-journal during hot-journal rollback, 0 changes will be made
 54058    ** to the database file. So there is no need to zero the journal 
 54059    ** header. Since the pager is in exclusive mode, there is no need
 54060    ** to drop any locks either.
 54061    */
 54062    if( pPager->eState==PAGER_WRITER_LOCKED 
 54063     && pPager->exclusiveMode 
 54064     && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
 54065    ){
 54066      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
 54067      pPager->eState = PAGER_READER;
 54068      return SQLITE_OK;
 54069    }
 54070  
 54071    PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
 54072    pPager->iDataVersion++;
 54073    rc = pager_end_transaction(pPager, pPager->setMaster, 1);
 54074    return pager_error(pPager, rc);
 54075  }
 54076  
 54077  /*
 54078  ** If a write transaction is open, then all changes made within the 
 54079  ** transaction are reverted and the current write-transaction is closed.
 54080  ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
 54081  ** state if an error occurs.
 54082  **
 54083  ** If the pager is already in PAGER_ERROR state when this function is called,
 54084  ** it returns Pager.errCode immediately. No work is performed in this case.
 54085  **
 54086  ** Otherwise, in rollback mode, this function performs two functions:
 54087  **
 54088  **   1) It rolls back the journal file, restoring all database file and 
 54089  **      in-memory cache pages to the state they were in when the transaction
 54090  **      was opened, and
 54091  **
 54092  **   2) It finalizes the journal file, so that it is not used for hot
 54093  **      rollback at any point in the future.
 54094  **
 54095  ** Finalization of the journal file (task 2) is only performed if the 
 54096  ** rollback is successful.
 54097  **
 54098  ** In WAL mode, all cache-entries containing data modified within the
 54099  ** current transaction are either expelled from the cache or reverted to
 54100  ** their pre-transaction state by re-reading data from the database or
 54101  ** WAL files. The WAL transaction is then closed.
 54102  */
 54103  SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
 54104    int rc = SQLITE_OK;                  /* Return code */
 54105    PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
 54106  
 54107    /* PagerRollback() is a no-op if called in READER or OPEN state. If
 54108    ** the pager is already in the ERROR state, the rollback is not 
 54109    ** attempted here. Instead, the error code is returned to the caller.
 54110    */
 54111    assert( assert_pager_state(pPager) );
 54112    if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
 54113    if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
 54114  
 54115    if( pagerUseWal(pPager) ){
 54116      int rc2;
 54117      rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
 54118      rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
 54119      if( rc==SQLITE_OK ) rc = rc2;
 54120    }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
 54121      int eState = pPager->eState;
 54122      rc = pager_end_transaction(pPager, 0, 0);
 54123      if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
 54124        /* This can happen using journal_mode=off. Move the pager to the error 
 54125        ** state to indicate that the contents of the cache may not be trusted.
 54126        ** Any active readers will get SQLITE_ABORT.
 54127        */
 54128        pPager->errCode = SQLITE_ABORT;
 54129        pPager->eState = PAGER_ERROR;
 54130        setGetterMethod(pPager);
 54131        return rc;
 54132      }
 54133    }else{
 54134      rc = pager_playback(pPager, 0);
 54135    }
 54136  
 54137    assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
 54138    assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
 54139            || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR 
 54140            || rc==SQLITE_CANTOPEN
 54141    );
 54142  
 54143    /* If an error occurs during a ROLLBACK, we can no longer trust the pager
 54144    ** cache. So call pager_error() on the way out to make any error persistent.
 54145    */
 54146    return pager_error(pPager, rc);
 54147  }
 54148  
 54149  /*
 54150  ** Return TRUE if the database file is opened read-only.  Return FALSE
 54151  ** if the database is (in theory) writable.
 54152  */
 54153  SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
 54154    return pPager->readOnly;
 54155  }
 54156  
 54157  #ifdef SQLITE_DEBUG
 54158  /*
 54159  ** Return the sum of the reference counts for all pages held by pPager.
 54160  */
 54161  SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
 54162    return sqlite3PcacheRefCount(pPager->pPCache);
 54163  }
 54164  #endif
 54165  
 54166  /*
 54167  ** Return the approximate number of bytes of memory currently
 54168  ** used by the pager and its associated cache.
 54169  */
 54170  SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
 54171    int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
 54172                                       + 5*sizeof(void*);
 54173    return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
 54174             + sqlite3MallocSize(pPager)
 54175             + pPager->pageSize;
 54176  }
 54177  
 54178  /*
 54179  ** Return the number of references to the specified page.
 54180  */
 54181  SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
 54182    return sqlite3PcachePageRefcount(pPage);
 54183  }
 54184  
 54185  #ifdef SQLITE_TEST
 54186  /*
 54187  ** This routine is used for testing and analysis only.
 54188  */
 54189  SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
 54190    static int a[11];
 54191    a[0] = sqlite3PcacheRefCount(pPager->pPCache);
 54192    a[1] = sqlite3PcachePagecount(pPager->pPCache);
 54193    a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
 54194    a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
 54195    a[4] = pPager->eState;
 54196    a[5] = pPager->errCode;
 54197    a[6] = pPager->aStat[PAGER_STAT_HIT];
 54198    a[7] = pPager->aStat[PAGER_STAT_MISS];
 54199    a[8] = 0;  /* Used to be pPager->nOvfl */
 54200    a[9] = pPager->nRead;
 54201    a[10] = pPager->aStat[PAGER_STAT_WRITE];
 54202    return a;
 54203  }
 54204  #endif
 54205  
 54206  /*
 54207  ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
 54208  ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
 54209  ** current cache hit or miss count, according to the value of eStat. If the 
 54210  ** reset parameter is non-zero, the cache hit or miss count is zeroed before 
 54211  ** returning.
 54212  */
 54213  SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
 54214  
 54215    assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
 54216         || eStat==SQLITE_DBSTATUS_CACHE_MISS
 54217         || eStat==SQLITE_DBSTATUS_CACHE_WRITE
 54218    );
 54219  
 54220    assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
 54221    assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
 54222    assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
 54223  
 54224    *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
 54225    if( reset ){
 54226      pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
 54227    }
 54228  }
 54229  
 54230  /*
 54231  ** Return true if this is an in-memory or temp-file backed pager.
 54232  */
 54233  SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
 54234    return pPager->tempFile;
 54235  }
 54236  
 54237  /*
 54238  ** Check that there are at least nSavepoint savepoints open. If there are
 54239  ** currently less than nSavepoints open, then open one or more savepoints
 54240  ** to make up the difference. If the number of savepoints is already
 54241  ** equal to nSavepoint, then this function is a no-op.
 54242  **
 54243  ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
 54244  ** occurs while opening the sub-journal file, then an IO error code is
 54245  ** returned. Otherwise, SQLITE_OK.
 54246  */
 54247  static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
 54248    int rc = SQLITE_OK;                       /* Return code */
 54249    int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
 54250    int ii;                                   /* Iterator variable */
 54251    PagerSavepoint *aNew;                     /* New Pager.aSavepoint array */
 54252  
 54253    assert( pPager->eState>=PAGER_WRITER_LOCKED );
 54254    assert( assert_pager_state(pPager) );
 54255    assert( nSavepoint>nCurrent && pPager->useJournal );
 54256  
 54257    /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
 54258    ** if the allocation fails. Otherwise, zero the new portion in case a 
 54259    ** malloc failure occurs while populating it in the for(...) loop below.
 54260    */
 54261    aNew = (PagerSavepoint *)sqlite3Realloc(
 54262        pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
 54263    );
 54264    if( !aNew ){
 54265      return SQLITE_NOMEM_BKPT;
 54266    }
 54267    memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
 54268    pPager->aSavepoint = aNew;
 54269  
 54270    /* Populate the PagerSavepoint structures just allocated. */
 54271    for(ii=nCurrent; ii<nSavepoint; ii++){
 54272      aNew[ii].nOrig = pPager->dbSize;
 54273      if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
 54274        aNew[ii].iOffset = pPager->journalOff;
 54275      }else{
 54276        aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
 54277      }
 54278      aNew[ii].iSubRec = pPager->nSubRec;
 54279      aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
 54280      if( !aNew[ii].pInSavepoint ){
 54281        return SQLITE_NOMEM_BKPT;
 54282      }
 54283      if( pagerUseWal(pPager) ){
 54284        sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
 54285      }
 54286      pPager->nSavepoint = ii+1;
 54287    }
 54288    assert( pPager->nSavepoint==nSavepoint );
 54289    assertTruncateConstraint(pPager);
 54290    return rc;
 54291  }
 54292  SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
 54293    assert( pPager->eState>=PAGER_WRITER_LOCKED );
 54294    assert( assert_pager_state(pPager) );
 54295  
 54296    if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
 54297      return pagerOpenSavepoint(pPager, nSavepoint);
 54298    }else{
 54299      return SQLITE_OK;
 54300    }
 54301  }
 54302  
 54303  
 54304  /*
 54305  ** This function is called to rollback or release (commit) a savepoint.
 54306  ** The savepoint to release or rollback need not be the most recently 
 54307  ** created savepoint.
 54308  **
 54309  ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
 54310  ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
 54311  ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
 54312  ** that have occurred since the specified savepoint was created.
 54313  **
 54314  ** The savepoint to rollback or release is identified by parameter 
 54315  ** iSavepoint. A value of 0 means to operate on the outermost savepoint
 54316  ** (the first created). A value of (Pager.nSavepoint-1) means operate
 54317  ** on the most recently created savepoint. If iSavepoint is greater than
 54318  ** (Pager.nSavepoint-1), then this function is a no-op.
 54319  **
 54320  ** If a negative value is passed to this function, then the current
 54321  ** transaction is rolled back. This is different to calling 
 54322  ** sqlite3PagerRollback() because this function does not terminate
 54323  ** the transaction or unlock the database, it just restores the 
 54324  ** contents of the database to its original state. 
 54325  **
 54326  ** In any case, all savepoints with an index greater than iSavepoint 
 54327  ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
 54328  ** then savepoint iSavepoint is also destroyed.
 54329  **
 54330  ** This function may return SQLITE_NOMEM if a memory allocation fails,
 54331  ** or an IO error code if an IO error occurs while rolling back a 
 54332  ** savepoint. If no errors occur, SQLITE_OK is returned.
 54333  */ 
 54334  SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
 54335    int rc = pPager->errCode;
 54336    
 54337  #ifdef SQLITE_ENABLE_ZIPVFS
 54338    if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
 54339  #endif
 54340  
 54341    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
 54342    assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
 54343  
 54344    if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
 54345      int ii;            /* Iterator variable */
 54346      int nNew;          /* Number of remaining savepoints after this op. */
 54347  
 54348      /* Figure out how many savepoints will still be active after this
 54349      ** operation. Store this value in nNew. Then free resources associated 
 54350      ** with any savepoints that are destroyed by this operation.
 54351      */
 54352      nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
 54353      for(ii=nNew; ii<pPager->nSavepoint; ii++){
 54354        sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
 54355      }
 54356      pPager->nSavepoint = nNew;
 54357  
 54358      /* If this is a release of the outermost savepoint, truncate 
 54359      ** the sub-journal to zero bytes in size. */
 54360      if( op==SAVEPOINT_RELEASE ){
 54361        if( nNew==0 && isOpen(pPager->sjfd) ){
 54362          /* Only truncate if it is an in-memory sub-journal. */
 54363          if( sqlite3JournalIsInMemory(pPager->sjfd) ){
 54364            rc = sqlite3OsTruncate(pPager->sjfd, 0);
 54365            assert( rc==SQLITE_OK );
 54366          }
 54367          pPager->nSubRec = 0;
 54368        }
 54369      }
 54370      /* Else this is a rollback operation, playback the specified savepoint.
 54371      ** If this is a temp-file, it is possible that the journal file has
 54372      ** not yet been opened. In this case there have been no changes to
 54373      ** the database file, so the playback operation can be skipped.
 54374      */
 54375      else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
 54376        PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
 54377        rc = pagerPlaybackSavepoint(pPager, pSavepoint);
 54378        assert(rc!=SQLITE_DONE);
 54379      }
 54380      
 54381  #ifdef SQLITE_ENABLE_ZIPVFS
 54382      /* If the cache has been modified but the savepoint cannot be rolled 
 54383      ** back journal_mode=off, put the pager in the error state. This way,
 54384      ** if the VFS used by this pager includes ZipVFS, the entire transaction
 54385      ** can be rolled back at the ZipVFS level.  */
 54386      else if( 
 54387          pPager->journalMode==PAGER_JOURNALMODE_OFF 
 54388       && pPager->eState>=PAGER_WRITER_CACHEMOD
 54389      ){
 54390        pPager->errCode = SQLITE_ABORT;
 54391        pPager->eState = PAGER_ERROR;
 54392        setGetterMethod(pPager);
 54393      }
 54394  #endif
 54395    }
 54396  
 54397    return rc;
 54398  }
 54399  
 54400  /*
 54401  ** Return the full pathname of the database file.
 54402  **
 54403  ** Except, if the pager is in-memory only, then return an empty string if
 54404  ** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
 54405  ** used to report the filename to the user, for compatibility with legacy
 54406  ** behavior.  But when the Btree needs to know the filename for matching to
 54407  ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
 54408  ** participate in shared-cache.
 54409  */
 54410  SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
 54411    return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
 54412  }
 54413  
 54414  /*
 54415  ** Return the VFS structure for the pager.
 54416  */
 54417  SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
 54418    return pPager->pVfs;
 54419  }
 54420  
 54421  /*
 54422  ** Return the file handle for the database file associated
 54423  ** with the pager.  This might return NULL if the file has
 54424  ** not yet been opened.
 54425  */
 54426  SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
 54427    return pPager->fd;
 54428  }
 54429  
 54430  /*
 54431  ** Return the file handle for the journal file (if it exists).
 54432  ** This will be either the rollback journal or the WAL file.
 54433  */
 54434  SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
 54435  #if SQLITE_OMIT_WAL
 54436    return pPager->jfd;
 54437  #else
 54438    return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
 54439  #endif
 54440  }
 54441  
 54442  /*
 54443  ** Return the full pathname of the journal file.
 54444  */
 54445  SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
 54446    return pPager->zJournal;
 54447  }
 54448  
 54449  #ifdef SQLITE_HAS_CODEC
 54450  /*
 54451  ** Set or retrieve the codec for this pager
 54452  */
 54453  SQLITE_PRIVATE void sqlite3PagerSetCodec(
 54454    Pager *pPager,
 54455    void *(*xCodec)(void*,void*,Pgno,int),
 54456    void (*xCodecSizeChng)(void*,int,int),
 54457    void (*xCodecFree)(void*),
 54458    void *pCodec
 54459  ){
 54460    if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
 54461    pPager->xCodec = pPager->memDb ? 0 : xCodec;
 54462    pPager->xCodecSizeChng = xCodecSizeChng;
 54463    pPager->xCodecFree = xCodecFree;
 54464    pPager->pCodec = pCodec;
 54465    setGetterMethod(pPager);
 54466    pagerReportSize(pPager);
 54467  }
 54468  SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
 54469    return pPager->pCodec;
 54470  }
 54471  
 54472  /*
 54473  ** This function is called by the wal module when writing page content
 54474  ** into the log file.
 54475  **
 54476  ** This function returns a pointer to a buffer containing the encrypted
 54477  ** page content. If a malloc fails, this function may return NULL.
 54478  */
 54479  SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
 54480    void *aData = 0;
 54481    CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
 54482    return aData;
 54483  }
 54484  
 54485  /*
 54486  ** Return the current pager state
 54487  */
 54488  SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
 54489    return pPager->eState;
 54490  }
 54491  #endif /* SQLITE_HAS_CODEC */
 54492  
 54493  #ifndef SQLITE_OMIT_AUTOVACUUM
 54494  /*
 54495  ** Move the page pPg to location pgno in the file.
 54496  **
 54497  ** There must be no references to the page previously located at
 54498  ** pgno (which we call pPgOld) though that page is allowed to be
 54499  ** in cache.  If the page previously located at pgno is not already
 54500  ** in the rollback journal, it is not put there by by this routine.
 54501  **
 54502  ** References to the page pPg remain valid. Updating any
 54503  ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
 54504  ** allocated along with the page) is the responsibility of the caller.
 54505  **
 54506  ** A transaction must be active when this routine is called. It used to be
 54507  ** required that a statement transaction was not active, but this restriction
 54508  ** has been removed (CREATE INDEX needs to move a page when a statement
 54509  ** transaction is active).
 54510  **
 54511  ** If the fourth argument, isCommit, is non-zero, then this page is being
 54512  ** moved as part of a database reorganization just before the transaction 
 54513  ** is being committed. In this case, it is guaranteed that the database page 
 54514  ** pPg refers to will not be written to again within this transaction.
 54515  **
 54516  ** This function may return SQLITE_NOMEM or an IO error code if an error
 54517  ** occurs. Otherwise, it returns SQLITE_OK.
 54518  */
 54519  SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
 54520    PgHdr *pPgOld;               /* The page being overwritten. */
 54521    Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
 54522    int rc;                      /* Return code */
 54523    Pgno origPgno;               /* The original page number */
 54524  
 54525    assert( pPg->nRef>0 );
 54526    assert( pPager->eState==PAGER_WRITER_CACHEMOD
 54527         || pPager->eState==PAGER_WRITER_DBMOD
 54528    );
 54529    assert( assert_pager_state(pPager) );
 54530  
 54531    /* In order to be able to rollback, an in-memory database must journal
 54532    ** the page we are moving from.
 54533    */
 54534    assert( pPager->tempFile || !MEMDB );
 54535    if( pPager->tempFile ){
 54536      rc = sqlite3PagerWrite(pPg);
 54537      if( rc ) return rc;
 54538    }
 54539  
 54540    /* If the page being moved is dirty and has not been saved by the latest
 54541    ** savepoint, then save the current contents of the page into the 
 54542    ** sub-journal now. This is required to handle the following scenario:
 54543    **
 54544    **   BEGIN;
 54545    **     <journal page X, then modify it in memory>
 54546    **     SAVEPOINT one;
 54547    **       <Move page X to location Y>
 54548    **     ROLLBACK TO one;
 54549    **
 54550    ** If page X were not written to the sub-journal here, it would not
 54551    ** be possible to restore its contents when the "ROLLBACK TO one"
 54552    ** statement were is processed.
 54553    **
 54554    ** subjournalPage() may need to allocate space to store pPg->pgno into
 54555    ** one or more savepoint bitvecs. This is the reason this function
 54556    ** may return SQLITE_NOMEM.
 54557    */
 54558    if( (pPg->flags & PGHDR_DIRTY)!=0
 54559     && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
 54560    ){
 54561      return rc;
 54562    }
 54563  
 54564    PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
 54565        PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
 54566    IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
 54567  
 54568    /* If the journal needs to be sync()ed before page pPg->pgno can
 54569    ** be written to, store pPg->pgno in local variable needSyncPgno.
 54570    **
 54571    ** If the isCommit flag is set, there is no need to remember that
 54572    ** the journal needs to be sync()ed before database page pPg->pgno 
 54573    ** can be written to. The caller has already promised not to write to it.
 54574    */
 54575    if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
 54576      needSyncPgno = pPg->pgno;
 54577      assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
 54578              pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
 54579      assert( pPg->flags&PGHDR_DIRTY );
 54580    }
 54581  
 54582    /* If the cache contains a page with page-number pgno, remove it
 54583    ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for 
 54584    ** page pgno before the 'move' operation, it needs to be retained 
 54585    ** for the page moved there.
 54586    */
 54587    pPg->flags &= ~PGHDR_NEED_SYNC;
 54588    pPgOld = sqlite3PagerLookup(pPager, pgno);
 54589    assert( !pPgOld || pPgOld->nRef==1 );
 54590    if( pPgOld ){
 54591      pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
 54592      if( pPager->tempFile ){
 54593        /* Do not discard pages from an in-memory database since we might
 54594        ** need to rollback later.  Just move the page out of the way. */
 54595        sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
 54596      }else{
 54597        sqlite3PcacheDrop(pPgOld);
 54598      }
 54599    }
 54600  
 54601    origPgno = pPg->pgno;
 54602    sqlite3PcacheMove(pPg, pgno);
 54603    sqlite3PcacheMakeDirty(pPg);
 54604  
 54605    /* For an in-memory database, make sure the original page continues
 54606    ** to exist, in case the transaction needs to roll back.  Use pPgOld
 54607    ** as the original page since it has already been allocated.
 54608    */
 54609    if( pPager->tempFile && pPgOld ){
 54610      sqlite3PcacheMove(pPgOld, origPgno);
 54611      sqlite3PagerUnrefNotNull(pPgOld);
 54612    }
 54613  
 54614    if( needSyncPgno ){
 54615      /* If needSyncPgno is non-zero, then the journal file needs to be 
 54616      ** sync()ed before any data is written to database file page needSyncPgno.
 54617      ** Currently, no such page exists in the page-cache and the 
 54618      ** "is journaled" bitvec flag has been set. This needs to be remedied by
 54619      ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
 54620      ** flag.
 54621      **
 54622      ** If the attempt to load the page into the page-cache fails, (due
 54623      ** to a malloc() or IO failure), clear the bit in the pInJournal[]
 54624      ** array. Otherwise, if the page is loaded and written again in
 54625      ** this transaction, it may be written to the database file before
 54626      ** it is synced into the journal file. This way, it may end up in
 54627      ** the journal file twice, but that is not a problem.
 54628      */
 54629      PgHdr *pPgHdr;
 54630      rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
 54631      if( rc!=SQLITE_OK ){
 54632        if( needSyncPgno<=pPager->dbOrigSize ){
 54633          assert( pPager->pTmpSpace!=0 );
 54634          sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
 54635        }
 54636        return rc;
 54637      }
 54638      pPgHdr->flags |= PGHDR_NEED_SYNC;
 54639      sqlite3PcacheMakeDirty(pPgHdr);
 54640      sqlite3PagerUnrefNotNull(pPgHdr);
 54641    }
 54642  
 54643    return SQLITE_OK;
 54644  }
 54645  #endif
 54646  
 54647  /*
 54648  ** The page handle passed as the first argument refers to a dirty page 
 54649  ** with a page number other than iNew. This function changes the page's 
 54650  ** page number to iNew and sets the value of the PgHdr.flags field to 
 54651  ** the value passed as the third parameter.
 54652  */
 54653  SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
 54654    assert( pPg->pgno!=iNew );
 54655    pPg->flags = flags;
 54656    sqlite3PcacheMove(pPg, iNew);
 54657  }
 54658  
 54659  /*
 54660  ** Return a pointer to the data for the specified page.
 54661  */
 54662  SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
 54663    assert( pPg->nRef>0 || pPg->pPager->memDb );
 54664    return pPg->pData;
 54665  }
 54666  
 54667  /*
 54668  ** Return a pointer to the Pager.nExtra bytes of "extra" space 
 54669  ** allocated along with the specified page.
 54670  */
 54671  SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
 54672    return pPg->pExtra;
 54673  }
 54674  
 54675  /*
 54676  ** Get/set the locking-mode for this pager. Parameter eMode must be one
 54677  ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
 54678  ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
 54679  ** the locking-mode is set to the value specified.
 54680  **
 54681  ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
 54682  ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
 54683  ** locking-mode.
 54684  */
 54685  SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
 54686    assert( eMode==PAGER_LOCKINGMODE_QUERY
 54687              || eMode==PAGER_LOCKINGMODE_NORMAL
 54688              || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
 54689    assert( PAGER_LOCKINGMODE_QUERY<0 );
 54690    assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
 54691    assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
 54692    if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
 54693      pPager->exclusiveMode = (u8)eMode;
 54694    }
 54695    return (int)pPager->exclusiveMode;
 54696  }
 54697  
 54698  /*
 54699  ** Set the journal-mode for this pager. Parameter eMode must be one of:
 54700  **
 54701  **    PAGER_JOURNALMODE_DELETE
 54702  **    PAGER_JOURNALMODE_TRUNCATE
 54703  **    PAGER_JOURNALMODE_PERSIST
 54704  **    PAGER_JOURNALMODE_OFF
 54705  **    PAGER_JOURNALMODE_MEMORY
 54706  **    PAGER_JOURNALMODE_WAL
 54707  **
 54708  ** The journalmode is set to the value specified if the change is allowed.
 54709  ** The change may be disallowed for the following reasons:
 54710  **
 54711  **   *  An in-memory database can only have its journal_mode set to _OFF
 54712  **      or _MEMORY.
 54713  **
 54714  **   *  Temporary databases cannot have _WAL journalmode.
 54715  **
 54716  ** The returned indicate the current (possibly updated) journal-mode.
 54717  */
 54718  SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
 54719    u8 eOld = pPager->journalMode;    /* Prior journalmode */
 54720  
 54721  #ifdef SQLITE_DEBUG
 54722    /* The print_pager_state() routine is intended to be used by the debugger
 54723    ** only.  We invoke it once here to suppress a compiler warning. */
 54724    print_pager_state(pPager);
 54725  #endif
 54726  
 54727  
 54728    /* The eMode parameter is always valid */
 54729    assert(      eMode==PAGER_JOURNALMODE_DELETE
 54730              || eMode==PAGER_JOURNALMODE_TRUNCATE
 54731              || eMode==PAGER_JOURNALMODE_PERSIST
 54732              || eMode==PAGER_JOURNALMODE_OFF 
 54733              || eMode==PAGER_JOURNALMODE_WAL 
 54734              || eMode==PAGER_JOURNALMODE_MEMORY );
 54735  
 54736    /* This routine is only called from the OP_JournalMode opcode, and
 54737    ** the logic there will never allow a temporary file to be changed
 54738    ** to WAL mode.
 54739    */
 54740    assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
 54741  
 54742    /* Do allow the journalmode of an in-memory database to be set to
 54743    ** anything other than MEMORY or OFF
 54744    */
 54745    if( MEMDB ){
 54746      assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
 54747      if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
 54748        eMode = eOld;
 54749      }
 54750    }
 54751  
 54752    if( eMode!=eOld ){
 54753  
 54754      /* Change the journal mode. */
 54755      assert( pPager->eState!=PAGER_ERROR );
 54756      pPager->journalMode = (u8)eMode;
 54757  
 54758      /* When transistioning from TRUNCATE or PERSIST to any other journal
 54759      ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
 54760      ** delete the journal file.
 54761      */
 54762      assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
 54763      assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
 54764      assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
 54765      assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
 54766      assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
 54767      assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
 54768  
 54769      assert( isOpen(pPager->fd) || pPager->exclusiveMode );
 54770      if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
 54771  
 54772        /* In this case we would like to delete the journal file. If it is
 54773        ** not possible, then that is not a problem. Deleting the journal file
 54774        ** here is an optimization only.
 54775        **
 54776        ** Before deleting the journal file, obtain a RESERVED lock on the
 54777        ** database file. This ensures that the journal file is not deleted
 54778        ** while it is in use by some other client.
 54779        */
 54780        sqlite3OsClose(pPager->jfd);
 54781        if( pPager->eLock>=RESERVED_LOCK ){
 54782          sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
 54783        }else{
 54784          int rc = SQLITE_OK;
 54785          int state = pPager->eState;
 54786          assert( state==PAGER_OPEN || state==PAGER_READER );
 54787          if( state==PAGER_OPEN ){
 54788            rc = sqlite3PagerSharedLock(pPager);
 54789          }
 54790          if( pPager->eState==PAGER_READER ){
 54791            assert( rc==SQLITE_OK );
 54792            rc = pagerLockDb(pPager, RESERVED_LOCK);
 54793          }
 54794          if( rc==SQLITE_OK ){
 54795            sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
 54796          }
 54797          if( rc==SQLITE_OK && state==PAGER_READER ){
 54798            pagerUnlockDb(pPager, SHARED_LOCK);
 54799          }else if( state==PAGER_OPEN ){
 54800            pager_unlock(pPager);
 54801          }
 54802          assert( state==pPager->eState );
 54803        }
 54804      }else if( eMode==PAGER_JOURNALMODE_OFF ){
 54805        sqlite3OsClose(pPager->jfd);
 54806      }
 54807    }
 54808  
 54809    /* Return the new journal mode */
 54810    return (int)pPager->journalMode;
 54811  }
 54812  
 54813  /*
 54814  ** Return the current journal mode.
 54815  */
 54816  SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
 54817    return (int)pPager->journalMode;
 54818  }
 54819  
 54820  /*
 54821  ** Return TRUE if the pager is in a state where it is OK to change the
 54822  ** journalmode.  Journalmode changes can only happen when the database
 54823  ** is unmodified.
 54824  */
 54825  SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
 54826    assert( assert_pager_state(pPager) );
 54827    if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
 54828    if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
 54829    return 1;
 54830  }
 54831  
 54832  /*
 54833  ** Get/set the size-limit used for persistent journal files.
 54834  **
 54835  ** Setting the size limit to -1 means no limit is enforced.
 54836  ** An attempt to set a limit smaller than -1 is a no-op.
 54837  */
 54838  SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
 54839    if( iLimit>=-1 ){
 54840      pPager->journalSizeLimit = iLimit;
 54841      sqlite3WalLimit(pPager->pWal, iLimit);
 54842    }
 54843    return pPager->journalSizeLimit;
 54844  }
 54845  
 54846  /*
 54847  ** Return a pointer to the pPager->pBackup variable. The backup module
 54848  ** in backup.c maintains the content of this variable. This module
 54849  ** uses it opaquely as an argument to sqlite3BackupRestart() and
 54850  ** sqlite3BackupUpdate() only.
 54851  */
 54852  SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
 54853    return &pPager->pBackup;
 54854  }
 54855  
 54856  #ifndef SQLITE_OMIT_VACUUM
 54857  /*
 54858  ** Unless this is an in-memory or temporary database, clear the pager cache.
 54859  */
 54860  SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
 54861    assert( MEMDB==0 || pPager->tempFile );
 54862    if( pPager->tempFile==0 ) pager_reset(pPager);
 54863  }
 54864  #endif
 54865  
 54866  
 54867  #ifndef SQLITE_OMIT_WAL
 54868  /*
 54869  ** This function is called when the user invokes "PRAGMA wal_checkpoint",
 54870  ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
 54871  ** or wal_blocking_checkpoint() API functions.
 54872  **
 54873  ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
 54874  */
 54875  SQLITE_PRIVATE int sqlite3PagerCheckpoint(
 54876    Pager *pPager,                  /* Checkpoint on this pager */
 54877    sqlite3 *db,                    /* Db handle used to check for interrupts */
 54878    int eMode,                      /* Type of checkpoint */
 54879    int *pnLog,                     /* OUT: Final number of frames in log */
 54880    int *pnCkpt                     /* OUT: Final number of checkpointed frames */
 54881  ){
 54882    int rc = SQLITE_OK;
 54883    if( pPager->pWal ){
 54884      rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,
 54885          (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
 54886          pPager->pBusyHandlerArg,
 54887          pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
 54888          pnLog, pnCkpt
 54889      );
 54890    }
 54891    return rc;
 54892  }
 54893  
 54894  SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
 54895    return sqlite3WalCallback(pPager->pWal);
 54896  }
 54897  
 54898  /*
 54899  ** Return true if the underlying VFS for the given pager supports the
 54900  ** primitives necessary for write-ahead logging.
 54901  */
 54902  SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
 54903    const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
 54904    if( pPager->noLock ) return 0;
 54905    return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
 54906  }
 54907  
 54908  /*
 54909  ** Attempt to take an exclusive lock on the database file. If a PENDING lock
 54910  ** is obtained instead, immediately release it.
 54911  */
 54912  static int pagerExclusiveLock(Pager *pPager){
 54913    int rc;                         /* Return code */
 54914  
 54915    assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
 54916    rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
 54917    if( rc!=SQLITE_OK ){
 54918      /* If the attempt to grab the exclusive lock failed, release the 
 54919      ** pending lock that may have been obtained instead.  */
 54920      pagerUnlockDb(pPager, SHARED_LOCK);
 54921    }
 54922  
 54923    return rc;
 54924  }
 54925  
 54926  /*
 54927  ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in 
 54928  ** exclusive-locking mode when this function is called, take an EXCLUSIVE
 54929  ** lock on the database file and use heap-memory to store the wal-index
 54930  ** in. Otherwise, use the normal shared-memory.
 54931  */
 54932  static int pagerOpenWal(Pager *pPager){
 54933    int rc = SQLITE_OK;
 54934  
 54935    assert( pPager->pWal==0 && pPager->tempFile==0 );
 54936    assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
 54937  
 54938    /* If the pager is already in exclusive-mode, the WAL module will use 
 54939    ** heap-memory for the wal-index instead of the VFS shared-memory 
 54940    ** implementation. Take the exclusive lock now, before opening the WAL
 54941    ** file, to make sure this is safe.
 54942    */
 54943    if( pPager->exclusiveMode ){
 54944      rc = pagerExclusiveLock(pPager);
 54945    }
 54946  
 54947    /* Open the connection to the log file. If this operation fails, 
 54948    ** (e.g. due to malloc() failure), return an error code.
 54949    */
 54950    if( rc==SQLITE_OK ){
 54951      rc = sqlite3WalOpen(pPager->pVfs,
 54952          pPager->fd, pPager->zWal, pPager->exclusiveMode,
 54953          pPager->journalSizeLimit, &pPager->pWal
 54954      );
 54955    }
 54956    pagerFixMaplimit(pPager);
 54957  
 54958    return rc;
 54959  }
 54960  
 54961  
 54962  /*
 54963  ** The caller must be holding a SHARED lock on the database file to call
 54964  ** this function.
 54965  **
 54966  ** If the pager passed as the first argument is open on a real database
 54967  ** file (not a temp file or an in-memory database), and the WAL file
 54968  ** is not already open, make an attempt to open it now. If successful,
 54969  ** return SQLITE_OK. If an error occurs or the VFS used by the pager does 
 54970  ** not support the xShmXXX() methods, return an error code. *pbOpen is
 54971  ** not modified in either case.
 54972  **
 54973  ** If the pager is open on a temp-file (or in-memory database), or if
 54974  ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
 54975  ** without doing anything.
 54976  */
 54977  SQLITE_PRIVATE int sqlite3PagerOpenWal(
 54978    Pager *pPager,                  /* Pager object */
 54979    int *pbOpen                     /* OUT: Set to true if call is a no-op */
 54980  ){
 54981    int rc = SQLITE_OK;             /* Return code */
 54982  
 54983    assert( assert_pager_state(pPager) );
 54984    assert( pPager->eState==PAGER_OPEN   || pbOpen );
 54985    assert( pPager->eState==PAGER_READER || !pbOpen );
 54986    assert( pbOpen==0 || *pbOpen==0 );
 54987    assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
 54988  
 54989    if( !pPager->tempFile && !pPager->pWal ){
 54990      if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
 54991  
 54992      /* Close any rollback journal previously open */
 54993      sqlite3OsClose(pPager->jfd);
 54994  
 54995      rc = pagerOpenWal(pPager);
 54996      if( rc==SQLITE_OK ){
 54997        pPager->journalMode = PAGER_JOURNALMODE_WAL;
 54998        pPager->eState = PAGER_OPEN;
 54999      }
 55000    }else{
 55001      *pbOpen = 1;
 55002    }
 55003  
 55004    return rc;
 55005  }
 55006  
 55007  /*
 55008  ** This function is called to close the connection to the log file prior
 55009  ** to switching from WAL to rollback mode.
 55010  **
 55011  ** Before closing the log file, this function attempts to take an 
 55012  ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
 55013  ** error (SQLITE_BUSY) is returned and the log connection is not closed.
 55014  ** If successful, the EXCLUSIVE lock is not released before returning.
 55015  */
 55016  SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){
 55017    int rc = SQLITE_OK;
 55018  
 55019    assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
 55020  
 55021    /* If the log file is not already open, but does exist in the file-system,
 55022    ** it may need to be checkpointed before the connection can switch to
 55023    ** rollback mode. Open it now so this can happen.
 55024    */
 55025    if( !pPager->pWal ){
 55026      int logexists = 0;
 55027      rc = pagerLockDb(pPager, SHARED_LOCK);
 55028      if( rc==SQLITE_OK ){
 55029        rc = sqlite3OsAccess(
 55030            pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
 55031        );
 55032      }
 55033      if( rc==SQLITE_OK && logexists ){
 55034        rc = pagerOpenWal(pPager);
 55035      }
 55036    }
 55037      
 55038    /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
 55039    ** the database file, the log and log-summary files will be deleted.
 55040    */
 55041    if( rc==SQLITE_OK && pPager->pWal ){
 55042      rc = pagerExclusiveLock(pPager);
 55043      if( rc==SQLITE_OK ){
 55044        rc = sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags,
 55045                             pPager->pageSize, (u8*)pPager->pTmpSpace);
 55046        pPager->pWal = 0;
 55047        pagerFixMaplimit(pPager);
 55048        if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
 55049      }
 55050    }
 55051    return rc;
 55052  }
 55053  
 55054  #ifdef SQLITE_ENABLE_SNAPSHOT
 55055  /*
 55056  ** If this is a WAL database, obtain a snapshot handle for the snapshot
 55057  ** currently open. Otherwise, return an error.
 55058  */
 55059  SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
 55060    int rc = SQLITE_ERROR;
 55061    if( pPager->pWal ){
 55062      rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
 55063    }
 55064    return rc;
 55065  }
 55066  
 55067  /*
 55068  ** If this is a WAL database, store a pointer to pSnapshot. Next time a
 55069  ** read transaction is opened, attempt to read from the snapshot it 
 55070  ** identifies. If this is not a WAL database, return an error.
 55071  */
 55072  SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
 55073    int rc = SQLITE_OK;
 55074    if( pPager->pWal ){
 55075      sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
 55076    }else{
 55077      rc = SQLITE_ERROR;
 55078    }
 55079    return rc;
 55080  }
 55081  
 55082  /*
 55083  ** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this 
 55084  ** is not a WAL database, return an error.
 55085  */
 55086  SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){
 55087    int rc;
 55088    if( pPager->pWal ){
 55089      rc = sqlite3WalSnapshotRecover(pPager->pWal);
 55090    }else{
 55091      rc = SQLITE_ERROR;
 55092    }
 55093    return rc;
 55094  }
 55095  #endif /* SQLITE_ENABLE_SNAPSHOT */
 55096  #endif /* !SQLITE_OMIT_WAL */
 55097  
 55098  #ifdef SQLITE_ENABLE_ZIPVFS
 55099  /*
 55100  ** A read-lock must be held on the pager when this function is called. If
 55101  ** the pager is in WAL mode and the WAL file currently contains one or more
 55102  ** frames, return the size in bytes of the page images stored within the
 55103  ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
 55104  ** is empty, return 0.
 55105  */
 55106  SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
 55107    assert( pPager->eState>=PAGER_READER );
 55108    return sqlite3WalFramesize(pPager->pWal);
 55109  }
 55110  #endif
 55111  
 55112  #endif /* SQLITE_OMIT_DISKIO */
 55113  
 55114  /************** End of pager.c ***********************************************/
 55115  /************** Begin file wal.c *********************************************/
 55116  /*
 55117  ** 2010 February 1
 55118  **
 55119  ** The author disclaims copyright to this source code.  In place of
 55120  ** a legal notice, here is a blessing:
 55121  **
 55122  **    May you do good and not evil.
 55123  **    May you find forgiveness for yourself and forgive others.
 55124  **    May you share freely, never taking more than you give.
 55125  **
 55126  *************************************************************************
 55127  **
 55128  ** This file contains the implementation of a write-ahead log (WAL) used in 
 55129  ** "journal_mode=WAL" mode.
 55130  **
 55131  ** WRITE-AHEAD LOG (WAL) FILE FORMAT
 55132  **
 55133  ** A WAL file consists of a header followed by zero or more "frames".
 55134  ** Each frame records the revised content of a single page from the
 55135  ** database file.  All changes to the database are recorded by writing
 55136  ** frames into the WAL.  Transactions commit when a frame is written that
 55137  ** contains a commit marker.  A single WAL can and usually does record 
 55138  ** multiple transactions.  Periodically, the content of the WAL is
 55139  ** transferred back into the database file in an operation called a
 55140  ** "checkpoint".
 55141  **
 55142  ** A single WAL file can be used multiple times.  In other words, the
 55143  ** WAL can fill up with frames and then be checkpointed and then new
 55144  ** frames can overwrite the old ones.  A WAL always grows from beginning
 55145  ** toward the end.  Checksums and counters attached to each frame are
 55146  ** used to determine which frames within the WAL are valid and which
 55147  ** are leftovers from prior checkpoints.
 55148  **
 55149  ** The WAL header is 32 bytes in size and consists of the following eight
 55150  ** big-endian 32-bit unsigned integer values:
 55151  **
 55152  **     0: Magic number.  0x377f0682 or 0x377f0683
 55153  **     4: File format version.  Currently 3007000
 55154  **     8: Database page size.  Example: 1024
 55155  **    12: Checkpoint sequence number
 55156  **    16: Salt-1, random integer incremented with each checkpoint
 55157  **    20: Salt-2, a different random integer changing with each ckpt
 55158  **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
 55159  **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
 55160  **
 55161  ** Immediately following the wal-header are zero or more frames. Each
 55162  ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
 55163  ** of page data. The frame-header is six big-endian 32-bit unsigned 
 55164  ** integer values, as follows:
 55165  **
 55166  **     0: Page number.
 55167  **     4: For commit records, the size of the database image in pages 
 55168  **        after the commit. For all other records, zero.
 55169  **     8: Salt-1 (copied from the header)
 55170  **    12: Salt-2 (copied from the header)
 55171  **    16: Checksum-1.
 55172  **    20: Checksum-2.
 55173  **
 55174  ** A frame is considered valid if and only if the following conditions are
 55175  ** true:
 55176  **
 55177  **    (1) The salt-1 and salt-2 values in the frame-header match
 55178  **        salt values in the wal-header
 55179  **
 55180  **    (2) The checksum values in the final 8 bytes of the frame-header
 55181  **        exactly match the checksum computed consecutively on the
 55182  **        WAL header and the first 8 bytes and the content of all frames
 55183  **        up to and including the current frame.
 55184  **
 55185  ** The checksum is computed using 32-bit big-endian integers if the
 55186  ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
 55187  ** is computed using little-endian if the magic number is 0x377f0682.
 55188  ** The checksum values are always stored in the frame header in a
 55189  ** big-endian format regardless of which byte order is used to compute
 55190  ** the checksum.  The checksum is computed by interpreting the input as
 55191  ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
 55192  ** algorithm used for the checksum is as follows:
 55193  ** 
 55194  **   for i from 0 to n-1 step 2:
 55195  **     s0 += x[i] + s1;
 55196  **     s1 += x[i+1] + s0;
 55197  **   endfor
 55198  **
 55199  ** Note that s0 and s1 are both weighted checksums using fibonacci weights
 55200  ** in reverse order (the largest fibonacci weight occurs on the first element
 55201  ** of the sequence being summed.)  The s1 value spans all 32-bit 
 55202  ** terms of the sequence whereas s0 omits the final term.
 55203  **
 55204  ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
 55205  ** WAL is transferred into the database, then the database is VFS.xSync-ed.
 55206  ** The VFS.xSync operations serve as write barriers - all writes launched
 55207  ** before the xSync must complete before any write that launches after the
 55208  ** xSync begins.
 55209  **
 55210  ** After each checkpoint, the salt-1 value is incremented and the salt-2
 55211  ** value is randomized.  This prevents old and new frames in the WAL from
 55212  ** being considered valid at the same time and being checkpointing together
 55213  ** following a crash.
 55214  **
 55215  ** READER ALGORITHM
 55216  **
 55217  ** To read a page from the database (call it page number P), a reader
 55218  ** first checks the WAL to see if it contains page P.  If so, then the
 55219  ** last valid instance of page P that is a followed by a commit frame
 55220  ** or is a commit frame itself becomes the value read.  If the WAL
 55221  ** contains no copies of page P that are valid and which are a commit
 55222  ** frame or are followed by a commit frame, then page P is read from
 55223  ** the database file.
 55224  **
 55225  ** To start a read transaction, the reader records the index of the last
 55226  ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
 55227  ** for all subsequent read operations.  New transactions can be appended
 55228  ** to the WAL, but as long as the reader uses its original mxFrame value
 55229  ** and ignores the newly appended content, it will see a consistent snapshot
 55230  ** of the database from a single point in time.  This technique allows
 55231  ** multiple concurrent readers to view different versions of the database
 55232  ** content simultaneously.
 55233  **
 55234  ** The reader algorithm in the previous paragraphs works correctly, but 
 55235  ** because frames for page P can appear anywhere within the WAL, the
 55236  ** reader has to scan the entire WAL looking for page P frames.  If the
 55237  ** WAL is large (multiple megabytes is typical) that scan can be slow,
 55238  ** and read performance suffers.  To overcome this problem, a separate
 55239  ** data structure called the wal-index is maintained to expedite the
 55240  ** search for frames of a particular page.
 55241  ** 
 55242  ** WAL-INDEX FORMAT
 55243  **
 55244  ** Conceptually, the wal-index is shared memory, though VFS implementations
 55245  ** might choose to implement the wal-index using a mmapped file.  Because
 55246  ** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
 55247  ** on a network filesystem.  All users of the database must be able to
 55248  ** share memory.
 55249  **
 55250  ** The wal-index is transient.  After a crash, the wal-index can (and should
 55251  ** be) reconstructed from the original WAL file.  In fact, the VFS is required
 55252  ** to either truncate or zero the header of the wal-index when the last
 55253  ** connection to it closes.  Because the wal-index is transient, it can
 55254  ** use an architecture-specific format; it does not have to be cross-platform.
 55255  ** Hence, unlike the database and WAL file formats which store all values
 55256  ** as big endian, the wal-index can store multi-byte values in the native
 55257  ** byte order of the host computer.
 55258  **
 55259  ** The purpose of the wal-index is to answer this question quickly:  Given
 55260  ** a page number P and a maximum frame index M, return the index of the 
 55261  ** last frame in the wal before frame M for page P in the WAL, or return
 55262  ** NULL if there are no frames for page P in the WAL prior to M.
 55263  **
 55264  ** The wal-index consists of a header region, followed by an one or
 55265  ** more index blocks.  
 55266  **
 55267  ** The wal-index header contains the total number of frames within the WAL
 55268  ** in the mxFrame field.
 55269  **
 55270  ** Each index block except for the first contains information on 
 55271  ** HASHTABLE_NPAGE frames. The first index block contains information on
 55272  ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
 55273  ** HASHTABLE_NPAGE are selected so that together the wal-index header and
 55274  ** first index block are the same size as all other index blocks in the
 55275  ** wal-index.
 55276  **
 55277  ** Each index block contains two sections, a page-mapping that contains the
 55278  ** database page number associated with each wal frame, and a hash-table 
 55279  ** that allows readers to query an index block for a specific page number.
 55280  ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
 55281  ** for the first index block) 32-bit page numbers. The first entry in the 
 55282  ** first index-block contains the database page number corresponding to the
 55283  ** first frame in the WAL file. The first entry in the second index block
 55284  ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
 55285  ** the log, and so on.
 55286  **
 55287  ** The last index block in a wal-index usually contains less than the full
 55288  ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
 55289  ** depending on the contents of the WAL file. This does not change the
 55290  ** allocated size of the page-mapping array - the page-mapping array merely
 55291  ** contains unused entries.
 55292  **
 55293  ** Even without using the hash table, the last frame for page P
 55294  ** can be found by scanning the page-mapping sections of each index block
 55295  ** starting with the last index block and moving toward the first, and
 55296  ** within each index block, starting at the end and moving toward the
 55297  ** beginning.  The first entry that equals P corresponds to the frame
 55298  ** holding the content for that page.
 55299  **
 55300  ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
 55301  ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
 55302  ** hash table for each page number in the mapping section, so the hash 
 55303  ** table is never more than half full.  The expected number of collisions 
 55304  ** prior to finding a match is 1.  Each entry of the hash table is an
 55305  ** 1-based index of an entry in the mapping section of the same
 55306  ** index block.   Let K be the 1-based index of the largest entry in
 55307  ** the mapping section.  (For index blocks other than the last, K will
 55308  ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
 55309  ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
 55310  ** contain a value of 0.
 55311  **
 55312  ** To look for page P in the hash table, first compute a hash iKey on
 55313  ** P as follows:
 55314  **
 55315  **      iKey = (P * 383) % HASHTABLE_NSLOT
 55316  **
 55317  ** Then start scanning entries of the hash table, starting with iKey
 55318  ** (wrapping around to the beginning when the end of the hash table is
 55319  ** reached) until an unused hash slot is found. Let the first unused slot
 55320  ** be at index iUnused.  (iUnused might be less than iKey if there was
 55321  ** wrap-around.) Because the hash table is never more than half full,
 55322  ** the search is guaranteed to eventually hit an unused entry.  Let 
 55323  ** iMax be the value between iKey and iUnused, closest to iUnused,
 55324  ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
 55325  ** no hash slot such that aHash[i]==p) then page P is not in the
 55326  ** current index block.  Otherwise the iMax-th mapping entry of the
 55327  ** current index block corresponds to the last entry that references 
 55328  ** page P.
 55329  **
 55330  ** A hash search begins with the last index block and moves toward the
 55331  ** first index block, looking for entries corresponding to page P.  On
 55332  ** average, only two or three slots in each index block need to be
 55333  ** examined in order to either find the last entry for page P, or to
 55334  ** establish that no such entry exists in the block.  Each index block
 55335  ** holds over 4000 entries.  So two or three index blocks are sufficient
 55336  ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
 55337  ** comparisons (on average) suffice to either locate a frame in the
 55338  ** WAL or to establish that the frame does not exist in the WAL.  This
 55339  ** is much faster than scanning the entire 10MB WAL.
 55340  **
 55341  ** Note that entries are added in order of increasing K.  Hence, one
 55342  ** reader might be using some value K0 and a second reader that started
 55343  ** at a later time (after additional transactions were added to the WAL
 55344  ** and to the wal-index) might be using a different value K1, where K1>K0.
 55345  ** Both readers can use the same hash table and mapping section to get
 55346  ** the correct result.  There may be entries in the hash table with
 55347  ** K>K0 but to the first reader, those entries will appear to be unused
 55348  ** slots in the hash table and so the first reader will get an answer as
 55349  ** if no values greater than K0 had ever been inserted into the hash table
 55350  ** in the first place - which is what reader one wants.  Meanwhile, the
 55351  ** second reader using K1 will see additional values that were inserted
 55352  ** later, which is exactly what reader two wants.  
 55353  **
 55354  ** When a rollback occurs, the value of K is decreased. Hash table entries
 55355  ** that correspond to frames greater than the new K value are removed
 55356  ** from the hash table at this point.
 55357  */
 55358  #ifndef SQLITE_OMIT_WAL
 55359  
 55360  /* #include "wal.h" */
 55361  
 55362  /*
 55363  ** Trace output macros
 55364  */
 55365  #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
 55366  SQLITE_PRIVATE int sqlite3WalTrace = 0;
 55367  # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
 55368  #else
 55369  # define WALTRACE(X)
 55370  #endif
 55371  
 55372  /*
 55373  ** The maximum (and only) versions of the wal and wal-index formats
 55374  ** that may be interpreted by this version of SQLite.
 55375  **
 55376  ** If a client begins recovering a WAL file and finds that (a) the checksum
 55377  ** values in the wal-header are correct and (b) the version field is not
 55378  ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
 55379  **
 55380  ** Similarly, if a client successfully reads a wal-index header (i.e. the 
 55381  ** checksum test is successful) and finds that the version field is not
 55382  ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
 55383  ** returns SQLITE_CANTOPEN.
 55384  */
 55385  #define WAL_MAX_VERSION      3007000
 55386  #define WALINDEX_MAX_VERSION 3007000
 55387  
 55388  /*
 55389  ** Indices of various locking bytes.   WAL_NREADER is the number
 55390  ** of available reader locks and should be at least 3.  The default
 55391  ** is SQLITE_SHM_NLOCK==8 and  WAL_NREADER==5.
 55392  */
 55393  #define WAL_WRITE_LOCK         0
 55394  #define WAL_ALL_BUT_WRITE      1
 55395  #define WAL_CKPT_LOCK          1
 55396  #define WAL_RECOVER_LOCK       2
 55397  #define WAL_READ_LOCK(I)       (3+(I))
 55398  #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
 55399  
 55400  
 55401  /* Object declarations */
 55402  typedef struct WalIndexHdr WalIndexHdr;
 55403  typedef struct WalIterator WalIterator;
 55404  typedef struct WalCkptInfo WalCkptInfo;
 55405  
 55406  
 55407  /*
 55408  ** The following object holds a copy of the wal-index header content.
 55409  **
 55410  ** The actual header in the wal-index consists of two copies of this
 55411  ** object followed by one instance of the WalCkptInfo object.
 55412  ** For all versions of SQLite through 3.10.0 and probably beyond,
 55413  ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
 55414  ** the total header size is 136 bytes.
 55415  **
 55416  ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
 55417  ** Or it can be 1 to represent a 65536-byte page.  The latter case was
 55418  ** added in 3.7.1 when support for 64K pages was added.  
 55419  */
 55420  struct WalIndexHdr {
 55421    u32 iVersion;                   /* Wal-index version */
 55422    u32 unused;                     /* Unused (padding) field */
 55423    u32 iChange;                    /* Counter incremented each transaction */
 55424    u8 isInit;                      /* 1 when initialized */
 55425    u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
 55426    u16 szPage;                     /* Database page size in bytes. 1==64K */
 55427    u32 mxFrame;                    /* Index of last valid frame in the WAL */
 55428    u32 nPage;                      /* Size of database in pages */
 55429    u32 aFrameCksum[2];             /* Checksum of last frame in log */
 55430    u32 aSalt[2];                   /* Two salt values copied from WAL header */
 55431    u32 aCksum[2];                  /* Checksum over all prior fields */
 55432  };
 55433  
 55434  /*
 55435  ** A copy of the following object occurs in the wal-index immediately
 55436  ** following the second copy of the WalIndexHdr.  This object stores
 55437  ** information used by checkpoint.
 55438  **
 55439  ** nBackfill is the number of frames in the WAL that have been written
 55440  ** back into the database. (We call the act of moving content from WAL to
 55441  ** database "backfilling".)  The nBackfill number is never greater than
 55442  ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
 55443  ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
 55444  ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
 55445  ** mxFrame back to zero when the WAL is reset.
 55446  **
 55447  ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
 55448  ** has attempted to achieve.  Normally nBackfill==nBackfillAtempted, however
 55449  ** the nBackfillAttempted is set before any backfilling is done and the
 55450  ** nBackfill is only set after all backfilling completes.  So if a checkpoint
 55451  ** crashes, nBackfillAttempted might be larger than nBackfill.  The
 55452  ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
 55453  **
 55454  ** The aLock[] field is a set of bytes used for locking.  These bytes should
 55455  ** never be read or written.
 55456  **
 55457  ** There is one entry in aReadMark[] for each reader lock.  If a reader
 55458  ** holds read-lock K, then the value in aReadMark[K] is no greater than
 55459  ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
 55460  ** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
 55461  ** a special case; its value is never used and it exists as a place-holder
 55462  ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
 55463  ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
 55464  ** directly from the database.
 55465  **
 55466  ** The value of aReadMark[K] may only be changed by a thread that
 55467  ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
 55468  ** aReadMark[K] cannot changed while there is a reader is using that mark
 55469  ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
 55470  **
 55471  ** The checkpointer may only transfer frames from WAL to database where
 55472  ** the frame numbers are less than or equal to every aReadMark[] that is
 55473  ** in use (that is, every aReadMark[j] for which there is a corresponding
 55474  ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
 55475  ** largest value and will increase an unused aReadMark[] to mxFrame if there
 55476  ** is not already an aReadMark[] equal to mxFrame.  The exception to the
 55477  ** previous sentence is when nBackfill equals mxFrame (meaning that everything
 55478  ** in the WAL has been backfilled into the database) then new readers
 55479  ** will choose aReadMark[0] which has value 0 and hence such reader will
 55480  ** get all their all content directly from the database file and ignore 
 55481  ** the WAL.
 55482  **
 55483  ** Writers normally append new frames to the end of the WAL.  However,
 55484  ** if nBackfill equals mxFrame (meaning that all WAL content has been
 55485  ** written back into the database) and if no readers are using the WAL
 55486  ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
 55487  ** the writer will first "reset" the WAL back to the beginning and start
 55488  ** writing new content beginning at frame 1.
 55489  **
 55490  ** We assume that 32-bit loads are atomic and so no locks are needed in
 55491  ** order to read from any aReadMark[] entries.
 55492  */
 55493  struct WalCkptInfo {
 55494    u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
 55495    u32 aReadMark[WAL_NREADER];     /* Reader marks */
 55496    u8 aLock[SQLITE_SHM_NLOCK];     /* Reserved space for locks */
 55497    u32 nBackfillAttempted;         /* WAL frames perhaps written, or maybe not */
 55498    u32 notUsed0;                   /* Available for future enhancements */
 55499  };
 55500  #define READMARK_NOT_USED  0xffffffff
 55501  
 55502  
 55503  /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
 55504  ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
 55505  ** only support mandatory file-locks, we do not read or write data
 55506  ** from the region of the file on which locks are applied.
 55507  */
 55508  #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
 55509  #define WALINDEX_HDR_SIZE    (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
 55510  
 55511  /* Size of header before each frame in wal */
 55512  #define WAL_FRAME_HDRSIZE 24
 55513  
 55514  /* Size of write ahead log header, including checksum. */
 55515  /* #define WAL_HDRSIZE 24 */
 55516  #define WAL_HDRSIZE 32
 55517  
 55518  /* WAL magic value. Either this value, or the same value with the least
 55519  ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
 55520  ** big-endian format in the first 4 bytes of a WAL file.
 55521  **
 55522  ** If the LSB is set, then the checksums for each frame within the WAL
 55523  ** file are calculated by treating all data as an array of 32-bit 
 55524  ** big-endian words. Otherwise, they are calculated by interpreting 
 55525  ** all data as 32-bit little-endian words.
 55526  */
 55527  #define WAL_MAGIC 0x377f0682
 55528  
 55529  /*
 55530  ** Return the offset of frame iFrame in the write-ahead log file, 
 55531  ** assuming a database page size of szPage bytes. The offset returned
 55532  ** is to the start of the write-ahead log frame-header.
 55533  */
 55534  #define walFrameOffset(iFrame, szPage) (                               \
 55535    WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
 55536  )
 55537  
 55538  /*
 55539  ** An open write-ahead log file is represented by an instance of the
 55540  ** following object.
 55541  */
 55542  struct Wal {
 55543    sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
 55544    sqlite3_file *pDbFd;       /* File handle for the database file */
 55545    sqlite3_file *pWalFd;      /* File handle for WAL file */
 55546    u32 iCallback;             /* Value to pass to log callback (or 0) */
 55547    i64 mxWalSize;             /* Truncate WAL to this size upon reset */
 55548    int nWiData;               /* Size of array apWiData */
 55549    int szFirstBlock;          /* Size of first block written to WAL file */
 55550    volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
 55551    u32 szPage;                /* Database page size */
 55552    i16 readLock;              /* Which read lock is being held.  -1 for none */
 55553    u8 syncFlags;              /* Flags to use to sync header writes */
 55554    u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
 55555    u8 writeLock;              /* True if in a write transaction */
 55556    u8 ckptLock;               /* True if holding a checkpoint lock */
 55557    u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
 55558    u8 truncateOnCommit;       /* True to truncate WAL file on commit */
 55559    u8 syncHeader;             /* Fsync the WAL header if true */
 55560    u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
 55561    WalIndexHdr hdr;           /* Wal-index header for current transaction */
 55562    u32 minFrame;              /* Ignore wal frames before this one */
 55563    u32 iReCksum;              /* On commit, recalculate checksums from here */
 55564    const char *zWalName;      /* Name of WAL file */
 55565    u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
 55566  #ifdef SQLITE_DEBUG
 55567    u8 lockError;              /* True if a locking error has occurred */
 55568  #endif
 55569  #ifdef SQLITE_ENABLE_SNAPSHOT
 55570    WalIndexHdr *pSnapshot;    /* Start transaction here if not NULL */
 55571  #endif
 55572  };
 55573  
 55574  /*
 55575  ** Candidate values for Wal.exclusiveMode.
 55576  */
 55577  #define WAL_NORMAL_MODE     0
 55578  #define WAL_EXCLUSIVE_MODE  1     
 55579  #define WAL_HEAPMEMORY_MODE 2
 55580  
 55581  /*
 55582  ** Possible values for WAL.readOnly
 55583  */
 55584  #define WAL_RDWR        0    /* Normal read/write connection */
 55585  #define WAL_RDONLY      1    /* The WAL file is readonly */
 55586  #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
 55587  
 55588  /*
 55589  ** Each page of the wal-index mapping contains a hash-table made up of
 55590  ** an array of HASHTABLE_NSLOT elements of the following type.
 55591  */
 55592  typedef u16 ht_slot;
 55593  
 55594  /*
 55595  ** This structure is used to implement an iterator that loops through
 55596  ** all frames in the WAL in database page order. Where two or more frames
 55597  ** correspond to the same database page, the iterator visits only the 
 55598  ** frame most recently written to the WAL (in other words, the frame with
 55599  ** the largest index).
 55600  **
 55601  ** The internals of this structure are only accessed by:
 55602  **
 55603  **   walIteratorInit() - Create a new iterator,
 55604  **   walIteratorNext() - Step an iterator,
 55605  **   walIteratorFree() - Free an iterator.
 55606  **
 55607  ** This functionality is used by the checkpoint code (see walCheckpoint()).
 55608  */
 55609  struct WalIterator {
 55610    int iPrior;                     /* Last result returned from the iterator */
 55611    int nSegment;                   /* Number of entries in aSegment[] */
 55612    struct WalSegment {
 55613      int iNext;                    /* Next slot in aIndex[] not yet returned */
 55614      ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
 55615      u32 *aPgno;                   /* Array of page numbers. */
 55616      int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
 55617      int iZero;                    /* Frame number associated with aPgno[0] */
 55618    } aSegment[1];                  /* One for every 32KB page in the wal-index */
 55619  };
 55620  
 55621  /*
 55622  ** Define the parameters of the hash tables in the wal-index file. There
 55623  ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
 55624  ** wal-index.
 55625  **
 55626  ** Changing any of these constants will alter the wal-index format and
 55627  ** create incompatibilities.
 55628  */
 55629  #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
 55630  #define HASHTABLE_HASH_1     383                  /* Should be prime */
 55631  #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
 55632  
 55633  /* 
 55634  ** The block of page numbers associated with the first hash-table in a
 55635  ** wal-index is smaller than usual. This is so that there is a complete
 55636  ** hash-table on each aligned 32KB page of the wal-index.
 55637  */
 55638  #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
 55639  
 55640  /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
 55641  #define WALINDEX_PGSZ   (                                         \
 55642      sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
 55643  )
 55644  
 55645  /*
 55646  ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
 55647  ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
 55648  ** numbered from zero.
 55649  **
 55650  ** If this call is successful, *ppPage is set to point to the wal-index
 55651  ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
 55652  ** then an SQLite error code is returned and *ppPage is set to 0.
 55653  */
 55654  static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
 55655    int rc = SQLITE_OK;
 55656  
 55657    /* Enlarge the pWal->apWiData[] array if required */
 55658    if( pWal->nWiData<=iPage ){
 55659      int nByte = sizeof(u32*)*(iPage+1);
 55660      volatile u32 **apNew;
 55661      apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
 55662      if( !apNew ){
 55663        *ppPage = 0;
 55664        return SQLITE_NOMEM_BKPT;
 55665      }
 55666      memset((void*)&apNew[pWal->nWiData], 0,
 55667             sizeof(u32*)*(iPage+1-pWal->nWiData));
 55668      pWal->apWiData = apNew;
 55669      pWal->nWiData = iPage+1;
 55670    }
 55671  
 55672    /* Request a pointer to the required page from the VFS */
 55673    if( pWal->apWiData[iPage]==0 ){
 55674      if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
 55675        pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
 55676        if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
 55677      }else{
 55678        rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
 55679            pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
 55680        );
 55681        if( rc==SQLITE_READONLY ){
 55682          pWal->readOnly |= WAL_SHM_RDONLY;
 55683          rc = SQLITE_OK;
 55684        }
 55685      }
 55686    }
 55687  
 55688    *ppPage = pWal->apWiData[iPage];
 55689    assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
 55690    return rc;
 55691  }
 55692  
 55693  /*
 55694  ** Return a pointer to the WalCkptInfo structure in the wal-index.
 55695  */
 55696  static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
 55697    assert( pWal->nWiData>0 && pWal->apWiData[0] );
 55698    return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
 55699  }
 55700  
 55701  /*
 55702  ** Return a pointer to the WalIndexHdr structure in the wal-index.
 55703  */
 55704  static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
 55705    assert( pWal->nWiData>0 && pWal->apWiData[0] );
 55706    return (volatile WalIndexHdr*)pWal->apWiData[0];
 55707  }
 55708  
 55709  /*
 55710  ** The argument to this macro must be of type u32. On a little-endian
 55711  ** architecture, it returns the u32 value that results from interpreting
 55712  ** the 4 bytes as a big-endian value. On a big-endian architecture, it
 55713  ** returns the value that would be produced by interpreting the 4 bytes
 55714  ** of the input value as a little-endian integer.
 55715  */
 55716  #define BYTESWAP32(x) ( \
 55717      (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
 55718    + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
 55719  )
 55720  
 55721  /*
 55722  ** Generate or extend an 8 byte checksum based on the data in 
 55723  ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
 55724  ** initial values of 0 and 0 if aIn==NULL).
 55725  **
 55726  ** The checksum is written back into aOut[] before returning.
 55727  **
 55728  ** nByte must be a positive multiple of 8.
 55729  */
 55730  static void walChecksumBytes(
 55731    int nativeCksum, /* True for native byte-order, false for non-native */
 55732    u8 *a,           /* Content to be checksummed */
 55733    int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
 55734    const u32 *aIn,  /* Initial checksum value input */
 55735    u32 *aOut        /* OUT: Final checksum value output */
 55736  ){
 55737    u32 s1, s2;
 55738    u32 *aData = (u32 *)a;
 55739    u32 *aEnd = (u32 *)&a[nByte];
 55740  
 55741    if( aIn ){
 55742      s1 = aIn[0];
 55743      s2 = aIn[1];
 55744    }else{
 55745      s1 = s2 = 0;
 55746    }
 55747  
 55748    assert( nByte>=8 );
 55749    assert( (nByte&0x00000007)==0 );
 55750  
 55751    if( nativeCksum ){
 55752      do {
 55753        s1 += *aData++ + s2;
 55754        s2 += *aData++ + s1;
 55755      }while( aData<aEnd );
 55756    }else{
 55757      do {
 55758        s1 += BYTESWAP32(aData[0]) + s2;
 55759        s2 += BYTESWAP32(aData[1]) + s1;
 55760        aData += 2;
 55761      }while( aData<aEnd );
 55762    }
 55763  
 55764    aOut[0] = s1;
 55765    aOut[1] = s2;
 55766  }
 55767  
 55768  static void walShmBarrier(Wal *pWal){
 55769    if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
 55770      sqlite3OsShmBarrier(pWal->pDbFd);
 55771    }
 55772  }
 55773  
 55774  /*
 55775  ** Write the header information in pWal->hdr into the wal-index.
 55776  **
 55777  ** The checksum on pWal->hdr is updated before it is written.
 55778  */
 55779  static void walIndexWriteHdr(Wal *pWal){
 55780    volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
 55781    const int nCksum = offsetof(WalIndexHdr, aCksum);
 55782  
 55783    assert( pWal->writeLock );
 55784    pWal->hdr.isInit = 1;
 55785    pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
 55786    walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
 55787    memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
 55788    walShmBarrier(pWal);
 55789    memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
 55790  }
 55791  
 55792  /*
 55793  ** This function encodes a single frame header and writes it to a buffer
 55794  ** supplied by the caller. A frame-header is made up of a series of 
 55795  ** 4-byte big-endian integers, as follows:
 55796  **
 55797  **     0: Page number.
 55798  **     4: For commit records, the size of the database image in pages 
 55799  **        after the commit. For all other records, zero.
 55800  **     8: Salt-1 (copied from the wal-header)
 55801  **    12: Salt-2 (copied from the wal-header)
 55802  **    16: Checksum-1.
 55803  **    20: Checksum-2.
 55804  */
 55805  static void walEncodeFrame(
 55806    Wal *pWal,                      /* The write-ahead log */
 55807    u32 iPage,                      /* Database page number for frame */
 55808    u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
 55809    u8 *aData,                      /* Pointer to page data */
 55810    u8 *aFrame                      /* OUT: Write encoded frame here */
 55811  ){
 55812    int nativeCksum;                /* True for native byte-order checksums */
 55813    u32 *aCksum = pWal->hdr.aFrameCksum;
 55814    assert( WAL_FRAME_HDRSIZE==24 );
 55815    sqlite3Put4byte(&aFrame[0], iPage);
 55816    sqlite3Put4byte(&aFrame[4], nTruncate);
 55817    if( pWal->iReCksum==0 ){
 55818      memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
 55819  
 55820      nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
 55821      walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
 55822      walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
 55823  
 55824      sqlite3Put4byte(&aFrame[16], aCksum[0]);
 55825      sqlite3Put4byte(&aFrame[20], aCksum[1]);
 55826    }else{
 55827      memset(&aFrame[8], 0, 16);
 55828    }
 55829  }
 55830  
 55831  /*
 55832  ** Check to see if the frame with header in aFrame[] and content
 55833  ** in aData[] is valid.  If it is a valid frame, fill *piPage and
 55834  ** *pnTruncate and return true.  Return if the frame is not valid.
 55835  */
 55836  static int walDecodeFrame(
 55837    Wal *pWal,                      /* The write-ahead log */
 55838    u32 *piPage,                    /* OUT: Database page number for frame */
 55839    u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
 55840    u8 *aData,                      /* Pointer to page data (for checksum) */
 55841    u8 *aFrame                      /* Frame data */
 55842  ){
 55843    int nativeCksum;                /* True for native byte-order checksums */
 55844    u32 *aCksum = pWal->hdr.aFrameCksum;
 55845    u32 pgno;                       /* Page number of the frame */
 55846    assert( WAL_FRAME_HDRSIZE==24 );
 55847  
 55848    /* A frame is only valid if the salt values in the frame-header
 55849    ** match the salt values in the wal-header. 
 55850    */
 55851    if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
 55852      return 0;
 55853    }
 55854  
 55855    /* A frame is only valid if the page number is creater than zero.
 55856    */
 55857    pgno = sqlite3Get4byte(&aFrame[0]);
 55858    if( pgno==0 ){
 55859      return 0;
 55860    }
 55861  
 55862    /* A frame is only valid if a checksum of the WAL header,
 55863    ** all prior frams, the first 16 bytes of this frame-header, 
 55864    ** and the frame-data matches the checksum in the last 8 
 55865    ** bytes of this frame-header.
 55866    */
 55867    nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
 55868    walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
 55869    walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
 55870    if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) 
 55871     || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) 
 55872    ){
 55873      /* Checksum failed. */
 55874      return 0;
 55875    }
 55876  
 55877    /* If we reach this point, the frame is valid.  Return the page number
 55878    ** and the new database size.
 55879    */
 55880    *piPage = pgno;
 55881    *pnTruncate = sqlite3Get4byte(&aFrame[4]);
 55882    return 1;
 55883  }
 55884  
 55885  
 55886  #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
 55887  /*
 55888  ** Names of locks.  This routine is used to provide debugging output and is not
 55889  ** a part of an ordinary build.
 55890  */
 55891  static const char *walLockName(int lockIdx){
 55892    if( lockIdx==WAL_WRITE_LOCK ){
 55893      return "WRITE-LOCK";
 55894    }else if( lockIdx==WAL_CKPT_LOCK ){
 55895      return "CKPT-LOCK";
 55896    }else if( lockIdx==WAL_RECOVER_LOCK ){
 55897      return "RECOVER-LOCK";
 55898    }else{
 55899      static char zName[15];
 55900      sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
 55901                       lockIdx-WAL_READ_LOCK(0));
 55902      return zName;
 55903    }
 55904  }
 55905  #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
 55906      
 55907  
 55908  /*
 55909  ** Set or release locks on the WAL.  Locks are either shared or exclusive.
 55910  ** A lock cannot be moved directly between shared and exclusive - it must go
 55911  ** through the unlocked state first.
 55912  **
 55913  ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
 55914  */
 55915  static int walLockShared(Wal *pWal, int lockIdx){
 55916    int rc;
 55917    if( pWal->exclusiveMode ) return SQLITE_OK;
 55918    rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
 55919                          SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
 55920    WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
 55921              walLockName(lockIdx), rc ? "failed" : "ok"));
 55922    VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
 55923    return rc;
 55924  }
 55925  static void walUnlockShared(Wal *pWal, int lockIdx){
 55926    if( pWal->exclusiveMode ) return;
 55927    (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
 55928                           SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
 55929    WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
 55930  }
 55931  static int walLockExclusive(Wal *pWal, int lockIdx, int n){
 55932    int rc;
 55933    if( pWal->exclusiveMode ) return SQLITE_OK;
 55934    rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
 55935                          SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
 55936    WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
 55937              walLockName(lockIdx), n, rc ? "failed" : "ok"));
 55938    VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
 55939    return rc;
 55940  }
 55941  static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
 55942    if( pWal->exclusiveMode ) return;
 55943    (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
 55944                           SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
 55945    WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
 55946               walLockName(lockIdx), n));
 55947  }
 55948  
 55949  /*
 55950  ** Compute a hash on a page number.  The resulting hash value must land
 55951  ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
 55952  ** the hash to the next value in the event of a collision.
 55953  */
 55954  static int walHash(u32 iPage){
 55955    assert( iPage>0 );
 55956    assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
 55957    return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
 55958  }
 55959  static int walNextHash(int iPriorHash){
 55960    return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
 55961  }
 55962  
 55963  /* 
 55964  ** Return pointers to the hash table and page number array stored on
 55965  ** page iHash of the wal-index. The wal-index is broken into 32KB pages
 55966  ** numbered starting from 0.
 55967  **
 55968  ** Set output variable *paHash to point to the start of the hash table
 55969  ** in the wal-index file. Set *piZero to one less than the frame 
 55970  ** number of the first frame indexed by this hash table. If a
 55971  ** slot in the hash table is set to N, it refers to frame number 
 55972  ** (*piZero+N) in the log.
 55973  **
 55974  ** Finally, set *paPgno so that *paPgno[1] is the page number of the
 55975  ** first frame indexed by the hash table, frame (*piZero+1).
 55976  */
 55977  static int walHashGet(
 55978    Wal *pWal,                      /* WAL handle */
 55979    int iHash,                      /* Find the iHash'th table */
 55980    volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
 55981    volatile u32 **paPgno,          /* OUT: Pointer to page number array */
 55982    u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
 55983  ){
 55984    int rc;                         /* Return code */
 55985    volatile u32 *aPgno;
 55986  
 55987    rc = walIndexPage(pWal, iHash, &aPgno);
 55988    assert( rc==SQLITE_OK || iHash>0 );
 55989  
 55990    if( rc==SQLITE_OK ){
 55991      u32 iZero;
 55992      volatile ht_slot *aHash;
 55993  
 55994      aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
 55995      if( iHash==0 ){
 55996        aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
 55997        iZero = 0;
 55998      }else{
 55999        iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
 56000      }
 56001    
 56002      *paPgno = &aPgno[-1];
 56003      *paHash = aHash;
 56004      *piZero = iZero;
 56005    }
 56006    return rc;
 56007  }
 56008  
 56009  /*
 56010  ** Return the number of the wal-index page that contains the hash-table
 56011  ** and page-number array that contain entries corresponding to WAL frame
 56012  ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
 56013  ** are numbered starting from 0.
 56014  */
 56015  static int walFramePage(u32 iFrame){
 56016    int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
 56017    assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
 56018         && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
 56019         && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
 56020         && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
 56021         && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
 56022    );
 56023    return iHash;
 56024  }
 56025  
 56026  /*
 56027  ** Return the page number associated with frame iFrame in this WAL.
 56028  */
 56029  static u32 walFramePgno(Wal *pWal, u32 iFrame){
 56030    int iHash = walFramePage(iFrame);
 56031    if( iHash==0 ){
 56032      return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
 56033    }
 56034    return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
 56035  }
 56036  
 56037  /*
 56038  ** Remove entries from the hash table that point to WAL slots greater
 56039  ** than pWal->hdr.mxFrame.
 56040  **
 56041  ** This function is called whenever pWal->hdr.mxFrame is decreased due
 56042  ** to a rollback or savepoint.
 56043  **
 56044  ** At most only the hash table containing pWal->hdr.mxFrame needs to be
 56045  ** updated.  Any later hash tables will be automatically cleared when
 56046  ** pWal->hdr.mxFrame advances to the point where those hash tables are
 56047  ** actually needed.
 56048  */
 56049  static void walCleanupHash(Wal *pWal){
 56050    volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
 56051    volatile u32 *aPgno = 0;        /* Page number array for hash table */
 56052    u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
 56053    int iLimit = 0;                 /* Zero values greater than this */
 56054    int nByte;                      /* Number of bytes to zero in aPgno[] */
 56055    int i;                          /* Used to iterate through aHash[] */
 56056  
 56057    assert( pWal->writeLock );
 56058    testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
 56059    testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
 56060    testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
 56061  
 56062    if( pWal->hdr.mxFrame==0 ) return;
 56063  
 56064    /* Obtain pointers to the hash-table and page-number array containing 
 56065    ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
 56066    ** that the page said hash-table and array reside on is already mapped.
 56067    */
 56068    assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
 56069    assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
 56070    walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
 56071  
 56072    /* Zero all hash-table entries that correspond to frame numbers greater
 56073    ** than pWal->hdr.mxFrame.
 56074    */
 56075    iLimit = pWal->hdr.mxFrame - iZero;
 56076    assert( iLimit>0 );
 56077    for(i=0; i<HASHTABLE_NSLOT; i++){
 56078      if( aHash[i]>iLimit ){
 56079        aHash[i] = 0;
 56080      }
 56081    }
 56082    
 56083    /* Zero the entries in the aPgno array that correspond to frames with
 56084    ** frame numbers greater than pWal->hdr.mxFrame. 
 56085    */
 56086    nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
 56087    memset((void *)&aPgno[iLimit+1], 0, nByte);
 56088  
 56089  #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
 56090    /* Verify that the every entry in the mapping region is still reachable
 56091    ** via the hash table even after the cleanup.
 56092    */
 56093    if( iLimit ){
 56094      int j;           /* Loop counter */
 56095      int iKey;        /* Hash key */
 56096      for(j=1; j<=iLimit; j++){
 56097        for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
 56098          if( aHash[iKey]==j ) break;
 56099        }
 56100        assert( aHash[iKey]==j );
 56101      }
 56102    }
 56103  #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
 56104  }
 56105  
 56106  
 56107  /*
 56108  ** Set an entry in the wal-index that will map database page number
 56109  ** pPage into WAL frame iFrame.
 56110  */
 56111  static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
 56112    int rc;                         /* Return code */
 56113    u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
 56114    volatile u32 *aPgno = 0;        /* Page number array */
 56115    volatile ht_slot *aHash = 0;    /* Hash table */
 56116  
 56117    rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
 56118  
 56119    /* Assuming the wal-index file was successfully mapped, populate the
 56120    ** page number array and hash table entry.
 56121    */
 56122    if( rc==SQLITE_OK ){
 56123      int iKey;                     /* Hash table key */
 56124      int idx;                      /* Value to write to hash-table slot */
 56125      int nCollide;                 /* Number of hash collisions */
 56126  
 56127      idx = iFrame - iZero;
 56128      assert( idx <= HASHTABLE_NSLOT/2 + 1 );
 56129      
 56130      /* If this is the first entry to be added to this hash-table, zero the
 56131      ** entire hash table and aPgno[] array before proceeding. 
 56132      */
 56133      if( idx==1 ){
 56134        int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
 56135        memset((void*)&aPgno[1], 0, nByte);
 56136      }
 56137  
 56138      /* If the entry in aPgno[] is already set, then the previous writer
 56139      ** must have exited unexpectedly in the middle of a transaction (after
 56140      ** writing one or more dirty pages to the WAL to free up memory). 
 56141      ** Remove the remnants of that writers uncommitted transaction from 
 56142      ** the hash-table before writing any new entries.
 56143      */
 56144      if( aPgno[idx] ){
 56145        walCleanupHash(pWal);
 56146        assert( !aPgno[idx] );
 56147      }
 56148  
 56149      /* Write the aPgno[] array entry and the hash-table slot. */
 56150      nCollide = idx;
 56151      for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
 56152        if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
 56153      }
 56154      aPgno[idx] = iPage;
 56155      aHash[iKey] = (ht_slot)idx;
 56156  
 56157  #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
 56158      /* Verify that the number of entries in the hash table exactly equals
 56159      ** the number of entries in the mapping region.
 56160      */
 56161      {
 56162        int i;           /* Loop counter */
 56163        int nEntry = 0;  /* Number of entries in the hash table */
 56164        for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
 56165        assert( nEntry==idx );
 56166      }
 56167  
 56168      /* Verify that the every entry in the mapping region is reachable
 56169      ** via the hash table.  This turns out to be a really, really expensive
 56170      ** thing to check, so only do this occasionally - not on every
 56171      ** iteration.
 56172      */
 56173      if( (idx&0x3ff)==0 ){
 56174        int i;           /* Loop counter */
 56175        for(i=1; i<=idx; i++){
 56176          for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
 56177            if( aHash[iKey]==i ) break;
 56178          }
 56179          assert( aHash[iKey]==i );
 56180        }
 56181      }
 56182  #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
 56183    }
 56184  
 56185  
 56186    return rc;
 56187  }
 56188  
 56189  
 56190  /*
 56191  ** Recover the wal-index by reading the write-ahead log file. 
 56192  **
 56193  ** This routine first tries to establish an exclusive lock on the
 56194  ** wal-index to prevent other threads/processes from doing anything
 56195  ** with the WAL or wal-index while recovery is running.  The
 56196  ** WAL_RECOVER_LOCK is also held so that other threads will know
 56197  ** that this thread is running recovery.  If unable to establish
 56198  ** the necessary locks, this routine returns SQLITE_BUSY.
 56199  */
 56200  static int walIndexRecover(Wal *pWal){
 56201    int rc;                         /* Return Code */
 56202    i64 nSize;                      /* Size of log file */
 56203    u32 aFrameCksum[2] = {0, 0};
 56204    int iLock;                      /* Lock offset to lock for checkpoint */
 56205    int nLock;                      /* Number of locks to hold */
 56206  
 56207    /* Obtain an exclusive lock on all byte in the locking range not already
 56208    ** locked by the caller. The caller is guaranteed to have locked the
 56209    ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
 56210    ** If successful, the same bytes that are locked here are unlocked before
 56211    ** this function returns.
 56212    */
 56213    assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
 56214    assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
 56215    assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
 56216    assert( pWal->writeLock );
 56217    iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
 56218    nLock = SQLITE_SHM_NLOCK - iLock;
 56219    rc = walLockExclusive(pWal, iLock, nLock);
 56220    if( rc ){
 56221      return rc;
 56222    }
 56223    WALTRACE(("WAL%p: recovery begin...\n", pWal));
 56224  
 56225    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
 56226  
 56227    rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
 56228    if( rc!=SQLITE_OK ){
 56229      goto recovery_error;
 56230    }
 56231  
 56232    if( nSize>WAL_HDRSIZE ){
 56233      u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
 56234      u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
 56235      int szFrame;                  /* Number of bytes in buffer aFrame[] */
 56236      u8 *aData;                    /* Pointer to data part of aFrame buffer */
 56237      int iFrame;                   /* Index of last frame read */
 56238      i64 iOffset;                  /* Next offset to read from log file */
 56239      int szPage;                   /* Page size according to the log */
 56240      u32 magic;                    /* Magic value read from WAL header */
 56241      u32 version;                  /* Magic value read from WAL header */
 56242      int isValid;                  /* True if this frame is valid */
 56243  
 56244      /* Read in the WAL header. */
 56245      rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
 56246      if( rc!=SQLITE_OK ){
 56247        goto recovery_error;
 56248      }
 56249  
 56250      /* If the database page size is not a power of two, or is greater than
 56251      ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
 56252      ** data. Similarly, if the 'magic' value is invalid, ignore the whole
 56253      ** WAL file.
 56254      */
 56255      magic = sqlite3Get4byte(&aBuf[0]);
 56256      szPage = sqlite3Get4byte(&aBuf[8]);
 56257      if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
 56258       || szPage&(szPage-1) 
 56259       || szPage>SQLITE_MAX_PAGE_SIZE 
 56260       || szPage<512 
 56261      ){
 56262        goto finished;
 56263      }
 56264      pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
 56265      pWal->szPage = szPage;
 56266      pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
 56267      memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
 56268  
 56269      /* Verify that the WAL header checksum is correct */
 56270      walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
 56271          aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
 56272      );
 56273      if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
 56274       || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
 56275      ){
 56276        goto finished;
 56277      }
 56278  
 56279      /* Verify that the version number on the WAL format is one that
 56280      ** are able to understand */
 56281      version = sqlite3Get4byte(&aBuf[4]);
 56282      if( version!=WAL_MAX_VERSION ){
 56283        rc = SQLITE_CANTOPEN_BKPT;
 56284        goto finished;
 56285      }
 56286  
 56287      /* Malloc a buffer to read frames into. */
 56288      szFrame = szPage + WAL_FRAME_HDRSIZE;
 56289      aFrame = (u8 *)sqlite3_malloc64(szFrame);
 56290      if( !aFrame ){
 56291        rc = SQLITE_NOMEM_BKPT;
 56292        goto recovery_error;
 56293      }
 56294      aData = &aFrame[WAL_FRAME_HDRSIZE];
 56295  
 56296      /* Read all frames from the log file. */
 56297      iFrame = 0;
 56298      for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
 56299        u32 pgno;                   /* Database page number for frame */
 56300        u32 nTruncate;              /* dbsize field from frame header */
 56301  
 56302        /* Read and decode the next log frame. */
 56303        iFrame++;
 56304        rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
 56305        if( rc!=SQLITE_OK ) break;
 56306        isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
 56307        if( !isValid ) break;
 56308        rc = walIndexAppend(pWal, iFrame, pgno);
 56309        if( rc!=SQLITE_OK ) break;
 56310  
 56311        /* If nTruncate is non-zero, this is a commit record. */
 56312        if( nTruncate ){
 56313          pWal->hdr.mxFrame = iFrame;
 56314          pWal->hdr.nPage = nTruncate;
 56315          pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
 56316          testcase( szPage<=32768 );
 56317          testcase( szPage>=65536 );
 56318          aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
 56319          aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
 56320        }
 56321      }
 56322  
 56323      sqlite3_free(aFrame);
 56324    }
 56325  
 56326  finished:
 56327    if( rc==SQLITE_OK ){
 56328      volatile WalCkptInfo *pInfo;
 56329      int i;
 56330      pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
 56331      pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
 56332      walIndexWriteHdr(pWal);
 56333  
 56334      /* Reset the checkpoint-header. This is safe because this thread is 
 56335      ** currently holding locks that exclude all other readers, writers and
 56336      ** checkpointers.
 56337      */
 56338      pInfo = walCkptInfo(pWal);
 56339      pInfo->nBackfill = 0;
 56340      pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
 56341      pInfo->aReadMark[0] = 0;
 56342      for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
 56343      if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
 56344  
 56345      /* If more than one frame was recovered from the log file, report an
 56346      ** event via sqlite3_log(). This is to help with identifying performance
 56347      ** problems caused by applications routinely shutting down without
 56348      ** checkpointing the log file.
 56349      */
 56350      if( pWal->hdr.nPage ){
 56351        sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
 56352            "recovered %d frames from WAL file %s",
 56353            pWal->hdr.mxFrame, pWal->zWalName
 56354        );
 56355      }
 56356    }
 56357  
 56358  recovery_error:
 56359    WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
 56360    walUnlockExclusive(pWal, iLock, nLock);
 56361    return rc;
 56362  }
 56363  
 56364  /*
 56365  ** Close an open wal-index.
 56366  */
 56367  static void walIndexClose(Wal *pWal, int isDelete){
 56368    if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
 56369      int i;
 56370      for(i=0; i<pWal->nWiData; i++){
 56371        sqlite3_free((void *)pWal->apWiData[i]);
 56372        pWal->apWiData[i] = 0;
 56373      }
 56374    }else{
 56375      sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
 56376    }
 56377  }
 56378  
 56379  /* 
 56380  ** Open a connection to the WAL file zWalName. The database file must 
 56381  ** already be opened on connection pDbFd. The buffer that zWalName points
 56382  ** to must remain valid for the lifetime of the returned Wal* handle.
 56383  **
 56384  ** A SHARED lock should be held on the database file when this function
 56385  ** is called. The purpose of this SHARED lock is to prevent any other
 56386  ** client from unlinking the WAL or wal-index file. If another process
 56387  ** were to do this just after this client opened one of these files, the
 56388  ** system would be badly broken.
 56389  **
 56390  ** If the log file is successfully opened, SQLITE_OK is returned and 
 56391  ** *ppWal is set to point to a new WAL handle. If an error occurs,
 56392  ** an SQLite error code is returned and *ppWal is left unmodified.
 56393  */
 56394  SQLITE_PRIVATE int sqlite3WalOpen(
 56395    sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
 56396    sqlite3_file *pDbFd,            /* The open database file */
 56397    const char *zWalName,           /* Name of the WAL file */
 56398    int bNoShm,                     /* True to run in heap-memory mode */
 56399    i64 mxWalSize,                  /* Truncate WAL to this size on reset */
 56400    Wal **ppWal                     /* OUT: Allocated Wal handle */
 56401  ){
 56402    int rc;                         /* Return Code */
 56403    Wal *pRet;                      /* Object to allocate and return */
 56404    int flags;                      /* Flags passed to OsOpen() */
 56405  
 56406    assert( zWalName && zWalName[0] );
 56407    assert( pDbFd );
 56408  
 56409    /* In the amalgamation, the os_unix.c and os_win.c source files come before
 56410    ** this source file.  Verify that the #defines of the locking byte offsets
 56411    ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
 56412    ** For that matter, if the lock offset ever changes from its initial design
 56413    ** value of 120, we need to know that so there is an assert() to check it.
 56414    */
 56415    assert( 120==WALINDEX_LOCK_OFFSET );
 56416    assert( 136==WALINDEX_HDR_SIZE );
 56417  #ifdef WIN_SHM_BASE
 56418    assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
 56419  #endif
 56420  #ifdef UNIX_SHM_BASE
 56421    assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
 56422  #endif
 56423  
 56424  
 56425    /* Allocate an instance of struct Wal to return. */
 56426    *ppWal = 0;
 56427    pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
 56428    if( !pRet ){
 56429      return SQLITE_NOMEM_BKPT;
 56430    }
 56431  
 56432    pRet->pVfs = pVfs;
 56433    pRet->pWalFd = (sqlite3_file *)&pRet[1];
 56434    pRet->pDbFd = pDbFd;
 56435    pRet->readLock = -1;
 56436    pRet->mxWalSize = mxWalSize;
 56437    pRet->zWalName = zWalName;
 56438    pRet->syncHeader = 1;
 56439    pRet->padToSectorBoundary = 1;
 56440    pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
 56441  
 56442    /* Open file handle on the write-ahead log file. */
 56443    flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
 56444    rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
 56445    if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
 56446      pRet->readOnly = WAL_RDONLY;
 56447    }
 56448  
 56449    if( rc!=SQLITE_OK ){
 56450      walIndexClose(pRet, 0);
 56451      sqlite3OsClose(pRet->pWalFd);
 56452      sqlite3_free(pRet);
 56453    }else{
 56454      int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
 56455      if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
 56456      if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
 56457        pRet->padToSectorBoundary = 0;
 56458      }
 56459      *ppWal = pRet;
 56460      WALTRACE(("WAL%d: opened\n", pRet));
 56461    }
 56462    return rc;
 56463  }
 56464  
 56465  /*
 56466  ** Change the size to which the WAL file is trucated on each reset.
 56467  */
 56468  SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
 56469    if( pWal ) pWal->mxWalSize = iLimit;
 56470  }
 56471  
 56472  /*
 56473  ** Find the smallest page number out of all pages held in the WAL that
 56474  ** has not been returned by any prior invocation of this method on the
 56475  ** same WalIterator object.   Write into *piFrame the frame index where
 56476  ** that page was last written into the WAL.  Write into *piPage the page
 56477  ** number.
 56478  **
 56479  ** Return 0 on success.  If there are no pages in the WAL with a page
 56480  ** number larger than *piPage, then return 1.
 56481  */
 56482  static int walIteratorNext(
 56483    WalIterator *p,               /* Iterator */
 56484    u32 *piPage,                  /* OUT: The page number of the next page */
 56485    u32 *piFrame                  /* OUT: Wal frame index of next page */
 56486  ){
 56487    u32 iMin;                     /* Result pgno must be greater than iMin */
 56488    u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
 56489    int i;                        /* For looping through segments */
 56490  
 56491    iMin = p->iPrior;
 56492    assert( iMin<0xffffffff );
 56493    for(i=p->nSegment-1; i>=0; i--){
 56494      struct WalSegment *pSegment = &p->aSegment[i];
 56495      while( pSegment->iNext<pSegment->nEntry ){
 56496        u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
 56497        if( iPg>iMin ){
 56498          if( iPg<iRet ){
 56499            iRet = iPg;
 56500            *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
 56501          }
 56502          break;
 56503        }
 56504        pSegment->iNext++;
 56505      }
 56506    }
 56507  
 56508    *piPage = p->iPrior = iRet;
 56509    return (iRet==0xFFFFFFFF);
 56510  }
 56511  
 56512  /*
 56513  ** This function merges two sorted lists into a single sorted list.
 56514  **
 56515  ** aLeft[] and aRight[] are arrays of indices.  The sort key is
 56516  ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
 56517  ** is guaranteed for all J<K:
 56518  **
 56519  **        aContent[aLeft[J]] < aContent[aLeft[K]]
 56520  **        aContent[aRight[J]] < aContent[aRight[K]]
 56521  **
 56522  ** This routine overwrites aRight[] with a new (probably longer) sequence
 56523  ** of indices such that the aRight[] contains every index that appears in
 56524  ** either aLeft[] or the old aRight[] and such that the second condition
 56525  ** above is still met.
 56526  **
 56527  ** The aContent[aLeft[X]] values will be unique for all X.  And the
 56528  ** aContent[aRight[X]] values will be unique too.  But there might be
 56529  ** one or more combinations of X and Y such that
 56530  **
 56531  **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
 56532  **
 56533  ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
 56534  */
 56535  static void walMerge(
 56536    const u32 *aContent,            /* Pages in wal - keys for the sort */
 56537    ht_slot *aLeft,                 /* IN: Left hand input list */
 56538    int nLeft,                      /* IN: Elements in array *paLeft */
 56539    ht_slot **paRight,              /* IN/OUT: Right hand input list */
 56540    int *pnRight,                   /* IN/OUT: Elements in *paRight */
 56541    ht_slot *aTmp                   /* Temporary buffer */
 56542  ){
 56543    int iLeft = 0;                  /* Current index in aLeft */
 56544    int iRight = 0;                 /* Current index in aRight */
 56545    int iOut = 0;                   /* Current index in output buffer */
 56546    int nRight = *pnRight;
 56547    ht_slot *aRight = *paRight;
 56548  
 56549    assert( nLeft>0 && nRight>0 );
 56550    while( iRight<nRight || iLeft<nLeft ){
 56551      ht_slot logpage;
 56552      Pgno dbpage;
 56553  
 56554      if( (iLeft<nLeft) 
 56555       && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
 56556      ){
 56557        logpage = aLeft[iLeft++];
 56558      }else{
 56559        logpage = aRight[iRight++];
 56560      }
 56561      dbpage = aContent[logpage];
 56562  
 56563      aTmp[iOut++] = logpage;
 56564      if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
 56565  
 56566      assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
 56567      assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
 56568    }
 56569  
 56570    *paRight = aLeft;
 56571    *pnRight = iOut;
 56572    memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
 56573  }
 56574  
 56575  /*
 56576  ** Sort the elements in list aList using aContent[] as the sort key.
 56577  ** Remove elements with duplicate keys, preferring to keep the
 56578  ** larger aList[] values.
 56579  **
 56580  ** The aList[] entries are indices into aContent[].  The values in
 56581  ** aList[] are to be sorted so that for all J<K:
 56582  **
 56583  **      aContent[aList[J]] < aContent[aList[K]]
 56584  **
 56585  ** For any X and Y such that
 56586  **
 56587  **      aContent[aList[X]] == aContent[aList[Y]]
 56588  **
 56589  ** Keep the larger of the two values aList[X] and aList[Y] and discard
 56590  ** the smaller.
 56591  */
 56592  static void walMergesort(
 56593    const u32 *aContent,            /* Pages in wal */
 56594    ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
 56595    ht_slot *aList,                 /* IN/OUT: List to sort */
 56596    int *pnList                     /* IN/OUT: Number of elements in aList[] */
 56597  ){
 56598    struct Sublist {
 56599      int nList;                    /* Number of elements in aList */
 56600      ht_slot *aList;               /* Pointer to sub-list content */
 56601    };
 56602  
 56603    const int nList = *pnList;      /* Size of input list */
 56604    int nMerge = 0;                 /* Number of elements in list aMerge */
 56605    ht_slot *aMerge = 0;            /* List to be merged */
 56606    int iList;                      /* Index into input list */
 56607    u32 iSub = 0;                   /* Index into aSub array */
 56608    struct Sublist aSub[13];        /* Array of sub-lists */
 56609  
 56610    memset(aSub, 0, sizeof(aSub));
 56611    assert( nList<=HASHTABLE_NPAGE && nList>0 );
 56612    assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
 56613  
 56614    for(iList=0; iList<nList; iList++){
 56615      nMerge = 1;
 56616      aMerge = &aList[iList];
 56617      for(iSub=0; iList & (1<<iSub); iSub++){
 56618        struct Sublist *p;
 56619        assert( iSub<ArraySize(aSub) );
 56620        p = &aSub[iSub];
 56621        assert( p->aList && p->nList<=(1<<iSub) );
 56622        assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
 56623        walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
 56624      }
 56625      aSub[iSub].aList = aMerge;
 56626      aSub[iSub].nList = nMerge;
 56627    }
 56628  
 56629    for(iSub++; iSub<ArraySize(aSub); iSub++){
 56630      if( nList & (1<<iSub) ){
 56631        struct Sublist *p;
 56632        assert( iSub<ArraySize(aSub) );
 56633        p = &aSub[iSub];
 56634        assert( p->nList<=(1<<iSub) );
 56635        assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
 56636        walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
 56637      }
 56638    }
 56639    assert( aMerge==aList );
 56640    *pnList = nMerge;
 56641  
 56642  #ifdef SQLITE_DEBUG
 56643    {
 56644      int i;
 56645      for(i=1; i<*pnList; i++){
 56646        assert( aContent[aList[i]] > aContent[aList[i-1]] );
 56647      }
 56648    }
 56649  #endif
 56650  }
 56651  
 56652  /* 
 56653  ** Free an iterator allocated by walIteratorInit().
 56654  */
 56655  static void walIteratorFree(WalIterator *p){
 56656    sqlite3_free(p);
 56657  }
 56658  
 56659  /*
 56660  ** Construct a WalInterator object that can be used to loop over all 
 56661  ** pages in the WAL in ascending order. The caller must hold the checkpoint
 56662  ** lock.
 56663  **
 56664  ** On success, make *pp point to the newly allocated WalInterator object
 56665  ** return SQLITE_OK. Otherwise, return an error code. If this routine
 56666  ** returns an error, the value of *pp is undefined.
 56667  **
 56668  ** The calling routine should invoke walIteratorFree() to destroy the
 56669  ** WalIterator object when it has finished with it.
 56670  */
 56671  static int walIteratorInit(Wal *pWal, WalIterator **pp){
 56672    WalIterator *p;                 /* Return value */
 56673    int nSegment;                   /* Number of segments to merge */
 56674    u32 iLast;                      /* Last frame in log */
 56675    int nByte;                      /* Number of bytes to allocate */
 56676    int i;                          /* Iterator variable */
 56677    ht_slot *aTmp;                  /* Temp space used by merge-sort */
 56678    int rc = SQLITE_OK;             /* Return Code */
 56679  
 56680    /* This routine only runs while holding the checkpoint lock. And
 56681    ** it only runs if there is actually content in the log (mxFrame>0).
 56682    */
 56683    assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
 56684    iLast = pWal->hdr.mxFrame;
 56685  
 56686    /* Allocate space for the WalIterator object. */
 56687    nSegment = walFramePage(iLast) + 1;
 56688    nByte = sizeof(WalIterator) 
 56689          + (nSegment-1)*sizeof(struct WalSegment)
 56690          + iLast*sizeof(ht_slot);
 56691    p = (WalIterator *)sqlite3_malloc64(nByte);
 56692    if( !p ){
 56693      return SQLITE_NOMEM_BKPT;
 56694    }
 56695    memset(p, 0, nByte);
 56696    p->nSegment = nSegment;
 56697  
 56698    /* Allocate temporary space used by the merge-sort routine. This block
 56699    ** of memory will be freed before this function returns.
 56700    */
 56701    aTmp = (ht_slot *)sqlite3_malloc64(
 56702        sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
 56703    );
 56704    if( !aTmp ){
 56705      rc = SQLITE_NOMEM_BKPT;
 56706    }
 56707  
 56708    for(i=0; rc==SQLITE_OK && i<nSegment; i++){
 56709      volatile ht_slot *aHash;
 56710      u32 iZero;
 56711      volatile u32 *aPgno;
 56712  
 56713      rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
 56714      if( rc==SQLITE_OK ){
 56715        int j;                      /* Counter variable */
 56716        int nEntry;                 /* Number of entries in this segment */
 56717        ht_slot *aIndex;            /* Sorted index for this segment */
 56718  
 56719        aPgno++;
 56720        if( (i+1)==nSegment ){
 56721          nEntry = (int)(iLast - iZero);
 56722        }else{
 56723          nEntry = (int)((u32*)aHash - (u32*)aPgno);
 56724        }
 56725        aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
 56726        iZero++;
 56727    
 56728        for(j=0; j<nEntry; j++){
 56729          aIndex[j] = (ht_slot)j;
 56730        }
 56731        walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
 56732        p->aSegment[i].iZero = iZero;
 56733        p->aSegment[i].nEntry = nEntry;
 56734        p->aSegment[i].aIndex = aIndex;
 56735        p->aSegment[i].aPgno = (u32 *)aPgno;
 56736      }
 56737    }
 56738    sqlite3_free(aTmp);
 56739  
 56740    if( rc!=SQLITE_OK ){
 56741      walIteratorFree(p);
 56742    }
 56743    *pp = p;
 56744    return rc;
 56745  }
 56746  
 56747  /*
 56748  ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
 56749  ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
 56750  ** busy-handler function. Invoke it and retry the lock until either the
 56751  ** lock is successfully obtained or the busy-handler returns 0.
 56752  */
 56753  static int walBusyLock(
 56754    Wal *pWal,                      /* WAL connection */
 56755    int (*xBusy)(void*),            /* Function to call when busy */
 56756    void *pBusyArg,                 /* Context argument for xBusyHandler */
 56757    int lockIdx,                    /* Offset of first byte to lock */
 56758    int n                           /* Number of bytes to lock */
 56759  ){
 56760    int rc;
 56761    do {
 56762      rc = walLockExclusive(pWal, lockIdx, n);
 56763    }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
 56764    return rc;
 56765  }
 56766  
 56767  /*
 56768  ** The cache of the wal-index header must be valid to call this function.
 56769  ** Return the page-size in bytes used by the database.
 56770  */
 56771  static int walPagesize(Wal *pWal){
 56772    return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
 56773  }
 56774  
 56775  /*
 56776  ** The following is guaranteed when this function is called:
 56777  **
 56778  **   a) the WRITER lock is held,
 56779  **   b) the entire log file has been checkpointed, and
 56780  **   c) any existing readers are reading exclusively from the database
 56781  **      file - there are no readers that may attempt to read a frame from
 56782  **      the log file.
 56783  **
 56784  ** This function updates the shared-memory structures so that the next
 56785  ** client to write to the database (which may be this one) does so by
 56786  ** writing frames into the start of the log file.
 56787  **
 56788  ** The value of parameter salt1 is used as the aSalt[1] value in the 
 56789  ** new wal-index header. It should be passed a pseudo-random value (i.e. 
 56790  ** one obtained from sqlite3_randomness()).
 56791  */
 56792  static void walRestartHdr(Wal *pWal, u32 salt1){
 56793    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
 56794    int i;                          /* Loop counter */
 56795    u32 *aSalt = pWal->hdr.aSalt;   /* Big-endian salt values */
 56796    pWal->nCkpt++;
 56797    pWal->hdr.mxFrame = 0;
 56798    sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
 56799    memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
 56800    walIndexWriteHdr(pWal);
 56801    pInfo->nBackfill = 0;
 56802    pInfo->nBackfillAttempted = 0;
 56803    pInfo->aReadMark[1] = 0;
 56804    for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
 56805    assert( pInfo->aReadMark[0]==0 );
 56806  }
 56807  
 56808  /*
 56809  ** Copy as much content as we can from the WAL back into the database file
 56810  ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
 56811  **
 56812  ** The amount of information copies from WAL to database might be limited
 56813  ** by active readers.  This routine will never overwrite a database page
 56814  ** that a concurrent reader might be using.
 56815  **
 56816  ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
 56817  ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
 56818  ** checkpoints are always run by a background thread or background 
 56819  ** process, foreground threads will never block on a lengthy fsync call.
 56820  **
 56821  ** Fsync is called on the WAL before writing content out of the WAL and
 56822  ** into the database.  This ensures that if the new content is persistent
 56823  ** in the WAL and can be recovered following a power-loss or hard reset.
 56824  **
 56825  ** Fsync is also called on the database file if (and only if) the entire
 56826  ** WAL content is copied into the database file.  This second fsync makes
 56827  ** it safe to delete the WAL since the new content will persist in the
 56828  ** database file.
 56829  **
 56830  ** This routine uses and updates the nBackfill field of the wal-index header.
 56831  ** This is the only routine that will increase the value of nBackfill.  
 56832  ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
 56833  ** its value.)
 56834  **
 56835  ** The caller must be holding sufficient locks to ensure that no other
 56836  ** checkpoint is running (in any other thread or process) at the same
 56837  ** time.
 56838  */
 56839  static int walCheckpoint(
 56840    Wal *pWal,                      /* Wal connection */
 56841    sqlite3 *db,                    /* Check for interrupts on this handle */
 56842    int eMode,                      /* One of PASSIVE, FULL or RESTART */
 56843    int (*xBusy)(void*),            /* Function to call when busy */
 56844    void *pBusyArg,                 /* Context argument for xBusyHandler */
 56845    int sync_flags,                 /* Flags for OsSync() (or 0) */
 56846    u8 *zBuf                        /* Temporary buffer to use */
 56847  ){
 56848    int rc = SQLITE_OK;             /* Return code */
 56849    int szPage;                     /* Database page-size */
 56850    WalIterator *pIter = 0;         /* Wal iterator context */
 56851    u32 iDbpage = 0;                /* Next database page to write */
 56852    u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
 56853    u32 mxSafeFrame;                /* Max frame that can be backfilled */
 56854    u32 mxPage;                     /* Max database page to write */
 56855    int i;                          /* Loop counter */
 56856    volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
 56857  
 56858    szPage = walPagesize(pWal);
 56859    testcase( szPage<=32768 );
 56860    testcase( szPage>=65536 );
 56861    pInfo = walCkptInfo(pWal);
 56862    if( pInfo->nBackfill<pWal->hdr.mxFrame ){
 56863  
 56864      /* Allocate the iterator */
 56865      rc = walIteratorInit(pWal, &pIter);
 56866      if( rc!=SQLITE_OK ){
 56867        return rc;
 56868      }
 56869      assert( pIter );
 56870  
 56871      /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
 56872      ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
 56873      assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
 56874  
 56875      /* Compute in mxSafeFrame the index of the last frame of the WAL that is
 56876      ** safe to write into the database.  Frames beyond mxSafeFrame might
 56877      ** overwrite database pages that are in use by active readers and thus
 56878      ** cannot be backfilled from the WAL.
 56879      */
 56880      mxSafeFrame = pWal->hdr.mxFrame;
 56881      mxPage = pWal->hdr.nPage;
 56882      for(i=1; i<WAL_NREADER; i++){
 56883        /* Thread-sanitizer reports that the following is an unsafe read,
 56884        ** as some other thread may be in the process of updating the value
 56885        ** of the aReadMark[] slot. The assumption here is that if that is
 56886        ** happening, the other client may only be increasing the value,
 56887        ** not decreasing it. So assuming either that either the "old" or
 56888        ** "new" version of the value is read, and not some arbitrary value
 56889        ** that would never be written by a real client, things are still 
 56890        ** safe.  */
 56891        u32 y = pInfo->aReadMark[i];
 56892        if( mxSafeFrame>y ){
 56893          assert( y<=pWal->hdr.mxFrame );
 56894          rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
 56895          if( rc==SQLITE_OK ){
 56896            pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
 56897            walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
 56898          }else if( rc==SQLITE_BUSY ){
 56899            mxSafeFrame = y;
 56900            xBusy = 0;
 56901          }else{
 56902            goto walcheckpoint_out;
 56903          }
 56904        }
 56905      }
 56906  
 56907      if( pInfo->nBackfill<mxSafeFrame
 56908       && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
 56909      ){
 56910        i64 nSize;                    /* Current size of database file */
 56911        u32 nBackfill = pInfo->nBackfill;
 56912  
 56913        pInfo->nBackfillAttempted = mxSafeFrame;
 56914  
 56915        /* Sync the WAL to disk */
 56916        rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
 56917  
 56918        /* If the database may grow as a result of this checkpoint, hint
 56919        ** about the eventual size of the db file to the VFS layer.
 56920        */
 56921        if( rc==SQLITE_OK ){
 56922          i64 nReq = ((i64)mxPage * szPage);
 56923          rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
 56924          if( rc==SQLITE_OK && nSize<nReq ){
 56925            sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
 56926          }
 56927        }
 56928  
 56929  
 56930        /* Iterate through the contents of the WAL, copying data to the db file */
 56931        while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
 56932          i64 iOffset;
 56933          assert( walFramePgno(pWal, iFrame)==iDbpage );
 56934          if( db->u1.isInterrupted ){
 56935            rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
 56936            break;
 56937          }
 56938          if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
 56939            continue;
 56940          }
 56941          iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
 56942          /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
 56943          rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
 56944          if( rc!=SQLITE_OK ) break;
 56945          iOffset = (iDbpage-1)*(i64)szPage;
 56946          testcase( IS_BIG_INT(iOffset) );
 56947          rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
 56948          if( rc!=SQLITE_OK ) break;
 56949        }
 56950  
 56951        /* If work was actually accomplished... */
 56952        if( rc==SQLITE_OK ){
 56953          if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
 56954            i64 szDb = pWal->hdr.nPage*(i64)szPage;
 56955            testcase( IS_BIG_INT(szDb) );
 56956            rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
 56957            if( rc==SQLITE_OK ){
 56958              rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));
 56959            }
 56960          }
 56961          if( rc==SQLITE_OK ){
 56962            pInfo->nBackfill = mxSafeFrame;
 56963          }
 56964        }
 56965  
 56966        /* Release the reader lock held while backfilling */
 56967        walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
 56968      }
 56969  
 56970      if( rc==SQLITE_BUSY ){
 56971        /* Reset the return code so as not to report a checkpoint failure
 56972        ** just because there are active readers.  */
 56973        rc = SQLITE_OK;
 56974      }
 56975    }
 56976  
 56977    /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
 56978    ** entire wal file has been copied into the database file, then block 
 56979    ** until all readers have finished using the wal file. This ensures that 
 56980    ** the next process to write to the database restarts the wal file.
 56981    */
 56982    if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
 56983      assert( pWal->writeLock );
 56984      if( pInfo->nBackfill<pWal->hdr.mxFrame ){
 56985        rc = SQLITE_BUSY;
 56986      }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
 56987        u32 salt1;
 56988        sqlite3_randomness(4, &salt1);
 56989        assert( pInfo->nBackfill==pWal->hdr.mxFrame );
 56990        rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
 56991        if( rc==SQLITE_OK ){
 56992          if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
 56993            /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
 56994            ** SQLITE_CHECKPOINT_RESTART with the addition that it also
 56995            ** truncates the log file to zero bytes just prior to a
 56996            ** successful return.
 56997            **
 56998            ** In theory, it might be safe to do this without updating the
 56999            ** wal-index header in shared memory, as all subsequent reader or
 57000            ** writer clients should see that the entire log file has been
 57001            ** checkpointed and behave accordingly. This seems unsafe though,
 57002            ** as it would leave the system in a state where the contents of
 57003            ** the wal-index header do not match the contents of the 
 57004            ** file-system. To avoid this, update the wal-index header to
 57005            ** indicate that the log file contains zero valid frames.  */
 57006            walRestartHdr(pWal, salt1);
 57007            rc = sqlite3OsTruncate(pWal->pWalFd, 0);
 57008          }
 57009          walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
 57010        }
 57011      }
 57012    }
 57013  
 57014   walcheckpoint_out:
 57015    walIteratorFree(pIter);
 57016    return rc;
 57017  }
 57018  
 57019  /*
 57020  ** If the WAL file is currently larger than nMax bytes in size, truncate
 57021  ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
 57022  */
 57023  static void walLimitSize(Wal *pWal, i64 nMax){
 57024    i64 sz;
 57025    int rx;
 57026    sqlite3BeginBenignMalloc();
 57027    rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
 57028    if( rx==SQLITE_OK && (sz > nMax ) ){
 57029      rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
 57030    }
 57031    sqlite3EndBenignMalloc();
 57032    if( rx ){
 57033      sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
 57034    }
 57035  }
 57036  
 57037  /*
 57038  ** Close a connection to a log file.
 57039  */
 57040  SQLITE_PRIVATE int sqlite3WalClose(
 57041    Wal *pWal,                      /* Wal to close */
 57042    sqlite3 *db,                    /* For interrupt flag */
 57043    int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
 57044    int nBuf,
 57045    u8 *zBuf                        /* Buffer of at least nBuf bytes */
 57046  ){
 57047    int rc = SQLITE_OK;
 57048    if( pWal ){
 57049      int isDelete = 0;             /* True to unlink wal and wal-index files */
 57050  
 57051      /* If an EXCLUSIVE lock can be obtained on the database file (using the
 57052      ** ordinary, rollback-mode locking methods, this guarantees that the
 57053      ** connection associated with this log file is the only connection to
 57054      ** the database. In this case checkpoint the database and unlink both
 57055      ** the wal and wal-index files.
 57056      **
 57057      ** The EXCLUSIVE lock is not released before returning.
 57058      */
 57059      if( zBuf!=0
 57060       && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
 57061      ){
 57062        if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
 57063          pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
 57064        }
 57065        rc = sqlite3WalCheckpoint(pWal, db, 
 57066            SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
 57067        );
 57068        if( rc==SQLITE_OK ){
 57069          int bPersist = -1;
 57070          sqlite3OsFileControlHint(
 57071              pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
 57072          );
 57073          if( bPersist!=1 ){
 57074            /* Try to delete the WAL file if the checkpoint completed and
 57075            ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
 57076            ** mode (!bPersist) */
 57077            isDelete = 1;
 57078          }else if( pWal->mxWalSize>=0 ){
 57079            /* Try to truncate the WAL file to zero bytes if the checkpoint
 57080            ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
 57081            ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
 57082            ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
 57083            ** to zero bytes as truncating to the journal_size_limit might
 57084            ** leave a corrupt WAL file on disk. */
 57085            walLimitSize(pWal, 0);
 57086          }
 57087        }
 57088      }
 57089  
 57090      walIndexClose(pWal, isDelete);
 57091      sqlite3OsClose(pWal->pWalFd);
 57092      if( isDelete ){
 57093        sqlite3BeginBenignMalloc();
 57094        sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
 57095        sqlite3EndBenignMalloc();
 57096      }
 57097      WALTRACE(("WAL%p: closed\n", pWal));
 57098      sqlite3_free((void *)pWal->apWiData);
 57099      sqlite3_free(pWal);
 57100    }
 57101    return rc;
 57102  }
 57103  
 57104  /*
 57105  ** Try to read the wal-index header.  Return 0 on success and 1 if
 57106  ** there is a problem.
 57107  **
 57108  ** The wal-index is in shared memory.  Another thread or process might
 57109  ** be writing the header at the same time this procedure is trying to
 57110  ** read it, which might result in inconsistency.  A dirty read is detected
 57111  ** by verifying that both copies of the header are the same and also by
 57112  ** a checksum on the header.
 57113  **
 57114  ** If and only if the read is consistent and the header is different from
 57115  ** pWal->hdr, then pWal->hdr is updated to the content of the new header
 57116  ** and *pChanged is set to 1.
 57117  **
 57118  ** If the checksum cannot be verified return non-zero. If the header
 57119  ** is read successfully and the checksum verified, return zero.
 57120  */
 57121  static int walIndexTryHdr(Wal *pWal, int *pChanged){
 57122    u32 aCksum[2];                  /* Checksum on the header content */
 57123    WalIndexHdr h1, h2;             /* Two copies of the header content */
 57124    WalIndexHdr volatile *aHdr;     /* Header in shared memory */
 57125  
 57126    /* The first page of the wal-index must be mapped at this point. */
 57127    assert( pWal->nWiData>0 && pWal->apWiData[0] );
 57128  
 57129    /* Read the header. This might happen concurrently with a write to the
 57130    ** same area of shared memory on a different CPU in a SMP,
 57131    ** meaning it is possible that an inconsistent snapshot is read
 57132    ** from the file. If this happens, return non-zero.
 57133    **
 57134    ** There are two copies of the header at the beginning of the wal-index.
 57135    ** When reading, read [0] first then [1].  Writes are in the reverse order.
 57136    ** Memory barriers are used to prevent the compiler or the hardware from
 57137    ** reordering the reads and writes.
 57138    */
 57139    aHdr = walIndexHdr(pWal);
 57140    memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
 57141    walShmBarrier(pWal);
 57142    memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
 57143  
 57144    if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
 57145      return 1;   /* Dirty read */
 57146    }  
 57147    if( h1.isInit==0 ){
 57148      return 1;   /* Malformed header - probably all zeros */
 57149    }
 57150    walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
 57151    if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
 57152      return 1;   /* Checksum does not match */
 57153    }
 57154  
 57155    if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
 57156      *pChanged = 1;
 57157      memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
 57158      pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
 57159      testcase( pWal->szPage<=32768 );
 57160      testcase( pWal->szPage>=65536 );
 57161    }
 57162  
 57163    /* The header was successfully read. Return zero. */
 57164    return 0;
 57165  }
 57166  
 57167  /*
 57168  ** Read the wal-index header from the wal-index and into pWal->hdr.
 57169  ** If the wal-header appears to be corrupt, try to reconstruct the
 57170  ** wal-index from the WAL before returning.
 57171  **
 57172  ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
 57173  ** changed by this operation.  If pWal->hdr is unchanged, set *pChanged
 57174  ** to 0.
 57175  **
 57176  ** If the wal-index header is successfully read, return SQLITE_OK. 
 57177  ** Otherwise an SQLite error code.
 57178  */
 57179  static int walIndexReadHdr(Wal *pWal, int *pChanged){
 57180    int rc;                         /* Return code */
 57181    int badHdr;                     /* True if a header read failed */
 57182    volatile u32 *page0;            /* Chunk of wal-index containing header */
 57183  
 57184    /* Ensure that page 0 of the wal-index (the page that contains the 
 57185    ** wal-index header) is mapped. Return early if an error occurs here.
 57186    */
 57187    assert( pChanged );
 57188    rc = walIndexPage(pWal, 0, &page0);
 57189    if( rc!=SQLITE_OK ){
 57190      return rc;
 57191    };
 57192    assert( page0 || pWal->writeLock==0 );
 57193  
 57194    /* If the first page of the wal-index has been mapped, try to read the
 57195    ** wal-index header immediately, without holding any lock. This usually
 57196    ** works, but may fail if the wal-index header is corrupt or currently 
 57197    ** being modified by another thread or process.
 57198    */
 57199    badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
 57200  
 57201    /* If the first attempt failed, it might have been due to a race
 57202    ** with a writer.  So get a WRITE lock and try again.
 57203    */
 57204    assert( badHdr==0 || pWal->writeLock==0 );
 57205    if( badHdr ){
 57206      if( pWal->readOnly & WAL_SHM_RDONLY ){
 57207        if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
 57208          walUnlockShared(pWal, WAL_WRITE_LOCK);
 57209          rc = SQLITE_READONLY_RECOVERY;
 57210        }
 57211      }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
 57212        pWal->writeLock = 1;
 57213        if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
 57214          badHdr = walIndexTryHdr(pWal, pChanged);
 57215          if( badHdr ){
 57216            /* If the wal-index header is still malformed even while holding
 57217            ** a WRITE lock, it can only mean that the header is corrupted and
 57218            ** needs to be reconstructed.  So run recovery to do exactly that.
 57219            */
 57220            rc = walIndexRecover(pWal);
 57221            *pChanged = 1;
 57222          }
 57223        }
 57224        pWal->writeLock = 0;
 57225        walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
 57226      }
 57227    }
 57228  
 57229    /* If the header is read successfully, check the version number to make
 57230    ** sure the wal-index was not constructed with some future format that
 57231    ** this version of SQLite cannot understand.
 57232    */
 57233    if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
 57234      rc = SQLITE_CANTOPEN_BKPT;
 57235    }
 57236  
 57237    return rc;
 57238  }
 57239  
 57240  /*
 57241  ** This is the value that walTryBeginRead returns when it needs to
 57242  ** be retried.
 57243  */
 57244  #define WAL_RETRY  (-1)
 57245  
 57246  /*
 57247  ** Attempt to start a read transaction.  This might fail due to a race or
 57248  ** other transient condition.  When that happens, it returns WAL_RETRY to
 57249  ** indicate to the caller that it is safe to retry immediately.
 57250  **
 57251  ** On success return SQLITE_OK.  On a permanent failure (such an
 57252  ** I/O error or an SQLITE_BUSY because another process is running
 57253  ** recovery) return a positive error code.
 57254  **
 57255  ** The useWal parameter is true to force the use of the WAL and disable
 57256  ** the case where the WAL is bypassed because it has been completely
 57257  ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
 57258  ** to make a copy of the wal-index header into pWal->hdr.  If the 
 57259  ** wal-index header has changed, *pChanged is set to 1 (as an indication 
 57260  ** to the caller that the local paget cache is obsolete and needs to be 
 57261  ** flushed.)  When useWal==1, the wal-index header is assumed to already
 57262  ** be loaded and the pChanged parameter is unused.
 57263  **
 57264  ** The caller must set the cnt parameter to the number of prior calls to
 57265  ** this routine during the current read attempt that returned WAL_RETRY.
 57266  ** This routine will start taking more aggressive measures to clear the
 57267  ** race conditions after multiple WAL_RETRY returns, and after an excessive
 57268  ** number of errors will ultimately return SQLITE_PROTOCOL.  The
 57269  ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
 57270  ** and is not honoring the locking protocol.  There is a vanishingly small
 57271  ** chance that SQLITE_PROTOCOL could be returned because of a run of really
 57272  ** bad luck when there is lots of contention for the wal-index, but that
 57273  ** possibility is so small that it can be safely neglected, we believe.
 57274  **
 57275  ** On success, this routine obtains a read lock on 
 57276  ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
 57277  ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
 57278  ** that means the Wal does not hold any read lock.  The reader must not
 57279  ** access any database page that is modified by a WAL frame up to and
 57280  ** including frame number aReadMark[pWal->readLock].  The reader will
 57281  ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
 57282  ** Or if pWal->readLock==0, then the reader will ignore the WAL
 57283  ** completely and get all content directly from the database file.
 57284  ** If the useWal parameter is 1 then the WAL will never be ignored and
 57285  ** this routine will always set pWal->readLock>0 on success.
 57286  ** When the read transaction is completed, the caller must release the
 57287  ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
 57288  **
 57289  ** This routine uses the nBackfill and aReadMark[] fields of the header
 57290  ** to select a particular WAL_READ_LOCK() that strives to let the
 57291  ** checkpoint process do as much work as possible.  This routine might
 57292  ** update values of the aReadMark[] array in the header, but if it does
 57293  ** so it takes care to hold an exclusive lock on the corresponding
 57294  ** WAL_READ_LOCK() while changing values.
 57295  */
 57296  static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
 57297    volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
 57298    u32 mxReadMark;                 /* Largest aReadMark[] value */
 57299    int mxI;                        /* Index of largest aReadMark[] value */
 57300    int i;                          /* Loop counter */
 57301    int rc = SQLITE_OK;             /* Return code  */
 57302    u32 mxFrame;                    /* Wal frame to lock to */
 57303  
 57304    assert( pWal->readLock<0 );     /* Not currently locked */
 57305  
 57306    /* Take steps to avoid spinning forever if there is a protocol error.
 57307    **
 57308    ** Circumstances that cause a RETRY should only last for the briefest
 57309    ** instances of time.  No I/O or other system calls are done while the
 57310    ** locks are held, so the locks should not be held for very long. But 
 57311    ** if we are unlucky, another process that is holding a lock might get
 57312    ** paged out or take a page-fault that is time-consuming to resolve, 
 57313    ** during the few nanoseconds that it is holding the lock.  In that case,
 57314    ** it might take longer than normal for the lock to free.
 57315    **
 57316    ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
 57317    ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
 57318    ** is more of a scheduler yield than an actual delay.  But on the 10th
 57319    ** an subsequent retries, the delays start becoming longer and longer, 
 57320    ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
 57321    ** The total delay time before giving up is less than 10 seconds.
 57322    */
 57323    if( cnt>5 ){
 57324      int nDelay = 1;                      /* Pause time in microseconds */
 57325      if( cnt>100 ){
 57326        VVA_ONLY( pWal->lockError = 1; )
 57327        return SQLITE_PROTOCOL;
 57328      }
 57329      if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
 57330      sqlite3OsSleep(pWal->pVfs, nDelay);
 57331    }
 57332  
 57333    if( !useWal ){
 57334      rc = walIndexReadHdr(pWal, pChanged);
 57335      if( rc==SQLITE_BUSY ){
 57336        /* If there is not a recovery running in another thread or process
 57337        ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
 57338        ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
 57339        ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
 57340        ** would be technically correct.  But the race is benign since with
 57341        ** WAL_RETRY this routine will be called again and will probably be
 57342        ** right on the second iteration.
 57343        */
 57344        if( pWal->apWiData[0]==0 ){
 57345          /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
 57346          ** We assume this is a transient condition, so return WAL_RETRY. The
 57347          ** xShmMap() implementation used by the default unix and win32 VFS 
 57348          ** modules may return SQLITE_BUSY due to a race condition in the 
 57349          ** code that determines whether or not the shared-memory region 
 57350          ** must be zeroed before the requested page is returned.
 57351          */
 57352          rc = WAL_RETRY;
 57353        }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
 57354          walUnlockShared(pWal, WAL_RECOVER_LOCK);
 57355          rc = WAL_RETRY;
 57356        }else if( rc==SQLITE_BUSY ){
 57357          rc = SQLITE_BUSY_RECOVERY;
 57358        }
 57359      }
 57360      if( rc!=SQLITE_OK ){
 57361        return rc;
 57362      }
 57363    }
 57364  
 57365    pInfo = walCkptInfo(pWal);
 57366    if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame 
 57367  #ifdef SQLITE_ENABLE_SNAPSHOT
 57368     && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0
 57369       || 0==memcmp(&pWal->hdr, pWal->pSnapshot, sizeof(WalIndexHdr)))
 57370  #endif
 57371    ){
 57372      /* The WAL has been completely backfilled (or it is empty).
 57373      ** and can be safely ignored.
 57374      */
 57375      rc = walLockShared(pWal, WAL_READ_LOCK(0));
 57376      walShmBarrier(pWal);
 57377      if( rc==SQLITE_OK ){
 57378        if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
 57379          /* It is not safe to allow the reader to continue here if frames
 57380          ** may have been appended to the log before READ_LOCK(0) was obtained.
 57381          ** When holding READ_LOCK(0), the reader ignores the entire log file,
 57382          ** which implies that the database file contains a trustworthy
 57383          ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
 57384          ** happening, this is usually correct.
 57385          **
 57386          ** However, if frames have been appended to the log (or if the log 
 57387          ** is wrapped and written for that matter) before the READ_LOCK(0)
 57388          ** is obtained, that is not necessarily true. A checkpointer may
 57389          ** have started to backfill the appended frames but crashed before
 57390          ** it finished. Leaving a corrupt image in the database file.
 57391          */
 57392          walUnlockShared(pWal, WAL_READ_LOCK(0));
 57393          return WAL_RETRY;
 57394        }
 57395        pWal->readLock = 0;
 57396        return SQLITE_OK;
 57397      }else if( rc!=SQLITE_BUSY ){
 57398        return rc;
 57399      }
 57400    }
 57401  
 57402    /* If we get this far, it means that the reader will want to use
 57403    ** the WAL to get at content from recent commits.  The job now is
 57404    ** to select one of the aReadMark[] entries that is closest to
 57405    ** but not exceeding pWal->hdr.mxFrame and lock that entry.
 57406    */
 57407    mxReadMark = 0;
 57408    mxI = 0;
 57409    mxFrame = pWal->hdr.mxFrame;
 57410  #ifdef SQLITE_ENABLE_SNAPSHOT
 57411    if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
 57412      mxFrame = pWal->pSnapshot->mxFrame;
 57413    }
 57414  #endif
 57415    for(i=1; i<WAL_NREADER; i++){
 57416      u32 thisMark = pInfo->aReadMark[i];
 57417      if( mxReadMark<=thisMark && thisMark<=mxFrame ){
 57418        assert( thisMark!=READMARK_NOT_USED );
 57419        mxReadMark = thisMark;
 57420        mxI = i;
 57421      }
 57422    }
 57423    if( (pWal->readOnly & WAL_SHM_RDONLY)==0
 57424     && (mxReadMark<mxFrame || mxI==0)
 57425    ){
 57426      for(i=1; i<WAL_NREADER; i++){
 57427        rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
 57428        if( rc==SQLITE_OK ){
 57429          mxReadMark = pInfo->aReadMark[i] = mxFrame;
 57430          mxI = i;
 57431          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
 57432          break;
 57433        }else if( rc!=SQLITE_BUSY ){
 57434          return rc;
 57435        }
 57436      }
 57437    }
 57438    if( mxI==0 ){
 57439      assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
 57440      return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
 57441    }
 57442  
 57443    rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
 57444    if( rc ){
 57445      return rc==SQLITE_BUSY ? WAL_RETRY : rc;
 57446    }
 57447    /* Now that the read-lock has been obtained, check that neither the
 57448    ** value in the aReadMark[] array or the contents of the wal-index
 57449    ** header have changed.
 57450    **
 57451    ** It is necessary to check that the wal-index header did not change
 57452    ** between the time it was read and when the shared-lock was obtained
 57453    ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
 57454    ** that the log file may have been wrapped by a writer, or that frames
 57455    ** that occur later in the log than pWal->hdr.mxFrame may have been
 57456    ** copied into the database by a checkpointer. If either of these things
 57457    ** happened, then reading the database with the current value of
 57458    ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
 57459    ** instead.
 57460    **
 57461    ** Before checking that the live wal-index header has not changed
 57462    ** since it was read, set Wal.minFrame to the first frame in the wal
 57463    ** file that has not yet been checkpointed. This client will not need
 57464    ** to read any frames earlier than minFrame from the wal file - they
 57465    ** can be safely read directly from the database file.
 57466    **
 57467    ** Because a ShmBarrier() call is made between taking the copy of 
 57468    ** nBackfill and checking that the wal-header in shared-memory still
 57469    ** matches the one cached in pWal->hdr, it is guaranteed that the 
 57470    ** checkpointer that set nBackfill was not working with a wal-index
 57471    ** header newer than that cached in pWal->hdr. If it were, that could
 57472    ** cause a problem. The checkpointer could omit to checkpoint
 57473    ** a version of page X that lies before pWal->minFrame (call that version
 57474    ** A) on the basis that there is a newer version (version B) of the same
 57475    ** page later in the wal file. But if version B happens to like past
 57476    ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
 57477    ** that it can read version A from the database file. However, since
 57478    ** we can guarantee that the checkpointer that set nBackfill could not
 57479    ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
 57480    */
 57481    pWal->minFrame = pInfo->nBackfill+1;
 57482    walShmBarrier(pWal);
 57483    if( pInfo->aReadMark[mxI]!=mxReadMark
 57484     || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
 57485    ){
 57486      walUnlockShared(pWal, WAL_READ_LOCK(mxI));
 57487      return WAL_RETRY;
 57488    }else{
 57489      assert( mxReadMark<=pWal->hdr.mxFrame );
 57490      pWal->readLock = (i16)mxI;
 57491    }
 57492    return rc;
 57493  }
 57494  
 57495  #ifdef SQLITE_ENABLE_SNAPSHOT
 57496  /*
 57497  ** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted 
 57498  ** variable so that older snapshots can be accessed. To do this, loop
 57499  ** through all wal frames from nBackfillAttempted to (nBackfill+1), 
 57500  ** comparing their content to the corresponding page with the database
 57501  ** file, if any. Set nBackfillAttempted to the frame number of the
 57502  ** first frame for which the wal file content matches the db file.
 57503  **
 57504  ** This is only really safe if the file-system is such that any page 
 57505  ** writes made by earlier checkpointers were atomic operations, which 
 57506  ** is not always true. It is also possible that nBackfillAttempted
 57507  ** may be left set to a value larger than expected, if a wal frame
 57508  ** contains content that duplicate of an earlier version of the same
 57509  ** page.
 57510  **
 57511  ** SQLITE_OK is returned if successful, or an SQLite error code if an
 57512  ** error occurs. It is not an error if nBackfillAttempted cannot be
 57513  ** decreased at all.
 57514  */
 57515  SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){
 57516    int rc;
 57517  
 57518    assert( pWal->readLock>=0 );
 57519    rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
 57520    if( rc==SQLITE_OK ){
 57521      volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
 57522      int szPage = (int)pWal->szPage;
 57523      i64 szDb;                   /* Size of db file in bytes */
 57524  
 57525      rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
 57526      if( rc==SQLITE_OK ){
 57527        void *pBuf1 = sqlite3_malloc(szPage);
 57528        void *pBuf2 = sqlite3_malloc(szPage);
 57529        if( pBuf1==0 || pBuf2==0 ){
 57530          rc = SQLITE_NOMEM;
 57531        }else{
 57532          u32 i = pInfo->nBackfillAttempted;
 57533          for(i=pInfo->nBackfillAttempted; i>pInfo->nBackfill; i--){
 57534            volatile ht_slot *dummy;
 57535            volatile u32 *aPgno;      /* Array of page numbers */
 57536            u32 iZero;                /* Frame corresponding to aPgno[0] */
 57537            u32 pgno;                 /* Page number in db file */
 57538            i64 iDbOff;               /* Offset of db file entry */
 57539            i64 iWalOff;              /* Offset of wal file entry */
 57540  
 57541            rc = walHashGet(pWal, walFramePage(i), &dummy, &aPgno, &iZero);
 57542            if( rc!=SQLITE_OK ) break;
 57543            pgno = aPgno[i-iZero];
 57544            iDbOff = (i64)(pgno-1) * szPage;
 57545  
 57546            if( iDbOff+szPage<=szDb ){
 57547              iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
 57548              rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
 57549  
 57550              if( rc==SQLITE_OK ){
 57551                rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
 57552              }
 57553  
 57554              if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
 57555                break;
 57556              }
 57557            }
 57558  
 57559            pInfo->nBackfillAttempted = i-1;
 57560          }
 57561        }
 57562  
 57563        sqlite3_free(pBuf1);
 57564        sqlite3_free(pBuf2);
 57565      }
 57566      walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
 57567    }
 57568  
 57569    return rc;
 57570  }
 57571  #endif /* SQLITE_ENABLE_SNAPSHOT */
 57572  
 57573  /*
 57574  ** Begin a read transaction on the database.
 57575  **
 57576  ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
 57577  ** it takes a snapshot of the state of the WAL and wal-index for the current
 57578  ** instant in time.  The current thread will continue to use this snapshot.
 57579  ** Other threads might append new content to the WAL and wal-index but
 57580  ** that extra content is ignored by the current thread.
 57581  **
 57582  ** If the database contents have changes since the previous read
 57583  ** transaction, then *pChanged is set to 1 before returning.  The
 57584  ** Pager layer will use this to know that is cache is stale and
 57585  ** needs to be flushed.
 57586  */
 57587  SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
 57588    int rc;                         /* Return code */
 57589    int cnt = 0;                    /* Number of TryBeginRead attempts */
 57590  
 57591  #ifdef SQLITE_ENABLE_SNAPSHOT
 57592    int bChanged = 0;
 57593    WalIndexHdr *pSnapshot = pWal->pSnapshot;
 57594    if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
 57595      bChanged = 1;
 57596    }
 57597  #endif
 57598  
 57599    do{
 57600      rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
 57601    }while( rc==WAL_RETRY );
 57602    testcase( (rc&0xff)==SQLITE_BUSY );
 57603    testcase( (rc&0xff)==SQLITE_IOERR );
 57604    testcase( rc==SQLITE_PROTOCOL );
 57605    testcase( rc==SQLITE_OK );
 57606  
 57607  #ifdef SQLITE_ENABLE_SNAPSHOT
 57608    if( rc==SQLITE_OK ){
 57609      if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
 57610        /* At this point the client has a lock on an aReadMark[] slot holding
 57611        ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
 57612        ** is populated with the wal-index header corresponding to the head
 57613        ** of the wal file. Verify that pSnapshot is still valid before
 57614        ** continuing.  Reasons why pSnapshot might no longer be valid:
 57615        **
 57616        **    (1)  The WAL file has been reset since the snapshot was taken.
 57617        **         In this case, the salt will have changed.
 57618        **
 57619        **    (2)  A checkpoint as been attempted that wrote frames past
 57620        **         pSnapshot->mxFrame into the database file.  Note that the
 57621        **         checkpoint need not have completed for this to cause problems.
 57622        */
 57623        volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
 57624  
 57625        assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
 57626        assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
 57627  
 57628        /* It is possible that there is a checkpointer thread running 
 57629        ** concurrent with this code. If this is the case, it may be that the
 57630        ** checkpointer has already determined that it will checkpoint 
 57631        ** snapshot X, where X is later in the wal file than pSnapshot, but 
 57632        ** has not yet set the pInfo->nBackfillAttempted variable to indicate 
 57633        ** its intent. To avoid the race condition this leads to, ensure that
 57634        ** there is no checkpointer process by taking a shared CKPT lock 
 57635        ** before checking pInfo->nBackfillAttempted.  
 57636        **
 57637        ** TODO: Does the aReadMark[] lock prevent a checkpointer from doing
 57638        **       this already?
 57639        */
 57640        rc = walLockShared(pWal, WAL_CKPT_LOCK);
 57641  
 57642        if( rc==SQLITE_OK ){
 57643          /* Check that the wal file has not been wrapped. Assuming that it has
 57644          ** not, also check that no checkpointer has attempted to checkpoint any
 57645          ** frames beyond pSnapshot->mxFrame. If either of these conditions are
 57646          ** true, return SQLITE_BUSY_SNAPSHOT. Otherwise, overwrite pWal->hdr
 57647          ** with *pSnapshot and set *pChanged as appropriate for opening the
 57648          ** snapshot.  */
 57649          if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
 57650           && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
 57651          ){
 57652            assert( pWal->readLock>0 );
 57653            memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
 57654            *pChanged = bChanged;
 57655          }else{
 57656            rc = SQLITE_BUSY_SNAPSHOT;
 57657          }
 57658  
 57659          /* Release the shared CKPT lock obtained above. */
 57660          walUnlockShared(pWal, WAL_CKPT_LOCK);
 57661        }
 57662  
 57663  
 57664        if( rc!=SQLITE_OK ){
 57665          sqlite3WalEndReadTransaction(pWal);
 57666        }
 57667      }
 57668    }
 57669  #endif
 57670    return rc;
 57671  }
 57672  
 57673  /*
 57674  ** Finish with a read transaction.  All this does is release the
 57675  ** read-lock.
 57676  */
 57677  SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
 57678    sqlite3WalEndWriteTransaction(pWal);
 57679    if( pWal->readLock>=0 ){
 57680      walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
 57681      pWal->readLock = -1;
 57682    }
 57683  }
 57684  
 57685  /*
 57686  ** Search the wal file for page pgno. If found, set *piRead to the frame that
 57687  ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
 57688  ** to zero.
 57689  **
 57690  ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
 57691  ** error does occur, the final value of *piRead is undefined.
 57692  */
 57693  SQLITE_PRIVATE int sqlite3WalFindFrame(
 57694    Wal *pWal,                      /* WAL handle */
 57695    Pgno pgno,                      /* Database page number to read data for */
 57696    u32 *piRead                     /* OUT: Frame number (or zero) */
 57697  ){
 57698    u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
 57699    u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
 57700    int iHash;                      /* Used to loop through N hash tables */
 57701    int iMinHash;
 57702  
 57703    /* This routine is only be called from within a read transaction. */
 57704    assert( pWal->readLock>=0 || pWal->lockError );
 57705  
 57706    /* If the "last page" field of the wal-index header snapshot is 0, then
 57707    ** no data will be read from the wal under any circumstances. Return early
 57708    ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
 57709    ** then the WAL is ignored by the reader so return early, as if the 
 57710    ** WAL were empty.
 57711    */
 57712    if( iLast==0 || pWal->readLock==0 ){
 57713      *piRead = 0;
 57714      return SQLITE_OK;
 57715    }
 57716  
 57717    /* Search the hash table or tables for an entry matching page number
 57718    ** pgno. Each iteration of the following for() loop searches one
 57719    ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
 57720    **
 57721    ** This code might run concurrently to the code in walIndexAppend()
 57722    ** that adds entries to the wal-index (and possibly to this hash 
 57723    ** table). This means the value just read from the hash 
 57724    ** slot (aHash[iKey]) may have been added before or after the 
 57725    ** current read transaction was opened. Values added after the
 57726    ** read transaction was opened may have been written incorrectly -
 57727    ** i.e. these slots may contain garbage data. However, we assume
 57728    ** that any slots written before the current read transaction was
 57729    ** opened remain unmodified.
 57730    **
 57731    ** For the reasons above, the if(...) condition featured in the inner
 57732    ** loop of the following block is more stringent that would be required 
 57733    ** if we had exclusive access to the hash-table:
 57734    **
 57735    **   (aPgno[iFrame]==pgno): 
 57736    **     This condition filters out normal hash-table collisions.
 57737    **
 57738    **   (iFrame<=iLast): 
 57739    **     This condition filters out entries that were added to the hash
 57740    **     table after the current read-transaction had started.
 57741    */
 57742    iMinHash = walFramePage(pWal->minFrame);
 57743    for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){
 57744      volatile ht_slot *aHash;      /* Pointer to hash table */
 57745      volatile u32 *aPgno;          /* Pointer to array of page numbers */
 57746      u32 iZero;                    /* Frame number corresponding to aPgno[0] */
 57747      int iKey;                     /* Hash slot index */
 57748      int nCollide;                 /* Number of hash collisions remaining */
 57749      int rc;                       /* Error code */
 57750  
 57751      rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
 57752      if( rc!=SQLITE_OK ){
 57753        return rc;
 57754      }
 57755      nCollide = HASHTABLE_NSLOT;
 57756      for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
 57757        u32 iFrame = aHash[iKey] + iZero;
 57758        if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){
 57759          assert( iFrame>iRead || CORRUPT_DB );
 57760          iRead = iFrame;
 57761        }
 57762        if( (nCollide--)==0 ){
 57763          return SQLITE_CORRUPT_BKPT;
 57764        }
 57765      }
 57766    }
 57767  
 57768  #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
 57769    /* If expensive assert() statements are available, do a linear search
 57770    ** of the wal-index file content. Make sure the results agree with the
 57771    ** result obtained using the hash indexes above.  */
 57772    {
 57773      u32 iRead2 = 0;
 57774      u32 iTest;
 57775      assert( pWal->minFrame>0 );
 57776      for(iTest=iLast; iTest>=pWal->minFrame; iTest--){
 57777        if( walFramePgno(pWal, iTest)==pgno ){
 57778          iRead2 = iTest;
 57779          break;
 57780        }
 57781      }
 57782      assert( iRead==iRead2 );
 57783    }
 57784  #endif
 57785  
 57786    *piRead = iRead;
 57787    return SQLITE_OK;
 57788  }
 57789  
 57790  /*
 57791  ** Read the contents of frame iRead from the wal file into buffer pOut
 57792  ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
 57793  ** error code otherwise.
 57794  */
 57795  SQLITE_PRIVATE int sqlite3WalReadFrame(
 57796    Wal *pWal,                      /* WAL handle */
 57797    u32 iRead,                      /* Frame to read */
 57798    int nOut,                       /* Size of buffer pOut in bytes */
 57799    u8 *pOut                        /* Buffer to write page data to */
 57800  ){
 57801    int sz;
 57802    i64 iOffset;
 57803    sz = pWal->hdr.szPage;
 57804    sz = (sz&0xfe00) + ((sz&0x0001)<<16);
 57805    testcase( sz<=32768 );
 57806    testcase( sz>=65536 );
 57807    iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
 57808    /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
 57809    return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
 57810  }
 57811  
 57812  /* 
 57813  ** Return the size of the database in pages (or zero, if unknown).
 57814  */
 57815  SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
 57816    if( pWal && ALWAYS(pWal->readLock>=0) ){
 57817      return pWal->hdr.nPage;
 57818    }
 57819    return 0;
 57820  }
 57821  
 57822  
 57823  /* 
 57824  ** This function starts a write transaction on the WAL.
 57825  **
 57826  ** A read transaction must have already been started by a prior call
 57827  ** to sqlite3WalBeginReadTransaction().
 57828  **
 57829  ** If another thread or process has written into the database since
 57830  ** the read transaction was started, then it is not possible for this
 57831  ** thread to write as doing so would cause a fork.  So this routine
 57832  ** returns SQLITE_BUSY in that case and no write transaction is started.
 57833  **
 57834  ** There can only be a single writer active at a time.
 57835  */
 57836  SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
 57837    int rc;
 57838  
 57839    /* Cannot start a write transaction without first holding a read
 57840    ** transaction. */
 57841    assert( pWal->readLock>=0 );
 57842    assert( pWal->writeLock==0 && pWal->iReCksum==0 );
 57843  
 57844    if( pWal->readOnly ){
 57845      return SQLITE_READONLY;
 57846    }
 57847  
 57848    /* Only one writer allowed at a time.  Get the write lock.  Return
 57849    ** SQLITE_BUSY if unable.
 57850    */
 57851    rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
 57852    if( rc ){
 57853      return rc;
 57854    }
 57855    pWal->writeLock = 1;
 57856  
 57857    /* If another connection has written to the database file since the
 57858    ** time the read transaction on this connection was started, then
 57859    ** the write is disallowed.
 57860    */
 57861    if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
 57862      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
 57863      pWal->writeLock = 0;
 57864      rc = SQLITE_BUSY_SNAPSHOT;
 57865    }
 57866  
 57867    return rc;
 57868  }
 57869  
 57870  /*
 57871  ** End a write transaction.  The commit has already been done.  This
 57872  ** routine merely releases the lock.
 57873  */
 57874  SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
 57875    if( pWal->writeLock ){
 57876      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
 57877      pWal->writeLock = 0;
 57878      pWal->iReCksum = 0;
 57879      pWal->truncateOnCommit = 0;
 57880    }
 57881    return SQLITE_OK;
 57882  }
 57883  
 57884  /*
 57885  ** If any data has been written (but not committed) to the log file, this
 57886  ** function moves the write-pointer back to the start of the transaction.
 57887  **
 57888  ** Additionally, the callback function is invoked for each frame written
 57889  ** to the WAL since the start of the transaction. If the callback returns
 57890  ** other than SQLITE_OK, it is not invoked again and the error code is
 57891  ** returned to the caller.
 57892  **
 57893  ** Otherwise, if the callback function does not return an error, this
 57894  ** function returns SQLITE_OK.
 57895  */
 57896  SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
 57897    int rc = SQLITE_OK;
 57898    if( ALWAYS(pWal->writeLock) ){
 57899      Pgno iMax = pWal->hdr.mxFrame;
 57900      Pgno iFrame;
 57901    
 57902      /* Restore the clients cache of the wal-index header to the state it
 57903      ** was in before the client began writing to the database. 
 57904      */
 57905      memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
 57906  
 57907      for(iFrame=pWal->hdr.mxFrame+1; 
 57908          ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
 57909          iFrame++
 57910      ){
 57911        /* This call cannot fail. Unless the page for which the page number
 57912        ** is passed as the second argument is (a) in the cache and 
 57913        ** (b) has an outstanding reference, then xUndo is either a no-op
 57914        ** (if (a) is false) or simply expels the page from the cache (if (b)
 57915        ** is false).
 57916        **
 57917        ** If the upper layer is doing a rollback, it is guaranteed that there
 57918        ** are no outstanding references to any page other than page 1. And
 57919        ** page 1 is never written to the log until the transaction is
 57920        ** committed. As a result, the call to xUndo may not fail.
 57921        */
 57922        assert( walFramePgno(pWal, iFrame)!=1 );
 57923        rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
 57924      }
 57925      if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
 57926    }
 57927    return rc;
 57928  }
 57929  
 57930  /* 
 57931  ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
 57932  ** values. This function populates the array with values required to 
 57933  ** "rollback" the write position of the WAL handle back to the current 
 57934  ** point in the event of a savepoint rollback (via WalSavepointUndo()).
 57935  */
 57936  SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
 57937    assert( pWal->writeLock );
 57938    aWalData[0] = pWal->hdr.mxFrame;
 57939    aWalData[1] = pWal->hdr.aFrameCksum[0];
 57940    aWalData[2] = pWal->hdr.aFrameCksum[1];
 57941    aWalData[3] = pWal->nCkpt;
 57942  }
 57943  
 57944  /* 
 57945  ** Move the write position of the WAL back to the point identified by
 57946  ** the values in the aWalData[] array. aWalData must point to an array
 57947  ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
 57948  ** by a call to WalSavepoint().
 57949  */
 57950  SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
 57951    int rc = SQLITE_OK;
 57952  
 57953    assert( pWal->writeLock );
 57954    assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
 57955  
 57956    if( aWalData[3]!=pWal->nCkpt ){
 57957      /* This savepoint was opened immediately after the write-transaction
 57958      ** was started. Right after that, the writer decided to wrap around
 57959      ** to the start of the log. Update the savepoint values to match.
 57960      */
 57961      aWalData[0] = 0;
 57962      aWalData[3] = pWal->nCkpt;
 57963    }
 57964  
 57965    if( aWalData[0]<pWal->hdr.mxFrame ){
 57966      pWal->hdr.mxFrame = aWalData[0];
 57967      pWal->hdr.aFrameCksum[0] = aWalData[1];
 57968      pWal->hdr.aFrameCksum[1] = aWalData[2];
 57969      walCleanupHash(pWal);
 57970    }
 57971  
 57972    return rc;
 57973  }
 57974  
 57975  /*
 57976  ** This function is called just before writing a set of frames to the log
 57977  ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
 57978  ** to the current log file, it is possible to overwrite the start of the
 57979  ** existing log file with the new frames (i.e. "reset" the log). If so,
 57980  ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
 57981  ** unchanged.
 57982  **
 57983  ** SQLITE_OK is returned if no error is encountered (regardless of whether
 57984  ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
 57985  ** if an error occurs.
 57986  */
 57987  static int walRestartLog(Wal *pWal){
 57988    int rc = SQLITE_OK;
 57989    int cnt;
 57990  
 57991    if( pWal->readLock==0 ){
 57992      volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
 57993      assert( pInfo->nBackfill==pWal->hdr.mxFrame );
 57994      if( pInfo->nBackfill>0 ){
 57995        u32 salt1;
 57996        sqlite3_randomness(4, &salt1);
 57997        rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
 57998        if( rc==SQLITE_OK ){
 57999          /* If all readers are using WAL_READ_LOCK(0) (in other words if no
 58000          ** readers are currently using the WAL), then the transactions
 58001          ** frames will overwrite the start of the existing log. Update the
 58002          ** wal-index header to reflect this.
 58003          **
 58004          ** In theory it would be Ok to update the cache of the header only
 58005          ** at this point. But updating the actual wal-index header is also
 58006          ** safe and means there is no special case for sqlite3WalUndo()
 58007          ** to handle if this transaction is rolled back.  */
 58008          walRestartHdr(pWal, salt1);
 58009          walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
 58010        }else if( rc!=SQLITE_BUSY ){
 58011          return rc;
 58012        }
 58013      }
 58014      walUnlockShared(pWal, WAL_READ_LOCK(0));
 58015      pWal->readLock = -1;
 58016      cnt = 0;
 58017      do{
 58018        int notUsed;
 58019        rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
 58020      }while( rc==WAL_RETRY );
 58021      assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
 58022      testcase( (rc&0xff)==SQLITE_IOERR );
 58023      testcase( rc==SQLITE_PROTOCOL );
 58024      testcase( rc==SQLITE_OK );
 58025    }
 58026    return rc;
 58027  }
 58028  
 58029  /*
 58030  ** Information about the current state of the WAL file and where
 58031  ** the next fsync should occur - passed from sqlite3WalFrames() into
 58032  ** walWriteToLog().
 58033  */
 58034  typedef struct WalWriter {
 58035    Wal *pWal;                   /* The complete WAL information */
 58036    sqlite3_file *pFd;           /* The WAL file to which we write */
 58037    sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
 58038    int syncFlags;               /* Flags for the fsync */
 58039    int szPage;                  /* Size of one page */
 58040  } WalWriter;
 58041  
 58042  /*
 58043  ** Write iAmt bytes of content into the WAL file beginning at iOffset.
 58044  ** Do a sync when crossing the p->iSyncPoint boundary.
 58045  **
 58046  ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
 58047  ** first write the part before iSyncPoint, then sync, then write the
 58048  ** rest.
 58049  */
 58050  static int walWriteToLog(
 58051    WalWriter *p,              /* WAL to write to */
 58052    void *pContent,            /* Content to be written */
 58053    int iAmt,                  /* Number of bytes to write */
 58054    sqlite3_int64 iOffset      /* Start writing at this offset */
 58055  ){
 58056    int rc;
 58057    if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
 58058      int iFirstAmt = (int)(p->iSyncPoint - iOffset);
 58059      rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
 58060      if( rc ) return rc;
 58061      iOffset += iFirstAmt;
 58062      iAmt -= iFirstAmt;
 58063      pContent = (void*)(iFirstAmt + (char*)pContent);
 58064      assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 );
 58065      rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags));
 58066      if( iAmt==0 || rc ) return rc;
 58067    }
 58068    rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
 58069    return rc;
 58070  }
 58071  
 58072  /*
 58073  ** Write out a single frame of the WAL
 58074  */
 58075  static int walWriteOneFrame(
 58076    WalWriter *p,               /* Where to write the frame */
 58077    PgHdr *pPage,               /* The page of the frame to be written */
 58078    int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
 58079    sqlite3_int64 iOffset       /* Byte offset at which to write */
 58080  ){
 58081    int rc;                         /* Result code from subfunctions */
 58082    void *pData;                    /* Data actually written */
 58083    u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
 58084  #if defined(SQLITE_HAS_CODEC)
 58085    if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
 58086  #else
 58087    pData = pPage->pData;
 58088  #endif
 58089    walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
 58090    rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
 58091    if( rc ) return rc;
 58092    /* Write the page data */
 58093    rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
 58094    return rc;
 58095  }
 58096  
 58097  /*
 58098  ** This function is called as part of committing a transaction within which
 58099  ** one or more frames have been overwritten. It updates the checksums for
 58100  ** all frames written to the wal file by the current transaction starting
 58101  ** with the earliest to have been overwritten.
 58102  **
 58103  ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
 58104  */
 58105  static int walRewriteChecksums(Wal *pWal, u32 iLast){
 58106    const int szPage = pWal->szPage;/* Database page size */
 58107    int rc = SQLITE_OK;             /* Return code */
 58108    u8 *aBuf;                       /* Buffer to load data from wal file into */
 58109    u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-headers in */
 58110    u32 iRead;                      /* Next frame to read from wal file */
 58111    i64 iCksumOff;
 58112  
 58113    aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
 58114    if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
 58115  
 58116    /* Find the checksum values to use as input for the recalculating the
 58117    ** first checksum. If the first frame is frame 1 (implying that the current
 58118    ** transaction restarted the wal file), these values must be read from the
 58119    ** wal-file header. Otherwise, read them from the frame header of the
 58120    ** previous frame.  */
 58121    assert( pWal->iReCksum>0 );
 58122    if( pWal->iReCksum==1 ){
 58123      iCksumOff = 24;
 58124    }else{
 58125      iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
 58126    }
 58127    rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
 58128    pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
 58129    pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
 58130  
 58131    iRead = pWal->iReCksum;
 58132    pWal->iReCksum = 0;
 58133    for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
 58134      i64 iOff = walFrameOffset(iRead, szPage);
 58135      rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
 58136      if( rc==SQLITE_OK ){
 58137        u32 iPgno, nDbSize;
 58138        iPgno = sqlite3Get4byte(aBuf);
 58139        nDbSize = sqlite3Get4byte(&aBuf[4]);
 58140  
 58141        walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
 58142        rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
 58143      }
 58144    }
 58145  
 58146    sqlite3_free(aBuf);
 58147    return rc;
 58148  }
 58149  
 58150  /* 
 58151  ** Write a set of frames to the log. The caller must hold the write-lock
 58152  ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
 58153  */
 58154  SQLITE_PRIVATE int sqlite3WalFrames(
 58155    Wal *pWal,                      /* Wal handle to write to */
 58156    int szPage,                     /* Database page-size in bytes */
 58157    PgHdr *pList,                   /* List of dirty pages to write */
 58158    Pgno nTruncate,                 /* Database size after this commit */
 58159    int isCommit,                   /* True if this is a commit */
 58160    int sync_flags                  /* Flags to pass to OsSync() (or 0) */
 58161  ){
 58162    int rc;                         /* Used to catch return codes */
 58163    u32 iFrame;                     /* Next frame address */
 58164    PgHdr *p;                       /* Iterator to run through pList with. */
 58165    PgHdr *pLast = 0;               /* Last frame in list */
 58166    int nExtra = 0;                 /* Number of extra copies of last page */
 58167    int szFrame;                    /* The size of a single frame */
 58168    i64 iOffset;                    /* Next byte to write in WAL file */
 58169    WalWriter w;                    /* The writer */
 58170    u32 iFirst = 0;                 /* First frame that may be overwritten */
 58171    WalIndexHdr *pLive;             /* Pointer to shared header */
 58172  
 58173    assert( pList );
 58174    assert( pWal->writeLock );
 58175  
 58176    /* If this frame set completes a transaction, then nTruncate>0.  If
 58177    ** nTruncate==0 then this frame set does not complete the transaction. */
 58178    assert( (isCommit!=0)==(nTruncate!=0) );
 58179  
 58180  #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
 58181    { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
 58182      WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
 58183                pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
 58184    }
 58185  #endif
 58186  
 58187    pLive = (WalIndexHdr*)walIndexHdr(pWal);
 58188    if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
 58189      iFirst = pLive->mxFrame+1;
 58190    }
 58191  
 58192    /* See if it is possible to write these frames into the start of the
 58193    ** log file, instead of appending to it at pWal->hdr.mxFrame.
 58194    */
 58195    if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
 58196      return rc;
 58197    }
 58198  
 58199    /* If this is the first frame written into the log, write the WAL
 58200    ** header to the start of the WAL file. See comments at the top of
 58201    ** this source file for a description of the WAL header format.
 58202    */
 58203    iFrame = pWal->hdr.mxFrame;
 58204    if( iFrame==0 ){
 58205      u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
 58206      u32 aCksum[2];                /* Checksum for wal-header */
 58207  
 58208      sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
 58209      sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
 58210      sqlite3Put4byte(&aWalHdr[8], szPage);
 58211      sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
 58212      if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
 58213      memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
 58214      walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
 58215      sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
 58216      sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
 58217      
 58218      pWal->szPage = szPage;
 58219      pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
 58220      pWal->hdr.aFrameCksum[0] = aCksum[0];
 58221      pWal->hdr.aFrameCksum[1] = aCksum[1];
 58222      pWal->truncateOnCommit = 1;
 58223  
 58224      rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
 58225      WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
 58226      if( rc!=SQLITE_OK ){
 58227        return rc;
 58228      }
 58229  
 58230      /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
 58231      ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
 58232      ** an out-of-order write following a WAL restart could result in
 58233      ** database corruption.  See the ticket:
 58234      **
 58235      **     https://sqlite.org/src/info/ff5be73dee
 58236      */
 58237      if( pWal->syncHeader ){
 58238        rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
 58239        if( rc ) return rc;
 58240      }
 58241    }
 58242    assert( (int)pWal->szPage==szPage );
 58243  
 58244    /* Setup information needed to write frames into the WAL */
 58245    w.pWal = pWal;
 58246    w.pFd = pWal->pWalFd;
 58247    w.iSyncPoint = 0;
 58248    w.syncFlags = sync_flags;
 58249    w.szPage = szPage;
 58250    iOffset = walFrameOffset(iFrame+1, szPage);
 58251    szFrame = szPage + WAL_FRAME_HDRSIZE;
 58252  
 58253    /* Write all frames into the log file exactly once */
 58254    for(p=pList; p; p=p->pDirty){
 58255      int nDbSize;   /* 0 normally.  Positive == commit flag */
 58256  
 58257      /* Check if this page has already been written into the wal file by
 58258      ** the current transaction. If so, overwrite the existing frame and
 58259      ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that 
 58260      ** checksums must be recomputed when the transaction is committed.  */
 58261      if( iFirst && (p->pDirty || isCommit==0) ){
 58262        u32 iWrite = 0;
 58263        VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
 58264        assert( rc==SQLITE_OK || iWrite==0 );
 58265        if( iWrite>=iFirst ){
 58266          i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
 58267          void *pData;
 58268          if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
 58269            pWal->iReCksum = iWrite;
 58270          }
 58271  #if defined(SQLITE_HAS_CODEC)
 58272          if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
 58273  #else
 58274          pData = p->pData;
 58275  #endif
 58276          rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
 58277          if( rc ) return rc;
 58278          p->flags &= ~PGHDR_WAL_APPEND;
 58279          continue;
 58280        }
 58281      }
 58282  
 58283      iFrame++;
 58284      assert( iOffset==walFrameOffset(iFrame, szPage) );
 58285      nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
 58286      rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
 58287      if( rc ) return rc;
 58288      pLast = p;
 58289      iOffset += szFrame;
 58290      p->flags |= PGHDR_WAL_APPEND;
 58291    }
 58292  
 58293    /* Recalculate checksums within the wal file if required. */
 58294    if( isCommit && pWal->iReCksum ){
 58295      rc = walRewriteChecksums(pWal, iFrame);
 58296      if( rc ) return rc;
 58297    }
 58298  
 58299    /* If this is the end of a transaction, then we might need to pad
 58300    ** the transaction and/or sync the WAL file.
 58301    **
 58302    ** Padding and syncing only occur if this set of frames complete a
 58303    ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
 58304    ** or synchronous==OFF, then no padding or syncing are needed.
 58305    **
 58306    ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
 58307    ** needed and only the sync is done.  If padding is needed, then the
 58308    ** final frame is repeated (with its commit mark) until the next sector
 58309    ** boundary is crossed.  Only the part of the WAL prior to the last
 58310    ** sector boundary is synced; the part of the last frame that extends
 58311    ** past the sector boundary is written after the sync.
 58312    */
 58313    if( isCommit && WAL_SYNC_FLAGS(sync_flags)!=0 ){
 58314      int bSync = 1;
 58315      if( pWal->padToSectorBoundary ){
 58316        int sectorSize = sqlite3SectorSize(pWal->pWalFd);
 58317        w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
 58318        bSync = (w.iSyncPoint==iOffset);
 58319        testcase( bSync );
 58320        while( iOffset<w.iSyncPoint ){
 58321          rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
 58322          if( rc ) return rc;
 58323          iOffset += szFrame;
 58324          nExtra++;
 58325        }
 58326      }
 58327      if( bSync ){
 58328        assert( rc==SQLITE_OK );
 58329        rc = sqlite3OsSync(w.pFd, WAL_SYNC_FLAGS(sync_flags));
 58330      }
 58331    }
 58332  
 58333    /* If this frame set completes the first transaction in the WAL and
 58334    ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
 58335    ** journal size limit, if possible.
 58336    */
 58337    if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
 58338      i64 sz = pWal->mxWalSize;
 58339      if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
 58340        sz = walFrameOffset(iFrame+nExtra+1, szPage);
 58341      }
 58342      walLimitSize(pWal, sz);
 58343      pWal->truncateOnCommit = 0;
 58344    }
 58345  
 58346    /* Append data to the wal-index. It is not necessary to lock the 
 58347    ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
 58348    ** guarantees that there are no other writers, and no data that may
 58349    ** be in use by existing readers is being overwritten.
 58350    */
 58351    iFrame = pWal->hdr.mxFrame;
 58352    for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
 58353      if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
 58354      iFrame++;
 58355      rc = walIndexAppend(pWal, iFrame, p->pgno);
 58356    }
 58357    while( rc==SQLITE_OK && nExtra>0 ){
 58358      iFrame++;
 58359      nExtra--;
 58360      rc = walIndexAppend(pWal, iFrame, pLast->pgno);
 58361    }
 58362  
 58363    if( rc==SQLITE_OK ){
 58364      /* Update the private copy of the header. */
 58365      pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
 58366      testcase( szPage<=32768 );
 58367      testcase( szPage>=65536 );
 58368      pWal->hdr.mxFrame = iFrame;
 58369      if( isCommit ){
 58370        pWal->hdr.iChange++;
 58371        pWal->hdr.nPage = nTruncate;
 58372      }
 58373      /* If this is a commit, update the wal-index header too. */
 58374      if( isCommit ){
 58375        walIndexWriteHdr(pWal);
 58376        pWal->iCallback = iFrame;
 58377      }
 58378    }
 58379  
 58380    WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
 58381    return rc;
 58382  }
 58383  
 58384  /* 
 58385  ** This routine is called to implement sqlite3_wal_checkpoint() and
 58386  ** related interfaces.
 58387  **
 58388  ** Obtain a CHECKPOINT lock and then backfill as much information as
 58389  ** we can from WAL into the database.
 58390  **
 58391  ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
 58392  ** callback. In this case this function runs a blocking checkpoint.
 58393  */
 58394  SQLITE_PRIVATE int sqlite3WalCheckpoint(
 58395    Wal *pWal,                      /* Wal connection */
 58396    sqlite3 *db,                    /* Check this handle's interrupt flag */
 58397    int eMode,                      /* PASSIVE, FULL, RESTART, or TRUNCATE */
 58398    int (*xBusy)(void*),            /* Function to call when busy */
 58399    void *pBusyArg,                 /* Context argument for xBusyHandler */
 58400    int sync_flags,                 /* Flags to sync db file with (or 0) */
 58401    int nBuf,                       /* Size of temporary buffer */
 58402    u8 *zBuf,                       /* Temporary buffer to use */
 58403    int *pnLog,                     /* OUT: Number of frames in WAL */
 58404    int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
 58405  ){
 58406    int rc;                         /* Return code */
 58407    int isChanged = 0;              /* True if a new wal-index header is loaded */
 58408    int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
 58409    int (*xBusy2)(void*) = xBusy;   /* Busy handler for eMode2 */
 58410  
 58411    assert( pWal->ckptLock==0 );
 58412    assert( pWal->writeLock==0 );
 58413  
 58414    /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
 58415    ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
 58416    assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
 58417  
 58418    if( pWal->readOnly ) return SQLITE_READONLY;
 58419    WALTRACE(("WAL%p: checkpoint begins\n", pWal));
 58420  
 58421    /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive 
 58422    ** "checkpoint" lock on the database file. */
 58423    rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
 58424    if( rc ){
 58425      /* EVIDENCE-OF: R-10421-19736 If any other process is running a
 58426      ** checkpoint operation at the same time, the lock cannot be obtained and
 58427      ** SQLITE_BUSY is returned.
 58428      ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
 58429      ** it will not be invoked in this case.
 58430      */
 58431      testcase( rc==SQLITE_BUSY );
 58432      testcase( xBusy!=0 );
 58433      return rc;
 58434    }
 58435    pWal->ckptLock = 1;
 58436  
 58437    /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
 58438    ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
 58439    ** file.
 58440    **
 58441    ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
 58442    ** immediately, and a busy-handler is configured, it is invoked and the
 58443    ** writer lock retried until either the busy-handler returns 0 or the
 58444    ** lock is successfully obtained.
 58445    */
 58446    if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
 58447      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
 58448      if( rc==SQLITE_OK ){
 58449        pWal->writeLock = 1;
 58450      }else if( rc==SQLITE_BUSY ){
 58451        eMode2 = SQLITE_CHECKPOINT_PASSIVE;
 58452        xBusy2 = 0;
 58453        rc = SQLITE_OK;
 58454      }
 58455    }
 58456  
 58457    /* Read the wal-index header. */
 58458    if( rc==SQLITE_OK ){
 58459      rc = walIndexReadHdr(pWal, &isChanged);
 58460      if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
 58461        sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
 58462      }
 58463    }
 58464  
 58465    /* Copy data from the log to the database file. */
 58466    if( rc==SQLITE_OK ){
 58467  
 58468      if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
 58469        rc = SQLITE_CORRUPT_BKPT;
 58470      }else{
 58471        rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
 58472      }
 58473  
 58474      /* If no error occurred, set the output variables. */
 58475      if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
 58476        if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
 58477        if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
 58478      }
 58479    }
 58480  
 58481    if( isChanged ){
 58482      /* If a new wal-index header was loaded before the checkpoint was 
 58483      ** performed, then the pager-cache associated with pWal is now
 58484      ** out of date. So zero the cached wal-index header to ensure that
 58485      ** next time the pager opens a snapshot on this database it knows that
 58486      ** the cache needs to be reset.
 58487      */
 58488      memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
 58489    }
 58490  
 58491    /* Release the locks. */
 58492    sqlite3WalEndWriteTransaction(pWal);
 58493    walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
 58494    pWal->ckptLock = 0;
 58495    WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
 58496    return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
 58497  }
 58498  
 58499  /* Return the value to pass to a sqlite3_wal_hook callback, the
 58500  ** number of frames in the WAL at the point of the last commit since
 58501  ** sqlite3WalCallback() was called.  If no commits have occurred since
 58502  ** the last call, then return 0.
 58503  */
 58504  SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
 58505    u32 ret = 0;
 58506    if( pWal ){
 58507      ret = pWal->iCallback;
 58508      pWal->iCallback = 0;
 58509    }
 58510    return (int)ret;
 58511  }
 58512  
 58513  /*
 58514  ** This function is called to change the WAL subsystem into or out
 58515  ** of locking_mode=EXCLUSIVE.
 58516  **
 58517  ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
 58518  ** into locking_mode=NORMAL.  This means that we must acquire a lock
 58519  ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
 58520  ** or if the acquisition of the lock fails, then return 0.  If the
 58521  ** transition out of exclusive-mode is successful, return 1.  This
 58522  ** operation must occur while the pager is still holding the exclusive
 58523  ** lock on the main database file.
 58524  **
 58525  ** If op is one, then change from locking_mode=NORMAL into 
 58526  ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
 58527  ** be released.  Return 1 if the transition is made and 0 if the
 58528  ** WAL is already in exclusive-locking mode - meaning that this
 58529  ** routine is a no-op.  The pager must already hold the exclusive lock
 58530  ** on the main database file before invoking this operation.
 58531  **
 58532  ** If op is negative, then do a dry-run of the op==1 case but do
 58533  ** not actually change anything. The pager uses this to see if it
 58534  ** should acquire the database exclusive lock prior to invoking
 58535  ** the op==1 case.
 58536  */
 58537  SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
 58538    int rc;
 58539    assert( pWal->writeLock==0 );
 58540    assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
 58541  
 58542    /* pWal->readLock is usually set, but might be -1 if there was a 
 58543    ** prior error while attempting to acquire are read-lock. This cannot 
 58544    ** happen if the connection is actually in exclusive mode (as no xShmLock
 58545    ** locks are taken in this case). Nor should the pager attempt to
 58546    ** upgrade to exclusive-mode following such an error.
 58547    */
 58548    assert( pWal->readLock>=0 || pWal->lockError );
 58549    assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
 58550  
 58551    if( op==0 ){
 58552      if( pWal->exclusiveMode ){
 58553        pWal->exclusiveMode = 0;
 58554        if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
 58555          pWal->exclusiveMode = 1;
 58556        }
 58557        rc = pWal->exclusiveMode==0;
 58558      }else{
 58559        /* Already in locking_mode=NORMAL */
 58560        rc = 0;
 58561      }
 58562    }else if( op>0 ){
 58563      assert( pWal->exclusiveMode==0 );
 58564      assert( pWal->readLock>=0 );
 58565      walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
 58566      pWal->exclusiveMode = 1;
 58567      rc = 1;
 58568    }else{
 58569      rc = pWal->exclusiveMode==0;
 58570    }
 58571    return rc;
 58572  }
 58573  
 58574  /* 
 58575  ** Return true if the argument is non-NULL and the WAL module is using
 58576  ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
 58577  ** WAL module is using shared-memory, return false. 
 58578  */
 58579  SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
 58580    return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
 58581  }
 58582  
 58583  #ifdef SQLITE_ENABLE_SNAPSHOT
 58584  /* Create a snapshot object.  The content of a snapshot is opaque to
 58585  ** every other subsystem, so the WAL module can put whatever it needs
 58586  ** in the object.
 58587  */
 58588  SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
 58589    int rc = SQLITE_OK;
 58590    WalIndexHdr *pRet;
 58591    static const u32 aZero[4] = { 0, 0, 0, 0 };
 58592  
 58593    assert( pWal->readLock>=0 && pWal->writeLock==0 );
 58594  
 58595    if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
 58596      *ppSnapshot = 0;
 58597      return SQLITE_ERROR;
 58598    }
 58599    pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
 58600    if( pRet==0 ){
 58601      rc = SQLITE_NOMEM_BKPT;
 58602    }else{
 58603      memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
 58604      *ppSnapshot = (sqlite3_snapshot*)pRet;
 58605    }
 58606  
 58607    return rc;
 58608  }
 58609  
 58610  /* Try to open on pSnapshot when the next read-transaction starts
 58611  */
 58612  SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
 58613    pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
 58614  }
 58615  
 58616  /* 
 58617  ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
 58618  ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
 58619  */
 58620  SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
 58621    WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
 58622    WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
 58623  
 58624    /* aSalt[0] is a copy of the value stored in the wal file header. It
 58625    ** is incremented each time the wal file is restarted.  */
 58626    if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
 58627    if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
 58628    if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
 58629    if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
 58630    return 0;
 58631  }
 58632  #endif /* SQLITE_ENABLE_SNAPSHOT */
 58633  
 58634  #ifdef SQLITE_ENABLE_ZIPVFS
 58635  /*
 58636  ** If the argument is not NULL, it points to a Wal object that holds a
 58637  ** read-lock. This function returns the database page-size if it is known,
 58638  ** or zero if it is not (or if pWal is NULL).
 58639  */
 58640  SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
 58641    assert( pWal==0 || pWal->readLock>=0 );
 58642    return (pWal ? pWal->szPage : 0);
 58643  }
 58644  #endif
 58645  
 58646  /* Return the sqlite3_file object for the WAL file
 58647  */
 58648  SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
 58649    return pWal->pWalFd;
 58650  }
 58651  
 58652  #endif /* #ifndef SQLITE_OMIT_WAL */
 58653  
 58654  /************** End of wal.c *************************************************/
 58655  /************** Begin file btmutex.c *****************************************/
 58656  /*
 58657  ** 2007 August 27
 58658  **
 58659  ** The author disclaims copyright to this source code.  In place of
 58660  ** a legal notice, here is a blessing:
 58661  **
 58662  **    May you do good and not evil.
 58663  **    May you find forgiveness for yourself and forgive others.
 58664  **    May you share freely, never taking more than you give.
 58665  **
 58666  *************************************************************************
 58667  **
 58668  ** This file contains code used to implement mutexes on Btree objects.
 58669  ** This code really belongs in btree.c.  But btree.c is getting too
 58670  ** big and we want to break it down some.  This packaged seemed like
 58671  ** a good breakout.
 58672  */
 58673  /************** Include btreeInt.h in the middle of btmutex.c ****************/
 58674  /************** Begin file btreeInt.h ****************************************/
 58675  /*
 58676  ** 2004 April 6
 58677  **
 58678  ** The author disclaims copyright to this source code.  In place of
 58679  ** a legal notice, here is a blessing:
 58680  **
 58681  **    May you do good and not evil.
 58682  **    May you find forgiveness for yourself and forgive others.
 58683  **    May you share freely, never taking more than you give.
 58684  **
 58685  *************************************************************************
 58686  ** This file implements an external (disk-based) database using BTrees.
 58687  ** For a detailed discussion of BTrees, refer to
 58688  **
 58689  **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
 58690  **     "Sorting And Searching", pages 473-480. Addison-Wesley
 58691  **     Publishing Company, Reading, Massachusetts.
 58692  **
 58693  ** The basic idea is that each page of the file contains N database
 58694  ** entries and N+1 pointers to subpages.
 58695  **
 58696  **   ----------------------------------------------------------------
 58697  **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
 58698  **   ----------------------------------------------------------------
 58699  **
 58700  ** All of the keys on the page that Ptr(0) points to have values less
 58701  ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
 58702  ** values greater than Key(0) and less than Key(1).  All of the keys
 58703  ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
 58704  ** so forth.
 58705  **
 58706  ** Finding a particular key requires reading O(log(M)) pages from the 
 58707  ** disk where M is the number of entries in the tree.
 58708  **
 58709  ** In this implementation, a single file can hold one or more separate 
 58710  ** BTrees.  Each BTree is identified by the index of its root page.  The
 58711  ** key and data for any entry are combined to form the "payload".  A
 58712  ** fixed amount of payload can be carried directly on the database
 58713  ** page.  If the payload is larger than the preset amount then surplus
 58714  ** bytes are stored on overflow pages.  The payload for an entry
 58715  ** and the preceding pointer are combined to form a "Cell".  Each 
 58716  ** page has a small header which contains the Ptr(N) pointer and other
 58717  ** information such as the size of key and data.
 58718  **
 58719  ** FORMAT DETAILS
 58720  **
 58721  ** The file is divided into pages.  The first page is called page 1,
 58722  ** the second is page 2, and so forth.  A page number of zero indicates
 58723  ** "no such page".  The page size can be any power of 2 between 512 and 65536.
 58724  ** Each page can be either a btree page, a freelist page, an overflow
 58725  ** page, or a pointer-map page.
 58726  **
 58727  ** The first page is always a btree page.  The first 100 bytes of the first
 58728  ** page contain a special header (the "file header") that describes the file.
 58729  ** The format of the file header is as follows:
 58730  **
 58731  **   OFFSET   SIZE    DESCRIPTION
 58732  **      0      16     Header string: "SQLite format 3\000"
 58733  **     16       2     Page size in bytes.  (1 means 65536)
 58734  **     18       1     File format write version
 58735  **     19       1     File format read version
 58736  **     20       1     Bytes of unused space at the end of each page
 58737  **     21       1     Max embedded payload fraction (must be 64)
 58738  **     22       1     Min embedded payload fraction (must be 32)
 58739  **     23       1     Min leaf payload fraction (must be 32)
 58740  **     24       4     File change counter
 58741  **     28       4     Reserved for future use
 58742  **     32       4     First freelist page
 58743  **     36       4     Number of freelist pages in the file
 58744  **     40      60     15 4-byte meta values passed to higher layers
 58745  **
 58746  **     40       4     Schema cookie
 58747  **     44       4     File format of schema layer
 58748  **     48       4     Size of page cache
 58749  **     52       4     Largest root-page (auto/incr_vacuum)
 58750  **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
 58751  **     60       4     User version
 58752  **     64       4     Incremental vacuum mode
 58753  **     68       4     Application-ID
 58754  **     72      20     unused
 58755  **     92       4     The version-valid-for number
 58756  **     96       4     SQLITE_VERSION_NUMBER
 58757  **
 58758  ** All of the integer values are big-endian (most significant byte first).
 58759  **
 58760  ** The file change counter is incremented when the database is changed
 58761  ** This counter allows other processes to know when the file has changed
 58762  ** and thus when they need to flush their cache.
 58763  **
 58764  ** The max embedded payload fraction is the amount of the total usable
 58765  ** space in a page that can be consumed by a single cell for standard
 58766  ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
 58767  ** is to limit the maximum cell size so that at least 4 cells will fit
 58768  ** on one page.  Thus the default max embedded payload fraction is 64.
 58769  **
 58770  ** If the payload for a cell is larger than the max payload, then extra
 58771  ** payload is spilled to overflow pages.  Once an overflow page is allocated,
 58772  ** as many bytes as possible are moved into the overflow pages without letting
 58773  ** the cell size drop below the min embedded payload fraction.
 58774  **
 58775  ** The min leaf payload fraction is like the min embedded payload fraction
 58776  ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
 58777  ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
 58778  ** not specified in the header.
 58779  **
 58780  ** Each btree pages is divided into three sections:  The header, the
 58781  ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
 58782  ** file header that occurs before the page header.
 58783  **
 58784  **      |----------------|
 58785  **      | file header    |   100 bytes.  Page 1 only.
 58786  **      |----------------|
 58787  **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
 58788  **      |----------------|
 58789  **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
 58790  **      | array          |   |  Grows downward
 58791  **      |                |   v
 58792  **      |----------------|
 58793  **      | unallocated    |
 58794  **      | space          |
 58795  **      |----------------|   ^  Grows upwards
 58796  **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
 58797  **      | area           |   |  and free space fragments.
 58798  **      |----------------|
 58799  **
 58800  ** The page headers looks like this:
 58801  **
 58802  **   OFFSET   SIZE     DESCRIPTION
 58803  **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
 58804  **      1       2      byte offset to the first freeblock
 58805  **      3       2      number of cells on this page
 58806  **      5       2      first byte of the cell content area
 58807  **      7       1      number of fragmented free bytes
 58808  **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
 58809  **
 58810  ** The flags define the format of this btree page.  The leaf flag means that
 58811  ** this page has no children.  The zerodata flag means that this page carries
 58812  ** only keys and no data.  The intkey flag means that the key is an integer
 58813  ** which is stored in the key size entry of the cell header rather than in
 58814  ** the payload area.
 58815  **
 58816  ** The cell pointer array begins on the first byte after the page header.
 58817  ** The cell pointer array contains zero or more 2-byte numbers which are
 58818  ** offsets from the beginning of the page to the cell content in the cell
 58819  ** content area.  The cell pointers occur in sorted order.  The system strives
 58820  ** to keep free space after the last cell pointer so that new cells can
 58821  ** be easily added without having to defragment the page.
 58822  **
 58823  ** Cell content is stored at the very end of the page and grows toward the
 58824  ** beginning of the page.
 58825  **
 58826  ** Unused space within the cell content area is collected into a linked list of
 58827  ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
 58828  ** to the first freeblock is given in the header.  Freeblocks occur in
 58829  ** increasing order.  Because a freeblock must be at least 4 bytes in size,
 58830  ** any group of 3 or fewer unused bytes in the cell content area cannot
 58831  ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
 58832  ** a fragment.  The total number of bytes in all fragments is recorded.
 58833  ** in the page header at offset 7.
 58834  **
 58835  **    SIZE    DESCRIPTION
 58836  **      2     Byte offset of the next freeblock
 58837  **      2     Bytes in this freeblock
 58838  **
 58839  ** Cells are of variable length.  Cells are stored in the cell content area at
 58840  ** the end of the page.  Pointers to the cells are in the cell pointer array
 58841  ** that immediately follows the page header.  Cells is not necessarily
 58842  ** contiguous or in order, but cell pointers are contiguous and in order.
 58843  **
 58844  ** Cell content makes use of variable length integers.  A variable
 58845  ** length integer is 1 to 9 bytes where the lower 7 bits of each 
 58846  ** byte are used.  The integer consists of all bytes that have bit 8 set and
 58847  ** the first byte with bit 8 clear.  The most significant byte of the integer
 58848  ** appears first.  A variable-length integer may not be more than 9 bytes long.
 58849  ** As a special case, all 8 bytes of the 9th byte are used as data.  This
 58850  ** allows a 64-bit integer to be encoded in 9 bytes.
 58851  **
 58852  **    0x00                      becomes  0x00000000
 58853  **    0x7f                      becomes  0x0000007f
 58854  **    0x81 0x00                 becomes  0x00000080
 58855  **    0x82 0x00                 becomes  0x00000100
 58856  **    0x80 0x7f                 becomes  0x0000007f
 58857  **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
 58858  **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
 58859  **
 58860  ** Variable length integers are used for rowids and to hold the number of
 58861  ** bytes of key and data in a btree cell.
 58862  **
 58863  ** The content of a cell looks like this:
 58864  **
 58865  **    SIZE    DESCRIPTION
 58866  **      4     Page number of the left child. Omitted if leaf flag is set.
 58867  **     var    Number of bytes of data. Omitted if the zerodata flag is set.
 58868  **     var    Number of bytes of key. Or the key itself if intkey flag is set.
 58869  **      *     Payload
 58870  **      4     First page of the overflow chain.  Omitted if no overflow
 58871  **
 58872  ** Overflow pages form a linked list.  Each page except the last is completely
 58873  ** filled with data (pagesize - 4 bytes).  The last page can have as little
 58874  ** as 1 byte of data.
 58875  **
 58876  **    SIZE    DESCRIPTION
 58877  **      4     Page number of next overflow page
 58878  **      *     Data
 58879  **
 58880  ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
 58881  ** file header points to the first in a linked list of trunk page.  Each trunk
 58882  ** page points to multiple leaf pages.  The content of a leaf page is
 58883  ** unspecified.  A trunk page looks like this:
 58884  **
 58885  **    SIZE    DESCRIPTION
 58886  **      4     Page number of next trunk page
 58887  **      4     Number of leaf pointers on this page
 58888  **      *     zero or more pages numbers of leaves
 58889  */
 58890  /* #include "sqliteInt.h" */
 58891  
 58892  
 58893  /* The following value is the maximum cell size assuming a maximum page
 58894  ** size give above.
 58895  */
 58896  #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
 58897  
 58898  /* The maximum number of cells on a single page of the database.  This
 58899  ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
 58900  ** plus 2 bytes for the index to the cell in the page header).  Such
 58901  ** small cells will be rare, but they are possible.
 58902  */
 58903  #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
 58904  
 58905  /* Forward declarations */
 58906  typedef struct MemPage MemPage;
 58907  typedef struct BtLock BtLock;
 58908  typedef struct CellInfo CellInfo;
 58909  
 58910  /*
 58911  ** This is a magic string that appears at the beginning of every
 58912  ** SQLite database in order to identify the file as a real database.
 58913  **
 58914  ** You can change this value at compile-time by specifying a
 58915  ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
 58916  ** header must be exactly 16 bytes including the zero-terminator so
 58917  ** the string itself should be 15 characters long.  If you change
 58918  ** the header, then your custom library will not be able to read 
 58919  ** databases generated by the standard tools and the standard tools
 58920  ** will not be able to read databases created by your custom library.
 58921  */
 58922  #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
 58923  #  define SQLITE_FILE_HEADER "SQLite format 3"
 58924  #endif
 58925  
 58926  /*
 58927  ** Page type flags.  An ORed combination of these flags appear as the
 58928  ** first byte of on-disk image of every BTree page.
 58929  */
 58930  #define PTF_INTKEY    0x01
 58931  #define PTF_ZERODATA  0x02
 58932  #define PTF_LEAFDATA  0x04
 58933  #define PTF_LEAF      0x08
 58934  
 58935  /*
 58936  ** An instance of this object stores information about each a single database
 58937  ** page that has been loaded into memory.  The information in this object
 58938  ** is derived from the raw on-disk page content.
 58939  **
 58940  ** As each database page is loaded into memory, the pager allocats an
 58941  ** instance of this object and zeros the first 8 bytes.  (This is the
 58942  ** "extra" information associated with each page of the pager.)
 58943  **
 58944  ** Access to all fields of this structure is controlled by the mutex
 58945  ** stored in MemPage.pBt->mutex.
 58946  */
 58947  struct MemPage {
 58948    u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
 58949    u8 bBusy;            /* Prevent endless loops on corrupt database files */
 58950    u8 intKey;           /* True if table b-trees.  False for index b-trees */
 58951    u8 intKeyLeaf;       /* True if the leaf of an intKey table */
 58952    Pgno pgno;           /* Page number for this page */
 58953    /* Only the first 8 bytes (above) are zeroed by pager.c when a new page
 58954    ** is allocated. All fields that follow must be initialized before use */
 58955    u8 leaf;             /* True if a leaf page */
 58956    u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
 58957    u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
 58958    u8 max1bytePayload;  /* min(maxLocal,127) */
 58959    u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
 58960    u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
 58961    u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
 58962    u16 cellOffset;      /* Index in aData of first cell pointer */
 58963    u16 nFree;           /* Number of free bytes on the page */
 58964    u16 nCell;           /* Number of cells on this page, local and ovfl */
 58965    u16 maskPage;        /* Mask for page offset */
 58966    u16 aiOvfl[4];       /* Insert the i-th overflow cell before the aiOvfl-th
 58967                         ** non-overflow cell */
 58968    u8 *apOvfl[4];       /* Pointers to the body of overflow cells */
 58969    BtShared *pBt;       /* Pointer to BtShared that this page is part of */
 58970    u8 *aData;           /* Pointer to disk image of the page data */
 58971    u8 *aDataEnd;        /* One byte past the end of usable data */
 58972    u8 *aCellIdx;        /* The cell index area */
 58973    u8 *aDataOfst;       /* Same as aData for leaves.  aData+4 for interior */
 58974    DbPage *pDbPage;     /* Pager page handle */
 58975    u16 (*xCellSize)(MemPage*,u8*);             /* cellSizePtr method */
 58976    void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
 58977  };
 58978  
 58979  /*
 58980  ** A linked list of the following structures is stored at BtShared.pLock.
 58981  ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
 58982  ** is opened on the table with root page BtShared.iTable. Locks are removed
 58983  ** from this list when a transaction is committed or rolled back, or when
 58984  ** a btree handle is closed.
 58985  */
 58986  struct BtLock {
 58987    Btree *pBtree;        /* Btree handle holding this lock */
 58988    Pgno iTable;          /* Root page of table */
 58989    u8 eLock;             /* READ_LOCK or WRITE_LOCK */
 58990    BtLock *pNext;        /* Next in BtShared.pLock list */
 58991  };
 58992  
 58993  /* Candidate values for BtLock.eLock */
 58994  #define READ_LOCK     1
 58995  #define WRITE_LOCK    2
 58996  
 58997  /* A Btree handle
 58998  **
 58999  ** A database connection contains a pointer to an instance of
 59000  ** this object for every database file that it has open.  This structure
 59001  ** is opaque to the database connection.  The database connection cannot
 59002  ** see the internals of this structure and only deals with pointers to
 59003  ** this structure.
 59004  **
 59005  ** For some database files, the same underlying database cache might be 
 59006  ** shared between multiple connections.  In that case, each connection
 59007  ** has it own instance of this object.  But each instance of this object
 59008  ** points to the same BtShared object.  The database cache and the
 59009  ** schema associated with the database file are all contained within
 59010  ** the BtShared object.
 59011  **
 59012  ** All fields in this structure are accessed under sqlite3.mutex.
 59013  ** The pBt pointer itself may not be changed while there exists cursors 
 59014  ** in the referenced BtShared that point back to this Btree since those
 59015  ** cursors have to go through this Btree to find their BtShared and
 59016  ** they often do so without holding sqlite3.mutex.
 59017  */
 59018  struct Btree {
 59019    sqlite3 *db;       /* The database connection holding this btree */
 59020    BtShared *pBt;     /* Sharable content of this btree */
 59021    u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
 59022    u8 sharable;       /* True if we can share pBt with another db */
 59023    u8 locked;         /* True if db currently has pBt locked */
 59024    u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
 59025    int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
 59026    int nBackup;       /* Number of backup operations reading this btree */
 59027    u32 iDataVersion;  /* Combines with pBt->pPager->iDataVersion */
 59028    Btree *pNext;      /* List of other sharable Btrees from the same db */
 59029    Btree *pPrev;      /* Back pointer of the same list */
 59030  #ifndef SQLITE_OMIT_SHARED_CACHE
 59031    BtLock lock;       /* Object used to lock page 1 */
 59032  #endif
 59033  };
 59034  
 59035  /*
 59036  ** Btree.inTrans may take one of the following values.
 59037  **
 59038  ** If the shared-data extension is enabled, there may be multiple users
 59039  ** of the Btree structure. At most one of these may open a write transaction,
 59040  ** but any number may have active read transactions.
 59041  */
 59042  #define TRANS_NONE  0
 59043  #define TRANS_READ  1
 59044  #define TRANS_WRITE 2
 59045  
 59046  /*
 59047  ** An instance of this object represents a single database file.
 59048  ** 
 59049  ** A single database file can be in use at the same time by two
 59050  ** or more database connections.  When two or more connections are
 59051  ** sharing the same database file, each connection has it own
 59052  ** private Btree object for the file and each of those Btrees points
 59053  ** to this one BtShared object.  BtShared.nRef is the number of
 59054  ** connections currently sharing this database file.
 59055  **
 59056  ** Fields in this structure are accessed under the BtShared.mutex
 59057  ** mutex, except for nRef and pNext which are accessed under the
 59058  ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
 59059  ** may not be modified once it is initially set as long as nRef>0.
 59060  ** The pSchema field may be set once under BtShared.mutex and
 59061  ** thereafter is unchanged as long as nRef>0.
 59062  **
 59063  ** isPending:
 59064  **
 59065  **   If a BtShared client fails to obtain a write-lock on a database
 59066  **   table (because there exists one or more read-locks on the table),
 59067  **   the shared-cache enters 'pending-lock' state and isPending is
 59068  **   set to true.
 59069  **
 59070  **   The shared-cache leaves the 'pending lock' state when either of
 59071  **   the following occur:
 59072  **
 59073  **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
 59074  **     2) The number of locks held by other connections drops to zero.
 59075  **
 59076  **   while in the 'pending-lock' state, no connection may start a new
 59077  **   transaction.
 59078  **
 59079  **   This feature is included to help prevent writer-starvation.
 59080  */
 59081  struct BtShared {
 59082    Pager *pPager;        /* The page cache */
 59083    sqlite3 *db;          /* Database connection currently using this Btree */
 59084    BtCursor *pCursor;    /* A list of all open cursors */
 59085    MemPage *pPage1;      /* First page of the database */
 59086    u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
 59087  #ifndef SQLITE_OMIT_AUTOVACUUM
 59088    u8 autoVacuum;        /* True if auto-vacuum is enabled */
 59089    u8 incrVacuum;        /* True if incr-vacuum is enabled */
 59090    u8 bDoTruncate;       /* True to truncate db on commit */
 59091  #endif
 59092    u8 inTransaction;     /* Transaction state */
 59093    u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
 59094  #ifdef SQLITE_HAS_CODEC
 59095    u8 optimalReserve;    /* Desired amount of reserved space per page */
 59096  #endif
 59097    u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
 59098    u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
 59099    u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
 59100    u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
 59101    u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
 59102    u32 pageSize;         /* Total number of bytes on a page */
 59103    u32 usableSize;       /* Number of usable bytes on each page */
 59104    int nTransaction;     /* Number of open transactions (read + write) */
 59105    u32 nPage;            /* Number of pages in the database */
 59106    void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
 59107    void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
 59108    sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
 59109    Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
 59110  #ifndef SQLITE_OMIT_SHARED_CACHE
 59111    int nRef;             /* Number of references to this structure */
 59112    BtShared *pNext;      /* Next on a list of sharable BtShared structs */
 59113    BtLock *pLock;        /* List of locks held on this shared-btree struct */
 59114    Btree *pWriter;       /* Btree with currently open write transaction */
 59115  #endif
 59116    u8 *pTmpSpace;        /* Temp space sufficient to hold a single cell */
 59117  };
 59118  
 59119  /*
 59120  ** Allowed values for BtShared.btsFlags
 59121  */
 59122  #define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
 59123  #define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
 59124  #define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
 59125  #define BTS_OVERWRITE        0x0008   /* Overwrite deleted content with zeros */
 59126  #define BTS_FAST_SECURE      0x000c   /* Combination of the previous two */
 59127  #define BTS_INITIALLY_EMPTY  0x0010   /* Database was empty at trans start */
 59128  #define BTS_NO_WAL           0x0020   /* Do not open write-ahead-log files */
 59129  #define BTS_EXCLUSIVE        0x0040   /* pWriter has an exclusive lock */
 59130  #define BTS_PENDING          0x0080   /* Waiting for read-locks to clear */
 59131  
 59132  /*
 59133  ** An instance of the following structure is used to hold information
 59134  ** about a cell.  The parseCellPtr() function fills in this structure
 59135  ** based on information extract from the raw disk page.
 59136  */
 59137  struct CellInfo {
 59138    i64 nKey;      /* The key for INTKEY tables, or nPayload otherwise */
 59139    u8 *pPayload;  /* Pointer to the start of payload */
 59140    u32 nPayload;  /* Bytes of payload */
 59141    u16 nLocal;    /* Amount of payload held locally, not on overflow */
 59142    u16 nSize;     /* Size of the cell content on the main b-tree page */
 59143  };
 59144  
 59145  /*
 59146  ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
 59147  ** this will be declared corrupt. This value is calculated based on a
 59148  ** maximum database size of 2^31 pages a minimum fanout of 2 for a
 59149  ** root-node and 3 for all other internal nodes.
 59150  **
 59151  ** If a tree that appears to be taller than this is encountered, it is
 59152  ** assumed that the database is corrupt.
 59153  */
 59154  #define BTCURSOR_MAX_DEPTH 20
 59155  
 59156  /*
 59157  ** A cursor is a pointer to a particular entry within a particular
 59158  ** b-tree within a database file.
 59159  **
 59160  ** The entry is identified by its MemPage and the index in
 59161  ** MemPage.aCell[] of the entry.
 59162  **
 59163  ** A single database file can be shared by two more database connections,
 59164  ** but cursors cannot be shared.  Each cursor is associated with a
 59165  ** particular database connection identified BtCursor.pBtree.db.
 59166  **
 59167  ** Fields in this structure are accessed under the BtShared.mutex
 59168  ** found at self->pBt->mutex. 
 59169  **
 59170  ** skipNext meaning:
 59171  **    eState==SKIPNEXT && skipNext>0:  Next sqlite3BtreeNext() is no-op.
 59172  **    eState==SKIPNEXT && skipNext<0:  Next sqlite3BtreePrevious() is no-op.
 59173  **    eState==FAULT:                   Cursor fault with skipNext as error code.
 59174  */
 59175  struct BtCursor {
 59176    u8 eState;                /* One of the CURSOR_XXX constants (see below) */
 59177    u8 curFlags;              /* zero or more BTCF_* flags defined below */
 59178    u8 curPagerFlags;         /* Flags to send to sqlite3PagerGet() */
 59179    u8 hints;                 /* As configured by CursorSetHints() */
 59180    int nOvflAlloc;           /* Allocated size of aOverflow[] array */
 59181    Btree *pBtree;            /* The Btree to which this cursor belongs */
 59182    BtShared *pBt;            /* The BtShared this cursor points to */
 59183    BtCursor *pNext;          /* Forms a linked list of all cursors */
 59184    Pgno *aOverflow;          /* Cache of overflow page locations */
 59185    CellInfo info;            /* A parse of the cell we are pointing at */
 59186    i64 nKey;                 /* Size of pKey, or last integer key */
 59187    void *pKey;               /* Saved key that was cursor last known position */
 59188    Pgno pgnoRoot;            /* The root page of this tree */
 59189    int skipNext;    /* Prev() is noop if negative. Next() is noop if positive.
 59190                     ** Error code if eState==CURSOR_FAULT */
 59191    /* All fields above are zeroed when the cursor is allocated.  See
 59192    ** sqlite3BtreeCursorZero().  Fields that follow must be manually
 59193    ** initialized. */
 59194    i8 iPage;                 /* Index of current page in apPage */
 59195    u8 curIntKey;             /* Value of apPage[0]->intKey */
 59196    u16 ix;                   /* Current index for apPage[iPage] */
 59197    u16 aiIdx[BTCURSOR_MAX_DEPTH-1];     /* Current index in apPage[i] */
 59198    struct KeyInfo *pKeyInfo;            /* Arg passed to comparison function */
 59199    MemPage *pPage;                        /* Current page */
 59200    MemPage *apPage[BTCURSOR_MAX_DEPTH-1]; /* Stack of parents of current page */
 59201  };
 59202  
 59203  /*
 59204  ** Legal values for BtCursor.curFlags
 59205  */
 59206  #define BTCF_WriteFlag    0x01   /* True if a write cursor */
 59207  #define BTCF_ValidNKey    0x02   /* True if info.nKey is valid */
 59208  #define BTCF_ValidOvfl    0x04   /* True if aOverflow is valid */
 59209  #define BTCF_AtLast       0x08   /* Cursor is pointing ot the last entry */
 59210  #define BTCF_Incrblob     0x10   /* True if an incremental I/O handle */
 59211  #define BTCF_Multiple     0x20   /* Maybe another cursor on the same btree */
 59212  
 59213  /*
 59214  ** Potential values for BtCursor.eState.
 59215  **
 59216  ** CURSOR_INVALID:
 59217  **   Cursor does not point to a valid entry. This can happen (for example) 
 59218  **   because the table is empty or because BtreeCursorFirst() has not been
 59219  **   called.
 59220  **
 59221  ** CURSOR_VALID:
 59222  **   Cursor points to a valid entry. getPayload() etc. may be called.
 59223  **
 59224  ** CURSOR_SKIPNEXT:
 59225  **   Cursor is valid except that the Cursor.skipNext field is non-zero
 59226  **   indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
 59227  **   operation should be a no-op.
 59228  **
 59229  ** CURSOR_REQUIRESEEK:
 59230  **   The table that this cursor was opened on still exists, but has been 
 59231  **   modified since the cursor was last used. The cursor position is saved
 59232  **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
 59233  **   this state, restoreCursorPosition() can be called to attempt to
 59234  **   seek the cursor to the saved position.
 59235  **
 59236  ** CURSOR_FAULT:
 59237  **   An unrecoverable error (an I/O error or a malloc failure) has occurred
 59238  **   on a different connection that shares the BtShared cache with this
 59239  **   cursor.  The error has left the cache in an inconsistent state.
 59240  **   Do nothing else with this cursor.  Any attempt to use the cursor
 59241  **   should return the error code stored in BtCursor.skipNext
 59242  */
 59243  #define CURSOR_INVALID           0
 59244  #define CURSOR_VALID             1
 59245  #define CURSOR_SKIPNEXT          2
 59246  #define CURSOR_REQUIRESEEK       3
 59247  #define CURSOR_FAULT             4
 59248  
 59249  /* 
 59250  ** The database page the PENDING_BYTE occupies. This page is never used.
 59251  */
 59252  # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
 59253  
 59254  /*
 59255  ** These macros define the location of the pointer-map entry for a 
 59256  ** database page. The first argument to each is the number of usable
 59257  ** bytes on each page of the database (often 1024). The second is the
 59258  ** page number to look up in the pointer map.
 59259  **
 59260  ** PTRMAP_PAGENO returns the database page number of the pointer-map
 59261  ** page that stores the required pointer. PTRMAP_PTROFFSET returns
 59262  ** the offset of the requested map entry.
 59263  **
 59264  ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
 59265  ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
 59266  ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
 59267  ** this test.
 59268  */
 59269  #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
 59270  #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
 59271  #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
 59272  
 59273  /*
 59274  ** The pointer map is a lookup table that identifies the parent page for
 59275  ** each child page in the database file.  The parent page is the page that
 59276  ** contains a pointer to the child.  Every page in the database contains
 59277  ** 0 or 1 parent pages.  (In this context 'database page' refers
 59278  ** to any page that is not part of the pointer map itself.)  Each pointer map
 59279  ** entry consists of a single byte 'type' and a 4 byte parent page number.
 59280  ** The PTRMAP_XXX identifiers below are the valid types.
 59281  **
 59282  ** The purpose of the pointer map is to facility moving pages from one
 59283  ** position in the file to another as part of autovacuum.  When a page
 59284  ** is moved, the pointer in its parent must be updated to point to the
 59285  ** new location.  The pointer map is used to locate the parent page quickly.
 59286  **
 59287  ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
 59288  **                  used in this case.
 59289  **
 59290  ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
 59291  **                  is not used in this case.
 59292  **
 59293  ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
 59294  **                   overflow pages. The page number identifies the page that
 59295  **                   contains the cell with a pointer to this overflow page.
 59296  **
 59297  ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
 59298  **                   overflow pages. The page-number identifies the previous
 59299  **                   page in the overflow page list.
 59300  **
 59301  ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
 59302  **               identifies the parent page in the btree.
 59303  */
 59304  #define PTRMAP_ROOTPAGE 1
 59305  #define PTRMAP_FREEPAGE 2
 59306  #define PTRMAP_OVERFLOW1 3
 59307  #define PTRMAP_OVERFLOW2 4
 59308  #define PTRMAP_BTREE 5
 59309  
 59310  /* A bunch of assert() statements to check the transaction state variables
 59311  ** of handle p (type Btree*) are internally consistent.
 59312  */
 59313  #define btreeIntegrity(p) \
 59314    assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
 59315    assert( p->pBt->inTransaction>=p->inTrans ); 
 59316  
 59317  
 59318  /*
 59319  ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
 59320  ** if the database supports auto-vacuum or not. Because it is used
 59321  ** within an expression that is an argument to another macro 
 59322  ** (sqliteMallocRaw), it is not possible to use conditional compilation.
 59323  ** So, this macro is defined instead.
 59324  */
 59325  #ifndef SQLITE_OMIT_AUTOVACUUM
 59326  #define ISAUTOVACUUM (pBt->autoVacuum)
 59327  #else
 59328  #define ISAUTOVACUUM 0
 59329  #endif
 59330  
 59331  
 59332  /*
 59333  ** This structure is passed around through all the sanity checking routines
 59334  ** in order to keep track of some global state information.
 59335  **
 59336  ** The aRef[] array is allocated so that there is 1 bit for each page in
 59337  ** the database. As the integrity-check proceeds, for each page used in
 59338  ** the database the corresponding bit is set. This allows integrity-check to 
 59339  ** detect pages that are used twice and orphaned pages (both of which 
 59340  ** indicate corruption).
 59341  */
 59342  typedef struct IntegrityCk IntegrityCk;
 59343  struct IntegrityCk {
 59344    BtShared *pBt;    /* The tree being checked out */
 59345    Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
 59346    u8 *aPgRef;       /* 1 bit per page in the db (see above) */
 59347    Pgno nPage;       /* Number of pages in the database */
 59348    int mxErr;        /* Stop accumulating errors when this reaches zero */
 59349    int nErr;         /* Number of messages written to zErrMsg so far */
 59350    int mallocFailed; /* A memory allocation error has occurred */
 59351    const char *zPfx; /* Error message prefix */
 59352    int v1, v2;       /* Values for up to two %d fields in zPfx */
 59353    StrAccum errMsg;  /* Accumulate the error message text here */
 59354    u32 *heap;        /* Min-heap used for analyzing cell coverage */
 59355  };
 59356  
 59357  /*
 59358  ** Routines to read or write a two- and four-byte big-endian integer values.
 59359  */
 59360  #define get2byte(x)   ((x)[0]<<8 | (x)[1])
 59361  #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
 59362  #define get4byte sqlite3Get4byte
 59363  #define put4byte sqlite3Put4byte
 59364  
 59365  /*
 59366  ** get2byteAligned(), unlike get2byte(), requires that its argument point to a
 59367  ** two-byte aligned address.  get2bytea() is only used for accessing the
 59368  ** cell addresses in a btree header.
 59369  */
 59370  #if SQLITE_BYTEORDER==4321
 59371  # define get2byteAligned(x)  (*(u16*)(x))
 59372  #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000
 59373  # define get2byteAligned(x)  __builtin_bswap16(*(u16*)(x))
 59374  #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
 59375  # define get2byteAligned(x)  _byteswap_ushort(*(u16*)(x))
 59376  #else
 59377  # define get2byteAligned(x)  ((x)[0]<<8 | (x)[1])
 59378  #endif
 59379  
 59380  /************** End of btreeInt.h ********************************************/
 59381  /************** Continuing where we left off in btmutex.c ********************/
 59382  #ifndef SQLITE_OMIT_SHARED_CACHE
 59383  #if SQLITE_THREADSAFE
 59384  
 59385  /*
 59386  ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
 59387  ** set BtShared.db to the database handle associated with p and the
 59388  ** p->locked boolean to true.
 59389  */
 59390  static void lockBtreeMutex(Btree *p){
 59391    assert( p->locked==0 );
 59392    assert( sqlite3_mutex_notheld(p->pBt->mutex) );
 59393    assert( sqlite3_mutex_held(p->db->mutex) );
 59394  
 59395    sqlite3_mutex_enter(p->pBt->mutex);
 59396    p->pBt->db = p->db;
 59397    p->locked = 1;
 59398  }
 59399  
 59400  /*
 59401  ** Release the BtShared mutex associated with B-Tree handle p and
 59402  ** clear the p->locked boolean.
 59403  */
 59404  static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
 59405    BtShared *pBt = p->pBt;
 59406    assert( p->locked==1 );
 59407    assert( sqlite3_mutex_held(pBt->mutex) );
 59408    assert( sqlite3_mutex_held(p->db->mutex) );
 59409    assert( p->db==pBt->db );
 59410  
 59411    sqlite3_mutex_leave(pBt->mutex);
 59412    p->locked = 0;
 59413  }
 59414  
 59415  /* Forward reference */
 59416  static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
 59417  
 59418  /*
 59419  ** Enter a mutex on the given BTree object.
 59420  **
 59421  ** If the object is not sharable, then no mutex is ever required
 59422  ** and this routine is a no-op.  The underlying mutex is non-recursive.
 59423  ** But we keep a reference count in Btree.wantToLock so the behavior
 59424  ** of this interface is recursive.
 59425  **
 59426  ** To avoid deadlocks, multiple Btrees are locked in the same order
 59427  ** by all database connections.  The p->pNext is a list of other
 59428  ** Btrees belonging to the same database connection as the p Btree
 59429  ** which need to be locked after p.  If we cannot get a lock on
 59430  ** p, then first unlock all of the others on p->pNext, then wait
 59431  ** for the lock to become available on p, then relock all of the
 59432  ** subsequent Btrees that desire a lock.
 59433  */
 59434  SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
 59435    /* Some basic sanity checking on the Btree.  The list of Btrees
 59436    ** connected by pNext and pPrev should be in sorted order by
 59437    ** Btree.pBt value. All elements of the list should belong to
 59438    ** the same connection. Only shared Btrees are on the list. */
 59439    assert( p->pNext==0 || p->pNext->pBt>p->pBt );
 59440    assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
 59441    assert( p->pNext==0 || p->pNext->db==p->db );
 59442    assert( p->pPrev==0 || p->pPrev->db==p->db );
 59443    assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
 59444  
 59445    /* Check for locking consistency */
 59446    assert( !p->locked || p->wantToLock>0 );
 59447    assert( p->sharable || p->wantToLock==0 );
 59448  
 59449    /* We should already hold a lock on the database connection */
 59450    assert( sqlite3_mutex_held(p->db->mutex) );
 59451  
 59452    /* Unless the database is sharable and unlocked, then BtShared.db
 59453    ** should already be set correctly. */
 59454    assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
 59455  
 59456    if( !p->sharable ) return;
 59457    p->wantToLock++;
 59458    if( p->locked ) return;
 59459    btreeLockCarefully(p);
 59460  }
 59461  
 59462  /* This is a helper function for sqlite3BtreeLock(). By moving
 59463  ** complex, but seldom used logic, out of sqlite3BtreeLock() and
 59464  ** into this routine, we avoid unnecessary stack pointer changes
 59465  ** and thus help the sqlite3BtreeLock() routine to run much faster
 59466  ** in the common case.
 59467  */
 59468  static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
 59469    Btree *pLater;
 59470  
 59471    /* In most cases, we should be able to acquire the lock we
 59472    ** want without having to go through the ascending lock
 59473    ** procedure that follows.  Just be sure not to block.
 59474    */
 59475    if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
 59476      p->pBt->db = p->db;
 59477      p->locked = 1;
 59478      return;
 59479    }
 59480  
 59481    /* To avoid deadlock, first release all locks with a larger
 59482    ** BtShared address.  Then acquire our lock.  Then reacquire
 59483    ** the other BtShared locks that we used to hold in ascending
 59484    ** order.
 59485    */
 59486    for(pLater=p->pNext; pLater; pLater=pLater->pNext){
 59487      assert( pLater->sharable );
 59488      assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
 59489      assert( !pLater->locked || pLater->wantToLock>0 );
 59490      if( pLater->locked ){
 59491        unlockBtreeMutex(pLater);
 59492      }
 59493    }
 59494    lockBtreeMutex(p);
 59495    for(pLater=p->pNext; pLater; pLater=pLater->pNext){
 59496      if( pLater->wantToLock ){
 59497        lockBtreeMutex(pLater);
 59498      }
 59499    }
 59500  }
 59501  
 59502  
 59503  /*
 59504  ** Exit the recursive mutex on a Btree.
 59505  */
 59506  SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
 59507    assert( sqlite3_mutex_held(p->db->mutex) );
 59508    if( p->sharable ){
 59509      assert( p->wantToLock>0 );
 59510      p->wantToLock--;
 59511      if( p->wantToLock==0 ){
 59512        unlockBtreeMutex(p);
 59513      }
 59514    }
 59515  }
 59516  
 59517  #ifndef NDEBUG
 59518  /*
 59519  ** Return true if the BtShared mutex is held on the btree, or if the
 59520  ** B-Tree is not marked as sharable.
 59521  **
 59522  ** This routine is used only from within assert() statements.
 59523  */
 59524  SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
 59525    assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
 59526    assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
 59527    assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
 59528    assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
 59529  
 59530    return (p->sharable==0 || p->locked);
 59531  }
 59532  #endif
 59533  
 59534  
 59535  /*
 59536  ** Enter the mutex on every Btree associated with a database
 59537  ** connection.  This is needed (for example) prior to parsing
 59538  ** a statement since we will be comparing table and column names
 59539  ** against all schemas and we do not want those schemas being
 59540  ** reset out from under us.
 59541  **
 59542  ** There is a corresponding leave-all procedures.
 59543  **
 59544  ** Enter the mutexes in accending order by BtShared pointer address
 59545  ** to avoid the possibility of deadlock when two threads with
 59546  ** two or more btrees in common both try to lock all their btrees
 59547  ** at the same instant.
 59548  */
 59549  static void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){
 59550    int i;
 59551    int skipOk = 1;
 59552    Btree *p;
 59553    assert( sqlite3_mutex_held(db->mutex) );
 59554    for(i=0; i<db->nDb; i++){
 59555      p = db->aDb[i].pBt;
 59556      if( p && p->sharable ){
 59557        sqlite3BtreeEnter(p);
 59558        skipOk = 0;
 59559      }
 59560    }
 59561    db->skipBtreeMutex = skipOk;
 59562  }
 59563  SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
 59564    if( db->skipBtreeMutex==0 ) btreeEnterAll(db);
 59565  }
 59566  static void SQLITE_NOINLINE btreeLeaveAll(sqlite3 *db){
 59567    int i;
 59568    Btree *p;
 59569    assert( sqlite3_mutex_held(db->mutex) );
 59570    for(i=0; i<db->nDb; i++){
 59571      p = db->aDb[i].pBt;
 59572      if( p ) sqlite3BtreeLeave(p);
 59573    }
 59574  }
 59575  SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
 59576    if( db->skipBtreeMutex==0 ) btreeLeaveAll(db);
 59577  }
 59578  
 59579  #ifndef NDEBUG
 59580  /*
 59581  ** Return true if the current thread holds the database connection
 59582  ** mutex and all required BtShared mutexes.
 59583  **
 59584  ** This routine is used inside assert() statements only.
 59585  */
 59586  SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
 59587    int i;
 59588    if( !sqlite3_mutex_held(db->mutex) ){
 59589      return 0;
 59590    }
 59591    for(i=0; i<db->nDb; i++){
 59592      Btree *p;
 59593      p = db->aDb[i].pBt;
 59594      if( p && p->sharable &&
 59595           (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
 59596        return 0;
 59597      }
 59598    }
 59599    return 1;
 59600  }
 59601  #endif /* NDEBUG */
 59602  
 59603  #ifndef NDEBUG
 59604  /*
 59605  ** Return true if the correct mutexes are held for accessing the
 59606  ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
 59607  ** access are:
 59608  **
 59609  **   (1) The mutex on db
 59610  **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
 59611  **
 59612  ** If pSchema is not NULL, then iDb is computed from pSchema and
 59613  ** db using sqlite3SchemaToIndex().
 59614  */
 59615  SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
 59616    Btree *p;
 59617    assert( db!=0 );
 59618    if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
 59619    assert( iDb>=0 && iDb<db->nDb );
 59620    if( !sqlite3_mutex_held(db->mutex) ) return 0;
 59621    if( iDb==1 ) return 1;
 59622    p = db->aDb[iDb].pBt;
 59623    assert( p!=0 );
 59624    return p->sharable==0 || p->locked==1;
 59625  }
 59626  #endif /* NDEBUG */
 59627  
 59628  #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
 59629  /*
 59630  ** The following are special cases for mutex enter routines for use
 59631  ** in single threaded applications that use shared cache.  Except for
 59632  ** these two routines, all mutex operations are no-ops in that case and
 59633  ** are null #defines in btree.h.
 59634  **
 59635  ** If shared cache is disabled, then all btree mutex routines, including
 59636  ** the ones below, are no-ops and are null #defines in btree.h.
 59637  */
 59638  
 59639  SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
 59640    p->pBt->db = p->db;
 59641  }
 59642  SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
 59643    int i;
 59644    for(i=0; i<db->nDb; i++){
 59645      Btree *p = db->aDb[i].pBt;
 59646      if( p ){
 59647        p->pBt->db = p->db;
 59648      }
 59649    }
 59650  }
 59651  #endif /* if SQLITE_THREADSAFE */
 59652  
 59653  #ifndef SQLITE_OMIT_INCRBLOB
 59654  /*
 59655  ** Enter a mutex on a Btree given a cursor owned by that Btree. 
 59656  **
 59657  ** These entry points are used by incremental I/O only. Enter() is required 
 59658  ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not 
 59659  ** the build is threadsafe. Leave() is only required by threadsafe builds.
 59660  */
 59661  SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
 59662    sqlite3BtreeEnter(pCur->pBtree);
 59663  }
 59664  # if SQLITE_THREADSAFE
 59665  SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
 59666    sqlite3BtreeLeave(pCur->pBtree);
 59667  }
 59668  # endif
 59669  #endif /* ifndef SQLITE_OMIT_INCRBLOB */
 59670  
 59671  #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
 59672  
 59673  /************** End of btmutex.c *********************************************/
 59674  /************** Begin file btree.c *******************************************/
 59675  /*
 59676  ** 2004 April 6
 59677  **
 59678  ** The author disclaims copyright to this source code.  In place of
 59679  ** a legal notice, here is a blessing:
 59680  **
 59681  **    May you do good and not evil.
 59682  **    May you find forgiveness for yourself and forgive others.
 59683  **    May you share freely, never taking more than you give.
 59684  **
 59685  *************************************************************************
 59686  ** This file implements an external (disk-based) database using BTrees.
 59687  ** See the header comment on "btreeInt.h" for additional information.
 59688  ** Including a description of file format and an overview of operation.
 59689  */
 59690  /* #include "btreeInt.h" */
 59691  
 59692  /*
 59693  ** The header string that appears at the beginning of every
 59694  ** SQLite database.
 59695  */
 59696  static const char zMagicHeader[] = SQLITE_FILE_HEADER;
 59697  
 59698  /*
 59699  ** Set this global variable to 1 to enable tracing using the TRACE
 59700  ** macro.
 59701  */
 59702  #if 0
 59703  int sqlite3BtreeTrace=1;  /* True to enable tracing */
 59704  # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
 59705  #else
 59706  # define TRACE(X)
 59707  #endif
 59708  
 59709  /*
 59710  ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
 59711  ** But if the value is zero, make it 65536.
 59712  **
 59713  ** This routine is used to extract the "offset to cell content area" value
 59714  ** from the header of a btree page.  If the page size is 65536 and the page
 59715  ** is empty, the offset should be 65536, but the 2-byte value stores zero.
 59716  ** This routine makes the necessary adjustment to 65536.
 59717  */
 59718  #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
 59719  
 59720  /*
 59721  ** Values passed as the 5th argument to allocateBtreePage()
 59722  */
 59723  #define BTALLOC_ANY   0           /* Allocate any page */
 59724  #define BTALLOC_EXACT 1           /* Allocate exact page if possible */
 59725  #define BTALLOC_LE    2           /* Allocate any page <= the parameter */
 59726  
 59727  /*
 59728  ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not 
 59729  ** defined, or 0 if it is. For example:
 59730  **
 59731  **   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
 59732  */
 59733  #ifndef SQLITE_OMIT_AUTOVACUUM
 59734  #define IfNotOmitAV(expr) (expr)
 59735  #else
 59736  #define IfNotOmitAV(expr) 0
 59737  #endif
 59738  
 59739  #ifndef SQLITE_OMIT_SHARED_CACHE
 59740  /*
 59741  ** A list of BtShared objects that are eligible for participation
 59742  ** in shared cache.  This variable has file scope during normal builds,
 59743  ** but the test harness needs to access it so we make it global for 
 59744  ** test builds.
 59745  **
 59746  ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
 59747  */
 59748  #ifdef SQLITE_TEST
 59749  SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
 59750  #else
 59751  static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
 59752  #endif
 59753  #endif /* SQLITE_OMIT_SHARED_CACHE */
 59754  
 59755  #ifndef SQLITE_OMIT_SHARED_CACHE
 59756  /*
 59757  ** Enable or disable the shared pager and schema features.
 59758  **
 59759  ** This routine has no effect on existing database connections.
 59760  ** The shared cache setting effects only future calls to
 59761  ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
 59762  */
 59763  SQLITE_API int sqlite3_enable_shared_cache(int enable){
 59764    sqlite3GlobalConfig.sharedCacheEnabled = enable;
 59765    return SQLITE_OK;
 59766  }
 59767  #endif
 59768  
 59769  
 59770  
 59771  #ifdef SQLITE_OMIT_SHARED_CACHE
 59772    /*
 59773    ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
 59774    ** and clearAllSharedCacheTableLocks()
 59775    ** manipulate entries in the BtShared.pLock linked list used to store
 59776    ** shared-cache table level locks. If the library is compiled with the
 59777    ** shared-cache feature disabled, then there is only ever one user
 59778    ** of each BtShared structure and so this locking is not necessary. 
 59779    ** So define the lock related functions as no-ops.
 59780    */
 59781    #define querySharedCacheTableLock(a,b,c) SQLITE_OK
 59782    #define setSharedCacheTableLock(a,b,c) SQLITE_OK
 59783    #define clearAllSharedCacheTableLocks(a)
 59784    #define downgradeAllSharedCacheTableLocks(a)
 59785    #define hasSharedCacheTableLock(a,b,c,d) 1
 59786    #define hasReadConflicts(a, b) 0
 59787  #endif
 59788  
 59789  #ifndef SQLITE_OMIT_SHARED_CACHE
 59790  
 59791  #ifdef SQLITE_DEBUG
 59792  /*
 59793  **** This function is only used as part of an assert() statement. ***
 59794  **
 59795  ** Check to see if pBtree holds the required locks to read or write to the 
 59796  ** table with root page iRoot.   Return 1 if it does and 0 if not.
 59797  **
 59798  ** For example, when writing to a table with root-page iRoot via 
 59799  ** Btree connection pBtree:
 59800  **
 59801  **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
 59802  **
 59803  ** When writing to an index that resides in a sharable database, the 
 59804  ** caller should have first obtained a lock specifying the root page of
 59805  ** the corresponding table. This makes things a bit more complicated,
 59806  ** as this module treats each table as a separate structure. To determine
 59807  ** the table corresponding to the index being written, this
 59808  ** function has to search through the database schema.
 59809  **
 59810  ** Instead of a lock on the table/index rooted at page iRoot, the caller may
 59811  ** hold a write-lock on the schema table (root page 1). This is also
 59812  ** acceptable.
 59813  */
 59814  static int hasSharedCacheTableLock(
 59815    Btree *pBtree,         /* Handle that must hold lock */
 59816    Pgno iRoot,            /* Root page of b-tree */
 59817    int isIndex,           /* True if iRoot is the root of an index b-tree */
 59818    int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
 59819  ){
 59820    Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
 59821    Pgno iTab = 0;
 59822    BtLock *pLock;
 59823  
 59824    /* If this database is not shareable, or if the client is reading
 59825    ** and has the read-uncommitted flag set, then no lock is required. 
 59826    ** Return true immediately.
 59827    */
 59828    if( (pBtree->sharable==0)
 59829     || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
 59830    ){
 59831      return 1;
 59832    }
 59833  
 59834    /* If the client is reading  or writing an index and the schema is
 59835    ** not loaded, then it is too difficult to actually check to see if
 59836    ** the correct locks are held.  So do not bother - just return true.
 59837    ** This case does not come up very often anyhow.
 59838    */
 59839    if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
 59840      return 1;
 59841    }
 59842  
 59843    /* Figure out the root-page that the lock should be held on. For table
 59844    ** b-trees, this is just the root page of the b-tree being read or
 59845    ** written. For index b-trees, it is the root page of the associated
 59846    ** table.  */
 59847    if( isIndex ){
 59848      HashElem *p;
 59849      for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
 59850        Index *pIdx = (Index *)sqliteHashData(p);
 59851        if( pIdx->tnum==(int)iRoot ){
 59852          if( iTab ){
 59853            /* Two or more indexes share the same root page.  There must
 59854            ** be imposter tables.  So just return true.  The assert is not
 59855            ** useful in that case. */
 59856            return 1;
 59857          }
 59858          iTab = pIdx->pTable->tnum;
 59859        }
 59860      }
 59861    }else{
 59862      iTab = iRoot;
 59863    }
 59864  
 59865    /* Search for the required lock. Either a write-lock on root-page iTab, a 
 59866    ** write-lock on the schema table, or (if the client is reading) a
 59867    ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
 59868    for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
 59869      if( pLock->pBtree==pBtree 
 59870       && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
 59871       && pLock->eLock>=eLockType 
 59872      ){
 59873        return 1;
 59874      }
 59875    }
 59876  
 59877    /* Failed to find the required lock. */
 59878    return 0;
 59879  }
 59880  #endif /* SQLITE_DEBUG */
 59881  
 59882  #ifdef SQLITE_DEBUG
 59883  /*
 59884  **** This function may be used as part of assert() statements only. ****
 59885  **
 59886  ** Return true if it would be illegal for pBtree to write into the
 59887  ** table or index rooted at iRoot because other shared connections are
 59888  ** simultaneously reading that same table or index.
 59889  **
 59890  ** It is illegal for pBtree to write if some other Btree object that
 59891  ** shares the same BtShared object is currently reading or writing
 59892  ** the iRoot table.  Except, if the other Btree object has the
 59893  ** read-uncommitted flag set, then it is OK for the other object to
 59894  ** have a read cursor.
 59895  **
 59896  ** For example, before writing to any part of the table or index
 59897  ** rooted at page iRoot, one should call:
 59898  **
 59899  **    assert( !hasReadConflicts(pBtree, iRoot) );
 59900  */
 59901  static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
 59902    BtCursor *p;
 59903    for(p=pBtree->pBt->pCursor; p; p=p->pNext){
 59904      if( p->pgnoRoot==iRoot 
 59905       && p->pBtree!=pBtree
 59906       && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
 59907      ){
 59908        return 1;
 59909      }
 59910    }
 59911    return 0;
 59912  }
 59913  #endif    /* #ifdef SQLITE_DEBUG */
 59914  
 59915  /*
 59916  ** Query to see if Btree handle p may obtain a lock of type eLock 
 59917  ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
 59918  ** SQLITE_OK if the lock may be obtained (by calling
 59919  ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
 59920  */
 59921  static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
 59922    BtShared *pBt = p->pBt;
 59923    BtLock *pIter;
 59924  
 59925    assert( sqlite3BtreeHoldsMutex(p) );
 59926    assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
 59927    assert( p->db!=0 );
 59928    assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
 59929    
 59930    /* If requesting a write-lock, then the Btree must have an open write
 59931    ** transaction on this file. And, obviously, for this to be so there 
 59932    ** must be an open write transaction on the file itself.
 59933    */
 59934    assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
 59935    assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
 59936    
 59937    /* This routine is a no-op if the shared-cache is not enabled */
 59938    if( !p->sharable ){
 59939      return SQLITE_OK;
 59940    }
 59941  
 59942    /* If some other connection is holding an exclusive lock, the
 59943    ** requested lock may not be obtained.
 59944    */
 59945    if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
 59946      sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
 59947      return SQLITE_LOCKED_SHAREDCACHE;
 59948    }
 59949  
 59950    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
 59951      /* The condition (pIter->eLock!=eLock) in the following if(...) 
 59952      ** statement is a simplification of:
 59953      **
 59954      **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
 59955      **
 59956      ** since we know that if eLock==WRITE_LOCK, then no other connection
 59957      ** may hold a WRITE_LOCK on any table in this file (since there can
 59958      ** only be a single writer).
 59959      */
 59960      assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
 59961      assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
 59962      if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
 59963        sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
 59964        if( eLock==WRITE_LOCK ){
 59965          assert( p==pBt->pWriter );
 59966          pBt->btsFlags |= BTS_PENDING;
 59967        }
 59968        return SQLITE_LOCKED_SHAREDCACHE;
 59969      }
 59970    }
 59971    return SQLITE_OK;
 59972  }
 59973  #endif /* !SQLITE_OMIT_SHARED_CACHE */
 59974  
 59975  #ifndef SQLITE_OMIT_SHARED_CACHE
 59976  /*
 59977  ** Add a lock on the table with root-page iTable to the shared-btree used
 59978  ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
 59979  ** WRITE_LOCK.
 59980  **
 59981  ** This function assumes the following:
 59982  **
 59983  **   (a) The specified Btree object p is connected to a sharable
 59984  **       database (one with the BtShared.sharable flag set), and
 59985  **
 59986  **   (b) No other Btree objects hold a lock that conflicts
 59987  **       with the requested lock (i.e. querySharedCacheTableLock() has
 59988  **       already been called and returned SQLITE_OK).
 59989  **
 59990  ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
 59991  ** is returned if a malloc attempt fails.
 59992  */
 59993  static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
 59994    BtShared *pBt = p->pBt;
 59995    BtLock *pLock = 0;
 59996    BtLock *pIter;
 59997  
 59998    assert( sqlite3BtreeHoldsMutex(p) );
 59999    assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
 60000    assert( p->db!=0 );
 60001  
 60002    /* A connection with the read-uncommitted flag set will never try to
 60003    ** obtain a read-lock using this function. The only read-lock obtained
 60004    ** by a connection in read-uncommitted mode is on the sqlite_master 
 60005    ** table, and that lock is obtained in BtreeBeginTrans().  */
 60006    assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
 60007  
 60008    /* This function should only be called on a sharable b-tree after it 
 60009    ** has been determined that no other b-tree holds a conflicting lock.  */
 60010    assert( p->sharable );
 60011    assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
 60012  
 60013    /* First search the list for an existing lock on this table. */
 60014    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
 60015      if( pIter->iTable==iTable && pIter->pBtree==p ){
 60016        pLock = pIter;
 60017        break;
 60018      }
 60019    }
 60020  
 60021    /* If the above search did not find a BtLock struct associating Btree p
 60022    ** with table iTable, allocate one and link it into the list.
 60023    */
 60024    if( !pLock ){
 60025      pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
 60026      if( !pLock ){
 60027        return SQLITE_NOMEM_BKPT;
 60028      }
 60029      pLock->iTable = iTable;
 60030      pLock->pBtree = p;
 60031      pLock->pNext = pBt->pLock;
 60032      pBt->pLock = pLock;
 60033    }
 60034  
 60035    /* Set the BtLock.eLock variable to the maximum of the current lock
 60036    ** and the requested lock. This means if a write-lock was already held
 60037    ** and a read-lock requested, we don't incorrectly downgrade the lock.
 60038    */
 60039    assert( WRITE_LOCK>READ_LOCK );
 60040    if( eLock>pLock->eLock ){
 60041      pLock->eLock = eLock;
 60042    }
 60043  
 60044    return SQLITE_OK;
 60045  }
 60046  #endif /* !SQLITE_OMIT_SHARED_CACHE */
 60047  
 60048  #ifndef SQLITE_OMIT_SHARED_CACHE
 60049  /*
 60050  ** Release all the table locks (locks obtained via calls to
 60051  ** the setSharedCacheTableLock() procedure) held by Btree object p.
 60052  **
 60053  ** This function assumes that Btree p has an open read or write 
 60054  ** transaction. If it does not, then the BTS_PENDING flag
 60055  ** may be incorrectly cleared.
 60056  */
 60057  static void clearAllSharedCacheTableLocks(Btree *p){
 60058    BtShared *pBt = p->pBt;
 60059    BtLock **ppIter = &pBt->pLock;
 60060  
 60061    assert( sqlite3BtreeHoldsMutex(p) );
 60062    assert( p->sharable || 0==*ppIter );
 60063    assert( p->inTrans>0 );
 60064  
 60065    while( *ppIter ){
 60066      BtLock *pLock = *ppIter;
 60067      assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
 60068      assert( pLock->pBtree->inTrans>=pLock->eLock );
 60069      if( pLock->pBtree==p ){
 60070        *ppIter = pLock->pNext;
 60071        assert( pLock->iTable!=1 || pLock==&p->lock );
 60072        if( pLock->iTable!=1 ){
 60073          sqlite3_free(pLock);
 60074        }
 60075      }else{
 60076        ppIter = &pLock->pNext;
 60077      }
 60078    }
 60079  
 60080    assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
 60081    if( pBt->pWriter==p ){
 60082      pBt->pWriter = 0;
 60083      pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
 60084    }else if( pBt->nTransaction==2 ){
 60085      /* This function is called when Btree p is concluding its 
 60086      ** transaction. If there currently exists a writer, and p is not
 60087      ** that writer, then the number of locks held by connections other
 60088      ** than the writer must be about to drop to zero. In this case
 60089      ** set the BTS_PENDING flag to 0.
 60090      **
 60091      ** If there is not currently a writer, then BTS_PENDING must
 60092      ** be zero already. So this next line is harmless in that case.
 60093      */
 60094      pBt->btsFlags &= ~BTS_PENDING;
 60095    }
 60096  }
 60097  
 60098  /*
 60099  ** This function changes all write-locks held by Btree p into read-locks.
 60100  */
 60101  static void downgradeAllSharedCacheTableLocks(Btree *p){
 60102    BtShared *pBt = p->pBt;
 60103    if( pBt->pWriter==p ){
 60104      BtLock *pLock;
 60105      pBt->pWriter = 0;
 60106      pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
 60107      for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
 60108        assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
 60109        pLock->eLock = READ_LOCK;
 60110      }
 60111    }
 60112  }
 60113  
 60114  #endif /* SQLITE_OMIT_SHARED_CACHE */
 60115  
 60116  static void releasePage(MemPage *pPage);         /* Forward reference */
 60117  static void releasePageOne(MemPage *pPage);      /* Forward reference */
 60118  static void releasePageNotNull(MemPage *pPage);  /* Forward reference */
 60119  
 60120  /*
 60121  ***** This routine is used inside of assert() only ****
 60122  **
 60123  ** Verify that the cursor holds the mutex on its BtShared
 60124  */
 60125  #ifdef SQLITE_DEBUG
 60126  static int cursorHoldsMutex(BtCursor *p){
 60127    return sqlite3_mutex_held(p->pBt->mutex);
 60128  }
 60129  
 60130  /* Verify that the cursor and the BtShared agree about what is the current
 60131  ** database connetion. This is important in shared-cache mode. If the database 
 60132  ** connection pointers get out-of-sync, it is possible for routines like
 60133  ** btreeInitPage() to reference an stale connection pointer that references a
 60134  ** a connection that has already closed.  This routine is used inside assert()
 60135  ** statements only and for the purpose of double-checking that the btree code
 60136  ** does keep the database connection pointers up-to-date.
 60137  */
 60138  static int cursorOwnsBtShared(BtCursor *p){
 60139    assert( cursorHoldsMutex(p) );
 60140    return (p->pBtree->db==p->pBt->db);
 60141  }
 60142  #endif
 60143  
 60144  /*
 60145  ** Invalidate the overflow cache of the cursor passed as the first argument.
 60146  ** on the shared btree structure pBt.
 60147  */
 60148  #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
 60149  
 60150  /*
 60151  ** Invalidate the overflow page-list cache for all cursors opened
 60152  ** on the shared btree structure pBt.
 60153  */
 60154  static void invalidateAllOverflowCache(BtShared *pBt){
 60155    BtCursor *p;
 60156    assert( sqlite3_mutex_held(pBt->mutex) );
 60157    for(p=pBt->pCursor; p; p=p->pNext){
 60158      invalidateOverflowCache(p);
 60159    }
 60160  }
 60161  
 60162  #ifndef SQLITE_OMIT_INCRBLOB
 60163  /*
 60164  ** This function is called before modifying the contents of a table
 60165  ** to invalidate any incrblob cursors that are open on the
 60166  ** row or one of the rows being modified.
 60167  **
 60168  ** If argument isClearTable is true, then the entire contents of the
 60169  ** table is about to be deleted. In this case invalidate all incrblob
 60170  ** cursors open on any row within the table with root-page pgnoRoot.
 60171  **
 60172  ** Otherwise, if argument isClearTable is false, then the row with
 60173  ** rowid iRow is being replaced or deleted. In this case invalidate
 60174  ** only those incrblob cursors open on that specific row.
 60175  */
 60176  static void invalidateIncrblobCursors(
 60177    Btree *pBtree,          /* The database file to check */
 60178    Pgno pgnoRoot,          /* The table that might be changing */
 60179    i64 iRow,               /* The rowid that might be changing */
 60180    int isClearTable        /* True if all rows are being deleted */
 60181  ){
 60182    BtCursor *p;
 60183    if( pBtree->hasIncrblobCur==0 ) return;
 60184    assert( sqlite3BtreeHoldsMutex(pBtree) );
 60185    pBtree->hasIncrblobCur = 0;
 60186    for(p=pBtree->pBt->pCursor; p; p=p->pNext){
 60187      if( (p->curFlags & BTCF_Incrblob)!=0 ){
 60188        pBtree->hasIncrblobCur = 1;
 60189        if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
 60190          p->eState = CURSOR_INVALID;
 60191        }
 60192      }
 60193    }
 60194  }
 60195  
 60196  #else
 60197    /* Stub function when INCRBLOB is omitted */
 60198    #define invalidateIncrblobCursors(w,x,y,z)
 60199  #endif /* SQLITE_OMIT_INCRBLOB */
 60200  
 60201  /*
 60202  ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
 60203  ** when a page that previously contained data becomes a free-list leaf 
 60204  ** page.
 60205  **
 60206  ** The BtShared.pHasContent bitvec exists to work around an obscure
 60207  ** bug caused by the interaction of two useful IO optimizations surrounding
 60208  ** free-list leaf pages:
 60209  **
 60210  **   1) When all data is deleted from a page and the page becomes
 60211  **      a free-list leaf page, the page is not written to the database
 60212  **      (as free-list leaf pages contain no meaningful data). Sometimes
 60213  **      such a page is not even journalled (as it will not be modified,
 60214  **      why bother journalling it?).
 60215  **
 60216  **   2) When a free-list leaf page is reused, its content is not read
 60217  **      from the database or written to the journal file (why should it
 60218  **      be, if it is not at all meaningful?).
 60219  **
 60220  ** By themselves, these optimizations work fine and provide a handy
 60221  ** performance boost to bulk delete or insert operations. However, if
 60222  ** a page is moved to the free-list and then reused within the same
 60223  ** transaction, a problem comes up. If the page is not journalled when
 60224  ** it is moved to the free-list and it is also not journalled when it
 60225  ** is extracted from the free-list and reused, then the original data
 60226  ** may be lost. In the event of a rollback, it may not be possible
 60227  ** to restore the database to its original configuration.
 60228  **
 60229  ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
 60230  ** moved to become a free-list leaf page, the corresponding bit is
 60231  ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
 60232  ** optimization 2 above is omitted if the corresponding bit is already
 60233  ** set in BtShared.pHasContent. The contents of the bitvec are cleared
 60234  ** at the end of every transaction.
 60235  */
 60236  static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
 60237    int rc = SQLITE_OK;
 60238    if( !pBt->pHasContent ){
 60239      assert( pgno<=pBt->nPage );
 60240      pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
 60241      if( !pBt->pHasContent ){
 60242        rc = SQLITE_NOMEM_BKPT;
 60243      }
 60244    }
 60245    if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
 60246      rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
 60247    }
 60248    return rc;
 60249  }
 60250  
 60251  /*
 60252  ** Query the BtShared.pHasContent vector.
 60253  **
 60254  ** This function is called when a free-list leaf page is removed from the
 60255  ** free-list for reuse. It returns false if it is safe to retrieve the
 60256  ** page from the pager layer with the 'no-content' flag set. True otherwise.
 60257  */
 60258  static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
 60259    Bitvec *p = pBt->pHasContent;
 60260    return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
 60261  }
 60262  
 60263  /*
 60264  ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
 60265  ** invoked at the conclusion of each write-transaction.
 60266  */
 60267  static void btreeClearHasContent(BtShared *pBt){
 60268    sqlite3BitvecDestroy(pBt->pHasContent);
 60269    pBt->pHasContent = 0;
 60270  }
 60271  
 60272  /*
 60273  ** Release all of the apPage[] pages for a cursor.
 60274  */
 60275  static void btreeReleaseAllCursorPages(BtCursor *pCur){
 60276    int i;
 60277    if( pCur->iPage>=0 ){
 60278      for(i=0; i<pCur->iPage; i++){
 60279        releasePageNotNull(pCur->apPage[i]);
 60280      }
 60281      releasePageNotNull(pCur->pPage);
 60282      pCur->iPage = -1;
 60283    }
 60284  }
 60285  
 60286  /*
 60287  ** The cursor passed as the only argument must point to a valid entry
 60288  ** when this function is called (i.e. have eState==CURSOR_VALID). This
 60289  ** function saves the current cursor key in variables pCur->nKey and
 60290  ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error 
 60291  ** code otherwise.
 60292  **
 60293  ** If the cursor is open on an intkey table, then the integer key
 60294  ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
 60295  ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is 
 60296  ** set to point to a malloced buffer pCur->nKey bytes in size containing 
 60297  ** the key.
 60298  */
 60299  static int saveCursorKey(BtCursor *pCur){
 60300    int rc = SQLITE_OK;
 60301    assert( CURSOR_VALID==pCur->eState );
 60302    assert( 0==pCur->pKey );
 60303    assert( cursorHoldsMutex(pCur) );
 60304  
 60305    if( pCur->curIntKey ){
 60306      /* Only the rowid is required for a table btree */
 60307      pCur->nKey = sqlite3BtreeIntegerKey(pCur);
 60308    }else{
 60309      /* For an index btree, save the complete key content */
 60310      void *pKey;
 60311      pCur->nKey = sqlite3BtreePayloadSize(pCur);
 60312      pKey = sqlite3Malloc( pCur->nKey );
 60313      if( pKey ){
 60314        rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
 60315        if( rc==SQLITE_OK ){
 60316          pCur->pKey = pKey;
 60317        }else{
 60318          sqlite3_free(pKey);
 60319        }
 60320      }else{
 60321        rc = SQLITE_NOMEM_BKPT;
 60322      }
 60323    }
 60324    assert( !pCur->curIntKey || !pCur->pKey );
 60325    return rc;
 60326  }
 60327  
 60328  /*
 60329  ** Save the current cursor position in the variables BtCursor.nKey 
 60330  ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
 60331  **
 60332  ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
 60333  ** prior to calling this routine.  
 60334  */
 60335  static int saveCursorPosition(BtCursor *pCur){
 60336    int rc;
 60337  
 60338    assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
 60339    assert( 0==pCur->pKey );
 60340    assert( cursorHoldsMutex(pCur) );
 60341  
 60342    if( pCur->eState==CURSOR_SKIPNEXT ){
 60343      pCur->eState = CURSOR_VALID;
 60344    }else{
 60345      pCur->skipNext = 0;
 60346    }
 60347  
 60348    rc = saveCursorKey(pCur);
 60349    if( rc==SQLITE_OK ){
 60350      btreeReleaseAllCursorPages(pCur);
 60351      pCur->eState = CURSOR_REQUIRESEEK;
 60352    }
 60353  
 60354    pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
 60355    return rc;
 60356  }
 60357  
 60358  /* Forward reference */
 60359  static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
 60360  
 60361  /*
 60362  ** Save the positions of all cursors (except pExcept) that are open on
 60363  ** the table with root-page iRoot.  "Saving the cursor position" means that
 60364  ** the location in the btree is remembered in such a way that it can be
 60365  ** moved back to the same spot after the btree has been modified.  This
 60366  ** routine is called just before cursor pExcept is used to modify the
 60367  ** table, for example in BtreeDelete() or BtreeInsert().
 60368  **
 60369  ** If there are two or more cursors on the same btree, then all such 
 60370  ** cursors should have their BTCF_Multiple flag set.  The btreeCursor()
 60371  ** routine enforces that rule.  This routine only needs to be called in
 60372  ** the uncommon case when pExpect has the BTCF_Multiple flag set.
 60373  **
 60374  ** If pExpect!=NULL and if no other cursors are found on the same root-page,
 60375  ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
 60376  ** pointless call to this routine.
 60377  **
 60378  ** Implementation note:  This routine merely checks to see if any cursors
 60379  ** need to be saved.  It calls out to saveCursorsOnList() in the (unusual)
 60380  ** event that cursors are in need to being saved.
 60381  */
 60382  static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
 60383    BtCursor *p;
 60384    assert( sqlite3_mutex_held(pBt->mutex) );
 60385    assert( pExcept==0 || pExcept->pBt==pBt );
 60386    for(p=pBt->pCursor; p; p=p->pNext){
 60387      if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
 60388    }
 60389    if( p ) return saveCursorsOnList(p, iRoot, pExcept);
 60390    if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
 60391    return SQLITE_OK;
 60392  }
 60393  
 60394  /* This helper routine to saveAllCursors does the actual work of saving
 60395  ** the cursors if and when a cursor is found that actually requires saving.
 60396  ** The common case is that no cursors need to be saved, so this routine is
 60397  ** broken out from its caller to avoid unnecessary stack pointer movement.
 60398  */
 60399  static int SQLITE_NOINLINE saveCursorsOnList(
 60400    BtCursor *p,         /* The first cursor that needs saving */
 60401    Pgno iRoot,          /* Only save cursor with this iRoot. Save all if zero */
 60402    BtCursor *pExcept    /* Do not save this cursor */
 60403  ){
 60404    do{
 60405      if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
 60406        if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
 60407          int rc = saveCursorPosition(p);
 60408          if( SQLITE_OK!=rc ){
 60409            return rc;
 60410          }
 60411        }else{
 60412          testcase( p->iPage>=0 );
 60413          btreeReleaseAllCursorPages(p);
 60414        }
 60415      }
 60416      p = p->pNext;
 60417    }while( p );
 60418    return SQLITE_OK;
 60419  }
 60420  
 60421  /*
 60422  ** Clear the current cursor position.
 60423  */
 60424  SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
 60425    assert( cursorHoldsMutex(pCur) );
 60426    sqlite3_free(pCur->pKey);
 60427    pCur->pKey = 0;
 60428    pCur->eState = CURSOR_INVALID;
 60429  }
 60430  
 60431  /*
 60432  ** In this version of BtreeMoveto, pKey is a packed index record
 60433  ** such as is generated by the OP_MakeRecord opcode.  Unpack the
 60434  ** record and then call BtreeMovetoUnpacked() to do the work.
 60435  */
 60436  static int btreeMoveto(
 60437    BtCursor *pCur,     /* Cursor open on the btree to be searched */
 60438    const void *pKey,   /* Packed key if the btree is an index */
 60439    i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
 60440    int bias,           /* Bias search to the high end */
 60441    int *pRes           /* Write search results here */
 60442  ){
 60443    int rc;                    /* Status code */
 60444    UnpackedRecord *pIdxKey;   /* Unpacked index key */
 60445  
 60446    if( pKey ){
 60447      assert( nKey==(i64)(int)nKey );
 60448      pIdxKey = sqlite3VdbeAllocUnpackedRecord(pCur->pKeyInfo);
 60449      if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
 60450      sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
 60451      if( pIdxKey->nField==0 ){
 60452        rc = SQLITE_CORRUPT_BKPT;
 60453        goto moveto_done;
 60454      }
 60455    }else{
 60456      pIdxKey = 0;
 60457    }
 60458    rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
 60459  moveto_done:
 60460    if( pIdxKey ){
 60461      sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
 60462    }
 60463    return rc;
 60464  }
 60465  
 60466  /*
 60467  ** Restore the cursor to the position it was in (or as close to as possible)
 60468  ** when saveCursorPosition() was called. Note that this call deletes the 
 60469  ** saved position info stored by saveCursorPosition(), so there can be
 60470  ** at most one effective restoreCursorPosition() call after each 
 60471  ** saveCursorPosition().
 60472  */
 60473  static int btreeRestoreCursorPosition(BtCursor *pCur){
 60474    int rc;
 60475    int skipNext;
 60476    assert( cursorOwnsBtShared(pCur) );
 60477    assert( pCur->eState>=CURSOR_REQUIRESEEK );
 60478    if( pCur->eState==CURSOR_FAULT ){
 60479      return pCur->skipNext;
 60480    }
 60481    pCur->eState = CURSOR_INVALID;
 60482    rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
 60483    if( rc==SQLITE_OK ){
 60484      sqlite3_free(pCur->pKey);
 60485      pCur->pKey = 0;
 60486      assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
 60487      pCur->skipNext |= skipNext;
 60488      if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
 60489        pCur->eState = CURSOR_SKIPNEXT;
 60490      }
 60491    }
 60492    return rc;
 60493  }
 60494  
 60495  #define restoreCursorPosition(p) \
 60496    (p->eState>=CURSOR_REQUIRESEEK ? \
 60497           btreeRestoreCursorPosition(p) : \
 60498           SQLITE_OK)
 60499  
 60500  /*
 60501  ** Determine whether or not a cursor has moved from the position where
 60502  ** it was last placed, or has been invalidated for any other reason.
 60503  ** Cursors can move when the row they are pointing at is deleted out
 60504  ** from under them, for example.  Cursor might also move if a btree
 60505  ** is rebalanced.
 60506  **
 60507  ** Calling this routine with a NULL cursor pointer returns false.
 60508  **
 60509  ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
 60510  ** back to where it ought to be if this routine returns true.
 60511  */
 60512  SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
 60513    return pCur->eState!=CURSOR_VALID;
 60514  }
 60515  
 60516  /*
 60517  ** Return a pointer to a fake BtCursor object that will always answer
 60518  ** false to the sqlite3BtreeCursorHasMoved() routine above.  The fake
 60519  ** cursor returned must not be used with any other Btree interface.
 60520  */
 60521  SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void){
 60522    static u8 fakeCursor = CURSOR_VALID;
 60523    assert( offsetof(BtCursor, eState)==0 );
 60524    return (BtCursor*)&fakeCursor;
 60525  }
 60526  
 60527  /*
 60528  ** This routine restores a cursor back to its original position after it
 60529  ** has been moved by some outside activity (such as a btree rebalance or
 60530  ** a row having been deleted out from under the cursor).  
 60531  **
 60532  ** On success, the *pDifferentRow parameter is false if the cursor is left
 60533  ** pointing at exactly the same row.  *pDifferntRow is the row the cursor
 60534  ** was pointing to has been deleted, forcing the cursor to point to some
 60535  ** nearby row.
 60536  **
 60537  ** This routine should only be called for a cursor that just returned
 60538  ** TRUE from sqlite3BtreeCursorHasMoved().
 60539  */
 60540  SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
 60541    int rc;
 60542  
 60543    assert( pCur!=0 );
 60544    assert( pCur->eState!=CURSOR_VALID );
 60545    rc = restoreCursorPosition(pCur);
 60546    if( rc ){
 60547      *pDifferentRow = 1;
 60548      return rc;
 60549    }
 60550    if( pCur->eState!=CURSOR_VALID ){
 60551      *pDifferentRow = 1;
 60552    }else{
 60553      assert( pCur->skipNext==0 );
 60554      *pDifferentRow = 0;
 60555    }
 60556    return SQLITE_OK;
 60557  }
 60558  
 60559  #ifdef SQLITE_ENABLE_CURSOR_HINTS
 60560  /*
 60561  ** Provide hints to the cursor.  The particular hint given (and the type
 60562  ** and number of the varargs parameters) is determined by the eHintType
 60563  ** parameter.  See the definitions of the BTREE_HINT_* macros for details.
 60564  */
 60565  SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
 60566    /* Used only by system that substitute their own storage engine */
 60567  }
 60568  #endif
 60569  
 60570  /*
 60571  ** Provide flag hints to the cursor.
 60572  */
 60573  SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
 60574    assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
 60575    pCur->hints = x;
 60576  }
 60577  
 60578  
 60579  #ifndef SQLITE_OMIT_AUTOVACUUM
 60580  /*
 60581  ** Given a page number of a regular database page, return the page
 60582  ** number for the pointer-map page that contains the entry for the
 60583  ** input page number.
 60584  **
 60585  ** Return 0 (not a valid page) for pgno==1 since there is
 60586  ** no pointer map associated with page 1.  The integrity_check logic
 60587  ** requires that ptrmapPageno(*,1)!=1.
 60588  */
 60589  static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
 60590    int nPagesPerMapPage;
 60591    Pgno iPtrMap, ret;
 60592    assert( sqlite3_mutex_held(pBt->mutex) );
 60593    if( pgno<2 ) return 0;
 60594    nPagesPerMapPage = (pBt->usableSize/5)+1;
 60595    iPtrMap = (pgno-2)/nPagesPerMapPage;
 60596    ret = (iPtrMap*nPagesPerMapPage) + 2; 
 60597    if( ret==PENDING_BYTE_PAGE(pBt) ){
 60598      ret++;
 60599    }
 60600    return ret;
 60601  }
 60602  
 60603  /*
 60604  ** Write an entry into the pointer map.
 60605  **
 60606  ** This routine updates the pointer map entry for page number 'key'
 60607  ** so that it maps to type 'eType' and parent page number 'pgno'.
 60608  **
 60609  ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
 60610  ** a no-op.  If an error occurs, the appropriate error code is written
 60611  ** into *pRC.
 60612  */
 60613  static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
 60614    DbPage *pDbPage;  /* The pointer map page */
 60615    u8 *pPtrmap;      /* The pointer map data */
 60616    Pgno iPtrmap;     /* The pointer map page number */
 60617    int offset;       /* Offset in pointer map page */
 60618    int rc;           /* Return code from subfunctions */
 60619  
 60620    if( *pRC ) return;
 60621  
 60622    assert( sqlite3_mutex_held(pBt->mutex) );
 60623    /* The master-journal page number must never be used as a pointer map page */
 60624    assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
 60625  
 60626    assert( pBt->autoVacuum );
 60627    if( key==0 ){
 60628      *pRC = SQLITE_CORRUPT_BKPT;
 60629      return;
 60630    }
 60631    iPtrmap = PTRMAP_PAGENO(pBt, key);
 60632    rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
 60633    if( rc!=SQLITE_OK ){
 60634      *pRC = rc;
 60635      return;
 60636    }
 60637    offset = PTRMAP_PTROFFSET(iPtrmap, key);
 60638    if( offset<0 ){
 60639      *pRC = SQLITE_CORRUPT_BKPT;
 60640      goto ptrmap_exit;
 60641    }
 60642    assert( offset <= (int)pBt->usableSize-5 );
 60643    pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
 60644  
 60645    if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
 60646      TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
 60647      *pRC= rc = sqlite3PagerWrite(pDbPage);
 60648      if( rc==SQLITE_OK ){
 60649        pPtrmap[offset] = eType;
 60650        put4byte(&pPtrmap[offset+1], parent);
 60651      }
 60652    }
 60653  
 60654  ptrmap_exit:
 60655    sqlite3PagerUnref(pDbPage);
 60656  }
 60657  
 60658  /*
 60659  ** Read an entry from the pointer map.
 60660  **
 60661  ** This routine retrieves the pointer map entry for page 'key', writing
 60662  ** the type and parent page number to *pEType and *pPgno respectively.
 60663  ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
 60664  */
 60665  static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
 60666    DbPage *pDbPage;   /* The pointer map page */
 60667    int iPtrmap;       /* Pointer map page index */
 60668    u8 *pPtrmap;       /* Pointer map page data */
 60669    int offset;        /* Offset of entry in pointer map */
 60670    int rc;
 60671  
 60672    assert( sqlite3_mutex_held(pBt->mutex) );
 60673  
 60674    iPtrmap = PTRMAP_PAGENO(pBt, key);
 60675    rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
 60676    if( rc!=0 ){
 60677      return rc;
 60678    }
 60679    pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
 60680  
 60681    offset = PTRMAP_PTROFFSET(iPtrmap, key);
 60682    if( offset<0 ){
 60683      sqlite3PagerUnref(pDbPage);
 60684      return SQLITE_CORRUPT_BKPT;
 60685    }
 60686    assert( offset <= (int)pBt->usableSize-5 );
 60687    assert( pEType!=0 );
 60688    *pEType = pPtrmap[offset];
 60689    if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
 60690  
 60691    sqlite3PagerUnref(pDbPage);
 60692    if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
 60693    return SQLITE_OK;
 60694  }
 60695  
 60696  #else /* if defined SQLITE_OMIT_AUTOVACUUM */
 60697    #define ptrmapPut(w,x,y,z,rc)
 60698    #define ptrmapGet(w,x,y,z) SQLITE_OK
 60699    #define ptrmapPutOvflPtr(x, y, rc)
 60700  #endif
 60701  
 60702  /*
 60703  ** Given a btree page and a cell index (0 means the first cell on
 60704  ** the page, 1 means the second cell, and so forth) return a pointer
 60705  ** to the cell content.
 60706  **
 60707  ** findCellPastPtr() does the same except it skips past the initial
 60708  ** 4-byte child pointer found on interior pages, if there is one.
 60709  **
 60710  ** This routine works only for pages that do not contain overflow cells.
 60711  */
 60712  #define findCell(P,I) \
 60713    ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
 60714  #define findCellPastPtr(P,I) \
 60715    ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
 60716  
 60717  
 60718  /*
 60719  ** This is common tail processing for btreeParseCellPtr() and
 60720  ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
 60721  ** on a single B-tree page.  Make necessary adjustments to the CellInfo
 60722  ** structure.
 60723  */
 60724  static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
 60725    MemPage *pPage,         /* Page containing the cell */
 60726    u8 *pCell,              /* Pointer to the cell text. */
 60727    CellInfo *pInfo         /* Fill in this structure */
 60728  ){
 60729    /* If the payload will not fit completely on the local page, we have
 60730    ** to decide how much to store locally and how much to spill onto
 60731    ** overflow pages.  The strategy is to minimize the amount of unused
 60732    ** space on overflow pages while keeping the amount of local storage
 60733    ** in between minLocal and maxLocal.
 60734    **
 60735    ** Warning:  changing the way overflow payload is distributed in any
 60736    ** way will result in an incompatible file format.
 60737    */
 60738    int minLocal;  /* Minimum amount of payload held locally */
 60739    int maxLocal;  /* Maximum amount of payload held locally */
 60740    int surplus;   /* Overflow payload available for local storage */
 60741  
 60742    minLocal = pPage->minLocal;
 60743    maxLocal = pPage->maxLocal;
 60744    surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
 60745    testcase( surplus==maxLocal );
 60746    testcase( surplus==maxLocal+1 );
 60747    if( surplus <= maxLocal ){
 60748      pInfo->nLocal = (u16)surplus;
 60749    }else{
 60750      pInfo->nLocal = (u16)minLocal;
 60751    }
 60752    pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
 60753  }
 60754  
 60755  /*
 60756  ** The following routines are implementations of the MemPage.xParseCell()
 60757  ** method.
 60758  **
 60759  ** Parse a cell content block and fill in the CellInfo structure.
 60760  **
 60761  ** btreeParseCellPtr()        =>   table btree leaf nodes
 60762  ** btreeParseCellNoPayload()  =>   table btree internal nodes
 60763  ** btreeParseCellPtrIndex()   =>   index btree nodes
 60764  **
 60765  ** There is also a wrapper function btreeParseCell() that works for
 60766  ** all MemPage types and that references the cell by index rather than
 60767  ** by pointer.
 60768  */
 60769  static void btreeParseCellPtrNoPayload(
 60770    MemPage *pPage,         /* Page containing the cell */
 60771    u8 *pCell,              /* Pointer to the cell text. */
 60772    CellInfo *pInfo         /* Fill in this structure */
 60773  ){
 60774    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 60775    assert( pPage->leaf==0 );
 60776    assert( pPage->childPtrSize==4 );
 60777  #ifndef SQLITE_DEBUG
 60778    UNUSED_PARAMETER(pPage);
 60779  #endif
 60780    pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
 60781    pInfo->nPayload = 0;
 60782    pInfo->nLocal = 0;
 60783    pInfo->pPayload = 0;
 60784    return;
 60785  }
 60786  static void btreeParseCellPtr(
 60787    MemPage *pPage,         /* Page containing the cell */
 60788    u8 *pCell,              /* Pointer to the cell text. */
 60789    CellInfo *pInfo         /* Fill in this structure */
 60790  ){
 60791    u8 *pIter;              /* For scanning through pCell */
 60792    u32 nPayload;           /* Number of bytes of cell payload */
 60793    u64 iKey;               /* Extracted Key value */
 60794  
 60795    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 60796    assert( pPage->leaf==0 || pPage->leaf==1 );
 60797    assert( pPage->intKeyLeaf );
 60798    assert( pPage->childPtrSize==0 );
 60799    pIter = pCell;
 60800  
 60801    /* The next block of code is equivalent to:
 60802    **
 60803    **     pIter += getVarint32(pIter, nPayload);
 60804    **
 60805    ** The code is inlined to avoid a function call.
 60806    */
 60807    nPayload = *pIter;
 60808    if( nPayload>=0x80 ){
 60809      u8 *pEnd = &pIter[8];
 60810      nPayload &= 0x7f;
 60811      do{
 60812        nPayload = (nPayload<<7) | (*++pIter & 0x7f);
 60813      }while( (*pIter)>=0x80 && pIter<pEnd );
 60814    }
 60815    pIter++;
 60816  
 60817    /* The next block of code is equivalent to:
 60818    **
 60819    **     pIter += getVarint(pIter, (u64*)&pInfo->nKey);
 60820    **
 60821    ** The code is inlined to avoid a function call.
 60822    */
 60823    iKey = *pIter;
 60824    if( iKey>=0x80 ){
 60825      u8 *pEnd = &pIter[7];
 60826      iKey &= 0x7f;
 60827      while(1){
 60828        iKey = (iKey<<7) | (*++pIter & 0x7f);
 60829        if( (*pIter)<0x80 ) break;
 60830        if( pIter>=pEnd ){
 60831          iKey = (iKey<<8) | *++pIter;
 60832          break;
 60833        }
 60834      }
 60835    }
 60836    pIter++;
 60837  
 60838    pInfo->nKey = *(i64*)&iKey;
 60839    pInfo->nPayload = nPayload;
 60840    pInfo->pPayload = pIter;
 60841    testcase( nPayload==pPage->maxLocal );
 60842    testcase( nPayload==pPage->maxLocal+1 );
 60843    if( nPayload<=pPage->maxLocal ){
 60844      /* This is the (easy) common case where the entire payload fits
 60845      ** on the local page.  No overflow is required.
 60846      */
 60847      pInfo->nSize = nPayload + (u16)(pIter - pCell);
 60848      if( pInfo->nSize<4 ) pInfo->nSize = 4;
 60849      pInfo->nLocal = (u16)nPayload;
 60850    }else{
 60851      btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
 60852    }
 60853  }
 60854  static void btreeParseCellPtrIndex(
 60855    MemPage *pPage,         /* Page containing the cell */
 60856    u8 *pCell,              /* Pointer to the cell text. */
 60857    CellInfo *pInfo         /* Fill in this structure */
 60858  ){
 60859    u8 *pIter;              /* For scanning through pCell */
 60860    u32 nPayload;           /* Number of bytes of cell payload */
 60861  
 60862    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 60863    assert( pPage->leaf==0 || pPage->leaf==1 );
 60864    assert( pPage->intKeyLeaf==0 );
 60865    pIter = pCell + pPage->childPtrSize;
 60866    nPayload = *pIter;
 60867    if( nPayload>=0x80 ){
 60868      u8 *pEnd = &pIter[8];
 60869      nPayload &= 0x7f;
 60870      do{
 60871        nPayload = (nPayload<<7) | (*++pIter & 0x7f);
 60872      }while( *(pIter)>=0x80 && pIter<pEnd );
 60873    }
 60874    pIter++;
 60875    pInfo->nKey = nPayload;
 60876    pInfo->nPayload = nPayload;
 60877    pInfo->pPayload = pIter;
 60878    testcase( nPayload==pPage->maxLocal );
 60879    testcase( nPayload==pPage->maxLocal+1 );
 60880    if( nPayload<=pPage->maxLocal ){
 60881      /* This is the (easy) common case where the entire payload fits
 60882      ** on the local page.  No overflow is required.
 60883      */
 60884      pInfo->nSize = nPayload + (u16)(pIter - pCell);
 60885      if( pInfo->nSize<4 ) pInfo->nSize = 4;
 60886      pInfo->nLocal = (u16)nPayload;
 60887    }else{
 60888      btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
 60889    }
 60890  }
 60891  static void btreeParseCell(
 60892    MemPage *pPage,         /* Page containing the cell */
 60893    int iCell,              /* The cell index.  First cell is 0 */
 60894    CellInfo *pInfo         /* Fill in this structure */
 60895  ){
 60896    pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
 60897  }
 60898  
 60899  /*
 60900  ** The following routines are implementations of the MemPage.xCellSize
 60901  ** method.
 60902  **
 60903  ** Compute the total number of bytes that a Cell needs in the cell
 60904  ** data area of the btree-page.  The return number includes the cell
 60905  ** data header and the local payload, but not any overflow page or
 60906  ** the space used by the cell pointer.
 60907  **
 60908  ** cellSizePtrNoPayload()    =>   table internal nodes
 60909  ** cellSizePtr()             =>   all index nodes & table leaf nodes
 60910  */
 60911  static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
 60912    u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
 60913    u8 *pEnd;                                /* End mark for a varint */
 60914    u32 nSize;                               /* Size value to return */
 60915  
 60916  #ifdef SQLITE_DEBUG
 60917    /* The value returned by this function should always be the same as
 60918    ** the (CellInfo.nSize) value found by doing a full parse of the
 60919    ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
 60920    ** this function verifies that this invariant is not violated. */
 60921    CellInfo debuginfo;
 60922    pPage->xParseCell(pPage, pCell, &debuginfo);
 60923  #endif
 60924  
 60925    nSize = *pIter;
 60926    if( nSize>=0x80 ){
 60927      pEnd = &pIter[8];
 60928      nSize &= 0x7f;
 60929      do{
 60930        nSize = (nSize<<7) | (*++pIter & 0x7f);
 60931      }while( *(pIter)>=0x80 && pIter<pEnd );
 60932    }
 60933    pIter++;
 60934    if( pPage->intKey ){
 60935      /* pIter now points at the 64-bit integer key value, a variable length 
 60936      ** integer. The following block moves pIter to point at the first byte
 60937      ** past the end of the key value. */
 60938      pEnd = &pIter[9];
 60939      while( (*pIter++)&0x80 && pIter<pEnd );
 60940    }
 60941    testcase( nSize==pPage->maxLocal );
 60942    testcase( nSize==pPage->maxLocal+1 );
 60943    if( nSize<=pPage->maxLocal ){
 60944      nSize += (u32)(pIter - pCell);
 60945      if( nSize<4 ) nSize = 4;
 60946    }else{
 60947      int minLocal = pPage->minLocal;
 60948      nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
 60949      testcase( nSize==pPage->maxLocal );
 60950      testcase( nSize==pPage->maxLocal+1 );
 60951      if( nSize>pPage->maxLocal ){
 60952        nSize = minLocal;
 60953      }
 60954      nSize += 4 + (u16)(pIter - pCell);
 60955    }
 60956    assert( nSize==debuginfo.nSize || CORRUPT_DB );
 60957    return (u16)nSize;
 60958  }
 60959  static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
 60960    u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
 60961    u8 *pEnd;              /* End mark for a varint */
 60962  
 60963  #ifdef SQLITE_DEBUG
 60964    /* The value returned by this function should always be the same as
 60965    ** the (CellInfo.nSize) value found by doing a full parse of the
 60966    ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
 60967    ** this function verifies that this invariant is not violated. */
 60968    CellInfo debuginfo;
 60969    pPage->xParseCell(pPage, pCell, &debuginfo);
 60970  #else
 60971    UNUSED_PARAMETER(pPage);
 60972  #endif
 60973  
 60974    assert( pPage->childPtrSize==4 );
 60975    pEnd = pIter + 9;
 60976    while( (*pIter++)&0x80 && pIter<pEnd );
 60977    assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
 60978    return (u16)(pIter - pCell);
 60979  }
 60980  
 60981  
 60982  #ifdef SQLITE_DEBUG
 60983  /* This variation on cellSizePtr() is used inside of assert() statements
 60984  ** only. */
 60985  static u16 cellSize(MemPage *pPage, int iCell){
 60986    return pPage->xCellSize(pPage, findCell(pPage, iCell));
 60987  }
 60988  #endif
 60989  
 60990  #ifndef SQLITE_OMIT_AUTOVACUUM
 60991  /*
 60992  ** If the cell pCell, part of page pPage contains a pointer
 60993  ** to an overflow page, insert an entry into the pointer-map
 60994  ** for the overflow page.
 60995  */
 60996  static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
 60997    CellInfo info;
 60998    if( *pRC ) return;
 60999    assert( pCell!=0 );
 61000    pPage->xParseCell(pPage, pCell, &info);
 61001    if( info.nLocal<info.nPayload ){
 61002      Pgno ovfl = get4byte(&pCell[info.nSize-4]);
 61003      ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
 61004    }
 61005  }
 61006  #endif
 61007  
 61008  
 61009  /*
 61010  ** Defragment the page given. This routine reorganizes cells within the
 61011  ** page so that there are no free-blocks on the free-block list.
 61012  **
 61013  ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
 61014  ** present in the page after this routine returns.
 61015  **
 61016  ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
 61017  ** b-tree page so that there are no freeblocks or fragment bytes, all
 61018  ** unused bytes are contained in the unallocated space region, and all
 61019  ** cells are packed tightly at the end of the page.
 61020  */
 61021  static int defragmentPage(MemPage *pPage, int nMaxFrag){
 61022    int i;                     /* Loop counter */
 61023    int pc;                    /* Address of the i-th cell */
 61024    int hdr;                   /* Offset to the page header */
 61025    int size;                  /* Size of a cell */
 61026    int usableSize;            /* Number of usable bytes on a page */
 61027    int cellOffset;            /* Offset to the cell pointer array */
 61028    int cbrk;                  /* Offset to the cell content area */
 61029    int nCell;                 /* Number of cells on the page */
 61030    unsigned char *data;       /* The page data */
 61031    unsigned char *temp;       /* Temp area for cell content */
 61032    unsigned char *src;        /* Source of content */
 61033    int iCellFirst;            /* First allowable cell index */
 61034    int iCellLast;             /* Last possible cell index */
 61035  
 61036    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 61037    assert( pPage->pBt!=0 );
 61038    assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
 61039    assert( pPage->nOverflow==0 );
 61040    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 61041    temp = 0;
 61042    src = data = pPage->aData;
 61043    hdr = pPage->hdrOffset;
 61044    cellOffset = pPage->cellOffset;
 61045    nCell = pPage->nCell;
 61046    assert( nCell==get2byte(&data[hdr+3]) );
 61047    iCellFirst = cellOffset + 2*nCell;
 61048    usableSize = pPage->pBt->usableSize;
 61049  
 61050    /* This block handles pages with two or fewer free blocks and nMaxFrag
 61051    ** or fewer fragmented bytes. In this case it is faster to move the
 61052    ** two (or one) blocks of cells using memmove() and add the required
 61053    ** offsets to each pointer in the cell-pointer array than it is to 
 61054    ** reconstruct the entire page.  */
 61055    if( (int)data[hdr+7]<=nMaxFrag ){
 61056      int iFree = get2byte(&data[hdr+1]);
 61057      if( iFree ){
 61058        int iFree2 = get2byte(&data[iFree]);
 61059  
 61060        /* pageFindSlot() has already verified that free blocks are sorted
 61061        ** in order of offset within the page, and that no block extends
 61062        ** past the end of the page. Provided the two free slots do not 
 61063        ** overlap, this guarantees that the memmove() calls below will not
 61064        ** overwrite the usableSize byte buffer, even if the database page
 61065        ** is corrupt.  */
 61066        assert( iFree2==0 || iFree2>iFree );
 61067        assert( iFree+get2byte(&data[iFree+2]) <= usableSize );
 61068        assert( iFree2==0 || iFree2+get2byte(&data[iFree2+2]) <= usableSize );
 61069  
 61070        if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
 61071          u8 *pEnd = &data[cellOffset + nCell*2];
 61072          u8 *pAddr;
 61073          int sz2 = 0;
 61074          int sz = get2byte(&data[iFree+2]);
 61075          int top = get2byte(&data[hdr+5]);
 61076          if( top>=iFree ){
 61077            return SQLITE_CORRUPT_PGNO(pPage->pgno);
 61078          }
 61079          if( iFree2 ){
 61080            assert( iFree+sz<=iFree2 ); /* Verified by pageFindSlot() */
 61081            sz2 = get2byte(&data[iFree2+2]);
 61082            assert( iFree+sz+sz2+iFree2-(iFree+sz) <= usableSize );
 61083            memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
 61084            sz += sz2;
 61085          }
 61086          cbrk = top+sz;
 61087          assert( cbrk+(iFree-top) <= usableSize );
 61088          memmove(&data[cbrk], &data[top], iFree-top);
 61089          for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
 61090            pc = get2byte(pAddr);
 61091            if( pc<iFree ){ put2byte(pAddr, pc+sz); }
 61092            else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
 61093          }
 61094          goto defragment_out;
 61095        }
 61096      }
 61097    }
 61098  
 61099    cbrk = usableSize;
 61100    iCellLast = usableSize - 4;
 61101    for(i=0; i<nCell; i++){
 61102      u8 *pAddr;     /* The i-th cell pointer */
 61103      pAddr = &data[cellOffset + i*2];
 61104      pc = get2byte(pAddr);
 61105      testcase( pc==iCellFirst );
 61106      testcase( pc==iCellLast );
 61107      /* These conditions have already been verified in btreeInitPage()
 61108      ** if PRAGMA cell_size_check=ON.
 61109      */
 61110      if( pc<iCellFirst || pc>iCellLast ){
 61111        return SQLITE_CORRUPT_PGNO(pPage->pgno);
 61112      }
 61113      assert( pc>=iCellFirst && pc<=iCellLast );
 61114      size = pPage->xCellSize(pPage, &src[pc]);
 61115      cbrk -= size;
 61116      if( cbrk<iCellFirst || pc+size>usableSize ){
 61117        return SQLITE_CORRUPT_PGNO(pPage->pgno);
 61118      }
 61119      assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
 61120      testcase( cbrk+size==usableSize );
 61121      testcase( pc+size==usableSize );
 61122      put2byte(pAddr, cbrk);
 61123      if( temp==0 ){
 61124        int x;
 61125        if( cbrk==pc ) continue;
 61126        temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
 61127        x = get2byte(&data[hdr+5]);
 61128        memcpy(&temp[x], &data[x], (cbrk+size) - x);
 61129        src = temp;
 61130      }
 61131      memcpy(&data[cbrk], &src[pc], size);
 61132    }
 61133    data[hdr+7] = 0;
 61134  
 61135   defragment_out:
 61136    if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
 61137      return SQLITE_CORRUPT_PGNO(pPage->pgno);
 61138    }
 61139    assert( cbrk>=iCellFirst );
 61140    put2byte(&data[hdr+5], cbrk);
 61141    data[hdr+1] = 0;
 61142    data[hdr+2] = 0;
 61143    memset(&data[iCellFirst], 0, cbrk-iCellFirst);
 61144    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 61145    return SQLITE_OK;
 61146  }
 61147  
 61148  /*
 61149  ** Search the free-list on page pPg for space to store a cell nByte bytes in
 61150  ** size. If one can be found, return a pointer to the space and remove it
 61151  ** from the free-list.
 61152  **
 61153  ** If no suitable space can be found on the free-list, return NULL.
 61154  **
 61155  ** This function may detect corruption within pPg.  If corruption is
 61156  ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
 61157  **
 61158  ** Slots on the free list that are between 1 and 3 bytes larger than nByte
 61159  ** will be ignored if adding the extra space to the fragmentation count
 61160  ** causes the fragmentation count to exceed 60.
 61161  */
 61162  static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
 61163    const int hdr = pPg->hdrOffset;
 61164    u8 * const aData = pPg->aData;
 61165    int iAddr = hdr + 1;
 61166    int pc = get2byte(&aData[iAddr]);
 61167    int x;
 61168    int usableSize = pPg->pBt->usableSize;
 61169    int size;            /* Size of the free slot */
 61170  
 61171    assert( pc>0 );
 61172    while( pc<=usableSize-4 ){
 61173      /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
 61174      ** freeblock form a big-endian integer which is the size of the freeblock
 61175      ** in bytes, including the 4-byte header. */
 61176      size = get2byte(&aData[pc+2]);
 61177      if( (x = size - nByte)>=0 ){
 61178        testcase( x==4 );
 61179        testcase( x==3 );
 61180        if( size+pc > usableSize ){
 61181          *pRc = SQLITE_CORRUPT_PGNO(pPg->pgno);
 61182          return 0;
 61183        }else if( x<4 ){
 61184          /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
 61185          ** number of bytes in fragments may not exceed 60. */
 61186          if( aData[hdr+7]>57 ) return 0;
 61187  
 61188          /* Remove the slot from the free-list. Update the number of
 61189          ** fragmented bytes within the page. */
 61190          memcpy(&aData[iAddr], &aData[pc], 2);
 61191          aData[hdr+7] += (u8)x;
 61192        }else{
 61193          /* The slot remains on the free-list. Reduce its size to account
 61194           ** for the portion used by the new allocation. */
 61195          put2byte(&aData[pc+2], x);
 61196        }
 61197        return &aData[pc + x];
 61198      }
 61199      iAddr = pc;
 61200      pc = get2byte(&aData[pc]);
 61201      if( pc<iAddr+size ) break;
 61202    }
 61203    if( pc ){
 61204      *pRc = SQLITE_CORRUPT_PGNO(pPg->pgno);
 61205    }
 61206  
 61207    return 0;
 61208  }
 61209  
 61210  /*
 61211  ** Allocate nByte bytes of space from within the B-Tree page passed
 61212  ** as the first argument. Write into *pIdx the index into pPage->aData[]
 61213  ** of the first byte of allocated space. Return either SQLITE_OK or
 61214  ** an error code (usually SQLITE_CORRUPT).
 61215  **
 61216  ** The caller guarantees that there is sufficient space to make the
 61217  ** allocation.  This routine might need to defragment in order to bring
 61218  ** all the space together, however.  This routine will avoid using
 61219  ** the first two bytes past the cell pointer area since presumably this
 61220  ** allocation is being made in order to insert a new cell, so we will
 61221  ** also end up needing a new cell pointer.
 61222  */
 61223  static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
 61224    const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
 61225    u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
 61226    int top;                             /* First byte of cell content area */
 61227    int rc = SQLITE_OK;                  /* Integer return code */
 61228    int gap;        /* First byte of gap between cell pointers and cell content */
 61229    
 61230    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 61231    assert( pPage->pBt );
 61232    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 61233    assert( nByte>=0 );  /* Minimum cell size is 4 */
 61234    assert( pPage->nFree>=nByte );
 61235    assert( pPage->nOverflow==0 );
 61236    assert( nByte < (int)(pPage->pBt->usableSize-8) );
 61237  
 61238    assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
 61239    gap = pPage->cellOffset + 2*pPage->nCell;
 61240    assert( gap<=65536 );
 61241    /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
 61242    ** and the reserved space is zero (the usual value for reserved space)
 61243    ** then the cell content offset of an empty page wants to be 65536.
 61244    ** However, that integer is too large to be stored in a 2-byte unsigned
 61245    ** integer, so a value of 0 is used in its place. */
 61246    top = get2byte(&data[hdr+5]);
 61247    assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
 61248    if( gap>top ){
 61249      if( top==0 && pPage->pBt->usableSize==65536 ){
 61250        top = 65536;
 61251      }else{
 61252        return SQLITE_CORRUPT_PGNO(pPage->pgno);
 61253      }
 61254    }
 61255  
 61256    /* If there is enough space between gap and top for one more cell pointer
 61257    ** array entry offset, and if the freelist is not empty, then search the
 61258    ** freelist looking for a free slot big enough to satisfy the request.
 61259    */
 61260    testcase( gap+2==top );
 61261    testcase( gap+1==top );
 61262    testcase( gap==top );
 61263    if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
 61264      u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
 61265      if( pSpace ){
 61266        assert( pSpace>=data && (pSpace - data)<65536 );
 61267        *pIdx = (int)(pSpace - data);
 61268        return SQLITE_OK;
 61269      }else if( rc ){
 61270        return rc;
 61271      }
 61272    }
 61273  
 61274    /* The request could not be fulfilled using a freelist slot.  Check
 61275    ** to see if defragmentation is necessary.
 61276    */
 61277    testcase( gap+2+nByte==top );
 61278    if( gap+2+nByte>top ){
 61279      assert( pPage->nCell>0 || CORRUPT_DB );
 61280      rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
 61281      if( rc ) return rc;
 61282      top = get2byteNotZero(&data[hdr+5]);
 61283      assert( gap+2+nByte<=top );
 61284    }
 61285  
 61286  
 61287    /* Allocate memory from the gap in between the cell pointer array
 61288    ** and the cell content area.  The btreeInitPage() call has already
 61289    ** validated the freelist.  Given that the freelist is valid, there
 61290    ** is no way that the allocation can extend off the end of the page.
 61291    ** The assert() below verifies the previous sentence.
 61292    */
 61293    top -= nByte;
 61294    put2byte(&data[hdr+5], top);
 61295    assert( top+nByte <= (int)pPage->pBt->usableSize );
 61296    *pIdx = top;
 61297    return SQLITE_OK;
 61298  }
 61299  
 61300  /*
 61301  ** Return a section of the pPage->aData to the freelist.
 61302  ** The first byte of the new free block is pPage->aData[iStart]
 61303  ** and the size of the block is iSize bytes.
 61304  **
 61305  ** Adjacent freeblocks are coalesced.
 61306  **
 61307  ** Note that even though the freeblock list was checked by btreeInitPage(),
 61308  ** that routine will not detect overlap between cells or freeblocks.  Nor
 61309  ** does it detect cells or freeblocks that encrouch into the reserved bytes
 61310  ** at the end of the page.  So do additional corruption checks inside this
 61311  ** routine and return SQLITE_CORRUPT if any problems are found.
 61312  */
 61313  static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
 61314    u16 iPtr;                             /* Address of ptr to next freeblock */
 61315    u16 iFreeBlk;                         /* Address of the next freeblock */
 61316    u8 hdr;                               /* Page header size.  0 or 100 */
 61317    u8 nFrag = 0;                         /* Reduction in fragmentation */
 61318    u16 iOrigSize = iSize;                /* Original value of iSize */
 61319    u16 x;                                /* Offset to cell content area */
 61320    u32 iEnd = iStart + iSize;            /* First byte past the iStart buffer */
 61321    unsigned char *data = pPage->aData;   /* Page content */
 61322  
 61323    assert( pPage->pBt!=0 );
 61324    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 61325    assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
 61326    assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
 61327    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 61328    assert( iSize>=4 );   /* Minimum cell size is 4 */
 61329    assert( iStart<=pPage->pBt->usableSize-4 );
 61330  
 61331    /* The list of freeblocks must be in ascending order.  Find the 
 61332    ** spot on the list where iStart should be inserted.
 61333    */
 61334    hdr = pPage->hdrOffset;
 61335    iPtr = hdr + 1;
 61336    if( data[iPtr+1]==0 && data[iPtr]==0 ){
 61337      iFreeBlk = 0;  /* Shortcut for the case when the freelist is empty */
 61338    }else{
 61339      while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
 61340        if( iFreeBlk<iPtr+4 ){
 61341          if( iFreeBlk==0 ) break;
 61342          return SQLITE_CORRUPT_PGNO(pPage->pgno);
 61343        }
 61344        iPtr = iFreeBlk;
 61345      }
 61346      if( iFreeBlk>pPage->pBt->usableSize-4 ){
 61347        return SQLITE_CORRUPT_PGNO(pPage->pgno);
 61348      }
 61349      assert( iFreeBlk>iPtr || iFreeBlk==0 );
 61350    
 61351      /* At this point:
 61352      **    iFreeBlk:   First freeblock after iStart, or zero if none
 61353      **    iPtr:       The address of a pointer to iFreeBlk
 61354      **
 61355      ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
 61356      */
 61357      if( iFreeBlk && iEnd+3>=iFreeBlk ){
 61358        nFrag = iFreeBlk - iEnd;
 61359        if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
 61360        iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
 61361        if( iEnd > pPage->pBt->usableSize ){
 61362          return SQLITE_CORRUPT_PGNO(pPage->pgno);
 61363        }
 61364        iSize = iEnd - iStart;
 61365        iFreeBlk = get2byte(&data[iFreeBlk]);
 61366      }
 61367    
 61368      /* If iPtr is another freeblock (that is, if iPtr is not the freelist
 61369      ** pointer in the page header) then check to see if iStart should be
 61370      ** coalesced onto the end of iPtr.
 61371      */
 61372      if( iPtr>hdr+1 ){
 61373        int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
 61374        if( iPtrEnd+3>=iStart ){
 61375          if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
 61376          nFrag += iStart - iPtrEnd;
 61377          iSize = iEnd - iPtr;
 61378          iStart = iPtr;
 61379        }
 61380      }
 61381      if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
 61382      data[hdr+7] -= nFrag;
 61383    }
 61384    x = get2byte(&data[hdr+5]);
 61385    if( iStart<=x ){
 61386      /* The new freeblock is at the beginning of the cell content area,
 61387      ** so just extend the cell content area rather than create another
 61388      ** freelist entry */
 61389      if( iStart<x || iPtr!=hdr+1 ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
 61390      put2byte(&data[hdr+1], iFreeBlk);
 61391      put2byte(&data[hdr+5], iEnd);
 61392    }else{
 61393      /* Insert the new freeblock into the freelist */
 61394      put2byte(&data[iPtr], iStart);
 61395    }
 61396    if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
 61397      /* Overwrite deleted information with zeros when the secure_delete
 61398      ** option is enabled */
 61399      memset(&data[iStart], 0, iSize);
 61400    }
 61401    put2byte(&data[iStart], iFreeBlk);
 61402    put2byte(&data[iStart+2], iSize);
 61403    pPage->nFree += iOrigSize;
 61404    return SQLITE_OK;
 61405  }
 61406  
 61407  /*
 61408  ** Decode the flags byte (the first byte of the header) for a page
 61409  ** and initialize fields of the MemPage structure accordingly.
 61410  **
 61411  ** Only the following combinations are supported.  Anything different
 61412  ** indicates a corrupt database files:
 61413  **
 61414  **         PTF_ZERODATA
 61415  **         PTF_ZERODATA | PTF_LEAF
 61416  **         PTF_LEAFDATA | PTF_INTKEY
 61417  **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
 61418  */
 61419  static int decodeFlags(MemPage *pPage, int flagByte){
 61420    BtShared *pBt;     /* A copy of pPage->pBt */
 61421  
 61422    assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
 61423    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 61424    pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
 61425    flagByte &= ~PTF_LEAF;
 61426    pPage->childPtrSize = 4-4*pPage->leaf;
 61427    pPage->xCellSize = cellSizePtr;
 61428    pBt = pPage->pBt;
 61429    if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
 61430      /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
 61431      ** interior table b-tree page. */
 61432      assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
 61433      /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
 61434      ** leaf table b-tree page. */
 61435      assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
 61436      pPage->intKey = 1;
 61437      if( pPage->leaf ){
 61438        pPage->intKeyLeaf = 1;
 61439        pPage->xParseCell = btreeParseCellPtr;
 61440      }else{
 61441        pPage->intKeyLeaf = 0;
 61442        pPage->xCellSize = cellSizePtrNoPayload;
 61443        pPage->xParseCell = btreeParseCellPtrNoPayload;
 61444      }
 61445      pPage->maxLocal = pBt->maxLeaf;
 61446      pPage->minLocal = pBt->minLeaf;
 61447    }else if( flagByte==PTF_ZERODATA ){
 61448      /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
 61449      ** interior index b-tree page. */
 61450      assert( (PTF_ZERODATA)==2 );
 61451      /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
 61452      ** leaf index b-tree page. */
 61453      assert( (PTF_ZERODATA|PTF_LEAF)==10 );
 61454      pPage->intKey = 0;
 61455      pPage->intKeyLeaf = 0;
 61456      pPage->xParseCell = btreeParseCellPtrIndex;
 61457      pPage->maxLocal = pBt->maxLocal;
 61458      pPage->minLocal = pBt->minLocal;
 61459    }else{
 61460      /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
 61461      ** an error. */
 61462      return SQLITE_CORRUPT_PGNO(pPage->pgno);
 61463    }
 61464    pPage->max1bytePayload = pBt->max1bytePayload;
 61465    return SQLITE_OK;
 61466  }
 61467  
 61468  /*
 61469  ** Initialize the auxiliary information for a disk block.
 61470  **
 61471  ** Return SQLITE_OK on success.  If we see that the page does
 61472  ** not contain a well-formed database page, then return 
 61473  ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
 61474  ** guarantee that the page is well-formed.  It only shows that
 61475  ** we failed to detect any corruption.
 61476  */
 61477  static int btreeInitPage(MemPage *pPage){
 61478    int pc;            /* Address of a freeblock within pPage->aData[] */
 61479    u8 hdr;            /* Offset to beginning of page header */
 61480    u8 *data;          /* Equal to pPage->aData */
 61481    BtShared *pBt;        /* The main btree structure */
 61482    int usableSize;    /* Amount of usable space on each page */
 61483    u16 cellOffset;    /* Offset from start of page to first cell pointer */
 61484    int nFree;         /* Number of unused bytes on the page */
 61485    int top;           /* First byte of the cell content area */
 61486    int iCellFirst;    /* First allowable cell or freeblock offset */
 61487    int iCellLast;     /* Last possible cell or freeblock offset */
 61488  
 61489    assert( pPage->pBt!=0 );
 61490    assert( pPage->pBt->db!=0 );
 61491    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 61492    assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
 61493    assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
 61494    assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
 61495    assert( pPage->isInit==0 );
 61496  
 61497    pBt = pPage->pBt;
 61498    hdr = pPage->hdrOffset;
 61499    data = pPage->aData;
 61500    /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
 61501    ** the b-tree page type. */
 61502    if( decodeFlags(pPage, data[hdr]) ){
 61503      return SQLITE_CORRUPT_PGNO(pPage->pgno);
 61504    }
 61505    assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
 61506    pPage->maskPage = (u16)(pBt->pageSize - 1);
 61507    pPage->nOverflow = 0;
 61508    usableSize = pBt->usableSize;
 61509    pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
 61510    pPage->aDataEnd = &data[usableSize];
 61511    pPage->aCellIdx = &data[cellOffset];
 61512    pPage->aDataOfst = &data[pPage->childPtrSize];
 61513    /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
 61514    ** the start of the cell content area. A zero value for this integer is
 61515    ** interpreted as 65536. */
 61516    top = get2byteNotZero(&data[hdr+5]);
 61517    /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
 61518    ** number of cells on the page. */
 61519    pPage->nCell = get2byte(&data[hdr+3]);
 61520    if( pPage->nCell>MX_CELL(pBt) ){
 61521      /* To many cells for a single page.  The page must be corrupt */
 61522      return SQLITE_CORRUPT_PGNO(pPage->pgno);
 61523    }
 61524    testcase( pPage->nCell==MX_CELL(pBt) );
 61525    /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
 61526    ** possible for a root page of a table that contains no rows) then the
 61527    ** offset to the cell content area will equal the page size minus the
 61528    ** bytes of reserved space. */
 61529    assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
 61530  
 61531    /* A malformed database page might cause us to read past the end
 61532    ** of page when parsing a cell.  
 61533    **
 61534    ** The following block of code checks early to see if a cell extends
 61535    ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
 61536    ** returned if it does.
 61537    */
 61538    iCellFirst = cellOffset + 2*pPage->nCell;
 61539    iCellLast = usableSize - 4;
 61540    if( pBt->db->flags & SQLITE_CellSizeCk ){
 61541      int i;            /* Index into the cell pointer array */
 61542      int sz;           /* Size of a cell */
 61543  
 61544      if( !pPage->leaf ) iCellLast--;
 61545      for(i=0; i<pPage->nCell; i++){
 61546        pc = get2byteAligned(&data[cellOffset+i*2]);
 61547        testcase( pc==iCellFirst );
 61548        testcase( pc==iCellLast );
 61549        if( pc<iCellFirst || pc>iCellLast ){
 61550          return SQLITE_CORRUPT_PGNO(pPage->pgno);
 61551        }
 61552        sz = pPage->xCellSize(pPage, &data[pc]);
 61553        testcase( pc+sz==usableSize );
 61554        if( pc+sz>usableSize ){
 61555          return SQLITE_CORRUPT_PGNO(pPage->pgno);
 61556        }
 61557      }
 61558      if( !pPage->leaf ) iCellLast++;
 61559    }  
 61560  
 61561    /* Compute the total free space on the page
 61562    ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
 61563    ** start of the first freeblock on the page, or is zero if there are no
 61564    ** freeblocks. */
 61565    pc = get2byte(&data[hdr+1]);
 61566    nFree = data[hdr+7] + top;  /* Init nFree to non-freeblock free space */
 61567    if( pc>0 ){
 61568      u32 next, size;
 61569      if( pc<iCellFirst ){
 61570        /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
 61571        ** always be at least one cell before the first freeblock.
 61572        */
 61573        return SQLITE_CORRUPT_PGNO(pPage->pgno); 
 61574      }
 61575      while( 1 ){
 61576        if( pc>iCellLast ){
 61577          /* Freeblock off the end of the page */
 61578          return SQLITE_CORRUPT_PGNO(pPage->pgno);
 61579        }
 61580        next = get2byte(&data[pc]);
 61581        size = get2byte(&data[pc+2]);
 61582        nFree = nFree + size;
 61583        if( next<=pc+size+3 ) break;
 61584        pc = next;
 61585      }
 61586      if( next>0 ){
 61587        /* Freeblock not in ascending order */
 61588        return SQLITE_CORRUPT_PGNO(pPage->pgno);
 61589      }
 61590      if( pc+size>(unsigned int)usableSize ){
 61591        /* Last freeblock extends past page end */
 61592        return SQLITE_CORRUPT_PGNO(pPage->pgno);
 61593      }
 61594    }
 61595  
 61596    /* At this point, nFree contains the sum of the offset to the start
 61597    ** of the cell-content area plus the number of free bytes within
 61598    ** the cell-content area. If this is greater than the usable-size
 61599    ** of the page, then the page must be corrupted. This check also
 61600    ** serves to verify that the offset to the start of the cell-content
 61601    ** area, according to the page header, lies within the page.
 61602    */
 61603    if( nFree>usableSize ){
 61604      return SQLITE_CORRUPT_PGNO(pPage->pgno);
 61605    }
 61606    pPage->nFree = (u16)(nFree - iCellFirst);
 61607    pPage->isInit = 1;
 61608    return SQLITE_OK;
 61609  }
 61610  
 61611  /*
 61612  ** Set up a raw page so that it looks like a database page holding
 61613  ** no entries.
 61614  */
 61615  static void zeroPage(MemPage *pPage, int flags){
 61616    unsigned char *data = pPage->aData;
 61617    BtShared *pBt = pPage->pBt;
 61618    u8 hdr = pPage->hdrOffset;
 61619    u16 first;
 61620  
 61621    assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
 61622    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
 61623    assert( sqlite3PagerGetData(pPage->pDbPage) == data );
 61624    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 61625    assert( sqlite3_mutex_held(pBt->mutex) );
 61626    if( pBt->btsFlags & BTS_FAST_SECURE ){
 61627      memset(&data[hdr], 0, pBt->usableSize - hdr);
 61628    }
 61629    data[hdr] = (char)flags;
 61630    first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
 61631    memset(&data[hdr+1], 0, 4);
 61632    data[hdr+7] = 0;
 61633    put2byte(&data[hdr+5], pBt->usableSize);
 61634    pPage->nFree = (u16)(pBt->usableSize - first);
 61635    decodeFlags(pPage, flags);
 61636    pPage->cellOffset = first;
 61637    pPage->aDataEnd = &data[pBt->usableSize];
 61638    pPage->aCellIdx = &data[first];
 61639    pPage->aDataOfst = &data[pPage->childPtrSize];
 61640    pPage->nOverflow = 0;
 61641    assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
 61642    pPage->maskPage = (u16)(pBt->pageSize - 1);
 61643    pPage->nCell = 0;
 61644    pPage->isInit = 1;
 61645  }
 61646  
 61647  
 61648  /*
 61649  ** Convert a DbPage obtained from the pager into a MemPage used by
 61650  ** the btree layer.
 61651  */
 61652  static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
 61653    MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
 61654    if( pgno!=pPage->pgno ){
 61655      pPage->aData = sqlite3PagerGetData(pDbPage);
 61656      pPage->pDbPage = pDbPage;
 61657      pPage->pBt = pBt;
 61658      pPage->pgno = pgno;
 61659      pPage->hdrOffset = pgno==1 ? 100 : 0;
 61660    }
 61661    assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
 61662    return pPage; 
 61663  }
 61664  
 61665  /*
 61666  ** Get a page from the pager.  Initialize the MemPage.pBt and
 61667  ** MemPage.aData elements if needed.  See also: btreeGetUnusedPage().
 61668  **
 61669  ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
 61670  ** about the content of the page at this time.  So do not go to the disk
 61671  ** to fetch the content.  Just fill in the content with zeros for now.
 61672  ** If in the future we call sqlite3PagerWrite() on this page, that
 61673  ** means we have started to be concerned about content and the disk
 61674  ** read should occur at that point.
 61675  */
 61676  static int btreeGetPage(
 61677    BtShared *pBt,       /* The btree */
 61678    Pgno pgno,           /* Number of the page to fetch */
 61679    MemPage **ppPage,    /* Return the page in this parameter */
 61680    int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
 61681  ){
 61682    int rc;
 61683    DbPage *pDbPage;
 61684  
 61685    assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
 61686    assert( sqlite3_mutex_held(pBt->mutex) );
 61687    rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
 61688    if( rc ) return rc;
 61689    *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
 61690    return SQLITE_OK;
 61691  }
 61692  
 61693  /*
 61694  ** Retrieve a page from the pager cache. If the requested page is not
 61695  ** already in the pager cache return NULL. Initialize the MemPage.pBt and
 61696  ** MemPage.aData elements if needed.
 61697  */
 61698  static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
 61699    DbPage *pDbPage;
 61700    assert( sqlite3_mutex_held(pBt->mutex) );
 61701    pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
 61702    if( pDbPage ){
 61703      return btreePageFromDbPage(pDbPage, pgno, pBt);
 61704    }
 61705    return 0;
 61706  }
 61707  
 61708  /*
 61709  ** Return the size of the database file in pages. If there is any kind of
 61710  ** error, return ((unsigned int)-1).
 61711  */
 61712  static Pgno btreePagecount(BtShared *pBt){
 61713    return pBt->nPage;
 61714  }
 61715  SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
 61716    assert( sqlite3BtreeHoldsMutex(p) );
 61717    assert( ((p->pBt->nPage)&0x80000000)==0 );
 61718    return btreePagecount(p->pBt);
 61719  }
 61720  
 61721  /*
 61722  ** Get a page from the pager and initialize it.
 61723  **
 61724  ** If pCur!=0 then the page is being fetched as part of a moveToChild()
 61725  ** call.  Do additional sanity checking on the page in this case.
 61726  ** And if the fetch fails, this routine must decrement pCur->iPage.
 61727  **
 61728  ** The page is fetched as read-write unless pCur is not NULL and is
 61729  ** a read-only cursor.
 61730  **
 61731  ** If an error occurs, then *ppPage is undefined. It
 61732  ** may remain unchanged, or it may be set to an invalid value.
 61733  */
 61734  static int getAndInitPage(
 61735    BtShared *pBt,                  /* The database file */
 61736    Pgno pgno,                      /* Number of the page to get */
 61737    MemPage **ppPage,               /* Write the page pointer here */
 61738    BtCursor *pCur,                 /* Cursor to receive the page, or NULL */
 61739    int bReadOnly                   /* True for a read-only page */
 61740  ){
 61741    int rc;
 61742    DbPage *pDbPage;
 61743    assert( sqlite3_mutex_held(pBt->mutex) );
 61744    assert( pCur==0 || ppPage==&pCur->pPage );
 61745    assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
 61746    assert( pCur==0 || pCur->iPage>0 );
 61747  
 61748    if( pgno>btreePagecount(pBt) ){
 61749      rc = SQLITE_CORRUPT_BKPT;
 61750      goto getAndInitPage_error;
 61751    }
 61752    rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
 61753    if( rc ){
 61754      goto getAndInitPage_error;
 61755    }
 61756    *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
 61757    if( (*ppPage)->isInit==0 ){
 61758      btreePageFromDbPage(pDbPage, pgno, pBt);
 61759      rc = btreeInitPage(*ppPage);
 61760      if( rc!=SQLITE_OK ){
 61761        releasePage(*ppPage);
 61762        goto getAndInitPage_error;
 61763      }
 61764    }
 61765    assert( (*ppPage)->pgno==pgno );
 61766    assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
 61767  
 61768    /* If obtaining a child page for a cursor, we must verify that the page is
 61769    ** compatible with the root page. */
 61770    if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
 61771      rc = SQLITE_CORRUPT_PGNO(pgno);
 61772      releasePage(*ppPage);
 61773      goto getAndInitPage_error;
 61774    }
 61775    return SQLITE_OK;
 61776  
 61777  getAndInitPage_error:
 61778    if( pCur ){
 61779      pCur->iPage--;
 61780      pCur->pPage = pCur->apPage[pCur->iPage];
 61781    }
 61782    testcase( pgno==0 );
 61783    assert( pgno!=0 || rc==SQLITE_CORRUPT );
 61784    return rc;
 61785  }
 61786  
 61787  /*
 61788  ** Release a MemPage.  This should be called once for each prior
 61789  ** call to btreeGetPage.
 61790  **
 61791  ** Page1 is a special case and must be released using releasePageOne().
 61792  */
 61793  static void releasePageNotNull(MemPage *pPage){
 61794    assert( pPage->aData );
 61795    assert( pPage->pBt );
 61796    assert( pPage->pDbPage!=0 );
 61797    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
 61798    assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
 61799    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 61800    sqlite3PagerUnrefNotNull(pPage->pDbPage);
 61801  }
 61802  static void releasePage(MemPage *pPage){
 61803    if( pPage ) releasePageNotNull(pPage);
 61804  }
 61805  static void releasePageOne(MemPage *pPage){
 61806    assert( pPage!=0 );
 61807    assert( pPage->aData );
 61808    assert( pPage->pBt );
 61809    assert( pPage->pDbPage!=0 );
 61810    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
 61811    assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
 61812    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 61813    sqlite3PagerUnrefPageOne(pPage->pDbPage);
 61814  }
 61815  
 61816  /*
 61817  ** Get an unused page.
 61818  **
 61819  ** This works just like btreeGetPage() with the addition:
 61820  **
 61821  **   *  If the page is already in use for some other purpose, immediately
 61822  **      release it and return an SQLITE_CURRUPT error.
 61823  **   *  Make sure the isInit flag is clear
 61824  */
 61825  static int btreeGetUnusedPage(
 61826    BtShared *pBt,       /* The btree */
 61827    Pgno pgno,           /* Number of the page to fetch */
 61828    MemPage **ppPage,    /* Return the page in this parameter */
 61829    int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
 61830  ){
 61831    int rc = btreeGetPage(pBt, pgno, ppPage, flags);
 61832    if( rc==SQLITE_OK ){
 61833      if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
 61834        releasePage(*ppPage);
 61835        *ppPage = 0;
 61836        return SQLITE_CORRUPT_BKPT;
 61837      }
 61838      (*ppPage)->isInit = 0;
 61839    }else{
 61840      *ppPage = 0;
 61841    }
 61842    return rc;
 61843  }
 61844  
 61845  
 61846  /*
 61847  ** During a rollback, when the pager reloads information into the cache
 61848  ** so that the cache is restored to its original state at the start of
 61849  ** the transaction, for each page restored this routine is called.
 61850  **
 61851  ** This routine needs to reset the extra data section at the end of the
 61852  ** page to agree with the restored data.
 61853  */
 61854  static void pageReinit(DbPage *pData){
 61855    MemPage *pPage;
 61856    pPage = (MemPage *)sqlite3PagerGetExtra(pData);
 61857    assert( sqlite3PagerPageRefcount(pData)>0 );
 61858    if( pPage->isInit ){
 61859      assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 61860      pPage->isInit = 0;
 61861      if( sqlite3PagerPageRefcount(pData)>1 ){
 61862        /* pPage might not be a btree page;  it might be an overflow page
 61863        ** or ptrmap page or a free page.  In those cases, the following
 61864        ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
 61865        ** But no harm is done by this.  And it is very important that
 61866        ** btreeInitPage() be called on every btree page so we make
 61867        ** the call for every page that comes in for re-initing. */
 61868        btreeInitPage(pPage);
 61869      }
 61870    }
 61871  }
 61872  
 61873  /*
 61874  ** Invoke the busy handler for a btree.
 61875  */
 61876  static int btreeInvokeBusyHandler(void *pArg){
 61877    BtShared *pBt = (BtShared*)pArg;
 61878    assert( pBt->db );
 61879    assert( sqlite3_mutex_held(pBt->db->mutex) );
 61880    return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
 61881  }
 61882  
 61883  /*
 61884  ** Open a database file.
 61885  ** 
 61886  ** zFilename is the name of the database file.  If zFilename is NULL
 61887  ** then an ephemeral database is created.  The ephemeral database might
 61888  ** be exclusively in memory, or it might use a disk-based memory cache.
 61889  ** Either way, the ephemeral database will be automatically deleted 
 61890  ** when sqlite3BtreeClose() is called.
 61891  **
 61892  ** If zFilename is ":memory:" then an in-memory database is created
 61893  ** that is automatically destroyed when it is closed.
 61894  **
 61895  ** The "flags" parameter is a bitmask that might contain bits like
 61896  ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
 61897  **
 61898  ** If the database is already opened in the same database connection
 61899  ** and we are in shared cache mode, then the open will fail with an
 61900  ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
 61901  ** objects in the same database connection since doing so will lead
 61902  ** to problems with locking.
 61903  */
 61904  SQLITE_PRIVATE int sqlite3BtreeOpen(
 61905    sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
 61906    const char *zFilename,  /* Name of the file containing the BTree database */
 61907    sqlite3 *db,            /* Associated database handle */
 61908    Btree **ppBtree,        /* Pointer to new Btree object written here */
 61909    int flags,              /* Options */
 61910    int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
 61911  ){
 61912    BtShared *pBt = 0;             /* Shared part of btree structure */
 61913    Btree *p;                      /* Handle to return */
 61914    sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
 61915    int rc = SQLITE_OK;            /* Result code from this function */
 61916    u8 nReserve;                   /* Byte of unused space on each page */
 61917    unsigned char zDbHeader[100];  /* Database header content */
 61918  
 61919    /* True if opening an ephemeral, temporary database */
 61920    const int isTempDb = zFilename==0 || zFilename[0]==0;
 61921  
 61922    /* Set the variable isMemdb to true for an in-memory database, or 
 61923    ** false for a file-based database.
 61924    */
 61925  #ifdef SQLITE_OMIT_MEMORYDB
 61926    const int isMemdb = 0;
 61927  #else
 61928    const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
 61929                         || (isTempDb && sqlite3TempInMemory(db))
 61930                         || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
 61931  #endif
 61932  
 61933    assert( db!=0 );
 61934    assert( pVfs!=0 );
 61935    assert( sqlite3_mutex_held(db->mutex) );
 61936    assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
 61937  
 61938    /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
 61939    assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
 61940  
 61941    /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
 61942    assert( (flags & BTREE_SINGLE)==0 || isTempDb );
 61943  
 61944    if( isMemdb ){
 61945      flags |= BTREE_MEMORY;
 61946    }
 61947    if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
 61948      vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
 61949    }
 61950    p = sqlite3MallocZero(sizeof(Btree));
 61951    if( !p ){
 61952      return SQLITE_NOMEM_BKPT;
 61953    }
 61954    p->inTrans = TRANS_NONE;
 61955    p->db = db;
 61956  #ifndef SQLITE_OMIT_SHARED_CACHE
 61957    p->lock.pBtree = p;
 61958    p->lock.iTable = 1;
 61959  #endif
 61960  
 61961  #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
 61962    /*
 61963    ** If this Btree is a candidate for shared cache, try to find an
 61964    ** existing BtShared object that we can share with
 61965    */
 61966    if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
 61967      if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
 61968        int nFilename = sqlite3Strlen30(zFilename)+1;
 61969        int nFullPathname = pVfs->mxPathname+1;
 61970        char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
 61971        MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
 61972  
 61973        p->sharable = 1;
 61974        if( !zFullPathname ){
 61975          sqlite3_free(p);
 61976          return SQLITE_NOMEM_BKPT;
 61977        }
 61978        if( isMemdb ){
 61979          memcpy(zFullPathname, zFilename, nFilename);
 61980        }else{
 61981          rc = sqlite3OsFullPathname(pVfs, zFilename,
 61982                                     nFullPathname, zFullPathname);
 61983          if( rc ){
 61984            sqlite3_free(zFullPathname);
 61985            sqlite3_free(p);
 61986            return rc;
 61987          }
 61988        }
 61989  #if SQLITE_THREADSAFE
 61990        mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
 61991        sqlite3_mutex_enter(mutexOpen);
 61992        mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
 61993        sqlite3_mutex_enter(mutexShared);
 61994  #endif
 61995        for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
 61996          assert( pBt->nRef>0 );
 61997          if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
 61998                   && sqlite3PagerVfs(pBt->pPager)==pVfs ){
 61999            int iDb;
 62000            for(iDb=db->nDb-1; iDb>=0; iDb--){
 62001              Btree *pExisting = db->aDb[iDb].pBt;
 62002              if( pExisting && pExisting->pBt==pBt ){
 62003                sqlite3_mutex_leave(mutexShared);
 62004                sqlite3_mutex_leave(mutexOpen);
 62005                sqlite3_free(zFullPathname);
 62006                sqlite3_free(p);
 62007                return SQLITE_CONSTRAINT;
 62008              }
 62009            }
 62010            p->pBt = pBt;
 62011            pBt->nRef++;
 62012            break;
 62013          }
 62014        }
 62015        sqlite3_mutex_leave(mutexShared);
 62016        sqlite3_free(zFullPathname);
 62017      }
 62018  #ifdef SQLITE_DEBUG
 62019      else{
 62020        /* In debug mode, we mark all persistent databases as sharable
 62021        ** even when they are not.  This exercises the locking code and
 62022        ** gives more opportunity for asserts(sqlite3_mutex_held())
 62023        ** statements to find locking problems.
 62024        */
 62025        p->sharable = 1;
 62026      }
 62027  #endif
 62028    }
 62029  #endif
 62030    if( pBt==0 ){
 62031      /*
 62032      ** The following asserts make sure that structures used by the btree are
 62033      ** the right size.  This is to guard against size changes that result
 62034      ** when compiling on a different architecture.
 62035      */
 62036      assert( sizeof(i64)==8 );
 62037      assert( sizeof(u64)==8 );
 62038      assert( sizeof(u32)==4 );
 62039      assert( sizeof(u16)==2 );
 62040      assert( sizeof(Pgno)==4 );
 62041    
 62042      pBt = sqlite3MallocZero( sizeof(*pBt) );
 62043      if( pBt==0 ){
 62044        rc = SQLITE_NOMEM_BKPT;
 62045        goto btree_open_out;
 62046      }
 62047      rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
 62048                            sizeof(MemPage), flags, vfsFlags, pageReinit);
 62049      if( rc==SQLITE_OK ){
 62050        sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
 62051        rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
 62052      }
 62053      if( rc!=SQLITE_OK ){
 62054        goto btree_open_out;
 62055      }
 62056      pBt->openFlags = (u8)flags;
 62057      pBt->db = db;
 62058      sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
 62059      p->pBt = pBt;
 62060    
 62061      pBt->pCursor = 0;
 62062      pBt->pPage1 = 0;
 62063      if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
 62064  #if defined(SQLITE_SECURE_DELETE)
 62065      pBt->btsFlags |= BTS_SECURE_DELETE;
 62066  #elif defined(SQLITE_FAST_SECURE_DELETE)
 62067      pBt->btsFlags |= BTS_OVERWRITE;
 62068  #endif
 62069      /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
 62070      ** determined by the 2-byte integer located at an offset of 16 bytes from
 62071      ** the beginning of the database file. */
 62072      pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
 62073      if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
 62074           || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
 62075        pBt->pageSize = 0;
 62076  #ifndef SQLITE_OMIT_AUTOVACUUM
 62077        /* If the magic name ":memory:" will create an in-memory database, then
 62078        ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
 62079        ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
 62080        ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
 62081        ** regular file-name. In this case the auto-vacuum applies as per normal.
 62082        */
 62083        if( zFilename && !isMemdb ){
 62084          pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
 62085          pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
 62086        }
 62087  #endif
 62088        nReserve = 0;
 62089      }else{
 62090        /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
 62091        ** determined by the one-byte unsigned integer found at an offset of 20
 62092        ** into the database file header. */
 62093        nReserve = zDbHeader[20];
 62094        pBt->btsFlags |= BTS_PAGESIZE_FIXED;
 62095  #ifndef SQLITE_OMIT_AUTOVACUUM
 62096        pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
 62097        pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
 62098  #endif
 62099      }
 62100      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
 62101      if( rc ) goto btree_open_out;
 62102      pBt->usableSize = pBt->pageSize - nReserve;
 62103      assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
 62104     
 62105  #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
 62106      /* Add the new BtShared object to the linked list sharable BtShareds.
 62107      */
 62108      pBt->nRef = 1;
 62109      if( p->sharable ){
 62110        MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
 62111        MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
 62112        if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
 62113          pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
 62114          if( pBt->mutex==0 ){
 62115            rc = SQLITE_NOMEM_BKPT;
 62116            goto btree_open_out;
 62117          }
 62118        }
 62119        sqlite3_mutex_enter(mutexShared);
 62120        pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
 62121        GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
 62122        sqlite3_mutex_leave(mutexShared);
 62123      }
 62124  #endif
 62125    }
 62126  
 62127  #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
 62128    /* If the new Btree uses a sharable pBtShared, then link the new
 62129    ** Btree into the list of all sharable Btrees for the same connection.
 62130    ** The list is kept in ascending order by pBt address.
 62131    */
 62132    if( p->sharable ){
 62133      int i;
 62134      Btree *pSib;
 62135      for(i=0; i<db->nDb; i++){
 62136        if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
 62137          while( pSib->pPrev ){ pSib = pSib->pPrev; }
 62138          if( (uptr)p->pBt<(uptr)pSib->pBt ){
 62139            p->pNext = pSib;
 62140            p->pPrev = 0;
 62141            pSib->pPrev = p;
 62142          }else{
 62143            while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
 62144              pSib = pSib->pNext;
 62145            }
 62146            p->pNext = pSib->pNext;
 62147            p->pPrev = pSib;
 62148            if( p->pNext ){
 62149              p->pNext->pPrev = p;
 62150            }
 62151            pSib->pNext = p;
 62152          }
 62153          break;
 62154        }
 62155      }
 62156    }
 62157  #endif
 62158    *ppBtree = p;
 62159  
 62160  btree_open_out:
 62161    if( rc!=SQLITE_OK ){
 62162      if( pBt && pBt->pPager ){
 62163        sqlite3PagerClose(pBt->pPager, 0);
 62164      }
 62165      sqlite3_free(pBt);
 62166      sqlite3_free(p);
 62167      *ppBtree = 0;
 62168    }else{
 62169      sqlite3_file *pFile;
 62170  
 62171      /* If the B-Tree was successfully opened, set the pager-cache size to the
 62172      ** default value. Except, when opening on an existing shared pager-cache,
 62173      ** do not change the pager-cache size.
 62174      */
 62175      if( sqlite3BtreeSchema(p, 0, 0)==0 ){
 62176        sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
 62177      }
 62178  
 62179      pFile = sqlite3PagerFile(pBt->pPager);
 62180      if( pFile->pMethods ){
 62181        sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
 62182      }
 62183    }
 62184    if( mutexOpen ){
 62185      assert( sqlite3_mutex_held(mutexOpen) );
 62186      sqlite3_mutex_leave(mutexOpen);
 62187    }
 62188    assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
 62189    return rc;
 62190  }
 62191  
 62192  /*
 62193  ** Decrement the BtShared.nRef counter.  When it reaches zero,
 62194  ** remove the BtShared structure from the sharing list.  Return
 62195  ** true if the BtShared.nRef counter reaches zero and return
 62196  ** false if it is still positive.
 62197  */
 62198  static int removeFromSharingList(BtShared *pBt){
 62199  #ifndef SQLITE_OMIT_SHARED_CACHE
 62200    MUTEX_LOGIC( sqlite3_mutex *pMaster; )
 62201    BtShared *pList;
 62202    int removed = 0;
 62203  
 62204    assert( sqlite3_mutex_notheld(pBt->mutex) );
 62205    MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
 62206    sqlite3_mutex_enter(pMaster);
 62207    pBt->nRef--;
 62208    if( pBt->nRef<=0 ){
 62209      if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
 62210        GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
 62211      }else{
 62212        pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
 62213        while( ALWAYS(pList) && pList->pNext!=pBt ){
 62214          pList=pList->pNext;
 62215        }
 62216        if( ALWAYS(pList) ){
 62217          pList->pNext = pBt->pNext;
 62218        }
 62219      }
 62220      if( SQLITE_THREADSAFE ){
 62221        sqlite3_mutex_free(pBt->mutex);
 62222      }
 62223      removed = 1;
 62224    }
 62225    sqlite3_mutex_leave(pMaster);
 62226    return removed;
 62227  #else
 62228    return 1;
 62229  #endif
 62230  }
 62231  
 62232  /*
 62233  ** Make sure pBt->pTmpSpace points to an allocation of 
 62234  ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
 62235  ** pointer.
 62236  */
 62237  static void allocateTempSpace(BtShared *pBt){
 62238    if( !pBt->pTmpSpace ){
 62239      pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
 62240  
 62241      /* One of the uses of pBt->pTmpSpace is to format cells before
 62242      ** inserting them into a leaf page (function fillInCell()). If
 62243      ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
 62244      ** by the various routines that manipulate binary cells. Which
 62245      ** can mean that fillInCell() only initializes the first 2 or 3
 62246      ** bytes of pTmpSpace, but that the first 4 bytes are copied from
 62247      ** it into a database page. This is not actually a problem, but it
 62248      ** does cause a valgrind error when the 1 or 2 bytes of unitialized 
 62249      ** data is passed to system call write(). So to avoid this error,
 62250      ** zero the first 4 bytes of temp space here.
 62251      **
 62252      ** Also:  Provide four bytes of initialized space before the
 62253      ** beginning of pTmpSpace as an area available to prepend the
 62254      ** left-child pointer to the beginning of a cell.
 62255      */
 62256      if( pBt->pTmpSpace ){
 62257        memset(pBt->pTmpSpace, 0, 8);
 62258        pBt->pTmpSpace += 4;
 62259      }
 62260    }
 62261  }
 62262  
 62263  /*
 62264  ** Free the pBt->pTmpSpace allocation
 62265  */
 62266  static void freeTempSpace(BtShared *pBt){
 62267    if( pBt->pTmpSpace ){
 62268      pBt->pTmpSpace -= 4;
 62269      sqlite3PageFree(pBt->pTmpSpace);
 62270      pBt->pTmpSpace = 0;
 62271    }
 62272  }
 62273  
 62274  /*
 62275  ** Close an open database and invalidate all cursors.
 62276  */
 62277  SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
 62278    BtShared *pBt = p->pBt;
 62279    BtCursor *pCur;
 62280  
 62281    /* Close all cursors opened via this handle.  */
 62282    assert( sqlite3_mutex_held(p->db->mutex) );
 62283    sqlite3BtreeEnter(p);
 62284    pCur = pBt->pCursor;
 62285    while( pCur ){
 62286      BtCursor *pTmp = pCur;
 62287      pCur = pCur->pNext;
 62288      if( pTmp->pBtree==p ){
 62289        sqlite3BtreeCloseCursor(pTmp);
 62290      }
 62291    }
 62292  
 62293    /* Rollback any active transaction and free the handle structure.
 62294    ** The call to sqlite3BtreeRollback() drops any table-locks held by
 62295    ** this handle.
 62296    */
 62297    sqlite3BtreeRollback(p, SQLITE_OK, 0);
 62298    sqlite3BtreeLeave(p);
 62299  
 62300    /* If there are still other outstanding references to the shared-btree
 62301    ** structure, return now. The remainder of this procedure cleans 
 62302    ** up the shared-btree.
 62303    */
 62304    assert( p->wantToLock==0 && p->locked==0 );
 62305    if( !p->sharable || removeFromSharingList(pBt) ){
 62306      /* The pBt is no longer on the sharing list, so we can access
 62307      ** it without having to hold the mutex.
 62308      **
 62309      ** Clean out and delete the BtShared object.
 62310      */
 62311      assert( !pBt->pCursor );
 62312      sqlite3PagerClose(pBt->pPager, p->db);
 62313      if( pBt->xFreeSchema && pBt->pSchema ){
 62314        pBt->xFreeSchema(pBt->pSchema);
 62315      }
 62316      sqlite3DbFree(0, pBt->pSchema);
 62317      freeTempSpace(pBt);
 62318      sqlite3_free(pBt);
 62319    }
 62320  
 62321  #ifndef SQLITE_OMIT_SHARED_CACHE
 62322    assert( p->wantToLock==0 );
 62323    assert( p->locked==0 );
 62324    if( p->pPrev ) p->pPrev->pNext = p->pNext;
 62325    if( p->pNext ) p->pNext->pPrev = p->pPrev;
 62326  #endif
 62327  
 62328    sqlite3_free(p);
 62329    return SQLITE_OK;
 62330  }
 62331  
 62332  /*
 62333  ** Change the "soft" limit on the number of pages in the cache.
 62334  ** Unused and unmodified pages will be recycled when the number of
 62335  ** pages in the cache exceeds this soft limit.  But the size of the
 62336  ** cache is allowed to grow larger than this limit if it contains
 62337  ** dirty pages or pages still in active use.
 62338  */
 62339  SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
 62340    BtShared *pBt = p->pBt;
 62341    assert( sqlite3_mutex_held(p->db->mutex) );
 62342    sqlite3BtreeEnter(p);
 62343    sqlite3PagerSetCachesize(pBt->pPager, mxPage);
 62344    sqlite3BtreeLeave(p);
 62345    return SQLITE_OK;
 62346  }
 62347  
 62348  /*
 62349  ** Change the "spill" limit on the number of pages in the cache.
 62350  ** If the number of pages exceeds this limit during a write transaction,
 62351  ** the pager might attempt to "spill" pages to the journal early in
 62352  ** order to free up memory.
 62353  **
 62354  ** The value returned is the current spill size.  If zero is passed
 62355  ** as an argument, no changes are made to the spill size setting, so
 62356  ** using mxPage of 0 is a way to query the current spill size.
 62357  */
 62358  SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
 62359    BtShared *pBt = p->pBt;
 62360    int res;
 62361    assert( sqlite3_mutex_held(p->db->mutex) );
 62362    sqlite3BtreeEnter(p);
 62363    res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
 62364    sqlite3BtreeLeave(p);
 62365    return res;
 62366  }
 62367  
 62368  #if SQLITE_MAX_MMAP_SIZE>0
 62369  /*
 62370  ** Change the limit on the amount of the database file that may be
 62371  ** memory mapped.
 62372  */
 62373  SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
 62374    BtShared *pBt = p->pBt;
 62375    assert( sqlite3_mutex_held(p->db->mutex) );
 62376    sqlite3BtreeEnter(p);
 62377    sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
 62378    sqlite3BtreeLeave(p);
 62379    return SQLITE_OK;
 62380  }
 62381  #endif /* SQLITE_MAX_MMAP_SIZE>0 */
 62382  
 62383  /*
 62384  ** Change the way data is synced to disk in order to increase or decrease
 62385  ** how well the database resists damage due to OS crashes and power
 62386  ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
 62387  ** there is a high probability of damage)  Level 2 is the default.  There
 62388  ** is a very low but non-zero probability of damage.  Level 3 reduces the
 62389  ** probability of damage to near zero but with a write performance reduction.
 62390  */
 62391  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
 62392  SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
 62393    Btree *p,              /* The btree to set the safety level on */
 62394    unsigned pgFlags       /* Various PAGER_* flags */
 62395  ){
 62396    BtShared *pBt = p->pBt;
 62397    assert( sqlite3_mutex_held(p->db->mutex) );
 62398    sqlite3BtreeEnter(p);
 62399    sqlite3PagerSetFlags(pBt->pPager, pgFlags);
 62400    sqlite3BtreeLeave(p);
 62401    return SQLITE_OK;
 62402  }
 62403  #endif
 62404  
 62405  /*
 62406  ** Change the default pages size and the number of reserved bytes per page.
 62407  ** Or, if the page size has already been fixed, return SQLITE_READONLY 
 62408  ** without changing anything.
 62409  **
 62410  ** The page size must be a power of 2 between 512 and 65536.  If the page
 62411  ** size supplied does not meet this constraint then the page size is not
 62412  ** changed.
 62413  **
 62414  ** Page sizes are constrained to be a power of two so that the region
 62415  ** of the database file used for locking (beginning at PENDING_BYTE,
 62416  ** the first byte past the 1GB boundary, 0x40000000) needs to occur
 62417  ** at the beginning of a page.
 62418  **
 62419  ** If parameter nReserve is less than zero, then the number of reserved
 62420  ** bytes per page is left unchanged.
 62421  **
 62422  ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
 62423  ** and autovacuum mode can no longer be changed.
 62424  */
 62425  SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
 62426    int rc = SQLITE_OK;
 62427    BtShared *pBt = p->pBt;
 62428    assert( nReserve>=-1 && nReserve<=255 );
 62429    sqlite3BtreeEnter(p);
 62430  #if SQLITE_HAS_CODEC
 62431    if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
 62432  #endif
 62433    if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
 62434      sqlite3BtreeLeave(p);
 62435      return SQLITE_READONLY;
 62436    }
 62437    if( nReserve<0 ){
 62438      nReserve = pBt->pageSize - pBt->usableSize;
 62439    }
 62440    assert( nReserve>=0 && nReserve<=255 );
 62441    if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
 62442          ((pageSize-1)&pageSize)==0 ){
 62443      assert( (pageSize & 7)==0 );
 62444      assert( !pBt->pCursor );
 62445      pBt->pageSize = (u32)pageSize;
 62446      freeTempSpace(pBt);
 62447    }
 62448    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
 62449    pBt->usableSize = pBt->pageSize - (u16)nReserve;
 62450    if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
 62451    sqlite3BtreeLeave(p);
 62452    return rc;
 62453  }
 62454  
 62455  /*
 62456  ** Return the currently defined page size
 62457  */
 62458  SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
 62459    return p->pBt->pageSize;
 62460  }
 62461  
 62462  /*
 62463  ** This function is similar to sqlite3BtreeGetReserve(), except that it
 62464  ** may only be called if it is guaranteed that the b-tree mutex is already
 62465  ** held.
 62466  **
 62467  ** This is useful in one special case in the backup API code where it is
 62468  ** known that the shared b-tree mutex is held, but the mutex on the 
 62469  ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
 62470  ** were to be called, it might collide with some other operation on the
 62471  ** database handle that owns *p, causing undefined behavior.
 62472  */
 62473  SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
 62474    int n;
 62475    assert( sqlite3_mutex_held(p->pBt->mutex) );
 62476    n = p->pBt->pageSize - p->pBt->usableSize;
 62477    return n;
 62478  }
 62479  
 62480  /*
 62481  ** Return the number of bytes of space at the end of every page that
 62482  ** are intentually left unused.  This is the "reserved" space that is
 62483  ** sometimes used by extensions.
 62484  **
 62485  ** If SQLITE_HAS_MUTEX is defined then the number returned is the
 62486  ** greater of the current reserved space and the maximum requested
 62487  ** reserve space.
 62488  */
 62489  SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
 62490    int n;
 62491    sqlite3BtreeEnter(p);
 62492    n = sqlite3BtreeGetReserveNoMutex(p);
 62493  #ifdef SQLITE_HAS_CODEC
 62494    if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
 62495  #endif
 62496    sqlite3BtreeLeave(p);
 62497    return n;
 62498  }
 62499  
 62500  
 62501  /*
 62502  ** Set the maximum page count for a database if mxPage is positive.
 62503  ** No changes are made if mxPage is 0 or negative.
 62504  ** Regardless of the value of mxPage, return the maximum page count.
 62505  */
 62506  SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
 62507    int n;
 62508    sqlite3BtreeEnter(p);
 62509    n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
 62510    sqlite3BtreeLeave(p);
 62511    return n;
 62512  }
 62513  
 62514  /*
 62515  ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
 62516  **
 62517  **    newFlag==0       Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
 62518  **    newFlag==1       BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
 62519  **    newFlag==2       BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
 62520  **    newFlag==(-1)    No changes
 62521  **
 62522  ** This routine acts as a query if newFlag is less than zero
 62523  **
 62524  ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
 62525  ** freelist leaf pages are not written back to the database.  Thus in-page
 62526  ** deleted content is cleared, but freelist deleted content is not.
 62527  **
 62528  ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
 62529  ** that freelist leaf pages are written back into the database, increasing
 62530  ** the amount of disk I/O.
 62531  */
 62532  SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
 62533    int b;
 62534    if( p==0 ) return 0;
 62535    sqlite3BtreeEnter(p);
 62536    assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
 62537    assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
 62538    if( newFlag>=0 ){
 62539      p->pBt->btsFlags &= ~BTS_FAST_SECURE;
 62540      p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
 62541    }
 62542    b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
 62543    sqlite3BtreeLeave(p);
 62544    return b;
 62545  }
 62546  
 62547  /*
 62548  ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
 62549  ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
 62550  ** is disabled. The default value for the auto-vacuum property is 
 62551  ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
 62552  */
 62553  SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
 62554  #ifdef SQLITE_OMIT_AUTOVACUUM
 62555    return SQLITE_READONLY;
 62556  #else
 62557    BtShared *pBt = p->pBt;
 62558    int rc = SQLITE_OK;
 62559    u8 av = (u8)autoVacuum;
 62560  
 62561    sqlite3BtreeEnter(p);
 62562    if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
 62563      rc = SQLITE_READONLY;
 62564    }else{
 62565      pBt->autoVacuum = av ?1:0;
 62566      pBt->incrVacuum = av==2 ?1:0;
 62567    }
 62568    sqlite3BtreeLeave(p);
 62569    return rc;
 62570  #endif
 62571  }
 62572  
 62573  /*
 62574  ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
 62575  ** enabled 1 is returned. Otherwise 0.
 62576  */
 62577  SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
 62578  #ifdef SQLITE_OMIT_AUTOVACUUM
 62579    return BTREE_AUTOVACUUM_NONE;
 62580  #else
 62581    int rc;
 62582    sqlite3BtreeEnter(p);
 62583    rc = (
 62584      (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
 62585      (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
 62586      BTREE_AUTOVACUUM_INCR
 62587    );
 62588    sqlite3BtreeLeave(p);
 62589    return rc;
 62590  #endif
 62591  }
 62592  
 62593  /*
 62594  ** If the user has not set the safety-level for this database connection
 62595  ** using "PRAGMA synchronous", and if the safety-level is not already
 62596  ** set to the value passed to this function as the second parameter,
 62597  ** set it so.
 62598  */
 62599  #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
 62600      && !defined(SQLITE_OMIT_WAL)
 62601  static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
 62602    sqlite3 *db;
 62603    Db *pDb;
 62604    if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
 62605      while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
 62606      if( pDb->bSyncSet==0 
 62607       && pDb->safety_level!=safety_level 
 62608       && pDb!=&db->aDb[1] 
 62609      ){
 62610        pDb->safety_level = safety_level;
 62611        sqlite3PagerSetFlags(pBt->pPager,
 62612            pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
 62613      }
 62614    }
 62615  }
 62616  #else
 62617  # define setDefaultSyncFlag(pBt,safety_level)
 62618  #endif
 62619  
 62620  /*
 62621  ** Get a reference to pPage1 of the database file.  This will
 62622  ** also acquire a readlock on that file.
 62623  **
 62624  ** SQLITE_OK is returned on success.  If the file is not a
 62625  ** well-formed database file, then SQLITE_CORRUPT is returned.
 62626  ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
 62627  ** is returned if we run out of memory. 
 62628  */
 62629  static int lockBtree(BtShared *pBt){
 62630    int rc;              /* Result code from subfunctions */
 62631    MemPage *pPage1;     /* Page 1 of the database file */
 62632    int nPage;           /* Number of pages in the database */
 62633    int nPageFile = 0;   /* Number of pages in the database file */
 62634    int nPageHeader;     /* Number of pages in the database according to hdr */
 62635  
 62636    assert( sqlite3_mutex_held(pBt->mutex) );
 62637    assert( pBt->pPage1==0 );
 62638    rc = sqlite3PagerSharedLock(pBt->pPager);
 62639    if( rc!=SQLITE_OK ) return rc;
 62640    rc = btreeGetPage(pBt, 1, &pPage1, 0);
 62641    if( rc!=SQLITE_OK ) return rc;
 62642  
 62643    /* Do some checking to help insure the file we opened really is
 62644    ** a valid database file. 
 62645    */
 62646    nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
 62647    sqlite3PagerPagecount(pBt->pPager, &nPageFile);
 62648    if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
 62649      nPage = nPageFile;
 62650    }
 62651    if( nPage>0 ){
 62652      u32 pageSize;
 62653      u32 usableSize;
 62654      u8 *page1 = pPage1->aData;
 62655      rc = SQLITE_NOTADB;
 62656      /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
 62657      ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
 62658      ** 61 74 20 33 00. */
 62659      if( memcmp(page1, zMagicHeader, 16)!=0 ){
 62660        goto page1_init_failed;
 62661      }
 62662  
 62663  #ifdef SQLITE_OMIT_WAL
 62664      if( page1[18]>1 ){
 62665        pBt->btsFlags |= BTS_READ_ONLY;
 62666      }
 62667      if( page1[19]>1 ){
 62668        goto page1_init_failed;
 62669      }
 62670  #else
 62671      if( page1[18]>2 ){
 62672        pBt->btsFlags |= BTS_READ_ONLY;
 62673      }
 62674      if( page1[19]>2 ){
 62675        goto page1_init_failed;
 62676      }
 62677  
 62678      /* If the write version is set to 2, this database should be accessed
 62679      ** in WAL mode. If the log is not already open, open it now. Then 
 62680      ** return SQLITE_OK and return without populating BtShared.pPage1.
 62681      ** The caller detects this and calls this function again. This is
 62682      ** required as the version of page 1 currently in the page1 buffer
 62683      ** may not be the latest version - there may be a newer one in the log
 62684      ** file.
 62685      */
 62686      if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
 62687        int isOpen = 0;
 62688        rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
 62689        if( rc!=SQLITE_OK ){
 62690          goto page1_init_failed;
 62691        }else{
 62692          setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
 62693          if( isOpen==0 ){
 62694            releasePageOne(pPage1);
 62695            return SQLITE_OK;
 62696          }
 62697        }
 62698        rc = SQLITE_NOTADB;
 62699      }else{
 62700        setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
 62701      }
 62702  #endif
 62703  
 62704      /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
 62705      ** fractions and the leaf payload fraction values must be 64, 32, and 32.
 62706      **
 62707      ** The original design allowed these amounts to vary, but as of
 62708      ** version 3.6.0, we require them to be fixed.
 62709      */
 62710      if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
 62711        goto page1_init_failed;
 62712      }
 62713      /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
 62714      ** determined by the 2-byte integer located at an offset of 16 bytes from
 62715      ** the beginning of the database file. */
 62716      pageSize = (page1[16]<<8) | (page1[17]<<16);
 62717      /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
 62718      ** between 512 and 65536 inclusive. */
 62719      if( ((pageSize-1)&pageSize)!=0
 62720       || pageSize>SQLITE_MAX_PAGE_SIZE 
 62721       || pageSize<=256 
 62722      ){
 62723        goto page1_init_failed;
 62724      }
 62725      assert( (pageSize & 7)==0 );
 62726      /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
 62727      ** integer at offset 20 is the number of bytes of space at the end of
 62728      ** each page to reserve for extensions. 
 62729      **
 62730      ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
 62731      ** determined by the one-byte unsigned integer found at an offset of 20
 62732      ** into the database file header. */
 62733      usableSize = pageSize - page1[20];
 62734      if( (u32)pageSize!=pBt->pageSize ){
 62735        /* After reading the first page of the database assuming a page size
 62736        ** of BtShared.pageSize, we have discovered that the page-size is
 62737        ** actually pageSize. Unlock the database, leave pBt->pPage1 at
 62738        ** zero and return SQLITE_OK. The caller will call this function
 62739        ** again with the correct page-size.
 62740        */
 62741        releasePageOne(pPage1);
 62742        pBt->usableSize = usableSize;
 62743        pBt->pageSize = pageSize;
 62744        freeTempSpace(pBt);
 62745        rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
 62746                                     pageSize-usableSize);
 62747        return rc;
 62748      }
 62749      if( (pBt->db->flags & SQLITE_WriteSchema)==0 && nPage>nPageFile ){
 62750        rc = SQLITE_CORRUPT_BKPT;
 62751        goto page1_init_failed;
 62752      }
 62753      /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
 62754      ** be less than 480. In other words, if the page size is 512, then the
 62755      ** reserved space size cannot exceed 32. */
 62756      if( usableSize<480 ){
 62757        goto page1_init_failed;
 62758      }
 62759      pBt->pageSize = pageSize;
 62760      pBt->usableSize = usableSize;
 62761  #ifndef SQLITE_OMIT_AUTOVACUUM
 62762      pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
 62763      pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
 62764  #endif
 62765    }
 62766  
 62767    /* maxLocal is the maximum amount of payload to store locally for
 62768    ** a cell.  Make sure it is small enough so that at least minFanout
 62769    ** cells can will fit on one page.  We assume a 10-byte page header.
 62770    ** Besides the payload, the cell must store:
 62771    **     2-byte pointer to the cell
 62772    **     4-byte child pointer
 62773    **     9-byte nKey value
 62774    **     4-byte nData value
 62775    **     4-byte overflow page pointer
 62776    ** So a cell consists of a 2-byte pointer, a header which is as much as
 62777    ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
 62778    ** page pointer.
 62779    */
 62780    pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
 62781    pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
 62782    pBt->maxLeaf = (u16)(pBt->usableSize - 35);
 62783    pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
 62784    if( pBt->maxLocal>127 ){
 62785      pBt->max1bytePayload = 127;
 62786    }else{
 62787      pBt->max1bytePayload = (u8)pBt->maxLocal;
 62788    }
 62789    assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
 62790    pBt->pPage1 = pPage1;
 62791    pBt->nPage = nPage;
 62792    return SQLITE_OK;
 62793  
 62794  page1_init_failed:
 62795    releasePageOne(pPage1);
 62796    pBt->pPage1 = 0;
 62797    return rc;
 62798  }
 62799  
 62800  #ifndef NDEBUG
 62801  /*
 62802  ** Return the number of cursors open on pBt. This is for use
 62803  ** in assert() expressions, so it is only compiled if NDEBUG is not
 62804  ** defined.
 62805  **
 62806  ** Only write cursors are counted if wrOnly is true.  If wrOnly is
 62807  ** false then all cursors are counted.
 62808  **
 62809  ** For the purposes of this routine, a cursor is any cursor that
 62810  ** is capable of reading or writing to the database.  Cursors that
 62811  ** have been tripped into the CURSOR_FAULT state are not counted.
 62812  */
 62813  static int countValidCursors(BtShared *pBt, int wrOnly){
 62814    BtCursor *pCur;
 62815    int r = 0;
 62816    for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
 62817      if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
 62818       && pCur->eState!=CURSOR_FAULT ) r++; 
 62819    }
 62820    return r;
 62821  }
 62822  #endif
 62823  
 62824  /*
 62825  ** If there are no outstanding cursors and we are not in the middle
 62826  ** of a transaction but there is a read lock on the database, then
 62827  ** this routine unrefs the first page of the database file which 
 62828  ** has the effect of releasing the read lock.
 62829  **
 62830  ** If there is a transaction in progress, this routine is a no-op.
 62831  */
 62832  static void unlockBtreeIfUnused(BtShared *pBt){
 62833    assert( sqlite3_mutex_held(pBt->mutex) );
 62834    assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
 62835    if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
 62836      MemPage *pPage1 = pBt->pPage1;
 62837      assert( pPage1->aData );
 62838      assert( sqlite3PagerRefcount(pBt->pPager)==1 );
 62839      pBt->pPage1 = 0;
 62840      releasePageOne(pPage1);
 62841    }
 62842  }
 62843  
 62844  /*
 62845  ** If pBt points to an empty file then convert that empty file
 62846  ** into a new empty database by initializing the first page of
 62847  ** the database.
 62848  */
 62849  static int newDatabase(BtShared *pBt){
 62850    MemPage *pP1;
 62851    unsigned char *data;
 62852    int rc;
 62853  
 62854    assert( sqlite3_mutex_held(pBt->mutex) );
 62855    if( pBt->nPage>0 ){
 62856      return SQLITE_OK;
 62857    }
 62858    pP1 = pBt->pPage1;
 62859    assert( pP1!=0 );
 62860    data = pP1->aData;
 62861    rc = sqlite3PagerWrite(pP1->pDbPage);
 62862    if( rc ) return rc;
 62863    memcpy(data, zMagicHeader, sizeof(zMagicHeader));
 62864    assert( sizeof(zMagicHeader)==16 );
 62865    data[16] = (u8)((pBt->pageSize>>8)&0xff);
 62866    data[17] = (u8)((pBt->pageSize>>16)&0xff);
 62867    data[18] = 1;
 62868    data[19] = 1;
 62869    assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
 62870    data[20] = (u8)(pBt->pageSize - pBt->usableSize);
 62871    data[21] = 64;
 62872    data[22] = 32;
 62873    data[23] = 32;
 62874    memset(&data[24], 0, 100-24);
 62875    zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
 62876    pBt->btsFlags |= BTS_PAGESIZE_FIXED;
 62877  #ifndef SQLITE_OMIT_AUTOVACUUM
 62878    assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
 62879    assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
 62880    put4byte(&data[36 + 4*4], pBt->autoVacuum);
 62881    put4byte(&data[36 + 7*4], pBt->incrVacuum);
 62882  #endif
 62883    pBt->nPage = 1;
 62884    data[31] = 1;
 62885    return SQLITE_OK;
 62886  }
 62887  
 62888  /*
 62889  ** Initialize the first page of the database file (creating a database
 62890  ** consisting of a single page and no schema objects). Return SQLITE_OK
 62891  ** if successful, or an SQLite error code otherwise.
 62892  */
 62893  SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
 62894    int rc;
 62895    sqlite3BtreeEnter(p);
 62896    p->pBt->nPage = 0;
 62897    rc = newDatabase(p->pBt);
 62898    sqlite3BtreeLeave(p);
 62899    return rc;
 62900  }
 62901  
 62902  /*
 62903  ** Attempt to start a new transaction. A write-transaction
 62904  ** is started if the second argument is nonzero, otherwise a read-
 62905  ** transaction.  If the second argument is 2 or more and exclusive
 62906  ** transaction is started, meaning that no other process is allowed
 62907  ** to access the database.  A preexisting transaction may not be
 62908  ** upgraded to exclusive by calling this routine a second time - the
 62909  ** exclusivity flag only works for a new transaction.
 62910  **
 62911  ** A write-transaction must be started before attempting any 
 62912  ** changes to the database.  None of the following routines 
 62913  ** will work unless a transaction is started first:
 62914  **
 62915  **      sqlite3BtreeCreateTable()
 62916  **      sqlite3BtreeCreateIndex()
 62917  **      sqlite3BtreeClearTable()
 62918  **      sqlite3BtreeDropTable()
 62919  **      sqlite3BtreeInsert()
 62920  **      sqlite3BtreeDelete()
 62921  **      sqlite3BtreeUpdateMeta()
 62922  **
 62923  ** If an initial attempt to acquire the lock fails because of lock contention
 62924  ** and the database was previously unlocked, then invoke the busy handler
 62925  ** if there is one.  But if there was previously a read-lock, do not
 62926  ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
 62927  ** returned when there is already a read-lock in order to avoid a deadlock.
 62928  **
 62929  ** Suppose there are two processes A and B.  A has a read lock and B has
 62930  ** a reserved lock.  B tries to promote to exclusive but is blocked because
 62931  ** of A's read lock.  A tries to promote to reserved but is blocked by B.
 62932  ** One or the other of the two processes must give way or there can be
 62933  ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
 62934  ** when A already has a read lock, we encourage A to give up and let B
 62935  ** proceed.
 62936  */
 62937  SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
 62938    BtShared *pBt = p->pBt;
 62939    int rc = SQLITE_OK;
 62940  
 62941    sqlite3BtreeEnter(p);
 62942    btreeIntegrity(p);
 62943  
 62944    /* If the btree is already in a write-transaction, or it
 62945    ** is already in a read-transaction and a read-transaction
 62946    ** is requested, this is a no-op.
 62947    */
 62948    if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
 62949      goto trans_begun;
 62950    }
 62951    assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
 62952  
 62953    /* Write transactions are not possible on a read-only database */
 62954    if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
 62955      rc = SQLITE_READONLY;
 62956      goto trans_begun;
 62957    }
 62958  
 62959  #ifndef SQLITE_OMIT_SHARED_CACHE
 62960    {
 62961      sqlite3 *pBlock = 0;
 62962      /* If another database handle has already opened a write transaction 
 62963      ** on this shared-btree structure and a second write transaction is
 62964      ** requested, return SQLITE_LOCKED.
 62965      */
 62966      if( (wrflag && pBt->inTransaction==TRANS_WRITE)
 62967       || (pBt->btsFlags & BTS_PENDING)!=0
 62968      ){
 62969        pBlock = pBt->pWriter->db;
 62970      }else if( wrflag>1 ){
 62971        BtLock *pIter;
 62972        for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
 62973          if( pIter->pBtree!=p ){
 62974            pBlock = pIter->pBtree->db;
 62975            break;
 62976          }
 62977        }
 62978      }
 62979      if( pBlock ){
 62980        sqlite3ConnectionBlocked(p->db, pBlock);
 62981        rc = SQLITE_LOCKED_SHAREDCACHE;
 62982        goto trans_begun;
 62983      }
 62984    }
 62985  #endif
 62986  
 62987    /* Any read-only or read-write transaction implies a read-lock on 
 62988    ** page 1. So if some other shared-cache client already has a write-lock 
 62989    ** on page 1, the transaction cannot be opened. */
 62990    rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
 62991    if( SQLITE_OK!=rc ) goto trans_begun;
 62992  
 62993    pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
 62994    if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
 62995    do {
 62996      /* Call lockBtree() until either pBt->pPage1 is populated or
 62997      ** lockBtree() returns something other than SQLITE_OK. lockBtree()
 62998      ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
 62999      ** reading page 1 it discovers that the page-size of the database 
 63000      ** file is not pBt->pageSize. In this case lockBtree() will update
 63001      ** pBt->pageSize to the page-size of the file on disk.
 63002      */
 63003      while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
 63004  
 63005      if( rc==SQLITE_OK && wrflag ){
 63006        if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
 63007          rc = SQLITE_READONLY;
 63008        }else{
 63009          rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
 63010          if( rc==SQLITE_OK ){
 63011            rc = newDatabase(pBt);
 63012          }
 63013        }
 63014      }
 63015    
 63016      if( rc!=SQLITE_OK ){
 63017        unlockBtreeIfUnused(pBt);
 63018      }
 63019    }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
 63020            btreeInvokeBusyHandler(pBt) );
 63021  
 63022    if( rc==SQLITE_OK ){
 63023      if( p->inTrans==TRANS_NONE ){
 63024        pBt->nTransaction++;
 63025  #ifndef SQLITE_OMIT_SHARED_CACHE
 63026        if( p->sharable ){
 63027          assert( p->lock.pBtree==p && p->lock.iTable==1 );
 63028          p->lock.eLock = READ_LOCK;
 63029          p->lock.pNext = pBt->pLock;
 63030          pBt->pLock = &p->lock;
 63031        }
 63032  #endif
 63033      }
 63034      p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
 63035      if( p->inTrans>pBt->inTransaction ){
 63036        pBt->inTransaction = p->inTrans;
 63037      }
 63038      if( wrflag ){
 63039        MemPage *pPage1 = pBt->pPage1;
 63040  #ifndef SQLITE_OMIT_SHARED_CACHE
 63041        assert( !pBt->pWriter );
 63042        pBt->pWriter = p;
 63043        pBt->btsFlags &= ~BTS_EXCLUSIVE;
 63044        if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
 63045  #endif
 63046  
 63047        /* If the db-size header field is incorrect (as it may be if an old
 63048        ** client has been writing the database file), update it now. Doing
 63049        ** this sooner rather than later means the database size can safely 
 63050        ** re-read the database size from page 1 if a savepoint or transaction
 63051        ** rollback occurs within the transaction.
 63052        */
 63053        if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
 63054          rc = sqlite3PagerWrite(pPage1->pDbPage);
 63055          if( rc==SQLITE_OK ){
 63056            put4byte(&pPage1->aData[28], pBt->nPage);
 63057          }
 63058        }
 63059      }
 63060    }
 63061  
 63062  
 63063  trans_begun:
 63064    if( rc==SQLITE_OK && wrflag ){
 63065      /* This call makes sure that the pager has the correct number of
 63066      ** open savepoints. If the second parameter is greater than 0 and
 63067      ** the sub-journal is not already open, then it will be opened here.
 63068      */
 63069      rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
 63070    }
 63071  
 63072    btreeIntegrity(p);
 63073    sqlite3BtreeLeave(p);
 63074    return rc;
 63075  }
 63076  
 63077  #ifndef SQLITE_OMIT_AUTOVACUUM
 63078  
 63079  /*
 63080  ** Set the pointer-map entries for all children of page pPage. Also, if
 63081  ** pPage contains cells that point to overflow pages, set the pointer
 63082  ** map entries for the overflow pages as well.
 63083  */
 63084  static int setChildPtrmaps(MemPage *pPage){
 63085    int i;                             /* Counter variable */
 63086    int nCell;                         /* Number of cells in page pPage */
 63087    int rc;                            /* Return code */
 63088    BtShared *pBt = pPage->pBt;
 63089    Pgno pgno = pPage->pgno;
 63090  
 63091    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 63092    rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
 63093    if( rc!=SQLITE_OK ) return rc;
 63094    nCell = pPage->nCell;
 63095  
 63096    for(i=0; i<nCell; i++){
 63097      u8 *pCell = findCell(pPage, i);
 63098  
 63099      ptrmapPutOvflPtr(pPage, pCell, &rc);
 63100  
 63101      if( !pPage->leaf ){
 63102        Pgno childPgno = get4byte(pCell);
 63103        ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
 63104      }
 63105    }
 63106  
 63107    if( !pPage->leaf ){
 63108      Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
 63109      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
 63110    }
 63111  
 63112    return rc;
 63113  }
 63114  
 63115  /*
 63116  ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
 63117  ** that it points to iTo. Parameter eType describes the type of pointer to
 63118  ** be modified, as  follows:
 63119  **
 63120  ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
 63121  **                   page of pPage.
 63122  **
 63123  ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
 63124  **                   page pointed to by one of the cells on pPage.
 63125  **
 63126  ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
 63127  **                   overflow page in the list.
 63128  */
 63129  static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
 63130    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 63131    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 63132    if( eType==PTRMAP_OVERFLOW2 ){
 63133      /* The pointer is always the first 4 bytes of the page in this case.  */
 63134      if( get4byte(pPage->aData)!=iFrom ){
 63135        return SQLITE_CORRUPT_PGNO(pPage->pgno);
 63136      }
 63137      put4byte(pPage->aData, iTo);
 63138    }else{
 63139      int i;
 63140      int nCell;
 63141      int rc;
 63142  
 63143      rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
 63144      if( rc ) return rc;
 63145      nCell = pPage->nCell;
 63146  
 63147      for(i=0; i<nCell; i++){
 63148        u8 *pCell = findCell(pPage, i);
 63149        if( eType==PTRMAP_OVERFLOW1 ){
 63150          CellInfo info;
 63151          pPage->xParseCell(pPage, pCell, &info);
 63152          if( info.nLocal<info.nPayload ){
 63153            if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
 63154              return SQLITE_CORRUPT_PGNO(pPage->pgno);
 63155            }
 63156            if( iFrom==get4byte(pCell+info.nSize-4) ){
 63157              put4byte(pCell+info.nSize-4, iTo);
 63158              break;
 63159            }
 63160          }
 63161        }else{
 63162          if( get4byte(pCell)==iFrom ){
 63163            put4byte(pCell, iTo);
 63164            break;
 63165          }
 63166        }
 63167      }
 63168    
 63169      if( i==nCell ){
 63170        if( eType!=PTRMAP_BTREE || 
 63171            get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
 63172          return SQLITE_CORRUPT_PGNO(pPage->pgno);
 63173        }
 63174        put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
 63175      }
 63176    }
 63177    return SQLITE_OK;
 63178  }
 63179  
 63180  
 63181  /*
 63182  ** Move the open database page pDbPage to location iFreePage in the 
 63183  ** database. The pDbPage reference remains valid.
 63184  **
 63185  ** The isCommit flag indicates that there is no need to remember that
 63186  ** the journal needs to be sync()ed before database page pDbPage->pgno 
 63187  ** can be written to. The caller has already promised not to write to that
 63188  ** page.
 63189  */
 63190  static int relocatePage(
 63191    BtShared *pBt,           /* Btree */
 63192    MemPage *pDbPage,        /* Open page to move */
 63193    u8 eType,                /* Pointer map 'type' entry for pDbPage */
 63194    Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
 63195    Pgno iFreePage,          /* The location to move pDbPage to */
 63196    int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
 63197  ){
 63198    MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
 63199    Pgno iDbPage = pDbPage->pgno;
 63200    Pager *pPager = pBt->pPager;
 63201    int rc;
 63202  
 63203    assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
 63204        eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
 63205    assert( sqlite3_mutex_held(pBt->mutex) );
 63206    assert( pDbPage->pBt==pBt );
 63207  
 63208    /* Move page iDbPage from its current location to page number iFreePage */
 63209    TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
 63210        iDbPage, iFreePage, iPtrPage, eType));
 63211    rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
 63212    if( rc!=SQLITE_OK ){
 63213      return rc;
 63214    }
 63215    pDbPage->pgno = iFreePage;
 63216  
 63217    /* If pDbPage was a btree-page, then it may have child pages and/or cells
 63218    ** that point to overflow pages. The pointer map entries for all these
 63219    ** pages need to be changed.
 63220    **
 63221    ** If pDbPage is an overflow page, then the first 4 bytes may store a
 63222    ** pointer to a subsequent overflow page. If this is the case, then
 63223    ** the pointer map needs to be updated for the subsequent overflow page.
 63224    */
 63225    if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
 63226      rc = setChildPtrmaps(pDbPage);
 63227      if( rc!=SQLITE_OK ){
 63228        return rc;
 63229      }
 63230    }else{
 63231      Pgno nextOvfl = get4byte(pDbPage->aData);
 63232      if( nextOvfl!=0 ){
 63233        ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
 63234        if( rc!=SQLITE_OK ){
 63235          return rc;
 63236        }
 63237      }
 63238    }
 63239  
 63240    /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
 63241    ** that it points at iFreePage. Also fix the pointer map entry for
 63242    ** iPtrPage.
 63243    */
 63244    if( eType!=PTRMAP_ROOTPAGE ){
 63245      rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
 63246      if( rc!=SQLITE_OK ){
 63247        return rc;
 63248      }
 63249      rc = sqlite3PagerWrite(pPtrPage->pDbPage);
 63250      if( rc!=SQLITE_OK ){
 63251        releasePage(pPtrPage);
 63252        return rc;
 63253      }
 63254      rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
 63255      releasePage(pPtrPage);
 63256      if( rc==SQLITE_OK ){
 63257        ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
 63258      }
 63259    }
 63260    return rc;
 63261  }
 63262  
 63263  /* Forward declaration required by incrVacuumStep(). */
 63264  static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
 63265  
 63266  /*
 63267  ** Perform a single step of an incremental-vacuum. If successful, return
 63268  ** SQLITE_OK. If there is no work to do (and therefore no point in 
 63269  ** calling this function again), return SQLITE_DONE. Or, if an error 
 63270  ** occurs, return some other error code.
 63271  **
 63272  ** More specifically, this function attempts to re-organize the database so 
 63273  ** that the last page of the file currently in use is no longer in use.
 63274  **
 63275  ** Parameter nFin is the number of pages that this database would contain
 63276  ** were this function called until it returns SQLITE_DONE.
 63277  **
 63278  ** If the bCommit parameter is non-zero, this function assumes that the 
 63279  ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE 
 63280  ** or an error. bCommit is passed true for an auto-vacuum-on-commit 
 63281  ** operation, or false for an incremental vacuum.
 63282  */
 63283  static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
 63284    Pgno nFreeList;           /* Number of pages still on the free-list */
 63285    int rc;
 63286  
 63287    assert( sqlite3_mutex_held(pBt->mutex) );
 63288    assert( iLastPg>nFin );
 63289  
 63290    if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
 63291      u8 eType;
 63292      Pgno iPtrPage;
 63293  
 63294      nFreeList = get4byte(&pBt->pPage1->aData[36]);
 63295      if( nFreeList==0 ){
 63296        return SQLITE_DONE;
 63297      }
 63298  
 63299      rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
 63300      if( rc!=SQLITE_OK ){
 63301        return rc;
 63302      }
 63303      if( eType==PTRMAP_ROOTPAGE ){
 63304        return SQLITE_CORRUPT_BKPT;
 63305      }
 63306  
 63307      if( eType==PTRMAP_FREEPAGE ){
 63308        if( bCommit==0 ){
 63309          /* Remove the page from the files free-list. This is not required
 63310          ** if bCommit is non-zero. In that case, the free-list will be
 63311          ** truncated to zero after this function returns, so it doesn't 
 63312          ** matter if it still contains some garbage entries.
 63313          */
 63314          Pgno iFreePg;
 63315          MemPage *pFreePg;
 63316          rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
 63317          if( rc!=SQLITE_OK ){
 63318            return rc;
 63319          }
 63320          assert( iFreePg==iLastPg );
 63321          releasePage(pFreePg);
 63322        }
 63323      } else {
 63324        Pgno iFreePg;             /* Index of free page to move pLastPg to */
 63325        MemPage *pLastPg;
 63326        u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
 63327        Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
 63328  
 63329        rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
 63330        if( rc!=SQLITE_OK ){
 63331          return rc;
 63332        }
 63333  
 63334        /* If bCommit is zero, this loop runs exactly once and page pLastPg
 63335        ** is swapped with the first free page pulled off the free list.
 63336        **
 63337        ** On the other hand, if bCommit is greater than zero, then keep
 63338        ** looping until a free-page located within the first nFin pages
 63339        ** of the file is found.
 63340        */
 63341        if( bCommit==0 ){
 63342          eMode = BTALLOC_LE;
 63343          iNear = nFin;
 63344        }
 63345        do {
 63346          MemPage *pFreePg;
 63347          rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
 63348          if( rc!=SQLITE_OK ){
 63349            releasePage(pLastPg);
 63350            return rc;
 63351          }
 63352          releasePage(pFreePg);
 63353        }while( bCommit && iFreePg>nFin );
 63354        assert( iFreePg<iLastPg );
 63355        
 63356        rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
 63357        releasePage(pLastPg);
 63358        if( rc!=SQLITE_OK ){
 63359          return rc;
 63360        }
 63361      }
 63362    }
 63363  
 63364    if( bCommit==0 ){
 63365      do {
 63366        iLastPg--;
 63367      }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
 63368      pBt->bDoTruncate = 1;
 63369      pBt->nPage = iLastPg;
 63370    }
 63371    return SQLITE_OK;
 63372  }
 63373  
 63374  /*
 63375  ** The database opened by the first argument is an auto-vacuum database
 63376  ** nOrig pages in size containing nFree free pages. Return the expected 
 63377  ** size of the database in pages following an auto-vacuum operation.
 63378  */
 63379  static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
 63380    int nEntry;                     /* Number of entries on one ptrmap page */
 63381    Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
 63382    Pgno nFin;                      /* Return value */
 63383  
 63384    nEntry = pBt->usableSize/5;
 63385    nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
 63386    nFin = nOrig - nFree - nPtrmap;
 63387    if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
 63388      nFin--;
 63389    }
 63390    while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
 63391      nFin--;
 63392    }
 63393  
 63394    return nFin;
 63395  }
 63396  
 63397  /*
 63398  ** A write-transaction must be opened before calling this function.
 63399  ** It performs a single unit of work towards an incremental vacuum.
 63400  **
 63401  ** If the incremental vacuum is finished after this function has run,
 63402  ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
 63403  ** SQLITE_OK is returned. Otherwise an SQLite error code. 
 63404  */
 63405  SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
 63406    int rc;
 63407    BtShared *pBt = p->pBt;
 63408  
 63409    sqlite3BtreeEnter(p);
 63410    assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
 63411    if( !pBt->autoVacuum ){
 63412      rc = SQLITE_DONE;
 63413    }else{
 63414      Pgno nOrig = btreePagecount(pBt);
 63415      Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
 63416      Pgno nFin = finalDbSize(pBt, nOrig, nFree);
 63417  
 63418      if( nOrig<nFin ){
 63419        rc = SQLITE_CORRUPT_BKPT;
 63420      }else if( nFree>0 ){
 63421        rc = saveAllCursors(pBt, 0, 0);
 63422        if( rc==SQLITE_OK ){
 63423          invalidateAllOverflowCache(pBt);
 63424          rc = incrVacuumStep(pBt, nFin, nOrig, 0);
 63425        }
 63426        if( rc==SQLITE_OK ){
 63427          rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
 63428          put4byte(&pBt->pPage1->aData[28], pBt->nPage);
 63429        }
 63430      }else{
 63431        rc = SQLITE_DONE;
 63432      }
 63433    }
 63434    sqlite3BtreeLeave(p);
 63435    return rc;
 63436  }
 63437  
 63438  /*
 63439  ** This routine is called prior to sqlite3PagerCommit when a transaction
 63440  ** is committed for an auto-vacuum database.
 63441  **
 63442  ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
 63443  ** the database file should be truncated to during the commit process. 
 63444  ** i.e. the database has been reorganized so that only the first *pnTrunc
 63445  ** pages are in use.
 63446  */
 63447  static int autoVacuumCommit(BtShared *pBt){
 63448    int rc = SQLITE_OK;
 63449    Pager *pPager = pBt->pPager;
 63450    VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
 63451  
 63452    assert( sqlite3_mutex_held(pBt->mutex) );
 63453    invalidateAllOverflowCache(pBt);
 63454    assert(pBt->autoVacuum);
 63455    if( !pBt->incrVacuum ){
 63456      Pgno nFin;         /* Number of pages in database after autovacuuming */
 63457      Pgno nFree;        /* Number of pages on the freelist initially */
 63458      Pgno iFree;        /* The next page to be freed */
 63459      Pgno nOrig;        /* Database size before freeing */
 63460  
 63461      nOrig = btreePagecount(pBt);
 63462      if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
 63463        /* It is not possible to create a database for which the final page
 63464        ** is either a pointer-map page or the pending-byte page. If one
 63465        ** is encountered, this indicates corruption.
 63466        */
 63467        return SQLITE_CORRUPT_BKPT;
 63468      }
 63469  
 63470      nFree = get4byte(&pBt->pPage1->aData[36]);
 63471      nFin = finalDbSize(pBt, nOrig, nFree);
 63472      if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
 63473      if( nFin<nOrig ){
 63474        rc = saveAllCursors(pBt, 0, 0);
 63475      }
 63476      for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
 63477        rc = incrVacuumStep(pBt, nFin, iFree, 1);
 63478      }
 63479      if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
 63480        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
 63481        put4byte(&pBt->pPage1->aData[32], 0);
 63482        put4byte(&pBt->pPage1->aData[36], 0);
 63483        put4byte(&pBt->pPage1->aData[28], nFin);
 63484        pBt->bDoTruncate = 1;
 63485        pBt->nPage = nFin;
 63486      }
 63487      if( rc!=SQLITE_OK ){
 63488        sqlite3PagerRollback(pPager);
 63489      }
 63490    }
 63491  
 63492    assert( nRef>=sqlite3PagerRefcount(pPager) );
 63493    return rc;
 63494  }
 63495  
 63496  #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
 63497  # define setChildPtrmaps(x) SQLITE_OK
 63498  #endif
 63499  
 63500  /*
 63501  ** This routine does the first phase of a two-phase commit.  This routine
 63502  ** causes a rollback journal to be created (if it does not already exist)
 63503  ** and populated with enough information so that if a power loss occurs
 63504  ** the database can be restored to its original state by playing back
 63505  ** the journal.  Then the contents of the journal are flushed out to
 63506  ** the disk.  After the journal is safely on oxide, the changes to the
 63507  ** database are written into the database file and flushed to oxide.
 63508  ** At the end of this call, the rollback journal still exists on the
 63509  ** disk and we are still holding all locks, so the transaction has not
 63510  ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
 63511  ** commit process.
 63512  **
 63513  ** This call is a no-op if no write-transaction is currently active on pBt.
 63514  **
 63515  ** Otherwise, sync the database file for the btree pBt. zMaster points to
 63516  ** the name of a master journal file that should be written into the
 63517  ** individual journal file, or is NULL, indicating no master journal file 
 63518  ** (single database transaction).
 63519  **
 63520  ** When this is called, the master journal should already have been
 63521  ** created, populated with this journal pointer and synced to disk.
 63522  **
 63523  ** Once this is routine has returned, the only thing required to commit
 63524  ** the write-transaction for this database file is to delete the journal.
 63525  */
 63526  SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
 63527    int rc = SQLITE_OK;
 63528    if( p->inTrans==TRANS_WRITE ){
 63529      BtShared *pBt = p->pBt;
 63530      sqlite3BtreeEnter(p);
 63531  #ifndef SQLITE_OMIT_AUTOVACUUM
 63532      if( pBt->autoVacuum ){
 63533        rc = autoVacuumCommit(pBt);
 63534        if( rc!=SQLITE_OK ){
 63535          sqlite3BtreeLeave(p);
 63536          return rc;
 63537        }
 63538      }
 63539      if( pBt->bDoTruncate ){
 63540        sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
 63541      }
 63542  #endif
 63543      rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
 63544      sqlite3BtreeLeave(p);
 63545    }
 63546    return rc;
 63547  }
 63548  
 63549  /*
 63550  ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
 63551  ** at the conclusion of a transaction.
 63552  */
 63553  static void btreeEndTransaction(Btree *p){
 63554    BtShared *pBt = p->pBt;
 63555    sqlite3 *db = p->db;
 63556    assert( sqlite3BtreeHoldsMutex(p) );
 63557  
 63558  #ifndef SQLITE_OMIT_AUTOVACUUM
 63559    pBt->bDoTruncate = 0;
 63560  #endif
 63561    if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
 63562      /* If there are other active statements that belong to this database
 63563      ** handle, downgrade to a read-only transaction. The other statements
 63564      ** may still be reading from the database.  */
 63565      downgradeAllSharedCacheTableLocks(p);
 63566      p->inTrans = TRANS_READ;
 63567    }else{
 63568      /* If the handle had any kind of transaction open, decrement the 
 63569      ** transaction count of the shared btree. If the transaction count 
 63570      ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
 63571      ** call below will unlock the pager.  */
 63572      if( p->inTrans!=TRANS_NONE ){
 63573        clearAllSharedCacheTableLocks(p);
 63574        pBt->nTransaction--;
 63575        if( 0==pBt->nTransaction ){
 63576          pBt->inTransaction = TRANS_NONE;
 63577        }
 63578      }
 63579  
 63580      /* Set the current transaction state to TRANS_NONE and unlock the 
 63581      ** pager if this call closed the only read or write transaction.  */
 63582      p->inTrans = TRANS_NONE;
 63583      unlockBtreeIfUnused(pBt);
 63584    }
 63585  
 63586    btreeIntegrity(p);
 63587  }
 63588  
 63589  /*
 63590  ** Commit the transaction currently in progress.
 63591  **
 63592  ** This routine implements the second phase of a 2-phase commit.  The
 63593  ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
 63594  ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
 63595  ** routine did all the work of writing information out to disk and flushing the
 63596  ** contents so that they are written onto the disk platter.  All this
 63597  ** routine has to do is delete or truncate or zero the header in the
 63598  ** the rollback journal (which causes the transaction to commit) and
 63599  ** drop locks.
 63600  **
 63601  ** Normally, if an error occurs while the pager layer is attempting to 
 63602  ** finalize the underlying journal file, this function returns an error and
 63603  ** the upper layer will attempt a rollback. However, if the second argument
 63604  ** is non-zero then this b-tree transaction is part of a multi-file 
 63605  ** transaction. In this case, the transaction has already been committed 
 63606  ** (by deleting a master journal file) and the caller will ignore this 
 63607  ** functions return code. So, even if an error occurs in the pager layer,
 63608  ** reset the b-tree objects internal state to indicate that the write
 63609  ** transaction has been closed. This is quite safe, as the pager will have
 63610  ** transitioned to the error state.
 63611  **
 63612  ** This will release the write lock on the database file.  If there
 63613  ** are no active cursors, it also releases the read lock.
 63614  */
 63615  SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
 63616  
 63617    if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
 63618    sqlite3BtreeEnter(p);
 63619    btreeIntegrity(p);
 63620  
 63621    /* If the handle has a write-transaction open, commit the shared-btrees 
 63622    ** transaction and set the shared state to TRANS_READ.
 63623    */
 63624    if( p->inTrans==TRANS_WRITE ){
 63625      int rc;
 63626      BtShared *pBt = p->pBt;
 63627      assert( pBt->inTransaction==TRANS_WRITE );
 63628      assert( pBt->nTransaction>0 );
 63629      rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
 63630      if( rc!=SQLITE_OK && bCleanup==0 ){
 63631        sqlite3BtreeLeave(p);
 63632        return rc;
 63633      }
 63634      p->iDataVersion--;  /* Compensate for pPager->iDataVersion++; */
 63635      pBt->inTransaction = TRANS_READ;
 63636      btreeClearHasContent(pBt);
 63637    }
 63638  
 63639    btreeEndTransaction(p);
 63640    sqlite3BtreeLeave(p);
 63641    return SQLITE_OK;
 63642  }
 63643  
 63644  /*
 63645  ** Do both phases of a commit.
 63646  */
 63647  SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
 63648    int rc;
 63649    sqlite3BtreeEnter(p);
 63650    rc = sqlite3BtreeCommitPhaseOne(p, 0);
 63651    if( rc==SQLITE_OK ){
 63652      rc = sqlite3BtreeCommitPhaseTwo(p, 0);
 63653    }
 63654    sqlite3BtreeLeave(p);
 63655    return rc;
 63656  }
 63657  
 63658  /*
 63659  ** This routine sets the state to CURSOR_FAULT and the error
 63660  ** code to errCode for every cursor on any BtShared that pBtree
 63661  ** references.  Or if the writeOnly flag is set to 1, then only
 63662  ** trip write cursors and leave read cursors unchanged.
 63663  **
 63664  ** Every cursor is a candidate to be tripped, including cursors
 63665  ** that belong to other database connections that happen to be
 63666  ** sharing the cache with pBtree.
 63667  **
 63668  ** This routine gets called when a rollback occurs. If the writeOnly
 63669  ** flag is true, then only write-cursors need be tripped - read-only
 63670  ** cursors save their current positions so that they may continue 
 63671  ** following the rollback. Or, if writeOnly is false, all cursors are 
 63672  ** tripped. In general, writeOnly is false if the transaction being
 63673  ** rolled back modified the database schema. In this case b-tree root
 63674  ** pages may be moved or deleted from the database altogether, making
 63675  ** it unsafe for read cursors to continue.
 63676  **
 63677  ** If the writeOnly flag is true and an error is encountered while 
 63678  ** saving the current position of a read-only cursor, all cursors, 
 63679  ** including all read-cursors are tripped.
 63680  **
 63681  ** SQLITE_OK is returned if successful, or if an error occurs while
 63682  ** saving a cursor position, an SQLite error code.
 63683  */
 63684  SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
 63685    BtCursor *p;
 63686    int rc = SQLITE_OK;
 63687  
 63688    assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
 63689    if( pBtree ){
 63690      sqlite3BtreeEnter(pBtree);
 63691      for(p=pBtree->pBt->pCursor; p; p=p->pNext){
 63692        if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
 63693          if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
 63694            rc = saveCursorPosition(p);
 63695            if( rc!=SQLITE_OK ){
 63696              (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
 63697              break;
 63698            }
 63699          }
 63700        }else{
 63701          sqlite3BtreeClearCursor(p);
 63702          p->eState = CURSOR_FAULT;
 63703          p->skipNext = errCode;
 63704        }
 63705        btreeReleaseAllCursorPages(p);
 63706      }
 63707      sqlite3BtreeLeave(pBtree);
 63708    }
 63709    return rc;
 63710  }
 63711  
 63712  /*
 63713  ** Rollback the transaction in progress.
 63714  **
 63715  ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
 63716  ** Only write cursors are tripped if writeOnly is true but all cursors are
 63717  ** tripped if writeOnly is false.  Any attempt to use
 63718  ** a tripped cursor will result in an error.
 63719  **
 63720  ** This will release the write lock on the database file.  If there
 63721  ** are no active cursors, it also releases the read lock.
 63722  */
 63723  SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
 63724    int rc;
 63725    BtShared *pBt = p->pBt;
 63726    MemPage *pPage1;
 63727  
 63728    assert( writeOnly==1 || writeOnly==0 );
 63729    assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
 63730    sqlite3BtreeEnter(p);
 63731    if( tripCode==SQLITE_OK ){
 63732      rc = tripCode = saveAllCursors(pBt, 0, 0);
 63733      if( rc ) writeOnly = 0;
 63734    }else{
 63735      rc = SQLITE_OK;
 63736    }
 63737    if( tripCode ){
 63738      int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
 63739      assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
 63740      if( rc2!=SQLITE_OK ) rc = rc2;
 63741    }
 63742    btreeIntegrity(p);
 63743  
 63744    if( p->inTrans==TRANS_WRITE ){
 63745      int rc2;
 63746  
 63747      assert( TRANS_WRITE==pBt->inTransaction );
 63748      rc2 = sqlite3PagerRollback(pBt->pPager);
 63749      if( rc2!=SQLITE_OK ){
 63750        rc = rc2;
 63751      }
 63752  
 63753      /* The rollback may have destroyed the pPage1->aData value.  So
 63754      ** call btreeGetPage() on page 1 again to make
 63755      ** sure pPage1->aData is set correctly. */
 63756      if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
 63757        int nPage = get4byte(28+(u8*)pPage1->aData);
 63758        testcase( nPage==0 );
 63759        if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
 63760        testcase( pBt->nPage!=nPage );
 63761        pBt->nPage = nPage;
 63762        releasePageOne(pPage1);
 63763      }
 63764      assert( countValidCursors(pBt, 1)==0 );
 63765      pBt->inTransaction = TRANS_READ;
 63766      btreeClearHasContent(pBt);
 63767    }
 63768  
 63769    btreeEndTransaction(p);
 63770    sqlite3BtreeLeave(p);
 63771    return rc;
 63772  }
 63773  
 63774  /*
 63775  ** Start a statement subtransaction. The subtransaction can be rolled
 63776  ** back independently of the main transaction. You must start a transaction 
 63777  ** before starting a subtransaction. The subtransaction is ended automatically 
 63778  ** if the main transaction commits or rolls back.
 63779  **
 63780  ** Statement subtransactions are used around individual SQL statements
 63781  ** that are contained within a BEGIN...COMMIT block.  If a constraint
 63782  ** error occurs within the statement, the effect of that one statement
 63783  ** can be rolled back without having to rollback the entire transaction.
 63784  **
 63785  ** A statement sub-transaction is implemented as an anonymous savepoint. The
 63786  ** value passed as the second parameter is the total number of savepoints,
 63787  ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
 63788  ** are no active savepoints and no other statement-transactions open,
 63789  ** iStatement is 1. This anonymous savepoint can be released or rolled back
 63790  ** using the sqlite3BtreeSavepoint() function.
 63791  */
 63792  SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
 63793    int rc;
 63794    BtShared *pBt = p->pBt;
 63795    sqlite3BtreeEnter(p);
 63796    assert( p->inTrans==TRANS_WRITE );
 63797    assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
 63798    assert( iStatement>0 );
 63799    assert( iStatement>p->db->nSavepoint );
 63800    assert( pBt->inTransaction==TRANS_WRITE );
 63801    /* At the pager level, a statement transaction is a savepoint with
 63802    ** an index greater than all savepoints created explicitly using
 63803    ** SQL statements. It is illegal to open, release or rollback any
 63804    ** such savepoints while the statement transaction savepoint is active.
 63805    */
 63806    rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
 63807    sqlite3BtreeLeave(p);
 63808    return rc;
 63809  }
 63810  
 63811  /*
 63812  ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
 63813  ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
 63814  ** savepoint identified by parameter iSavepoint, depending on the value 
 63815  ** of op.
 63816  **
 63817  ** Normally, iSavepoint is greater than or equal to zero. However, if op is
 63818  ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
 63819  ** contents of the entire transaction are rolled back. This is different
 63820  ** from a normal transaction rollback, as no locks are released and the
 63821  ** transaction remains open.
 63822  */
 63823  SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
 63824    int rc = SQLITE_OK;
 63825    if( p && p->inTrans==TRANS_WRITE ){
 63826      BtShared *pBt = p->pBt;
 63827      assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
 63828      assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
 63829      sqlite3BtreeEnter(p);
 63830      if( op==SAVEPOINT_ROLLBACK ){
 63831        rc = saveAllCursors(pBt, 0, 0);
 63832      }
 63833      if( rc==SQLITE_OK ){
 63834        rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
 63835      }
 63836      if( rc==SQLITE_OK ){
 63837        if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
 63838          pBt->nPage = 0;
 63839        }
 63840        rc = newDatabase(pBt);
 63841        pBt->nPage = get4byte(28 + pBt->pPage1->aData);
 63842  
 63843        /* The database size was written into the offset 28 of the header
 63844        ** when the transaction started, so we know that the value at offset
 63845        ** 28 is nonzero. */
 63846        assert( pBt->nPage>0 );
 63847      }
 63848      sqlite3BtreeLeave(p);
 63849    }
 63850    return rc;
 63851  }
 63852  
 63853  /*
 63854  ** Create a new cursor for the BTree whose root is on the page
 63855  ** iTable. If a read-only cursor is requested, it is assumed that
 63856  ** the caller already has at least a read-only transaction open
 63857  ** on the database already. If a write-cursor is requested, then
 63858  ** the caller is assumed to have an open write transaction.
 63859  **
 63860  ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
 63861  ** be used for reading.  If the BTREE_WRCSR bit is set, then the cursor
 63862  ** can be used for reading or for writing if other conditions for writing
 63863  ** are also met.  These are the conditions that must be met in order
 63864  ** for writing to be allowed:
 63865  **
 63866  ** 1:  The cursor must have been opened with wrFlag containing BTREE_WRCSR
 63867  **
 63868  ** 2:  Other database connections that share the same pager cache
 63869  **     but which are not in the READ_UNCOMMITTED state may not have
 63870  **     cursors open with wrFlag==0 on the same table.  Otherwise
 63871  **     the changes made by this write cursor would be visible to
 63872  **     the read cursors in the other database connection.
 63873  **
 63874  ** 3:  The database must be writable (not on read-only media)
 63875  **
 63876  ** 4:  There must be an active transaction.
 63877  **
 63878  ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
 63879  ** is set.  If FORDELETE is set, that is a hint to the implementation that
 63880  ** this cursor will only be used to seek to and delete entries of an index
 63881  ** as part of a larger DELETE statement.  The FORDELETE hint is not used by
 63882  ** this implementation.  But in a hypothetical alternative storage engine 
 63883  ** in which index entries are automatically deleted when corresponding table
 63884  ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
 63885  ** operations on this cursor can be no-ops and all READ operations can 
 63886  ** return a null row (2-bytes: 0x01 0x00).
 63887  **
 63888  ** No checking is done to make sure that page iTable really is the
 63889  ** root page of a b-tree.  If it is not, then the cursor acquired
 63890  ** will not work correctly.
 63891  **
 63892  ** It is assumed that the sqlite3BtreeCursorZero() has been called
 63893  ** on pCur to initialize the memory space prior to invoking this routine.
 63894  */
 63895  static int btreeCursor(
 63896    Btree *p,                              /* The btree */
 63897    int iTable,                            /* Root page of table to open */
 63898    int wrFlag,                            /* 1 to write. 0 read-only */
 63899    struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
 63900    BtCursor *pCur                         /* Space for new cursor */
 63901  ){
 63902    BtShared *pBt = p->pBt;                /* Shared b-tree handle */
 63903    BtCursor *pX;                          /* Looping over other all cursors */
 63904  
 63905    assert( sqlite3BtreeHoldsMutex(p) );
 63906    assert( wrFlag==0 
 63907         || wrFlag==BTREE_WRCSR 
 63908         || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE) 
 63909    );
 63910  
 63911    /* The following assert statements verify that if this is a sharable 
 63912    ** b-tree database, the connection is holding the required table locks, 
 63913    ** and that no other connection has any open cursor that conflicts with 
 63914    ** this lock.  */
 63915    assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
 63916    assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
 63917  
 63918    /* Assert that the caller has opened the required transaction. */
 63919    assert( p->inTrans>TRANS_NONE );
 63920    assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
 63921    assert( pBt->pPage1 && pBt->pPage1->aData );
 63922    assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
 63923  
 63924    if( wrFlag ){
 63925      allocateTempSpace(pBt);
 63926      if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
 63927    }
 63928    if( iTable==1 && btreePagecount(pBt)==0 ){
 63929      assert( wrFlag==0 );
 63930      iTable = 0;
 63931    }
 63932  
 63933    /* Now that no other errors can occur, finish filling in the BtCursor
 63934    ** variables and link the cursor into the BtShared list.  */
 63935    pCur->pgnoRoot = (Pgno)iTable;
 63936    pCur->iPage = -1;
 63937    pCur->pKeyInfo = pKeyInfo;
 63938    pCur->pBtree = p;
 63939    pCur->pBt = pBt;
 63940    pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
 63941    pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
 63942    /* If there are two or more cursors on the same btree, then all such
 63943    ** cursors *must* have the BTCF_Multiple flag set. */
 63944    for(pX=pBt->pCursor; pX; pX=pX->pNext){
 63945      if( pX->pgnoRoot==(Pgno)iTable ){
 63946        pX->curFlags |= BTCF_Multiple;
 63947        pCur->curFlags |= BTCF_Multiple;
 63948      }
 63949    }
 63950    pCur->pNext = pBt->pCursor;
 63951    pBt->pCursor = pCur;
 63952    pCur->eState = CURSOR_INVALID;
 63953    return SQLITE_OK;
 63954  }
 63955  SQLITE_PRIVATE int sqlite3BtreeCursor(
 63956    Btree *p,                                   /* The btree */
 63957    int iTable,                                 /* Root page of table to open */
 63958    int wrFlag,                                 /* 1 to write. 0 read-only */
 63959    struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
 63960    BtCursor *pCur                              /* Write new cursor here */
 63961  ){
 63962    int rc;
 63963    if( iTable<1 ){
 63964      rc = SQLITE_CORRUPT_BKPT;
 63965    }else{
 63966      sqlite3BtreeEnter(p);
 63967      rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
 63968      sqlite3BtreeLeave(p);
 63969    }
 63970    return rc;
 63971  }
 63972  
 63973  /*
 63974  ** Return the size of a BtCursor object in bytes.
 63975  **
 63976  ** This interfaces is needed so that users of cursors can preallocate
 63977  ** sufficient storage to hold a cursor.  The BtCursor object is opaque
 63978  ** to users so they cannot do the sizeof() themselves - they must call
 63979  ** this routine.
 63980  */
 63981  SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
 63982    return ROUND8(sizeof(BtCursor));
 63983  }
 63984  
 63985  /*
 63986  ** Initialize memory that will be converted into a BtCursor object.
 63987  **
 63988  ** The simple approach here would be to memset() the entire object
 63989  ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
 63990  ** do not need to be zeroed and they are large, so we can save a lot
 63991  ** of run-time by skipping the initialization of those elements.
 63992  */
 63993  SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
 63994    memset(p, 0, offsetof(BtCursor, iPage));
 63995  }
 63996  
 63997  /*
 63998  ** Close a cursor.  The read lock on the database file is released
 63999  ** when the last cursor is closed.
 64000  */
 64001  SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
 64002    Btree *pBtree = pCur->pBtree;
 64003    if( pBtree ){
 64004      BtShared *pBt = pCur->pBt;
 64005      sqlite3BtreeEnter(pBtree);
 64006      assert( pBt->pCursor!=0 );
 64007      if( pBt->pCursor==pCur ){
 64008        pBt->pCursor = pCur->pNext;
 64009      }else{
 64010        BtCursor *pPrev = pBt->pCursor;
 64011        do{
 64012          if( pPrev->pNext==pCur ){
 64013            pPrev->pNext = pCur->pNext;
 64014            break;
 64015          }
 64016          pPrev = pPrev->pNext;
 64017        }while( ALWAYS(pPrev) );
 64018      }
 64019      btreeReleaseAllCursorPages(pCur);
 64020      unlockBtreeIfUnused(pBt);
 64021      sqlite3_free(pCur->aOverflow);
 64022      sqlite3_free(pCur->pKey);
 64023      sqlite3BtreeLeave(pBtree);
 64024    }
 64025    return SQLITE_OK;
 64026  }
 64027  
 64028  /*
 64029  ** Make sure the BtCursor* given in the argument has a valid
 64030  ** BtCursor.info structure.  If it is not already valid, call
 64031  ** btreeParseCell() to fill it in.
 64032  **
 64033  ** BtCursor.info is a cache of the information in the current cell.
 64034  ** Using this cache reduces the number of calls to btreeParseCell().
 64035  */
 64036  #ifndef NDEBUG
 64037    static void assertCellInfo(BtCursor *pCur){
 64038      CellInfo info;
 64039      memset(&info, 0, sizeof(info));
 64040      btreeParseCell(pCur->pPage, pCur->ix, &info);
 64041      assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
 64042    }
 64043  #else
 64044    #define assertCellInfo(x)
 64045  #endif
 64046  static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
 64047    if( pCur->info.nSize==0 ){
 64048      pCur->curFlags |= BTCF_ValidNKey;
 64049      btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
 64050    }else{
 64051      assertCellInfo(pCur);
 64052    }
 64053  }
 64054  
 64055  #ifndef NDEBUG  /* The next routine used only within assert() statements */
 64056  /*
 64057  ** Return true if the given BtCursor is valid.  A valid cursor is one
 64058  ** that is currently pointing to a row in a (non-empty) table.
 64059  ** This is a verification routine is used only within assert() statements.
 64060  */
 64061  SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
 64062    return pCur && pCur->eState==CURSOR_VALID;
 64063  }
 64064  #endif /* NDEBUG */
 64065  SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
 64066    assert( pCur!=0 );
 64067    return pCur->eState==CURSOR_VALID;
 64068  }
 64069  
 64070  /*
 64071  ** Return the value of the integer key or "rowid" for a table btree.
 64072  ** This routine is only valid for a cursor that is pointing into a
 64073  ** ordinary table btree.  If the cursor points to an index btree or
 64074  ** is invalid, the result of this routine is undefined.
 64075  */
 64076  SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
 64077    assert( cursorHoldsMutex(pCur) );
 64078    assert( pCur->eState==CURSOR_VALID );
 64079    assert( pCur->curIntKey );
 64080    getCellInfo(pCur);
 64081    return pCur->info.nKey;
 64082  }
 64083  
 64084  /*
 64085  ** Return the number of bytes of payload for the entry that pCur is
 64086  ** currently pointing to.  For table btrees, this will be the amount
 64087  ** of data.  For index btrees, this will be the size of the key.
 64088  **
 64089  ** The caller must guarantee that the cursor is pointing to a non-NULL
 64090  ** valid entry.  In other words, the calling procedure must guarantee
 64091  ** that the cursor has Cursor.eState==CURSOR_VALID.
 64092  */
 64093  SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){
 64094    assert( cursorHoldsMutex(pCur) );
 64095    assert( pCur->eState==CURSOR_VALID );
 64096    getCellInfo(pCur);
 64097    return pCur->info.nPayload;
 64098  }
 64099  
 64100  /*
 64101  ** Given the page number of an overflow page in the database (parameter
 64102  ** ovfl), this function finds the page number of the next page in the 
 64103  ** linked list of overflow pages. If possible, it uses the auto-vacuum
 64104  ** pointer-map data instead of reading the content of page ovfl to do so. 
 64105  **
 64106  ** If an error occurs an SQLite error code is returned. Otherwise:
 64107  **
 64108  ** The page number of the next overflow page in the linked list is 
 64109  ** written to *pPgnoNext. If page ovfl is the last page in its linked 
 64110  ** list, *pPgnoNext is set to zero. 
 64111  **
 64112  ** If ppPage is not NULL, and a reference to the MemPage object corresponding
 64113  ** to page number pOvfl was obtained, then *ppPage is set to point to that
 64114  ** reference. It is the responsibility of the caller to call releasePage()
 64115  ** on *ppPage to free the reference. In no reference was obtained (because
 64116  ** the pointer-map was used to obtain the value for *pPgnoNext), then
 64117  ** *ppPage is set to zero.
 64118  */
 64119  static int getOverflowPage(
 64120    BtShared *pBt,               /* The database file */
 64121    Pgno ovfl,                   /* Current overflow page number */
 64122    MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
 64123    Pgno *pPgnoNext              /* OUT: Next overflow page number */
 64124  ){
 64125    Pgno next = 0;
 64126    MemPage *pPage = 0;
 64127    int rc = SQLITE_OK;
 64128  
 64129    assert( sqlite3_mutex_held(pBt->mutex) );
 64130    assert(pPgnoNext);
 64131  
 64132  #ifndef SQLITE_OMIT_AUTOVACUUM
 64133    /* Try to find the next page in the overflow list using the
 64134    ** autovacuum pointer-map pages. Guess that the next page in 
 64135    ** the overflow list is page number (ovfl+1). If that guess turns 
 64136    ** out to be wrong, fall back to loading the data of page 
 64137    ** number ovfl to determine the next page number.
 64138    */
 64139    if( pBt->autoVacuum ){
 64140      Pgno pgno;
 64141      Pgno iGuess = ovfl+1;
 64142      u8 eType;
 64143  
 64144      while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
 64145        iGuess++;
 64146      }
 64147  
 64148      if( iGuess<=btreePagecount(pBt) ){
 64149        rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
 64150        if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
 64151          next = iGuess;
 64152          rc = SQLITE_DONE;
 64153        }
 64154      }
 64155    }
 64156  #endif
 64157  
 64158    assert( next==0 || rc==SQLITE_DONE );
 64159    if( rc==SQLITE_OK ){
 64160      rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
 64161      assert( rc==SQLITE_OK || pPage==0 );
 64162      if( rc==SQLITE_OK ){
 64163        next = get4byte(pPage->aData);
 64164      }
 64165    }
 64166  
 64167    *pPgnoNext = next;
 64168    if( ppPage ){
 64169      *ppPage = pPage;
 64170    }else{
 64171      releasePage(pPage);
 64172    }
 64173    return (rc==SQLITE_DONE ? SQLITE_OK : rc);
 64174  }
 64175  
 64176  /*
 64177  ** Copy data from a buffer to a page, or from a page to a buffer.
 64178  **
 64179  ** pPayload is a pointer to data stored on database page pDbPage.
 64180  ** If argument eOp is false, then nByte bytes of data are copied
 64181  ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
 64182  ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
 64183  ** of data are copied from the buffer pBuf to pPayload.
 64184  **
 64185  ** SQLITE_OK is returned on success, otherwise an error code.
 64186  */
 64187  static int copyPayload(
 64188    void *pPayload,           /* Pointer to page data */
 64189    void *pBuf,               /* Pointer to buffer */
 64190    int nByte,                /* Number of bytes to copy */
 64191    int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
 64192    DbPage *pDbPage           /* Page containing pPayload */
 64193  ){
 64194    if( eOp ){
 64195      /* Copy data from buffer to page (a write operation) */
 64196      int rc = sqlite3PagerWrite(pDbPage);
 64197      if( rc!=SQLITE_OK ){
 64198        return rc;
 64199      }
 64200      memcpy(pPayload, pBuf, nByte);
 64201    }else{
 64202      /* Copy data from page to buffer (a read operation) */
 64203      memcpy(pBuf, pPayload, nByte);
 64204    }
 64205    return SQLITE_OK;
 64206  }
 64207  
 64208  /*
 64209  ** This function is used to read or overwrite payload information
 64210  ** for the entry that the pCur cursor is pointing to. The eOp
 64211  ** argument is interpreted as follows:
 64212  **
 64213  **   0: The operation is a read. Populate the overflow cache.
 64214  **   1: The operation is a write. Populate the overflow cache.
 64215  **
 64216  ** A total of "amt" bytes are read or written beginning at "offset".
 64217  ** Data is read to or from the buffer pBuf.
 64218  **
 64219  ** The content being read or written might appear on the main page
 64220  ** or be scattered out on multiple overflow pages.
 64221  **
 64222  ** If the current cursor entry uses one or more overflow pages
 64223  ** this function may allocate space for and lazily populate
 64224  ** the overflow page-list cache array (BtCursor.aOverflow). 
 64225  ** Subsequent calls use this cache to make seeking to the supplied offset 
 64226  ** more efficient.
 64227  **
 64228  ** Once an overflow page-list cache has been allocated, it must be
 64229  ** invalidated if some other cursor writes to the same table, or if
 64230  ** the cursor is moved to a different row. Additionally, in auto-vacuum
 64231  ** mode, the following events may invalidate an overflow page-list cache.
 64232  **
 64233  **   * An incremental vacuum,
 64234  **   * A commit in auto_vacuum="full" mode,
 64235  **   * Creating a table (may require moving an overflow page).
 64236  */
 64237  static int accessPayload(
 64238    BtCursor *pCur,      /* Cursor pointing to entry to read from */
 64239    u32 offset,          /* Begin reading this far into payload */
 64240    u32 amt,             /* Read this many bytes */
 64241    unsigned char *pBuf, /* Write the bytes into this buffer */ 
 64242    int eOp              /* zero to read. non-zero to write. */
 64243  ){
 64244    unsigned char *aPayload;
 64245    int rc = SQLITE_OK;
 64246    int iIdx = 0;
 64247    MemPage *pPage = pCur->pPage;               /* Btree page of current entry */
 64248    BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
 64249  #ifdef SQLITE_DIRECT_OVERFLOW_READ
 64250    unsigned char * const pBufStart = pBuf;     /* Start of original out buffer */
 64251  #endif
 64252  
 64253    assert( pPage );
 64254    assert( eOp==0 || eOp==1 );
 64255    assert( pCur->eState==CURSOR_VALID );
 64256    assert( pCur->ix<pPage->nCell );
 64257    assert( cursorHoldsMutex(pCur) );
 64258  
 64259    getCellInfo(pCur);
 64260    aPayload = pCur->info.pPayload;
 64261    assert( offset+amt <= pCur->info.nPayload );
 64262  
 64263    assert( aPayload > pPage->aData );
 64264    if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
 64265      /* Trying to read or write past the end of the data is an error.  The
 64266      ** conditional above is really:
 64267      **    &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
 64268      ** but is recast into its current form to avoid integer overflow problems
 64269      */
 64270      return SQLITE_CORRUPT_PGNO(pPage->pgno);
 64271    }
 64272  
 64273    /* Check if data must be read/written to/from the btree page itself. */
 64274    if( offset<pCur->info.nLocal ){
 64275      int a = amt;
 64276      if( a+offset>pCur->info.nLocal ){
 64277        a = pCur->info.nLocal - offset;
 64278      }
 64279      rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
 64280      offset = 0;
 64281      pBuf += a;
 64282      amt -= a;
 64283    }else{
 64284      offset -= pCur->info.nLocal;
 64285    }
 64286  
 64287  
 64288    if( rc==SQLITE_OK && amt>0 ){
 64289      const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
 64290      Pgno nextPage;
 64291  
 64292      nextPage = get4byte(&aPayload[pCur->info.nLocal]);
 64293  
 64294      /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
 64295      **
 64296      ** The aOverflow[] array is sized at one entry for each overflow page
 64297      ** in the overflow chain. The page number of the first overflow page is
 64298      ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
 64299      ** means "not yet known" (the cache is lazily populated).
 64300      */
 64301      if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
 64302        int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
 64303        if( nOvfl>pCur->nOvflAlloc ){
 64304          Pgno *aNew = (Pgno*)sqlite3Realloc(
 64305              pCur->aOverflow, nOvfl*2*sizeof(Pgno)
 64306          );
 64307          if( aNew==0 ){
 64308            return SQLITE_NOMEM_BKPT;
 64309          }else{
 64310            pCur->nOvflAlloc = nOvfl*2;
 64311            pCur->aOverflow = aNew;
 64312          }
 64313        }
 64314        memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
 64315        pCur->curFlags |= BTCF_ValidOvfl;
 64316      }else{
 64317        /* If the overflow page-list cache has been allocated and the
 64318        ** entry for the first required overflow page is valid, skip
 64319        ** directly to it.
 64320        */
 64321        if( pCur->aOverflow[offset/ovflSize] ){
 64322          iIdx = (offset/ovflSize);
 64323          nextPage = pCur->aOverflow[iIdx];
 64324          offset = (offset%ovflSize);
 64325        }
 64326      }
 64327  
 64328      assert( rc==SQLITE_OK && amt>0 );
 64329      while( nextPage ){
 64330        /* If required, populate the overflow page-list cache. */
 64331        assert( pCur->aOverflow[iIdx]==0
 64332                || pCur->aOverflow[iIdx]==nextPage
 64333                || CORRUPT_DB );
 64334        pCur->aOverflow[iIdx] = nextPage;
 64335  
 64336        if( offset>=ovflSize ){
 64337          /* The only reason to read this page is to obtain the page
 64338          ** number for the next page in the overflow chain. The page
 64339          ** data is not required. So first try to lookup the overflow
 64340          ** page-list cache, if any, then fall back to the getOverflowPage()
 64341          ** function.
 64342          */
 64343          assert( pCur->curFlags & BTCF_ValidOvfl );
 64344          assert( pCur->pBtree->db==pBt->db );
 64345          if( pCur->aOverflow[iIdx+1] ){
 64346            nextPage = pCur->aOverflow[iIdx+1];
 64347          }else{
 64348            rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
 64349          }
 64350          offset -= ovflSize;
 64351        }else{
 64352          /* Need to read this page properly. It contains some of the
 64353          ** range of data that is being read (eOp==0) or written (eOp!=0).
 64354          */
 64355  #ifdef SQLITE_DIRECT_OVERFLOW_READ
 64356          sqlite3_file *fd;      /* File from which to do direct overflow read */
 64357  #endif
 64358          int a = amt;
 64359          if( a + offset > ovflSize ){
 64360            a = ovflSize - offset;
 64361          }
 64362  
 64363  #ifdef SQLITE_DIRECT_OVERFLOW_READ
 64364          /* If all the following are true:
 64365          **
 64366          **   1) this is a read operation, and 
 64367          **   2) data is required from the start of this overflow page, and
 64368          **   3) there is no open write-transaction, and
 64369          **   4) the database is file-backed, and
 64370          **   5) the page is not in the WAL file
 64371          **   6) at least 4 bytes have already been read into the output buffer 
 64372          **
 64373          ** then data can be read directly from the database file into the
 64374          ** output buffer, bypassing the page-cache altogether. This speeds
 64375          ** up loading large records that span many overflow pages.
 64376          */
 64377          if( eOp==0                                             /* (1) */
 64378           && offset==0                                          /* (2) */
 64379           && pBt->inTransaction==TRANS_READ                     /* (3) */
 64380           && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (4) */
 64381           && 0==sqlite3PagerUseWal(pBt->pPager, nextPage)       /* (5) */
 64382           && &pBuf[-4]>=pBufStart                               /* (6) */
 64383          ){
 64384            u8 aSave[4];
 64385            u8 *aWrite = &pBuf[-4];
 64386            assert( aWrite>=pBufStart );                         /* due to (6) */
 64387            memcpy(aSave, aWrite, 4);
 64388            rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
 64389            nextPage = get4byte(aWrite);
 64390            memcpy(aWrite, aSave, 4);
 64391          }else
 64392  #endif
 64393  
 64394          {
 64395            DbPage *pDbPage;
 64396            rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
 64397                (eOp==0 ? PAGER_GET_READONLY : 0)
 64398            );
 64399            if( rc==SQLITE_OK ){
 64400              aPayload = sqlite3PagerGetData(pDbPage);
 64401              nextPage = get4byte(aPayload);
 64402              rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
 64403              sqlite3PagerUnref(pDbPage);
 64404              offset = 0;
 64405            }
 64406          }
 64407          amt -= a;
 64408          if( amt==0 ) return rc;
 64409          pBuf += a;
 64410        }
 64411        if( rc ) break;
 64412        iIdx++;
 64413      }
 64414    }
 64415  
 64416    if( rc==SQLITE_OK && amt>0 ){
 64417      /* Overflow chain ends prematurely */
 64418      return SQLITE_CORRUPT_PGNO(pPage->pgno);
 64419    }
 64420    return rc;
 64421  }
 64422  
 64423  /*
 64424  ** Read part of the payload for the row at which that cursor pCur is currently
 64425  ** pointing.  "amt" bytes will be transferred into pBuf[].  The transfer
 64426  ** begins at "offset".
 64427  **
 64428  ** pCur can be pointing to either a table or an index b-tree.
 64429  ** If pointing to a table btree, then the content section is read.  If
 64430  ** pCur is pointing to an index b-tree then the key section is read.
 64431  **
 64432  ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
 64433  ** to a valid row in the table.  For sqlite3BtreePayloadChecked(), the
 64434  ** cursor might be invalid or might need to be restored before being read.
 64435  **
 64436  ** Return SQLITE_OK on success or an error code if anything goes
 64437  ** wrong.  An error is returned if "offset+amt" is larger than
 64438  ** the available payload.
 64439  */
 64440  SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
 64441    assert( cursorHoldsMutex(pCur) );
 64442    assert( pCur->eState==CURSOR_VALID );
 64443    assert( pCur->iPage>=0 && pCur->pPage );
 64444    assert( pCur->ix<pCur->pPage->nCell );
 64445    return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
 64446  }
 64447  
 64448  /*
 64449  ** This variant of sqlite3BtreePayload() works even if the cursor has not
 64450  ** in the CURSOR_VALID state.  It is only used by the sqlite3_blob_read()
 64451  ** interface.
 64452  */
 64453  #ifndef SQLITE_OMIT_INCRBLOB
 64454  static SQLITE_NOINLINE int accessPayloadChecked(
 64455    BtCursor *pCur,
 64456    u32 offset,
 64457    u32 amt,
 64458    void *pBuf
 64459  ){
 64460    int rc;
 64461    if ( pCur->eState==CURSOR_INVALID ){
 64462      return SQLITE_ABORT;
 64463    }
 64464    assert( cursorOwnsBtShared(pCur) );
 64465    rc = btreeRestoreCursorPosition(pCur);
 64466    return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
 64467  }
 64468  SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
 64469    if( pCur->eState==CURSOR_VALID ){
 64470      assert( cursorOwnsBtShared(pCur) );
 64471      return accessPayload(pCur, offset, amt, pBuf, 0);
 64472    }else{
 64473      return accessPayloadChecked(pCur, offset, amt, pBuf);
 64474    }
 64475  }
 64476  #endif /* SQLITE_OMIT_INCRBLOB */
 64477  
 64478  /*
 64479  ** Return a pointer to payload information from the entry that the 
 64480  ** pCur cursor is pointing to.  The pointer is to the beginning of
 64481  ** the key if index btrees (pPage->intKey==0) and is the data for
 64482  ** table btrees (pPage->intKey==1). The number of bytes of available
 64483  ** key/data is written into *pAmt.  If *pAmt==0, then the value
 64484  ** returned will not be a valid pointer.
 64485  **
 64486  ** This routine is an optimization.  It is common for the entire key
 64487  ** and data to fit on the local page and for there to be no overflow
 64488  ** pages.  When that is so, this routine can be used to access the
 64489  ** key and data without making a copy.  If the key and/or data spills
 64490  ** onto overflow pages, then accessPayload() must be used to reassemble
 64491  ** the key/data and copy it into a preallocated buffer.
 64492  **
 64493  ** The pointer returned by this routine looks directly into the cached
 64494  ** page of the database.  The data might change or move the next time
 64495  ** any btree routine is called.
 64496  */
 64497  static const void *fetchPayload(
 64498    BtCursor *pCur,      /* Cursor pointing to entry to read from */
 64499    u32 *pAmt            /* Write the number of available bytes here */
 64500  ){
 64501    int amt;
 64502    assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
 64503    assert( pCur->eState==CURSOR_VALID );
 64504    assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
 64505    assert( cursorOwnsBtShared(pCur) );
 64506    assert( pCur->ix<pCur->pPage->nCell );
 64507    assert( pCur->info.nSize>0 );
 64508    assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
 64509    assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
 64510    amt = pCur->info.nLocal;
 64511    if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
 64512      /* There is too little space on the page for the expected amount
 64513      ** of local content. Database must be corrupt. */
 64514      assert( CORRUPT_DB );
 64515      amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
 64516    }
 64517    *pAmt = (u32)amt;
 64518    return (void*)pCur->info.pPayload;
 64519  }
 64520  
 64521  
 64522  /*
 64523  ** For the entry that cursor pCur is point to, return as
 64524  ** many bytes of the key or data as are available on the local
 64525  ** b-tree page.  Write the number of available bytes into *pAmt.
 64526  **
 64527  ** The pointer returned is ephemeral.  The key/data may move
 64528  ** or be destroyed on the next call to any Btree routine,
 64529  ** including calls from other threads against the same cache.
 64530  ** Hence, a mutex on the BtShared should be held prior to calling
 64531  ** this routine.
 64532  **
 64533  ** These routines is used to get quick access to key and data
 64534  ** in the common case where no overflow pages are used.
 64535  */
 64536  SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
 64537    return fetchPayload(pCur, pAmt);
 64538  }
 64539  
 64540  
 64541  /*
 64542  ** Move the cursor down to a new child page.  The newPgno argument is the
 64543  ** page number of the child page to move to.
 64544  **
 64545  ** This function returns SQLITE_CORRUPT if the page-header flags field of
 64546  ** the new child page does not match the flags field of the parent (i.e.
 64547  ** if an intkey page appears to be the parent of a non-intkey page, or
 64548  ** vice-versa).
 64549  */
 64550  static int moveToChild(BtCursor *pCur, u32 newPgno){
 64551    BtShared *pBt = pCur->pBt;
 64552  
 64553    assert( cursorOwnsBtShared(pCur) );
 64554    assert( pCur->eState==CURSOR_VALID );
 64555    assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
 64556    assert( pCur->iPage>=0 );
 64557    if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
 64558      return SQLITE_CORRUPT_BKPT;
 64559    }
 64560    pCur->info.nSize = 0;
 64561    pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
 64562    pCur->aiIdx[pCur->iPage] = pCur->ix;
 64563    pCur->apPage[pCur->iPage] = pCur->pPage;
 64564    pCur->ix = 0;
 64565    pCur->iPage++;
 64566    return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
 64567  }
 64568  
 64569  #ifdef SQLITE_DEBUG
 64570  /*
 64571  ** Page pParent is an internal (non-leaf) tree page. This function 
 64572  ** asserts that page number iChild is the left-child if the iIdx'th
 64573  ** cell in page pParent. Or, if iIdx is equal to the total number of
 64574  ** cells in pParent, that page number iChild is the right-child of
 64575  ** the page.
 64576  */
 64577  static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
 64578    if( CORRUPT_DB ) return;  /* The conditions tested below might not be true
 64579                              ** in a corrupt database */
 64580    assert( iIdx<=pParent->nCell );
 64581    if( iIdx==pParent->nCell ){
 64582      assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
 64583    }else{
 64584      assert( get4byte(findCell(pParent, iIdx))==iChild );
 64585    }
 64586  }
 64587  #else
 64588  #  define assertParentIndex(x,y,z) 
 64589  #endif
 64590  
 64591  /*
 64592  ** Move the cursor up to the parent page.
 64593  **
 64594  ** pCur->idx is set to the cell index that contains the pointer
 64595  ** to the page we are coming from.  If we are coming from the
 64596  ** right-most child page then pCur->idx is set to one more than
 64597  ** the largest cell index.
 64598  */
 64599  static void moveToParent(BtCursor *pCur){
 64600    MemPage *pLeaf;
 64601    assert( cursorOwnsBtShared(pCur) );
 64602    assert( pCur->eState==CURSOR_VALID );
 64603    assert( pCur->iPage>0 );
 64604    assert( pCur->pPage );
 64605    assertParentIndex(
 64606      pCur->apPage[pCur->iPage-1], 
 64607      pCur->aiIdx[pCur->iPage-1], 
 64608      pCur->pPage->pgno
 64609    );
 64610    testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
 64611    pCur->info.nSize = 0;
 64612    pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
 64613    pCur->ix = pCur->aiIdx[pCur->iPage-1];
 64614    pLeaf = pCur->pPage;
 64615    pCur->pPage = pCur->apPage[--pCur->iPage];
 64616    releasePageNotNull(pLeaf);
 64617  }
 64618  
 64619  /*
 64620  ** Move the cursor to point to the root page of its b-tree structure.
 64621  **
 64622  ** If the table has a virtual root page, then the cursor is moved to point
 64623  ** to the virtual root page instead of the actual root page. A table has a
 64624  ** virtual root page when the actual root page contains no cells and a 
 64625  ** single child page. This can only happen with the table rooted at page 1.
 64626  **
 64627  ** If the b-tree structure is empty, the cursor state is set to 
 64628  ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
 64629  ** the cursor is set to point to the first cell located on the root
 64630  ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
 64631  **
 64632  ** If this function returns successfully, it may be assumed that the
 64633  ** page-header flags indicate that the [virtual] root-page is the expected 
 64634  ** kind of b-tree page (i.e. if when opening the cursor the caller did not
 64635  ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
 64636  ** indicating a table b-tree, or if the caller did specify a KeyInfo 
 64637  ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
 64638  ** b-tree).
 64639  */
 64640  static int moveToRoot(BtCursor *pCur){
 64641    MemPage *pRoot;
 64642    int rc = SQLITE_OK;
 64643  
 64644    assert( cursorOwnsBtShared(pCur) );
 64645    assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
 64646    assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
 64647    assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
 64648    assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
 64649    assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
 64650  
 64651    if( pCur->iPage>=0 ){
 64652      if( pCur->iPage ){
 64653        releasePageNotNull(pCur->pPage);
 64654        while( --pCur->iPage ){
 64655          releasePageNotNull(pCur->apPage[pCur->iPage]);
 64656        }
 64657        pCur->pPage = pCur->apPage[0];
 64658        goto skip_init;
 64659      }
 64660    }else if( pCur->pgnoRoot==0 ){
 64661      pCur->eState = CURSOR_INVALID;
 64662      return SQLITE_EMPTY;
 64663    }else{
 64664      assert( pCur->iPage==(-1) );
 64665      if( pCur->eState>=CURSOR_REQUIRESEEK ){
 64666        if( pCur->eState==CURSOR_FAULT ){
 64667          assert( pCur->skipNext!=SQLITE_OK );
 64668          return pCur->skipNext;
 64669        }
 64670        sqlite3BtreeClearCursor(pCur);
 64671      }
 64672      rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
 64673                          0, pCur->curPagerFlags);
 64674      if( rc!=SQLITE_OK ){
 64675        pCur->eState = CURSOR_INVALID;
 64676        return rc;
 64677      }
 64678      pCur->iPage = 0;
 64679      pCur->curIntKey = pCur->pPage->intKey;
 64680    }
 64681    pRoot = pCur->pPage;
 64682    assert( pRoot->pgno==pCur->pgnoRoot );
 64683  
 64684    /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
 64685    ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
 64686    ** NULL, the caller expects a table b-tree. If this is not the case,
 64687    ** return an SQLITE_CORRUPT error. 
 64688    **
 64689    ** Earlier versions of SQLite assumed that this test could not fail
 64690    ** if the root page was already loaded when this function was called (i.e.
 64691    ** if pCur->iPage>=0). But this is not so if the database is corrupted 
 64692    ** in such a way that page pRoot is linked into a second b-tree table 
 64693    ** (or the freelist).  */
 64694    assert( pRoot->intKey==1 || pRoot->intKey==0 );
 64695    if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
 64696      return SQLITE_CORRUPT_PGNO(pCur->pPage->pgno);
 64697    }
 64698  
 64699  skip_init:  
 64700    pCur->ix = 0;
 64701    pCur->info.nSize = 0;
 64702    pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
 64703  
 64704    pRoot = pCur->pPage;
 64705    if( pRoot->nCell>0 ){
 64706      pCur->eState = CURSOR_VALID;
 64707    }else if( !pRoot->leaf ){
 64708      Pgno subpage;
 64709      if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
 64710      subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
 64711      pCur->eState = CURSOR_VALID;
 64712      rc = moveToChild(pCur, subpage);
 64713    }else{
 64714      pCur->eState = CURSOR_INVALID;
 64715      rc = SQLITE_EMPTY;
 64716    }
 64717    return rc;
 64718  }
 64719  
 64720  /*
 64721  ** Move the cursor down to the left-most leaf entry beneath the
 64722  ** entry to which it is currently pointing.
 64723  **
 64724  ** The left-most leaf is the one with the smallest key - the first
 64725  ** in ascending order.
 64726  */
 64727  static int moveToLeftmost(BtCursor *pCur){
 64728    Pgno pgno;
 64729    int rc = SQLITE_OK;
 64730    MemPage *pPage;
 64731  
 64732    assert( cursorOwnsBtShared(pCur) );
 64733    assert( pCur->eState==CURSOR_VALID );
 64734    while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
 64735      assert( pCur->ix<pPage->nCell );
 64736      pgno = get4byte(findCell(pPage, pCur->ix));
 64737      rc = moveToChild(pCur, pgno);
 64738    }
 64739    return rc;
 64740  }
 64741  
 64742  /*
 64743  ** Move the cursor down to the right-most leaf entry beneath the
 64744  ** page to which it is currently pointing.  Notice the difference
 64745  ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
 64746  ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
 64747  ** finds the right-most entry beneath the *page*.
 64748  **
 64749  ** The right-most entry is the one with the largest key - the last
 64750  ** key in ascending order.
 64751  */
 64752  static int moveToRightmost(BtCursor *pCur){
 64753    Pgno pgno;
 64754    int rc = SQLITE_OK;
 64755    MemPage *pPage = 0;
 64756  
 64757    assert( cursorOwnsBtShared(pCur) );
 64758    assert( pCur->eState==CURSOR_VALID );
 64759    while( !(pPage = pCur->pPage)->leaf ){
 64760      pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
 64761      pCur->ix = pPage->nCell;
 64762      rc = moveToChild(pCur, pgno);
 64763      if( rc ) return rc;
 64764    }
 64765    pCur->ix = pPage->nCell-1;
 64766    assert( pCur->info.nSize==0 );
 64767    assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
 64768    return SQLITE_OK;
 64769  }
 64770  
 64771  /* Move the cursor to the first entry in the table.  Return SQLITE_OK
 64772  ** on success.  Set *pRes to 0 if the cursor actually points to something
 64773  ** or set *pRes to 1 if the table is empty.
 64774  */
 64775  SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
 64776    int rc;
 64777  
 64778    assert( cursorOwnsBtShared(pCur) );
 64779    assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
 64780    rc = moveToRoot(pCur);
 64781    if( rc==SQLITE_OK ){
 64782      assert( pCur->pPage->nCell>0 );
 64783      *pRes = 0;
 64784      rc = moveToLeftmost(pCur);
 64785    }else if( rc==SQLITE_EMPTY ){
 64786      assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
 64787      *pRes = 1;
 64788      rc = SQLITE_OK;
 64789    }
 64790    return rc;
 64791  }
 64792  
 64793  /* Move the cursor to the last entry in the table.  Return SQLITE_OK
 64794  ** on success.  Set *pRes to 0 if the cursor actually points to something
 64795  ** or set *pRes to 1 if the table is empty.
 64796  */
 64797  SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
 64798    int rc;
 64799   
 64800    assert( cursorOwnsBtShared(pCur) );
 64801    assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
 64802  
 64803    /* If the cursor already points to the last entry, this is a no-op. */
 64804    if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
 64805  #ifdef SQLITE_DEBUG
 64806      /* This block serves to assert() that the cursor really does point 
 64807      ** to the last entry in the b-tree. */
 64808      int ii;
 64809      for(ii=0; ii<pCur->iPage; ii++){
 64810        assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
 64811      }
 64812      assert( pCur->ix==pCur->pPage->nCell-1 );
 64813      assert( pCur->pPage->leaf );
 64814  #endif
 64815      return SQLITE_OK;
 64816    }
 64817  
 64818    rc = moveToRoot(pCur);
 64819    if( rc==SQLITE_OK ){
 64820      assert( pCur->eState==CURSOR_VALID );
 64821      *pRes = 0;
 64822      rc = moveToRightmost(pCur);
 64823      if( rc==SQLITE_OK ){
 64824        pCur->curFlags |= BTCF_AtLast;
 64825      }else{
 64826        pCur->curFlags &= ~BTCF_AtLast;
 64827      }
 64828    }else if( rc==SQLITE_EMPTY ){
 64829      assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
 64830      *pRes = 1;
 64831      rc = SQLITE_OK;
 64832    }
 64833    return rc;
 64834  }
 64835  
 64836  /* Move the cursor so that it points to an entry near the key 
 64837  ** specified by pIdxKey or intKey.   Return a success code.
 64838  **
 64839  ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
 64840  ** must be NULL.  For index tables, pIdxKey is used and intKey
 64841  ** is ignored.
 64842  **
 64843  ** If an exact match is not found, then the cursor is always
 64844  ** left pointing at a leaf page which would hold the entry if it
 64845  ** were present.  The cursor might point to an entry that comes
 64846  ** before or after the key.
 64847  **
 64848  ** An integer is written into *pRes which is the result of
 64849  ** comparing the key with the entry to which the cursor is 
 64850  ** pointing.  The meaning of the integer written into
 64851  ** *pRes is as follows:
 64852  **
 64853  **     *pRes<0      The cursor is left pointing at an entry that
 64854  **                  is smaller than intKey/pIdxKey or if the table is empty
 64855  **                  and the cursor is therefore left point to nothing.
 64856  **
 64857  **     *pRes==0     The cursor is left pointing at an entry that
 64858  **                  exactly matches intKey/pIdxKey.
 64859  **
 64860  **     *pRes>0      The cursor is left pointing at an entry that
 64861  **                  is larger than intKey/pIdxKey.
 64862  **
 64863  ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
 64864  ** exists an entry in the table that exactly matches pIdxKey.  
 64865  */
 64866  SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
 64867    BtCursor *pCur,          /* The cursor to be moved */
 64868    UnpackedRecord *pIdxKey, /* Unpacked index key */
 64869    i64 intKey,              /* The table key */
 64870    int biasRight,           /* If true, bias the search to the high end */
 64871    int *pRes                /* Write search results here */
 64872  ){
 64873    int rc;
 64874    RecordCompare xRecordCompare;
 64875  
 64876    assert( cursorOwnsBtShared(pCur) );
 64877    assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
 64878    assert( pRes );
 64879    assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
 64880    assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
 64881  
 64882    /* If the cursor is already positioned at the point we are trying
 64883    ** to move to, then just return without doing any work */
 64884    if( pIdxKey==0
 64885     && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
 64886    ){
 64887      if( pCur->info.nKey==intKey ){
 64888        *pRes = 0;
 64889        return SQLITE_OK;
 64890      }
 64891      if( pCur->info.nKey<intKey ){
 64892        if( (pCur->curFlags & BTCF_AtLast)!=0 ){
 64893          *pRes = -1;
 64894          return SQLITE_OK;
 64895        }
 64896        /* If the requested key is one more than the previous key, then
 64897        ** try to get there using sqlite3BtreeNext() rather than a full
 64898        ** binary search.  This is an optimization only.  The correct answer
 64899        ** is still obtained without this case, only a little more slowely */
 64900        if( pCur->info.nKey+1==intKey && !pCur->skipNext ){
 64901          *pRes = 0;
 64902          rc = sqlite3BtreeNext(pCur, 0);
 64903          if( rc==SQLITE_OK ){
 64904            getCellInfo(pCur);
 64905            if( pCur->info.nKey==intKey ){
 64906              return SQLITE_OK;
 64907            }
 64908          }else if( rc==SQLITE_DONE ){
 64909            rc = SQLITE_OK;
 64910          }else{
 64911            return rc;
 64912          }
 64913        }
 64914      }
 64915    }
 64916  
 64917    if( pIdxKey ){
 64918      xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
 64919      pIdxKey->errCode = 0;
 64920      assert( pIdxKey->default_rc==1 
 64921           || pIdxKey->default_rc==0 
 64922           || pIdxKey->default_rc==-1
 64923      );
 64924    }else{
 64925      xRecordCompare = 0; /* All keys are integers */
 64926    }
 64927  
 64928    rc = moveToRoot(pCur);
 64929    if( rc ){
 64930      if( rc==SQLITE_EMPTY ){
 64931        assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
 64932        *pRes = -1;
 64933        return SQLITE_OK;
 64934      }
 64935      return rc;
 64936    }
 64937    assert( pCur->pPage );
 64938    assert( pCur->pPage->isInit );
 64939    assert( pCur->eState==CURSOR_VALID );
 64940    assert( pCur->pPage->nCell > 0 );
 64941    assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
 64942    assert( pCur->curIntKey || pIdxKey );
 64943    for(;;){
 64944      int lwr, upr, idx, c;
 64945      Pgno chldPg;
 64946      MemPage *pPage = pCur->pPage;
 64947      u8 *pCell;                          /* Pointer to current cell in pPage */
 64948  
 64949      /* pPage->nCell must be greater than zero. If this is the root-page
 64950      ** the cursor would have been INVALID above and this for(;;) loop
 64951      ** not run. If this is not the root-page, then the moveToChild() routine
 64952      ** would have already detected db corruption. Similarly, pPage must
 64953      ** be the right kind (index or table) of b-tree page. Otherwise
 64954      ** a moveToChild() or moveToRoot() call would have detected corruption.  */
 64955      assert( pPage->nCell>0 );
 64956      assert( pPage->intKey==(pIdxKey==0) );
 64957      lwr = 0;
 64958      upr = pPage->nCell-1;
 64959      assert( biasRight==0 || biasRight==1 );
 64960      idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
 64961      pCur->ix = (u16)idx;
 64962      if( xRecordCompare==0 ){
 64963        for(;;){
 64964          i64 nCellKey;
 64965          pCell = findCellPastPtr(pPage, idx);
 64966          if( pPage->intKeyLeaf ){
 64967            while( 0x80 <= *(pCell++) ){
 64968              if( pCell>=pPage->aDataEnd ){
 64969                return SQLITE_CORRUPT_PGNO(pPage->pgno);
 64970              }
 64971            }
 64972          }
 64973          getVarint(pCell, (u64*)&nCellKey);
 64974          if( nCellKey<intKey ){
 64975            lwr = idx+1;
 64976            if( lwr>upr ){ c = -1; break; }
 64977          }else if( nCellKey>intKey ){
 64978            upr = idx-1;
 64979            if( lwr>upr ){ c = +1; break; }
 64980          }else{
 64981            assert( nCellKey==intKey );
 64982            pCur->ix = (u16)idx;
 64983            if( !pPage->leaf ){
 64984              lwr = idx;
 64985              goto moveto_next_layer;
 64986            }else{
 64987              pCur->curFlags |= BTCF_ValidNKey;
 64988              pCur->info.nKey = nCellKey;
 64989              pCur->info.nSize = 0;
 64990              *pRes = 0;
 64991              return SQLITE_OK;
 64992            }
 64993          }
 64994          assert( lwr+upr>=0 );
 64995          idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
 64996        }
 64997      }else{
 64998        for(;;){
 64999          int nCell;  /* Size of the pCell cell in bytes */
 65000          pCell = findCellPastPtr(pPage, idx);
 65001  
 65002          /* The maximum supported page-size is 65536 bytes. This means that
 65003          ** the maximum number of record bytes stored on an index B-Tree
 65004          ** page is less than 16384 bytes and may be stored as a 2-byte
 65005          ** varint. This information is used to attempt to avoid parsing 
 65006          ** the entire cell by checking for the cases where the record is 
 65007          ** stored entirely within the b-tree page by inspecting the first 
 65008          ** 2 bytes of the cell.
 65009          */
 65010          nCell = pCell[0];
 65011          if( nCell<=pPage->max1bytePayload ){
 65012            /* This branch runs if the record-size field of the cell is a
 65013            ** single byte varint and the record fits entirely on the main
 65014            ** b-tree page.  */
 65015            testcase( pCell+nCell+1==pPage->aDataEnd );
 65016            c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
 65017          }else if( !(pCell[1] & 0x80) 
 65018            && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
 65019          ){
 65020            /* The record-size field is a 2 byte varint and the record 
 65021            ** fits entirely on the main b-tree page.  */
 65022            testcase( pCell+nCell+2==pPage->aDataEnd );
 65023            c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
 65024          }else{
 65025            /* The record flows over onto one or more overflow pages. In
 65026            ** this case the whole cell needs to be parsed, a buffer allocated
 65027            ** and accessPayload() used to retrieve the record into the
 65028            ** buffer before VdbeRecordCompare() can be called. 
 65029            **
 65030            ** If the record is corrupt, the xRecordCompare routine may read
 65031            ** up to two varints past the end of the buffer. An extra 18 
 65032            ** bytes of padding is allocated at the end of the buffer in
 65033            ** case this happens.  */
 65034            void *pCellKey;
 65035            u8 * const pCellBody = pCell - pPage->childPtrSize;
 65036            pPage->xParseCell(pPage, pCellBody, &pCur->info);
 65037            nCell = (int)pCur->info.nKey;
 65038            testcase( nCell<0 );   /* True if key size is 2^32 or more */
 65039            testcase( nCell==0 );  /* Invalid key size:  0x80 0x80 0x00 */
 65040            testcase( nCell==1 );  /* Invalid key size:  0x80 0x80 0x01 */
 65041            testcase( nCell==2 );  /* Minimum legal index key size */
 65042            if( nCell<2 ){
 65043              rc = SQLITE_CORRUPT_PGNO(pPage->pgno);
 65044              goto moveto_finish;
 65045            }
 65046            pCellKey = sqlite3Malloc( nCell+18 );
 65047            if( pCellKey==0 ){
 65048              rc = SQLITE_NOMEM_BKPT;
 65049              goto moveto_finish;
 65050            }
 65051            pCur->ix = (u16)idx;
 65052            rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
 65053            pCur->curFlags &= ~BTCF_ValidOvfl;
 65054            if( rc ){
 65055              sqlite3_free(pCellKey);
 65056              goto moveto_finish;
 65057            }
 65058            c = xRecordCompare(nCell, pCellKey, pIdxKey);
 65059            sqlite3_free(pCellKey);
 65060          }
 65061          assert( 
 65062              (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
 65063           && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
 65064          );
 65065          if( c<0 ){
 65066            lwr = idx+1;
 65067          }else if( c>0 ){
 65068            upr = idx-1;
 65069          }else{
 65070            assert( c==0 );
 65071            *pRes = 0;
 65072            rc = SQLITE_OK;
 65073            pCur->ix = (u16)idx;
 65074            if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
 65075            goto moveto_finish;
 65076          }
 65077          if( lwr>upr ) break;
 65078          assert( lwr+upr>=0 );
 65079          idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
 65080        }
 65081      }
 65082      assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
 65083      assert( pPage->isInit );
 65084      if( pPage->leaf ){
 65085        assert( pCur->ix<pCur->pPage->nCell );
 65086        pCur->ix = (u16)idx;
 65087        *pRes = c;
 65088        rc = SQLITE_OK;
 65089        goto moveto_finish;
 65090      }
 65091  moveto_next_layer:
 65092      if( lwr>=pPage->nCell ){
 65093        chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
 65094      }else{
 65095        chldPg = get4byte(findCell(pPage, lwr));
 65096      }
 65097      pCur->ix = (u16)lwr;
 65098      rc = moveToChild(pCur, chldPg);
 65099      if( rc ) break;
 65100    }
 65101  moveto_finish:
 65102    pCur->info.nSize = 0;
 65103    assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
 65104    return rc;
 65105  }
 65106  
 65107  
 65108  /*
 65109  ** Return TRUE if the cursor is not pointing at an entry of the table.
 65110  **
 65111  ** TRUE will be returned after a call to sqlite3BtreeNext() moves
 65112  ** past the last entry in the table or sqlite3BtreePrev() moves past
 65113  ** the first entry.  TRUE is also returned if the table is empty.
 65114  */
 65115  SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
 65116    /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
 65117    ** have been deleted? This API will need to change to return an error code
 65118    ** as well as the boolean result value.
 65119    */
 65120    return (CURSOR_VALID!=pCur->eState);
 65121  }
 65122  
 65123  /*
 65124  ** Return an estimate for the number of rows in the table that pCur is
 65125  ** pointing to.  Return a negative number if no estimate is currently 
 65126  ** available.
 65127  */
 65128  SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
 65129    i64 n;
 65130    u8 i;
 65131  
 65132    assert( cursorOwnsBtShared(pCur) );
 65133    assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
 65134  
 65135    /* Currently this interface is only called by the OP_IfSmaller
 65136    ** opcode, and it that case the cursor will always be valid and
 65137    ** will always point to a leaf node. */
 65138    if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
 65139    if( NEVER(pCur->pPage->leaf==0) ) return -1;
 65140  
 65141    n = pCur->pPage->nCell;
 65142    for(i=0; i<pCur->iPage; i++){
 65143      n *= pCur->apPage[i]->nCell;
 65144    }
 65145    return n;
 65146  }
 65147  
 65148  /*
 65149  ** Advance the cursor to the next entry in the database. 
 65150  ** Return value:
 65151  **
 65152  **    SQLITE_OK        success
 65153  **    SQLITE_DONE      cursor is already pointing at the last element
 65154  **    otherwise        some kind of error occurred
 65155  **
 65156  ** The main entry point is sqlite3BtreeNext().  That routine is optimized
 65157  ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
 65158  ** to the next cell on the current page.  The (slower) btreeNext() helper
 65159  ** routine is called when it is necessary to move to a different page or
 65160  ** to restore the cursor.
 65161  **
 65162  ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
 65163  ** cursor corresponds to an SQL index and this routine could have been
 65164  ** skipped if the SQL index had been a unique index.  The F argument
 65165  ** is a hint to the implement.  SQLite btree implementation does not use
 65166  ** this hint, but COMDB2 does.
 65167  */
 65168  static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
 65169    int rc;
 65170    int idx;
 65171    MemPage *pPage;
 65172  
 65173    assert( cursorOwnsBtShared(pCur) );
 65174    assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
 65175    if( pCur->eState!=CURSOR_VALID ){
 65176      assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
 65177      rc = restoreCursorPosition(pCur);
 65178      if( rc!=SQLITE_OK ){
 65179        return rc;
 65180      }
 65181      if( CURSOR_INVALID==pCur->eState ){
 65182        return SQLITE_DONE;
 65183      }
 65184      if( pCur->skipNext ){
 65185        assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
 65186        pCur->eState = CURSOR_VALID;
 65187        if( pCur->skipNext>0 ){
 65188          pCur->skipNext = 0;
 65189          return SQLITE_OK;
 65190        }
 65191        pCur->skipNext = 0;
 65192      }
 65193    }
 65194  
 65195    pPage = pCur->pPage;
 65196    idx = ++pCur->ix;
 65197    assert( pPage->isInit );
 65198  
 65199    /* If the database file is corrupt, it is possible for the value of idx 
 65200    ** to be invalid here. This can only occur if a second cursor modifies
 65201    ** the page while cursor pCur is holding a reference to it. Which can
 65202    ** only happen if the database is corrupt in such a way as to link the
 65203    ** page into more than one b-tree structure. */
 65204    testcase( idx>pPage->nCell );
 65205  
 65206    if( idx>=pPage->nCell ){
 65207      if( !pPage->leaf ){
 65208        rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
 65209        if( rc ) return rc;
 65210        return moveToLeftmost(pCur);
 65211      }
 65212      do{
 65213        if( pCur->iPage==0 ){
 65214          pCur->eState = CURSOR_INVALID;
 65215          return SQLITE_DONE;
 65216        }
 65217        moveToParent(pCur);
 65218        pPage = pCur->pPage;
 65219      }while( pCur->ix>=pPage->nCell );
 65220      if( pPage->intKey ){
 65221        return sqlite3BtreeNext(pCur, 0);
 65222      }else{
 65223        return SQLITE_OK;
 65224      }
 65225    }
 65226    if( pPage->leaf ){
 65227      return SQLITE_OK;
 65228    }else{
 65229      return moveToLeftmost(pCur);
 65230    }
 65231  }
 65232  SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int flags){
 65233    MemPage *pPage;
 65234    UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
 65235    assert( cursorOwnsBtShared(pCur) );
 65236    assert( flags==0 || flags==1 );
 65237    assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
 65238    pCur->info.nSize = 0;
 65239    pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
 65240    if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
 65241    pPage = pCur->pPage;
 65242    if( (++pCur->ix)>=pPage->nCell ){
 65243      pCur->ix--;
 65244      return btreeNext(pCur);
 65245    }
 65246    if( pPage->leaf ){
 65247      return SQLITE_OK;
 65248    }else{
 65249      return moveToLeftmost(pCur);
 65250    }
 65251  }
 65252  
 65253  /*
 65254  ** Step the cursor to the back to the previous entry in the database.
 65255  ** Return values:
 65256  **
 65257  **     SQLITE_OK     success
 65258  **     SQLITE_DONE   the cursor is already on the first element of the table
 65259  **     otherwise     some kind of error occurred
 65260  **
 65261  ** The main entry point is sqlite3BtreePrevious().  That routine is optimized
 65262  ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
 65263  ** to the previous cell on the current page.  The (slower) btreePrevious()
 65264  ** helper routine is called when it is necessary to move to a different page
 65265  ** or to restore the cursor.
 65266  **
 65267  ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
 65268  ** the cursor corresponds to an SQL index and this routine could have been
 65269  ** skipped if the SQL index had been a unique index.  The F argument is a
 65270  ** hint to the implement.  The native SQLite btree implementation does not
 65271  ** use this hint, but COMDB2 does.
 65272  */
 65273  static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
 65274    int rc;
 65275    MemPage *pPage;
 65276  
 65277    assert( cursorOwnsBtShared(pCur) );
 65278    assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
 65279    assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
 65280    assert( pCur->info.nSize==0 );
 65281    if( pCur->eState!=CURSOR_VALID ){
 65282      rc = restoreCursorPosition(pCur);
 65283      if( rc!=SQLITE_OK ){
 65284        return rc;
 65285      }
 65286      if( CURSOR_INVALID==pCur->eState ){
 65287        return SQLITE_DONE;
 65288      }
 65289      if( pCur->skipNext ){
 65290        assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
 65291        pCur->eState = CURSOR_VALID;
 65292        if( pCur->skipNext<0 ){
 65293          pCur->skipNext = 0;
 65294          return SQLITE_OK;
 65295        }
 65296        pCur->skipNext = 0;
 65297      }
 65298    }
 65299  
 65300    pPage = pCur->pPage;
 65301    assert( pPage->isInit );
 65302    if( !pPage->leaf ){
 65303      int idx = pCur->ix;
 65304      rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
 65305      if( rc ) return rc;
 65306      rc = moveToRightmost(pCur);
 65307    }else{
 65308      while( pCur->ix==0 ){
 65309        if( pCur->iPage==0 ){
 65310          pCur->eState = CURSOR_INVALID;
 65311          return SQLITE_DONE;
 65312        }
 65313        moveToParent(pCur);
 65314      }
 65315      assert( pCur->info.nSize==0 );
 65316      assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
 65317  
 65318      pCur->ix--;
 65319      pPage = pCur->pPage;
 65320      if( pPage->intKey && !pPage->leaf ){
 65321        rc = sqlite3BtreePrevious(pCur, 0);
 65322      }else{
 65323        rc = SQLITE_OK;
 65324      }
 65325    }
 65326    return rc;
 65327  }
 65328  SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int flags){
 65329    assert( cursorOwnsBtShared(pCur) );
 65330    assert( flags==0 || flags==1 );
 65331    assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
 65332    UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
 65333    pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
 65334    pCur->info.nSize = 0;
 65335    if( pCur->eState!=CURSOR_VALID
 65336     || pCur->ix==0
 65337     || pCur->pPage->leaf==0
 65338    ){
 65339      return btreePrevious(pCur);
 65340    }
 65341    pCur->ix--;
 65342    return SQLITE_OK;
 65343  }
 65344  
 65345  /*
 65346  ** Allocate a new page from the database file.
 65347  **
 65348  ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
 65349  ** has already been called on the new page.)  The new page has also
 65350  ** been referenced and the calling routine is responsible for calling
 65351  ** sqlite3PagerUnref() on the new page when it is done.
 65352  **
 65353  ** SQLITE_OK is returned on success.  Any other return value indicates
 65354  ** an error.  *ppPage is set to NULL in the event of an error.
 65355  **
 65356  ** If the "nearby" parameter is not 0, then an effort is made to 
 65357  ** locate a page close to the page number "nearby".  This can be used in an
 65358  ** attempt to keep related pages close to each other in the database file,
 65359  ** which in turn can make database access faster.
 65360  **
 65361  ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
 65362  ** anywhere on the free-list, then it is guaranteed to be returned.  If
 65363  ** eMode is BTALLOC_LT then the page returned will be less than or equal
 65364  ** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
 65365  ** are no restrictions on which page is returned.
 65366  */
 65367  static int allocateBtreePage(
 65368    BtShared *pBt,         /* The btree */
 65369    MemPage **ppPage,      /* Store pointer to the allocated page here */
 65370    Pgno *pPgno,           /* Store the page number here */
 65371    Pgno nearby,           /* Search for a page near this one */
 65372    u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
 65373  ){
 65374    MemPage *pPage1;
 65375    int rc;
 65376    u32 n;     /* Number of pages on the freelist */
 65377    u32 k;     /* Number of leaves on the trunk of the freelist */
 65378    MemPage *pTrunk = 0;
 65379    MemPage *pPrevTrunk = 0;
 65380    Pgno mxPage;     /* Total size of the database file */
 65381  
 65382    assert( sqlite3_mutex_held(pBt->mutex) );
 65383    assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
 65384    pPage1 = pBt->pPage1;
 65385    mxPage = btreePagecount(pBt);
 65386    /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
 65387    ** stores stores the total number of pages on the freelist. */
 65388    n = get4byte(&pPage1->aData[36]);
 65389    testcase( n==mxPage-1 );
 65390    if( n>=mxPage ){
 65391      return SQLITE_CORRUPT_BKPT;
 65392    }
 65393    if( n>0 ){
 65394      /* There are pages on the freelist.  Reuse one of those pages. */
 65395      Pgno iTrunk;
 65396      u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
 65397      u32 nSearch = 0;   /* Count of the number of search attempts */
 65398      
 65399      /* If eMode==BTALLOC_EXACT and a query of the pointer-map
 65400      ** shows that the page 'nearby' is somewhere on the free-list, then
 65401      ** the entire-list will be searched for that page.
 65402      */
 65403  #ifndef SQLITE_OMIT_AUTOVACUUM
 65404      if( eMode==BTALLOC_EXACT ){
 65405        if( nearby<=mxPage ){
 65406          u8 eType;
 65407          assert( nearby>0 );
 65408          assert( pBt->autoVacuum );
 65409          rc = ptrmapGet(pBt, nearby, &eType, 0);
 65410          if( rc ) return rc;
 65411          if( eType==PTRMAP_FREEPAGE ){
 65412            searchList = 1;
 65413          }
 65414        }
 65415      }else if( eMode==BTALLOC_LE ){
 65416        searchList = 1;
 65417      }
 65418  #endif
 65419  
 65420      /* Decrement the free-list count by 1. Set iTrunk to the index of the
 65421      ** first free-list trunk page. iPrevTrunk is initially 1.
 65422      */
 65423      rc = sqlite3PagerWrite(pPage1->pDbPage);
 65424      if( rc ) return rc;
 65425      put4byte(&pPage1->aData[36], n-1);
 65426  
 65427      /* The code within this loop is run only once if the 'searchList' variable
 65428      ** is not true. Otherwise, it runs once for each trunk-page on the
 65429      ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
 65430      ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
 65431      */
 65432      do {
 65433        pPrevTrunk = pTrunk;
 65434        if( pPrevTrunk ){
 65435          /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
 65436          ** is the page number of the next freelist trunk page in the list or
 65437          ** zero if this is the last freelist trunk page. */
 65438          iTrunk = get4byte(&pPrevTrunk->aData[0]);
 65439        }else{
 65440          /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
 65441          ** stores the page number of the first page of the freelist, or zero if
 65442          ** the freelist is empty. */
 65443          iTrunk = get4byte(&pPage1->aData[32]);
 65444        }
 65445        testcase( iTrunk==mxPage );
 65446        if( iTrunk>mxPage || nSearch++ > n ){
 65447          rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
 65448        }else{
 65449          rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
 65450        }
 65451        if( rc ){
 65452          pTrunk = 0;
 65453          goto end_allocate_page;
 65454        }
 65455        assert( pTrunk!=0 );
 65456        assert( pTrunk->aData!=0 );
 65457        /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
 65458        ** is the number of leaf page pointers to follow. */
 65459        k = get4byte(&pTrunk->aData[4]);
 65460        if( k==0 && !searchList ){
 65461          /* The trunk has no leaves and the list is not being searched. 
 65462          ** So extract the trunk page itself and use it as the newly 
 65463          ** allocated page */
 65464          assert( pPrevTrunk==0 );
 65465          rc = sqlite3PagerWrite(pTrunk->pDbPage);
 65466          if( rc ){
 65467            goto end_allocate_page;
 65468          }
 65469          *pPgno = iTrunk;
 65470          memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
 65471          *ppPage = pTrunk;
 65472          pTrunk = 0;
 65473          TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
 65474        }else if( k>(u32)(pBt->usableSize/4 - 2) ){
 65475          /* Value of k is out of range.  Database corruption */
 65476          rc = SQLITE_CORRUPT_PGNO(iTrunk);
 65477          goto end_allocate_page;
 65478  #ifndef SQLITE_OMIT_AUTOVACUUM
 65479        }else if( searchList 
 65480              && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE)) 
 65481        ){
 65482          /* The list is being searched and this trunk page is the page
 65483          ** to allocate, regardless of whether it has leaves.
 65484          */
 65485          *pPgno = iTrunk;
 65486          *ppPage = pTrunk;
 65487          searchList = 0;
 65488          rc = sqlite3PagerWrite(pTrunk->pDbPage);
 65489          if( rc ){
 65490            goto end_allocate_page;
 65491          }
 65492          if( k==0 ){
 65493            if( !pPrevTrunk ){
 65494              memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
 65495            }else{
 65496              rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
 65497              if( rc!=SQLITE_OK ){
 65498                goto end_allocate_page;
 65499              }
 65500              memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
 65501            }
 65502          }else{
 65503            /* The trunk page is required by the caller but it contains 
 65504            ** pointers to free-list leaves. The first leaf becomes a trunk
 65505            ** page in this case.
 65506            */
 65507            MemPage *pNewTrunk;
 65508            Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
 65509            if( iNewTrunk>mxPage ){ 
 65510              rc = SQLITE_CORRUPT_PGNO(iTrunk);
 65511              goto end_allocate_page;
 65512            }
 65513            testcase( iNewTrunk==mxPage );
 65514            rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
 65515            if( rc!=SQLITE_OK ){
 65516              goto end_allocate_page;
 65517            }
 65518            rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
 65519            if( rc!=SQLITE_OK ){
 65520              releasePage(pNewTrunk);
 65521              goto end_allocate_page;
 65522            }
 65523            memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
 65524            put4byte(&pNewTrunk->aData[4], k-1);
 65525            memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
 65526            releasePage(pNewTrunk);
 65527            if( !pPrevTrunk ){
 65528              assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
 65529              put4byte(&pPage1->aData[32], iNewTrunk);
 65530            }else{
 65531              rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
 65532              if( rc ){
 65533                goto end_allocate_page;
 65534              }
 65535              put4byte(&pPrevTrunk->aData[0], iNewTrunk);
 65536            }
 65537          }
 65538          pTrunk = 0;
 65539          TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
 65540  #endif
 65541        }else if( k>0 ){
 65542          /* Extract a leaf from the trunk */
 65543          u32 closest;
 65544          Pgno iPage;
 65545          unsigned char *aData = pTrunk->aData;
 65546          if( nearby>0 ){
 65547            u32 i;
 65548            closest = 0;
 65549            if( eMode==BTALLOC_LE ){
 65550              for(i=0; i<k; i++){
 65551                iPage = get4byte(&aData[8+i*4]);
 65552                if( iPage<=nearby ){
 65553                  closest = i;
 65554                  break;
 65555                }
 65556              }
 65557            }else{
 65558              int dist;
 65559              dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
 65560              for(i=1; i<k; i++){
 65561                int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
 65562                if( d2<dist ){
 65563                  closest = i;
 65564                  dist = d2;
 65565                }
 65566              }
 65567            }
 65568          }else{
 65569            closest = 0;
 65570          }
 65571  
 65572          iPage = get4byte(&aData[8+closest*4]);
 65573          testcase( iPage==mxPage );
 65574          if( iPage>mxPage ){
 65575            rc = SQLITE_CORRUPT_PGNO(iTrunk);
 65576            goto end_allocate_page;
 65577          }
 65578          testcase( iPage==mxPage );
 65579          if( !searchList 
 65580           || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE)) 
 65581          ){
 65582            int noContent;
 65583            *pPgno = iPage;
 65584            TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
 65585                   ": %d more free pages\n",
 65586                   *pPgno, closest+1, k, pTrunk->pgno, n-1));
 65587            rc = sqlite3PagerWrite(pTrunk->pDbPage);
 65588            if( rc ) goto end_allocate_page;
 65589            if( closest<k-1 ){
 65590              memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
 65591            }
 65592            put4byte(&aData[4], k-1);
 65593            noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
 65594            rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
 65595            if( rc==SQLITE_OK ){
 65596              rc = sqlite3PagerWrite((*ppPage)->pDbPage);
 65597              if( rc!=SQLITE_OK ){
 65598                releasePage(*ppPage);
 65599                *ppPage = 0;
 65600              }
 65601            }
 65602            searchList = 0;
 65603          }
 65604        }
 65605        releasePage(pPrevTrunk);
 65606        pPrevTrunk = 0;
 65607      }while( searchList );
 65608    }else{
 65609      /* There are no pages on the freelist, so append a new page to the
 65610      ** database image.
 65611      **
 65612      ** Normally, new pages allocated by this block can be requested from the
 65613      ** pager layer with the 'no-content' flag set. This prevents the pager
 65614      ** from trying to read the pages content from disk. However, if the
 65615      ** current transaction has already run one or more incremental-vacuum
 65616      ** steps, then the page we are about to allocate may contain content
 65617      ** that is required in the event of a rollback. In this case, do
 65618      ** not set the no-content flag. This causes the pager to load and journal
 65619      ** the current page content before overwriting it.
 65620      **
 65621      ** Note that the pager will not actually attempt to load or journal 
 65622      ** content for any page that really does lie past the end of the database
 65623      ** file on disk. So the effects of disabling the no-content optimization
 65624      ** here are confined to those pages that lie between the end of the
 65625      ** database image and the end of the database file.
 65626      */
 65627      int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
 65628  
 65629      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
 65630      if( rc ) return rc;
 65631      pBt->nPage++;
 65632      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
 65633  
 65634  #ifndef SQLITE_OMIT_AUTOVACUUM
 65635      if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
 65636        /* If *pPgno refers to a pointer-map page, allocate two new pages
 65637        ** at the end of the file instead of one. The first allocated page
 65638        ** becomes a new pointer-map page, the second is used by the caller.
 65639        */
 65640        MemPage *pPg = 0;
 65641        TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
 65642        assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
 65643        rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
 65644        if( rc==SQLITE_OK ){
 65645          rc = sqlite3PagerWrite(pPg->pDbPage);
 65646          releasePage(pPg);
 65647        }
 65648        if( rc ) return rc;
 65649        pBt->nPage++;
 65650        if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
 65651      }
 65652  #endif
 65653      put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
 65654      *pPgno = pBt->nPage;
 65655  
 65656      assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
 65657      rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
 65658      if( rc ) return rc;
 65659      rc = sqlite3PagerWrite((*ppPage)->pDbPage);
 65660      if( rc!=SQLITE_OK ){
 65661        releasePage(*ppPage);
 65662        *ppPage = 0;
 65663      }
 65664      TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
 65665    }
 65666  
 65667    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
 65668  
 65669  end_allocate_page:
 65670    releasePage(pTrunk);
 65671    releasePage(pPrevTrunk);
 65672    assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
 65673    assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
 65674    return rc;
 65675  }
 65676  
 65677  /*
 65678  ** This function is used to add page iPage to the database file free-list. 
 65679  ** It is assumed that the page is not already a part of the free-list.
 65680  **
 65681  ** The value passed as the second argument to this function is optional.
 65682  ** If the caller happens to have a pointer to the MemPage object 
 65683  ** corresponding to page iPage handy, it may pass it as the second value. 
 65684  ** Otherwise, it may pass NULL.
 65685  **
 65686  ** If a pointer to a MemPage object is passed as the second argument,
 65687  ** its reference count is not altered by this function.
 65688  */
 65689  static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
 65690    MemPage *pTrunk = 0;                /* Free-list trunk page */
 65691    Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
 65692    MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
 65693    MemPage *pPage;                     /* Page being freed. May be NULL. */
 65694    int rc;                             /* Return Code */
 65695    int nFree;                          /* Initial number of pages on free-list */
 65696  
 65697    assert( sqlite3_mutex_held(pBt->mutex) );
 65698    assert( CORRUPT_DB || iPage>1 );
 65699    assert( !pMemPage || pMemPage->pgno==iPage );
 65700  
 65701    if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
 65702    if( pMemPage ){
 65703      pPage = pMemPage;
 65704      sqlite3PagerRef(pPage->pDbPage);
 65705    }else{
 65706      pPage = btreePageLookup(pBt, iPage);
 65707    }
 65708  
 65709    /* Increment the free page count on pPage1 */
 65710    rc = sqlite3PagerWrite(pPage1->pDbPage);
 65711    if( rc ) goto freepage_out;
 65712    nFree = get4byte(&pPage1->aData[36]);
 65713    put4byte(&pPage1->aData[36], nFree+1);
 65714  
 65715    if( pBt->btsFlags & BTS_SECURE_DELETE ){
 65716      /* If the secure_delete option is enabled, then
 65717      ** always fully overwrite deleted information with zeros.
 65718      */
 65719      if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
 65720       ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
 65721      ){
 65722        goto freepage_out;
 65723      }
 65724      memset(pPage->aData, 0, pPage->pBt->pageSize);
 65725    }
 65726  
 65727    /* If the database supports auto-vacuum, write an entry in the pointer-map
 65728    ** to indicate that the page is free.
 65729    */
 65730    if( ISAUTOVACUUM ){
 65731      ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
 65732      if( rc ) goto freepage_out;
 65733    }
 65734  
 65735    /* Now manipulate the actual database free-list structure. There are two
 65736    ** possibilities. If the free-list is currently empty, or if the first
 65737    ** trunk page in the free-list is full, then this page will become a
 65738    ** new free-list trunk page. Otherwise, it will become a leaf of the
 65739    ** first trunk page in the current free-list. This block tests if it
 65740    ** is possible to add the page as a new free-list leaf.
 65741    */
 65742    if( nFree!=0 ){
 65743      u32 nLeaf;                /* Initial number of leaf cells on trunk page */
 65744  
 65745      iTrunk = get4byte(&pPage1->aData[32]);
 65746      rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
 65747      if( rc!=SQLITE_OK ){
 65748        goto freepage_out;
 65749      }
 65750  
 65751      nLeaf = get4byte(&pTrunk->aData[4]);
 65752      assert( pBt->usableSize>32 );
 65753      if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
 65754        rc = SQLITE_CORRUPT_BKPT;
 65755        goto freepage_out;
 65756      }
 65757      if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
 65758        /* In this case there is room on the trunk page to insert the page
 65759        ** being freed as a new leaf.
 65760        **
 65761        ** Note that the trunk page is not really full until it contains
 65762        ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
 65763        ** coded.  But due to a coding error in versions of SQLite prior to
 65764        ** 3.6.0, databases with freelist trunk pages holding more than
 65765        ** usableSize/4 - 8 entries will be reported as corrupt.  In order
 65766        ** to maintain backwards compatibility with older versions of SQLite,
 65767        ** we will continue to restrict the number of entries to usableSize/4 - 8
 65768        ** for now.  At some point in the future (once everyone has upgraded
 65769        ** to 3.6.0 or later) we should consider fixing the conditional above
 65770        ** to read "usableSize/4-2" instead of "usableSize/4-8".
 65771        **
 65772        ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
 65773        ** avoid using the last six entries in the freelist trunk page array in
 65774        ** order that database files created by newer versions of SQLite can be
 65775        ** read by older versions of SQLite.
 65776        */
 65777        rc = sqlite3PagerWrite(pTrunk->pDbPage);
 65778        if( rc==SQLITE_OK ){
 65779          put4byte(&pTrunk->aData[4], nLeaf+1);
 65780          put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
 65781          if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
 65782            sqlite3PagerDontWrite(pPage->pDbPage);
 65783          }
 65784          rc = btreeSetHasContent(pBt, iPage);
 65785        }
 65786        TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
 65787        goto freepage_out;
 65788      }
 65789    }
 65790  
 65791    /* If control flows to this point, then it was not possible to add the
 65792    ** the page being freed as a leaf page of the first trunk in the free-list.
 65793    ** Possibly because the free-list is empty, or possibly because the 
 65794    ** first trunk in the free-list is full. Either way, the page being freed
 65795    ** will become the new first trunk page in the free-list.
 65796    */
 65797    if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
 65798      goto freepage_out;
 65799    }
 65800    rc = sqlite3PagerWrite(pPage->pDbPage);
 65801    if( rc!=SQLITE_OK ){
 65802      goto freepage_out;
 65803    }
 65804    put4byte(pPage->aData, iTrunk);
 65805    put4byte(&pPage->aData[4], 0);
 65806    put4byte(&pPage1->aData[32], iPage);
 65807    TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
 65808  
 65809  freepage_out:
 65810    if( pPage ){
 65811      pPage->isInit = 0;
 65812    }
 65813    releasePage(pPage);
 65814    releasePage(pTrunk);
 65815    return rc;
 65816  }
 65817  static void freePage(MemPage *pPage, int *pRC){
 65818    if( (*pRC)==SQLITE_OK ){
 65819      *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
 65820    }
 65821  }
 65822  
 65823  /*
 65824  ** Free any overflow pages associated with the given Cell.  Write the
 65825  ** local Cell size (the number of bytes on the original page, omitting
 65826  ** overflow) into *pnSize.
 65827  */
 65828  static int clearCell(
 65829    MemPage *pPage,          /* The page that contains the Cell */
 65830    unsigned char *pCell,    /* First byte of the Cell */
 65831    CellInfo *pInfo          /* Size information about the cell */
 65832  ){
 65833    BtShared *pBt;
 65834    Pgno ovflPgno;
 65835    int rc;
 65836    int nOvfl;
 65837    u32 ovflPageSize;
 65838  
 65839    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 65840    pPage->xParseCell(pPage, pCell, pInfo);
 65841    if( pInfo->nLocal==pInfo->nPayload ){
 65842      return SQLITE_OK;  /* No overflow pages. Return without doing anything */
 65843    }
 65844    if( pCell+pInfo->nSize-1 > pPage->aData+pPage->maskPage ){
 65845      /* Cell extends past end of page */
 65846      return SQLITE_CORRUPT_PGNO(pPage->pgno);
 65847    }
 65848    ovflPgno = get4byte(pCell + pInfo->nSize - 4);
 65849    pBt = pPage->pBt;
 65850    assert( pBt->usableSize > 4 );
 65851    ovflPageSize = pBt->usableSize - 4;
 65852    nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
 65853    assert( nOvfl>0 || 
 65854      (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
 65855    );
 65856    while( nOvfl-- ){
 65857      Pgno iNext = 0;
 65858      MemPage *pOvfl = 0;
 65859      if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
 65860        /* 0 is not a legal page number and page 1 cannot be an 
 65861        ** overflow page. Therefore if ovflPgno<2 or past the end of the 
 65862        ** file the database must be corrupt. */
 65863        return SQLITE_CORRUPT_BKPT;
 65864      }
 65865      if( nOvfl ){
 65866        rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
 65867        if( rc ) return rc;
 65868      }
 65869  
 65870      if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
 65871       && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
 65872      ){
 65873        /* There is no reason any cursor should have an outstanding reference 
 65874        ** to an overflow page belonging to a cell that is being deleted/updated.
 65875        ** So if there exists more than one reference to this page, then it 
 65876        ** must not really be an overflow page and the database must be corrupt. 
 65877        ** It is helpful to detect this before calling freePage2(), as 
 65878        ** freePage2() may zero the page contents if secure-delete mode is
 65879        ** enabled. If this 'overflow' page happens to be a page that the
 65880        ** caller is iterating through or using in some other way, this
 65881        ** can be problematic.
 65882        */
 65883        rc = SQLITE_CORRUPT_BKPT;
 65884      }else{
 65885        rc = freePage2(pBt, pOvfl, ovflPgno);
 65886      }
 65887  
 65888      if( pOvfl ){
 65889        sqlite3PagerUnref(pOvfl->pDbPage);
 65890      }
 65891      if( rc ) return rc;
 65892      ovflPgno = iNext;
 65893    }
 65894    return SQLITE_OK;
 65895  }
 65896  
 65897  /*
 65898  ** Create the byte sequence used to represent a cell on page pPage
 65899  ** and write that byte sequence into pCell[].  Overflow pages are
 65900  ** allocated and filled in as necessary.  The calling procedure
 65901  ** is responsible for making sure sufficient space has been allocated
 65902  ** for pCell[].
 65903  **
 65904  ** Note that pCell does not necessary need to point to the pPage->aData
 65905  ** area.  pCell might point to some temporary storage.  The cell will
 65906  ** be constructed in this temporary area then copied into pPage->aData
 65907  ** later.
 65908  */
 65909  static int fillInCell(
 65910    MemPage *pPage,                /* The page that contains the cell */
 65911    unsigned char *pCell,          /* Complete text of the cell */
 65912    const BtreePayload *pX,        /* Payload with which to construct the cell */
 65913    int *pnSize                    /* Write cell size here */
 65914  ){
 65915    int nPayload;
 65916    const u8 *pSrc;
 65917    int nSrc, n, rc, mn;
 65918    int spaceLeft;
 65919    MemPage *pToRelease;
 65920    unsigned char *pPrior;
 65921    unsigned char *pPayload;
 65922    BtShared *pBt;
 65923    Pgno pgnoOvfl;
 65924    int nHeader;
 65925  
 65926    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 65927  
 65928    /* pPage is not necessarily writeable since pCell might be auxiliary
 65929    ** buffer space that is separate from the pPage buffer area */
 65930    assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
 65931              || sqlite3PagerIswriteable(pPage->pDbPage) );
 65932  
 65933    /* Fill in the header. */
 65934    nHeader = pPage->childPtrSize;
 65935    if( pPage->intKey ){
 65936      nPayload = pX->nData + pX->nZero;
 65937      pSrc = pX->pData;
 65938      nSrc = pX->nData;
 65939      assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
 65940      nHeader += putVarint32(&pCell[nHeader], nPayload);
 65941      nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
 65942    }else{
 65943      assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
 65944      nSrc = nPayload = (int)pX->nKey;
 65945      pSrc = pX->pKey;
 65946      nHeader += putVarint32(&pCell[nHeader], nPayload);
 65947    }
 65948    
 65949    /* Fill in the payload */
 65950    pPayload = &pCell[nHeader];
 65951    if( nPayload<=pPage->maxLocal ){
 65952      /* This is the common case where everything fits on the btree page
 65953      ** and no overflow pages are required. */
 65954      n = nHeader + nPayload;
 65955      testcase( n==3 );
 65956      testcase( n==4 );
 65957      if( n<4 ) n = 4;
 65958      *pnSize = n;
 65959      assert( nSrc<=nPayload );
 65960      testcase( nSrc<nPayload );
 65961      memcpy(pPayload, pSrc, nSrc);
 65962      memset(pPayload+nSrc, 0, nPayload-nSrc);
 65963      return SQLITE_OK;
 65964    }
 65965  
 65966    /* If we reach this point, it means that some of the content will need
 65967    ** to spill onto overflow pages.
 65968    */
 65969    mn = pPage->minLocal;
 65970    n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
 65971    testcase( n==pPage->maxLocal );
 65972    testcase( n==pPage->maxLocal+1 );
 65973    if( n > pPage->maxLocal ) n = mn;
 65974    spaceLeft = n;
 65975    *pnSize = n + nHeader + 4;
 65976    pPrior = &pCell[nHeader+n];
 65977    pToRelease = 0;
 65978    pgnoOvfl = 0;
 65979    pBt = pPage->pBt;
 65980  
 65981    /* At this point variables should be set as follows:
 65982    **
 65983    **   nPayload           Total payload size in bytes
 65984    **   pPayload           Begin writing payload here
 65985    **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
 65986    **                      that means content must spill into overflow pages.
 65987    **   *pnSize            Size of the local cell (not counting overflow pages)
 65988    **   pPrior             Where to write the pgno of the first overflow page
 65989    **
 65990    ** Use a call to btreeParseCellPtr() to verify that the values above
 65991    ** were computed correctly.
 65992    */
 65993  #ifdef SQLITE_DEBUG
 65994    {
 65995      CellInfo info;
 65996      pPage->xParseCell(pPage, pCell, &info);
 65997      assert( nHeader==(int)(info.pPayload - pCell) );
 65998      assert( info.nKey==pX->nKey );
 65999      assert( *pnSize == info.nSize );
 66000      assert( spaceLeft == info.nLocal );
 66001    }
 66002  #endif
 66003  
 66004    /* Write the payload into the local Cell and any extra into overflow pages */
 66005    while( 1 ){
 66006      n = nPayload;
 66007      if( n>spaceLeft ) n = spaceLeft;
 66008  
 66009      /* If pToRelease is not zero than pPayload points into the data area
 66010      ** of pToRelease.  Make sure pToRelease is still writeable. */
 66011      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
 66012  
 66013      /* If pPayload is part of the data area of pPage, then make sure pPage
 66014      ** is still writeable */
 66015      assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
 66016              || sqlite3PagerIswriteable(pPage->pDbPage) );
 66017  
 66018      if( nSrc>=n ){
 66019        memcpy(pPayload, pSrc, n);
 66020      }else if( nSrc>0 ){
 66021        n = nSrc;
 66022        memcpy(pPayload, pSrc, n);
 66023      }else{
 66024        memset(pPayload, 0, n);
 66025      }
 66026      nPayload -= n;
 66027      if( nPayload<=0 ) break;
 66028      pPayload += n;
 66029      pSrc += n;
 66030      nSrc -= n;
 66031      spaceLeft -= n;
 66032      if( spaceLeft==0 ){
 66033        MemPage *pOvfl = 0;
 66034  #ifndef SQLITE_OMIT_AUTOVACUUM
 66035        Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
 66036        if( pBt->autoVacuum ){
 66037          do{
 66038            pgnoOvfl++;
 66039          } while( 
 66040            PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
 66041          );
 66042        }
 66043  #endif
 66044        rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
 66045  #ifndef SQLITE_OMIT_AUTOVACUUM
 66046        /* If the database supports auto-vacuum, and the second or subsequent
 66047        ** overflow page is being allocated, add an entry to the pointer-map
 66048        ** for that page now. 
 66049        **
 66050        ** If this is the first overflow page, then write a partial entry 
 66051        ** to the pointer-map. If we write nothing to this pointer-map slot,
 66052        ** then the optimistic overflow chain processing in clearCell()
 66053        ** may misinterpret the uninitialized values and delete the
 66054        ** wrong pages from the database.
 66055        */
 66056        if( pBt->autoVacuum && rc==SQLITE_OK ){
 66057          u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
 66058          ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
 66059          if( rc ){
 66060            releasePage(pOvfl);
 66061          }
 66062        }
 66063  #endif
 66064        if( rc ){
 66065          releasePage(pToRelease);
 66066          return rc;
 66067        }
 66068  
 66069        /* If pToRelease is not zero than pPrior points into the data area
 66070        ** of pToRelease.  Make sure pToRelease is still writeable. */
 66071        assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
 66072  
 66073        /* If pPrior is part of the data area of pPage, then make sure pPage
 66074        ** is still writeable */
 66075        assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
 66076              || sqlite3PagerIswriteable(pPage->pDbPage) );
 66077  
 66078        put4byte(pPrior, pgnoOvfl);
 66079        releasePage(pToRelease);
 66080        pToRelease = pOvfl;
 66081        pPrior = pOvfl->aData;
 66082        put4byte(pPrior, 0);
 66083        pPayload = &pOvfl->aData[4];
 66084        spaceLeft = pBt->usableSize - 4;
 66085      }
 66086    }
 66087    releasePage(pToRelease);
 66088    return SQLITE_OK;
 66089  }
 66090  
 66091  /*
 66092  ** Remove the i-th cell from pPage.  This routine effects pPage only.
 66093  ** The cell content is not freed or deallocated.  It is assumed that
 66094  ** the cell content has been copied someplace else.  This routine just
 66095  ** removes the reference to the cell from pPage.
 66096  **
 66097  ** "sz" must be the number of bytes in the cell.
 66098  */
 66099  static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
 66100    u32 pc;         /* Offset to cell content of cell being deleted */
 66101    u8 *data;       /* pPage->aData */
 66102    u8 *ptr;        /* Used to move bytes around within data[] */
 66103    int rc;         /* The return code */
 66104    int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
 66105  
 66106    if( *pRC ) return;
 66107    assert( idx>=0 && idx<pPage->nCell );
 66108    assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
 66109    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 66110    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 66111    data = pPage->aData;
 66112    ptr = &pPage->aCellIdx[2*idx];
 66113    pc = get2byte(ptr);
 66114    hdr = pPage->hdrOffset;
 66115    testcase( pc==get2byte(&data[hdr+5]) );
 66116    testcase( pc+sz==pPage->pBt->usableSize );
 66117    if( pc+sz > pPage->pBt->usableSize ){
 66118      *pRC = SQLITE_CORRUPT_BKPT;
 66119      return;
 66120    }
 66121    rc = freeSpace(pPage, pc, sz);
 66122    if( rc ){
 66123      *pRC = rc;
 66124      return;
 66125    }
 66126    pPage->nCell--;
 66127    if( pPage->nCell==0 ){
 66128      memset(&data[hdr+1], 0, 4);
 66129      data[hdr+7] = 0;
 66130      put2byte(&data[hdr+5], pPage->pBt->usableSize);
 66131      pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
 66132                         - pPage->childPtrSize - 8;
 66133    }else{
 66134      memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
 66135      put2byte(&data[hdr+3], pPage->nCell);
 66136      pPage->nFree += 2;
 66137    }
 66138  }
 66139  
 66140  /*
 66141  ** Insert a new cell on pPage at cell index "i".  pCell points to the
 66142  ** content of the cell.
 66143  **
 66144  ** If the cell content will fit on the page, then put it there.  If it
 66145  ** will not fit, then make a copy of the cell content into pTemp if
 66146  ** pTemp is not null.  Regardless of pTemp, allocate a new entry
 66147  ** in pPage->apOvfl[] and make it point to the cell content (either
 66148  ** in pTemp or the original pCell) and also record its index. 
 66149  ** Allocating a new entry in pPage->aCell[] implies that 
 66150  ** pPage->nOverflow is incremented.
 66151  **
 66152  ** *pRC must be SQLITE_OK when this routine is called.
 66153  */
 66154  static void insertCell(
 66155    MemPage *pPage,   /* Page into which we are copying */
 66156    int i,            /* New cell becomes the i-th cell of the page */
 66157    u8 *pCell,        /* Content of the new cell */
 66158    int sz,           /* Bytes of content in pCell */
 66159    u8 *pTemp,        /* Temp storage space for pCell, if needed */
 66160    Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
 66161    int *pRC          /* Read and write return code from here */
 66162  ){
 66163    int idx = 0;      /* Where to write new cell content in data[] */
 66164    int j;            /* Loop counter */
 66165    u8 *data;         /* The content of the whole page */
 66166    u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */
 66167  
 66168    assert( *pRC==SQLITE_OK );
 66169    assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
 66170    assert( MX_CELL(pPage->pBt)<=10921 );
 66171    assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
 66172    assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
 66173    assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
 66174    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 66175    /* The cell should normally be sized correctly.  However, when moving a
 66176    ** malformed cell from a leaf page to an interior page, if the cell size
 66177    ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
 66178    ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
 66179    ** the term after the || in the following assert(). */
 66180    assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
 66181    if( pPage->nOverflow || sz+2>pPage->nFree ){
 66182      if( pTemp ){
 66183        memcpy(pTemp, pCell, sz);
 66184        pCell = pTemp;
 66185      }
 66186      if( iChild ){
 66187        put4byte(pCell, iChild);
 66188      }
 66189      j = pPage->nOverflow++;
 66190      /* Comparison against ArraySize-1 since we hold back one extra slot
 66191      ** as a contingency.  In other words, never need more than 3 overflow
 66192      ** slots but 4 are allocated, just to be safe. */
 66193      assert( j < ArraySize(pPage->apOvfl)-1 );
 66194      pPage->apOvfl[j] = pCell;
 66195      pPage->aiOvfl[j] = (u16)i;
 66196  
 66197      /* When multiple overflows occur, they are always sequential and in
 66198      ** sorted order.  This invariants arise because multiple overflows can
 66199      ** only occur when inserting divider cells into the parent page during
 66200      ** balancing, and the dividers are adjacent and sorted.
 66201      */
 66202      assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
 66203      assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */
 66204    }else{
 66205      int rc = sqlite3PagerWrite(pPage->pDbPage);
 66206      if( rc!=SQLITE_OK ){
 66207        *pRC = rc;
 66208        return;
 66209      }
 66210      assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 66211      data = pPage->aData;
 66212      assert( &data[pPage->cellOffset]==pPage->aCellIdx );
 66213      rc = allocateSpace(pPage, sz, &idx);
 66214      if( rc ){ *pRC = rc; return; }
 66215      /* The allocateSpace() routine guarantees the following properties
 66216      ** if it returns successfully */
 66217      assert( idx >= 0 );
 66218      assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
 66219      assert( idx+sz <= (int)pPage->pBt->usableSize );
 66220      pPage->nFree -= (u16)(2 + sz);
 66221      memcpy(&data[idx], pCell, sz);
 66222      if( iChild ){
 66223        put4byte(&data[idx], iChild);
 66224      }
 66225      pIns = pPage->aCellIdx + i*2;
 66226      memmove(pIns+2, pIns, 2*(pPage->nCell - i));
 66227      put2byte(pIns, idx);
 66228      pPage->nCell++;
 66229      /* increment the cell count */
 66230      if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
 66231      assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
 66232  #ifndef SQLITE_OMIT_AUTOVACUUM
 66233      if( pPage->pBt->autoVacuum ){
 66234        /* The cell may contain a pointer to an overflow page. If so, write
 66235        ** the entry for the overflow page into the pointer map.
 66236        */
 66237        ptrmapPutOvflPtr(pPage, pCell, pRC);
 66238      }
 66239  #endif
 66240    }
 66241  }
 66242  
 66243  /*
 66244  ** A CellArray object contains a cache of pointers and sizes for a
 66245  ** consecutive sequence of cells that might be held on multiple pages.
 66246  */
 66247  typedef struct CellArray CellArray;
 66248  struct CellArray {
 66249    int nCell;              /* Number of cells in apCell[] */
 66250    MemPage *pRef;          /* Reference page */
 66251    u8 **apCell;            /* All cells begin balanced */
 66252    u16 *szCell;            /* Local size of all cells in apCell[] */
 66253  };
 66254  
 66255  /*
 66256  ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
 66257  ** computed.
 66258  */
 66259  static void populateCellCache(CellArray *p, int idx, int N){
 66260    assert( idx>=0 && idx+N<=p->nCell );
 66261    while( N>0 ){
 66262      assert( p->apCell[idx]!=0 );
 66263      if( p->szCell[idx]==0 ){
 66264        p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
 66265      }else{
 66266        assert( CORRUPT_DB ||
 66267                p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
 66268      }
 66269      idx++;
 66270      N--;
 66271    }
 66272  }
 66273  
 66274  /*
 66275  ** Return the size of the Nth element of the cell array
 66276  */
 66277  static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
 66278    assert( N>=0 && N<p->nCell );
 66279    assert( p->szCell[N]==0 );
 66280    p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
 66281    return p->szCell[N];
 66282  }
 66283  static u16 cachedCellSize(CellArray *p, int N){
 66284    assert( N>=0 && N<p->nCell );
 66285    if( p->szCell[N] ) return p->szCell[N];
 66286    return computeCellSize(p, N);
 66287  }
 66288  
 66289  /*
 66290  ** Array apCell[] contains pointers to nCell b-tree page cells. The 
 66291  ** szCell[] array contains the size in bytes of each cell. This function
 66292  ** replaces the current contents of page pPg with the contents of the cell
 66293  ** array.
 66294  **
 66295  ** Some of the cells in apCell[] may currently be stored in pPg. This
 66296  ** function works around problems caused by this by making a copy of any 
 66297  ** such cells before overwriting the page data.
 66298  **
 66299  ** The MemPage.nFree field is invalidated by this function. It is the 
 66300  ** responsibility of the caller to set it correctly.
 66301  */
 66302  static int rebuildPage(
 66303    MemPage *pPg,                   /* Edit this page */
 66304    int nCell,                      /* Final number of cells on page */
 66305    u8 **apCell,                    /* Array of cells */
 66306    u16 *szCell                     /* Array of cell sizes */
 66307  ){
 66308    const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */
 66309    u8 * const aData = pPg->aData;           /* Pointer to data for pPg */
 66310    const int usableSize = pPg->pBt->usableSize;
 66311    u8 * const pEnd = &aData[usableSize];
 66312    int i;
 66313    u8 *pCellptr = pPg->aCellIdx;
 66314    u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
 66315    u8 *pData;
 66316  
 66317    i = get2byte(&aData[hdr+5]);
 66318    memcpy(&pTmp[i], &aData[i], usableSize - i);
 66319  
 66320    pData = pEnd;
 66321    for(i=0; i<nCell; i++){
 66322      u8 *pCell = apCell[i];
 66323      if( SQLITE_WITHIN(pCell,aData,pEnd) ){
 66324        pCell = &pTmp[pCell - aData];
 66325      }
 66326      pData -= szCell[i];
 66327      put2byte(pCellptr, (pData - aData));
 66328      pCellptr += 2;
 66329      if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
 66330      memcpy(pData, pCell, szCell[i]);
 66331      assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
 66332      testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
 66333    }
 66334  
 66335    /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
 66336    pPg->nCell = nCell;
 66337    pPg->nOverflow = 0;
 66338  
 66339    put2byte(&aData[hdr+1], 0);
 66340    put2byte(&aData[hdr+3], pPg->nCell);
 66341    put2byte(&aData[hdr+5], pData - aData);
 66342    aData[hdr+7] = 0x00;
 66343    return SQLITE_OK;
 66344  }
 66345  
 66346  /*
 66347  ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
 66348  ** contains the size in bytes of each such cell. This function attempts to 
 66349  ** add the cells stored in the array to page pPg. If it cannot (because 
 66350  ** the page needs to be defragmented before the cells will fit), non-zero
 66351  ** is returned. Otherwise, if the cells are added successfully, zero is
 66352  ** returned.
 66353  **
 66354  ** Argument pCellptr points to the first entry in the cell-pointer array
 66355  ** (part of page pPg) to populate. After cell apCell[0] is written to the
 66356  ** page body, a 16-bit offset is written to pCellptr. And so on, for each
 66357  ** cell in the array. It is the responsibility of the caller to ensure
 66358  ** that it is safe to overwrite this part of the cell-pointer array.
 66359  **
 66360  ** When this function is called, *ppData points to the start of the 
 66361  ** content area on page pPg. If the size of the content area is extended,
 66362  ** *ppData is updated to point to the new start of the content area
 66363  ** before returning.
 66364  **
 66365  ** Finally, argument pBegin points to the byte immediately following the
 66366  ** end of the space required by this page for the cell-pointer area (for
 66367  ** all cells - not just those inserted by the current call). If the content
 66368  ** area must be extended to before this point in order to accomodate all
 66369  ** cells in apCell[], then the cells do not fit and non-zero is returned.
 66370  */
 66371  static int pageInsertArray(
 66372    MemPage *pPg,                   /* Page to add cells to */
 66373    u8 *pBegin,                     /* End of cell-pointer array */
 66374    u8 **ppData,                    /* IN/OUT: Page content -area pointer */
 66375    u8 *pCellptr,                   /* Pointer to cell-pointer area */
 66376    int iFirst,                     /* Index of first cell to add */
 66377    int nCell,                      /* Number of cells to add to pPg */
 66378    CellArray *pCArray              /* Array of cells */
 66379  ){
 66380    int i;
 66381    u8 *aData = pPg->aData;
 66382    u8 *pData = *ppData;
 66383    int iEnd = iFirst + nCell;
 66384    assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
 66385    for(i=iFirst; i<iEnd; i++){
 66386      int sz, rc;
 66387      u8 *pSlot;
 66388      sz = cachedCellSize(pCArray, i);
 66389      if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
 66390        if( (pData - pBegin)<sz ) return 1;
 66391        pData -= sz;
 66392        pSlot = pData;
 66393      }
 66394      /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
 66395      ** database.  But they might for a corrupt database.  Hence use memmove()
 66396      ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
 66397      assert( (pSlot+sz)<=pCArray->apCell[i]
 66398           || pSlot>=(pCArray->apCell[i]+sz)
 66399           || CORRUPT_DB );
 66400      memmove(pSlot, pCArray->apCell[i], sz);
 66401      put2byte(pCellptr, (pSlot - aData));
 66402      pCellptr += 2;
 66403    }
 66404    *ppData = pData;
 66405    return 0;
 66406  }
 66407  
 66408  /*
 66409  ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell 
 66410  ** contains the size in bytes of each such cell. This function adds the
 66411  ** space associated with each cell in the array that is currently stored 
 66412  ** within the body of pPg to the pPg free-list. The cell-pointers and other
 66413  ** fields of the page are not updated.
 66414  **
 66415  ** This function returns the total number of cells added to the free-list.
 66416  */
 66417  static int pageFreeArray(
 66418    MemPage *pPg,                   /* Page to edit */
 66419    int iFirst,                     /* First cell to delete */
 66420    int nCell,                      /* Cells to delete */
 66421    CellArray *pCArray              /* Array of cells */
 66422  ){
 66423    u8 * const aData = pPg->aData;
 66424    u8 * const pEnd = &aData[pPg->pBt->usableSize];
 66425    u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
 66426    int nRet = 0;
 66427    int i;
 66428    int iEnd = iFirst + nCell;
 66429    u8 *pFree = 0;
 66430    int szFree = 0;
 66431  
 66432    for(i=iFirst; i<iEnd; i++){
 66433      u8 *pCell = pCArray->apCell[i];
 66434      if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
 66435        int sz;
 66436        /* No need to use cachedCellSize() here.  The sizes of all cells that
 66437        ** are to be freed have already been computing while deciding which
 66438        ** cells need freeing */
 66439        sz = pCArray->szCell[i];  assert( sz>0 );
 66440        if( pFree!=(pCell + sz) ){
 66441          if( pFree ){
 66442            assert( pFree>aData && (pFree - aData)<65536 );
 66443            freeSpace(pPg, (u16)(pFree - aData), szFree);
 66444          }
 66445          pFree = pCell;
 66446          szFree = sz;
 66447          if( pFree+sz>pEnd ) return 0;
 66448        }else{
 66449          pFree = pCell;
 66450          szFree += sz;
 66451        }
 66452        nRet++;
 66453      }
 66454    }
 66455    if( pFree ){
 66456      assert( pFree>aData && (pFree - aData)<65536 );
 66457      freeSpace(pPg, (u16)(pFree - aData), szFree);
 66458    }
 66459    return nRet;
 66460  }
 66461  
 66462  /*
 66463  ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
 66464  ** pages being balanced.  The current page, pPg, has pPg->nCell cells starting
 66465  ** with apCell[iOld].  After balancing, this page should hold nNew cells
 66466  ** starting at apCell[iNew].
 66467  **
 66468  ** This routine makes the necessary adjustments to pPg so that it contains
 66469  ** the correct cells after being balanced.
 66470  **
 66471  ** The pPg->nFree field is invalid when this function returns. It is the
 66472  ** responsibility of the caller to set it correctly.
 66473  */
 66474  static int editPage(
 66475    MemPage *pPg,                   /* Edit this page */
 66476    int iOld,                       /* Index of first cell currently on page */
 66477    int iNew,                       /* Index of new first cell on page */
 66478    int nNew,                       /* Final number of cells on page */
 66479    CellArray *pCArray              /* Array of cells and sizes */
 66480  ){
 66481    u8 * const aData = pPg->aData;
 66482    const int hdr = pPg->hdrOffset;
 66483    u8 *pBegin = &pPg->aCellIdx[nNew * 2];
 66484    int nCell = pPg->nCell;       /* Cells stored on pPg */
 66485    u8 *pData;
 66486    u8 *pCellptr;
 66487    int i;
 66488    int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
 66489    int iNewEnd = iNew + nNew;
 66490  
 66491  #ifdef SQLITE_DEBUG
 66492    u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
 66493    memcpy(pTmp, aData, pPg->pBt->usableSize);
 66494  #endif
 66495  
 66496    /* Remove cells from the start and end of the page */
 66497    if( iOld<iNew ){
 66498      int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
 66499      memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
 66500      nCell -= nShift;
 66501    }
 66502    if( iNewEnd < iOldEnd ){
 66503      nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
 66504    }
 66505  
 66506    pData = &aData[get2byteNotZero(&aData[hdr+5])];
 66507    if( pData<pBegin ) goto editpage_fail;
 66508  
 66509    /* Add cells to the start of the page */
 66510    if( iNew<iOld ){
 66511      int nAdd = MIN(nNew,iOld-iNew);
 66512      assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
 66513      pCellptr = pPg->aCellIdx;
 66514      memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
 66515      if( pageInsertArray(
 66516            pPg, pBegin, &pData, pCellptr,
 66517            iNew, nAdd, pCArray
 66518      ) ) goto editpage_fail;
 66519      nCell += nAdd;
 66520    }
 66521  
 66522    /* Add any overflow cells */
 66523    for(i=0; i<pPg->nOverflow; i++){
 66524      int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
 66525      if( iCell>=0 && iCell<nNew ){
 66526        pCellptr = &pPg->aCellIdx[iCell * 2];
 66527        memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
 66528        nCell++;
 66529        if( pageInsertArray(
 66530              pPg, pBegin, &pData, pCellptr,
 66531              iCell+iNew, 1, pCArray
 66532        ) ) goto editpage_fail;
 66533      }
 66534    }
 66535  
 66536    /* Append cells to the end of the page */
 66537    pCellptr = &pPg->aCellIdx[nCell*2];
 66538    if( pageInsertArray(
 66539          pPg, pBegin, &pData, pCellptr,
 66540          iNew+nCell, nNew-nCell, pCArray
 66541    ) ) goto editpage_fail;
 66542  
 66543    pPg->nCell = nNew;
 66544    pPg->nOverflow = 0;
 66545  
 66546    put2byte(&aData[hdr+3], pPg->nCell);
 66547    put2byte(&aData[hdr+5], pData - aData);
 66548  
 66549  #ifdef SQLITE_DEBUG
 66550    for(i=0; i<nNew && !CORRUPT_DB; i++){
 66551      u8 *pCell = pCArray->apCell[i+iNew];
 66552      int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
 66553      if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
 66554        pCell = &pTmp[pCell - aData];
 66555      }
 66556      assert( 0==memcmp(pCell, &aData[iOff],
 66557              pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
 66558    }
 66559  #endif
 66560  
 66561    return SQLITE_OK;
 66562   editpage_fail:
 66563    /* Unable to edit this page. Rebuild it from scratch instead. */
 66564    populateCellCache(pCArray, iNew, nNew);
 66565    return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
 66566  }
 66567  
 66568  /*
 66569  ** The following parameters determine how many adjacent pages get involved
 66570  ** in a balancing operation.  NN is the number of neighbors on either side
 66571  ** of the page that participate in the balancing operation.  NB is the
 66572  ** total number of pages that participate, including the target page and
 66573  ** NN neighbors on either side.
 66574  **
 66575  ** The minimum value of NN is 1 (of course).  Increasing NN above 1
 66576  ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
 66577  ** in exchange for a larger degradation in INSERT and UPDATE performance.
 66578  ** The value of NN appears to give the best results overall.
 66579  */
 66580  #define NN 1             /* Number of neighbors on either side of pPage */
 66581  #define NB (NN*2+1)      /* Total pages involved in the balance */
 66582  
 66583  
 66584  #ifndef SQLITE_OMIT_QUICKBALANCE
 66585  /*
 66586  ** This version of balance() handles the common special case where
 66587  ** a new entry is being inserted on the extreme right-end of the
 66588  ** tree, in other words, when the new entry will become the largest
 66589  ** entry in the tree.
 66590  **
 66591  ** Instead of trying to balance the 3 right-most leaf pages, just add
 66592  ** a new page to the right-hand side and put the one new entry in
 66593  ** that page.  This leaves the right side of the tree somewhat
 66594  ** unbalanced.  But odds are that we will be inserting new entries
 66595  ** at the end soon afterwards so the nearly empty page will quickly
 66596  ** fill up.  On average.
 66597  **
 66598  ** pPage is the leaf page which is the right-most page in the tree.
 66599  ** pParent is its parent.  pPage must have a single overflow entry
 66600  ** which is also the right-most entry on the page.
 66601  **
 66602  ** The pSpace buffer is used to store a temporary copy of the divider
 66603  ** cell that will be inserted into pParent. Such a cell consists of a 4
 66604  ** byte page number followed by a variable length integer. In other
 66605  ** words, at most 13 bytes. Hence the pSpace buffer must be at
 66606  ** least 13 bytes in size.
 66607  */
 66608  static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
 66609    BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
 66610    MemPage *pNew;                       /* Newly allocated page */
 66611    int rc;                              /* Return Code */
 66612    Pgno pgnoNew;                        /* Page number of pNew */
 66613  
 66614    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 66615    assert( sqlite3PagerIswriteable(pParent->pDbPage) );
 66616    assert( pPage->nOverflow==1 );
 66617  
 66618    /* This error condition is now caught prior to reaching this function */
 66619    if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
 66620  
 66621    /* Allocate a new page. This page will become the right-sibling of 
 66622    ** pPage. Make the parent page writable, so that the new divider cell
 66623    ** may be inserted. If both these operations are successful, proceed.
 66624    */
 66625    rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
 66626  
 66627    if( rc==SQLITE_OK ){
 66628  
 66629      u8 *pOut = &pSpace[4];
 66630      u8 *pCell = pPage->apOvfl[0];
 66631      u16 szCell = pPage->xCellSize(pPage, pCell);
 66632      u8 *pStop;
 66633  
 66634      assert( sqlite3PagerIswriteable(pNew->pDbPage) );
 66635      assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
 66636      zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
 66637      rc = rebuildPage(pNew, 1, &pCell, &szCell);
 66638      if( NEVER(rc) ) return rc;
 66639      pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
 66640  
 66641      /* If this is an auto-vacuum database, update the pointer map
 66642      ** with entries for the new page, and any pointer from the 
 66643      ** cell on the page to an overflow page. If either of these
 66644      ** operations fails, the return code is set, but the contents
 66645      ** of the parent page are still manipulated by thh code below.
 66646      ** That is Ok, at this point the parent page is guaranteed to
 66647      ** be marked as dirty. Returning an error code will cause a
 66648      ** rollback, undoing any changes made to the parent page.
 66649      */
 66650      if( ISAUTOVACUUM ){
 66651        ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
 66652        if( szCell>pNew->minLocal ){
 66653          ptrmapPutOvflPtr(pNew, pCell, &rc);
 66654        }
 66655      }
 66656    
 66657      /* Create a divider cell to insert into pParent. The divider cell
 66658      ** consists of a 4-byte page number (the page number of pPage) and
 66659      ** a variable length key value (which must be the same value as the
 66660      ** largest key on pPage).
 66661      **
 66662      ** To find the largest key value on pPage, first find the right-most 
 66663      ** cell on pPage. The first two fields of this cell are the 
 66664      ** record-length (a variable length integer at most 32-bits in size)
 66665      ** and the key value (a variable length integer, may have any value).
 66666      ** The first of the while(...) loops below skips over the record-length
 66667      ** field. The second while(...) loop copies the key value from the
 66668      ** cell on pPage into the pSpace buffer.
 66669      */
 66670      pCell = findCell(pPage, pPage->nCell-1);
 66671      pStop = &pCell[9];
 66672      while( (*(pCell++)&0x80) && pCell<pStop );
 66673      pStop = &pCell[9];
 66674      while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
 66675  
 66676      /* Insert the new divider cell into pParent. */
 66677      if( rc==SQLITE_OK ){
 66678        insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
 66679                     0, pPage->pgno, &rc);
 66680      }
 66681  
 66682      /* Set the right-child pointer of pParent to point to the new page. */
 66683      put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
 66684    
 66685      /* Release the reference to the new page. */
 66686      releasePage(pNew);
 66687    }
 66688  
 66689    return rc;
 66690  }
 66691  #endif /* SQLITE_OMIT_QUICKBALANCE */
 66692  
 66693  #if 0
 66694  /*
 66695  ** This function does not contribute anything to the operation of SQLite.
 66696  ** it is sometimes activated temporarily while debugging code responsible 
 66697  ** for setting pointer-map entries.
 66698  */
 66699  static int ptrmapCheckPages(MemPage **apPage, int nPage){
 66700    int i, j;
 66701    for(i=0; i<nPage; i++){
 66702      Pgno n;
 66703      u8 e;
 66704      MemPage *pPage = apPage[i];
 66705      BtShared *pBt = pPage->pBt;
 66706      assert( pPage->isInit );
 66707  
 66708      for(j=0; j<pPage->nCell; j++){
 66709        CellInfo info;
 66710        u8 *z;
 66711       
 66712        z = findCell(pPage, j);
 66713        pPage->xParseCell(pPage, z, &info);
 66714        if( info.nLocal<info.nPayload ){
 66715          Pgno ovfl = get4byte(&z[info.nSize-4]);
 66716          ptrmapGet(pBt, ovfl, &e, &n);
 66717          assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
 66718        }
 66719        if( !pPage->leaf ){
 66720          Pgno child = get4byte(z);
 66721          ptrmapGet(pBt, child, &e, &n);
 66722          assert( n==pPage->pgno && e==PTRMAP_BTREE );
 66723        }
 66724      }
 66725      if( !pPage->leaf ){
 66726        Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
 66727        ptrmapGet(pBt, child, &e, &n);
 66728        assert( n==pPage->pgno && e==PTRMAP_BTREE );
 66729      }
 66730    }
 66731    return 1;
 66732  }
 66733  #endif
 66734  
 66735  /*
 66736  ** This function is used to copy the contents of the b-tree node stored 
 66737  ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
 66738  ** the pointer-map entries for each child page are updated so that the
 66739  ** parent page stored in the pointer map is page pTo. If pFrom contained
 66740  ** any cells with overflow page pointers, then the corresponding pointer
 66741  ** map entries are also updated so that the parent page is page pTo.
 66742  **
 66743  ** If pFrom is currently carrying any overflow cells (entries in the
 66744  ** MemPage.apOvfl[] array), they are not copied to pTo. 
 66745  **
 66746  ** Before returning, page pTo is reinitialized using btreeInitPage().
 66747  **
 66748  ** The performance of this function is not critical. It is only used by 
 66749  ** the balance_shallower() and balance_deeper() procedures, neither of
 66750  ** which are called often under normal circumstances.
 66751  */
 66752  static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
 66753    if( (*pRC)==SQLITE_OK ){
 66754      BtShared * const pBt = pFrom->pBt;
 66755      u8 * const aFrom = pFrom->aData;
 66756      u8 * const aTo = pTo->aData;
 66757      int const iFromHdr = pFrom->hdrOffset;
 66758      int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
 66759      int rc;
 66760      int iData;
 66761    
 66762    
 66763      assert( pFrom->isInit );
 66764      assert( pFrom->nFree>=iToHdr );
 66765      assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
 66766    
 66767      /* Copy the b-tree node content from page pFrom to page pTo. */
 66768      iData = get2byte(&aFrom[iFromHdr+5]);
 66769      memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
 66770      memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
 66771    
 66772      /* Reinitialize page pTo so that the contents of the MemPage structure
 66773      ** match the new data. The initialization of pTo can actually fail under
 66774      ** fairly obscure circumstances, even though it is a copy of initialized 
 66775      ** page pFrom.
 66776      */
 66777      pTo->isInit = 0;
 66778      rc = btreeInitPage(pTo);
 66779      if( rc!=SQLITE_OK ){
 66780        *pRC = rc;
 66781        return;
 66782      }
 66783    
 66784      /* If this is an auto-vacuum database, update the pointer-map entries
 66785      ** for any b-tree or overflow pages that pTo now contains the pointers to.
 66786      */
 66787      if( ISAUTOVACUUM ){
 66788        *pRC = setChildPtrmaps(pTo);
 66789      }
 66790    }
 66791  }
 66792  
 66793  /*
 66794  ** This routine redistributes cells on the iParentIdx'th child of pParent
 66795  ** (hereafter "the page") and up to 2 siblings so that all pages have about the
 66796  ** same amount of free space. Usually a single sibling on either side of the
 66797  ** page are used in the balancing, though both siblings might come from one
 66798  ** side if the page is the first or last child of its parent. If the page 
 66799  ** has fewer than 2 siblings (something which can only happen if the page
 66800  ** is a root page or a child of a root page) then all available siblings
 66801  ** participate in the balancing.
 66802  **
 66803  ** The number of siblings of the page might be increased or decreased by 
 66804  ** one or two in an effort to keep pages nearly full but not over full. 
 66805  **
 66806  ** Note that when this routine is called, some of the cells on the page
 66807  ** might not actually be stored in MemPage.aData[]. This can happen
 66808  ** if the page is overfull. This routine ensures that all cells allocated
 66809  ** to the page and its siblings fit into MemPage.aData[] before returning.
 66810  **
 66811  ** In the course of balancing the page and its siblings, cells may be
 66812  ** inserted into or removed from the parent page (pParent). Doing so
 66813  ** may cause the parent page to become overfull or underfull. If this
 66814  ** happens, it is the responsibility of the caller to invoke the correct
 66815  ** balancing routine to fix this problem (see the balance() routine). 
 66816  **
 66817  ** If this routine fails for any reason, it might leave the database
 66818  ** in a corrupted state. So if this routine fails, the database should
 66819  ** be rolled back.
 66820  **
 66821  ** The third argument to this function, aOvflSpace, is a pointer to a
 66822  ** buffer big enough to hold one page. If while inserting cells into the parent
 66823  ** page (pParent) the parent page becomes overfull, this buffer is
 66824  ** used to store the parent's overflow cells. Because this function inserts
 66825  ** a maximum of four divider cells into the parent page, and the maximum
 66826  ** size of a cell stored within an internal node is always less than 1/4
 66827  ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
 66828  ** enough for all overflow cells.
 66829  **
 66830  ** If aOvflSpace is set to a null pointer, this function returns 
 66831  ** SQLITE_NOMEM.
 66832  */
 66833  static int balance_nonroot(
 66834    MemPage *pParent,               /* Parent page of siblings being balanced */
 66835    int iParentIdx,                 /* Index of "the page" in pParent */
 66836    u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
 66837    int isRoot,                     /* True if pParent is a root-page */
 66838    int bBulk                       /* True if this call is part of a bulk load */
 66839  ){
 66840    BtShared *pBt;               /* The whole database */
 66841    int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
 66842    int nNew = 0;                /* Number of pages in apNew[] */
 66843    int nOld;                    /* Number of pages in apOld[] */
 66844    int i, j, k;                 /* Loop counters */
 66845    int nxDiv;                   /* Next divider slot in pParent->aCell[] */
 66846    int rc = SQLITE_OK;          /* The return code */
 66847    u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
 66848    int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
 66849    int usableSpace;             /* Bytes in pPage beyond the header */
 66850    int pageFlags;               /* Value of pPage->aData[0] */
 66851    int iSpace1 = 0;             /* First unused byte of aSpace1[] */
 66852    int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
 66853    int szScratch;               /* Size of scratch memory requested */
 66854    MemPage *apOld[NB];          /* pPage and up to two siblings */
 66855    MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
 66856    u8 *pRight;                  /* Location in parent of right-sibling pointer */
 66857    u8 *apDiv[NB-1];             /* Divider cells in pParent */
 66858    int cntNew[NB+2];            /* Index in b.paCell[] of cell after i-th page */
 66859    int cntOld[NB+2];            /* Old index in b.apCell[] */
 66860    int szNew[NB+2];             /* Combined size of cells placed on i-th page */
 66861    u8 *aSpace1;                 /* Space for copies of dividers cells */
 66862    Pgno pgno;                   /* Temp var to store a page number in */
 66863    u8 abDone[NB+2];             /* True after i'th new page is populated */
 66864    Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
 66865    Pgno aPgOrder[NB+2];         /* Copy of aPgno[] used for sorting pages */
 66866    u16 aPgFlags[NB+2];          /* flags field of new pages before shuffling */
 66867    CellArray b;                  /* Parsed information on cells being balanced */
 66868  
 66869    memset(abDone, 0, sizeof(abDone));
 66870    b.nCell = 0;
 66871    b.apCell = 0;
 66872    pBt = pParent->pBt;
 66873    assert( sqlite3_mutex_held(pBt->mutex) );
 66874    assert( sqlite3PagerIswriteable(pParent->pDbPage) );
 66875  
 66876  #if 0
 66877    TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
 66878  #endif
 66879  
 66880    /* At this point pParent may have at most one overflow cell. And if
 66881    ** this overflow cell is present, it must be the cell with 
 66882    ** index iParentIdx. This scenario comes about when this function
 66883    ** is called (indirectly) from sqlite3BtreeDelete().
 66884    */
 66885    assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
 66886    assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
 66887  
 66888    if( !aOvflSpace ){
 66889      return SQLITE_NOMEM_BKPT;
 66890    }
 66891  
 66892    /* Find the sibling pages to balance. Also locate the cells in pParent 
 66893    ** that divide the siblings. An attempt is made to find NN siblings on 
 66894    ** either side of pPage. More siblings are taken from one side, however, 
 66895    ** if there are fewer than NN siblings on the other side. If pParent
 66896    ** has NB or fewer children then all children of pParent are taken.  
 66897    **
 66898    ** This loop also drops the divider cells from the parent page. This
 66899    ** way, the remainder of the function does not have to deal with any
 66900    ** overflow cells in the parent page, since if any existed they will
 66901    ** have already been removed.
 66902    */
 66903    i = pParent->nOverflow + pParent->nCell;
 66904    if( i<2 ){
 66905      nxDiv = 0;
 66906    }else{
 66907      assert( bBulk==0 || bBulk==1 );
 66908      if( iParentIdx==0 ){                 
 66909        nxDiv = 0;
 66910      }else if( iParentIdx==i ){
 66911        nxDiv = i-2+bBulk;
 66912      }else{
 66913        nxDiv = iParentIdx-1;
 66914      }
 66915      i = 2-bBulk;
 66916    }
 66917    nOld = i+1;
 66918    if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
 66919      pRight = &pParent->aData[pParent->hdrOffset+8];
 66920    }else{
 66921      pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
 66922    }
 66923    pgno = get4byte(pRight);
 66924    while( 1 ){
 66925      rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
 66926      if( rc ){
 66927        memset(apOld, 0, (i+1)*sizeof(MemPage*));
 66928        goto balance_cleanup;
 66929      }
 66930      nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
 66931      if( (i--)==0 ) break;
 66932  
 66933      if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
 66934        apDiv[i] = pParent->apOvfl[0];
 66935        pgno = get4byte(apDiv[i]);
 66936        szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
 66937        pParent->nOverflow = 0;
 66938      }else{
 66939        apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
 66940        pgno = get4byte(apDiv[i]);
 66941        szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
 66942  
 66943        /* Drop the cell from the parent page. apDiv[i] still points to
 66944        ** the cell within the parent, even though it has been dropped.
 66945        ** This is safe because dropping a cell only overwrites the first
 66946        ** four bytes of it, and this function does not need the first
 66947        ** four bytes of the divider cell. So the pointer is safe to use
 66948        ** later on.  
 66949        **
 66950        ** But not if we are in secure-delete mode. In secure-delete mode,
 66951        ** the dropCell() routine will overwrite the entire cell with zeroes.
 66952        ** In this case, temporarily copy the cell into the aOvflSpace[]
 66953        ** buffer. It will be copied out again as soon as the aSpace[] buffer
 66954        ** is allocated.  */
 66955        if( pBt->btsFlags & BTS_FAST_SECURE ){
 66956          int iOff;
 66957  
 66958          iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
 66959          if( (iOff+szNew[i])>(int)pBt->usableSize ){
 66960            rc = SQLITE_CORRUPT_BKPT;
 66961            memset(apOld, 0, (i+1)*sizeof(MemPage*));
 66962            goto balance_cleanup;
 66963          }else{
 66964            memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
 66965            apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
 66966          }
 66967        }
 66968        dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
 66969      }
 66970    }
 66971  
 66972    /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
 66973    ** alignment */
 66974    nMaxCells = (nMaxCells + 3)&~3;
 66975  
 66976    /*
 66977    ** Allocate space for memory structures
 66978    */
 66979    szScratch =
 66980         nMaxCells*sizeof(u8*)                       /* b.apCell */
 66981       + nMaxCells*sizeof(u16)                       /* b.szCell */
 66982       + pBt->pageSize;                              /* aSpace1 */
 66983  
 66984    assert( szScratch<=6*(int)pBt->pageSize );
 66985    b.apCell = sqlite3StackAllocRaw(0, szScratch );
 66986    if( b.apCell==0 ){
 66987      rc = SQLITE_NOMEM_BKPT;
 66988      goto balance_cleanup;
 66989    }
 66990    b.szCell = (u16*)&b.apCell[nMaxCells];
 66991    aSpace1 = (u8*)&b.szCell[nMaxCells];
 66992    assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
 66993  
 66994    /*
 66995    ** Load pointers to all cells on sibling pages and the divider cells
 66996    ** into the local b.apCell[] array.  Make copies of the divider cells
 66997    ** into space obtained from aSpace1[]. The divider cells have already
 66998    ** been removed from pParent.
 66999    **
 67000    ** If the siblings are on leaf pages, then the child pointers of the
 67001    ** divider cells are stripped from the cells before they are copied
 67002    ** into aSpace1[].  In this way, all cells in b.apCell[] are without
 67003    ** child pointers.  If siblings are not leaves, then all cell in
 67004    ** b.apCell[] include child pointers.  Either way, all cells in b.apCell[]
 67005    ** are alike.
 67006    **
 67007    ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
 67008    **       leafData:  1 if pPage holds key+data and pParent holds only keys.
 67009    */
 67010    b.pRef = apOld[0];
 67011    leafCorrection = b.pRef->leaf*4;
 67012    leafData = b.pRef->intKeyLeaf;
 67013    for(i=0; i<nOld; i++){
 67014      MemPage *pOld = apOld[i];
 67015      int limit = pOld->nCell;
 67016      u8 *aData = pOld->aData;
 67017      u16 maskPage = pOld->maskPage;
 67018      u8 *piCell = aData + pOld->cellOffset;
 67019      u8 *piEnd;
 67020  
 67021      /* Verify that all sibling pages are of the same "type" (table-leaf,
 67022      ** table-interior, index-leaf, or index-interior).
 67023      */
 67024      if( pOld->aData[0]!=apOld[0]->aData[0] ){
 67025        rc = SQLITE_CORRUPT_BKPT;
 67026        goto balance_cleanup;
 67027      }
 67028  
 67029      /* Load b.apCell[] with pointers to all cells in pOld.  If pOld
 67030      ** constains overflow cells, include them in the b.apCell[] array
 67031      ** in the correct spot.
 67032      **
 67033      ** Note that when there are multiple overflow cells, it is always the
 67034      ** case that they are sequential and adjacent.  This invariant arises
 67035      ** because multiple overflows can only occurs when inserting divider
 67036      ** cells into a parent on a prior balance, and divider cells are always
 67037      ** adjacent and are inserted in order.  There is an assert() tagged
 67038      ** with "NOTE 1" in the overflow cell insertion loop to prove this
 67039      ** invariant.
 67040      **
 67041      ** This must be done in advance.  Once the balance starts, the cell
 67042      ** offset section of the btree page will be overwritten and we will no
 67043      ** long be able to find the cells if a pointer to each cell is not saved
 67044      ** first.
 67045      */
 67046      memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
 67047      if( pOld->nOverflow>0 ){
 67048        limit = pOld->aiOvfl[0];
 67049        for(j=0; j<limit; j++){
 67050          b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
 67051          piCell += 2;
 67052          b.nCell++;
 67053        }
 67054        for(k=0; k<pOld->nOverflow; k++){
 67055          assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
 67056          b.apCell[b.nCell] = pOld->apOvfl[k];
 67057          b.nCell++;
 67058        }
 67059      }
 67060      piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
 67061      while( piCell<piEnd ){
 67062        assert( b.nCell<nMaxCells );
 67063        b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
 67064        piCell += 2;
 67065        b.nCell++;
 67066      }
 67067  
 67068      cntOld[i] = b.nCell;
 67069      if( i<nOld-1 && !leafData){
 67070        u16 sz = (u16)szNew[i];
 67071        u8 *pTemp;
 67072        assert( b.nCell<nMaxCells );
 67073        b.szCell[b.nCell] = sz;
 67074        pTemp = &aSpace1[iSpace1];
 67075        iSpace1 += sz;
 67076        assert( sz<=pBt->maxLocal+23 );
 67077        assert( iSpace1 <= (int)pBt->pageSize );
 67078        memcpy(pTemp, apDiv[i], sz);
 67079        b.apCell[b.nCell] = pTemp+leafCorrection;
 67080        assert( leafCorrection==0 || leafCorrection==4 );
 67081        b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
 67082        if( !pOld->leaf ){
 67083          assert( leafCorrection==0 );
 67084          assert( pOld->hdrOffset==0 );
 67085          /* The right pointer of the child page pOld becomes the left
 67086          ** pointer of the divider cell */
 67087          memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
 67088        }else{
 67089          assert( leafCorrection==4 );
 67090          while( b.szCell[b.nCell]<4 ){
 67091            /* Do not allow any cells smaller than 4 bytes. If a smaller cell
 67092            ** does exist, pad it with 0x00 bytes. */
 67093            assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
 67094            assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
 67095            aSpace1[iSpace1++] = 0x00;
 67096            b.szCell[b.nCell]++;
 67097          }
 67098        }
 67099        b.nCell++;
 67100      }
 67101    }
 67102  
 67103    /*
 67104    ** Figure out the number of pages needed to hold all b.nCell cells.
 67105    ** Store this number in "k".  Also compute szNew[] which is the total
 67106    ** size of all cells on the i-th page and cntNew[] which is the index
 67107    ** in b.apCell[] of the cell that divides page i from page i+1.  
 67108    ** cntNew[k] should equal b.nCell.
 67109    **
 67110    ** Values computed by this block:
 67111    **
 67112    **           k: The total number of sibling pages
 67113    **    szNew[i]: Spaced used on the i-th sibling page.
 67114    **   cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
 67115    **              the right of the i-th sibling page.
 67116    ** usableSpace: Number of bytes of space available on each sibling.
 67117    ** 
 67118    */
 67119    usableSpace = pBt->usableSize - 12 + leafCorrection;
 67120    for(i=0; i<nOld; i++){
 67121      MemPage *p = apOld[i];
 67122      szNew[i] = usableSpace - p->nFree;
 67123      for(j=0; j<p->nOverflow; j++){
 67124        szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
 67125      }
 67126      cntNew[i] = cntOld[i];
 67127    }
 67128    k = nOld;
 67129    for(i=0; i<k; i++){
 67130      int sz;
 67131      while( szNew[i]>usableSpace ){
 67132        if( i+1>=k ){
 67133          k = i+2;
 67134          if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
 67135          szNew[k-1] = 0;
 67136          cntNew[k-1] = b.nCell;
 67137        }
 67138        sz = 2 + cachedCellSize(&b, cntNew[i]-1);
 67139        szNew[i] -= sz;
 67140        if( !leafData ){
 67141          if( cntNew[i]<b.nCell ){
 67142            sz = 2 + cachedCellSize(&b, cntNew[i]);
 67143          }else{
 67144            sz = 0;
 67145          }
 67146        }
 67147        szNew[i+1] += sz;
 67148        cntNew[i]--;
 67149      }
 67150      while( cntNew[i]<b.nCell ){
 67151        sz = 2 + cachedCellSize(&b, cntNew[i]);
 67152        if( szNew[i]+sz>usableSpace ) break;
 67153        szNew[i] += sz;
 67154        cntNew[i]++;
 67155        if( !leafData ){
 67156          if( cntNew[i]<b.nCell ){
 67157            sz = 2 + cachedCellSize(&b, cntNew[i]);
 67158          }else{
 67159            sz = 0;
 67160          }
 67161        }
 67162        szNew[i+1] -= sz;
 67163      }
 67164      if( cntNew[i]>=b.nCell ){
 67165        k = i+1;
 67166      }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
 67167        rc = SQLITE_CORRUPT_BKPT;
 67168        goto balance_cleanup;
 67169      }
 67170    }
 67171  
 67172    /*
 67173    ** The packing computed by the previous block is biased toward the siblings
 67174    ** on the left side (siblings with smaller keys). The left siblings are
 67175    ** always nearly full, while the right-most sibling might be nearly empty.
 67176    ** The next block of code attempts to adjust the packing of siblings to
 67177    ** get a better balance.
 67178    **
 67179    ** This adjustment is more than an optimization.  The packing above might
 67180    ** be so out of balance as to be illegal.  For example, the right-most
 67181    ** sibling might be completely empty.  This adjustment is not optional.
 67182    */
 67183    for(i=k-1; i>0; i--){
 67184      int szRight = szNew[i];  /* Size of sibling on the right */
 67185      int szLeft = szNew[i-1]; /* Size of sibling on the left */
 67186      int r;              /* Index of right-most cell in left sibling */
 67187      int d;              /* Index of first cell to the left of right sibling */
 67188  
 67189      r = cntNew[i-1] - 1;
 67190      d = r + 1 - leafData;
 67191      (void)cachedCellSize(&b, d);
 67192      do{
 67193        assert( d<nMaxCells );
 67194        assert( r<nMaxCells );
 67195        (void)cachedCellSize(&b, r);
 67196        if( szRight!=0
 67197         && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
 67198          break;
 67199        }
 67200        szRight += b.szCell[d] + 2;
 67201        szLeft -= b.szCell[r] + 2;
 67202        cntNew[i-1] = r;
 67203        r--;
 67204        d--;
 67205      }while( r>=0 );
 67206      szNew[i] = szRight;
 67207      szNew[i-1] = szLeft;
 67208      if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
 67209        rc = SQLITE_CORRUPT_BKPT;
 67210        goto balance_cleanup;
 67211      }
 67212    }
 67213  
 67214    /* Sanity check:  For a non-corrupt database file one of the follwing
 67215    ** must be true:
 67216    **    (1) We found one or more cells (cntNew[0])>0), or
 67217    **    (2) pPage is a virtual root page.  A virtual root page is when
 67218    **        the real root page is page 1 and we are the only child of
 67219    **        that page.
 67220    */
 67221    assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
 67222    TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
 67223      apOld[0]->pgno, apOld[0]->nCell,
 67224      nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
 67225      nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
 67226    ));
 67227  
 67228    /*
 67229    ** Allocate k new pages.  Reuse old pages where possible.
 67230    */
 67231    pageFlags = apOld[0]->aData[0];
 67232    for(i=0; i<k; i++){
 67233      MemPage *pNew;
 67234      if( i<nOld ){
 67235        pNew = apNew[i] = apOld[i];
 67236        apOld[i] = 0;
 67237        rc = sqlite3PagerWrite(pNew->pDbPage);
 67238        nNew++;
 67239        if( rc ) goto balance_cleanup;
 67240      }else{
 67241        assert( i>0 );
 67242        rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
 67243        if( rc ) goto balance_cleanup;
 67244        zeroPage(pNew, pageFlags);
 67245        apNew[i] = pNew;
 67246        nNew++;
 67247        cntOld[i] = b.nCell;
 67248  
 67249        /* Set the pointer-map entry for the new sibling page. */
 67250        if( ISAUTOVACUUM ){
 67251          ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
 67252          if( rc!=SQLITE_OK ){
 67253            goto balance_cleanup;
 67254          }
 67255        }
 67256      }
 67257    }
 67258  
 67259    /*
 67260    ** Reassign page numbers so that the new pages are in ascending order. 
 67261    ** This helps to keep entries in the disk file in order so that a scan
 67262    ** of the table is closer to a linear scan through the file. That in turn 
 67263    ** helps the operating system to deliver pages from the disk more rapidly.
 67264    **
 67265    ** An O(n^2) insertion sort algorithm is used, but since n is never more 
 67266    ** than (NB+2) (a small constant), that should not be a problem.
 67267    **
 67268    ** When NB==3, this one optimization makes the database about 25% faster 
 67269    ** for large insertions and deletions.
 67270    */
 67271    for(i=0; i<nNew; i++){
 67272      aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
 67273      aPgFlags[i] = apNew[i]->pDbPage->flags;
 67274      for(j=0; j<i; j++){
 67275        if( aPgno[j]==aPgno[i] ){
 67276          /* This branch is taken if the set of sibling pages somehow contains
 67277          ** duplicate entries. This can happen if the database is corrupt. 
 67278          ** It would be simpler to detect this as part of the loop below, but
 67279          ** we do the detection here in order to avoid populating the pager
 67280          ** cache with two separate objects associated with the same
 67281          ** page number.  */
 67282          assert( CORRUPT_DB );
 67283          rc = SQLITE_CORRUPT_BKPT;
 67284          goto balance_cleanup;
 67285        }
 67286      }
 67287    }
 67288    for(i=0; i<nNew; i++){
 67289      int iBest = 0;                /* aPgno[] index of page number to use */
 67290      for(j=1; j<nNew; j++){
 67291        if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
 67292      }
 67293      pgno = aPgOrder[iBest];
 67294      aPgOrder[iBest] = 0xffffffff;
 67295      if( iBest!=i ){
 67296        if( iBest>i ){
 67297          sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
 67298        }
 67299        sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
 67300        apNew[i]->pgno = pgno;
 67301      }
 67302    }
 67303  
 67304    TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
 67305           "%d(%d nc=%d) %d(%d nc=%d)\n",
 67306      apNew[0]->pgno, szNew[0], cntNew[0],
 67307      nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
 67308      nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
 67309      nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
 67310      nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
 67311      nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
 67312      nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
 67313      nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
 67314      nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
 67315    ));
 67316  
 67317    assert( sqlite3PagerIswriteable(pParent->pDbPage) );
 67318    put4byte(pRight, apNew[nNew-1]->pgno);
 67319  
 67320    /* If the sibling pages are not leaves, ensure that the right-child pointer
 67321    ** of the right-most new sibling page is set to the value that was 
 67322    ** originally in the same field of the right-most old sibling page. */
 67323    if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
 67324      MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
 67325      memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
 67326    }
 67327  
 67328    /* Make any required updates to pointer map entries associated with 
 67329    ** cells stored on sibling pages following the balance operation. Pointer
 67330    ** map entries associated with divider cells are set by the insertCell()
 67331    ** routine. The associated pointer map entries are:
 67332    **
 67333    **   a) if the cell contains a reference to an overflow chain, the
 67334    **      entry associated with the first page in the overflow chain, and
 67335    **
 67336    **   b) if the sibling pages are not leaves, the child page associated
 67337    **      with the cell.
 67338    **
 67339    ** If the sibling pages are not leaves, then the pointer map entry 
 67340    ** associated with the right-child of each sibling may also need to be 
 67341    ** updated. This happens below, after the sibling pages have been 
 67342    ** populated, not here.
 67343    */
 67344    if( ISAUTOVACUUM ){
 67345      MemPage *pNew = apNew[0];
 67346      u8 *aOld = pNew->aData;
 67347      int cntOldNext = pNew->nCell + pNew->nOverflow;
 67348      int usableSize = pBt->usableSize;
 67349      int iNew = 0;
 67350      int iOld = 0;
 67351  
 67352      for(i=0; i<b.nCell; i++){
 67353        u8 *pCell = b.apCell[i];
 67354        if( i==cntOldNext ){
 67355          MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
 67356          cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
 67357          aOld = pOld->aData;
 67358        }
 67359        if( i==cntNew[iNew] ){
 67360          pNew = apNew[++iNew];
 67361          if( !leafData ) continue;
 67362        }
 67363  
 67364        /* Cell pCell is destined for new sibling page pNew. Originally, it
 67365        ** was either part of sibling page iOld (possibly an overflow cell), 
 67366        ** or else the divider cell to the left of sibling page iOld. So,
 67367        ** if sibling page iOld had the same page number as pNew, and if
 67368        ** pCell really was a part of sibling page iOld (not a divider or
 67369        ** overflow cell), we can skip updating the pointer map entries.  */
 67370        if( iOld>=nNew
 67371         || pNew->pgno!=aPgno[iOld]
 67372         || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
 67373        ){
 67374          if( !leafCorrection ){
 67375            ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
 67376          }
 67377          if( cachedCellSize(&b,i)>pNew->minLocal ){
 67378            ptrmapPutOvflPtr(pNew, pCell, &rc);
 67379          }
 67380          if( rc ) goto balance_cleanup;
 67381        }
 67382      }
 67383    }
 67384  
 67385    /* Insert new divider cells into pParent. */
 67386    for(i=0; i<nNew-1; i++){
 67387      u8 *pCell;
 67388      u8 *pTemp;
 67389      int sz;
 67390      MemPage *pNew = apNew[i];
 67391      j = cntNew[i];
 67392  
 67393      assert( j<nMaxCells );
 67394      assert( b.apCell[j]!=0 );
 67395      pCell = b.apCell[j];
 67396      sz = b.szCell[j] + leafCorrection;
 67397      pTemp = &aOvflSpace[iOvflSpace];
 67398      if( !pNew->leaf ){
 67399        memcpy(&pNew->aData[8], pCell, 4);
 67400      }else if( leafData ){
 67401        /* If the tree is a leaf-data tree, and the siblings are leaves, 
 67402        ** then there is no divider cell in b.apCell[]. Instead, the divider 
 67403        ** cell consists of the integer key for the right-most cell of 
 67404        ** the sibling-page assembled above only.
 67405        */
 67406        CellInfo info;
 67407        j--;
 67408        pNew->xParseCell(pNew, b.apCell[j], &info);
 67409        pCell = pTemp;
 67410        sz = 4 + putVarint(&pCell[4], info.nKey);
 67411        pTemp = 0;
 67412      }else{
 67413        pCell -= 4;
 67414        /* Obscure case for non-leaf-data trees: If the cell at pCell was
 67415        ** previously stored on a leaf node, and its reported size was 4
 67416        ** bytes, then it may actually be smaller than this 
 67417        ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
 67418        ** any cell). But it is important to pass the correct size to 
 67419        ** insertCell(), so reparse the cell now.
 67420        **
 67421        ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
 67422        ** and WITHOUT ROWID tables with exactly one column which is the
 67423        ** primary key.
 67424        */
 67425        if( b.szCell[j]==4 ){
 67426          assert(leafCorrection==4);
 67427          sz = pParent->xCellSize(pParent, pCell);
 67428        }
 67429      }
 67430      iOvflSpace += sz;
 67431      assert( sz<=pBt->maxLocal+23 );
 67432      assert( iOvflSpace <= (int)pBt->pageSize );
 67433      insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
 67434      if( rc!=SQLITE_OK ) goto balance_cleanup;
 67435      assert( sqlite3PagerIswriteable(pParent->pDbPage) );
 67436    }
 67437  
 67438    /* Now update the actual sibling pages. The order in which they are updated
 67439    ** is important, as this code needs to avoid disrupting any page from which
 67440    ** cells may still to be read. In practice, this means:
 67441    **
 67442    **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
 67443    **      then it is not safe to update page apNew[iPg] until after
 67444    **      the left-hand sibling apNew[iPg-1] has been updated.
 67445    **
 67446    **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
 67447    **      then it is not safe to update page apNew[iPg] until after
 67448    **      the right-hand sibling apNew[iPg+1] has been updated.
 67449    **
 67450    ** If neither of the above apply, the page is safe to update.
 67451    **
 67452    ** The iPg value in the following loop starts at nNew-1 goes down
 67453    ** to 0, then back up to nNew-1 again, thus making two passes over
 67454    ** the pages.  On the initial downward pass, only condition (1) above
 67455    ** needs to be tested because (2) will always be true from the previous
 67456    ** step.  On the upward pass, both conditions are always true, so the
 67457    ** upwards pass simply processes pages that were missed on the downward
 67458    ** pass.
 67459    */
 67460    for(i=1-nNew; i<nNew; i++){
 67461      int iPg = i<0 ? -i : i;
 67462      assert( iPg>=0 && iPg<nNew );
 67463      if( abDone[iPg] ) continue;         /* Skip pages already processed */
 67464      if( i>=0                            /* On the upwards pass, or... */
 67465       || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */
 67466      ){
 67467        int iNew;
 67468        int iOld;
 67469        int nNewCell;
 67470  
 67471        /* Verify condition (1):  If cells are moving left, update iPg
 67472        ** only after iPg-1 has already been updated. */
 67473        assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
 67474  
 67475        /* Verify condition (2):  If cells are moving right, update iPg
 67476        ** only after iPg+1 has already been updated. */
 67477        assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
 67478  
 67479        if( iPg==0 ){
 67480          iNew = iOld = 0;
 67481          nNewCell = cntNew[0];
 67482        }else{
 67483          iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
 67484          iNew = cntNew[iPg-1] + !leafData;
 67485          nNewCell = cntNew[iPg] - iNew;
 67486        }
 67487  
 67488        rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
 67489        if( rc ) goto balance_cleanup;
 67490        abDone[iPg]++;
 67491        apNew[iPg]->nFree = usableSpace-szNew[iPg];
 67492        assert( apNew[iPg]->nOverflow==0 );
 67493        assert( apNew[iPg]->nCell==nNewCell );
 67494      }
 67495    }
 67496  
 67497    /* All pages have been processed exactly once */
 67498    assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
 67499  
 67500    assert( nOld>0 );
 67501    assert( nNew>0 );
 67502  
 67503    if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
 67504      /* The root page of the b-tree now contains no cells. The only sibling
 67505      ** page is the right-child of the parent. Copy the contents of the
 67506      ** child page into the parent, decreasing the overall height of the
 67507      ** b-tree structure by one. This is described as the "balance-shallower"
 67508      ** sub-algorithm in some documentation.
 67509      **
 67510      ** If this is an auto-vacuum database, the call to copyNodeContent() 
 67511      ** sets all pointer-map entries corresponding to database image pages 
 67512      ** for which the pointer is stored within the content being copied.
 67513      **
 67514      ** It is critical that the child page be defragmented before being
 67515      ** copied into the parent, because if the parent is page 1 then it will
 67516      ** by smaller than the child due to the database header, and so all the
 67517      ** free space needs to be up front.
 67518      */
 67519      assert( nNew==1 || CORRUPT_DB );
 67520      rc = defragmentPage(apNew[0], -1);
 67521      testcase( rc!=SQLITE_OK );
 67522      assert( apNew[0]->nFree == 
 67523          (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
 67524        || rc!=SQLITE_OK
 67525      );
 67526      copyNodeContent(apNew[0], pParent, &rc);
 67527      freePage(apNew[0], &rc);
 67528    }else if( ISAUTOVACUUM && !leafCorrection ){
 67529      /* Fix the pointer map entries associated with the right-child of each
 67530      ** sibling page. All other pointer map entries have already been taken
 67531      ** care of.  */
 67532      for(i=0; i<nNew; i++){
 67533        u32 key = get4byte(&apNew[i]->aData[8]);
 67534        ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
 67535      }
 67536    }
 67537  
 67538    assert( pParent->isInit );
 67539    TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
 67540            nOld, nNew, b.nCell));
 67541  
 67542    /* Free any old pages that were not reused as new pages.
 67543    */
 67544    for(i=nNew; i<nOld; i++){
 67545      freePage(apOld[i], &rc);
 67546    }
 67547  
 67548  #if 0
 67549    if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
 67550      /* The ptrmapCheckPages() contains assert() statements that verify that
 67551      ** all pointer map pages are set correctly. This is helpful while 
 67552      ** debugging. This is usually disabled because a corrupt database may
 67553      ** cause an assert() statement to fail.  */
 67554      ptrmapCheckPages(apNew, nNew);
 67555      ptrmapCheckPages(&pParent, 1);
 67556    }
 67557  #endif
 67558  
 67559    /*
 67560    ** Cleanup before returning.
 67561    */
 67562  balance_cleanup:
 67563    sqlite3StackFree(0, b.apCell);
 67564    for(i=0; i<nOld; i++){
 67565      releasePage(apOld[i]);
 67566    }
 67567    for(i=0; i<nNew; i++){
 67568      releasePage(apNew[i]);
 67569    }
 67570  
 67571    return rc;
 67572  }
 67573  
 67574  
 67575  /*
 67576  ** This function is called when the root page of a b-tree structure is
 67577  ** overfull (has one or more overflow pages).
 67578  **
 67579  ** A new child page is allocated and the contents of the current root
 67580  ** page, including overflow cells, are copied into the child. The root
 67581  ** page is then overwritten to make it an empty page with the right-child 
 67582  ** pointer pointing to the new page.
 67583  **
 67584  ** Before returning, all pointer-map entries corresponding to pages 
 67585  ** that the new child-page now contains pointers to are updated. The
 67586  ** entry corresponding to the new right-child pointer of the root
 67587  ** page is also updated.
 67588  **
 67589  ** If successful, *ppChild is set to contain a reference to the child 
 67590  ** page and SQLITE_OK is returned. In this case the caller is required
 67591  ** to call releasePage() on *ppChild exactly once. If an error occurs,
 67592  ** an error code is returned and *ppChild is set to 0.
 67593  */
 67594  static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
 67595    int rc;                        /* Return value from subprocedures */
 67596    MemPage *pChild = 0;           /* Pointer to a new child page */
 67597    Pgno pgnoChild = 0;            /* Page number of the new child page */
 67598    BtShared *pBt = pRoot->pBt;    /* The BTree */
 67599  
 67600    assert( pRoot->nOverflow>0 );
 67601    assert( sqlite3_mutex_held(pBt->mutex) );
 67602  
 67603    /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
 67604    ** page that will become the new right-child of pPage. Copy the contents
 67605    ** of the node stored on pRoot into the new child page.
 67606    */
 67607    rc = sqlite3PagerWrite(pRoot->pDbPage);
 67608    if( rc==SQLITE_OK ){
 67609      rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
 67610      copyNodeContent(pRoot, pChild, &rc);
 67611      if( ISAUTOVACUUM ){
 67612        ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
 67613      }
 67614    }
 67615    if( rc ){
 67616      *ppChild = 0;
 67617      releasePage(pChild);
 67618      return rc;
 67619    }
 67620    assert( sqlite3PagerIswriteable(pChild->pDbPage) );
 67621    assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
 67622    assert( pChild->nCell==pRoot->nCell );
 67623  
 67624    TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
 67625  
 67626    /* Copy the overflow cells from pRoot to pChild */
 67627    memcpy(pChild->aiOvfl, pRoot->aiOvfl,
 67628           pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
 67629    memcpy(pChild->apOvfl, pRoot->apOvfl,
 67630           pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
 67631    pChild->nOverflow = pRoot->nOverflow;
 67632  
 67633    /* Zero the contents of pRoot. Then install pChild as the right-child. */
 67634    zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
 67635    put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
 67636  
 67637    *ppChild = pChild;
 67638    return SQLITE_OK;
 67639  }
 67640  
 67641  /*
 67642  ** The page that pCur currently points to has just been modified in
 67643  ** some way. This function figures out if this modification means the
 67644  ** tree needs to be balanced, and if so calls the appropriate balancing 
 67645  ** routine. Balancing routines are:
 67646  **
 67647  **   balance_quick()
 67648  **   balance_deeper()
 67649  **   balance_nonroot()
 67650  */
 67651  static int balance(BtCursor *pCur){
 67652    int rc = SQLITE_OK;
 67653    const int nMin = pCur->pBt->usableSize * 2 / 3;
 67654    u8 aBalanceQuickSpace[13];
 67655    u8 *pFree = 0;
 67656  
 67657    VVA_ONLY( int balance_quick_called = 0 );
 67658    VVA_ONLY( int balance_deeper_called = 0 );
 67659  
 67660    do {
 67661      int iPage = pCur->iPage;
 67662      MemPage *pPage = pCur->pPage;
 67663  
 67664      if( iPage==0 ){
 67665        if( pPage->nOverflow ){
 67666          /* The root page of the b-tree is overfull. In this case call the
 67667          ** balance_deeper() function to create a new child for the root-page
 67668          ** and copy the current contents of the root-page to it. The
 67669          ** next iteration of the do-loop will balance the child page.
 67670          */ 
 67671          assert( balance_deeper_called==0 );
 67672          VVA_ONLY( balance_deeper_called++ );
 67673          rc = balance_deeper(pPage, &pCur->apPage[1]);
 67674          if( rc==SQLITE_OK ){
 67675            pCur->iPage = 1;
 67676            pCur->ix = 0;
 67677            pCur->aiIdx[0] = 0;
 67678            pCur->apPage[0] = pPage;
 67679            pCur->pPage = pCur->apPage[1];
 67680            assert( pCur->pPage->nOverflow );
 67681          }
 67682        }else{
 67683          break;
 67684        }
 67685      }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
 67686        break;
 67687      }else{
 67688        MemPage * const pParent = pCur->apPage[iPage-1];
 67689        int const iIdx = pCur->aiIdx[iPage-1];
 67690  
 67691        rc = sqlite3PagerWrite(pParent->pDbPage);
 67692        if( rc==SQLITE_OK ){
 67693  #ifndef SQLITE_OMIT_QUICKBALANCE
 67694          if( pPage->intKeyLeaf
 67695           && pPage->nOverflow==1
 67696           && pPage->aiOvfl[0]==pPage->nCell
 67697           && pParent->pgno!=1
 67698           && pParent->nCell==iIdx
 67699          ){
 67700            /* Call balance_quick() to create a new sibling of pPage on which
 67701            ** to store the overflow cell. balance_quick() inserts a new cell
 67702            ** into pParent, which may cause pParent overflow. If this
 67703            ** happens, the next iteration of the do-loop will balance pParent 
 67704            ** use either balance_nonroot() or balance_deeper(). Until this
 67705            ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
 67706            ** buffer. 
 67707            **
 67708            ** The purpose of the following assert() is to check that only a
 67709            ** single call to balance_quick() is made for each call to this
 67710            ** function. If this were not verified, a subtle bug involving reuse
 67711            ** of the aBalanceQuickSpace[] might sneak in.
 67712            */
 67713            assert( balance_quick_called==0 ); 
 67714            VVA_ONLY( balance_quick_called++ );
 67715            rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
 67716          }else
 67717  #endif
 67718          {
 67719            /* In this case, call balance_nonroot() to redistribute cells
 67720            ** between pPage and up to 2 of its sibling pages. This involves
 67721            ** modifying the contents of pParent, which may cause pParent to
 67722            ** become overfull or underfull. The next iteration of the do-loop
 67723            ** will balance the parent page to correct this.
 67724            ** 
 67725            ** If the parent page becomes overfull, the overflow cell or cells
 67726            ** are stored in the pSpace buffer allocated immediately below. 
 67727            ** A subsequent iteration of the do-loop will deal with this by
 67728            ** calling balance_nonroot() (balance_deeper() may be called first,
 67729            ** but it doesn't deal with overflow cells - just moves them to a
 67730            ** different page). Once this subsequent call to balance_nonroot() 
 67731            ** has completed, it is safe to release the pSpace buffer used by
 67732            ** the previous call, as the overflow cell data will have been 
 67733            ** copied either into the body of a database page or into the new
 67734            ** pSpace buffer passed to the latter call to balance_nonroot().
 67735            */
 67736            u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
 67737            rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
 67738                                 pCur->hints&BTREE_BULKLOAD);
 67739            if( pFree ){
 67740              /* If pFree is not NULL, it points to the pSpace buffer used 
 67741              ** by a previous call to balance_nonroot(). Its contents are
 67742              ** now stored either on real database pages or within the 
 67743              ** new pSpace buffer, so it may be safely freed here. */
 67744              sqlite3PageFree(pFree);
 67745            }
 67746  
 67747            /* The pSpace buffer will be freed after the next call to
 67748            ** balance_nonroot(), or just before this function returns, whichever
 67749            ** comes first. */
 67750            pFree = pSpace;
 67751          }
 67752        }
 67753  
 67754        pPage->nOverflow = 0;
 67755  
 67756        /* The next iteration of the do-loop balances the parent page. */
 67757        releasePage(pPage);
 67758        pCur->iPage--;
 67759        assert( pCur->iPage>=0 );
 67760        pCur->pPage = pCur->apPage[pCur->iPage];
 67761      }
 67762    }while( rc==SQLITE_OK );
 67763  
 67764    if( pFree ){
 67765      sqlite3PageFree(pFree);
 67766    }
 67767    return rc;
 67768  }
 67769  
 67770  
 67771  /*
 67772  ** Insert a new record into the BTree.  The content of the new record
 67773  ** is described by the pX object.  The pCur cursor is used only to
 67774  ** define what table the record should be inserted into, and is left
 67775  ** pointing at a random location.
 67776  **
 67777  ** For a table btree (used for rowid tables), only the pX.nKey value of
 67778  ** the key is used. The pX.pKey value must be NULL.  The pX.nKey is the
 67779  ** rowid or INTEGER PRIMARY KEY of the row.  The pX.nData,pData,nZero fields
 67780  ** hold the content of the row.
 67781  **
 67782  ** For an index btree (used for indexes and WITHOUT ROWID tables), the
 67783  ** key is an arbitrary byte sequence stored in pX.pKey,nKey.  The 
 67784  ** pX.pData,nData,nZero fields must be zero.
 67785  **
 67786  ** If the seekResult parameter is non-zero, then a successful call to
 67787  ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
 67788  ** been performed.  In other words, if seekResult!=0 then the cursor
 67789  ** is currently pointing to a cell that will be adjacent to the cell
 67790  ** to be inserted.  If seekResult<0 then pCur points to a cell that is
 67791  ** smaller then (pKey,nKey).  If seekResult>0 then pCur points to a cell
 67792  ** that is larger than (pKey,nKey).
 67793  **
 67794  ** If seekResult==0, that means pCur is pointing at some unknown location.
 67795  ** In that case, this routine must seek the cursor to the correct insertion
 67796  ** point for (pKey,nKey) before doing the insertion.  For index btrees,
 67797  ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
 67798  ** key values and pX->aMem can be used instead of pX->pKey to avoid having
 67799  ** to decode the key.
 67800  */
 67801  SQLITE_PRIVATE int sqlite3BtreeInsert(
 67802    BtCursor *pCur,                /* Insert data into the table of this cursor */
 67803    const BtreePayload *pX,        /* Content of the row to be inserted */
 67804    int flags,                     /* True if this is likely an append */
 67805    int seekResult                 /* Result of prior MovetoUnpacked() call */
 67806  ){
 67807    int rc;
 67808    int loc = seekResult;          /* -1: before desired location  +1: after */
 67809    int szNew = 0;
 67810    int idx;
 67811    MemPage *pPage;
 67812    Btree *p = pCur->pBtree;
 67813    BtShared *pBt = p->pBt;
 67814    unsigned char *oldCell;
 67815    unsigned char *newCell = 0;
 67816  
 67817    assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
 67818  
 67819    if( pCur->eState==CURSOR_FAULT ){
 67820      assert( pCur->skipNext!=SQLITE_OK );
 67821      return pCur->skipNext;
 67822    }
 67823  
 67824    assert( cursorOwnsBtShared(pCur) );
 67825    assert( (pCur->curFlags & BTCF_WriteFlag)!=0
 67826                && pBt->inTransaction==TRANS_WRITE
 67827                && (pBt->btsFlags & BTS_READ_ONLY)==0 );
 67828    assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
 67829  
 67830    /* Assert that the caller has been consistent. If this cursor was opened
 67831    ** expecting an index b-tree, then the caller should be inserting blob
 67832    ** keys with no associated data. If the cursor was opened expecting an
 67833    ** intkey table, the caller should be inserting integer keys with a
 67834    ** blob of associated data.  */
 67835    assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
 67836  
 67837    /* Save the positions of any other cursors open on this table.
 67838    **
 67839    ** In some cases, the call to btreeMoveto() below is a no-op. For
 67840    ** example, when inserting data into a table with auto-generated integer
 67841    ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
 67842    ** integer key to use. It then calls this function to actually insert the 
 67843    ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
 67844    ** that the cursor is already where it needs to be and returns without
 67845    ** doing any work. To avoid thwarting these optimizations, it is important
 67846    ** not to clear the cursor here.
 67847    */
 67848    if( pCur->curFlags & BTCF_Multiple ){
 67849      rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
 67850      if( rc ) return rc;
 67851    }
 67852  
 67853    if( pCur->pKeyInfo==0 ){
 67854      assert( pX->pKey==0 );
 67855      /* If this is an insert into a table b-tree, invalidate any incrblob 
 67856      ** cursors open on the row being replaced */
 67857      invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
 67858  
 67859      /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing 
 67860      ** to a row with the same key as the new entry being inserted.  */
 67861      assert( (flags & BTREE_SAVEPOSITION)==0 || 
 67862              ((pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey) );
 67863  
 67864      /* If the cursor is currently on the last row and we are appending a
 67865      ** new row onto the end, set the "loc" to avoid an unnecessary
 67866      ** btreeMoveto() call */
 67867      if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
 67868        loc = 0;
 67869      }else if( loc==0 ){
 67870        rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
 67871        if( rc ) return rc;
 67872      }
 67873    }else if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
 67874      if( pX->nMem ){
 67875        UnpackedRecord r;
 67876        r.pKeyInfo = pCur->pKeyInfo;
 67877        r.aMem = pX->aMem;
 67878        r.nField = pX->nMem;
 67879        r.default_rc = 0;
 67880        r.errCode = 0;
 67881        r.r1 = 0;
 67882        r.r2 = 0;
 67883        r.eqSeen = 0;
 67884        rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
 67885      }else{
 67886        rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
 67887      }
 67888      if( rc ) return rc;
 67889    }
 67890    assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
 67891  
 67892    pPage = pCur->pPage;
 67893    assert( pPage->intKey || pX->nKey>=0 );
 67894    assert( pPage->leaf || !pPage->intKey );
 67895  
 67896    TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
 67897            pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
 67898            loc==0 ? "overwrite" : "new entry"));
 67899    assert( pPage->isInit );
 67900    newCell = pBt->pTmpSpace;
 67901    assert( newCell!=0 );
 67902    rc = fillInCell(pPage, newCell, pX, &szNew);
 67903    if( rc ) goto end_insert;
 67904    assert( szNew==pPage->xCellSize(pPage, newCell) );
 67905    assert( szNew <= MX_CELL_SIZE(pBt) );
 67906    idx = pCur->ix;
 67907    if( loc==0 ){
 67908      CellInfo info;
 67909      assert( idx<pPage->nCell );
 67910      rc = sqlite3PagerWrite(pPage->pDbPage);
 67911      if( rc ){
 67912        goto end_insert;
 67913      }
 67914      oldCell = findCell(pPage, idx);
 67915      if( !pPage->leaf ){
 67916        memcpy(newCell, oldCell, 4);
 67917      }
 67918      rc = clearCell(pPage, oldCell, &info);
 67919      if( info.nSize==szNew && info.nLocal==info.nPayload 
 67920       && (!ISAUTOVACUUM || szNew<pPage->minLocal)
 67921      ){
 67922        /* Overwrite the old cell with the new if they are the same size.
 67923        ** We could also try to do this if the old cell is smaller, then add
 67924        ** the leftover space to the free list.  But experiments show that
 67925        ** doing that is no faster then skipping this optimization and just
 67926        ** calling dropCell() and insertCell(). 
 67927        **
 67928        ** This optimization cannot be used on an autovacuum database if the
 67929        ** new entry uses overflow pages, as the insertCell() call below is
 67930        ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry.  */
 67931        assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
 67932        if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
 67933        memcpy(oldCell, newCell, szNew);
 67934        return SQLITE_OK;
 67935      }
 67936      dropCell(pPage, idx, info.nSize, &rc);
 67937      if( rc ) goto end_insert;
 67938    }else if( loc<0 && pPage->nCell>0 ){
 67939      assert( pPage->leaf );
 67940      idx = ++pCur->ix;
 67941      pCur->curFlags &= ~BTCF_ValidNKey;
 67942    }else{
 67943      assert( pPage->leaf );
 67944    }
 67945    insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
 67946    assert( pPage->nOverflow==0 || rc==SQLITE_OK );
 67947    assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
 67948  
 67949    /* If no error has occurred and pPage has an overflow cell, call balance() 
 67950    ** to redistribute the cells within the tree. Since balance() may move
 67951    ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
 67952    ** variables.
 67953    **
 67954    ** Previous versions of SQLite called moveToRoot() to move the cursor
 67955    ** back to the root page as balance() used to invalidate the contents
 67956    ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
 67957    ** set the cursor state to "invalid". This makes common insert operations
 67958    ** slightly faster.
 67959    **
 67960    ** There is a subtle but important optimization here too. When inserting
 67961    ** multiple records into an intkey b-tree using a single cursor (as can
 67962    ** happen while processing an "INSERT INTO ... SELECT" statement), it
 67963    ** is advantageous to leave the cursor pointing to the last entry in
 67964    ** the b-tree if possible. If the cursor is left pointing to the last
 67965    ** entry in the table, and the next row inserted has an integer key
 67966    ** larger than the largest existing key, it is possible to insert the
 67967    ** row without seeking the cursor. This can be a big performance boost.
 67968    */
 67969    pCur->info.nSize = 0;
 67970    if( pPage->nOverflow ){
 67971      assert( rc==SQLITE_OK );
 67972      pCur->curFlags &= ~(BTCF_ValidNKey);
 67973      rc = balance(pCur);
 67974  
 67975      /* Must make sure nOverflow is reset to zero even if the balance()
 67976      ** fails. Internal data structure corruption will result otherwise. 
 67977      ** Also, set the cursor state to invalid. This stops saveCursorPosition()
 67978      ** from trying to save the current position of the cursor.  */
 67979      pCur->pPage->nOverflow = 0;
 67980      pCur->eState = CURSOR_INVALID;
 67981      if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
 67982        btreeReleaseAllCursorPages(pCur);
 67983        if( pCur->pKeyInfo ){
 67984          assert( pCur->pKey==0 );
 67985          pCur->pKey = sqlite3Malloc( pX->nKey );
 67986          if( pCur->pKey==0 ){
 67987            rc = SQLITE_NOMEM;
 67988          }else{
 67989            memcpy(pCur->pKey, pX->pKey, pX->nKey);
 67990          }
 67991        }
 67992        pCur->eState = CURSOR_REQUIRESEEK;
 67993        pCur->nKey = pX->nKey;
 67994      }
 67995    }
 67996    assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
 67997  
 67998  end_insert:
 67999    return rc;
 68000  }
 68001  
 68002  /*
 68003  ** Delete the entry that the cursor is pointing to. 
 68004  **
 68005  ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
 68006  ** the cursor is left pointing at an arbitrary location after the delete.
 68007  ** But if that bit is set, then the cursor is left in a state such that
 68008  ** the next call to BtreeNext() or BtreePrev() moves it to the same row
 68009  ** as it would have been on if the call to BtreeDelete() had been omitted.
 68010  **
 68011  ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
 68012  ** associated with a single table entry and its indexes.  Only one of those
 68013  ** deletes is considered the "primary" delete.  The primary delete occurs
 68014  ** on a cursor that is not a BTREE_FORDELETE cursor.  All but one delete
 68015  ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
 68016  ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
 68017  ** but which might be used by alternative storage engines.
 68018  */
 68019  SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
 68020    Btree *p = pCur->pBtree;
 68021    BtShared *pBt = p->pBt;              
 68022    int rc;                              /* Return code */
 68023    MemPage *pPage;                      /* Page to delete cell from */
 68024    unsigned char *pCell;                /* Pointer to cell to delete */
 68025    int iCellIdx;                        /* Index of cell to delete */
 68026    int iCellDepth;                      /* Depth of node containing pCell */ 
 68027    CellInfo info;                       /* Size of the cell being deleted */
 68028    int bSkipnext = 0;                   /* Leaf cursor in SKIPNEXT state */
 68029    u8 bPreserve = flags & BTREE_SAVEPOSITION;  /* Keep cursor valid */
 68030  
 68031    assert( cursorOwnsBtShared(pCur) );
 68032    assert( pBt->inTransaction==TRANS_WRITE );
 68033    assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
 68034    assert( pCur->curFlags & BTCF_WriteFlag );
 68035    assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
 68036    assert( !hasReadConflicts(p, pCur->pgnoRoot) );
 68037    assert( pCur->ix<pCur->pPage->nCell );
 68038    assert( pCur->eState==CURSOR_VALID );
 68039    assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
 68040  
 68041    iCellDepth = pCur->iPage;
 68042    iCellIdx = pCur->ix;
 68043    pPage = pCur->pPage;
 68044    pCell = findCell(pPage, iCellIdx);
 68045  
 68046    /* If the bPreserve flag is set to true, then the cursor position must
 68047    ** be preserved following this delete operation. If the current delete
 68048    ** will cause a b-tree rebalance, then this is done by saving the cursor
 68049    ** key and leaving the cursor in CURSOR_REQUIRESEEK state before 
 68050    ** returning. 
 68051    **
 68052    ** Or, if the current delete will not cause a rebalance, then the cursor
 68053    ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
 68054    ** before or after the deleted entry. In this case set bSkipnext to true.  */
 68055    if( bPreserve ){
 68056      if( !pPage->leaf 
 68057       || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
 68058      ){
 68059        /* A b-tree rebalance will be required after deleting this entry.
 68060        ** Save the cursor key.  */
 68061        rc = saveCursorKey(pCur);
 68062        if( rc ) return rc;
 68063      }else{
 68064        bSkipnext = 1;
 68065      }
 68066    }
 68067  
 68068    /* If the page containing the entry to delete is not a leaf page, move
 68069    ** the cursor to the largest entry in the tree that is smaller than
 68070    ** the entry being deleted. This cell will replace the cell being deleted
 68071    ** from the internal node. The 'previous' entry is used for this instead
 68072    ** of the 'next' entry, as the previous entry is always a part of the
 68073    ** sub-tree headed by the child page of the cell being deleted. This makes
 68074    ** balancing the tree following the delete operation easier.  */
 68075    if( !pPage->leaf ){
 68076      rc = sqlite3BtreePrevious(pCur, 0);
 68077      assert( rc!=SQLITE_DONE );
 68078      if( rc ) return rc;
 68079    }
 68080  
 68081    /* Save the positions of any other cursors open on this table before
 68082    ** making any modifications.  */
 68083    if( pCur->curFlags & BTCF_Multiple ){
 68084      rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
 68085      if( rc ) return rc;
 68086    }
 68087  
 68088    /* If this is a delete operation to remove a row from a table b-tree,
 68089    ** invalidate any incrblob cursors open on the row being deleted.  */
 68090    if( pCur->pKeyInfo==0 ){
 68091      invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
 68092    }
 68093  
 68094    /* Make the page containing the entry to be deleted writable. Then free any
 68095    ** overflow pages associated with the entry and finally remove the cell
 68096    ** itself from within the page.  */
 68097    rc = sqlite3PagerWrite(pPage->pDbPage);
 68098    if( rc ) return rc;
 68099    rc = clearCell(pPage, pCell, &info);
 68100    dropCell(pPage, iCellIdx, info.nSize, &rc);
 68101    if( rc ) return rc;
 68102  
 68103    /* If the cell deleted was not located on a leaf page, then the cursor
 68104    ** is currently pointing to the largest entry in the sub-tree headed
 68105    ** by the child-page of the cell that was just deleted from an internal
 68106    ** node. The cell from the leaf node needs to be moved to the internal
 68107    ** node to replace the deleted cell.  */
 68108    if( !pPage->leaf ){
 68109      MemPage *pLeaf = pCur->pPage;
 68110      int nCell;
 68111      Pgno n;
 68112      unsigned char *pTmp;
 68113  
 68114      if( iCellDepth<pCur->iPage-1 ){
 68115        n = pCur->apPage[iCellDepth+1]->pgno;
 68116      }else{
 68117        n = pCur->pPage->pgno;
 68118      }
 68119      pCell = findCell(pLeaf, pLeaf->nCell-1);
 68120      if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
 68121      nCell = pLeaf->xCellSize(pLeaf, pCell);
 68122      assert( MX_CELL_SIZE(pBt) >= nCell );
 68123      pTmp = pBt->pTmpSpace;
 68124      assert( pTmp!=0 );
 68125      rc = sqlite3PagerWrite(pLeaf->pDbPage);
 68126      if( rc==SQLITE_OK ){
 68127        insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
 68128      }
 68129      dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
 68130      if( rc ) return rc;
 68131    }
 68132  
 68133    /* Balance the tree. If the entry deleted was located on a leaf page,
 68134    ** then the cursor still points to that page. In this case the first
 68135    ** call to balance() repairs the tree, and the if(...) condition is
 68136    ** never true.
 68137    **
 68138    ** Otherwise, if the entry deleted was on an internal node page, then
 68139    ** pCur is pointing to the leaf page from which a cell was removed to
 68140    ** replace the cell deleted from the internal node. This is slightly
 68141    ** tricky as the leaf node may be underfull, and the internal node may
 68142    ** be either under or overfull. In this case run the balancing algorithm
 68143    ** on the leaf node first. If the balance proceeds far enough up the
 68144    ** tree that we can be sure that any problem in the internal node has
 68145    ** been corrected, so be it. Otherwise, after balancing the leaf node,
 68146    ** walk the cursor up the tree to the internal node and balance it as 
 68147    ** well.  */
 68148    rc = balance(pCur);
 68149    if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
 68150      releasePageNotNull(pCur->pPage);
 68151      pCur->iPage--;
 68152      while( pCur->iPage>iCellDepth ){
 68153        releasePage(pCur->apPage[pCur->iPage--]);
 68154      }
 68155      pCur->pPage = pCur->apPage[pCur->iPage];
 68156      rc = balance(pCur);
 68157    }
 68158  
 68159    if( rc==SQLITE_OK ){
 68160      if( bSkipnext ){
 68161        assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
 68162        assert( pPage==pCur->pPage || CORRUPT_DB );
 68163        assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
 68164        pCur->eState = CURSOR_SKIPNEXT;
 68165        if( iCellIdx>=pPage->nCell ){
 68166          pCur->skipNext = -1;
 68167          pCur->ix = pPage->nCell-1;
 68168        }else{
 68169          pCur->skipNext = 1;
 68170        }
 68171      }else{
 68172        rc = moveToRoot(pCur);
 68173        if( bPreserve ){
 68174          btreeReleaseAllCursorPages(pCur);
 68175          pCur->eState = CURSOR_REQUIRESEEK;
 68176        }
 68177        if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
 68178      }
 68179    }
 68180    return rc;
 68181  }
 68182  
 68183  /*
 68184  ** Create a new BTree table.  Write into *piTable the page
 68185  ** number for the root page of the new table.
 68186  **
 68187  ** The type of type is determined by the flags parameter.  Only the
 68188  ** following values of flags are currently in use.  Other values for
 68189  ** flags might not work:
 68190  **
 68191  **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
 68192  **     BTREE_ZERODATA                  Used for SQL indices
 68193  */
 68194  static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
 68195    BtShared *pBt = p->pBt;
 68196    MemPage *pRoot;
 68197    Pgno pgnoRoot;
 68198    int rc;
 68199    int ptfFlags;          /* Page-type flage for the root page of new table */
 68200  
 68201    assert( sqlite3BtreeHoldsMutex(p) );
 68202    assert( pBt->inTransaction==TRANS_WRITE );
 68203    assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
 68204  
 68205  #ifdef SQLITE_OMIT_AUTOVACUUM
 68206    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
 68207    if( rc ){
 68208      return rc;
 68209    }
 68210  #else
 68211    if( pBt->autoVacuum ){
 68212      Pgno pgnoMove;      /* Move a page here to make room for the root-page */
 68213      MemPage *pPageMove; /* The page to move to. */
 68214  
 68215      /* Creating a new table may probably require moving an existing database
 68216      ** to make room for the new tables root page. In case this page turns
 68217      ** out to be an overflow page, delete all overflow page-map caches
 68218      ** held by open cursors.
 68219      */
 68220      invalidateAllOverflowCache(pBt);
 68221  
 68222      /* Read the value of meta[3] from the database to determine where the
 68223      ** root page of the new table should go. meta[3] is the largest root-page
 68224      ** created so far, so the new root-page is (meta[3]+1).
 68225      */
 68226      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
 68227      pgnoRoot++;
 68228  
 68229      /* The new root-page may not be allocated on a pointer-map page, or the
 68230      ** PENDING_BYTE page.
 68231      */
 68232      while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
 68233          pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
 68234        pgnoRoot++;
 68235      }
 68236      assert( pgnoRoot>=3 || CORRUPT_DB );
 68237      testcase( pgnoRoot<3 );
 68238  
 68239      /* Allocate a page. The page that currently resides at pgnoRoot will
 68240      ** be moved to the allocated page (unless the allocated page happens
 68241      ** to reside at pgnoRoot).
 68242      */
 68243      rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
 68244      if( rc!=SQLITE_OK ){
 68245        return rc;
 68246      }
 68247  
 68248      if( pgnoMove!=pgnoRoot ){
 68249        /* pgnoRoot is the page that will be used for the root-page of
 68250        ** the new table (assuming an error did not occur). But we were
 68251        ** allocated pgnoMove. If required (i.e. if it was not allocated
 68252        ** by extending the file), the current page at position pgnoMove
 68253        ** is already journaled.
 68254        */
 68255        u8 eType = 0;
 68256        Pgno iPtrPage = 0;
 68257  
 68258        /* Save the positions of any open cursors. This is required in
 68259        ** case they are holding a reference to an xFetch reference
 68260        ** corresponding to page pgnoRoot.  */
 68261        rc = saveAllCursors(pBt, 0, 0);
 68262        releasePage(pPageMove);
 68263        if( rc!=SQLITE_OK ){
 68264          return rc;
 68265        }
 68266  
 68267        /* Move the page currently at pgnoRoot to pgnoMove. */
 68268        rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
 68269        if( rc!=SQLITE_OK ){
 68270          return rc;
 68271        }
 68272        rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
 68273        if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
 68274          rc = SQLITE_CORRUPT_BKPT;
 68275        }
 68276        if( rc!=SQLITE_OK ){
 68277          releasePage(pRoot);
 68278          return rc;
 68279        }
 68280        assert( eType!=PTRMAP_ROOTPAGE );
 68281        assert( eType!=PTRMAP_FREEPAGE );
 68282        rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
 68283        releasePage(pRoot);
 68284  
 68285        /* Obtain the page at pgnoRoot */
 68286        if( rc!=SQLITE_OK ){
 68287          return rc;
 68288        }
 68289        rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
 68290        if( rc!=SQLITE_OK ){
 68291          return rc;
 68292        }
 68293        rc = sqlite3PagerWrite(pRoot->pDbPage);
 68294        if( rc!=SQLITE_OK ){
 68295          releasePage(pRoot);
 68296          return rc;
 68297        }
 68298      }else{
 68299        pRoot = pPageMove;
 68300      } 
 68301  
 68302      /* Update the pointer-map and meta-data with the new root-page number. */
 68303      ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
 68304      if( rc ){
 68305        releasePage(pRoot);
 68306        return rc;
 68307      }
 68308  
 68309      /* When the new root page was allocated, page 1 was made writable in
 68310      ** order either to increase the database filesize, or to decrement the
 68311      ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
 68312      */
 68313      assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
 68314      rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
 68315      if( NEVER(rc) ){
 68316        releasePage(pRoot);
 68317        return rc;
 68318      }
 68319  
 68320    }else{
 68321      rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
 68322      if( rc ) return rc;
 68323    }
 68324  #endif
 68325    assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
 68326    if( createTabFlags & BTREE_INTKEY ){
 68327      ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
 68328    }else{
 68329      ptfFlags = PTF_ZERODATA | PTF_LEAF;
 68330    }
 68331    zeroPage(pRoot, ptfFlags);
 68332    sqlite3PagerUnref(pRoot->pDbPage);
 68333    assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
 68334    *piTable = (int)pgnoRoot;
 68335    return SQLITE_OK;
 68336  }
 68337  SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
 68338    int rc;
 68339    sqlite3BtreeEnter(p);
 68340    rc = btreeCreateTable(p, piTable, flags);
 68341    sqlite3BtreeLeave(p);
 68342    return rc;
 68343  }
 68344  
 68345  /*
 68346  ** Erase the given database page and all its children.  Return
 68347  ** the page to the freelist.
 68348  */
 68349  static int clearDatabasePage(
 68350    BtShared *pBt,           /* The BTree that contains the table */
 68351    Pgno pgno,               /* Page number to clear */
 68352    int freePageFlag,        /* Deallocate page if true */
 68353    int *pnChange            /* Add number of Cells freed to this counter */
 68354  ){
 68355    MemPage *pPage;
 68356    int rc;
 68357    unsigned char *pCell;
 68358    int i;
 68359    int hdr;
 68360    CellInfo info;
 68361  
 68362    assert( sqlite3_mutex_held(pBt->mutex) );
 68363    if( pgno>btreePagecount(pBt) ){
 68364      return SQLITE_CORRUPT_BKPT;
 68365    }
 68366    rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
 68367    if( rc ) return rc;
 68368    if( pPage->bBusy ){
 68369      rc = SQLITE_CORRUPT_BKPT;
 68370      goto cleardatabasepage_out;
 68371    }
 68372    pPage->bBusy = 1;
 68373    hdr = pPage->hdrOffset;
 68374    for(i=0; i<pPage->nCell; i++){
 68375      pCell = findCell(pPage, i);
 68376      if( !pPage->leaf ){
 68377        rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
 68378        if( rc ) goto cleardatabasepage_out;
 68379      }
 68380      rc = clearCell(pPage, pCell, &info);
 68381      if( rc ) goto cleardatabasepage_out;
 68382    }
 68383    if( !pPage->leaf ){
 68384      rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
 68385      if( rc ) goto cleardatabasepage_out;
 68386    }else if( pnChange ){
 68387      assert( pPage->intKey || CORRUPT_DB );
 68388      testcase( !pPage->intKey );
 68389      *pnChange += pPage->nCell;
 68390    }
 68391    if( freePageFlag ){
 68392      freePage(pPage, &rc);
 68393    }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
 68394      zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
 68395    }
 68396  
 68397  cleardatabasepage_out:
 68398    pPage->bBusy = 0;
 68399    releasePage(pPage);
 68400    return rc;
 68401  }
 68402  
 68403  /*
 68404  ** Delete all information from a single table in the database.  iTable is
 68405  ** the page number of the root of the table.  After this routine returns,
 68406  ** the root page is empty, but still exists.
 68407  **
 68408  ** This routine will fail with SQLITE_LOCKED if there are any open
 68409  ** read cursors on the table.  Open write cursors are moved to the
 68410  ** root of the table.
 68411  **
 68412  ** If pnChange is not NULL, then table iTable must be an intkey table. The
 68413  ** integer value pointed to by pnChange is incremented by the number of
 68414  ** entries in the table.
 68415  */
 68416  SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
 68417    int rc;
 68418    BtShared *pBt = p->pBt;
 68419    sqlite3BtreeEnter(p);
 68420    assert( p->inTrans==TRANS_WRITE );
 68421  
 68422    rc = saveAllCursors(pBt, (Pgno)iTable, 0);
 68423  
 68424    if( SQLITE_OK==rc ){
 68425      /* Invalidate all incrblob cursors open on table iTable (assuming iTable
 68426      ** is the root of a table b-tree - if it is not, the following call is
 68427      ** a no-op).  */
 68428      invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
 68429      rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
 68430    }
 68431    sqlite3BtreeLeave(p);
 68432    return rc;
 68433  }
 68434  
 68435  /*
 68436  ** Delete all information from the single table that pCur is open on.
 68437  **
 68438  ** This routine only work for pCur on an ephemeral table.
 68439  */
 68440  SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
 68441    return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
 68442  }
 68443  
 68444  /*
 68445  ** Erase all information in a table and add the root of the table to
 68446  ** the freelist.  Except, the root of the principle table (the one on
 68447  ** page 1) is never added to the freelist.
 68448  **
 68449  ** This routine will fail with SQLITE_LOCKED if there are any open
 68450  ** cursors on the table.
 68451  **
 68452  ** If AUTOVACUUM is enabled and the page at iTable is not the last
 68453  ** root page in the database file, then the last root page 
 68454  ** in the database file is moved into the slot formerly occupied by
 68455  ** iTable and that last slot formerly occupied by the last root page
 68456  ** is added to the freelist instead of iTable.  In this say, all
 68457  ** root pages are kept at the beginning of the database file, which
 68458  ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
 68459  ** page number that used to be the last root page in the file before
 68460  ** the move.  If no page gets moved, *piMoved is set to 0.
 68461  ** The last root page is recorded in meta[3] and the value of
 68462  ** meta[3] is updated by this procedure.
 68463  */
 68464  static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
 68465    int rc;
 68466    MemPage *pPage = 0;
 68467    BtShared *pBt = p->pBt;
 68468  
 68469    assert( sqlite3BtreeHoldsMutex(p) );
 68470    assert( p->inTrans==TRANS_WRITE );
 68471    assert( iTable>=2 );
 68472  
 68473    rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
 68474    if( rc ) return rc;
 68475    rc = sqlite3BtreeClearTable(p, iTable, 0);
 68476    if( rc ){
 68477      releasePage(pPage);
 68478      return rc;
 68479    }
 68480  
 68481    *piMoved = 0;
 68482  
 68483  #ifdef SQLITE_OMIT_AUTOVACUUM
 68484    freePage(pPage, &rc);
 68485    releasePage(pPage);
 68486  #else
 68487    if( pBt->autoVacuum ){
 68488      Pgno maxRootPgno;
 68489      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
 68490  
 68491      if( iTable==maxRootPgno ){
 68492        /* If the table being dropped is the table with the largest root-page
 68493        ** number in the database, put the root page on the free list. 
 68494        */
 68495        freePage(pPage, &rc);
 68496        releasePage(pPage);
 68497        if( rc!=SQLITE_OK ){
 68498          return rc;
 68499        }
 68500      }else{
 68501        /* The table being dropped does not have the largest root-page
 68502        ** number in the database. So move the page that does into the 
 68503        ** gap left by the deleted root-page.
 68504        */
 68505        MemPage *pMove;
 68506        releasePage(pPage);
 68507        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
 68508        if( rc!=SQLITE_OK ){
 68509          return rc;
 68510        }
 68511        rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
 68512        releasePage(pMove);
 68513        if( rc!=SQLITE_OK ){
 68514          return rc;
 68515        }
 68516        pMove = 0;
 68517        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
 68518        freePage(pMove, &rc);
 68519        releasePage(pMove);
 68520        if( rc!=SQLITE_OK ){
 68521          return rc;
 68522        }
 68523        *piMoved = maxRootPgno;
 68524      }
 68525  
 68526      /* Set the new 'max-root-page' value in the database header. This
 68527      ** is the old value less one, less one more if that happens to
 68528      ** be a root-page number, less one again if that is the
 68529      ** PENDING_BYTE_PAGE.
 68530      */
 68531      maxRootPgno--;
 68532      while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
 68533             || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
 68534        maxRootPgno--;
 68535      }
 68536      assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
 68537  
 68538      rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
 68539    }else{
 68540      freePage(pPage, &rc);
 68541      releasePage(pPage);
 68542    }
 68543  #endif
 68544    return rc;  
 68545  }
 68546  SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
 68547    int rc;
 68548    sqlite3BtreeEnter(p);
 68549    rc = btreeDropTable(p, iTable, piMoved);
 68550    sqlite3BtreeLeave(p);
 68551    return rc;
 68552  }
 68553  
 68554  
 68555  /*
 68556  ** This function may only be called if the b-tree connection already
 68557  ** has a read or write transaction open on the database.
 68558  **
 68559  ** Read the meta-information out of a database file.  Meta[0]
 68560  ** is the number of free pages currently in the database.  Meta[1]
 68561  ** through meta[15] are available for use by higher layers.  Meta[0]
 68562  ** is read-only, the others are read/write.
 68563  ** 
 68564  ** The schema layer numbers meta values differently.  At the schema
 68565  ** layer (and the SetCookie and ReadCookie opcodes) the number of
 68566  ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
 68567  **
 68568  ** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead
 68569  ** of reading the value out of the header, it instead loads the "DataVersion"
 68570  ** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the
 68571  ** database file.  It is a number computed by the pager.  But its access
 68572  ** pattern is the same as header meta values, and so it is convenient to
 68573  ** read it from this routine.
 68574  */
 68575  SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
 68576    BtShared *pBt = p->pBt;
 68577  
 68578    sqlite3BtreeEnter(p);
 68579    assert( p->inTrans>TRANS_NONE );
 68580    assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
 68581    assert( pBt->pPage1 );
 68582    assert( idx>=0 && idx<=15 );
 68583  
 68584    if( idx==BTREE_DATA_VERSION ){
 68585      *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
 68586    }else{
 68587      *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
 68588    }
 68589  
 68590    /* If auto-vacuum is disabled in this build and this is an auto-vacuum
 68591    ** database, mark the database as read-only.  */
 68592  #ifdef SQLITE_OMIT_AUTOVACUUM
 68593    if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
 68594      pBt->btsFlags |= BTS_READ_ONLY;
 68595    }
 68596  #endif
 68597  
 68598    sqlite3BtreeLeave(p);
 68599  }
 68600  
 68601  /*
 68602  ** Write meta-information back into the database.  Meta[0] is
 68603  ** read-only and may not be written.
 68604  */
 68605  SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
 68606    BtShared *pBt = p->pBt;
 68607    unsigned char *pP1;
 68608    int rc;
 68609    assert( idx>=1 && idx<=15 );
 68610    sqlite3BtreeEnter(p);
 68611    assert( p->inTrans==TRANS_WRITE );
 68612    assert( pBt->pPage1!=0 );
 68613    pP1 = pBt->pPage1->aData;
 68614    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
 68615    if( rc==SQLITE_OK ){
 68616      put4byte(&pP1[36 + idx*4], iMeta);
 68617  #ifndef SQLITE_OMIT_AUTOVACUUM
 68618      if( idx==BTREE_INCR_VACUUM ){
 68619        assert( pBt->autoVacuum || iMeta==0 );
 68620        assert( iMeta==0 || iMeta==1 );
 68621        pBt->incrVacuum = (u8)iMeta;
 68622      }
 68623  #endif
 68624    }
 68625    sqlite3BtreeLeave(p);
 68626    return rc;
 68627  }
 68628  
 68629  #ifndef SQLITE_OMIT_BTREECOUNT
 68630  /*
 68631  ** The first argument, pCur, is a cursor opened on some b-tree. Count the
 68632  ** number of entries in the b-tree and write the result to *pnEntry.
 68633  **
 68634  ** SQLITE_OK is returned if the operation is successfully executed. 
 68635  ** Otherwise, if an error is encountered (i.e. an IO error or database
 68636  ** corruption) an SQLite error code is returned.
 68637  */
 68638  SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
 68639    i64 nEntry = 0;                      /* Value to return in *pnEntry */
 68640    int rc;                              /* Return code */
 68641  
 68642    rc = moveToRoot(pCur);
 68643    if( rc==SQLITE_EMPTY ){
 68644      *pnEntry = 0;
 68645      return SQLITE_OK;
 68646    }
 68647  
 68648    /* Unless an error occurs, the following loop runs one iteration for each
 68649    ** page in the B-Tree structure (not including overflow pages). 
 68650    */
 68651    while( rc==SQLITE_OK ){
 68652      int iIdx;                          /* Index of child node in parent */
 68653      MemPage *pPage;                    /* Current page of the b-tree */
 68654  
 68655      /* If this is a leaf page or the tree is not an int-key tree, then 
 68656      ** this page contains countable entries. Increment the entry counter
 68657      ** accordingly.
 68658      */
 68659      pPage = pCur->pPage;
 68660      if( pPage->leaf || !pPage->intKey ){
 68661        nEntry += pPage->nCell;
 68662      }
 68663  
 68664      /* pPage is a leaf node. This loop navigates the cursor so that it 
 68665      ** points to the first interior cell that it points to the parent of
 68666      ** the next page in the tree that has not yet been visited. The
 68667      ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
 68668      ** of the page, or to the number of cells in the page if the next page
 68669      ** to visit is the right-child of its parent.
 68670      **
 68671      ** If all pages in the tree have been visited, return SQLITE_OK to the
 68672      ** caller.
 68673      */
 68674      if( pPage->leaf ){
 68675        do {
 68676          if( pCur->iPage==0 ){
 68677            /* All pages of the b-tree have been visited. Return successfully. */
 68678            *pnEntry = nEntry;
 68679            return moveToRoot(pCur);
 68680          }
 68681          moveToParent(pCur);
 68682        }while ( pCur->ix>=pCur->pPage->nCell );
 68683  
 68684        pCur->ix++;
 68685        pPage = pCur->pPage;
 68686      }
 68687  
 68688      /* Descend to the child node of the cell that the cursor currently 
 68689      ** points at. This is the right-child if (iIdx==pPage->nCell).
 68690      */
 68691      iIdx = pCur->ix;
 68692      if( iIdx==pPage->nCell ){
 68693        rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
 68694      }else{
 68695        rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
 68696      }
 68697    }
 68698  
 68699    /* An error has occurred. Return an error code. */
 68700    return rc;
 68701  }
 68702  #endif
 68703  
 68704  /*
 68705  ** Return the pager associated with a BTree.  This routine is used for
 68706  ** testing and debugging only.
 68707  */
 68708  SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
 68709    return p->pBt->pPager;
 68710  }
 68711  
 68712  #ifndef SQLITE_OMIT_INTEGRITY_CHECK
 68713  /*
 68714  ** Append a message to the error message string.
 68715  */
 68716  static void checkAppendMsg(
 68717    IntegrityCk *pCheck,
 68718    const char *zFormat,
 68719    ...
 68720  ){
 68721    va_list ap;
 68722    if( !pCheck->mxErr ) return;
 68723    pCheck->mxErr--;
 68724    pCheck->nErr++;
 68725    va_start(ap, zFormat);
 68726    if( pCheck->errMsg.nChar ){
 68727      sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
 68728    }
 68729    if( pCheck->zPfx ){
 68730      sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
 68731    }
 68732    sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
 68733    va_end(ap);
 68734    if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
 68735      pCheck->mallocFailed = 1;
 68736    }
 68737  }
 68738  #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
 68739  
 68740  #ifndef SQLITE_OMIT_INTEGRITY_CHECK
 68741  
 68742  /*
 68743  ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
 68744  ** corresponds to page iPg is already set.
 68745  */
 68746  static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
 68747    assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
 68748    return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
 68749  }
 68750  
 68751  /*
 68752  ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
 68753  */
 68754  static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
 68755    assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
 68756    pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
 68757  }
 68758  
 68759  
 68760  /*
 68761  ** Add 1 to the reference count for page iPage.  If this is the second
 68762  ** reference to the page, add an error message to pCheck->zErrMsg.
 68763  ** Return 1 if there are 2 or more references to the page and 0 if
 68764  ** if this is the first reference to the page.
 68765  **
 68766  ** Also check that the page number is in bounds.
 68767  */
 68768  static int checkRef(IntegrityCk *pCheck, Pgno iPage){
 68769    if( iPage==0 ) return 1;
 68770    if( iPage>pCheck->nPage ){
 68771      checkAppendMsg(pCheck, "invalid page number %d", iPage);
 68772      return 1;
 68773    }
 68774    if( getPageReferenced(pCheck, iPage) ){
 68775      checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
 68776      return 1;
 68777    }
 68778    setPageReferenced(pCheck, iPage);
 68779    return 0;
 68780  }
 68781  
 68782  #ifndef SQLITE_OMIT_AUTOVACUUM
 68783  /*
 68784  ** Check that the entry in the pointer-map for page iChild maps to 
 68785  ** page iParent, pointer type ptrType. If not, append an error message
 68786  ** to pCheck.
 68787  */
 68788  static void checkPtrmap(
 68789    IntegrityCk *pCheck,   /* Integrity check context */
 68790    Pgno iChild,           /* Child page number */
 68791    u8 eType,              /* Expected pointer map type */
 68792    Pgno iParent           /* Expected pointer map parent page number */
 68793  ){
 68794    int rc;
 68795    u8 ePtrmapType;
 68796    Pgno iPtrmapParent;
 68797  
 68798    rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
 68799    if( rc!=SQLITE_OK ){
 68800      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
 68801      checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
 68802      return;
 68803    }
 68804  
 68805    if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
 68806      checkAppendMsg(pCheck,
 68807        "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
 68808        iChild, eType, iParent, ePtrmapType, iPtrmapParent);
 68809    }
 68810  }
 68811  #endif
 68812  
 68813  /*
 68814  ** Check the integrity of the freelist or of an overflow page list.
 68815  ** Verify that the number of pages on the list is N.
 68816  */
 68817  static void checkList(
 68818    IntegrityCk *pCheck,  /* Integrity checking context */
 68819    int isFreeList,       /* True for a freelist.  False for overflow page list */
 68820    int iPage,            /* Page number for first page in the list */
 68821    int N                 /* Expected number of pages in the list */
 68822  ){
 68823    int i;
 68824    int expected = N;
 68825    int iFirst = iPage;
 68826    while( N-- > 0 && pCheck->mxErr ){
 68827      DbPage *pOvflPage;
 68828      unsigned char *pOvflData;
 68829      if( iPage<1 ){
 68830        checkAppendMsg(pCheck,
 68831           "%d of %d pages missing from overflow list starting at %d",
 68832            N+1, expected, iFirst);
 68833        break;
 68834      }
 68835      if( checkRef(pCheck, iPage) ) break;
 68836      if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
 68837        checkAppendMsg(pCheck, "failed to get page %d", iPage);
 68838        break;
 68839      }
 68840      pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
 68841      if( isFreeList ){
 68842        int n = get4byte(&pOvflData[4]);
 68843  #ifndef SQLITE_OMIT_AUTOVACUUM
 68844        if( pCheck->pBt->autoVacuum ){
 68845          checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
 68846        }
 68847  #endif
 68848        if( n>(int)pCheck->pBt->usableSize/4-2 ){
 68849          checkAppendMsg(pCheck,
 68850             "freelist leaf count too big on page %d", iPage);
 68851          N--;
 68852        }else{
 68853          for(i=0; i<n; i++){
 68854            Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
 68855  #ifndef SQLITE_OMIT_AUTOVACUUM
 68856            if( pCheck->pBt->autoVacuum ){
 68857              checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
 68858            }
 68859  #endif
 68860            checkRef(pCheck, iFreePage);
 68861          }
 68862          N -= n;
 68863        }
 68864      }
 68865  #ifndef SQLITE_OMIT_AUTOVACUUM
 68866      else{
 68867        /* If this database supports auto-vacuum and iPage is not the last
 68868        ** page in this overflow list, check that the pointer-map entry for
 68869        ** the following page matches iPage.
 68870        */
 68871        if( pCheck->pBt->autoVacuum && N>0 ){
 68872          i = get4byte(pOvflData);
 68873          checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
 68874        }
 68875      }
 68876  #endif
 68877      iPage = get4byte(pOvflData);
 68878      sqlite3PagerUnref(pOvflPage);
 68879  
 68880      if( isFreeList && N<(iPage!=0) ){
 68881        checkAppendMsg(pCheck, "free-page count in header is too small");
 68882      }
 68883    }
 68884  }
 68885  #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
 68886  
 68887  /*
 68888  ** An implementation of a min-heap.
 68889  **
 68890  ** aHeap[0] is the number of elements on the heap.  aHeap[1] is the
 68891  ** root element.  The daughter nodes of aHeap[N] are aHeap[N*2]
 68892  ** and aHeap[N*2+1].
 68893  **
 68894  ** The heap property is this:  Every node is less than or equal to both
 68895  ** of its daughter nodes.  A consequence of the heap property is that the
 68896  ** root node aHeap[1] is always the minimum value currently in the heap.
 68897  **
 68898  ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
 68899  ** the heap, preserving the heap property.  The btreeHeapPull() routine
 68900  ** removes the root element from the heap (the minimum value in the heap)
 68901  ** and then moves other nodes around as necessary to preserve the heap
 68902  ** property.
 68903  **
 68904  ** This heap is used for cell overlap and coverage testing.  Each u32
 68905  ** entry represents the span of a cell or freeblock on a btree page.  
 68906  ** The upper 16 bits are the index of the first byte of a range and the
 68907  ** lower 16 bits are the index of the last byte of that range.
 68908  */
 68909  static void btreeHeapInsert(u32 *aHeap, u32 x){
 68910    u32 j, i = ++aHeap[0];
 68911    aHeap[i] = x;
 68912    while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
 68913      x = aHeap[j];
 68914      aHeap[j] = aHeap[i];
 68915      aHeap[i] = x;
 68916      i = j;
 68917    }
 68918  }
 68919  static int btreeHeapPull(u32 *aHeap, u32 *pOut){
 68920    u32 j, i, x;
 68921    if( (x = aHeap[0])==0 ) return 0;
 68922    *pOut = aHeap[1];
 68923    aHeap[1] = aHeap[x];
 68924    aHeap[x] = 0xffffffff;
 68925    aHeap[0]--;
 68926    i = 1;
 68927    while( (j = i*2)<=aHeap[0] ){
 68928      if( aHeap[j]>aHeap[j+1] ) j++;
 68929      if( aHeap[i]<aHeap[j] ) break;
 68930      x = aHeap[i];
 68931      aHeap[i] = aHeap[j];
 68932      aHeap[j] = x;
 68933      i = j;
 68934    }
 68935    return 1;  
 68936  }
 68937  
 68938  #ifndef SQLITE_OMIT_INTEGRITY_CHECK
 68939  /*
 68940  ** Do various sanity checks on a single page of a tree.  Return
 68941  ** the tree depth.  Root pages return 0.  Parents of root pages
 68942  ** return 1, and so forth.
 68943  ** 
 68944  ** These checks are done:
 68945  **
 68946  **      1.  Make sure that cells and freeblocks do not overlap
 68947  **          but combine to completely cover the page.
 68948  **      2.  Make sure integer cell keys are in order.
 68949  **      3.  Check the integrity of overflow pages.
 68950  **      4.  Recursively call checkTreePage on all children.
 68951  **      5.  Verify that the depth of all children is the same.
 68952  */
 68953  static int checkTreePage(
 68954    IntegrityCk *pCheck,  /* Context for the sanity check */
 68955    int iPage,            /* Page number of the page to check */
 68956    i64 *piMinKey,        /* Write minimum integer primary key here */
 68957    i64 maxKey            /* Error if integer primary key greater than this */
 68958  ){
 68959    MemPage *pPage = 0;      /* The page being analyzed */
 68960    int i;                   /* Loop counter */
 68961    int rc;                  /* Result code from subroutine call */
 68962    int depth = -1, d2;      /* Depth of a subtree */
 68963    int pgno;                /* Page number */
 68964    int nFrag;               /* Number of fragmented bytes on the page */
 68965    int hdr;                 /* Offset to the page header */
 68966    int cellStart;           /* Offset to the start of the cell pointer array */
 68967    int nCell;               /* Number of cells */
 68968    int doCoverageCheck = 1; /* True if cell coverage checking should be done */
 68969    int keyCanBeEqual = 1;   /* True if IPK can be equal to maxKey
 68970                             ** False if IPK must be strictly less than maxKey */
 68971    u8 *data;                /* Page content */
 68972    u8 *pCell;               /* Cell content */
 68973    u8 *pCellIdx;            /* Next element of the cell pointer array */
 68974    BtShared *pBt;           /* The BtShared object that owns pPage */
 68975    u32 pc;                  /* Address of a cell */
 68976    u32 usableSize;          /* Usable size of the page */
 68977    u32 contentOffset;       /* Offset to the start of the cell content area */
 68978    u32 *heap = 0;           /* Min-heap used for checking cell coverage */
 68979    u32 x, prev = 0;         /* Next and previous entry on the min-heap */
 68980    const char *saved_zPfx = pCheck->zPfx;
 68981    int saved_v1 = pCheck->v1;
 68982    int saved_v2 = pCheck->v2;
 68983    u8 savedIsInit = 0;
 68984  
 68985    /* Check that the page exists
 68986    */
 68987    pBt = pCheck->pBt;
 68988    usableSize = pBt->usableSize;
 68989    if( iPage==0 ) return 0;
 68990    if( checkRef(pCheck, iPage) ) return 0;
 68991    pCheck->zPfx = "Page %d: ";
 68992    pCheck->v1 = iPage;
 68993    if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
 68994      checkAppendMsg(pCheck,
 68995         "unable to get the page. error code=%d", rc);
 68996      goto end_of_check;
 68997    }
 68998  
 68999    /* Clear MemPage.isInit to make sure the corruption detection code in
 69000    ** btreeInitPage() is executed.  */
 69001    savedIsInit = pPage->isInit;
 69002    pPage->isInit = 0;
 69003    if( (rc = btreeInitPage(pPage))!=0 ){
 69004      assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
 69005      checkAppendMsg(pCheck,
 69006                     "btreeInitPage() returns error code %d", rc);
 69007      goto end_of_check;
 69008    }
 69009    data = pPage->aData;
 69010    hdr = pPage->hdrOffset;
 69011  
 69012    /* Set up for cell analysis */
 69013    pCheck->zPfx = "On tree page %d cell %d: ";
 69014    contentOffset = get2byteNotZero(&data[hdr+5]);
 69015    assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
 69016  
 69017    /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
 69018    ** number of cells on the page. */
 69019    nCell = get2byte(&data[hdr+3]);
 69020    assert( pPage->nCell==nCell );
 69021  
 69022    /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
 69023    ** immediately follows the b-tree page header. */
 69024    cellStart = hdr + 12 - 4*pPage->leaf;
 69025    assert( pPage->aCellIdx==&data[cellStart] );
 69026    pCellIdx = &data[cellStart + 2*(nCell-1)];
 69027  
 69028    if( !pPage->leaf ){
 69029      /* Analyze the right-child page of internal pages */
 69030      pgno = get4byte(&data[hdr+8]);
 69031  #ifndef SQLITE_OMIT_AUTOVACUUM
 69032      if( pBt->autoVacuum ){
 69033        pCheck->zPfx = "On page %d at right child: ";
 69034        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
 69035      }
 69036  #endif
 69037      depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
 69038      keyCanBeEqual = 0;
 69039    }else{
 69040      /* For leaf pages, the coverage check will occur in the same loop
 69041      ** as the other cell checks, so initialize the heap.  */
 69042      heap = pCheck->heap;
 69043      heap[0] = 0;
 69044    }
 69045  
 69046    /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
 69047    ** integer offsets to the cell contents. */
 69048    for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
 69049      CellInfo info;
 69050  
 69051      /* Check cell size */
 69052      pCheck->v2 = i;
 69053      assert( pCellIdx==&data[cellStart + i*2] );
 69054      pc = get2byteAligned(pCellIdx);
 69055      pCellIdx -= 2;
 69056      if( pc<contentOffset || pc>usableSize-4 ){
 69057        checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
 69058                               pc, contentOffset, usableSize-4);
 69059        doCoverageCheck = 0;
 69060        continue;
 69061      }
 69062      pCell = &data[pc];
 69063      pPage->xParseCell(pPage, pCell, &info);
 69064      if( pc+info.nSize>usableSize ){
 69065        checkAppendMsg(pCheck, "Extends off end of page");
 69066        doCoverageCheck = 0;
 69067        continue;
 69068      }
 69069  
 69070      /* Check for integer primary key out of range */
 69071      if( pPage->intKey ){
 69072        if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
 69073          checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
 69074        }
 69075        maxKey = info.nKey;
 69076        keyCanBeEqual = 0;     /* Only the first key on the page may ==maxKey */
 69077      }
 69078  
 69079      /* Check the content overflow list */
 69080      if( info.nPayload>info.nLocal ){
 69081        int nPage;       /* Number of pages on the overflow chain */
 69082        Pgno pgnoOvfl;   /* First page of the overflow chain */
 69083        assert( pc + info.nSize - 4 <= usableSize );
 69084        nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
 69085        pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
 69086  #ifndef SQLITE_OMIT_AUTOVACUUM
 69087        if( pBt->autoVacuum ){
 69088          checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
 69089        }
 69090  #endif
 69091        checkList(pCheck, 0, pgnoOvfl, nPage);
 69092      }
 69093  
 69094      if( !pPage->leaf ){
 69095        /* Check sanity of left child page for internal pages */
 69096        pgno = get4byte(pCell);
 69097  #ifndef SQLITE_OMIT_AUTOVACUUM
 69098        if( pBt->autoVacuum ){
 69099          checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
 69100        }
 69101  #endif
 69102        d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
 69103        keyCanBeEqual = 0;
 69104        if( d2!=depth ){
 69105          checkAppendMsg(pCheck, "Child page depth differs");
 69106          depth = d2;
 69107        }
 69108      }else{
 69109        /* Populate the coverage-checking heap for leaf pages */
 69110        btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
 69111      }
 69112    }
 69113    *piMinKey = maxKey;
 69114  
 69115    /* Check for complete coverage of the page
 69116    */
 69117    pCheck->zPfx = 0;
 69118    if( doCoverageCheck && pCheck->mxErr>0 ){
 69119      /* For leaf pages, the min-heap has already been initialized and the
 69120      ** cells have already been inserted.  But for internal pages, that has
 69121      ** not yet been done, so do it now */
 69122      if( !pPage->leaf ){
 69123        heap = pCheck->heap;
 69124        heap[0] = 0;
 69125        for(i=nCell-1; i>=0; i--){
 69126          u32 size;
 69127          pc = get2byteAligned(&data[cellStart+i*2]);
 69128          size = pPage->xCellSize(pPage, &data[pc]);
 69129          btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
 69130        }
 69131      }
 69132      /* Add the freeblocks to the min-heap
 69133      **
 69134      ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
 69135      ** is the offset of the first freeblock, or zero if there are no
 69136      ** freeblocks on the page. 
 69137      */
 69138      i = get2byte(&data[hdr+1]);
 69139      while( i>0 ){
 69140        int size, j;
 69141        assert( (u32)i<=usableSize-4 );     /* Enforced by btreeInitPage() */
 69142        size = get2byte(&data[i+2]);
 69143        assert( (u32)(i+size)<=usableSize );  /* Enforced by btreeInitPage() */
 69144        btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
 69145        /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
 69146        ** big-endian integer which is the offset in the b-tree page of the next
 69147        ** freeblock in the chain, or zero if the freeblock is the last on the
 69148        ** chain. */
 69149        j = get2byte(&data[i]);
 69150        /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
 69151        ** increasing offset. */
 69152        assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
 69153        assert( (u32)j<=usableSize-4 );   /* Enforced by btreeInitPage() */
 69154        i = j;
 69155      }
 69156      /* Analyze the min-heap looking for overlap between cells and/or 
 69157      ** freeblocks, and counting the number of untracked bytes in nFrag.
 69158      ** 
 69159      ** Each min-heap entry is of the form:    (start_address<<16)|end_address.
 69160      ** There is an implied first entry the covers the page header, the cell
 69161      ** pointer index, and the gap between the cell pointer index and the start
 69162      ** of cell content.  
 69163      **
 69164      ** The loop below pulls entries from the min-heap in order and compares
 69165      ** the start_address against the previous end_address.  If there is an
 69166      ** overlap, that means bytes are used multiple times.  If there is a gap,
 69167      ** that gap is added to the fragmentation count.
 69168      */
 69169      nFrag = 0;
 69170      prev = contentOffset - 1;   /* Implied first min-heap entry */
 69171      while( btreeHeapPull(heap,&x) ){
 69172        if( (prev&0xffff)>=(x>>16) ){
 69173          checkAppendMsg(pCheck,
 69174            "Multiple uses for byte %u of page %d", x>>16, iPage);
 69175          break;
 69176        }else{
 69177          nFrag += (x>>16) - (prev&0xffff) - 1;
 69178          prev = x;
 69179        }
 69180      }
 69181      nFrag += usableSize - (prev&0xffff) - 1;
 69182      /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
 69183      ** is stored in the fifth field of the b-tree page header.
 69184      ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
 69185      ** number of fragmented free bytes within the cell content area.
 69186      */
 69187      if( heap[0]==0 && nFrag!=data[hdr+7] ){
 69188        checkAppendMsg(pCheck,
 69189            "Fragmentation of %d bytes reported as %d on page %d",
 69190            nFrag, data[hdr+7], iPage);
 69191      }
 69192    }
 69193  
 69194  end_of_check:
 69195    if( !doCoverageCheck ) pPage->isInit = savedIsInit;
 69196    releasePage(pPage);
 69197    pCheck->zPfx = saved_zPfx;
 69198    pCheck->v1 = saved_v1;
 69199    pCheck->v2 = saved_v2;
 69200    return depth+1;
 69201  }
 69202  #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
 69203  
 69204  #ifndef SQLITE_OMIT_INTEGRITY_CHECK
 69205  /*
 69206  ** This routine does a complete check of the given BTree file.  aRoot[] is
 69207  ** an array of pages numbers were each page number is the root page of
 69208  ** a table.  nRoot is the number of entries in aRoot.
 69209  **
 69210  ** A read-only or read-write transaction must be opened before calling
 69211  ** this function.
 69212  **
 69213  ** Write the number of error seen in *pnErr.  Except for some memory
 69214  ** allocation errors,  an error message held in memory obtained from
 69215  ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
 69216  ** returned.  If a memory allocation error occurs, NULL is returned.
 69217  */
 69218  SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
 69219    Btree *p,     /* The btree to be checked */
 69220    int *aRoot,   /* An array of root pages numbers for individual trees */
 69221    int nRoot,    /* Number of entries in aRoot[] */
 69222    int mxErr,    /* Stop reporting errors after this many */
 69223    int *pnErr    /* Write number of errors seen to this variable */
 69224  ){
 69225    Pgno i;
 69226    IntegrityCk sCheck;
 69227    BtShared *pBt = p->pBt;
 69228    int savedDbFlags = pBt->db->flags;
 69229    char zErr[100];
 69230    VVA_ONLY( int nRef );
 69231  
 69232    sqlite3BtreeEnter(p);
 69233    assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
 69234    VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
 69235    assert( nRef>=0 );
 69236    sCheck.pBt = pBt;
 69237    sCheck.pPager = pBt->pPager;
 69238    sCheck.nPage = btreePagecount(sCheck.pBt);
 69239    sCheck.mxErr = mxErr;
 69240    sCheck.nErr = 0;
 69241    sCheck.mallocFailed = 0;
 69242    sCheck.zPfx = 0;
 69243    sCheck.v1 = 0;
 69244    sCheck.v2 = 0;
 69245    sCheck.aPgRef = 0;
 69246    sCheck.heap = 0;
 69247    sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
 69248    sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
 69249    if( sCheck.nPage==0 ){
 69250      goto integrity_ck_cleanup;
 69251    }
 69252  
 69253    sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
 69254    if( !sCheck.aPgRef ){
 69255      sCheck.mallocFailed = 1;
 69256      goto integrity_ck_cleanup;
 69257    }
 69258    sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
 69259    if( sCheck.heap==0 ){
 69260      sCheck.mallocFailed = 1;
 69261      goto integrity_ck_cleanup;
 69262    }
 69263  
 69264    i = PENDING_BYTE_PAGE(pBt);
 69265    if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
 69266  
 69267    /* Check the integrity of the freelist
 69268    */
 69269    sCheck.zPfx = "Main freelist: ";
 69270    checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
 69271              get4byte(&pBt->pPage1->aData[36]));
 69272    sCheck.zPfx = 0;
 69273  
 69274    /* Check all the tables.
 69275    */
 69276    testcase( pBt->db->flags & SQLITE_CellSizeCk );
 69277    pBt->db->flags &= ~SQLITE_CellSizeCk;
 69278    for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
 69279      i64 notUsed;
 69280      if( aRoot[i]==0 ) continue;
 69281  #ifndef SQLITE_OMIT_AUTOVACUUM
 69282      if( pBt->autoVacuum && aRoot[i]>1 ){
 69283        checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
 69284      }
 69285  #endif
 69286      checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
 69287    }
 69288    pBt->db->flags = savedDbFlags;
 69289  
 69290    /* Make sure every page in the file is referenced
 69291    */
 69292    for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
 69293  #ifdef SQLITE_OMIT_AUTOVACUUM
 69294      if( getPageReferenced(&sCheck, i)==0 ){
 69295        checkAppendMsg(&sCheck, "Page %d is never used", i);
 69296      }
 69297  #else
 69298      /* If the database supports auto-vacuum, make sure no tables contain
 69299      ** references to pointer-map pages.
 69300      */
 69301      if( getPageReferenced(&sCheck, i)==0 && 
 69302         (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
 69303        checkAppendMsg(&sCheck, "Page %d is never used", i);
 69304      }
 69305      if( getPageReferenced(&sCheck, i)!=0 && 
 69306         (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
 69307        checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
 69308      }
 69309  #endif
 69310    }
 69311  
 69312    /* Clean  up and report errors.
 69313    */
 69314  integrity_ck_cleanup:
 69315    sqlite3PageFree(sCheck.heap);
 69316    sqlite3_free(sCheck.aPgRef);
 69317    if( sCheck.mallocFailed ){
 69318      sqlite3StrAccumReset(&sCheck.errMsg);
 69319      sCheck.nErr++;
 69320    }
 69321    *pnErr = sCheck.nErr;
 69322    if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
 69323    /* Make sure this analysis did not leave any unref() pages. */
 69324    assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
 69325    sqlite3BtreeLeave(p);
 69326    return sqlite3StrAccumFinish(&sCheck.errMsg);
 69327  }
 69328  #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
 69329  
 69330  /*
 69331  ** Return the full pathname of the underlying database file.  Return
 69332  ** an empty string if the database is in-memory or a TEMP database.
 69333  **
 69334  ** The pager filename is invariant as long as the pager is
 69335  ** open so it is safe to access without the BtShared mutex.
 69336  */
 69337  SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
 69338    assert( p->pBt->pPager!=0 );
 69339    return sqlite3PagerFilename(p->pBt->pPager, 1);
 69340  }
 69341  
 69342  /*
 69343  ** Return the pathname of the journal file for this database. The return
 69344  ** value of this routine is the same regardless of whether the journal file
 69345  ** has been created or not.
 69346  **
 69347  ** The pager journal filename is invariant as long as the pager is
 69348  ** open so it is safe to access without the BtShared mutex.
 69349  */
 69350  SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
 69351    assert( p->pBt->pPager!=0 );
 69352    return sqlite3PagerJournalname(p->pBt->pPager);
 69353  }
 69354  
 69355  /*
 69356  ** Return non-zero if a transaction is active.
 69357  */
 69358  SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
 69359    assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
 69360    return (p && (p->inTrans==TRANS_WRITE));
 69361  }
 69362  
 69363  #ifndef SQLITE_OMIT_WAL
 69364  /*
 69365  ** Run a checkpoint on the Btree passed as the first argument.
 69366  **
 69367  ** Return SQLITE_LOCKED if this or any other connection has an open 
 69368  ** transaction on the shared-cache the argument Btree is connected to.
 69369  **
 69370  ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
 69371  */
 69372  SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
 69373    int rc = SQLITE_OK;
 69374    if( p ){
 69375      BtShared *pBt = p->pBt;
 69376      sqlite3BtreeEnter(p);
 69377      if( pBt->inTransaction!=TRANS_NONE ){
 69378        rc = SQLITE_LOCKED;
 69379      }else{
 69380        rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
 69381      }
 69382      sqlite3BtreeLeave(p);
 69383    }
 69384    return rc;
 69385  }
 69386  #endif
 69387  
 69388  /*
 69389  ** Return non-zero if a read (or write) transaction is active.
 69390  */
 69391  SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
 69392    assert( p );
 69393    assert( sqlite3_mutex_held(p->db->mutex) );
 69394    return p->inTrans!=TRANS_NONE;
 69395  }
 69396  
 69397  SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
 69398    assert( p );
 69399    assert( sqlite3_mutex_held(p->db->mutex) );
 69400    return p->nBackup!=0;
 69401  }
 69402  
 69403  /*
 69404  ** This function returns a pointer to a blob of memory associated with
 69405  ** a single shared-btree. The memory is used by client code for its own
 69406  ** purposes (for example, to store a high-level schema associated with 
 69407  ** the shared-btree). The btree layer manages reference counting issues.
 69408  **
 69409  ** The first time this is called on a shared-btree, nBytes bytes of memory
 69410  ** are allocated, zeroed, and returned to the caller. For each subsequent 
 69411  ** call the nBytes parameter is ignored and a pointer to the same blob
 69412  ** of memory returned. 
 69413  **
 69414  ** If the nBytes parameter is 0 and the blob of memory has not yet been
 69415  ** allocated, a null pointer is returned. If the blob has already been
 69416  ** allocated, it is returned as normal.
 69417  **
 69418  ** Just before the shared-btree is closed, the function passed as the 
 69419  ** xFree argument when the memory allocation was made is invoked on the 
 69420  ** blob of allocated memory. The xFree function should not call sqlite3_free()
 69421  ** on the memory, the btree layer does that.
 69422  */
 69423  SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
 69424    BtShared *pBt = p->pBt;
 69425    sqlite3BtreeEnter(p);
 69426    if( !pBt->pSchema && nBytes ){
 69427      pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
 69428      pBt->xFreeSchema = xFree;
 69429    }
 69430    sqlite3BtreeLeave(p);
 69431    return pBt->pSchema;
 69432  }
 69433  
 69434  /*
 69435  ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
 69436  ** btree as the argument handle holds an exclusive lock on the 
 69437  ** sqlite_master table. Otherwise SQLITE_OK.
 69438  */
 69439  SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
 69440    int rc;
 69441    assert( sqlite3_mutex_held(p->db->mutex) );
 69442    sqlite3BtreeEnter(p);
 69443    rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
 69444    assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
 69445    sqlite3BtreeLeave(p);
 69446    return rc;
 69447  }
 69448  
 69449  
 69450  #ifndef SQLITE_OMIT_SHARED_CACHE
 69451  /*
 69452  ** Obtain a lock on the table whose root page is iTab.  The
 69453  ** lock is a write lock if isWritelock is true or a read lock
 69454  ** if it is false.
 69455  */
 69456  SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
 69457    int rc = SQLITE_OK;
 69458    assert( p->inTrans!=TRANS_NONE );
 69459    if( p->sharable ){
 69460      u8 lockType = READ_LOCK + isWriteLock;
 69461      assert( READ_LOCK+1==WRITE_LOCK );
 69462      assert( isWriteLock==0 || isWriteLock==1 );
 69463  
 69464      sqlite3BtreeEnter(p);
 69465      rc = querySharedCacheTableLock(p, iTab, lockType);
 69466      if( rc==SQLITE_OK ){
 69467        rc = setSharedCacheTableLock(p, iTab, lockType);
 69468      }
 69469      sqlite3BtreeLeave(p);
 69470    }
 69471    return rc;
 69472  }
 69473  #endif
 69474  
 69475  #ifndef SQLITE_OMIT_INCRBLOB
 69476  /*
 69477  ** Argument pCsr must be a cursor opened for writing on an 
 69478  ** INTKEY table currently pointing at a valid table entry. 
 69479  ** This function modifies the data stored as part of that entry.
 69480  **
 69481  ** Only the data content may only be modified, it is not possible to 
 69482  ** change the length of the data stored. If this function is called with
 69483  ** parameters that attempt to write past the end of the existing data,
 69484  ** no modifications are made and SQLITE_CORRUPT is returned.
 69485  */
 69486  SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
 69487    int rc;
 69488    assert( cursorOwnsBtShared(pCsr) );
 69489    assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
 69490    assert( pCsr->curFlags & BTCF_Incrblob );
 69491  
 69492    rc = restoreCursorPosition(pCsr);
 69493    if( rc!=SQLITE_OK ){
 69494      return rc;
 69495    }
 69496    assert( pCsr->eState!=CURSOR_REQUIRESEEK );
 69497    if( pCsr->eState!=CURSOR_VALID ){
 69498      return SQLITE_ABORT;
 69499    }
 69500  
 69501    /* Save the positions of all other cursors open on this table. This is
 69502    ** required in case any of them are holding references to an xFetch
 69503    ** version of the b-tree page modified by the accessPayload call below.
 69504    **
 69505    ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
 69506    ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
 69507    ** saveAllCursors can only return SQLITE_OK.
 69508    */
 69509    VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
 69510    assert( rc==SQLITE_OK );
 69511  
 69512    /* Check some assumptions: 
 69513    **   (a) the cursor is open for writing,
 69514    **   (b) there is a read/write transaction open,
 69515    **   (c) the connection holds a write-lock on the table (if required),
 69516    **   (d) there are no conflicting read-locks, and
 69517    **   (e) the cursor points at a valid row of an intKey table.
 69518    */
 69519    if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
 69520      return SQLITE_READONLY;
 69521    }
 69522    assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
 69523                && pCsr->pBt->inTransaction==TRANS_WRITE );
 69524    assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
 69525    assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
 69526    assert( pCsr->pPage->intKey );
 69527  
 69528    return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
 69529  }
 69530  
 69531  /* 
 69532  ** Mark this cursor as an incremental blob cursor.
 69533  */
 69534  SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
 69535    pCur->curFlags |= BTCF_Incrblob;
 69536    pCur->pBtree->hasIncrblobCur = 1;
 69537  }
 69538  #endif
 69539  
 69540  /*
 69541  ** Set both the "read version" (single byte at byte offset 18) and 
 69542  ** "write version" (single byte at byte offset 19) fields in the database
 69543  ** header to iVersion.
 69544  */
 69545  SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
 69546    BtShared *pBt = pBtree->pBt;
 69547    int rc;                         /* Return code */
 69548   
 69549    assert( iVersion==1 || iVersion==2 );
 69550  
 69551    /* If setting the version fields to 1, do not automatically open the
 69552    ** WAL connection, even if the version fields are currently set to 2.
 69553    */
 69554    pBt->btsFlags &= ~BTS_NO_WAL;
 69555    if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
 69556  
 69557    rc = sqlite3BtreeBeginTrans(pBtree, 0);
 69558    if( rc==SQLITE_OK ){
 69559      u8 *aData = pBt->pPage1->aData;
 69560      if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
 69561        rc = sqlite3BtreeBeginTrans(pBtree, 2);
 69562        if( rc==SQLITE_OK ){
 69563          rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
 69564          if( rc==SQLITE_OK ){
 69565            aData[18] = (u8)iVersion;
 69566            aData[19] = (u8)iVersion;
 69567          }
 69568        }
 69569      }
 69570    }
 69571  
 69572    pBt->btsFlags &= ~BTS_NO_WAL;
 69573    return rc;
 69574  }
 69575  
 69576  /*
 69577  ** Return true if the cursor has a hint specified.  This routine is
 69578  ** only used from within assert() statements
 69579  */
 69580  SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
 69581    return (pCsr->hints & mask)!=0;
 69582  }
 69583  
 69584  /*
 69585  ** Return true if the given Btree is read-only.
 69586  */
 69587  SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
 69588    return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
 69589  }
 69590  
 69591  /*
 69592  ** Return the size of the header added to each page by this module.
 69593  */
 69594  SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
 69595  
 69596  #if !defined(SQLITE_OMIT_SHARED_CACHE)
 69597  /*
 69598  ** Return true if the Btree passed as the only argument is sharable.
 69599  */
 69600  SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
 69601    return p->sharable;
 69602  }
 69603  
 69604  /*
 69605  ** Return the number of connections to the BtShared object accessed by
 69606  ** the Btree handle passed as the only argument. For private caches 
 69607  ** this is always 1. For shared caches it may be 1 or greater.
 69608  */
 69609  SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
 69610    testcase( p->sharable );
 69611    return p->pBt->nRef;
 69612  }
 69613  #endif
 69614  
 69615  /************** End of btree.c ***********************************************/
 69616  /************** Begin file backup.c ******************************************/
 69617  /*
 69618  ** 2009 January 28
 69619  **
 69620  ** The author disclaims copyright to this source code.  In place of
 69621  ** a legal notice, here is a blessing:
 69622  **
 69623  **    May you do good and not evil.
 69624  **    May you find forgiveness for yourself and forgive others.
 69625  **    May you share freely, never taking more than you give.
 69626  **
 69627  *************************************************************************
 69628  ** This file contains the implementation of the sqlite3_backup_XXX() 
 69629  ** API functions and the related features.
 69630  */
 69631  /* #include "sqliteInt.h" */
 69632  /* #include "btreeInt.h" */
 69633  
 69634  /*
 69635  ** Structure allocated for each backup operation.
 69636  */
 69637  struct sqlite3_backup {
 69638    sqlite3* pDestDb;        /* Destination database handle */
 69639    Btree *pDest;            /* Destination b-tree file */
 69640    u32 iDestSchema;         /* Original schema cookie in destination */
 69641    int bDestLocked;         /* True once a write-transaction is open on pDest */
 69642  
 69643    Pgno iNext;              /* Page number of the next source page to copy */
 69644    sqlite3* pSrcDb;         /* Source database handle */
 69645    Btree *pSrc;             /* Source b-tree file */
 69646  
 69647    int rc;                  /* Backup process error code */
 69648  
 69649    /* These two variables are set by every call to backup_step(). They are
 69650    ** read by calls to backup_remaining() and backup_pagecount().
 69651    */
 69652    Pgno nRemaining;         /* Number of pages left to copy */
 69653    Pgno nPagecount;         /* Total number of pages to copy */
 69654  
 69655    int isAttached;          /* True once backup has been registered with pager */
 69656    sqlite3_backup *pNext;   /* Next backup associated with source pager */
 69657  };
 69658  
 69659  /*
 69660  ** THREAD SAFETY NOTES:
 69661  **
 69662  **   Once it has been created using backup_init(), a single sqlite3_backup
 69663  **   structure may be accessed via two groups of thread-safe entry points:
 69664  **
 69665  **     * Via the sqlite3_backup_XXX() API function backup_step() and 
 69666  **       backup_finish(). Both these functions obtain the source database
 69667  **       handle mutex and the mutex associated with the source BtShared 
 69668  **       structure, in that order.
 69669  **
 69670  **     * Via the BackupUpdate() and BackupRestart() functions, which are
 69671  **       invoked by the pager layer to report various state changes in
 69672  **       the page cache associated with the source database. The mutex
 69673  **       associated with the source database BtShared structure will always 
 69674  **       be held when either of these functions are invoked.
 69675  **
 69676  **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
 69677  **   backup_pagecount() are not thread-safe functions. If they are called
 69678  **   while some other thread is calling backup_step() or backup_finish(),
 69679  **   the values returned may be invalid. There is no way for a call to
 69680  **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
 69681  **   or backup_pagecount().
 69682  **
 69683  **   Depending on the SQLite configuration, the database handles and/or
 69684  **   the Btree objects may have their own mutexes that require locking.
 69685  **   Non-sharable Btrees (in-memory databases for example), do not have
 69686  **   associated mutexes.
 69687  */
 69688  
 69689  /*
 69690  ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
 69691  ** in connection handle pDb. If such a database cannot be found, return
 69692  ** a NULL pointer and write an error message to pErrorDb.
 69693  **
 69694  ** If the "temp" database is requested, it may need to be opened by this 
 69695  ** function. If an error occurs while doing so, return 0 and write an 
 69696  ** error message to pErrorDb.
 69697  */
 69698  static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
 69699    int i = sqlite3FindDbName(pDb, zDb);
 69700  
 69701    if( i==1 ){
 69702      Parse sParse;
 69703      int rc = 0;
 69704      memset(&sParse, 0, sizeof(sParse));
 69705      sParse.db = pDb;
 69706      if( sqlite3OpenTempDatabase(&sParse) ){
 69707        sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
 69708        rc = SQLITE_ERROR;
 69709      }
 69710      sqlite3DbFree(pErrorDb, sParse.zErrMsg);
 69711      sqlite3ParserReset(&sParse);
 69712      if( rc ){
 69713        return 0;
 69714      }
 69715    }
 69716  
 69717    if( i<0 ){
 69718      sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
 69719      return 0;
 69720    }
 69721  
 69722    return pDb->aDb[i].pBt;
 69723  }
 69724  
 69725  /*
 69726  ** Attempt to set the page size of the destination to match the page size
 69727  ** of the source.
 69728  */
 69729  static int setDestPgsz(sqlite3_backup *p){
 69730    int rc;
 69731    rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
 69732    return rc;
 69733  }
 69734  
 69735  /*
 69736  ** Check that there is no open read-transaction on the b-tree passed as the
 69737  ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
 69738  ** is an open read-transaction, return SQLITE_ERROR and leave an error 
 69739  ** message in database handle db.
 69740  */
 69741  static int checkReadTransaction(sqlite3 *db, Btree *p){
 69742    if( sqlite3BtreeIsInReadTrans(p) ){
 69743      sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
 69744      return SQLITE_ERROR;
 69745    }
 69746    return SQLITE_OK;
 69747  }
 69748  
 69749  /*
 69750  ** Create an sqlite3_backup process to copy the contents of zSrcDb from
 69751  ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
 69752  ** a pointer to the new sqlite3_backup object.
 69753  **
 69754  ** If an error occurs, NULL is returned and an error code and error message
 69755  ** stored in database handle pDestDb.
 69756  */
 69757  SQLITE_API sqlite3_backup *sqlite3_backup_init(
 69758    sqlite3* pDestDb,                     /* Database to write to */
 69759    const char *zDestDb,                  /* Name of database within pDestDb */
 69760    sqlite3* pSrcDb,                      /* Database connection to read from */
 69761    const char *zSrcDb                    /* Name of database within pSrcDb */
 69762  ){
 69763    sqlite3_backup *p;                    /* Value to return */
 69764  
 69765  #ifdef SQLITE_ENABLE_API_ARMOR
 69766    if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
 69767      (void)SQLITE_MISUSE_BKPT;
 69768      return 0;
 69769    }
 69770  #endif
 69771  
 69772    /* Lock the source database handle. The destination database
 69773    ** handle is not locked in this routine, but it is locked in
 69774    ** sqlite3_backup_step(). The user is required to ensure that no
 69775    ** other thread accesses the destination handle for the duration
 69776    ** of the backup operation.  Any attempt to use the destination
 69777    ** database connection while a backup is in progress may cause
 69778    ** a malfunction or a deadlock.
 69779    */
 69780    sqlite3_mutex_enter(pSrcDb->mutex);
 69781    sqlite3_mutex_enter(pDestDb->mutex);
 69782  
 69783    if( pSrcDb==pDestDb ){
 69784      sqlite3ErrorWithMsg(
 69785          pDestDb, SQLITE_ERROR, "source and destination must be distinct"
 69786      );
 69787      p = 0;
 69788    }else {
 69789      /* Allocate space for a new sqlite3_backup object...
 69790      ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
 69791      ** call to sqlite3_backup_init() and is destroyed by a call to
 69792      ** sqlite3_backup_finish(). */
 69793      p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
 69794      if( !p ){
 69795        sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
 69796      }
 69797    }
 69798  
 69799    /* If the allocation succeeded, populate the new object. */
 69800    if( p ){
 69801      p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
 69802      p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
 69803      p->pDestDb = pDestDb;
 69804      p->pSrcDb = pSrcDb;
 69805      p->iNext = 1;
 69806      p->isAttached = 0;
 69807  
 69808      if( 0==p->pSrc || 0==p->pDest 
 69809       || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK 
 69810       ){
 69811        /* One (or both) of the named databases did not exist or an OOM
 69812        ** error was hit. Or there is a transaction open on the destination
 69813        ** database. The error has already been written into the pDestDb 
 69814        ** handle. All that is left to do here is free the sqlite3_backup 
 69815        ** structure.  */
 69816        sqlite3_free(p);
 69817        p = 0;
 69818      }
 69819    }
 69820    if( p ){
 69821      p->pSrc->nBackup++;
 69822    }
 69823  
 69824    sqlite3_mutex_leave(pDestDb->mutex);
 69825    sqlite3_mutex_leave(pSrcDb->mutex);
 69826    return p;
 69827  }
 69828  
 69829  /*
 69830  ** Argument rc is an SQLite error code. Return true if this error is 
 69831  ** considered fatal if encountered during a backup operation. All errors
 69832  ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
 69833  */
 69834  static int isFatalError(int rc){
 69835    return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
 69836  }
 69837  
 69838  /*
 69839  ** Parameter zSrcData points to a buffer containing the data for 
 69840  ** page iSrcPg from the source database. Copy this data into the 
 69841  ** destination database.
 69842  */
 69843  static int backupOnePage(
 69844    sqlite3_backup *p,              /* Backup handle */
 69845    Pgno iSrcPg,                    /* Source database page to backup */
 69846    const u8 *zSrcData,             /* Source database page data */
 69847    int bUpdate                     /* True for an update, false otherwise */
 69848  ){
 69849    Pager * const pDestPager = sqlite3BtreePager(p->pDest);
 69850    const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
 69851    int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
 69852    const int nCopy = MIN(nSrcPgsz, nDestPgsz);
 69853    const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
 69854  #ifdef SQLITE_HAS_CODEC
 69855    /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
 69856    ** guaranteed that the shared-mutex is held by this thread, handle
 69857    ** p->pSrc may not actually be the owner.  */
 69858    int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
 69859    int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
 69860  #endif
 69861    int rc = SQLITE_OK;
 69862    i64 iOff;
 69863  
 69864    assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
 69865    assert( p->bDestLocked );
 69866    assert( !isFatalError(p->rc) );
 69867    assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
 69868    assert( zSrcData );
 69869  
 69870    /* Catch the case where the destination is an in-memory database and the
 69871    ** page sizes of the source and destination differ. 
 69872    */
 69873    if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
 69874      rc = SQLITE_READONLY;
 69875    }
 69876  
 69877  #ifdef SQLITE_HAS_CODEC
 69878    /* Backup is not possible if the page size of the destination is changing
 69879    ** and a codec is in use.
 69880    */
 69881    if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
 69882      rc = SQLITE_READONLY;
 69883    }
 69884  
 69885    /* Backup is not possible if the number of bytes of reserve space differ
 69886    ** between source and destination.  If there is a difference, try to
 69887    ** fix the destination to agree with the source.  If that is not possible,
 69888    ** then the backup cannot proceed.
 69889    */
 69890    if( nSrcReserve!=nDestReserve ){
 69891      u32 newPgsz = nSrcPgsz;
 69892      rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
 69893      if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
 69894    }
 69895  #endif
 69896  
 69897    /* This loop runs once for each destination page spanned by the source 
 69898    ** page. For each iteration, variable iOff is set to the byte offset
 69899    ** of the destination page.
 69900    */
 69901    for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
 69902      DbPage *pDestPg = 0;
 69903      Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
 69904      if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
 69905      if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
 69906       && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
 69907      ){
 69908        const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
 69909        u8 *zDestData = sqlite3PagerGetData(pDestPg);
 69910        u8 *zOut = &zDestData[iOff%nDestPgsz];
 69911  
 69912        /* Copy the data from the source page into the destination page.
 69913        ** Then clear the Btree layer MemPage.isInit flag. Both this module
 69914        ** and the pager code use this trick (clearing the first byte
 69915        ** of the page 'extra' space to invalidate the Btree layers
 69916        ** cached parse of the page). MemPage.isInit is marked 
 69917        ** "MUST BE FIRST" for this purpose.
 69918        */
 69919        memcpy(zOut, zIn, nCopy);
 69920        ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
 69921        if( iOff==0 && bUpdate==0 ){
 69922          sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
 69923        }
 69924      }
 69925      sqlite3PagerUnref(pDestPg);
 69926    }
 69927  
 69928    return rc;
 69929  }
 69930  
 69931  /*
 69932  ** If pFile is currently larger than iSize bytes, then truncate it to
 69933  ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
 69934  ** this function is a no-op.
 69935  **
 69936  ** Return SQLITE_OK if everything is successful, or an SQLite error 
 69937  ** code if an error occurs.
 69938  */
 69939  static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
 69940    i64 iCurrent;
 69941    int rc = sqlite3OsFileSize(pFile, &iCurrent);
 69942    if( rc==SQLITE_OK && iCurrent>iSize ){
 69943      rc = sqlite3OsTruncate(pFile, iSize);
 69944    }
 69945    return rc;
 69946  }
 69947  
 69948  /*
 69949  ** Register this backup object with the associated source pager for
 69950  ** callbacks when pages are changed or the cache invalidated.
 69951  */
 69952  static void attachBackupObject(sqlite3_backup *p){
 69953    sqlite3_backup **pp;
 69954    assert( sqlite3BtreeHoldsMutex(p->pSrc) );
 69955    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
 69956    p->pNext = *pp;
 69957    *pp = p;
 69958    p->isAttached = 1;
 69959  }
 69960  
 69961  /*
 69962  ** Copy nPage pages from the source b-tree to the destination.
 69963  */
 69964  SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
 69965    int rc;
 69966    int destMode;       /* Destination journal mode */
 69967    int pgszSrc = 0;    /* Source page size */
 69968    int pgszDest = 0;   /* Destination page size */
 69969  
 69970  #ifdef SQLITE_ENABLE_API_ARMOR
 69971    if( p==0 ) return SQLITE_MISUSE_BKPT;
 69972  #endif
 69973    sqlite3_mutex_enter(p->pSrcDb->mutex);
 69974    sqlite3BtreeEnter(p->pSrc);
 69975    if( p->pDestDb ){
 69976      sqlite3_mutex_enter(p->pDestDb->mutex);
 69977    }
 69978  
 69979    rc = p->rc;
 69980    if( !isFatalError(rc) ){
 69981      Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
 69982      Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
 69983      int ii;                            /* Iterator variable */
 69984      int nSrcPage = -1;                 /* Size of source db in pages */
 69985      int bCloseTrans = 0;               /* True if src db requires unlocking */
 69986  
 69987      /* If the source pager is currently in a write-transaction, return
 69988      ** SQLITE_BUSY immediately.
 69989      */
 69990      if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
 69991        rc = SQLITE_BUSY;
 69992      }else{
 69993        rc = SQLITE_OK;
 69994      }
 69995  
 69996      /* If there is no open read-transaction on the source database, open
 69997      ** one now. If a transaction is opened here, then it will be closed
 69998      ** before this function exits.
 69999      */
 70000      if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
 70001        rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
 70002        bCloseTrans = 1;
 70003      }
 70004  
 70005      /* If the destination database has not yet been locked (i.e. if this
 70006      ** is the first call to backup_step() for the current backup operation),
 70007      ** try to set its page size to the same as the source database. This
 70008      ** is especially important on ZipVFS systems, as in that case it is
 70009      ** not possible to create a database file that uses one page size by
 70010      ** writing to it with another.  */
 70011      if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
 70012        rc = SQLITE_NOMEM;
 70013      }
 70014  
 70015      /* Lock the destination database, if it is not locked already. */
 70016      if( SQLITE_OK==rc && p->bDestLocked==0
 70017       && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
 70018      ){
 70019        p->bDestLocked = 1;
 70020        sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
 70021      }
 70022  
 70023      /* Do not allow backup if the destination database is in WAL mode
 70024      ** and the page sizes are different between source and destination */
 70025      pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
 70026      pgszDest = sqlite3BtreeGetPageSize(p->pDest);
 70027      destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
 70028      if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
 70029        rc = SQLITE_READONLY;
 70030      }
 70031    
 70032      /* Now that there is a read-lock on the source database, query the
 70033      ** source pager for the number of pages in the database.
 70034      */
 70035      nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
 70036      assert( nSrcPage>=0 );
 70037      for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
 70038        const Pgno iSrcPg = p->iNext;                 /* Source page number */
 70039        if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
 70040          DbPage *pSrcPg;                             /* Source page object */
 70041          rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
 70042          if( rc==SQLITE_OK ){
 70043            rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
 70044            sqlite3PagerUnref(pSrcPg);
 70045          }
 70046        }
 70047        p->iNext++;
 70048      }
 70049      if( rc==SQLITE_OK ){
 70050        p->nPagecount = nSrcPage;
 70051        p->nRemaining = nSrcPage+1-p->iNext;
 70052        if( p->iNext>(Pgno)nSrcPage ){
 70053          rc = SQLITE_DONE;
 70054        }else if( !p->isAttached ){
 70055          attachBackupObject(p);
 70056        }
 70057      }
 70058    
 70059      /* Update the schema version field in the destination database. This
 70060      ** is to make sure that the schema-version really does change in
 70061      ** the case where the source and destination databases have the
 70062      ** same schema version.
 70063      */
 70064      if( rc==SQLITE_DONE ){
 70065        if( nSrcPage==0 ){
 70066          rc = sqlite3BtreeNewDb(p->pDest);
 70067          nSrcPage = 1;
 70068        }
 70069        if( rc==SQLITE_OK || rc==SQLITE_DONE ){
 70070          rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
 70071        }
 70072        if( rc==SQLITE_OK ){
 70073          if( p->pDestDb ){
 70074            sqlite3ResetAllSchemasOfConnection(p->pDestDb);
 70075          }
 70076          if( destMode==PAGER_JOURNALMODE_WAL ){
 70077            rc = sqlite3BtreeSetVersion(p->pDest, 2);
 70078          }
 70079        }
 70080        if( rc==SQLITE_OK ){
 70081          int nDestTruncate;
 70082          /* Set nDestTruncate to the final number of pages in the destination
 70083          ** database. The complication here is that the destination page
 70084          ** size may be different to the source page size. 
 70085          **
 70086          ** If the source page size is smaller than the destination page size, 
 70087          ** round up. In this case the call to sqlite3OsTruncate() below will
 70088          ** fix the size of the file. However it is important to call
 70089          ** sqlite3PagerTruncateImage() here so that any pages in the 
 70090          ** destination file that lie beyond the nDestTruncate page mark are
 70091          ** journalled by PagerCommitPhaseOne() before they are destroyed
 70092          ** by the file truncation.
 70093          */
 70094          assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
 70095          assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
 70096          if( pgszSrc<pgszDest ){
 70097            int ratio = pgszDest/pgszSrc;
 70098            nDestTruncate = (nSrcPage+ratio-1)/ratio;
 70099            if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
 70100              nDestTruncate--;
 70101            }
 70102          }else{
 70103            nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
 70104          }
 70105          assert( nDestTruncate>0 );
 70106  
 70107          if( pgszSrc<pgszDest ){
 70108            /* If the source page-size is smaller than the destination page-size,
 70109            ** two extra things may need to happen:
 70110            **
 70111            **   * The destination may need to be truncated, and
 70112            **
 70113            **   * Data stored on the pages immediately following the 
 70114            **     pending-byte page in the source database may need to be
 70115            **     copied into the destination database.
 70116            */
 70117            const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
 70118            sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
 70119            Pgno iPg;
 70120            int nDstPage;
 70121            i64 iOff;
 70122            i64 iEnd;
 70123  
 70124            assert( pFile );
 70125            assert( nDestTruncate==0 
 70126                || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
 70127                  nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
 70128               && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
 70129            ));
 70130  
 70131            /* This block ensures that all data required to recreate the original
 70132            ** database has been stored in the journal for pDestPager and the
 70133            ** journal synced to disk. So at this point we may safely modify
 70134            ** the database file in any way, knowing that if a power failure
 70135            ** occurs, the original database will be reconstructed from the 
 70136            ** journal file.  */
 70137            sqlite3PagerPagecount(pDestPager, &nDstPage);
 70138            for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
 70139              if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
 70140                DbPage *pPg;
 70141                rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
 70142                if( rc==SQLITE_OK ){
 70143                  rc = sqlite3PagerWrite(pPg);
 70144                  sqlite3PagerUnref(pPg);
 70145                }
 70146              }
 70147            }
 70148            if( rc==SQLITE_OK ){
 70149              rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
 70150            }
 70151  
 70152            /* Write the extra pages and truncate the database file as required */
 70153            iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
 70154            for(
 70155              iOff=PENDING_BYTE+pgszSrc; 
 70156              rc==SQLITE_OK && iOff<iEnd; 
 70157              iOff+=pgszSrc
 70158            ){
 70159              PgHdr *pSrcPg = 0;
 70160              const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
 70161              rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
 70162              if( rc==SQLITE_OK ){
 70163                u8 *zData = sqlite3PagerGetData(pSrcPg);
 70164                rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
 70165              }
 70166              sqlite3PagerUnref(pSrcPg);
 70167            }
 70168            if( rc==SQLITE_OK ){
 70169              rc = backupTruncateFile(pFile, iSize);
 70170            }
 70171  
 70172            /* Sync the database file to disk. */
 70173            if( rc==SQLITE_OK ){
 70174              rc = sqlite3PagerSync(pDestPager, 0);
 70175            }
 70176          }else{
 70177            sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
 70178            rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
 70179          }
 70180      
 70181          /* Finish committing the transaction to the destination database. */
 70182          if( SQLITE_OK==rc
 70183           && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
 70184          ){
 70185            rc = SQLITE_DONE;
 70186          }
 70187        }
 70188      }
 70189    
 70190      /* If bCloseTrans is true, then this function opened a read transaction
 70191      ** on the source database. Close the read transaction here. There is
 70192      ** no need to check the return values of the btree methods here, as
 70193      ** "committing" a read-only transaction cannot fail.
 70194      */
 70195      if( bCloseTrans ){
 70196        TESTONLY( int rc2 );
 70197        TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
 70198        TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
 70199        assert( rc2==SQLITE_OK );
 70200      }
 70201    
 70202      if( rc==SQLITE_IOERR_NOMEM ){
 70203        rc = SQLITE_NOMEM_BKPT;
 70204      }
 70205      p->rc = rc;
 70206    }
 70207    if( p->pDestDb ){
 70208      sqlite3_mutex_leave(p->pDestDb->mutex);
 70209    }
 70210    sqlite3BtreeLeave(p->pSrc);
 70211    sqlite3_mutex_leave(p->pSrcDb->mutex);
 70212    return rc;
 70213  }
 70214  
 70215  /*
 70216  ** Release all resources associated with an sqlite3_backup* handle.
 70217  */
 70218  SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
 70219    sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
 70220    sqlite3 *pSrcDb;                     /* Source database connection */
 70221    int rc;                              /* Value to return */
 70222  
 70223    /* Enter the mutexes */
 70224    if( p==0 ) return SQLITE_OK;
 70225    pSrcDb = p->pSrcDb;
 70226    sqlite3_mutex_enter(pSrcDb->mutex);
 70227    sqlite3BtreeEnter(p->pSrc);
 70228    if( p->pDestDb ){
 70229      sqlite3_mutex_enter(p->pDestDb->mutex);
 70230    }
 70231  
 70232    /* Detach this backup from the source pager. */
 70233    if( p->pDestDb ){
 70234      p->pSrc->nBackup--;
 70235    }
 70236    if( p->isAttached ){
 70237      pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
 70238      while( *pp!=p ){
 70239        pp = &(*pp)->pNext;
 70240      }
 70241      *pp = p->pNext;
 70242    }
 70243  
 70244    /* If a transaction is still open on the Btree, roll it back. */
 70245    sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
 70246  
 70247    /* Set the error code of the destination database handle. */
 70248    rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
 70249    if( p->pDestDb ){
 70250      sqlite3Error(p->pDestDb, rc);
 70251  
 70252      /* Exit the mutexes and free the backup context structure. */
 70253      sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
 70254    }
 70255    sqlite3BtreeLeave(p->pSrc);
 70256    if( p->pDestDb ){
 70257      /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
 70258      ** call to sqlite3_backup_init() and is destroyed by a call to
 70259      ** sqlite3_backup_finish(). */
 70260      sqlite3_free(p);
 70261    }
 70262    sqlite3LeaveMutexAndCloseZombie(pSrcDb);
 70263    return rc;
 70264  }
 70265  
 70266  /*
 70267  ** Return the number of pages still to be backed up as of the most recent
 70268  ** call to sqlite3_backup_step().
 70269  */
 70270  SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
 70271  #ifdef SQLITE_ENABLE_API_ARMOR
 70272    if( p==0 ){
 70273      (void)SQLITE_MISUSE_BKPT;
 70274      return 0;
 70275    }
 70276  #endif
 70277    return p->nRemaining;
 70278  }
 70279  
 70280  /*
 70281  ** Return the total number of pages in the source database as of the most 
 70282  ** recent call to sqlite3_backup_step().
 70283  */
 70284  SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
 70285  #ifdef SQLITE_ENABLE_API_ARMOR
 70286    if( p==0 ){
 70287      (void)SQLITE_MISUSE_BKPT;
 70288      return 0;
 70289    }
 70290  #endif
 70291    return p->nPagecount;
 70292  }
 70293  
 70294  /*
 70295  ** This function is called after the contents of page iPage of the
 70296  ** source database have been modified. If page iPage has already been 
 70297  ** copied into the destination database, then the data written to the
 70298  ** destination is now invalidated. The destination copy of iPage needs
 70299  ** to be updated with the new data before the backup operation is
 70300  ** complete.
 70301  **
 70302  ** It is assumed that the mutex associated with the BtShared object
 70303  ** corresponding to the source database is held when this function is
 70304  ** called.
 70305  */
 70306  static SQLITE_NOINLINE void backupUpdate(
 70307    sqlite3_backup *p,
 70308    Pgno iPage,
 70309    const u8 *aData
 70310  ){
 70311    assert( p!=0 );
 70312    do{
 70313      assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
 70314      if( !isFatalError(p->rc) && iPage<p->iNext ){
 70315        /* The backup process p has already copied page iPage. But now it
 70316        ** has been modified by a transaction on the source pager. Copy
 70317        ** the new data into the backup.
 70318        */
 70319        int rc;
 70320        assert( p->pDestDb );
 70321        sqlite3_mutex_enter(p->pDestDb->mutex);
 70322        rc = backupOnePage(p, iPage, aData, 1);
 70323        sqlite3_mutex_leave(p->pDestDb->mutex);
 70324        assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
 70325        if( rc!=SQLITE_OK ){
 70326          p->rc = rc;
 70327        }
 70328      }
 70329    }while( (p = p->pNext)!=0 );
 70330  }
 70331  SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
 70332    if( pBackup ) backupUpdate(pBackup, iPage, aData);
 70333  }
 70334  
 70335  /*
 70336  ** Restart the backup process. This is called when the pager layer
 70337  ** detects that the database has been modified by an external database
 70338  ** connection. In this case there is no way of knowing which of the
 70339  ** pages that have been copied into the destination database are still 
 70340  ** valid and which are not, so the entire process needs to be restarted.
 70341  **
 70342  ** It is assumed that the mutex associated with the BtShared object
 70343  ** corresponding to the source database is held when this function is
 70344  ** called.
 70345  */
 70346  SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
 70347    sqlite3_backup *p;                   /* Iterator variable */
 70348    for(p=pBackup; p; p=p->pNext){
 70349      assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
 70350      p->iNext = 1;
 70351    }
 70352  }
 70353  
 70354  #ifndef SQLITE_OMIT_VACUUM
 70355  /*
 70356  ** Copy the complete content of pBtFrom into pBtTo.  A transaction
 70357  ** must be active for both files.
 70358  **
 70359  ** The size of file pTo may be reduced by this operation. If anything 
 70360  ** goes wrong, the transaction on pTo is rolled back. If successful, the 
 70361  ** transaction is committed before returning.
 70362  */
 70363  SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
 70364    int rc;
 70365    sqlite3_file *pFd;              /* File descriptor for database pTo */
 70366    sqlite3_backup b;
 70367    sqlite3BtreeEnter(pTo);
 70368    sqlite3BtreeEnter(pFrom);
 70369  
 70370    assert( sqlite3BtreeIsInTrans(pTo) );
 70371    pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
 70372    if( pFd->pMethods ){
 70373      i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
 70374      rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
 70375      if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
 70376      if( rc ) goto copy_finished;
 70377    }
 70378  
 70379    /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
 70380    ** to 0. This is used by the implementations of sqlite3_backup_step()
 70381    ** and sqlite3_backup_finish() to detect that they are being called
 70382    ** from this function, not directly by the user.
 70383    */
 70384    memset(&b, 0, sizeof(b));
 70385    b.pSrcDb = pFrom->db;
 70386    b.pSrc = pFrom;
 70387    b.pDest = pTo;
 70388    b.iNext = 1;
 70389  
 70390  #ifdef SQLITE_HAS_CODEC
 70391    sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
 70392  #endif
 70393  
 70394    /* 0x7FFFFFFF is the hard limit for the number of pages in a database
 70395    ** file. By passing this as the number of pages to copy to
 70396    ** sqlite3_backup_step(), we can guarantee that the copy finishes 
 70397    ** within a single call (unless an error occurs). The assert() statement
 70398    ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
 70399    ** or an error code.  */
 70400    sqlite3_backup_step(&b, 0x7FFFFFFF);
 70401    assert( b.rc!=SQLITE_OK );
 70402  
 70403    rc = sqlite3_backup_finish(&b);
 70404    if( rc==SQLITE_OK ){
 70405      pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
 70406    }else{
 70407      sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
 70408    }
 70409  
 70410    assert( sqlite3BtreeIsInTrans(pTo)==0 );
 70411  copy_finished:
 70412    sqlite3BtreeLeave(pFrom);
 70413    sqlite3BtreeLeave(pTo);
 70414    return rc;
 70415  }
 70416  #endif /* SQLITE_OMIT_VACUUM */
 70417  
 70418  /************** End of backup.c **********************************************/
 70419  /************** Begin file vdbemem.c *****************************************/
 70420  /*
 70421  ** 2004 May 26
 70422  **
 70423  ** The author disclaims copyright to this source code.  In place of
 70424  ** a legal notice, here is a blessing:
 70425  **
 70426  **    May you do good and not evil.
 70427  **    May you find forgiveness for yourself and forgive others.
 70428  **    May you share freely, never taking more than you give.
 70429  **
 70430  *************************************************************************
 70431  **
 70432  ** This file contains code use to manipulate "Mem" structure.  A "Mem"
 70433  ** stores a single value in the VDBE.  Mem is an opaque structure visible
 70434  ** only within the VDBE.  Interface routines refer to a Mem using the
 70435  ** name sqlite_value
 70436  */
 70437  /* #include "sqliteInt.h" */
 70438  /* #include "vdbeInt.h" */
 70439  
 70440  #ifdef SQLITE_DEBUG
 70441  /*
 70442  ** Check invariants on a Mem object.
 70443  **
 70444  ** This routine is intended for use inside of assert() statements, like
 70445  ** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
 70446  */
 70447  SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
 70448    /* If MEM_Dyn is set then Mem.xDel!=0.  
 70449    ** Mem.xDel might not be initialized if MEM_Dyn is clear.
 70450    */
 70451    assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
 70452  
 70453    /* MEM_Dyn may only be set if Mem.szMalloc==0.  In this way we
 70454    ** ensure that if Mem.szMalloc>0 then it is safe to do
 70455    ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
 70456    ** That saves a few cycles in inner loops. */
 70457    assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
 70458  
 70459    /* Cannot be both MEM_Int and MEM_Real at the same time */
 70460    assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
 70461  
 70462    if( p->flags & MEM_Null ){
 70463      /* Cannot be both MEM_Null and some other type */
 70464      assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob
 70465                           |MEM_RowSet|MEM_Frame|MEM_Agg|MEM_Zero))==0 );
 70466  
 70467      /* If MEM_Null is set, then either the value is a pure NULL (the usual
 70468      ** case) or it is a pointer set using sqlite3_bind_pointer() or
 70469      ** sqlite3_result_pointer().  If a pointer, then MEM_Term must also be
 70470      ** set.
 70471      */
 70472      if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){
 70473        /* This is a pointer type.  There may be a flag to indicate what to
 70474        ** do with the pointer. */
 70475        assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
 70476                ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
 70477                ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 );
 70478  
 70479        /* No other bits set */
 70480        assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype
 70481                             |MEM_Dyn|MEM_Ephem|MEM_Static))==0 );
 70482      }else{
 70483        /* A pure NULL might have other flags, such as MEM_Static, MEM_Dyn,
 70484        ** MEM_Ephem, MEM_Cleared, or MEM_Subtype */
 70485      }
 70486    }else{
 70487      /* The MEM_Cleared bit is only allowed on NULLs */
 70488      assert( (p->flags & MEM_Cleared)==0 );
 70489    }
 70490  
 70491    /* The szMalloc field holds the correct memory allocation size */
 70492    assert( p->szMalloc==0
 70493         || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
 70494  
 70495    /* If p holds a string or blob, the Mem.z must point to exactly
 70496    ** one of the following:
 70497    **
 70498    **   (1) Memory in Mem.zMalloc and managed by the Mem object
 70499    **   (2) Memory to be freed using Mem.xDel
 70500    **   (3) An ephemeral string or blob
 70501    **   (4) A static string or blob
 70502    */
 70503    if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
 70504      assert( 
 70505        ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
 70506        ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
 70507        ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
 70508        ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
 70509      );
 70510    }
 70511    return 1;
 70512  }
 70513  #endif
 70514  
 70515  
 70516  /*
 70517  ** If pMem is an object with a valid string representation, this routine
 70518  ** ensures the internal encoding for the string representation is
 70519  ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
 70520  **
 70521  ** If pMem is not a string object, or the encoding of the string
 70522  ** representation is already stored using the requested encoding, then this
 70523  ** routine is a no-op.
 70524  **
 70525  ** SQLITE_OK is returned if the conversion is successful (or not required).
 70526  ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
 70527  ** between formats.
 70528  */
 70529  SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
 70530  #ifndef SQLITE_OMIT_UTF16
 70531    int rc;
 70532  #endif
 70533    assert( (pMem->flags&MEM_RowSet)==0 );
 70534    assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
 70535             || desiredEnc==SQLITE_UTF16BE );
 70536    if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
 70537      return SQLITE_OK;
 70538    }
 70539    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 70540  #ifdef SQLITE_OMIT_UTF16
 70541    return SQLITE_ERROR;
 70542  #else
 70543  
 70544    /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
 70545    ** then the encoding of the value may not have changed.
 70546    */
 70547    rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
 70548    assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
 70549    assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
 70550    assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
 70551    return rc;
 70552  #endif
 70553  }
 70554  
 70555  /*
 70556  ** Make sure pMem->z points to a writable allocation of at least 
 70557  ** min(n,32) bytes.
 70558  **
 70559  ** If the bPreserve argument is true, then copy of the content of
 70560  ** pMem->z into the new allocation.  pMem must be either a string or
 70561  ** blob if bPreserve is true.  If bPreserve is false, any prior content
 70562  ** in pMem->z is discarded.
 70563  */
 70564  SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
 70565    assert( sqlite3VdbeCheckMemInvariants(pMem) );
 70566    assert( (pMem->flags&MEM_RowSet)==0 );
 70567    testcase( pMem->db==0 );
 70568  
 70569    /* If the bPreserve flag is set to true, then the memory cell must already
 70570    ** contain a valid string or blob value.  */
 70571    assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
 70572    testcase( bPreserve && pMem->z==0 );
 70573  
 70574    assert( pMem->szMalloc==0
 70575         || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
 70576    if( n<32 ) n = 32;
 70577    if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){
 70578      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
 70579      bPreserve = 0;
 70580    }else{
 70581      if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
 70582      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
 70583    }
 70584    if( pMem->zMalloc==0 ){
 70585      sqlite3VdbeMemSetNull(pMem);
 70586      pMem->z = 0;
 70587      pMem->szMalloc = 0;
 70588      return SQLITE_NOMEM_BKPT;
 70589    }else{
 70590      pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
 70591    }
 70592  
 70593    if( bPreserve && pMem->z ){
 70594      assert( pMem->z!=pMem->zMalloc );
 70595      memcpy(pMem->zMalloc, pMem->z, pMem->n);
 70596    }
 70597    if( (pMem->flags&MEM_Dyn)!=0 ){
 70598      assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
 70599      pMem->xDel((void *)(pMem->z));
 70600    }
 70601  
 70602    pMem->z = pMem->zMalloc;
 70603    pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
 70604    return SQLITE_OK;
 70605  }
 70606  
 70607  /*
 70608  ** Change the pMem->zMalloc allocation to be at least szNew bytes.
 70609  ** If pMem->zMalloc already meets or exceeds the requested size, this
 70610  ** routine is a no-op.
 70611  **
 70612  ** Any prior string or blob content in the pMem object may be discarded.
 70613  ** The pMem->xDel destructor is called, if it exists.  Though MEM_Str
 70614  ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
 70615  ** values are preserved.
 70616  **
 70617  ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
 70618  ** if unable to complete the resizing.
 70619  */
 70620  SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
 70621    assert( szNew>0 );
 70622    assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
 70623    if( pMem->szMalloc<szNew ){
 70624      return sqlite3VdbeMemGrow(pMem, szNew, 0);
 70625    }
 70626    assert( (pMem->flags & MEM_Dyn)==0 );
 70627    pMem->z = pMem->zMalloc;
 70628    pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
 70629    return SQLITE_OK;
 70630  }
 70631  
 70632  /*
 70633  ** It is already known that pMem contains an unterminated string.
 70634  ** Add the zero terminator.
 70635  */
 70636  static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
 70637    if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
 70638      return SQLITE_NOMEM_BKPT;
 70639    }
 70640    pMem->z[pMem->n] = 0;
 70641    pMem->z[pMem->n+1] = 0;
 70642    pMem->flags |= MEM_Term;
 70643    return SQLITE_OK;
 70644  }
 70645  
 70646  /*
 70647  ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
 70648  ** MEM.zMalloc, where it can be safely written.
 70649  **
 70650  ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
 70651  */
 70652  SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
 70653    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 70654    assert( (pMem->flags&MEM_RowSet)==0 );
 70655    if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
 70656      if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
 70657      if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
 70658        int rc = vdbeMemAddTerminator(pMem);
 70659        if( rc ) return rc;
 70660      }
 70661    }
 70662    pMem->flags &= ~MEM_Ephem;
 70663  #ifdef SQLITE_DEBUG
 70664    pMem->pScopyFrom = 0;
 70665  #endif
 70666  
 70667    return SQLITE_OK;
 70668  }
 70669  
 70670  /*
 70671  ** If the given Mem* has a zero-filled tail, turn it into an ordinary
 70672  ** blob stored in dynamically allocated space.
 70673  */
 70674  #ifndef SQLITE_OMIT_INCRBLOB
 70675  SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
 70676    int nByte;
 70677    assert( pMem->flags & MEM_Zero );
 70678    assert( pMem->flags&MEM_Blob );
 70679    assert( (pMem->flags&MEM_RowSet)==0 );
 70680    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 70681  
 70682    /* Set nByte to the number of bytes required to store the expanded blob. */
 70683    nByte = pMem->n + pMem->u.nZero;
 70684    if( nByte<=0 ){
 70685      nByte = 1;
 70686    }
 70687    if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
 70688      return SQLITE_NOMEM_BKPT;
 70689    }
 70690  
 70691    memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
 70692    pMem->n += pMem->u.nZero;
 70693    pMem->flags &= ~(MEM_Zero|MEM_Term);
 70694    return SQLITE_OK;
 70695  }
 70696  #endif
 70697  
 70698  /*
 70699  ** Make sure the given Mem is \u0000 terminated.
 70700  */
 70701  SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
 70702    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 70703    testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
 70704    testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
 70705    if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
 70706      return SQLITE_OK;   /* Nothing to do */
 70707    }else{
 70708      return vdbeMemAddTerminator(pMem);
 70709    }
 70710  }
 70711  
 70712  /*
 70713  ** Add MEM_Str to the set of representations for the given Mem.  Numbers
 70714  ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
 70715  ** is a no-op.
 70716  **
 70717  ** Existing representations MEM_Int and MEM_Real are invalidated if
 70718  ** bForce is true but are retained if bForce is false.
 70719  **
 70720  ** A MEM_Null value will never be passed to this function. This function is
 70721  ** used for converting values to text for returning to the user (i.e. via
 70722  ** sqlite3_value_text()), or for ensuring that values to be used as btree
 70723  ** keys are strings. In the former case a NULL pointer is returned the
 70724  ** user and the latter is an internal programming error.
 70725  */
 70726  SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
 70727    int fg = pMem->flags;
 70728    const int nByte = 32;
 70729  
 70730    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 70731    assert( !(fg&MEM_Zero) );
 70732    assert( !(fg&(MEM_Str|MEM_Blob)) );
 70733    assert( fg&(MEM_Int|MEM_Real) );
 70734    assert( (pMem->flags&MEM_RowSet)==0 );
 70735    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 70736  
 70737  
 70738    if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
 70739      pMem->enc = 0;
 70740      return SQLITE_NOMEM_BKPT;
 70741    }
 70742  
 70743    /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
 70744    ** string representation of the value. Then, if the required encoding
 70745    ** is UTF-16le or UTF-16be do a translation.
 70746    ** 
 70747    ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
 70748    */
 70749    if( fg & MEM_Int ){
 70750      sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
 70751    }else{
 70752      assert( fg & MEM_Real );
 70753      sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
 70754    }
 70755    pMem->n = sqlite3Strlen30(pMem->z);
 70756    pMem->enc = SQLITE_UTF8;
 70757    pMem->flags |= MEM_Str|MEM_Term;
 70758    if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
 70759    sqlite3VdbeChangeEncoding(pMem, enc);
 70760    return SQLITE_OK;
 70761  }
 70762  
 70763  /*
 70764  ** Memory cell pMem contains the context of an aggregate function.
 70765  ** This routine calls the finalize method for that function.  The
 70766  ** result of the aggregate is stored back into pMem.
 70767  **
 70768  ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
 70769  ** otherwise.
 70770  */
 70771  SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
 70772    int rc = SQLITE_OK;
 70773    if( ALWAYS(pFunc && pFunc->xFinalize) ){
 70774      sqlite3_context ctx;
 70775      Mem t;
 70776      assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
 70777      assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 70778      memset(&ctx, 0, sizeof(ctx));
 70779      memset(&t, 0, sizeof(t));
 70780      t.flags = MEM_Null;
 70781      t.db = pMem->db;
 70782      ctx.pOut = &t;
 70783      ctx.pMem = pMem;
 70784      ctx.pFunc = pFunc;
 70785      pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
 70786      assert( (pMem->flags & MEM_Dyn)==0 );
 70787      if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
 70788      memcpy(pMem, &t, sizeof(t));
 70789      rc = ctx.isError;
 70790    }
 70791    return rc;
 70792  }
 70793  
 70794  /*
 70795  ** If the memory cell contains a value that must be freed by
 70796  ** invoking the external callback in Mem.xDel, then this routine
 70797  ** will free that value.  It also sets Mem.flags to MEM_Null.
 70798  **
 70799  ** This is a helper routine for sqlite3VdbeMemSetNull() and
 70800  ** for sqlite3VdbeMemRelease().  Use those other routines as the
 70801  ** entry point for releasing Mem resources.
 70802  */
 70803  static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
 70804    assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
 70805    assert( VdbeMemDynamic(p) );
 70806    if( p->flags&MEM_Agg ){
 70807      sqlite3VdbeMemFinalize(p, p->u.pDef);
 70808      assert( (p->flags & MEM_Agg)==0 );
 70809      testcase( p->flags & MEM_Dyn );
 70810    }
 70811    if( p->flags&MEM_Dyn ){
 70812      assert( (p->flags&MEM_RowSet)==0 );
 70813      assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
 70814      p->xDel((void *)p->z);
 70815    }else if( p->flags&MEM_RowSet ){
 70816      sqlite3RowSetClear(p->u.pRowSet);
 70817    }else if( p->flags&MEM_Frame ){
 70818      VdbeFrame *pFrame = p->u.pFrame;
 70819      pFrame->pParent = pFrame->v->pDelFrame;
 70820      pFrame->v->pDelFrame = pFrame;
 70821    }
 70822    p->flags = MEM_Null;
 70823  }
 70824  
 70825  /*
 70826  ** Release memory held by the Mem p, both external memory cleared
 70827  ** by p->xDel and memory in p->zMalloc.
 70828  **
 70829  ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
 70830  ** the unusual case where there really is memory in p that needs
 70831  ** to be freed.
 70832  */
 70833  static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
 70834    if( VdbeMemDynamic(p) ){
 70835      vdbeMemClearExternAndSetNull(p);
 70836    }
 70837    if( p->szMalloc ){
 70838      sqlite3DbFreeNN(p->db, p->zMalloc);
 70839      p->szMalloc = 0;
 70840    }
 70841    p->z = 0;
 70842  }
 70843  
 70844  /*
 70845  ** Release any memory resources held by the Mem.  Both the memory that is
 70846  ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
 70847  **
 70848  ** Use this routine prior to clean up prior to abandoning a Mem, or to
 70849  ** reset a Mem back to its minimum memory utilization.
 70850  **
 70851  ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
 70852  ** prior to inserting new content into the Mem.
 70853  */
 70854  SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
 70855    assert( sqlite3VdbeCheckMemInvariants(p) );
 70856    if( VdbeMemDynamic(p) || p->szMalloc ){
 70857      vdbeMemClear(p);
 70858    }
 70859  }
 70860  
 70861  /*
 70862  ** Convert a 64-bit IEEE double into a 64-bit signed integer.
 70863  ** If the double is out of range of a 64-bit signed integer then
 70864  ** return the closest available 64-bit signed integer.
 70865  */
 70866  static SQLITE_NOINLINE i64 doubleToInt64(double r){
 70867  #ifdef SQLITE_OMIT_FLOATING_POINT
 70868    /* When floating-point is omitted, double and int64 are the same thing */
 70869    return r;
 70870  #else
 70871    /*
 70872    ** Many compilers we encounter do not define constants for the
 70873    ** minimum and maximum 64-bit integers, or they define them
 70874    ** inconsistently.  And many do not understand the "LL" notation.
 70875    ** So we define our own static constants here using nothing
 70876    ** larger than a 32-bit integer constant.
 70877    */
 70878    static const i64 maxInt = LARGEST_INT64;
 70879    static const i64 minInt = SMALLEST_INT64;
 70880  
 70881    if( r<=(double)minInt ){
 70882      return minInt;
 70883    }else if( r>=(double)maxInt ){
 70884      return maxInt;
 70885    }else{
 70886      return (i64)r;
 70887    }
 70888  #endif
 70889  }
 70890  
 70891  /*
 70892  ** Return some kind of integer value which is the best we can do
 70893  ** at representing the value that *pMem describes as an integer.
 70894  ** If pMem is an integer, then the value is exact.  If pMem is
 70895  ** a floating-point then the value returned is the integer part.
 70896  ** If pMem is a string or blob, then we make an attempt to convert
 70897  ** it into an integer and return that.  If pMem represents an
 70898  ** an SQL-NULL value, return 0.
 70899  **
 70900  ** If pMem represents a string value, its encoding might be changed.
 70901  */
 70902  static SQLITE_NOINLINE i64 memIntValue(Mem *pMem){
 70903    i64 value = 0;
 70904    sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
 70905    return value;
 70906  }
 70907  SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
 70908    int flags;
 70909    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 70910    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 70911    flags = pMem->flags;
 70912    if( flags & MEM_Int ){
 70913      return pMem->u.i;
 70914    }else if( flags & MEM_Real ){
 70915      return doubleToInt64(pMem->u.r);
 70916    }else if( flags & (MEM_Str|MEM_Blob) ){
 70917      assert( pMem->z || pMem->n==0 );
 70918      return memIntValue(pMem);
 70919    }else{
 70920      return 0;
 70921    }
 70922  }
 70923  
 70924  /*
 70925  ** Return the best representation of pMem that we can get into a
 70926  ** double.  If pMem is already a double or an integer, return its
 70927  ** value.  If it is a string or blob, try to convert it to a double.
 70928  ** If it is a NULL, return 0.0.
 70929  */
 70930  static SQLITE_NOINLINE double memRealValue(Mem *pMem){
 70931    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
 70932    double val = (double)0;
 70933    sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
 70934    return val;
 70935  }
 70936  SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
 70937    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 70938    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 70939    if( pMem->flags & MEM_Real ){
 70940      return pMem->u.r;
 70941    }else if( pMem->flags & MEM_Int ){
 70942      return (double)pMem->u.i;
 70943    }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
 70944      return memRealValue(pMem);
 70945    }else{
 70946      /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
 70947      return (double)0;
 70948    }
 70949  }
 70950  
 70951  /*
 70952  ** The MEM structure is already a MEM_Real.  Try to also make it a
 70953  ** MEM_Int if we can.
 70954  */
 70955  SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
 70956    i64 ix;
 70957    assert( pMem->flags & MEM_Real );
 70958    assert( (pMem->flags & MEM_RowSet)==0 );
 70959    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 70960    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 70961  
 70962    ix = doubleToInt64(pMem->u.r);
 70963  
 70964    /* Only mark the value as an integer if
 70965    **
 70966    **    (1) the round-trip conversion real->int->real is a no-op, and
 70967    **    (2) The integer is neither the largest nor the smallest
 70968    **        possible integer (ticket #3922)
 70969    **
 70970    ** The second and third terms in the following conditional enforces
 70971    ** the second condition under the assumption that addition overflow causes
 70972    ** values to wrap around.
 70973    */
 70974    if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
 70975      pMem->u.i = ix;
 70976      MemSetTypeFlag(pMem, MEM_Int);
 70977    }
 70978  }
 70979  
 70980  /*
 70981  ** Convert pMem to type integer.  Invalidate any prior representations.
 70982  */
 70983  SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
 70984    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 70985    assert( (pMem->flags & MEM_RowSet)==0 );
 70986    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 70987  
 70988    pMem->u.i = sqlite3VdbeIntValue(pMem);
 70989    MemSetTypeFlag(pMem, MEM_Int);
 70990    return SQLITE_OK;
 70991  }
 70992  
 70993  /*
 70994  ** Convert pMem so that it is of type MEM_Real.
 70995  ** Invalidate any prior representations.
 70996  */
 70997  SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
 70998    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 70999    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 71000  
 71001    pMem->u.r = sqlite3VdbeRealValue(pMem);
 71002    MemSetTypeFlag(pMem, MEM_Real);
 71003    return SQLITE_OK;
 71004  }
 71005  
 71006  /*
 71007  ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
 71008  ** Invalidate any prior representations.
 71009  **
 71010  ** Every effort is made to force the conversion, even if the input
 71011  ** is a string that does not look completely like a number.  Convert
 71012  ** as much of the string as we can and ignore the rest.
 71013  */
 71014  SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
 71015    if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
 71016      int rc;
 71017      assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
 71018      assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 71019      rc = sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc);
 71020      if( rc==0 ){
 71021        MemSetTypeFlag(pMem, MEM_Int);
 71022      }else{
 71023        i64 i = pMem->u.i;
 71024        sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
 71025        if( rc==1 && pMem->u.r==(double)i ){
 71026          pMem->u.i = i;
 71027          MemSetTypeFlag(pMem, MEM_Int);
 71028        }else{
 71029          MemSetTypeFlag(pMem, MEM_Real);
 71030        }
 71031      }
 71032    }
 71033    assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
 71034    pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
 71035    return SQLITE_OK;
 71036  }
 71037  
 71038  /*
 71039  ** Cast the datatype of the value in pMem according to the affinity
 71040  ** "aff".  Casting is different from applying affinity in that a cast
 71041  ** is forced.  In other words, the value is converted into the desired
 71042  ** affinity even if that results in loss of data.  This routine is
 71043  ** used (for example) to implement the SQL "cast()" operator.
 71044  */
 71045  SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
 71046    if( pMem->flags & MEM_Null ) return;
 71047    switch( aff ){
 71048      case SQLITE_AFF_BLOB: {   /* Really a cast to BLOB */
 71049        if( (pMem->flags & MEM_Blob)==0 ){
 71050          sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
 71051          assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
 71052          if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
 71053        }else{
 71054          pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
 71055        }
 71056        break;
 71057      }
 71058      case SQLITE_AFF_NUMERIC: {
 71059        sqlite3VdbeMemNumerify(pMem);
 71060        break;
 71061      }
 71062      case SQLITE_AFF_INTEGER: {
 71063        sqlite3VdbeMemIntegerify(pMem);
 71064        break;
 71065      }
 71066      case SQLITE_AFF_REAL: {
 71067        sqlite3VdbeMemRealify(pMem);
 71068        break;
 71069      }
 71070      default: {
 71071        assert( aff==SQLITE_AFF_TEXT );
 71072        assert( MEM_Str==(MEM_Blob>>3) );
 71073        pMem->flags |= (pMem->flags&MEM_Blob)>>3;
 71074        sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
 71075        assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
 71076        pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
 71077        break;
 71078      }
 71079    }
 71080  }
 71081  
 71082  /*
 71083  ** Initialize bulk memory to be a consistent Mem object.
 71084  **
 71085  ** The minimum amount of initialization feasible is performed.
 71086  */
 71087  SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
 71088    assert( (flags & ~MEM_TypeMask)==0 );
 71089    pMem->flags = flags;
 71090    pMem->db = db;
 71091    pMem->szMalloc = 0;
 71092  }
 71093  
 71094  
 71095  /*
 71096  ** Delete any previous value and set the value stored in *pMem to NULL.
 71097  **
 71098  ** This routine calls the Mem.xDel destructor to dispose of values that
 71099  ** require the destructor.  But it preserves the Mem.zMalloc memory allocation.
 71100  ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
 71101  ** routine to invoke the destructor and deallocates Mem.zMalloc.
 71102  **
 71103  ** Use this routine to reset the Mem prior to insert a new value.
 71104  **
 71105  ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
 71106  */
 71107  SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
 71108    if( VdbeMemDynamic(pMem) ){
 71109      vdbeMemClearExternAndSetNull(pMem);
 71110    }else{
 71111      pMem->flags = MEM_Null;
 71112    }
 71113  }
 71114  SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
 71115    sqlite3VdbeMemSetNull((Mem*)p); 
 71116  }
 71117  
 71118  /*
 71119  ** Delete any previous value and set the value to be a BLOB of length
 71120  ** n containing all zeros.
 71121  */
 71122  SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
 71123    sqlite3VdbeMemRelease(pMem);
 71124    pMem->flags = MEM_Blob|MEM_Zero;
 71125    pMem->n = 0;
 71126    if( n<0 ) n = 0;
 71127    pMem->u.nZero = n;
 71128    pMem->enc = SQLITE_UTF8;
 71129    pMem->z = 0;
 71130  }
 71131  
 71132  /*
 71133  ** The pMem is known to contain content that needs to be destroyed prior
 71134  ** to a value change.  So invoke the destructor, then set the value to
 71135  ** a 64-bit integer.
 71136  */
 71137  static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
 71138    sqlite3VdbeMemSetNull(pMem);
 71139    pMem->u.i = val;
 71140    pMem->flags = MEM_Int;
 71141  }
 71142  
 71143  /*
 71144  ** Delete any previous value and set the value stored in *pMem to val,
 71145  ** manifest type INTEGER.
 71146  */
 71147  SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
 71148    if( VdbeMemDynamic(pMem) ){
 71149      vdbeReleaseAndSetInt64(pMem, val);
 71150    }else{
 71151      pMem->u.i = val;
 71152      pMem->flags = MEM_Int;
 71153    }
 71154  }
 71155  
 71156  /* A no-op destructor */
 71157  static void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); }
 71158  
 71159  /*
 71160  ** Set the value stored in *pMem should already be a NULL.
 71161  ** Also store a pointer to go with it.
 71162  */
 71163  SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(
 71164    Mem *pMem,
 71165    void *pPtr,
 71166    const char *zPType,
 71167    void (*xDestructor)(void*)
 71168  ){
 71169    assert( pMem->flags==MEM_Null );
 71170    pMem->u.zPType = zPType ? zPType : "";
 71171    pMem->z = pPtr;
 71172    pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;
 71173    pMem->eSubtype = 'p';
 71174    pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor;
 71175  }
 71176  
 71177  #ifndef SQLITE_OMIT_FLOATING_POINT
 71178  /*
 71179  ** Delete any previous value and set the value stored in *pMem to val,
 71180  ** manifest type REAL.
 71181  */
 71182  SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
 71183    sqlite3VdbeMemSetNull(pMem);
 71184    if( !sqlite3IsNaN(val) ){
 71185      pMem->u.r = val;
 71186      pMem->flags = MEM_Real;
 71187    }
 71188  }
 71189  #endif
 71190  
 71191  /*
 71192  ** Delete any previous value and set the value of pMem to be an
 71193  ** empty boolean index.
 71194  */
 71195  SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
 71196    sqlite3 *db = pMem->db;
 71197    assert( db!=0 );
 71198    assert( (pMem->flags & MEM_RowSet)==0 );
 71199    sqlite3VdbeMemRelease(pMem);
 71200    pMem->zMalloc = sqlite3DbMallocRawNN(db, 64);
 71201    if( db->mallocFailed ){
 71202      pMem->flags = MEM_Null;
 71203      pMem->szMalloc = 0;
 71204    }else{
 71205      assert( pMem->zMalloc );
 71206      pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
 71207      pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
 71208      assert( pMem->u.pRowSet!=0 );
 71209      pMem->flags = MEM_RowSet;
 71210    }
 71211  }
 71212  
 71213  /*
 71214  ** Return true if the Mem object contains a TEXT or BLOB that is
 71215  ** too large - whose size exceeds SQLITE_MAX_LENGTH.
 71216  */
 71217  SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
 71218    assert( p->db!=0 );
 71219    if( p->flags & (MEM_Str|MEM_Blob) ){
 71220      int n = p->n;
 71221      if( p->flags & MEM_Zero ){
 71222        n += p->u.nZero;
 71223      }
 71224      return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
 71225    }
 71226    return 0; 
 71227  }
 71228  
 71229  #ifdef SQLITE_DEBUG
 71230  /*
 71231  ** This routine prepares a memory cell for modification by breaking
 71232  ** its link to a shallow copy and by marking any current shallow
 71233  ** copies of this cell as invalid.
 71234  **
 71235  ** This is used for testing and debugging only - to make sure shallow
 71236  ** copies are not misused.
 71237  */
 71238  SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
 71239    int i;
 71240    Mem *pX;
 71241    for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
 71242      if( pX->pScopyFrom==pMem ){
 71243        pX->flags |= MEM_Undefined;
 71244        pX->pScopyFrom = 0;
 71245      }
 71246    }
 71247    pMem->pScopyFrom = 0;
 71248  }
 71249  #endif /* SQLITE_DEBUG */
 71250  
 71251  
 71252  /*
 71253  ** Make an shallow copy of pFrom into pTo.  Prior contents of
 71254  ** pTo are freed.  The pFrom->z field is not duplicated.  If
 71255  ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
 71256  ** and flags gets srcType (either MEM_Ephem or MEM_Static).
 71257  */
 71258  static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
 71259    vdbeMemClearExternAndSetNull(pTo);
 71260    assert( !VdbeMemDynamic(pTo) );
 71261    sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
 71262  }
 71263  SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
 71264    assert( (pFrom->flags & MEM_RowSet)==0 );
 71265    assert( pTo->db==pFrom->db );
 71266    if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
 71267    memcpy(pTo, pFrom, MEMCELLSIZE);
 71268    if( (pFrom->flags&MEM_Static)==0 ){
 71269      pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
 71270      assert( srcType==MEM_Ephem || srcType==MEM_Static );
 71271      pTo->flags |= srcType;
 71272    }
 71273  }
 71274  
 71275  /*
 71276  ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
 71277  ** freed before the copy is made.
 71278  */
 71279  SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
 71280    int rc = SQLITE_OK;
 71281  
 71282    assert( (pFrom->flags & MEM_RowSet)==0 );
 71283    if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
 71284    memcpy(pTo, pFrom, MEMCELLSIZE);
 71285    pTo->flags &= ~MEM_Dyn;
 71286    if( pTo->flags&(MEM_Str|MEM_Blob) ){
 71287      if( 0==(pFrom->flags&MEM_Static) ){
 71288        pTo->flags |= MEM_Ephem;
 71289        rc = sqlite3VdbeMemMakeWriteable(pTo);
 71290      }
 71291    }
 71292  
 71293    return rc;
 71294  }
 71295  
 71296  /*
 71297  ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
 71298  ** freed. If pFrom contains ephemeral data, a copy is made.
 71299  **
 71300  ** pFrom contains an SQL NULL when this routine returns.
 71301  */
 71302  SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
 71303    assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
 71304    assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
 71305    assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
 71306  
 71307    sqlite3VdbeMemRelease(pTo);
 71308    memcpy(pTo, pFrom, sizeof(Mem));
 71309    pFrom->flags = MEM_Null;
 71310    pFrom->szMalloc = 0;
 71311  }
 71312  
 71313  /*
 71314  ** Change the value of a Mem to be a string or a BLOB.
 71315  **
 71316  ** The memory management strategy depends on the value of the xDel
 71317  ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
 71318  ** string is copied into a (possibly existing) buffer managed by the 
 71319  ** Mem structure. Otherwise, any existing buffer is freed and the
 71320  ** pointer copied.
 71321  **
 71322  ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
 71323  ** size limit) then no memory allocation occurs.  If the string can be
 71324  ** stored without allocating memory, then it is.  If a memory allocation
 71325  ** is required to store the string, then value of pMem is unchanged.  In
 71326  ** either case, SQLITE_TOOBIG is returned.
 71327  */
 71328  SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
 71329    Mem *pMem,          /* Memory cell to set to string value */
 71330    const char *z,      /* String pointer */
 71331    int n,              /* Bytes in string, or negative */
 71332    u8 enc,             /* Encoding of z.  0 for BLOBs */
 71333    void (*xDel)(void*) /* Destructor function */
 71334  ){
 71335    int nByte = n;      /* New value for pMem->n */
 71336    int iLimit;         /* Maximum allowed string or blob size */
 71337    u16 flags = 0;      /* New value for pMem->flags */
 71338  
 71339    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 71340    assert( (pMem->flags & MEM_RowSet)==0 );
 71341  
 71342    /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
 71343    if( !z ){
 71344      sqlite3VdbeMemSetNull(pMem);
 71345      return SQLITE_OK;
 71346    }
 71347  
 71348    if( pMem->db ){
 71349      iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
 71350    }else{
 71351      iLimit = SQLITE_MAX_LENGTH;
 71352    }
 71353    flags = (enc==0?MEM_Blob:MEM_Str);
 71354    if( nByte<0 ){
 71355      assert( enc!=0 );
 71356      if( enc==SQLITE_UTF8 ){
 71357        nByte = 0x7fffffff & (int)strlen(z);
 71358        if( nByte>iLimit ) nByte = iLimit+1;
 71359      }else{
 71360        for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
 71361      }
 71362      flags |= MEM_Term;
 71363    }
 71364  
 71365    /* The following block sets the new values of Mem.z and Mem.xDel. It
 71366    ** also sets a flag in local variable "flags" to indicate the memory
 71367    ** management (one of MEM_Dyn or MEM_Static).
 71368    */
 71369    if( xDel==SQLITE_TRANSIENT ){
 71370      int nAlloc = nByte;
 71371      if( flags&MEM_Term ){
 71372        nAlloc += (enc==SQLITE_UTF8?1:2);
 71373      }
 71374      if( nByte>iLimit ){
 71375        return SQLITE_TOOBIG;
 71376      }
 71377      testcase( nAlloc==0 );
 71378      testcase( nAlloc==31 );
 71379      testcase( nAlloc==32 );
 71380      if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
 71381        return SQLITE_NOMEM_BKPT;
 71382      }
 71383      memcpy(pMem->z, z, nAlloc);
 71384    }else if( xDel==SQLITE_DYNAMIC ){
 71385      sqlite3VdbeMemRelease(pMem);
 71386      pMem->zMalloc = pMem->z = (char *)z;
 71387      pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
 71388    }else{
 71389      sqlite3VdbeMemRelease(pMem);
 71390      pMem->z = (char *)z;
 71391      pMem->xDel = xDel;
 71392      flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
 71393    }
 71394  
 71395    pMem->n = nByte;
 71396    pMem->flags = flags;
 71397    pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
 71398  
 71399  #ifndef SQLITE_OMIT_UTF16
 71400    if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
 71401      return SQLITE_NOMEM_BKPT;
 71402    }
 71403  #endif
 71404  
 71405    if( nByte>iLimit ){
 71406      return SQLITE_TOOBIG;
 71407    }
 71408  
 71409    return SQLITE_OK;
 71410  }
 71411  
 71412  /*
 71413  ** Move data out of a btree key or data field and into a Mem structure.
 71414  ** The data is payload from the entry that pCur is currently pointing
 71415  ** to.  offset and amt determine what portion of the data or key to retrieve.
 71416  ** The result is written into the pMem element.
 71417  **
 71418  ** The pMem object must have been initialized.  This routine will use
 71419  ** pMem->zMalloc to hold the content from the btree, if possible.  New
 71420  ** pMem->zMalloc space will be allocated if necessary.  The calling routine
 71421  ** is responsible for making sure that the pMem object is eventually
 71422  ** destroyed.
 71423  **
 71424  ** If this routine fails for any reason (malloc returns NULL or unable
 71425  ** to read from the disk) then the pMem is left in an inconsistent state.
 71426  */
 71427  static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
 71428    BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
 71429    u32 offset,       /* Offset from the start of data to return bytes from. */
 71430    u32 amt,          /* Number of bytes to return. */
 71431    Mem *pMem         /* OUT: Return data in this Mem structure. */
 71432  ){
 71433    int rc;
 71434    pMem->flags = MEM_Null;
 71435    if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){
 71436      rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
 71437      if( rc==SQLITE_OK ){
 71438        pMem->z[amt] = 0;   /* Overrun area used when reading malformed records */
 71439        pMem->flags = MEM_Blob;
 71440        pMem->n = (int)amt;
 71441      }else{
 71442        sqlite3VdbeMemRelease(pMem);
 71443      }
 71444    }
 71445    return rc;
 71446  }
 71447  SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
 71448    BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
 71449    u32 offset,       /* Offset from the start of data to return bytes from. */
 71450    u32 amt,          /* Number of bytes to return. */
 71451    Mem *pMem         /* OUT: Return data in this Mem structure. */
 71452  ){
 71453    char *zData;        /* Data from the btree layer */
 71454    u32 available = 0;  /* Number of bytes available on the local btree page */
 71455    int rc = SQLITE_OK; /* Return code */
 71456  
 71457    assert( sqlite3BtreeCursorIsValid(pCur) );
 71458    assert( !VdbeMemDynamic(pMem) );
 71459  
 71460    /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
 71461    ** that both the BtShared and database handle mutexes are held. */
 71462    assert( (pMem->flags & MEM_RowSet)==0 );
 71463    zData = (char *)sqlite3BtreePayloadFetch(pCur, &available);
 71464    assert( zData!=0 );
 71465  
 71466    if( offset+amt<=available ){
 71467      pMem->z = &zData[offset];
 71468      pMem->flags = MEM_Blob|MEM_Ephem;
 71469      pMem->n = (int)amt;
 71470    }else{
 71471      rc = vdbeMemFromBtreeResize(pCur, offset, amt, pMem);
 71472    }
 71473  
 71474    return rc;
 71475  }
 71476  
 71477  /*
 71478  ** The pVal argument is known to be a value other than NULL.
 71479  ** Convert it into a string with encoding enc and return a pointer
 71480  ** to a zero-terminated version of that string.
 71481  */
 71482  static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
 71483    assert( pVal!=0 );
 71484    assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
 71485    assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
 71486    assert( (pVal->flags & MEM_RowSet)==0 );
 71487    assert( (pVal->flags & (MEM_Null))==0 );
 71488    if( pVal->flags & (MEM_Blob|MEM_Str) ){
 71489      if( ExpandBlob(pVal) ) return 0;
 71490      pVal->flags |= MEM_Str;
 71491      if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
 71492        sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
 71493      }
 71494      if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
 71495        assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
 71496        if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
 71497          return 0;
 71498        }
 71499      }
 71500      sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
 71501    }else{
 71502      sqlite3VdbeMemStringify(pVal, enc, 0);
 71503      assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
 71504    }
 71505    assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
 71506                || pVal->db->mallocFailed );
 71507    if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
 71508      return pVal->z;
 71509    }else{
 71510      return 0;
 71511    }
 71512  }
 71513  
 71514  /* This function is only available internally, it is not part of the
 71515  ** external API. It works in a similar way to sqlite3_value_text(),
 71516  ** except the data returned is in the encoding specified by the second
 71517  ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
 71518  ** SQLITE_UTF8.
 71519  **
 71520  ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
 71521  ** If that is the case, then the result must be aligned on an even byte
 71522  ** boundary.
 71523  */
 71524  SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
 71525    if( !pVal ) return 0;
 71526    assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
 71527    assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
 71528    assert( (pVal->flags & MEM_RowSet)==0 );
 71529    if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
 71530      return pVal->z;
 71531    }
 71532    if( pVal->flags&MEM_Null ){
 71533      return 0;
 71534    }
 71535    return valueToText(pVal, enc);
 71536  }
 71537  
 71538  /*
 71539  ** Create a new sqlite3_value object.
 71540  */
 71541  SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
 71542    Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
 71543    if( p ){
 71544      p->flags = MEM_Null;
 71545      p->db = db;
 71546    }
 71547    return p;
 71548  }
 71549  
 71550  /*
 71551  ** Context object passed by sqlite3Stat4ProbeSetValue() through to 
 71552  ** valueNew(). See comments above valueNew() for details.
 71553  */
 71554  struct ValueNewStat4Ctx {
 71555    Parse *pParse;
 71556    Index *pIdx;
 71557    UnpackedRecord **ppRec;
 71558    int iVal;
 71559  };
 71560  
 71561  /*
 71562  ** Allocate and return a pointer to a new sqlite3_value object. If
 71563  ** the second argument to this function is NULL, the object is allocated
 71564  ** by calling sqlite3ValueNew().
 71565  **
 71566  ** Otherwise, if the second argument is non-zero, then this function is 
 71567  ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
 71568  ** already been allocated, allocate the UnpackedRecord structure that 
 71569  ** that function will return to its caller here. Then return a pointer to
 71570  ** an sqlite3_value within the UnpackedRecord.a[] array.
 71571  */
 71572  static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
 71573  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 71574    if( p ){
 71575      UnpackedRecord *pRec = p->ppRec[0];
 71576  
 71577      if( pRec==0 ){
 71578        Index *pIdx = p->pIdx;      /* Index being probed */
 71579        int nByte;                  /* Bytes of space to allocate */
 71580        int i;                      /* Counter variable */
 71581        int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
 71582    
 71583        nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
 71584        pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
 71585        if( pRec ){
 71586          pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
 71587          if( pRec->pKeyInfo ){
 71588            assert( pRec->pKeyInfo->nAllField==nCol );
 71589            assert( pRec->pKeyInfo->enc==ENC(db) );
 71590            pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
 71591            for(i=0; i<nCol; i++){
 71592              pRec->aMem[i].flags = MEM_Null;
 71593              pRec->aMem[i].db = db;
 71594            }
 71595          }else{
 71596            sqlite3DbFreeNN(db, pRec);
 71597            pRec = 0;
 71598          }
 71599        }
 71600        if( pRec==0 ) return 0;
 71601        p->ppRec[0] = pRec;
 71602      }
 71603    
 71604      pRec->nField = p->iVal+1;
 71605      return &pRec->aMem[p->iVal];
 71606    }
 71607  #else
 71608    UNUSED_PARAMETER(p);
 71609  #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
 71610    return sqlite3ValueNew(db);
 71611  }
 71612  
 71613  /*
 71614  ** The expression object indicated by the second argument is guaranteed
 71615  ** to be a scalar SQL function. If
 71616  **
 71617  **   * all function arguments are SQL literals,
 71618  **   * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
 71619  **   * the SQLITE_FUNC_NEEDCOLL function flag is not set,
 71620  **
 71621  ** then this routine attempts to invoke the SQL function. Assuming no
 71622  ** error occurs, output parameter (*ppVal) is set to point to a value 
 71623  ** object containing the result before returning SQLITE_OK.
 71624  **
 71625  ** Affinity aff is applied to the result of the function before returning.
 71626  ** If the result is a text value, the sqlite3_value object uses encoding 
 71627  ** enc.
 71628  **
 71629  ** If the conditions above are not met, this function returns SQLITE_OK
 71630  ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
 71631  ** NULL and an SQLite error code returned.
 71632  */
 71633  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 71634  static int valueFromFunction(
 71635    sqlite3 *db,                    /* The database connection */
 71636    Expr *p,                        /* The expression to evaluate */
 71637    u8 enc,                         /* Encoding to use */
 71638    u8 aff,                         /* Affinity to use */
 71639    sqlite3_value **ppVal,          /* Write the new value here */
 71640    struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
 71641  ){
 71642    sqlite3_context ctx;            /* Context object for function invocation */
 71643    sqlite3_value **apVal = 0;      /* Function arguments */
 71644    int nVal = 0;                   /* Size of apVal[] array */
 71645    FuncDef *pFunc = 0;             /* Function definition */
 71646    sqlite3_value *pVal = 0;        /* New value */
 71647    int rc = SQLITE_OK;             /* Return code */
 71648    ExprList *pList = 0;            /* Function arguments */
 71649    int i;                          /* Iterator variable */
 71650  
 71651    assert( pCtx!=0 );
 71652    assert( (p->flags & EP_TokenOnly)==0 );
 71653    pList = p->x.pList;
 71654    if( pList ) nVal = pList->nExpr;
 71655    pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
 71656    assert( pFunc );
 71657    if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0 
 71658     || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
 71659    ){
 71660      return SQLITE_OK;
 71661    }
 71662  
 71663    if( pList ){
 71664      apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
 71665      if( apVal==0 ){
 71666        rc = SQLITE_NOMEM_BKPT;
 71667        goto value_from_function_out;
 71668      }
 71669      for(i=0; i<nVal; i++){
 71670        rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
 71671        if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
 71672      }
 71673    }
 71674  
 71675    pVal = valueNew(db, pCtx);
 71676    if( pVal==0 ){
 71677      rc = SQLITE_NOMEM_BKPT;
 71678      goto value_from_function_out;
 71679    }
 71680  
 71681    assert( pCtx->pParse->rc==SQLITE_OK );
 71682    memset(&ctx, 0, sizeof(ctx));
 71683    ctx.pOut = pVal;
 71684    ctx.pFunc = pFunc;
 71685    pFunc->xSFunc(&ctx, nVal, apVal);
 71686    if( ctx.isError ){
 71687      rc = ctx.isError;
 71688      sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
 71689    }else{
 71690      sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
 71691      assert( rc==SQLITE_OK );
 71692      rc = sqlite3VdbeChangeEncoding(pVal, enc);
 71693      if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
 71694        rc = SQLITE_TOOBIG;
 71695        pCtx->pParse->nErr++;
 71696      }
 71697    }
 71698    pCtx->pParse->rc = rc;
 71699  
 71700   value_from_function_out:
 71701    if( rc!=SQLITE_OK ){
 71702      pVal = 0;
 71703    }
 71704    if( apVal ){
 71705      for(i=0; i<nVal; i++){
 71706        sqlite3ValueFree(apVal[i]);
 71707      }
 71708      sqlite3DbFreeNN(db, apVal);
 71709    }
 71710  
 71711    *ppVal = pVal;
 71712    return rc;
 71713  }
 71714  #else
 71715  # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
 71716  #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
 71717  
 71718  /*
 71719  ** Extract a value from the supplied expression in the manner described
 71720  ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
 71721  ** using valueNew().
 71722  **
 71723  ** If pCtx is NULL and an error occurs after the sqlite3_value object
 71724  ** has been allocated, it is freed before returning. Or, if pCtx is not
 71725  ** NULL, it is assumed that the caller will free any allocated object
 71726  ** in all cases.
 71727  */
 71728  static int valueFromExpr(
 71729    sqlite3 *db,                    /* The database connection */
 71730    Expr *pExpr,                    /* The expression to evaluate */
 71731    u8 enc,                         /* Encoding to use */
 71732    u8 affinity,                    /* Affinity to use */
 71733    sqlite3_value **ppVal,          /* Write the new value here */
 71734    struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
 71735  ){
 71736    int op;
 71737    char *zVal = 0;
 71738    sqlite3_value *pVal = 0;
 71739    int negInt = 1;
 71740    const char *zNeg = "";
 71741    int rc = SQLITE_OK;
 71742  
 71743    assert( pExpr!=0 );
 71744    while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
 71745    if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
 71746  
 71747    /* Compressed expressions only appear when parsing the DEFAULT clause
 71748    ** on a table column definition, and hence only when pCtx==0.  This
 71749    ** check ensures that an EP_TokenOnly expression is never passed down
 71750    ** into valueFromFunction(). */
 71751    assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
 71752  
 71753    if( op==TK_CAST ){
 71754      u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
 71755      rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
 71756      testcase( rc!=SQLITE_OK );
 71757      if( *ppVal ){
 71758        sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
 71759        sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
 71760      }
 71761      return rc;
 71762    }
 71763  
 71764    /* Handle negative integers in a single step.  This is needed in the
 71765    ** case when the value is -9223372036854775808.
 71766    */
 71767    if( op==TK_UMINUS
 71768     && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
 71769      pExpr = pExpr->pLeft;
 71770      op = pExpr->op;
 71771      negInt = -1;
 71772      zNeg = "-";
 71773    }
 71774  
 71775    if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
 71776      pVal = valueNew(db, pCtx);
 71777      if( pVal==0 ) goto no_mem;
 71778      if( ExprHasProperty(pExpr, EP_IntValue) ){
 71779        sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
 71780      }else{
 71781        zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
 71782        if( zVal==0 ) goto no_mem;
 71783        sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
 71784      }
 71785      if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
 71786        sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
 71787      }else{
 71788        sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
 71789      }
 71790      if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
 71791      if( enc!=SQLITE_UTF8 ){
 71792        rc = sqlite3VdbeChangeEncoding(pVal, enc);
 71793      }
 71794    }else if( op==TK_UMINUS ) {
 71795      /* This branch happens for multiple negative signs.  Ex: -(-5) */
 71796      if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx) 
 71797       && pVal!=0
 71798      ){
 71799        sqlite3VdbeMemNumerify(pVal);
 71800        if( pVal->flags & MEM_Real ){
 71801          pVal->u.r = -pVal->u.r;
 71802        }else if( pVal->u.i==SMALLEST_INT64 ){
 71803          pVal->u.r = -(double)SMALLEST_INT64;
 71804          MemSetTypeFlag(pVal, MEM_Real);
 71805        }else{
 71806          pVal->u.i = -pVal->u.i;
 71807        }
 71808        sqlite3ValueApplyAffinity(pVal, affinity, enc);
 71809      }
 71810    }else if( op==TK_NULL ){
 71811      pVal = valueNew(db, pCtx);
 71812      if( pVal==0 ) goto no_mem;
 71813      sqlite3VdbeMemNumerify(pVal);
 71814    }
 71815  #ifndef SQLITE_OMIT_BLOB_LITERAL
 71816    else if( op==TK_BLOB ){
 71817      int nVal;
 71818      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
 71819      assert( pExpr->u.zToken[1]=='\'' );
 71820      pVal = valueNew(db, pCtx);
 71821      if( !pVal ) goto no_mem;
 71822      zVal = &pExpr->u.zToken[2];
 71823      nVal = sqlite3Strlen30(zVal)-1;
 71824      assert( zVal[nVal]=='\'' );
 71825      sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
 71826                           0, SQLITE_DYNAMIC);
 71827    }
 71828  #endif
 71829  
 71830  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 71831    else if( op==TK_FUNCTION && pCtx!=0 ){
 71832      rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
 71833    }
 71834  #endif
 71835  
 71836    *ppVal = pVal;
 71837    return rc;
 71838  
 71839  no_mem:
 71840    sqlite3OomFault(db);
 71841    sqlite3DbFree(db, zVal);
 71842    assert( *ppVal==0 );
 71843  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 71844    if( pCtx==0 ) sqlite3ValueFree(pVal);
 71845  #else
 71846    assert( pCtx==0 ); sqlite3ValueFree(pVal);
 71847  #endif
 71848    return SQLITE_NOMEM_BKPT;
 71849  }
 71850  
 71851  /*
 71852  ** Create a new sqlite3_value object, containing the value of pExpr.
 71853  **
 71854  ** This only works for very simple expressions that consist of one constant
 71855  ** token (i.e. "5", "5.1", "'a string'"). If the expression can
 71856  ** be converted directly into a value, then the value is allocated and
 71857  ** a pointer written to *ppVal. The caller is responsible for deallocating
 71858  ** the value by passing it to sqlite3ValueFree() later on. If the expression
 71859  ** cannot be converted to a value, then *ppVal is set to NULL.
 71860  */
 71861  SQLITE_PRIVATE int sqlite3ValueFromExpr(
 71862    sqlite3 *db,              /* The database connection */
 71863    Expr *pExpr,              /* The expression to evaluate */
 71864    u8 enc,                   /* Encoding to use */
 71865    u8 affinity,              /* Affinity to use */
 71866    sqlite3_value **ppVal     /* Write the new value here */
 71867  ){
 71868    return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
 71869  }
 71870  
 71871  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 71872  /*
 71873  ** The implementation of the sqlite_record() function. This function accepts
 71874  ** a single argument of any type. The return value is a formatted database 
 71875  ** record (a blob) containing the argument value.
 71876  **
 71877  ** This is used to convert the value stored in the 'sample' column of the
 71878  ** sqlite_stat3 table to the record format SQLite uses internally.
 71879  */
 71880  static void recordFunc(
 71881    sqlite3_context *context,
 71882    int argc,
 71883    sqlite3_value **argv
 71884  ){
 71885    const int file_format = 1;
 71886    u32 iSerial;                    /* Serial type */
 71887    int nSerial;                    /* Bytes of space for iSerial as varint */
 71888    u32 nVal;                       /* Bytes of space required for argv[0] */
 71889    int nRet;
 71890    sqlite3 *db;
 71891    u8 *aRet;
 71892  
 71893    UNUSED_PARAMETER( argc );
 71894    iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
 71895    nSerial = sqlite3VarintLen(iSerial);
 71896    db = sqlite3_context_db_handle(context);
 71897  
 71898    nRet = 1 + nSerial + nVal;
 71899    aRet = sqlite3DbMallocRawNN(db, nRet);
 71900    if( aRet==0 ){
 71901      sqlite3_result_error_nomem(context);
 71902    }else{
 71903      aRet[0] = nSerial+1;
 71904      putVarint32(&aRet[1], iSerial);
 71905      sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
 71906      sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
 71907      sqlite3DbFreeNN(db, aRet);
 71908    }
 71909  }
 71910  
 71911  /*
 71912  ** Register built-in functions used to help read ANALYZE data.
 71913  */
 71914  SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
 71915    static FuncDef aAnalyzeTableFuncs[] = {
 71916      FUNCTION(sqlite_record,   1, 0, 0, recordFunc),
 71917    };
 71918    sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
 71919  }
 71920  
 71921  /*
 71922  ** Attempt to extract a value from pExpr and use it to construct *ppVal.
 71923  **
 71924  ** If pAlloc is not NULL, then an UnpackedRecord object is created for
 71925  ** pAlloc if one does not exist and the new value is added to the
 71926  ** UnpackedRecord object.
 71927  **
 71928  ** A value is extracted in the following cases:
 71929  **
 71930  **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
 71931  **
 71932  **  * The expression is a bound variable, and this is a reprepare, or
 71933  **
 71934  **  * The expression is a literal value.
 71935  **
 71936  ** On success, *ppVal is made to point to the extracted value.  The caller
 71937  ** is responsible for ensuring that the value is eventually freed.
 71938  */
 71939  static int stat4ValueFromExpr(
 71940    Parse *pParse,                  /* Parse context */
 71941    Expr *pExpr,                    /* The expression to extract a value from */
 71942    u8 affinity,                    /* Affinity to use */
 71943    struct ValueNewStat4Ctx *pAlloc,/* How to allocate space.  Or NULL */
 71944    sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
 71945  ){
 71946    int rc = SQLITE_OK;
 71947    sqlite3_value *pVal = 0;
 71948    sqlite3 *db = pParse->db;
 71949  
 71950    /* Skip over any TK_COLLATE nodes */
 71951    pExpr = sqlite3ExprSkipCollate(pExpr);
 71952  
 71953    assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE );
 71954    if( !pExpr ){
 71955      pVal = valueNew(db, pAlloc);
 71956      if( pVal ){
 71957        sqlite3VdbeMemSetNull((Mem*)pVal);
 71958      }
 71959    }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
 71960      Vdbe *v;
 71961      int iBindVar = pExpr->iColumn;
 71962      sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
 71963      if( (v = pParse->pReprepare)!=0 ){
 71964        pVal = valueNew(db, pAlloc);
 71965        if( pVal ){
 71966          rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
 71967          sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
 71968          pVal->db = pParse->db;
 71969        }
 71970      }
 71971    }else{
 71972      rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
 71973    }
 71974  
 71975    assert( pVal==0 || pVal->db==db );
 71976    *ppVal = pVal;
 71977    return rc;
 71978  }
 71979  
 71980  /*
 71981  ** This function is used to allocate and populate UnpackedRecord 
 71982  ** structures intended to be compared against sample index keys stored 
 71983  ** in the sqlite_stat4 table.
 71984  **
 71985  ** A single call to this function populates zero or more fields of the
 71986  ** record starting with field iVal (fields are numbered from left to
 71987  ** right starting with 0). A single field is populated if:
 71988  **
 71989  **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
 71990  **
 71991  **  * The expression is a bound variable, and this is a reprepare, or
 71992  **
 71993  **  * The sqlite3ValueFromExpr() function is able to extract a value 
 71994  **    from the expression (i.e. the expression is a literal value).
 71995  **
 71996  ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
 71997  ** vector components that match either of the two latter criteria listed
 71998  ** above.
 71999  **
 72000  ** Before any value is appended to the record, the affinity of the 
 72001  ** corresponding column within index pIdx is applied to it. Before
 72002  ** this function returns, output parameter *pnExtract is set to the
 72003  ** number of values appended to the record.
 72004  **
 72005  ** When this function is called, *ppRec must either point to an object
 72006  ** allocated by an earlier call to this function, or must be NULL. If it
 72007  ** is NULL and a value can be successfully extracted, a new UnpackedRecord
 72008  ** is allocated (and *ppRec set to point to it) before returning.
 72009  **
 72010  ** Unless an error is encountered, SQLITE_OK is returned. It is not an
 72011  ** error if a value cannot be extracted from pExpr. If an error does
 72012  ** occur, an SQLite error code is returned.
 72013  */
 72014  SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
 72015    Parse *pParse,                  /* Parse context */
 72016    Index *pIdx,                    /* Index being probed */
 72017    UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
 72018    Expr *pExpr,                    /* The expression to extract a value from */
 72019    int nElem,                      /* Maximum number of values to append */
 72020    int iVal,                       /* Array element to populate */
 72021    int *pnExtract                  /* OUT: Values appended to the record */
 72022  ){
 72023    int rc = SQLITE_OK;
 72024    int nExtract = 0;
 72025  
 72026    if( pExpr==0 || pExpr->op!=TK_SELECT ){
 72027      int i;
 72028      struct ValueNewStat4Ctx alloc;
 72029  
 72030      alloc.pParse = pParse;
 72031      alloc.pIdx = pIdx;
 72032      alloc.ppRec = ppRec;
 72033  
 72034      for(i=0; i<nElem; i++){
 72035        sqlite3_value *pVal = 0;
 72036        Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
 72037        u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
 72038        alloc.iVal = iVal+i;
 72039        rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
 72040        if( !pVal ) break;
 72041        nExtract++;
 72042      }
 72043    }
 72044  
 72045    *pnExtract = nExtract;
 72046    return rc;
 72047  }
 72048  
 72049  /*
 72050  ** Attempt to extract a value from expression pExpr using the methods
 72051  ** as described for sqlite3Stat4ProbeSetValue() above. 
 72052  **
 72053  ** If successful, set *ppVal to point to a new value object and return 
 72054  ** SQLITE_OK. If no value can be extracted, but no other error occurs
 72055  ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
 72056  ** does occur, return an SQLite error code. The final value of *ppVal
 72057  ** is undefined in this case.
 72058  */
 72059  SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
 72060    Parse *pParse,                  /* Parse context */
 72061    Expr *pExpr,                    /* The expression to extract a value from */
 72062    u8 affinity,                    /* Affinity to use */
 72063    sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
 72064  ){
 72065    return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
 72066  }
 72067  
 72068  /*
 72069  ** Extract the iCol-th column from the nRec-byte record in pRec.  Write
 72070  ** the column value into *ppVal.  If *ppVal is initially NULL then a new
 72071  ** sqlite3_value object is allocated.
 72072  **
 72073  ** If *ppVal is initially NULL then the caller is responsible for 
 72074  ** ensuring that the value written into *ppVal is eventually freed.
 72075  */
 72076  SQLITE_PRIVATE int sqlite3Stat4Column(
 72077    sqlite3 *db,                    /* Database handle */
 72078    const void *pRec,               /* Pointer to buffer containing record */
 72079    int nRec,                       /* Size of buffer pRec in bytes */
 72080    int iCol,                       /* Column to extract */
 72081    sqlite3_value **ppVal           /* OUT: Extracted value */
 72082  ){
 72083    u32 t;                          /* a column type code */
 72084    int nHdr;                       /* Size of the header in the record */
 72085    int iHdr;                       /* Next unread header byte */
 72086    int iField;                     /* Next unread data byte */
 72087    int szField;                    /* Size of the current data field */
 72088    int i;                          /* Column index */
 72089    u8 *a = (u8*)pRec;              /* Typecast byte array */
 72090    Mem *pMem = *ppVal;             /* Write result into this Mem object */
 72091  
 72092    assert( iCol>0 );
 72093    iHdr = getVarint32(a, nHdr);
 72094    if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
 72095    iField = nHdr;
 72096    for(i=0; i<=iCol; i++){
 72097      iHdr += getVarint32(&a[iHdr], t);
 72098      testcase( iHdr==nHdr );
 72099      testcase( iHdr==nHdr+1 );
 72100      if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
 72101      szField = sqlite3VdbeSerialTypeLen(t);
 72102      iField += szField;
 72103    }
 72104    testcase( iField==nRec );
 72105    testcase( iField==nRec+1 );
 72106    if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
 72107    if( pMem==0 ){
 72108      pMem = *ppVal = sqlite3ValueNew(db);
 72109      if( pMem==0 ) return SQLITE_NOMEM_BKPT;
 72110    }
 72111    sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
 72112    pMem->enc = ENC(db);
 72113    return SQLITE_OK;
 72114  }
 72115  
 72116  /*
 72117  ** Unless it is NULL, the argument must be an UnpackedRecord object returned
 72118  ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
 72119  ** the object.
 72120  */
 72121  SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
 72122    if( pRec ){
 72123      int i;
 72124      int nCol = pRec->pKeyInfo->nAllField;
 72125      Mem *aMem = pRec->aMem;
 72126      sqlite3 *db = aMem[0].db;
 72127      for(i=0; i<nCol; i++){
 72128        sqlite3VdbeMemRelease(&aMem[i]);
 72129      }
 72130      sqlite3KeyInfoUnref(pRec->pKeyInfo);
 72131      sqlite3DbFreeNN(db, pRec);
 72132    }
 72133  }
 72134  #endif /* ifdef SQLITE_ENABLE_STAT4 */
 72135  
 72136  /*
 72137  ** Change the string value of an sqlite3_value object
 72138  */
 72139  SQLITE_PRIVATE void sqlite3ValueSetStr(
 72140    sqlite3_value *v,     /* Value to be set */
 72141    int n,                /* Length of string z */
 72142    const void *z,        /* Text of the new string */
 72143    u8 enc,               /* Encoding to use */
 72144    void (*xDel)(void*)   /* Destructor for the string */
 72145  ){
 72146    if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
 72147  }
 72148  
 72149  /*
 72150  ** Free an sqlite3_value object
 72151  */
 72152  SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
 72153    if( !v ) return;
 72154    sqlite3VdbeMemRelease((Mem *)v);
 72155    sqlite3DbFreeNN(((Mem*)v)->db, v);
 72156  }
 72157  
 72158  /*
 72159  ** The sqlite3ValueBytes() routine returns the number of bytes in the
 72160  ** sqlite3_value object assuming that it uses the encoding "enc".
 72161  ** The valueBytes() routine is a helper function.
 72162  */
 72163  static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
 72164    return valueToText(pVal, enc)!=0 ? pVal->n : 0;
 72165  }
 72166  SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
 72167    Mem *p = (Mem*)pVal;
 72168    assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
 72169    if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
 72170      return p->n;
 72171    }
 72172    if( (p->flags & MEM_Blob)!=0 ){
 72173      if( p->flags & MEM_Zero ){
 72174        return p->n + p->u.nZero;
 72175      }else{
 72176        return p->n;
 72177      }
 72178    }
 72179    if( p->flags & MEM_Null ) return 0;
 72180    return valueBytes(pVal, enc);
 72181  }
 72182  
 72183  /************** End of vdbemem.c *********************************************/
 72184  /************** Begin file vdbeaux.c *****************************************/
 72185  /*
 72186  ** 2003 September 6
 72187  **
 72188  ** The author disclaims copyright to this source code.  In place of
 72189  ** a legal notice, here is a blessing:
 72190  **
 72191  **    May you do good and not evil.
 72192  **    May you find forgiveness for yourself and forgive others.
 72193  **    May you share freely, never taking more than you give.
 72194  **
 72195  *************************************************************************
 72196  ** This file contains code used for creating, destroying, and populating
 72197  ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) 
 72198  */
 72199  /* #include "sqliteInt.h" */
 72200  /* #include "vdbeInt.h" */
 72201  
 72202  /*
 72203  ** Create a new virtual database engine.
 72204  */
 72205  SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
 72206    sqlite3 *db = pParse->db;
 72207    Vdbe *p;
 72208    p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
 72209    if( p==0 ) return 0;
 72210    memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
 72211    p->db = db;
 72212    if( db->pVdbe ){
 72213      db->pVdbe->pPrev = p;
 72214    }
 72215    p->pNext = db->pVdbe;
 72216    p->pPrev = 0;
 72217    db->pVdbe = p;
 72218    p->magic = VDBE_MAGIC_INIT;
 72219    p->pParse = pParse;
 72220    pParse->pVdbe = p;
 72221    assert( pParse->aLabel==0 );
 72222    assert( pParse->nLabel==0 );
 72223    assert( pParse->nOpAlloc==0 );
 72224    assert( pParse->szOpAlloc==0 );
 72225    sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
 72226    return p;
 72227  }
 72228  
 72229  /*
 72230  ** Change the error string stored in Vdbe.zErrMsg
 72231  */
 72232  SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
 72233    va_list ap;
 72234    sqlite3DbFree(p->db, p->zErrMsg);
 72235    va_start(ap, zFormat);
 72236    p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
 72237    va_end(ap);
 72238  }
 72239  
 72240  /*
 72241  ** Remember the SQL string for a prepared statement.
 72242  */
 72243  SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){
 72244    if( p==0 ) return;
 72245    p->prepFlags = prepFlags;
 72246    if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
 72247      p->expmask = 0;
 72248    }
 72249    assert( p->zSql==0 );
 72250    p->zSql = sqlite3DbStrNDup(p->db, z, n);
 72251  }
 72252  
 72253  /*
 72254  ** Swap all content between two VDBE structures.
 72255  */
 72256  SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
 72257    Vdbe tmp, *pTmp;
 72258    char *zTmp;
 72259    assert( pA->db==pB->db );
 72260    tmp = *pA;
 72261    *pA = *pB;
 72262    *pB = tmp;
 72263    pTmp = pA->pNext;
 72264    pA->pNext = pB->pNext;
 72265    pB->pNext = pTmp;
 72266    pTmp = pA->pPrev;
 72267    pA->pPrev = pB->pPrev;
 72268    pB->pPrev = pTmp;
 72269    zTmp = pA->zSql;
 72270    pA->zSql = pB->zSql;
 72271    pB->zSql = zTmp;
 72272    pB->expmask = pA->expmask;
 72273    pB->prepFlags = pA->prepFlags;
 72274    memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
 72275    pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
 72276  }
 72277  
 72278  /*
 72279  ** Resize the Vdbe.aOp array so that it is at least nOp elements larger 
 72280  ** than its current size. nOp is guaranteed to be less than or equal
 72281  ** to 1024/sizeof(Op).
 72282  **
 72283  ** If an out-of-memory error occurs while resizing the array, return
 72284  ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain 
 72285  ** unchanged (this is so that any opcodes already allocated can be 
 72286  ** correctly deallocated along with the rest of the Vdbe).
 72287  */
 72288  static int growOpArray(Vdbe *v, int nOp){
 72289    VdbeOp *pNew;
 72290    Parse *p = v->pParse;
 72291  
 72292    /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
 72293    ** more frequent reallocs and hence provide more opportunities for 
 72294    ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used
 72295    ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array
 72296    ** by the minimum* amount required until the size reaches 512.  Normal
 72297    ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
 72298    ** size of the op array or add 1KB of space, whichever is smaller. */
 72299  #ifdef SQLITE_TEST_REALLOC_STRESS
 72300    int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
 72301  #else
 72302    int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
 72303    UNUSED_PARAMETER(nOp);
 72304  #endif
 72305  
 72306    /* Ensure that the size of a VDBE does not grow too large */
 72307    if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
 72308      sqlite3OomFault(p->db);
 72309      return SQLITE_NOMEM;
 72310    }
 72311  
 72312    assert( nOp<=(1024/sizeof(Op)) );
 72313    assert( nNew>=(p->nOpAlloc+nOp) );
 72314    pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
 72315    if( pNew ){
 72316      p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
 72317      p->nOpAlloc = p->szOpAlloc/sizeof(Op);
 72318      v->aOp = pNew;
 72319    }
 72320    return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
 72321  }
 72322  
 72323  #ifdef SQLITE_DEBUG
 72324  /* This routine is just a convenient place to set a breakpoint that will
 72325  ** fire after each opcode is inserted and displayed using
 72326  ** "PRAGMA vdbe_addoptrace=on".
 72327  */
 72328  static void test_addop_breakpoint(void){
 72329    static int n = 0;
 72330    n++;
 72331  }
 72332  #endif
 72333  
 72334  /*
 72335  ** Add a new instruction to the list of instructions current in the
 72336  ** VDBE.  Return the address of the new instruction.
 72337  **
 72338  ** Parameters:
 72339  **
 72340  **    p               Pointer to the VDBE
 72341  **
 72342  **    op              The opcode for this instruction
 72343  **
 72344  **    p1, p2, p3      Operands
 72345  **
 72346  ** Use the sqlite3VdbeResolveLabel() function to fix an address and
 72347  ** the sqlite3VdbeChangeP4() function to change the value of the P4
 72348  ** operand.
 72349  */
 72350  static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
 72351    assert( p->pParse->nOpAlloc<=p->nOp );
 72352    if( growOpArray(p, 1) ) return 1;
 72353    assert( p->pParse->nOpAlloc>p->nOp );
 72354    return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
 72355  }
 72356  SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
 72357    int i;
 72358    VdbeOp *pOp;
 72359  
 72360    i = p->nOp;
 72361    assert( p->magic==VDBE_MAGIC_INIT );
 72362    assert( op>=0 && op<0xff );
 72363    if( p->pParse->nOpAlloc<=i ){
 72364      return growOp3(p, op, p1, p2, p3);
 72365    }
 72366    p->nOp++;
 72367    pOp = &p->aOp[i];
 72368    pOp->opcode = (u8)op;
 72369    pOp->p5 = 0;
 72370    pOp->p1 = p1;
 72371    pOp->p2 = p2;
 72372    pOp->p3 = p3;
 72373    pOp->p4.p = 0;
 72374    pOp->p4type = P4_NOTUSED;
 72375  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 72376    pOp->zComment = 0;
 72377  #endif
 72378  #ifdef SQLITE_DEBUG
 72379    if( p->db->flags & SQLITE_VdbeAddopTrace ){
 72380      int jj, kk;
 72381      Parse *pParse = p->pParse;
 72382      for(jj=kk=0; jj<pParse->nColCache; jj++){
 72383        struct yColCache *x = pParse->aColCache + jj;
 72384        printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
 72385        kk++;
 72386      }
 72387      if( kk ) printf("\n");
 72388      sqlite3VdbePrintOp(0, i, &p->aOp[i]);
 72389      test_addop_breakpoint();
 72390    }
 72391  #endif
 72392  #ifdef VDBE_PROFILE
 72393    pOp->cycles = 0;
 72394    pOp->cnt = 0;
 72395  #endif
 72396  #ifdef SQLITE_VDBE_COVERAGE
 72397    pOp->iSrcLine = 0;
 72398  #endif
 72399    return i;
 72400  }
 72401  SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
 72402    return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
 72403  }
 72404  SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
 72405    return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
 72406  }
 72407  SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
 72408    return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
 72409  }
 72410  
 72411  /* Generate code for an unconditional jump to instruction iDest
 72412  */
 72413  SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
 72414    return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
 72415  }
 72416  
 72417  /* Generate code to cause the string zStr to be loaded into
 72418  ** register iDest
 72419  */
 72420  SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
 72421    return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
 72422  }
 72423  
 72424  /*
 72425  ** Generate code that initializes multiple registers to string or integer
 72426  ** constants.  The registers begin with iDest and increase consecutively.
 72427  ** One register is initialized for each characgter in zTypes[].  For each
 72428  ** "s" character in zTypes[], the register is a string if the argument is
 72429  ** not NULL, or OP_Null if the value is a null pointer.  For each "i" character
 72430  ** in zTypes[], the register is initialized to an integer.
 72431  **
 72432  ** If the input string does not end with "X" then an OP_ResultRow instruction
 72433  ** is generated for the values inserted.
 72434  */
 72435  SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
 72436    va_list ap;
 72437    int i;
 72438    char c;
 72439    va_start(ap, zTypes);
 72440    for(i=0; (c = zTypes[i])!=0; i++){
 72441      if( c=='s' ){
 72442        const char *z = va_arg(ap, const char*);
 72443        sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
 72444      }else if( c=='i' ){
 72445        sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
 72446      }else{
 72447        goto skip_op_resultrow;
 72448      }
 72449    }
 72450    sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
 72451  skip_op_resultrow:
 72452    va_end(ap);
 72453  }
 72454  
 72455  /*
 72456  ** Add an opcode that includes the p4 value as a pointer.
 72457  */
 72458  SQLITE_PRIVATE int sqlite3VdbeAddOp4(
 72459    Vdbe *p,            /* Add the opcode to this VM */
 72460    int op,             /* The new opcode */
 72461    int p1,             /* The P1 operand */
 72462    int p2,             /* The P2 operand */
 72463    int p3,             /* The P3 operand */
 72464    const char *zP4,    /* The P4 operand */
 72465    int p4type          /* P4 operand type */
 72466  ){
 72467    int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
 72468    sqlite3VdbeChangeP4(p, addr, zP4, p4type);
 72469    return addr;
 72470  }
 72471  
 72472  /*
 72473  ** Add an opcode that includes the p4 value with a P4_INT64 or
 72474  ** P4_REAL type.
 72475  */
 72476  SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
 72477    Vdbe *p,            /* Add the opcode to this VM */
 72478    int op,             /* The new opcode */
 72479    int p1,             /* The P1 operand */
 72480    int p2,             /* The P2 operand */
 72481    int p3,             /* The P3 operand */
 72482    const u8 *zP4,      /* The P4 operand */
 72483    int p4type          /* P4 operand type */
 72484  ){
 72485    char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
 72486    if( p4copy ) memcpy(p4copy, zP4, 8);
 72487    return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
 72488  }
 72489  
 72490  /*
 72491  ** Add an OP_ParseSchema opcode.  This routine is broken out from
 72492  ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
 72493  ** as having been used.
 72494  **
 72495  ** The zWhere string must have been obtained from sqlite3_malloc().
 72496  ** This routine will take ownership of the allocated memory.
 72497  */
 72498  SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
 72499    int j;
 72500    sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
 72501    for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
 72502  }
 72503  
 72504  /*
 72505  ** Add an opcode that includes the p4 value as an integer.
 72506  */
 72507  SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
 72508    Vdbe *p,            /* Add the opcode to this VM */
 72509    int op,             /* The new opcode */
 72510    int p1,             /* The P1 operand */
 72511    int p2,             /* The P2 operand */
 72512    int p3,             /* The P3 operand */
 72513    int p4              /* The P4 operand as an integer */
 72514  ){
 72515    int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
 72516    if( p->db->mallocFailed==0 ){
 72517      VdbeOp *pOp = &p->aOp[addr];
 72518      pOp->p4type = P4_INT32;
 72519      pOp->p4.i = p4;
 72520    }
 72521    return addr;
 72522  }
 72523  
 72524  /* Insert the end of a co-routine
 72525  */
 72526  SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
 72527    sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
 72528  
 72529    /* Clear the temporary register cache, thereby ensuring that each
 72530    ** co-routine has its own independent set of registers, because co-routines
 72531    ** might expect their registers to be preserved across an OP_Yield, and
 72532    ** that could cause problems if two or more co-routines are using the same
 72533    ** temporary register.
 72534    */
 72535    v->pParse->nTempReg = 0;
 72536    v->pParse->nRangeReg = 0;
 72537  }
 72538  
 72539  /*
 72540  ** Create a new symbolic label for an instruction that has yet to be
 72541  ** coded.  The symbolic label is really just a negative number.  The
 72542  ** label can be used as the P2 value of an operation.  Later, when
 72543  ** the label is resolved to a specific address, the VDBE will scan
 72544  ** through its operation list and change all values of P2 which match
 72545  ** the label into the resolved address.
 72546  **
 72547  ** The VDBE knows that a P2 value is a label because labels are
 72548  ** always negative and P2 values are suppose to be non-negative.
 72549  ** Hence, a negative P2 value is a label that has yet to be resolved.
 72550  **
 72551  ** Zero is returned if a malloc() fails.
 72552  */
 72553  SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
 72554    Parse *p = v->pParse;
 72555    int i = p->nLabel++;
 72556    assert( v->magic==VDBE_MAGIC_INIT );
 72557    if( (i & (i-1))==0 ){
 72558      p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel, 
 72559                                         (i*2+1)*sizeof(p->aLabel[0]));
 72560    }
 72561    if( p->aLabel ){
 72562      p->aLabel[i] = -1;
 72563    }
 72564    return ADDR(i);
 72565  }
 72566  
 72567  /*
 72568  ** Resolve label "x" to be the address of the next instruction to
 72569  ** be inserted.  The parameter "x" must have been obtained from
 72570  ** a prior call to sqlite3VdbeMakeLabel().
 72571  */
 72572  SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
 72573    Parse *p = v->pParse;
 72574    int j = ADDR(x);
 72575    assert( v->magic==VDBE_MAGIC_INIT );
 72576    assert( j<p->nLabel );
 72577    assert( j>=0 );
 72578    if( p->aLabel ){
 72579      p->aLabel[j] = v->nOp;
 72580    }
 72581  }
 72582  
 72583  /*
 72584  ** Mark the VDBE as one that can only be run one time.
 72585  */
 72586  SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
 72587    p->runOnlyOnce = 1;
 72588  }
 72589  
 72590  /*
 72591  ** Mark the VDBE as one that can only be run multiple times.
 72592  */
 72593  SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
 72594    p->runOnlyOnce = 0;
 72595  }
 72596  
 72597  #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
 72598  
 72599  /*
 72600  ** The following type and function are used to iterate through all opcodes
 72601  ** in a Vdbe main program and each of the sub-programs (triggers) it may 
 72602  ** invoke directly or indirectly. It should be used as follows:
 72603  **
 72604  **   Op *pOp;
 72605  **   VdbeOpIter sIter;
 72606  **
 72607  **   memset(&sIter, 0, sizeof(sIter));
 72608  **   sIter.v = v;                            // v is of type Vdbe* 
 72609  **   while( (pOp = opIterNext(&sIter)) ){
 72610  **     // Do something with pOp
 72611  **   }
 72612  **   sqlite3DbFree(v->db, sIter.apSub);
 72613  ** 
 72614  */
 72615  typedef struct VdbeOpIter VdbeOpIter;
 72616  struct VdbeOpIter {
 72617    Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
 72618    SubProgram **apSub;        /* Array of subprograms */
 72619    int nSub;                  /* Number of entries in apSub */
 72620    int iAddr;                 /* Address of next instruction to return */
 72621    int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
 72622  };
 72623  static Op *opIterNext(VdbeOpIter *p){
 72624    Vdbe *v = p->v;
 72625    Op *pRet = 0;
 72626    Op *aOp;
 72627    int nOp;
 72628  
 72629    if( p->iSub<=p->nSub ){
 72630  
 72631      if( p->iSub==0 ){
 72632        aOp = v->aOp;
 72633        nOp = v->nOp;
 72634      }else{
 72635        aOp = p->apSub[p->iSub-1]->aOp;
 72636        nOp = p->apSub[p->iSub-1]->nOp;
 72637      }
 72638      assert( p->iAddr<nOp );
 72639  
 72640      pRet = &aOp[p->iAddr];
 72641      p->iAddr++;
 72642      if( p->iAddr==nOp ){
 72643        p->iSub++;
 72644        p->iAddr = 0;
 72645      }
 72646    
 72647      if( pRet->p4type==P4_SUBPROGRAM ){
 72648        int nByte = (p->nSub+1)*sizeof(SubProgram*);
 72649        int j;
 72650        for(j=0; j<p->nSub; j++){
 72651          if( p->apSub[j]==pRet->p4.pProgram ) break;
 72652        }
 72653        if( j==p->nSub ){
 72654          p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
 72655          if( !p->apSub ){
 72656            pRet = 0;
 72657          }else{
 72658            p->apSub[p->nSub++] = pRet->p4.pProgram;
 72659          }
 72660        }
 72661      }
 72662    }
 72663  
 72664    return pRet;
 72665  }
 72666  
 72667  /*
 72668  ** Check if the program stored in the VM associated with pParse may
 72669  ** throw an ABORT exception (causing the statement, but not entire transaction
 72670  ** to be rolled back). This condition is true if the main program or any
 72671  ** sub-programs contains any of the following:
 72672  **
 72673  **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
 72674  **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
 72675  **   *  OP_Destroy
 72676  **   *  OP_VUpdate
 72677  **   *  OP_VRename
 72678  **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
 72679  **   *  OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine 
 72680  **      (for CREATE TABLE AS SELECT ...)
 72681  **
 72682  ** Then check that the value of Parse.mayAbort is true if an
 72683  ** ABORT may be thrown, or false otherwise. Return true if it does
 72684  ** match, or false otherwise. This function is intended to be used as
 72685  ** part of an assert statement in the compiler. Similar to:
 72686  **
 72687  **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
 72688  */
 72689  SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
 72690    int hasAbort = 0;
 72691    int hasFkCounter = 0;
 72692    int hasCreateTable = 0;
 72693    int hasInitCoroutine = 0;
 72694    Op *pOp;
 72695    VdbeOpIter sIter;
 72696    memset(&sIter, 0, sizeof(sIter));
 72697    sIter.v = v;
 72698  
 72699    while( (pOp = opIterNext(&sIter))!=0 ){
 72700      int opcode = pOp->opcode;
 72701      if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
 72702       || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
 72703        && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
 72704      ){
 72705        hasAbort = 1;
 72706        break;
 72707      }
 72708      if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
 72709      if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
 72710  #ifndef SQLITE_OMIT_FOREIGN_KEY
 72711      if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
 72712        hasFkCounter = 1;
 72713      }
 72714  #endif
 72715    }
 72716    sqlite3DbFree(v->db, sIter.apSub);
 72717  
 72718    /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
 72719    ** If malloc failed, then the while() loop above may not have iterated
 72720    ** through all opcodes and hasAbort may be set incorrectly. Return
 72721    ** true for this case to prevent the assert() in the callers frame
 72722    ** from failing.  */
 72723    return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
 72724                || (hasCreateTable && hasInitCoroutine) );
 72725  }
 72726  #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
 72727  
 72728  /*
 72729  ** This routine is called after all opcodes have been inserted.  It loops
 72730  ** through all the opcodes and fixes up some details.
 72731  **
 72732  ** (1) For each jump instruction with a negative P2 value (a label)
 72733  **     resolve the P2 value to an actual address.
 72734  **
 72735  ** (2) Compute the maximum number of arguments used by any SQL function
 72736  **     and store that value in *pMaxFuncArgs.
 72737  **
 72738  ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
 72739  **     indicate what the prepared statement actually does.
 72740  **
 72741  ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
 72742  **
 72743  ** (5) Reclaim the memory allocated for storing labels.
 72744  **
 72745  ** This routine will only function correctly if the mkopcodeh.tcl generator
 72746  ** script numbers the opcodes correctly.  Changes to this routine must be
 72747  ** coordinated with changes to mkopcodeh.tcl.
 72748  */
 72749  static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
 72750    int nMaxArgs = *pMaxFuncArgs;
 72751    Op *pOp;
 72752    Parse *pParse = p->pParse;
 72753    int *aLabel = pParse->aLabel;
 72754    p->readOnly = 1;
 72755    p->bIsReader = 0;
 72756    pOp = &p->aOp[p->nOp-1];
 72757    while(1){
 72758  
 72759      /* Only JUMP opcodes and the short list of special opcodes in the switch
 72760      ** below need to be considered.  The mkopcodeh.tcl generator script groups
 72761      ** all these opcodes together near the front of the opcode list.  Skip
 72762      ** any opcode that does not need processing by virtual of the fact that
 72763      ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
 72764      */
 72765      if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
 72766        /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
 72767        ** cases from this switch! */
 72768        switch( pOp->opcode ){
 72769          case OP_Transaction: {
 72770            if( pOp->p2!=0 ) p->readOnly = 0;
 72771            /* fall thru */
 72772          }
 72773          case OP_AutoCommit:
 72774          case OP_Savepoint: {
 72775            p->bIsReader = 1;
 72776            break;
 72777          }
 72778  #ifndef SQLITE_OMIT_WAL
 72779          case OP_Checkpoint:
 72780  #endif
 72781          case OP_Vacuum:
 72782          case OP_JournalMode: {
 72783            p->readOnly = 0;
 72784            p->bIsReader = 1;
 72785            break;
 72786          }
 72787          case OP_Next:
 72788          case OP_NextIfOpen:
 72789          case OP_SorterNext: {
 72790            pOp->p4.xAdvance = sqlite3BtreeNext;
 72791            pOp->p4type = P4_ADVANCE;
 72792            /* The code generator never codes any of these opcodes as a jump
 72793            ** to a label.  They are always coded as a jump backwards to a 
 72794            ** known address */
 72795            assert( pOp->p2>=0 );
 72796            break;
 72797          }
 72798          case OP_Prev:
 72799          case OP_PrevIfOpen: {
 72800            pOp->p4.xAdvance = sqlite3BtreePrevious;
 72801            pOp->p4type = P4_ADVANCE;
 72802            /* The code generator never codes any of these opcodes as a jump
 72803            ** to a label.  They are always coded as a jump backwards to a 
 72804            ** known address */
 72805            assert( pOp->p2>=0 );
 72806            break;
 72807          }
 72808  #ifndef SQLITE_OMIT_VIRTUALTABLE
 72809          case OP_VUpdate: {
 72810            if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
 72811            break;
 72812          }
 72813          case OP_VFilter: {
 72814            int n;
 72815            assert( (pOp - p->aOp) >= 3 );
 72816            assert( pOp[-1].opcode==OP_Integer );
 72817            n = pOp[-1].p1;
 72818            if( n>nMaxArgs ) nMaxArgs = n;
 72819            /* Fall through into the default case */
 72820          }
 72821  #endif
 72822          default: {
 72823            if( pOp->p2<0 ){
 72824              /* The mkopcodeh.tcl script has so arranged things that the only
 72825              ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
 72826              ** have non-negative values for P2. */
 72827              assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
 72828              assert( ADDR(pOp->p2)<pParse->nLabel );
 72829              pOp->p2 = aLabel[ADDR(pOp->p2)];
 72830            }
 72831            break;
 72832          }
 72833        }
 72834        /* The mkopcodeh.tcl script has so arranged things that the only
 72835        ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
 72836        ** have non-negative values for P2. */
 72837        assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);
 72838      }
 72839      if( pOp==p->aOp ) break;
 72840      pOp--;
 72841    }
 72842    sqlite3DbFree(p->db, pParse->aLabel);
 72843    pParse->aLabel = 0;
 72844    pParse->nLabel = 0;
 72845    *pMaxFuncArgs = nMaxArgs;
 72846    assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
 72847  }
 72848  
 72849  /*
 72850  ** Return the address of the next instruction to be inserted.
 72851  */
 72852  SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
 72853    assert( p->magic==VDBE_MAGIC_INIT );
 72854    return p->nOp;
 72855  }
 72856  
 72857  /*
 72858  ** Verify that at least N opcode slots are available in p without
 72859  ** having to malloc for more space (except when compiled using
 72860  ** SQLITE_TEST_REALLOC_STRESS).  This interface is used during testing
 72861  ** to verify that certain calls to sqlite3VdbeAddOpList() can never
 72862  ** fail due to a OOM fault and hence that the return value from
 72863  ** sqlite3VdbeAddOpList() will always be non-NULL.
 72864  */
 72865  #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
 72866  SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
 72867    assert( p->nOp + N <= p->pParse->nOpAlloc );
 72868  }
 72869  #endif
 72870  
 72871  /*
 72872  ** Verify that the VM passed as the only argument does not contain
 72873  ** an OP_ResultRow opcode. Fail an assert() if it does. This is used
 72874  ** by code in pragma.c to ensure that the implementation of certain
 72875  ** pragmas comports with the flags specified in the mkpragmatab.tcl
 72876  ** script.
 72877  */
 72878  #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
 72879  SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
 72880    int i;
 72881    for(i=0; i<p->nOp; i++){
 72882      assert( p->aOp[i].opcode!=OP_ResultRow );
 72883    }
 72884  }
 72885  #endif
 72886  
 72887  /*
 72888  ** This function returns a pointer to the array of opcodes associated with
 72889  ** the Vdbe passed as the first argument. It is the callers responsibility
 72890  ** to arrange for the returned array to be eventually freed using the 
 72891  ** vdbeFreeOpArray() function.
 72892  **
 72893  ** Before returning, *pnOp is set to the number of entries in the returned
 72894  ** array. Also, *pnMaxArg is set to the larger of its current value and 
 72895  ** the number of entries in the Vdbe.apArg[] array required to execute the 
 72896  ** returned program.
 72897  */
 72898  SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
 72899    VdbeOp *aOp = p->aOp;
 72900    assert( aOp && !p->db->mallocFailed );
 72901  
 72902    /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
 72903    assert( DbMaskAllZero(p->btreeMask) );
 72904  
 72905    resolveP2Values(p, pnMaxArg);
 72906    *pnOp = p->nOp;
 72907    p->aOp = 0;
 72908    return aOp;
 72909  }
 72910  
 72911  /*
 72912  ** Add a whole list of operations to the operation stack.  Return a
 72913  ** pointer to the first operation inserted.
 72914  **
 72915  ** Non-zero P2 arguments to jump instructions are automatically adjusted
 72916  ** so that the jump target is relative to the first operation inserted.
 72917  */
 72918  SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
 72919    Vdbe *p,                     /* Add opcodes to the prepared statement */
 72920    int nOp,                     /* Number of opcodes to add */
 72921    VdbeOpList const *aOp,       /* The opcodes to be added */
 72922    int iLineno                  /* Source-file line number of first opcode */
 72923  ){
 72924    int i;
 72925    VdbeOp *pOut, *pFirst;
 72926    assert( nOp>0 );
 72927    assert( p->magic==VDBE_MAGIC_INIT );
 72928    if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
 72929      return 0;
 72930    }
 72931    pFirst = pOut = &p->aOp[p->nOp];
 72932    for(i=0; i<nOp; i++, aOp++, pOut++){
 72933      pOut->opcode = aOp->opcode;
 72934      pOut->p1 = aOp->p1;
 72935      pOut->p2 = aOp->p2;
 72936      assert( aOp->p2>=0 );
 72937      if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
 72938        pOut->p2 += p->nOp;
 72939      }
 72940      pOut->p3 = aOp->p3;
 72941      pOut->p4type = P4_NOTUSED;
 72942      pOut->p4.p = 0;
 72943      pOut->p5 = 0;
 72944  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 72945      pOut->zComment = 0;
 72946  #endif
 72947  #ifdef SQLITE_VDBE_COVERAGE
 72948      pOut->iSrcLine = iLineno+i;
 72949  #else
 72950      (void)iLineno;
 72951  #endif
 72952  #ifdef SQLITE_DEBUG
 72953      if( p->db->flags & SQLITE_VdbeAddopTrace ){
 72954        sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
 72955      }
 72956  #endif
 72957    }
 72958    p->nOp += nOp;
 72959    return pFirst;
 72960  }
 72961  
 72962  #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
 72963  /*
 72964  ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
 72965  */
 72966  SQLITE_PRIVATE void sqlite3VdbeScanStatus(
 72967    Vdbe *p,                        /* VM to add scanstatus() to */
 72968    int addrExplain,                /* Address of OP_Explain (or 0) */
 72969    int addrLoop,                   /* Address of loop counter */ 
 72970    int addrVisit,                  /* Address of rows visited counter */
 72971    LogEst nEst,                    /* Estimated number of output rows */
 72972    const char *zName               /* Name of table or index being scanned */
 72973  ){
 72974    int nByte = (p->nScan+1) * sizeof(ScanStatus);
 72975    ScanStatus *aNew;
 72976    aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
 72977    if( aNew ){
 72978      ScanStatus *pNew = &aNew[p->nScan++];
 72979      pNew->addrExplain = addrExplain;
 72980      pNew->addrLoop = addrLoop;
 72981      pNew->addrVisit = addrVisit;
 72982      pNew->nEst = nEst;
 72983      pNew->zName = sqlite3DbStrDup(p->db, zName);
 72984      p->aScan = aNew;
 72985    }
 72986  }
 72987  #endif
 72988  
 72989  
 72990  /*
 72991  ** Change the value of the opcode, or P1, P2, P3, or P5 operands
 72992  ** for a specific instruction.
 72993  */
 72994  SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
 72995    sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
 72996  }
 72997  SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
 72998    sqlite3VdbeGetOp(p,addr)->p1 = val;
 72999  }
 73000  SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
 73001    sqlite3VdbeGetOp(p,addr)->p2 = val;
 73002  }
 73003  SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
 73004    sqlite3VdbeGetOp(p,addr)->p3 = val;
 73005  }
 73006  SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
 73007    assert( p->nOp>0 || p->db->mallocFailed );
 73008    if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
 73009  }
 73010  
 73011  /*
 73012  ** Change the P2 operand of instruction addr so that it points to
 73013  ** the address of the next instruction to be coded.
 73014  */
 73015  SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
 73016    sqlite3VdbeChangeP2(p, addr, p->nOp);
 73017  }
 73018  
 73019  
 73020  /*
 73021  ** If the input FuncDef structure is ephemeral, then free it.  If
 73022  ** the FuncDef is not ephermal, then do nothing.
 73023  */
 73024  static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
 73025    if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
 73026      sqlite3DbFreeNN(db, pDef);
 73027    }
 73028  }
 73029  
 73030  static void vdbeFreeOpArray(sqlite3 *, Op *, int);
 73031  
 73032  /*
 73033  ** Delete a P4 value if necessary.
 73034  */
 73035  static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
 73036    if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
 73037    sqlite3DbFreeNN(db, p);
 73038  }
 73039  static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
 73040    freeEphemeralFunction(db, p->pFunc);
 73041   sqlite3DbFreeNN(db, p);
 73042  }
 73043  static void freeP4(sqlite3 *db, int p4type, void *p4){
 73044    assert( db );
 73045    switch( p4type ){
 73046      case P4_FUNCCTX: {
 73047        freeP4FuncCtx(db, (sqlite3_context*)p4);
 73048        break;
 73049      }
 73050      case P4_REAL:
 73051      case P4_INT64:
 73052      case P4_DYNAMIC:
 73053      case P4_INTARRAY: {
 73054        sqlite3DbFree(db, p4);
 73055        break;
 73056      }
 73057      case P4_KEYINFO: {
 73058        if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
 73059        break;
 73060      }
 73061  #ifdef SQLITE_ENABLE_CURSOR_HINTS
 73062      case P4_EXPR: {
 73063        sqlite3ExprDelete(db, (Expr*)p4);
 73064        break;
 73065      }
 73066  #endif
 73067      case P4_FUNCDEF: {
 73068        freeEphemeralFunction(db, (FuncDef*)p4);
 73069        break;
 73070      }
 73071      case P4_MEM: {
 73072        if( db->pnBytesFreed==0 ){
 73073          sqlite3ValueFree((sqlite3_value*)p4);
 73074        }else{
 73075          freeP4Mem(db, (Mem*)p4);
 73076        }
 73077        break;
 73078      }
 73079      case P4_VTAB : {
 73080        if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
 73081        break;
 73082      }
 73083    }
 73084  }
 73085  
 73086  /*
 73087  ** Free the space allocated for aOp and any p4 values allocated for the
 73088  ** opcodes contained within. If aOp is not NULL it is assumed to contain 
 73089  ** nOp entries. 
 73090  */
 73091  static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
 73092    if( aOp ){
 73093      Op *pOp;
 73094      for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){
 73095        if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
 73096  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 73097        sqlite3DbFree(db, pOp->zComment);
 73098  #endif     
 73099      }
 73100      sqlite3DbFreeNN(db, aOp);
 73101    }
 73102  }
 73103  
 73104  /*
 73105  ** Link the SubProgram object passed as the second argument into the linked
 73106  ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
 73107  ** objects when the VM is no longer required.
 73108  */
 73109  SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
 73110    p->pNext = pVdbe->pProgram;
 73111    pVdbe->pProgram = p;
 73112  }
 73113  
 73114  /*
 73115  ** Change the opcode at addr into OP_Noop
 73116  */
 73117  SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
 73118    VdbeOp *pOp;
 73119    if( p->db->mallocFailed ) return 0;
 73120    assert( addr>=0 && addr<p->nOp );
 73121    pOp = &p->aOp[addr];
 73122    freeP4(p->db, pOp->p4type, pOp->p4.p);
 73123    pOp->p4type = P4_NOTUSED;
 73124    pOp->p4.z = 0;
 73125    pOp->opcode = OP_Noop;
 73126    return 1;
 73127  }
 73128  
 73129  /*
 73130  ** If the last opcode is "op" and it is not a jump destination,
 73131  ** then remove it.  Return true if and only if an opcode was removed.
 73132  */
 73133  SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
 73134    if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
 73135      return sqlite3VdbeChangeToNoop(p, p->nOp-1);
 73136    }else{
 73137      return 0;
 73138    }
 73139  }
 73140  
 73141  /*
 73142  ** Change the value of the P4 operand for a specific instruction.
 73143  ** This routine is useful when a large program is loaded from a
 73144  ** static array using sqlite3VdbeAddOpList but we want to make a
 73145  ** few minor changes to the program.
 73146  **
 73147  ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
 73148  ** the string is made into memory obtained from sqlite3_malloc().
 73149  ** A value of n==0 means copy bytes of zP4 up to and including the
 73150  ** first null byte.  If n>0 then copy n+1 bytes of zP4.
 73151  ** 
 73152  ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
 73153  ** to a string or structure that is guaranteed to exist for the lifetime of
 73154  ** the Vdbe. In these cases we can just copy the pointer.
 73155  **
 73156  ** If addr<0 then change P4 on the most recently inserted instruction.
 73157  */
 73158  static void SQLITE_NOINLINE vdbeChangeP4Full(
 73159    Vdbe *p,
 73160    Op *pOp,
 73161    const char *zP4,
 73162    int n
 73163  ){
 73164    if( pOp->p4type ){
 73165      freeP4(p->db, pOp->p4type, pOp->p4.p);
 73166      pOp->p4type = 0;
 73167      pOp->p4.p = 0;
 73168    }
 73169    if( n<0 ){
 73170      sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
 73171    }else{
 73172      if( n==0 ) n = sqlite3Strlen30(zP4);
 73173      pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
 73174      pOp->p4type = P4_DYNAMIC;
 73175    }
 73176  }
 73177  SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
 73178    Op *pOp;
 73179    sqlite3 *db;
 73180    assert( p!=0 );
 73181    db = p->db;
 73182    assert( p->magic==VDBE_MAGIC_INIT );
 73183    assert( p->aOp!=0 || db->mallocFailed );
 73184    if( db->mallocFailed ){
 73185      if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
 73186      return;
 73187    }
 73188    assert( p->nOp>0 );
 73189    assert( addr<p->nOp );
 73190    if( addr<0 ){
 73191      addr = p->nOp - 1;
 73192    }
 73193    pOp = &p->aOp[addr];
 73194    if( n>=0 || pOp->p4type ){
 73195      vdbeChangeP4Full(p, pOp, zP4, n);
 73196      return;
 73197    }
 73198    if( n==P4_INT32 ){
 73199      /* Note: this cast is safe, because the origin data point was an int
 73200      ** that was cast to a (const char *). */
 73201      pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
 73202      pOp->p4type = P4_INT32;
 73203    }else if( zP4!=0 ){
 73204      assert( n<0 );
 73205      pOp->p4.p = (void*)zP4;
 73206      pOp->p4type = (signed char)n;
 73207      if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
 73208    }
 73209  }
 73210  
 73211  /*
 73212  ** Change the P4 operand of the most recently coded instruction 
 73213  ** to the value defined by the arguments.  This is a high-speed
 73214  ** version of sqlite3VdbeChangeP4().
 73215  **
 73216  ** The P4 operand must not have been previously defined.  And the new
 73217  ** P4 must not be P4_INT32.  Use sqlite3VdbeChangeP4() in either of
 73218  ** those cases.
 73219  */
 73220  SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
 73221    VdbeOp *pOp;
 73222    assert( n!=P4_INT32 && n!=P4_VTAB );
 73223    assert( n<=0 );
 73224    if( p->db->mallocFailed ){
 73225      freeP4(p->db, n, pP4);
 73226    }else{
 73227      assert( pP4!=0 );
 73228      assert( p->nOp>0 );
 73229      pOp = &p->aOp[p->nOp-1];
 73230      assert( pOp->p4type==P4_NOTUSED );
 73231      pOp->p4type = n;
 73232      pOp->p4.p = pP4;
 73233    }
 73234  }
 73235  
 73236  /*
 73237  ** Set the P4 on the most recently added opcode to the KeyInfo for the
 73238  ** index given.
 73239  */
 73240  SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
 73241    Vdbe *v = pParse->pVdbe;
 73242    KeyInfo *pKeyInfo;
 73243    assert( v!=0 );
 73244    assert( pIdx!=0 );
 73245    pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
 73246    if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
 73247  }
 73248  
 73249  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 73250  /*
 73251  ** Change the comment on the most recently coded instruction.  Or
 73252  ** insert a No-op and add the comment to that new instruction.  This
 73253  ** makes the code easier to read during debugging.  None of this happens
 73254  ** in a production build.
 73255  */
 73256  static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
 73257    assert( p->nOp>0 || p->aOp==0 );
 73258    assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
 73259    if( p->nOp ){
 73260      assert( p->aOp );
 73261      sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
 73262      p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
 73263    }
 73264  }
 73265  SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
 73266    va_list ap;
 73267    if( p ){
 73268      va_start(ap, zFormat);
 73269      vdbeVComment(p, zFormat, ap);
 73270      va_end(ap);
 73271    }
 73272  }
 73273  SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
 73274    va_list ap;
 73275    if( p ){
 73276      sqlite3VdbeAddOp0(p, OP_Noop);
 73277      va_start(ap, zFormat);
 73278      vdbeVComment(p, zFormat, ap);
 73279      va_end(ap);
 73280    }
 73281  }
 73282  #endif  /* NDEBUG */
 73283  
 73284  #ifdef SQLITE_VDBE_COVERAGE
 73285  /*
 73286  ** Set the value if the iSrcLine field for the previously coded instruction.
 73287  */
 73288  SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
 73289    sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
 73290  }
 73291  #endif /* SQLITE_VDBE_COVERAGE */
 73292  
 73293  /*
 73294  ** Return the opcode for a given address.  If the address is -1, then
 73295  ** return the most recently inserted opcode.
 73296  **
 73297  ** If a memory allocation error has occurred prior to the calling of this
 73298  ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
 73299  ** is readable but not writable, though it is cast to a writable value.
 73300  ** The return of a dummy opcode allows the call to continue functioning
 73301  ** after an OOM fault without having to check to see if the return from 
 73302  ** this routine is a valid pointer.  But because the dummy.opcode is 0,
 73303  ** dummy will never be written to.  This is verified by code inspection and
 73304  ** by running with Valgrind.
 73305  */
 73306  SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
 73307    /* C89 specifies that the constant "dummy" will be initialized to all
 73308    ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
 73309    static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
 73310    assert( p->magic==VDBE_MAGIC_INIT );
 73311    if( addr<0 ){
 73312      addr = p->nOp - 1;
 73313    }
 73314    assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
 73315    if( p->db->mallocFailed ){
 73316      return (VdbeOp*)&dummy;
 73317    }else{
 73318      return &p->aOp[addr];
 73319    }
 73320  }
 73321  
 73322  #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
 73323  /*
 73324  ** Return an integer value for one of the parameters to the opcode pOp
 73325  ** determined by character c.
 73326  */
 73327  static int translateP(char c, const Op *pOp){
 73328    if( c=='1' ) return pOp->p1;
 73329    if( c=='2' ) return pOp->p2;
 73330    if( c=='3' ) return pOp->p3;
 73331    if( c=='4' ) return pOp->p4.i;
 73332    return pOp->p5;
 73333  }
 73334  
 73335  /*
 73336  ** Compute a string for the "comment" field of a VDBE opcode listing.
 73337  **
 73338  ** The Synopsis: field in comments in the vdbe.c source file gets converted
 73339  ** to an extra string that is appended to the sqlite3OpcodeName().  In the
 73340  ** absence of other comments, this synopsis becomes the comment on the opcode.
 73341  ** Some translation occurs:
 73342  **
 73343  **       "PX"      ->  "r[X]"
 73344  **       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
 73345  **       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
 73346  **       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
 73347  */
 73348  static int displayComment(
 73349    const Op *pOp,     /* The opcode to be commented */
 73350    const char *zP4,   /* Previously obtained value for P4 */
 73351    char *zTemp,       /* Write result here */
 73352    int nTemp          /* Space available in zTemp[] */
 73353  ){
 73354    const char *zOpName;
 73355    const char *zSynopsis;
 73356    int nOpName;
 73357    int ii, jj;
 73358    char zAlt[50];
 73359    zOpName = sqlite3OpcodeName(pOp->opcode);
 73360    nOpName = sqlite3Strlen30(zOpName);
 73361    if( zOpName[nOpName+1] ){
 73362      int seenCom = 0;
 73363      char c;
 73364      zSynopsis = zOpName += nOpName + 1;
 73365      if( strncmp(zSynopsis,"IF ",3)==0 ){
 73366        if( pOp->p5 & SQLITE_STOREP2 ){
 73367          sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
 73368        }else{
 73369          sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
 73370        }
 73371        zSynopsis = zAlt;
 73372      }
 73373      for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
 73374        if( c=='P' ){
 73375          c = zSynopsis[++ii];
 73376          if( c=='4' ){
 73377            sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
 73378          }else if( c=='X' ){
 73379            sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
 73380            seenCom = 1;
 73381          }else{
 73382            int v1 = translateP(c, pOp);
 73383            int v2;
 73384            sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
 73385            if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
 73386              ii += 3;
 73387              jj += sqlite3Strlen30(zTemp+jj);
 73388              v2 = translateP(zSynopsis[ii], pOp);
 73389              if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
 73390                ii += 2;
 73391                v2++;
 73392              }
 73393              if( v2>1 ){
 73394                sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
 73395              }
 73396            }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
 73397              ii += 4;
 73398            }
 73399          }
 73400          jj += sqlite3Strlen30(zTemp+jj);
 73401        }else{
 73402          zTemp[jj++] = c;
 73403        }
 73404      }
 73405      if( !seenCom && jj<nTemp-5 && pOp->zComment ){
 73406        sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
 73407        jj += sqlite3Strlen30(zTemp+jj);
 73408      }
 73409      if( jj<nTemp ) zTemp[jj] = 0;
 73410    }else if( pOp->zComment ){
 73411      sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
 73412      jj = sqlite3Strlen30(zTemp);
 73413    }else{
 73414      zTemp[0] = 0;
 73415      jj = 0;
 73416    }
 73417    return jj;
 73418  }
 73419  #endif /* SQLITE_DEBUG */
 73420  
 73421  #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
 73422  /*
 73423  ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
 73424  ** that can be displayed in the P4 column of EXPLAIN output.
 73425  */
 73426  static void displayP4Expr(StrAccum *p, Expr *pExpr){
 73427    const char *zOp = 0;
 73428    switch( pExpr->op ){
 73429      case TK_STRING:
 73430        sqlite3XPrintf(p, "%Q", pExpr->u.zToken);
 73431        break;
 73432      case TK_INTEGER:
 73433        sqlite3XPrintf(p, "%d", pExpr->u.iValue);
 73434        break;
 73435      case TK_NULL:
 73436        sqlite3XPrintf(p, "NULL");
 73437        break;
 73438      case TK_REGISTER: {
 73439        sqlite3XPrintf(p, "r[%d]", pExpr->iTable);
 73440        break;
 73441      }
 73442      case TK_COLUMN: {
 73443        if( pExpr->iColumn<0 ){
 73444          sqlite3XPrintf(p, "rowid");
 73445        }else{
 73446          sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn);
 73447        }
 73448        break;
 73449      }
 73450      case TK_LT:      zOp = "LT";      break;
 73451      case TK_LE:      zOp = "LE";      break;
 73452      case TK_GT:      zOp = "GT";      break;
 73453      case TK_GE:      zOp = "GE";      break;
 73454      case TK_NE:      zOp = "NE";      break;
 73455      case TK_EQ:      zOp = "EQ";      break;
 73456      case TK_IS:      zOp = "IS";      break;
 73457      case TK_ISNOT:   zOp = "ISNOT";   break;
 73458      case TK_AND:     zOp = "AND";     break;
 73459      case TK_OR:      zOp = "OR";      break;
 73460      case TK_PLUS:    zOp = "ADD";     break;
 73461      case TK_STAR:    zOp = "MUL";     break;
 73462      case TK_MINUS:   zOp = "SUB";     break;
 73463      case TK_REM:     zOp = "REM";     break;
 73464      case TK_BITAND:  zOp = "BITAND";  break;
 73465      case TK_BITOR:   zOp = "BITOR";   break;
 73466      case TK_SLASH:   zOp = "DIV";     break;
 73467      case TK_LSHIFT:  zOp = "LSHIFT";  break;
 73468      case TK_RSHIFT:  zOp = "RSHIFT";  break;
 73469      case TK_CONCAT:  zOp = "CONCAT";  break;
 73470      case TK_UMINUS:  zOp = "MINUS";   break;
 73471      case TK_UPLUS:   zOp = "PLUS";    break;
 73472      case TK_BITNOT:  zOp = "BITNOT";  break;
 73473      case TK_NOT:     zOp = "NOT";     break;
 73474      case TK_ISNULL:  zOp = "ISNULL";  break;
 73475      case TK_NOTNULL: zOp = "NOTNULL"; break;
 73476  
 73477      default:
 73478        sqlite3XPrintf(p, "%s", "expr");
 73479        break;
 73480    }
 73481  
 73482    if( zOp ){
 73483      sqlite3XPrintf(p, "%s(", zOp);
 73484      displayP4Expr(p, pExpr->pLeft);
 73485      if( pExpr->pRight ){
 73486        sqlite3StrAccumAppend(p, ",", 1);
 73487        displayP4Expr(p, pExpr->pRight);
 73488      }
 73489      sqlite3StrAccumAppend(p, ")", 1);
 73490    }
 73491  }
 73492  #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
 73493  
 73494  
 73495  #if VDBE_DISPLAY_P4
 73496  /*
 73497  ** Compute a string that describes the P4 parameter for an opcode.
 73498  ** Use zTemp for any required temporary buffer space.
 73499  */
 73500  static char *displayP4(Op *pOp, char *zTemp, int nTemp){
 73501    char *zP4 = zTemp;
 73502    StrAccum x;
 73503    assert( nTemp>=20 );
 73504    sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
 73505    switch( pOp->p4type ){
 73506      case P4_KEYINFO: {
 73507        int j;
 73508        KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
 73509        assert( pKeyInfo->aSortOrder!=0 );
 73510        sqlite3XPrintf(&x, "k(%d", pKeyInfo->nKeyField);
 73511        for(j=0; j<pKeyInfo->nKeyField; j++){
 73512          CollSeq *pColl = pKeyInfo->aColl[j];
 73513          const char *zColl = pColl ? pColl->zName : "";
 73514          if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
 73515          sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
 73516        }
 73517        sqlite3StrAccumAppend(&x, ")", 1);
 73518        break;
 73519      }
 73520  #ifdef SQLITE_ENABLE_CURSOR_HINTS
 73521      case P4_EXPR: {
 73522        displayP4Expr(&x, pOp->p4.pExpr);
 73523        break;
 73524      }
 73525  #endif
 73526      case P4_COLLSEQ: {
 73527        CollSeq *pColl = pOp->p4.pColl;
 73528        sqlite3XPrintf(&x, "(%.20s)", pColl->zName);
 73529        break;
 73530      }
 73531      case P4_FUNCDEF: {
 73532        FuncDef *pDef = pOp->p4.pFunc;
 73533        sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
 73534        break;
 73535      }
 73536  #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
 73537      case P4_FUNCCTX: {
 73538        FuncDef *pDef = pOp->p4.pCtx->pFunc;
 73539        sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
 73540        break;
 73541      }
 73542  #endif
 73543      case P4_INT64: {
 73544        sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64);
 73545        break;
 73546      }
 73547      case P4_INT32: {
 73548        sqlite3XPrintf(&x, "%d", pOp->p4.i);
 73549        break;
 73550      }
 73551      case P4_REAL: {
 73552        sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal);
 73553        break;
 73554      }
 73555      case P4_MEM: {
 73556        Mem *pMem = pOp->p4.pMem;
 73557        if( pMem->flags & MEM_Str ){
 73558          zP4 = pMem->z;
 73559        }else if( pMem->flags & MEM_Int ){
 73560          sqlite3XPrintf(&x, "%lld", pMem->u.i);
 73561        }else if( pMem->flags & MEM_Real ){
 73562          sqlite3XPrintf(&x, "%.16g", pMem->u.r);
 73563        }else if( pMem->flags & MEM_Null ){
 73564          zP4 = "NULL";
 73565        }else{
 73566          assert( pMem->flags & MEM_Blob );
 73567          zP4 = "(blob)";
 73568        }
 73569        break;
 73570      }
 73571  #ifndef SQLITE_OMIT_VIRTUALTABLE
 73572      case P4_VTAB: {
 73573        sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
 73574        sqlite3XPrintf(&x, "vtab:%p", pVtab);
 73575        break;
 73576      }
 73577  #endif
 73578      case P4_INTARRAY: {
 73579        int i;
 73580        int *ai = pOp->p4.ai;
 73581        int n = ai[0];   /* The first element of an INTARRAY is always the
 73582                         ** count of the number of elements to follow */
 73583        for(i=1; i<=n; i++){
 73584          sqlite3XPrintf(&x, ",%d", ai[i]);
 73585        }
 73586        zTemp[0] = '[';
 73587        sqlite3StrAccumAppend(&x, "]", 1);
 73588        break;
 73589      }
 73590      case P4_SUBPROGRAM: {
 73591        sqlite3XPrintf(&x, "program");
 73592        break;
 73593      }
 73594      case P4_ADVANCE: {
 73595        zTemp[0] = 0;
 73596        break;
 73597      }
 73598      case P4_TABLE: {
 73599        sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName);
 73600        break;
 73601      }
 73602      default: {
 73603        zP4 = pOp->p4.z;
 73604        if( zP4==0 ){
 73605          zP4 = zTemp;
 73606          zTemp[0] = 0;
 73607        }
 73608      }
 73609    }
 73610    sqlite3StrAccumFinish(&x);
 73611    assert( zP4!=0 );
 73612    return zP4;
 73613  }
 73614  #endif /* VDBE_DISPLAY_P4 */
 73615  
 73616  /*
 73617  ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
 73618  **
 73619  ** The prepared statements need to know in advance the complete set of
 73620  ** attached databases that will be use.  A mask of these databases
 73621  ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
 73622  ** p->btreeMask of databases that will require a lock.
 73623  */
 73624  SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
 73625    assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
 73626    assert( i<(int)sizeof(p->btreeMask)*8 );
 73627    DbMaskSet(p->btreeMask, i);
 73628    if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
 73629      DbMaskSet(p->lockMask, i);
 73630    }
 73631  }
 73632  
 73633  #if !defined(SQLITE_OMIT_SHARED_CACHE)
 73634  /*
 73635  ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
 73636  ** this routine obtains the mutex associated with each BtShared structure
 73637  ** that may be accessed by the VM passed as an argument. In doing so it also
 73638  ** sets the BtShared.db member of each of the BtShared structures, ensuring
 73639  ** that the correct busy-handler callback is invoked if required.
 73640  **
 73641  ** If SQLite is not threadsafe but does support shared-cache mode, then
 73642  ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
 73643  ** of all of BtShared structures accessible via the database handle 
 73644  ** associated with the VM.
 73645  **
 73646  ** If SQLite is not threadsafe and does not support shared-cache mode, this
 73647  ** function is a no-op.
 73648  **
 73649  ** The p->btreeMask field is a bitmask of all btrees that the prepared 
 73650  ** statement p will ever use.  Let N be the number of bits in p->btreeMask
 73651  ** corresponding to btrees that use shared cache.  Then the runtime of
 73652  ** this routine is N*N.  But as N is rarely more than 1, this should not
 73653  ** be a problem.
 73654  */
 73655  SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
 73656    int i;
 73657    sqlite3 *db;
 73658    Db *aDb;
 73659    int nDb;
 73660    if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
 73661    db = p->db;
 73662    aDb = db->aDb;
 73663    nDb = db->nDb;
 73664    for(i=0; i<nDb; i++){
 73665      if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
 73666        sqlite3BtreeEnter(aDb[i].pBt);
 73667      }
 73668    }
 73669  }
 73670  #endif
 73671  
 73672  #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
 73673  /*
 73674  ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
 73675  */
 73676  static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
 73677    int i;
 73678    sqlite3 *db;
 73679    Db *aDb;
 73680    int nDb;
 73681    db = p->db;
 73682    aDb = db->aDb;
 73683    nDb = db->nDb;
 73684    for(i=0; i<nDb; i++){
 73685      if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
 73686        sqlite3BtreeLeave(aDb[i].pBt);
 73687      }
 73688    }
 73689  }
 73690  SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
 73691    if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
 73692    vdbeLeave(p);
 73693  }
 73694  #endif
 73695  
 73696  #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
 73697  /*
 73698  ** Print a single opcode.  This routine is used for debugging only.
 73699  */
 73700  SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
 73701    char *zP4;
 73702    char zPtr[50];
 73703    char zCom[100];
 73704    static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
 73705    if( pOut==0 ) pOut = stdout;
 73706    zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
 73707  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 73708    displayComment(pOp, zP4, zCom, sizeof(zCom));
 73709  #else
 73710    zCom[0] = 0;
 73711  #endif
 73712    /* NB:  The sqlite3OpcodeName() function is implemented by code created
 73713    ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
 73714    ** information from the vdbe.c source text */
 73715    fprintf(pOut, zFormat1, pc, 
 73716        sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
 73717        zCom
 73718    );
 73719    fflush(pOut);
 73720  }
 73721  #endif
 73722  
 73723  /*
 73724  ** Initialize an array of N Mem element.
 73725  */
 73726  static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
 73727    while( (N--)>0 ){
 73728      p->db = db;
 73729      p->flags = flags;
 73730      p->szMalloc = 0;
 73731  #ifdef SQLITE_DEBUG
 73732      p->pScopyFrom = 0;
 73733  #endif
 73734      p++;
 73735    }
 73736  }
 73737  
 73738  /*
 73739  ** Release an array of N Mem elements
 73740  */
 73741  static void releaseMemArray(Mem *p, int N){
 73742    if( p && N ){
 73743      Mem *pEnd = &p[N];
 73744      sqlite3 *db = p->db;
 73745      if( db->pnBytesFreed ){
 73746        do{
 73747          if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
 73748        }while( (++p)<pEnd );
 73749        return;
 73750      }
 73751      do{
 73752        assert( (&p[1])==pEnd || p[0].db==p[1].db );
 73753        assert( sqlite3VdbeCheckMemInvariants(p) );
 73754  
 73755        /* This block is really an inlined version of sqlite3VdbeMemRelease()
 73756        ** that takes advantage of the fact that the memory cell value is 
 73757        ** being set to NULL after releasing any dynamic resources.
 73758        **
 73759        ** The justification for duplicating code is that according to 
 73760        ** callgrind, this causes a certain test case to hit the CPU 4.7 
 73761        ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
 73762        ** sqlite3MemRelease() were called from here. With -O2, this jumps
 73763        ** to 6.6 percent. The test case is inserting 1000 rows into a table 
 73764        ** with no indexes using a single prepared INSERT statement, bind() 
 73765        ** and reset(). Inserts are grouped into a transaction.
 73766        */
 73767        testcase( p->flags & MEM_Agg );
 73768        testcase( p->flags & MEM_Dyn );
 73769        testcase( p->flags & MEM_Frame );
 73770        testcase( p->flags & MEM_RowSet );
 73771        if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
 73772          sqlite3VdbeMemRelease(p);
 73773        }else if( p->szMalloc ){
 73774          sqlite3DbFreeNN(db, p->zMalloc);
 73775          p->szMalloc = 0;
 73776        }
 73777  
 73778        p->flags = MEM_Undefined;
 73779      }while( (++p)<pEnd );
 73780    }
 73781  }
 73782  
 73783  /*
 73784  ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
 73785  ** allocated by the OP_Program opcode in sqlite3VdbeExec().
 73786  */
 73787  SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
 73788    int i;
 73789    Mem *aMem = VdbeFrameMem(p);
 73790    VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
 73791    for(i=0; i<p->nChildCsr; i++){
 73792      sqlite3VdbeFreeCursor(p->v, apCsr[i]);
 73793    }
 73794    releaseMemArray(aMem, p->nChildMem);
 73795    sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
 73796    sqlite3DbFree(p->v->db, p);
 73797  }
 73798  
 73799  #ifndef SQLITE_OMIT_EXPLAIN
 73800  /*
 73801  ** Give a listing of the program in the virtual machine.
 73802  **
 73803  ** The interface is the same as sqlite3VdbeExec().  But instead of
 73804  ** running the code, it invokes the callback once for each instruction.
 73805  ** This feature is used to implement "EXPLAIN".
 73806  **
 73807  ** When p->explain==1, each instruction is listed.  When
 73808  ** p->explain==2, only OP_Explain instructions are listed and these
 73809  ** are shown in a different format.  p->explain==2 is used to implement
 73810  ** EXPLAIN QUERY PLAN.
 73811  **
 73812  ** When p->explain==1, first the main program is listed, then each of
 73813  ** the trigger subprograms are listed one by one.
 73814  */
 73815  SQLITE_PRIVATE int sqlite3VdbeList(
 73816    Vdbe *p                   /* The VDBE */
 73817  ){
 73818    int nRow;                            /* Stop when row count reaches this */
 73819    int nSub = 0;                        /* Number of sub-vdbes seen so far */
 73820    SubProgram **apSub = 0;              /* Array of sub-vdbes */
 73821    Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
 73822    sqlite3 *db = p->db;                 /* The database connection */
 73823    int i;                               /* Loop counter */
 73824    int rc = SQLITE_OK;                  /* Return code */
 73825    Mem *pMem = &p->aMem[1];             /* First Mem of result set */
 73826  
 73827    assert( p->explain );
 73828    assert( p->magic==VDBE_MAGIC_RUN );
 73829    assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
 73830  
 73831    /* Even though this opcode does not use dynamic strings for
 73832    ** the result, result columns may become dynamic if the user calls
 73833    ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
 73834    */
 73835    releaseMemArray(pMem, 8);
 73836    p->pResultSet = 0;
 73837  
 73838    if( p->rc==SQLITE_NOMEM_BKPT ){
 73839      /* This happens if a malloc() inside a call to sqlite3_column_text() or
 73840      ** sqlite3_column_text16() failed.  */
 73841      sqlite3OomFault(db);
 73842      return SQLITE_ERROR;
 73843    }
 73844  
 73845    /* When the number of output rows reaches nRow, that means the
 73846    ** listing has finished and sqlite3_step() should return SQLITE_DONE.
 73847    ** nRow is the sum of the number of rows in the main program, plus
 73848    ** the sum of the number of rows in all trigger subprograms encountered
 73849    ** so far.  The nRow value will increase as new trigger subprograms are
 73850    ** encountered, but p->pc will eventually catch up to nRow.
 73851    */
 73852    nRow = p->nOp;
 73853    if( p->explain==1 ){
 73854      /* The first 8 memory cells are used for the result set.  So we will
 73855      ** commandeer the 9th cell to use as storage for an array of pointers
 73856      ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
 73857      ** cells.  */
 73858      assert( p->nMem>9 );
 73859      pSub = &p->aMem[9];
 73860      if( pSub->flags&MEM_Blob ){
 73861        /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
 73862        ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
 73863        nSub = pSub->n/sizeof(Vdbe*);
 73864        apSub = (SubProgram **)pSub->z;
 73865      }
 73866      for(i=0; i<nSub; i++){
 73867        nRow += apSub[i]->nOp;
 73868      }
 73869    }
 73870  
 73871    do{
 73872      i = p->pc++;
 73873    }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
 73874    if( i>=nRow ){
 73875      p->rc = SQLITE_OK;
 73876      rc = SQLITE_DONE;
 73877    }else if( db->u1.isInterrupted ){
 73878      p->rc = SQLITE_INTERRUPT;
 73879      rc = SQLITE_ERROR;
 73880      sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
 73881    }else{
 73882      char *zP4;
 73883      Op *pOp;
 73884      if( i<p->nOp ){
 73885        /* The output line number is small enough that we are still in the
 73886        ** main program. */
 73887        pOp = &p->aOp[i];
 73888      }else{
 73889        /* We are currently listing subprograms.  Figure out which one and
 73890        ** pick up the appropriate opcode. */
 73891        int j;
 73892        i -= p->nOp;
 73893        for(j=0; i>=apSub[j]->nOp; j++){
 73894          i -= apSub[j]->nOp;
 73895        }
 73896        pOp = &apSub[j]->aOp[i];
 73897      }
 73898      if( p->explain==1 ){
 73899        pMem->flags = MEM_Int;
 73900        pMem->u.i = i;                                /* Program counter */
 73901        pMem++;
 73902    
 73903        pMem->flags = MEM_Static|MEM_Str|MEM_Term;
 73904        pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
 73905        assert( pMem->z!=0 );
 73906        pMem->n = sqlite3Strlen30(pMem->z);
 73907        pMem->enc = SQLITE_UTF8;
 73908        pMem++;
 73909  
 73910        /* When an OP_Program opcode is encounter (the only opcode that has
 73911        ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
 73912        ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
 73913        ** has not already been seen.
 73914        */
 73915        if( pOp->p4type==P4_SUBPROGRAM ){
 73916          int nByte = (nSub+1)*sizeof(SubProgram*);
 73917          int j;
 73918          for(j=0; j<nSub; j++){
 73919            if( apSub[j]==pOp->p4.pProgram ) break;
 73920          }
 73921          if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
 73922            apSub = (SubProgram **)pSub->z;
 73923            apSub[nSub++] = pOp->p4.pProgram;
 73924            pSub->flags |= MEM_Blob;
 73925            pSub->n = nSub*sizeof(SubProgram*);
 73926          }
 73927        }
 73928      }
 73929  
 73930      pMem->flags = MEM_Int;
 73931      pMem->u.i = pOp->p1;                          /* P1 */
 73932      pMem++;
 73933  
 73934      pMem->flags = MEM_Int;
 73935      pMem->u.i = pOp->p2;                          /* P2 */
 73936      pMem++;
 73937  
 73938      pMem->flags = MEM_Int;
 73939      pMem->u.i = pOp->p3;                          /* P3 */
 73940      pMem++;
 73941  
 73942      if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
 73943        assert( p->db->mallocFailed );
 73944        return SQLITE_ERROR;
 73945      }
 73946      pMem->flags = MEM_Str|MEM_Term;
 73947      zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
 73948      if( zP4!=pMem->z ){
 73949        pMem->n = 0;
 73950        sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
 73951      }else{
 73952        assert( pMem->z!=0 );
 73953        pMem->n = sqlite3Strlen30(pMem->z);
 73954        pMem->enc = SQLITE_UTF8;
 73955      }
 73956      pMem++;
 73957  
 73958      if( p->explain==1 ){
 73959        if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
 73960          assert( p->db->mallocFailed );
 73961          return SQLITE_ERROR;
 73962        }
 73963        pMem->flags = MEM_Str|MEM_Term;
 73964        pMem->n = 2;
 73965        sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
 73966        pMem->enc = SQLITE_UTF8;
 73967        pMem++;
 73968    
 73969  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 73970        if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
 73971          assert( p->db->mallocFailed );
 73972          return SQLITE_ERROR;
 73973        }
 73974        pMem->flags = MEM_Str|MEM_Term;
 73975        pMem->n = displayComment(pOp, zP4, pMem->z, 500);
 73976        pMem->enc = SQLITE_UTF8;
 73977  #else
 73978        pMem->flags = MEM_Null;                       /* Comment */
 73979  #endif
 73980      }
 73981  
 73982      p->nResColumn = 8 - 4*(p->explain-1);
 73983      p->pResultSet = &p->aMem[1];
 73984      p->rc = SQLITE_OK;
 73985      rc = SQLITE_ROW;
 73986    }
 73987    return rc;
 73988  }
 73989  #endif /* SQLITE_OMIT_EXPLAIN */
 73990  
 73991  #ifdef SQLITE_DEBUG
 73992  /*
 73993  ** Print the SQL that was used to generate a VDBE program.
 73994  */
 73995  SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
 73996    const char *z = 0;
 73997    if( p->zSql ){
 73998      z = p->zSql;
 73999    }else if( p->nOp>=1 ){
 74000      const VdbeOp *pOp = &p->aOp[0];
 74001      if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
 74002        z = pOp->p4.z;
 74003        while( sqlite3Isspace(*z) ) z++;
 74004      }
 74005    }
 74006    if( z ) printf("SQL: [%s]\n", z);
 74007  }
 74008  #endif
 74009  
 74010  #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
 74011  /*
 74012  ** Print an IOTRACE message showing SQL content.
 74013  */
 74014  SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
 74015    int nOp = p->nOp;
 74016    VdbeOp *pOp;
 74017    if( sqlite3IoTrace==0 ) return;
 74018    if( nOp<1 ) return;
 74019    pOp = &p->aOp[0];
 74020    if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
 74021      int i, j;
 74022      char z[1000];
 74023      sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
 74024      for(i=0; sqlite3Isspace(z[i]); i++){}
 74025      for(j=0; z[i]; i++){
 74026        if( sqlite3Isspace(z[i]) ){
 74027          if( z[i-1]!=' ' ){
 74028            z[j++] = ' ';
 74029          }
 74030        }else{
 74031          z[j++] = z[i];
 74032        }
 74033      }
 74034      z[j] = 0;
 74035      sqlite3IoTrace("SQL %s\n", z);
 74036    }
 74037  }
 74038  #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
 74039  
 74040  /* An instance of this object describes bulk memory available for use
 74041  ** by subcomponents of a prepared statement.  Space is allocated out
 74042  ** of a ReusableSpace object by the allocSpace() routine below.
 74043  */
 74044  struct ReusableSpace {
 74045    u8 *pSpace;          /* Available memory */
 74046    int nFree;           /* Bytes of available memory */
 74047    int nNeeded;         /* Total bytes that could not be allocated */
 74048  };
 74049  
 74050  /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
 74051  ** from the ReusableSpace object.  Return a pointer to the allocated
 74052  ** memory on success.  If insufficient memory is available in the
 74053  ** ReusableSpace object, increase the ReusableSpace.nNeeded
 74054  ** value by the amount needed and return NULL.
 74055  **
 74056  ** If pBuf is not initially NULL, that means that the memory has already
 74057  ** been allocated by a prior call to this routine, so just return a copy
 74058  ** of pBuf and leave ReusableSpace unchanged.
 74059  **
 74060  ** This allocator is employed to repurpose unused slots at the end of the
 74061  ** opcode array of prepared state for other memory needs of the prepared
 74062  ** statement.
 74063  */
 74064  static void *allocSpace(
 74065    struct ReusableSpace *p,  /* Bulk memory available for allocation */
 74066    void *pBuf,               /* Pointer to a prior allocation */
 74067    int nByte                 /* Bytes of memory needed */
 74068  ){
 74069    assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
 74070    if( pBuf==0 ){
 74071      nByte = ROUND8(nByte);
 74072      if( nByte <= p->nFree ){
 74073        p->nFree -= nByte;
 74074        pBuf = &p->pSpace[p->nFree];
 74075      }else{
 74076        p->nNeeded += nByte;
 74077      }
 74078    }
 74079    assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
 74080    return pBuf;
 74081  }
 74082  
 74083  /*
 74084  ** Rewind the VDBE back to the beginning in preparation for
 74085  ** running it.
 74086  */
 74087  SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
 74088  #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
 74089    int i;
 74090  #endif
 74091    assert( p!=0 );
 74092    assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
 74093  
 74094    /* There should be at least one opcode.
 74095    */
 74096    assert( p->nOp>0 );
 74097  
 74098    /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
 74099    p->magic = VDBE_MAGIC_RUN;
 74100  
 74101  #ifdef SQLITE_DEBUG
 74102    for(i=0; i<p->nMem; i++){
 74103      assert( p->aMem[i].db==p->db );
 74104    }
 74105  #endif
 74106    p->pc = -1;
 74107    p->rc = SQLITE_OK;
 74108    p->errorAction = OE_Abort;
 74109    p->nChange = 0;
 74110    p->cacheCtr = 1;
 74111    p->minWriteFileFormat = 255;
 74112    p->iStatement = 0;
 74113    p->nFkConstraint = 0;
 74114  #ifdef VDBE_PROFILE
 74115    for(i=0; i<p->nOp; i++){
 74116      p->aOp[i].cnt = 0;
 74117      p->aOp[i].cycles = 0;
 74118    }
 74119  #endif
 74120  }
 74121  
 74122  /*
 74123  ** Prepare a virtual machine for execution for the first time after
 74124  ** creating the virtual machine.  This involves things such
 74125  ** as allocating registers and initializing the program counter.
 74126  ** After the VDBE has be prepped, it can be executed by one or more
 74127  ** calls to sqlite3VdbeExec().  
 74128  **
 74129  ** This function may be called exactly once on each virtual machine.
 74130  ** After this routine is called the VM has been "packaged" and is ready
 74131  ** to run.  After this routine is called, further calls to 
 74132  ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
 74133  ** the Vdbe from the Parse object that helped generate it so that the
 74134  ** the Vdbe becomes an independent entity and the Parse object can be
 74135  ** destroyed.
 74136  **
 74137  ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
 74138  ** to its initial state after it has been run.
 74139  */
 74140  SQLITE_PRIVATE void sqlite3VdbeMakeReady(
 74141    Vdbe *p,                       /* The VDBE */
 74142    Parse *pParse                  /* Parsing context */
 74143  ){
 74144    sqlite3 *db;                   /* The database connection */
 74145    int nVar;                      /* Number of parameters */
 74146    int nMem;                      /* Number of VM memory registers */
 74147    int nCursor;                   /* Number of cursors required */
 74148    int nArg;                      /* Number of arguments in subprograms */
 74149    int n;                         /* Loop counter */
 74150    struct ReusableSpace x;        /* Reusable bulk memory */
 74151  
 74152    assert( p!=0 );
 74153    assert( p->nOp>0 );
 74154    assert( pParse!=0 );
 74155    assert( p->magic==VDBE_MAGIC_INIT );
 74156    assert( pParse==p->pParse );
 74157    db = p->db;
 74158    assert( db->mallocFailed==0 );
 74159    nVar = pParse->nVar;
 74160    nMem = pParse->nMem;
 74161    nCursor = pParse->nTab;
 74162    nArg = pParse->nMaxArg;
 74163    
 74164    /* Each cursor uses a memory cell.  The first cursor (cursor 0) can
 74165    ** use aMem[0] which is not otherwise used by the VDBE program.  Allocate
 74166    ** space at the end of aMem[] for cursors 1 and greater.
 74167    ** See also: allocateCursor().
 74168    */
 74169    nMem += nCursor;
 74170    if( nCursor==0 && nMem>0 ) nMem++;  /* Space for aMem[0] even if not used */
 74171  
 74172    /* Figure out how much reusable memory is available at the end of the
 74173    ** opcode array.  This extra memory will be reallocated for other elements
 74174    ** of the prepared statement.
 74175    */
 74176    n = ROUND8(sizeof(Op)*p->nOp);              /* Bytes of opcode memory used */
 74177    x.pSpace = &((u8*)p->aOp)[n];               /* Unused opcode memory */
 74178    assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
 74179    x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n);  /* Bytes of unused memory */
 74180    assert( x.nFree>=0 );
 74181    assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
 74182  
 74183    resolveP2Values(p, &nArg);
 74184    p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
 74185    if( pParse->explain && nMem<10 ){
 74186      nMem = 10;
 74187    }
 74188    p->expired = 0;
 74189  
 74190    /* Memory for registers, parameters, cursor, etc, is allocated in one or two
 74191    ** passes.  On the first pass, we try to reuse unused memory at the 
 74192    ** end of the opcode array.  If we are unable to satisfy all memory
 74193    ** requirements by reusing the opcode array tail, then the second
 74194    ** pass will fill in the remainder using a fresh memory allocation.  
 74195    **
 74196    ** This two-pass approach that reuses as much memory as possible from
 74197    ** the leftover memory at the end of the opcode array.  This can significantly
 74198    ** reduce the amount of memory held by a prepared statement.
 74199    */
 74200    do {
 74201      x.nNeeded = 0;
 74202      p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
 74203      p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
 74204      p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
 74205      p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
 74206  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 74207      p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
 74208  #endif
 74209      if( x.nNeeded==0 ) break;
 74210      x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
 74211      x.nFree = x.nNeeded;
 74212    }while( !db->mallocFailed );
 74213  
 74214    p->pVList = pParse->pVList;
 74215    pParse->pVList =  0;
 74216    p->explain = pParse->explain;
 74217    if( db->mallocFailed ){
 74218      p->nVar = 0;
 74219      p->nCursor = 0;
 74220      p->nMem = 0;
 74221    }else{
 74222      p->nCursor = nCursor;
 74223      p->nVar = (ynVar)nVar;
 74224      initMemArray(p->aVar, nVar, db, MEM_Null);
 74225      p->nMem = nMem;
 74226      initMemArray(p->aMem, nMem, db, MEM_Undefined);
 74227      memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
 74228  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 74229      memset(p->anExec, 0, p->nOp*sizeof(i64));
 74230  #endif
 74231    }
 74232    sqlite3VdbeRewind(p);
 74233  }
 74234  
 74235  /*
 74236  ** Close a VDBE cursor and release all the resources that cursor 
 74237  ** happens to hold.
 74238  */
 74239  SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
 74240    if( pCx==0 ){
 74241      return;
 74242    }
 74243    assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );
 74244    switch( pCx->eCurType ){
 74245      case CURTYPE_SORTER: {
 74246        sqlite3VdbeSorterClose(p->db, pCx);
 74247        break;
 74248      }
 74249      case CURTYPE_BTREE: {
 74250        if( pCx->isEphemeral ){
 74251          if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx);
 74252          /* The pCx->pCursor will be close automatically, if it exists, by
 74253          ** the call above. */
 74254        }else{
 74255          assert( pCx->uc.pCursor!=0 );
 74256          sqlite3BtreeCloseCursor(pCx->uc.pCursor);
 74257        }
 74258        break;
 74259      }
 74260  #ifndef SQLITE_OMIT_VIRTUALTABLE
 74261      case CURTYPE_VTAB: {
 74262        sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
 74263        const sqlite3_module *pModule = pVCur->pVtab->pModule;
 74264        assert( pVCur->pVtab->nRef>0 );
 74265        pVCur->pVtab->nRef--;
 74266        pModule->xClose(pVCur);
 74267        break;
 74268      }
 74269  #endif
 74270    }
 74271  }
 74272  
 74273  /*
 74274  ** Close all cursors in the current frame.
 74275  */
 74276  static void closeCursorsInFrame(Vdbe *p){
 74277    if( p->apCsr ){
 74278      int i;
 74279      for(i=0; i<p->nCursor; i++){
 74280        VdbeCursor *pC = p->apCsr[i];
 74281        if( pC ){
 74282          sqlite3VdbeFreeCursor(p, pC);
 74283          p->apCsr[i] = 0;
 74284        }
 74285      }
 74286    }
 74287  }
 74288  
 74289  /*
 74290  ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
 74291  ** is used, for example, when a trigger sub-program is halted to restore
 74292  ** control to the main program.
 74293  */
 74294  SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
 74295    Vdbe *v = pFrame->v;
 74296    closeCursorsInFrame(v);
 74297  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 74298    v->anExec = pFrame->anExec;
 74299  #endif
 74300    v->aOp = pFrame->aOp;
 74301    v->nOp = pFrame->nOp;
 74302    v->aMem = pFrame->aMem;
 74303    v->nMem = pFrame->nMem;
 74304    v->apCsr = pFrame->apCsr;
 74305    v->nCursor = pFrame->nCursor;
 74306    v->db->lastRowid = pFrame->lastRowid;
 74307    v->nChange = pFrame->nChange;
 74308    v->db->nChange = pFrame->nDbChange;
 74309    sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
 74310    v->pAuxData = pFrame->pAuxData;
 74311    pFrame->pAuxData = 0;
 74312    return pFrame->pc;
 74313  }
 74314  
 74315  /*
 74316  ** Close all cursors.
 74317  **
 74318  ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
 74319  ** cell array. This is necessary as the memory cell array may contain
 74320  ** pointers to VdbeFrame objects, which may in turn contain pointers to
 74321  ** open cursors.
 74322  */
 74323  static void closeAllCursors(Vdbe *p){
 74324    if( p->pFrame ){
 74325      VdbeFrame *pFrame;
 74326      for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
 74327      sqlite3VdbeFrameRestore(pFrame);
 74328      p->pFrame = 0;
 74329      p->nFrame = 0;
 74330    }
 74331    assert( p->nFrame==0 );
 74332    closeCursorsInFrame(p);
 74333    if( p->aMem ){
 74334      releaseMemArray(p->aMem, p->nMem);
 74335    }
 74336    while( p->pDelFrame ){
 74337      VdbeFrame *pDel = p->pDelFrame;
 74338      p->pDelFrame = pDel->pParent;
 74339      sqlite3VdbeFrameDelete(pDel);
 74340    }
 74341  
 74342    /* Delete any auxdata allocations made by the VM */
 74343    if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
 74344    assert( p->pAuxData==0 );
 74345  }
 74346  
 74347  /*
 74348  ** Set the number of result columns that will be returned by this SQL
 74349  ** statement. This is now set at compile time, rather than during
 74350  ** execution of the vdbe program so that sqlite3_column_count() can
 74351  ** be called on an SQL statement before sqlite3_step().
 74352  */
 74353  SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
 74354    int n;
 74355    sqlite3 *db = p->db;
 74356  
 74357    if( p->nResColumn ){
 74358      releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
 74359      sqlite3DbFree(db, p->aColName);
 74360    }
 74361    n = nResColumn*COLNAME_N;
 74362    p->nResColumn = (u16)nResColumn;
 74363    p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
 74364    if( p->aColName==0 ) return;
 74365    initMemArray(p->aColName, n, db, MEM_Null);
 74366  }
 74367  
 74368  /*
 74369  ** Set the name of the idx'th column to be returned by the SQL statement.
 74370  ** zName must be a pointer to a nul terminated string.
 74371  **
 74372  ** This call must be made after a call to sqlite3VdbeSetNumCols().
 74373  **
 74374  ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
 74375  ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
 74376  ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
 74377  */
 74378  SQLITE_PRIVATE int sqlite3VdbeSetColName(
 74379    Vdbe *p,                         /* Vdbe being configured */
 74380    int idx,                         /* Index of column zName applies to */
 74381    int var,                         /* One of the COLNAME_* constants */
 74382    const char *zName,               /* Pointer to buffer containing name */
 74383    void (*xDel)(void*)              /* Memory management strategy for zName */
 74384  ){
 74385    int rc;
 74386    Mem *pColName;
 74387    assert( idx<p->nResColumn );
 74388    assert( var<COLNAME_N );
 74389    if( p->db->mallocFailed ){
 74390      assert( !zName || xDel!=SQLITE_DYNAMIC );
 74391      return SQLITE_NOMEM_BKPT;
 74392    }
 74393    assert( p->aColName!=0 );
 74394    pColName = &(p->aColName[idx+var*p->nResColumn]);
 74395    rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
 74396    assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
 74397    return rc;
 74398  }
 74399  
 74400  /*
 74401  ** A read or write transaction may or may not be active on database handle
 74402  ** db. If a transaction is active, commit it. If there is a
 74403  ** write-transaction spanning more than one database file, this routine
 74404  ** takes care of the master journal trickery.
 74405  */
 74406  static int vdbeCommit(sqlite3 *db, Vdbe *p){
 74407    int i;
 74408    int nTrans = 0;  /* Number of databases with an active write-transaction
 74409                     ** that are candidates for a two-phase commit using a
 74410                     ** master-journal */
 74411    int rc = SQLITE_OK;
 74412    int needXcommit = 0;
 74413  
 74414  #ifdef SQLITE_OMIT_VIRTUALTABLE
 74415    /* With this option, sqlite3VtabSync() is defined to be simply 
 74416    ** SQLITE_OK so p is not used. 
 74417    */
 74418    UNUSED_PARAMETER(p);
 74419  #endif
 74420  
 74421    /* Before doing anything else, call the xSync() callback for any
 74422    ** virtual module tables written in this transaction. This has to
 74423    ** be done before determining whether a master journal file is 
 74424    ** required, as an xSync() callback may add an attached database
 74425    ** to the transaction.
 74426    */
 74427    rc = sqlite3VtabSync(db, p);
 74428  
 74429    /* This loop determines (a) if the commit hook should be invoked and
 74430    ** (b) how many database files have open write transactions, not 
 74431    ** including the temp database. (b) is important because if more than 
 74432    ** one database file has an open write transaction, a master journal
 74433    ** file is required for an atomic commit.
 74434    */ 
 74435    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
 74436      Btree *pBt = db->aDb[i].pBt;
 74437      if( sqlite3BtreeIsInTrans(pBt) ){
 74438        /* Whether or not a database might need a master journal depends upon
 74439        ** its journal mode (among other things).  This matrix determines which
 74440        ** journal modes use a master journal and which do not */
 74441        static const u8 aMJNeeded[] = {
 74442          /* DELETE   */  1,
 74443          /* PERSIST   */ 1,
 74444          /* OFF       */ 0,
 74445          /* TRUNCATE  */ 1,
 74446          /* MEMORY    */ 0,
 74447          /* WAL       */ 0
 74448        };
 74449        Pager *pPager;   /* Pager associated with pBt */
 74450        needXcommit = 1;
 74451        sqlite3BtreeEnter(pBt);
 74452        pPager = sqlite3BtreePager(pBt);
 74453        if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
 74454         && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
 74455        ){ 
 74456          assert( i!=1 );
 74457          nTrans++;
 74458        }
 74459        rc = sqlite3PagerExclusiveLock(pPager);
 74460        sqlite3BtreeLeave(pBt);
 74461      }
 74462    }
 74463    if( rc!=SQLITE_OK ){
 74464      return rc;
 74465    }
 74466  
 74467    /* If there are any write-transactions at all, invoke the commit hook */
 74468    if( needXcommit && db->xCommitCallback ){
 74469      rc = db->xCommitCallback(db->pCommitArg);
 74470      if( rc ){
 74471        return SQLITE_CONSTRAINT_COMMITHOOK;
 74472      }
 74473    }
 74474  
 74475    /* The simple case - no more than one database file (not counting the
 74476    ** TEMP database) has a transaction active.   There is no need for the
 74477    ** master-journal.
 74478    **
 74479    ** If the return value of sqlite3BtreeGetFilename() is a zero length
 74480    ** string, it means the main database is :memory: or a temp file.  In 
 74481    ** that case we do not support atomic multi-file commits, so use the 
 74482    ** simple case then too.
 74483    */
 74484    if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
 74485     || nTrans<=1
 74486    ){
 74487      for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
 74488        Btree *pBt = db->aDb[i].pBt;
 74489        if( pBt ){
 74490          rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
 74491        }
 74492      }
 74493  
 74494      /* Do the commit only if all databases successfully complete phase 1. 
 74495      ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
 74496      ** IO error while deleting or truncating a journal file. It is unlikely,
 74497      ** but could happen. In this case abandon processing and return the error.
 74498      */
 74499      for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
 74500        Btree *pBt = db->aDb[i].pBt;
 74501        if( pBt ){
 74502          rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
 74503        }
 74504      }
 74505      if( rc==SQLITE_OK ){
 74506        sqlite3VtabCommit(db);
 74507      }
 74508    }
 74509  
 74510    /* The complex case - There is a multi-file write-transaction active.
 74511    ** This requires a master journal file to ensure the transaction is
 74512    ** committed atomically.
 74513    */
 74514  #ifndef SQLITE_OMIT_DISKIO
 74515    else{
 74516      sqlite3_vfs *pVfs = db->pVfs;
 74517      char *zMaster = 0;   /* File-name for the master journal */
 74518      char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
 74519      sqlite3_file *pMaster = 0;
 74520      i64 offset = 0;
 74521      int res;
 74522      int retryCount = 0;
 74523      int nMainFile;
 74524  
 74525      /* Select a master journal file name */
 74526      nMainFile = sqlite3Strlen30(zMainFile);
 74527      zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
 74528      if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
 74529      do {
 74530        u32 iRandom;
 74531        if( retryCount ){
 74532          if( retryCount>100 ){
 74533            sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
 74534            sqlite3OsDelete(pVfs, zMaster, 0);
 74535            break;
 74536          }else if( retryCount==1 ){
 74537            sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
 74538          }
 74539        }
 74540        retryCount++;
 74541        sqlite3_randomness(sizeof(iRandom), &iRandom);
 74542        sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
 74543                                 (iRandom>>8)&0xffffff, iRandom&0xff);
 74544        /* The antipenultimate character of the master journal name must
 74545        ** be "9" to avoid name collisions when using 8+3 filenames. */
 74546        assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
 74547        sqlite3FileSuffix3(zMainFile, zMaster);
 74548        rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
 74549      }while( rc==SQLITE_OK && res );
 74550      if( rc==SQLITE_OK ){
 74551        /* Open the master journal. */
 74552        rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
 74553            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
 74554            SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
 74555        );
 74556      }
 74557      if( rc!=SQLITE_OK ){
 74558        sqlite3DbFree(db, zMaster);
 74559        return rc;
 74560      }
 74561   
 74562      /* Write the name of each database file in the transaction into the new
 74563      ** master journal file. If an error occurs at this point close
 74564      ** and delete the master journal file. All the individual journal files
 74565      ** still have 'null' as the master journal pointer, so they will roll
 74566      ** back independently if a failure occurs.
 74567      */
 74568      for(i=0; i<db->nDb; i++){
 74569        Btree *pBt = db->aDb[i].pBt;
 74570        if( sqlite3BtreeIsInTrans(pBt) ){
 74571          char const *zFile = sqlite3BtreeGetJournalname(pBt);
 74572          if( zFile==0 ){
 74573            continue;  /* Ignore TEMP and :memory: databases */
 74574          }
 74575          assert( zFile[0]!=0 );
 74576          rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
 74577          offset += sqlite3Strlen30(zFile)+1;
 74578          if( rc!=SQLITE_OK ){
 74579            sqlite3OsCloseFree(pMaster);
 74580            sqlite3OsDelete(pVfs, zMaster, 0);
 74581            sqlite3DbFree(db, zMaster);
 74582            return rc;
 74583          }
 74584        }
 74585      }
 74586  
 74587      /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
 74588      ** flag is set this is not required.
 74589      */
 74590      if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
 74591       && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
 74592      ){
 74593        sqlite3OsCloseFree(pMaster);
 74594        sqlite3OsDelete(pVfs, zMaster, 0);
 74595        sqlite3DbFree(db, zMaster);
 74596        return rc;
 74597      }
 74598  
 74599      /* Sync all the db files involved in the transaction. The same call
 74600      ** sets the master journal pointer in each individual journal. If
 74601      ** an error occurs here, do not delete the master journal file.
 74602      **
 74603      ** If the error occurs during the first call to
 74604      ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
 74605      ** master journal file will be orphaned. But we cannot delete it,
 74606      ** in case the master journal file name was written into the journal
 74607      ** file before the failure occurred.
 74608      */
 74609      for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
 74610        Btree *pBt = db->aDb[i].pBt;
 74611        if( pBt ){
 74612          rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
 74613        }
 74614      }
 74615      sqlite3OsCloseFree(pMaster);
 74616      assert( rc!=SQLITE_BUSY );
 74617      if( rc!=SQLITE_OK ){
 74618        sqlite3DbFree(db, zMaster);
 74619        return rc;
 74620      }
 74621  
 74622      /* Delete the master journal file. This commits the transaction. After
 74623      ** doing this the directory is synced again before any individual
 74624      ** transaction files are deleted.
 74625      */
 74626      rc = sqlite3OsDelete(pVfs, zMaster, 1);
 74627      sqlite3DbFree(db, zMaster);
 74628      zMaster = 0;
 74629      if( rc ){
 74630        return rc;
 74631      }
 74632  
 74633      /* All files and directories have already been synced, so the following
 74634      ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
 74635      ** deleting or truncating journals. If something goes wrong while
 74636      ** this is happening we don't really care. The integrity of the
 74637      ** transaction is already guaranteed, but some stray 'cold' journals
 74638      ** may be lying around. Returning an error code won't help matters.
 74639      */
 74640      disable_simulated_io_errors();
 74641      sqlite3BeginBenignMalloc();
 74642      for(i=0; i<db->nDb; i++){ 
 74643        Btree *pBt = db->aDb[i].pBt;
 74644        if( pBt ){
 74645          sqlite3BtreeCommitPhaseTwo(pBt, 1);
 74646        }
 74647      }
 74648      sqlite3EndBenignMalloc();
 74649      enable_simulated_io_errors();
 74650  
 74651      sqlite3VtabCommit(db);
 74652    }
 74653  #endif
 74654  
 74655    return rc;
 74656  }
 74657  
 74658  /* 
 74659  ** This routine checks that the sqlite3.nVdbeActive count variable
 74660  ** matches the number of vdbe's in the list sqlite3.pVdbe that are
 74661  ** currently active. An assertion fails if the two counts do not match.
 74662  ** This is an internal self-check only - it is not an essential processing
 74663  ** step.
 74664  **
 74665  ** This is a no-op if NDEBUG is defined.
 74666  */
 74667  #ifndef NDEBUG
 74668  static void checkActiveVdbeCnt(sqlite3 *db){
 74669    Vdbe *p;
 74670    int cnt = 0;
 74671    int nWrite = 0;
 74672    int nRead = 0;
 74673    p = db->pVdbe;
 74674    while( p ){
 74675      if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
 74676        cnt++;
 74677        if( p->readOnly==0 ) nWrite++;
 74678        if( p->bIsReader ) nRead++;
 74679      }
 74680      p = p->pNext;
 74681    }
 74682    assert( cnt==db->nVdbeActive );
 74683    assert( nWrite==db->nVdbeWrite );
 74684    assert( nRead==db->nVdbeRead );
 74685  }
 74686  #else
 74687  #define checkActiveVdbeCnt(x)
 74688  #endif
 74689  
 74690  /*
 74691  ** If the Vdbe passed as the first argument opened a statement-transaction,
 74692  ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
 74693  ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
 74694  ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
 74695  ** statement transaction is committed.
 74696  **
 74697  ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
 74698  ** Otherwise SQLITE_OK.
 74699  */
 74700  static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
 74701    sqlite3 *const db = p->db;
 74702    int rc = SQLITE_OK;
 74703    int i;
 74704    const int iSavepoint = p->iStatement-1;
 74705  
 74706    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
 74707    assert( db->nStatement>0 );
 74708    assert( p->iStatement==(db->nStatement+db->nSavepoint) );
 74709  
 74710    for(i=0; i<db->nDb; i++){ 
 74711      int rc2 = SQLITE_OK;
 74712      Btree *pBt = db->aDb[i].pBt;
 74713      if( pBt ){
 74714        if( eOp==SAVEPOINT_ROLLBACK ){
 74715          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
 74716        }
 74717        if( rc2==SQLITE_OK ){
 74718          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
 74719        }
 74720        if( rc==SQLITE_OK ){
 74721          rc = rc2;
 74722        }
 74723      }
 74724    }
 74725    db->nStatement--;
 74726    p->iStatement = 0;
 74727  
 74728    if( rc==SQLITE_OK ){
 74729      if( eOp==SAVEPOINT_ROLLBACK ){
 74730        rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
 74731      }
 74732      if( rc==SQLITE_OK ){
 74733        rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
 74734      }
 74735    }
 74736  
 74737    /* If the statement transaction is being rolled back, also restore the 
 74738    ** database handles deferred constraint counter to the value it had when 
 74739    ** the statement transaction was opened.  */
 74740    if( eOp==SAVEPOINT_ROLLBACK ){
 74741      db->nDeferredCons = p->nStmtDefCons;
 74742      db->nDeferredImmCons = p->nStmtDefImmCons;
 74743    }
 74744    return rc;
 74745  }
 74746  SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
 74747    if( p->db->nStatement && p->iStatement ){
 74748      return vdbeCloseStatement(p, eOp);
 74749    }
 74750    return SQLITE_OK;
 74751  }
 74752  
 74753  
 74754  /*
 74755  ** This function is called when a transaction opened by the database 
 74756  ** handle associated with the VM passed as an argument is about to be 
 74757  ** committed. If there are outstanding deferred foreign key constraint
 74758  ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
 74759  **
 74760  ** If there are outstanding FK violations and this function returns 
 74761  ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
 74762  ** and write an error message to it. Then return SQLITE_ERROR.
 74763  */
 74764  #ifndef SQLITE_OMIT_FOREIGN_KEY
 74765  SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
 74766    sqlite3 *db = p->db;
 74767    if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0) 
 74768     || (!deferred && p->nFkConstraint>0) 
 74769    ){
 74770      p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
 74771      p->errorAction = OE_Abort;
 74772      sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
 74773      return SQLITE_ERROR;
 74774    }
 74775    return SQLITE_OK;
 74776  }
 74777  #endif
 74778  
 74779  /*
 74780  ** This routine is called the when a VDBE tries to halt.  If the VDBE
 74781  ** has made changes and is in autocommit mode, then commit those
 74782  ** changes.  If a rollback is needed, then do the rollback.
 74783  **
 74784  ** This routine is the only way to move the state of a VM from
 74785  ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
 74786  ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
 74787  **
 74788  ** Return an error code.  If the commit could not complete because of
 74789  ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
 74790  ** means the close did not happen and needs to be repeated.
 74791  */
 74792  SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
 74793    int rc;                         /* Used to store transient return codes */
 74794    sqlite3 *db = p->db;
 74795  
 74796    /* This function contains the logic that determines if a statement or
 74797    ** transaction will be committed or rolled back as a result of the
 74798    ** execution of this virtual machine. 
 74799    **
 74800    ** If any of the following errors occur:
 74801    **
 74802    **     SQLITE_NOMEM
 74803    **     SQLITE_IOERR
 74804    **     SQLITE_FULL
 74805    **     SQLITE_INTERRUPT
 74806    **
 74807    ** Then the internal cache might have been left in an inconsistent
 74808    ** state.  We need to rollback the statement transaction, if there is
 74809    ** one, or the complete transaction if there is no statement transaction.
 74810    */
 74811  
 74812    if( p->magic!=VDBE_MAGIC_RUN ){
 74813      return SQLITE_OK;
 74814    }
 74815    if( db->mallocFailed ){
 74816      p->rc = SQLITE_NOMEM_BKPT;
 74817    }
 74818    closeAllCursors(p);
 74819    checkActiveVdbeCnt(db);
 74820  
 74821    /* No commit or rollback needed if the program never started or if the
 74822    ** SQL statement does not read or write a database file.  */
 74823    if( p->pc>=0 && p->bIsReader ){
 74824      int mrc;   /* Primary error code from p->rc */
 74825      int eStatementOp = 0;
 74826      int isSpecialError;            /* Set to true if a 'special' error */
 74827  
 74828      /* Lock all btrees used by the statement */
 74829      sqlite3VdbeEnter(p);
 74830  
 74831      /* Check for one of the special errors */
 74832      mrc = p->rc & 0xff;
 74833      isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
 74834                       || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
 74835      if( isSpecialError ){
 74836        /* If the query was read-only and the error code is SQLITE_INTERRUPT, 
 74837        ** no rollback is necessary. Otherwise, at least a savepoint 
 74838        ** transaction must be rolled back to restore the database to a 
 74839        ** consistent state.
 74840        **
 74841        ** Even if the statement is read-only, it is important to perform
 74842        ** a statement or transaction rollback operation. If the error 
 74843        ** occurred while writing to the journal, sub-journal or database
 74844        ** file as part of an effort to free up cache space (see function
 74845        ** pagerStress() in pager.c), the rollback is required to restore 
 74846        ** the pager to a consistent state.
 74847        */
 74848        if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
 74849          if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
 74850            eStatementOp = SAVEPOINT_ROLLBACK;
 74851          }else{
 74852            /* We are forced to roll back the active transaction. Before doing
 74853            ** so, abort any other statements this handle currently has active.
 74854            */
 74855            sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
 74856            sqlite3CloseSavepoints(db);
 74857            db->autoCommit = 1;
 74858            p->nChange = 0;
 74859          }
 74860        }
 74861      }
 74862  
 74863      /* Check for immediate foreign key violations. */
 74864      if( p->rc==SQLITE_OK ){
 74865        sqlite3VdbeCheckFk(p, 0);
 74866      }
 74867    
 74868      /* If the auto-commit flag is set and this is the only active writer 
 74869      ** VM, then we do either a commit or rollback of the current transaction. 
 74870      **
 74871      ** Note: This block also runs if one of the special errors handled 
 74872      ** above has occurred. 
 74873      */
 74874      if( !sqlite3VtabInSync(db) 
 74875       && db->autoCommit 
 74876       && db->nVdbeWrite==(p->readOnly==0) 
 74877      ){
 74878        if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
 74879          rc = sqlite3VdbeCheckFk(p, 1);
 74880          if( rc!=SQLITE_OK ){
 74881            if( NEVER(p->readOnly) ){
 74882              sqlite3VdbeLeave(p);
 74883              return SQLITE_ERROR;
 74884            }
 74885            rc = SQLITE_CONSTRAINT_FOREIGNKEY;
 74886          }else{ 
 74887            /* The auto-commit flag is true, the vdbe program was successful 
 74888            ** or hit an 'OR FAIL' constraint and there are no deferred foreign
 74889            ** key constraints to hold up the transaction. This means a commit 
 74890            ** is required. */
 74891            rc = vdbeCommit(db, p);
 74892          }
 74893          if( rc==SQLITE_BUSY && p->readOnly ){
 74894            sqlite3VdbeLeave(p);
 74895            return SQLITE_BUSY;
 74896          }else if( rc!=SQLITE_OK ){
 74897            p->rc = rc;
 74898            sqlite3RollbackAll(db, SQLITE_OK);
 74899            p->nChange = 0;
 74900          }else{
 74901            db->nDeferredCons = 0;
 74902            db->nDeferredImmCons = 0;
 74903            db->flags &= ~SQLITE_DeferFKs;
 74904            sqlite3CommitInternalChanges(db);
 74905          }
 74906        }else{
 74907          sqlite3RollbackAll(db, SQLITE_OK);
 74908          p->nChange = 0;
 74909        }
 74910        db->nStatement = 0;
 74911      }else if( eStatementOp==0 ){
 74912        if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
 74913          eStatementOp = SAVEPOINT_RELEASE;
 74914        }else if( p->errorAction==OE_Abort ){
 74915          eStatementOp = SAVEPOINT_ROLLBACK;
 74916        }else{
 74917          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
 74918          sqlite3CloseSavepoints(db);
 74919          db->autoCommit = 1;
 74920          p->nChange = 0;
 74921        }
 74922      }
 74923    
 74924      /* If eStatementOp is non-zero, then a statement transaction needs to
 74925      ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
 74926      ** do so. If this operation returns an error, and the current statement
 74927      ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
 74928      ** current statement error code.
 74929      */
 74930      if( eStatementOp ){
 74931        rc = sqlite3VdbeCloseStatement(p, eStatementOp);
 74932        if( rc ){
 74933          if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
 74934            p->rc = rc;
 74935            sqlite3DbFree(db, p->zErrMsg);
 74936            p->zErrMsg = 0;
 74937          }
 74938          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
 74939          sqlite3CloseSavepoints(db);
 74940          db->autoCommit = 1;
 74941          p->nChange = 0;
 74942        }
 74943      }
 74944    
 74945      /* If this was an INSERT, UPDATE or DELETE and no statement transaction
 74946      ** has been rolled back, update the database connection change-counter. 
 74947      */
 74948      if( p->changeCntOn ){
 74949        if( eStatementOp!=SAVEPOINT_ROLLBACK ){
 74950          sqlite3VdbeSetChanges(db, p->nChange);
 74951        }else{
 74952          sqlite3VdbeSetChanges(db, 0);
 74953        }
 74954        p->nChange = 0;
 74955      }
 74956  
 74957      /* Release the locks */
 74958      sqlite3VdbeLeave(p);
 74959    }
 74960  
 74961    /* We have successfully halted and closed the VM.  Record this fact. */
 74962    if( p->pc>=0 ){
 74963      db->nVdbeActive--;
 74964      if( !p->readOnly ) db->nVdbeWrite--;
 74965      if( p->bIsReader ) db->nVdbeRead--;
 74966      assert( db->nVdbeActive>=db->nVdbeRead );
 74967      assert( db->nVdbeRead>=db->nVdbeWrite );
 74968      assert( db->nVdbeWrite>=0 );
 74969    }
 74970    p->magic = VDBE_MAGIC_HALT;
 74971    checkActiveVdbeCnt(db);
 74972    if( db->mallocFailed ){
 74973      p->rc = SQLITE_NOMEM_BKPT;
 74974    }
 74975  
 74976    /* If the auto-commit flag is set to true, then any locks that were held
 74977    ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
 74978    ** to invoke any required unlock-notify callbacks.
 74979    */
 74980    if( db->autoCommit ){
 74981      sqlite3ConnectionUnlocked(db);
 74982    }
 74983  
 74984    assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
 74985    return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
 74986  }
 74987  
 74988  
 74989  /*
 74990  ** Each VDBE holds the result of the most recent sqlite3_step() call
 74991  ** in p->rc.  This routine sets that result back to SQLITE_OK.
 74992  */
 74993  SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
 74994    p->rc = SQLITE_OK;
 74995  }
 74996  
 74997  /*
 74998  ** Copy the error code and error message belonging to the VDBE passed
 74999  ** as the first argument to its database handle (so that they will be 
 75000  ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
 75001  **
 75002  ** This function does not clear the VDBE error code or message, just
 75003  ** copies them to the database handle.
 75004  */
 75005  SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
 75006    sqlite3 *db = p->db;
 75007    int rc = p->rc;
 75008    if( p->zErrMsg ){
 75009      db->bBenignMalloc++;
 75010      sqlite3BeginBenignMalloc();
 75011      if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
 75012      sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
 75013      sqlite3EndBenignMalloc();
 75014      db->bBenignMalloc--;
 75015    }else if( db->pErr ){
 75016      sqlite3ValueSetNull(db->pErr);
 75017    }
 75018    db->errCode = rc;
 75019    return rc;
 75020  }
 75021  
 75022  #ifdef SQLITE_ENABLE_SQLLOG
 75023  /*
 75024  ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run, 
 75025  ** invoke it.
 75026  */
 75027  static void vdbeInvokeSqllog(Vdbe *v){
 75028    if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
 75029      char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
 75030      assert( v->db->init.busy==0 );
 75031      if( zExpanded ){
 75032        sqlite3GlobalConfig.xSqllog(
 75033            sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
 75034        );
 75035        sqlite3DbFree(v->db, zExpanded);
 75036      }
 75037    }
 75038  }
 75039  #else
 75040  # define vdbeInvokeSqllog(x)
 75041  #endif
 75042  
 75043  /*
 75044  ** Clean up a VDBE after execution but do not delete the VDBE just yet.
 75045  ** Write any error messages into *pzErrMsg.  Return the result code.
 75046  **
 75047  ** After this routine is run, the VDBE should be ready to be executed
 75048  ** again.
 75049  **
 75050  ** To look at it another way, this routine resets the state of the
 75051  ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
 75052  ** VDBE_MAGIC_INIT.
 75053  */
 75054  SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
 75055  #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
 75056    int i;
 75057  #endif
 75058  
 75059    sqlite3 *db;
 75060    db = p->db;
 75061  
 75062    /* If the VM did not run to completion or if it encountered an
 75063    ** error, then it might not have been halted properly.  So halt
 75064    ** it now.
 75065    */
 75066    sqlite3VdbeHalt(p);
 75067  
 75068    /* If the VDBE has be run even partially, then transfer the error code
 75069    ** and error message from the VDBE into the main database structure.  But
 75070    ** if the VDBE has just been set to run but has not actually executed any
 75071    ** instructions yet, leave the main database error information unchanged.
 75072    */
 75073    if( p->pc>=0 ){
 75074      vdbeInvokeSqllog(p);
 75075      sqlite3VdbeTransferError(p);
 75076      if( p->runOnlyOnce ) p->expired = 1;
 75077    }else if( p->rc && p->expired ){
 75078      /* The expired flag was set on the VDBE before the first call
 75079      ** to sqlite3_step(). For consistency (since sqlite3_step() was
 75080      ** called), set the database error in this case as well.
 75081      */
 75082      sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
 75083    }
 75084  
 75085    /* Reset register contents and reclaim error message memory.
 75086    */
 75087  #ifdef SQLITE_DEBUG
 75088    /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
 75089    ** Vdbe.aMem[] arrays have already been cleaned up.  */
 75090    if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
 75091    if( p->aMem ){
 75092      for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
 75093    }
 75094  #endif
 75095    sqlite3DbFree(db, p->zErrMsg);
 75096    p->zErrMsg = 0;
 75097    p->pResultSet = 0;
 75098  
 75099    /* Save profiling information from this VDBE run.
 75100    */
 75101  #ifdef VDBE_PROFILE
 75102    {
 75103      FILE *out = fopen("vdbe_profile.out", "a");
 75104      if( out ){
 75105        fprintf(out, "---- ");
 75106        for(i=0; i<p->nOp; i++){
 75107          fprintf(out, "%02x", p->aOp[i].opcode);
 75108        }
 75109        fprintf(out, "\n");
 75110        if( p->zSql ){
 75111          char c, pc = 0;
 75112          fprintf(out, "-- ");
 75113          for(i=0; (c = p->zSql[i])!=0; i++){
 75114            if( pc=='\n' ) fprintf(out, "-- ");
 75115            putc(c, out);
 75116            pc = c;
 75117          }
 75118          if( pc!='\n' ) fprintf(out, "\n");
 75119        }
 75120        for(i=0; i<p->nOp; i++){
 75121          char zHdr[100];
 75122          sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
 75123             p->aOp[i].cnt,
 75124             p->aOp[i].cycles,
 75125             p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
 75126          );
 75127          fprintf(out, "%s", zHdr);
 75128          sqlite3VdbePrintOp(out, i, &p->aOp[i]);
 75129        }
 75130        fclose(out);
 75131      }
 75132    }
 75133  #endif
 75134    p->magic = VDBE_MAGIC_RESET;
 75135    return p->rc & db->errMask;
 75136  }
 75137   
 75138  /*
 75139  ** Clean up and delete a VDBE after execution.  Return an integer which is
 75140  ** the result code.  Write any error message text into *pzErrMsg.
 75141  */
 75142  SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
 75143    int rc = SQLITE_OK;
 75144    if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
 75145      rc = sqlite3VdbeReset(p);
 75146      assert( (rc & p->db->errMask)==rc );
 75147    }
 75148    sqlite3VdbeDelete(p);
 75149    return rc;
 75150  }
 75151  
 75152  /*
 75153  ** If parameter iOp is less than zero, then invoke the destructor for
 75154  ** all auxiliary data pointers currently cached by the VM passed as
 75155  ** the first argument.
 75156  **
 75157  ** Or, if iOp is greater than or equal to zero, then the destructor is
 75158  ** only invoked for those auxiliary data pointers created by the user 
 75159  ** function invoked by the OP_Function opcode at instruction iOp of 
 75160  ** VM pVdbe, and only then if:
 75161  **
 75162  **    * the associated function parameter is the 32nd or later (counting
 75163  **      from left to right), or
 75164  **
 75165  **    * the corresponding bit in argument mask is clear (where the first
 75166  **      function parameter corresponds to bit 0 etc.).
 75167  */
 75168  SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
 75169    while( *pp ){
 75170      AuxData *pAux = *pp;
 75171      if( (iOp<0)
 75172       || (pAux->iAuxOp==iOp
 75173            && pAux->iAuxArg>=0
 75174            && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
 75175      ){
 75176        testcase( pAux->iAuxArg==31 );
 75177        if( pAux->xDeleteAux ){
 75178          pAux->xDeleteAux(pAux->pAux);
 75179        }
 75180        *pp = pAux->pNextAux;
 75181        sqlite3DbFree(db, pAux);
 75182      }else{
 75183        pp= &pAux->pNextAux;
 75184      }
 75185    }
 75186  }
 75187  
 75188  /*
 75189  ** Free all memory associated with the Vdbe passed as the second argument,
 75190  ** except for object itself, which is preserved.
 75191  **
 75192  ** The difference between this function and sqlite3VdbeDelete() is that
 75193  ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
 75194  ** the database connection and frees the object itself.
 75195  */
 75196  SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
 75197    SubProgram *pSub, *pNext;
 75198    assert( p->db==0 || p->db==db );
 75199    releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
 75200    for(pSub=p->pProgram; pSub; pSub=pNext){
 75201      pNext = pSub->pNext;
 75202      vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
 75203      sqlite3DbFree(db, pSub);
 75204    }
 75205    if( p->magic!=VDBE_MAGIC_INIT ){
 75206      releaseMemArray(p->aVar, p->nVar);
 75207      sqlite3DbFree(db, p->pVList);
 75208      sqlite3DbFree(db, p->pFree);
 75209    }
 75210    vdbeFreeOpArray(db, p->aOp, p->nOp);
 75211    sqlite3DbFree(db, p->aColName);
 75212    sqlite3DbFree(db, p->zSql);
 75213  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 75214    {
 75215      int i;
 75216      for(i=0; i<p->nScan; i++){
 75217        sqlite3DbFree(db, p->aScan[i].zName);
 75218      }
 75219      sqlite3DbFree(db, p->aScan);
 75220    }
 75221  #endif
 75222  }
 75223  
 75224  /*
 75225  ** Delete an entire VDBE.
 75226  */
 75227  SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
 75228    sqlite3 *db;
 75229  
 75230    if( NEVER(p==0) ) return;
 75231    db = p->db;
 75232    assert( sqlite3_mutex_held(db->mutex) );
 75233    sqlite3VdbeClearObject(db, p);
 75234    if( p->pPrev ){
 75235      p->pPrev->pNext = p->pNext;
 75236    }else{
 75237      assert( db->pVdbe==p );
 75238      db->pVdbe = p->pNext;
 75239    }
 75240    if( p->pNext ){
 75241      p->pNext->pPrev = p->pPrev;
 75242    }
 75243    p->magic = VDBE_MAGIC_DEAD;
 75244    p->db = 0;
 75245    sqlite3DbFreeNN(db, p);
 75246  }
 75247  
 75248  /*
 75249  ** The cursor "p" has a pending seek operation that has not yet been
 75250  ** carried out.  Seek the cursor now.  If an error occurs, return
 75251  ** the appropriate error code.
 75252  */
 75253  static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
 75254    int res, rc;
 75255  #ifdef SQLITE_TEST
 75256    extern int sqlite3_search_count;
 75257  #endif
 75258    assert( p->deferredMoveto );
 75259    assert( p->isTable );
 75260    assert( p->eCurType==CURTYPE_BTREE );
 75261    rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
 75262    if( rc ) return rc;
 75263    if( res!=0 ) return SQLITE_CORRUPT_BKPT;
 75264  #ifdef SQLITE_TEST
 75265    sqlite3_search_count++;
 75266  #endif
 75267    p->deferredMoveto = 0;
 75268    p->cacheStatus = CACHE_STALE;
 75269    return SQLITE_OK;
 75270  }
 75271  
 75272  /*
 75273  ** Something has moved cursor "p" out of place.  Maybe the row it was
 75274  ** pointed to was deleted out from under it.  Or maybe the btree was
 75275  ** rebalanced.  Whatever the cause, try to restore "p" to the place it
 75276  ** is supposed to be pointing.  If the row was deleted out from under the
 75277  ** cursor, set the cursor to point to a NULL row.
 75278  */
 75279  static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
 75280    int isDifferentRow, rc;
 75281    assert( p->eCurType==CURTYPE_BTREE );
 75282    assert( p->uc.pCursor!=0 );
 75283    assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
 75284    rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
 75285    p->cacheStatus = CACHE_STALE;
 75286    if( isDifferentRow ) p->nullRow = 1;
 75287    return rc;
 75288  }
 75289  
 75290  /*
 75291  ** Check to ensure that the cursor is valid.  Restore the cursor
 75292  ** if need be.  Return any I/O error from the restore operation.
 75293  */
 75294  SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
 75295    assert( p->eCurType==CURTYPE_BTREE );
 75296    if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
 75297      return handleMovedCursor(p);
 75298    }
 75299    return SQLITE_OK;
 75300  }
 75301  
 75302  /*
 75303  ** Make sure the cursor p is ready to read or write the row to which it
 75304  ** was last positioned.  Return an error code if an OOM fault or I/O error
 75305  ** prevents us from positioning the cursor to its correct position.
 75306  **
 75307  ** If a MoveTo operation is pending on the given cursor, then do that
 75308  ** MoveTo now.  If no move is pending, check to see if the row has been
 75309  ** deleted out from under the cursor and if it has, mark the row as
 75310  ** a NULL row.
 75311  **
 75312  ** If the cursor is already pointing to the correct row and that row has
 75313  ** not been deleted out from under the cursor, then this routine is a no-op.
 75314  */
 75315  SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
 75316    VdbeCursor *p = *pp;
 75317    assert( p->eCurType==CURTYPE_BTREE || p->eCurType==CURTYPE_PSEUDO );
 75318    if( p->deferredMoveto ){
 75319      int iMap;
 75320      if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
 75321        *pp = p->pAltCursor;
 75322        *piCol = iMap - 1;
 75323        return SQLITE_OK;
 75324      }
 75325      return handleDeferredMoveto(p);
 75326    }
 75327    if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
 75328      return handleMovedCursor(p);
 75329    }
 75330    return SQLITE_OK;
 75331  }
 75332  
 75333  /*
 75334  ** The following functions:
 75335  **
 75336  ** sqlite3VdbeSerialType()
 75337  ** sqlite3VdbeSerialTypeLen()
 75338  ** sqlite3VdbeSerialLen()
 75339  ** sqlite3VdbeSerialPut()
 75340  ** sqlite3VdbeSerialGet()
 75341  **
 75342  ** encapsulate the code that serializes values for storage in SQLite
 75343  ** data and index records. Each serialized value consists of a
 75344  ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
 75345  ** integer, stored as a varint.
 75346  **
 75347  ** In an SQLite index record, the serial type is stored directly before
 75348  ** the blob of data that it corresponds to. In a table record, all serial
 75349  ** types are stored at the start of the record, and the blobs of data at
 75350  ** the end. Hence these functions allow the caller to handle the
 75351  ** serial-type and data blob separately.
 75352  **
 75353  ** The following table describes the various storage classes for data:
 75354  **
 75355  **   serial type        bytes of data      type
 75356  **   --------------     ---------------    ---------------
 75357  **      0                     0            NULL
 75358  **      1                     1            signed integer
 75359  **      2                     2            signed integer
 75360  **      3                     3            signed integer
 75361  **      4                     4            signed integer
 75362  **      5                     6            signed integer
 75363  **      6                     8            signed integer
 75364  **      7                     8            IEEE float
 75365  **      8                     0            Integer constant 0
 75366  **      9                     0            Integer constant 1
 75367  **     10,11                               reserved for expansion
 75368  **    N>=12 and even       (N-12)/2        BLOB
 75369  **    N>=13 and odd        (N-13)/2        text
 75370  **
 75371  ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
 75372  ** of SQLite will not understand those serial types.
 75373  */
 75374  
 75375  /*
 75376  ** Return the serial-type for the value stored in pMem.
 75377  */
 75378  SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
 75379    int flags = pMem->flags;
 75380    u32 n;
 75381  
 75382    assert( pLen!=0 );
 75383    if( flags&MEM_Null ){
 75384      *pLen = 0;
 75385      return 0;
 75386    }
 75387    if( flags&MEM_Int ){
 75388      /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
 75389  #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
 75390      i64 i = pMem->u.i;
 75391      u64 u;
 75392      if( i<0 ){
 75393        u = ~i;
 75394      }else{
 75395        u = i;
 75396      }
 75397      if( u<=127 ){
 75398        if( (i&1)==i && file_format>=4 ){
 75399          *pLen = 0;
 75400          return 8+(u32)u;
 75401        }else{
 75402          *pLen = 1;
 75403          return 1;
 75404        }
 75405      }
 75406      if( u<=32767 ){ *pLen = 2; return 2; }
 75407      if( u<=8388607 ){ *pLen = 3; return 3; }
 75408      if( u<=2147483647 ){ *pLen = 4; return 4; }
 75409      if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
 75410      *pLen = 8;
 75411      return 6;
 75412    }
 75413    if( flags&MEM_Real ){
 75414      *pLen = 8;
 75415      return 7;
 75416    }
 75417    assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
 75418    assert( pMem->n>=0 );
 75419    n = (u32)pMem->n;
 75420    if( flags & MEM_Zero ){
 75421      n += pMem->u.nZero;
 75422    }
 75423    *pLen = n;
 75424    return ((n*2) + 12 + ((flags&MEM_Str)!=0));
 75425  }
 75426  
 75427  /*
 75428  ** The sizes for serial types less than 128
 75429  */
 75430  static const u8 sqlite3SmallTypeSizes[] = {
 75431          /*  0   1   2   3   4   5   6   7   8   9 */   
 75432  /*   0 */   0,  1,  2,  3,  4,  6,  8,  8,  0,  0,
 75433  /*  10 */   0,  0,  0,  0,  1,  1,  2,  2,  3,  3,
 75434  /*  20 */   4,  4,  5,  5,  6,  6,  7,  7,  8,  8,
 75435  /*  30 */   9,  9, 10, 10, 11, 11, 12, 12, 13, 13,
 75436  /*  40 */  14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
 75437  /*  50 */  19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
 75438  /*  60 */  24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
 75439  /*  70 */  29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
 75440  /*  80 */  34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
 75441  /*  90 */  39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
 75442  /* 100 */  44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
 75443  /* 110 */  49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
 75444  /* 120 */  54, 54, 55, 55, 56, 56, 57, 57
 75445  };
 75446  
 75447  /*
 75448  ** Return the length of the data corresponding to the supplied serial-type.
 75449  */
 75450  SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
 75451    if( serial_type>=128 ){
 75452      return (serial_type-12)/2;
 75453    }else{
 75454      assert( serial_type<12 
 75455              || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
 75456      return sqlite3SmallTypeSizes[serial_type];
 75457    }
 75458  }
 75459  SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
 75460    assert( serial_type<128 );
 75461    return sqlite3SmallTypeSizes[serial_type];  
 75462  }
 75463  
 75464  /*
 75465  ** If we are on an architecture with mixed-endian floating 
 75466  ** points (ex: ARM7) then swap the lower 4 bytes with the 
 75467  ** upper 4 bytes.  Return the result.
 75468  **
 75469  ** For most architectures, this is a no-op.
 75470  **
 75471  ** (later):  It is reported to me that the mixed-endian problem
 75472  ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
 75473  ** that early versions of GCC stored the two words of a 64-bit
 75474  ** float in the wrong order.  And that error has been propagated
 75475  ** ever since.  The blame is not necessarily with GCC, though.
 75476  ** GCC might have just copying the problem from a prior compiler.
 75477  ** I am also told that newer versions of GCC that follow a different
 75478  ** ABI get the byte order right.
 75479  **
 75480  ** Developers using SQLite on an ARM7 should compile and run their
 75481  ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
 75482  ** enabled, some asserts below will ensure that the byte order of
 75483  ** floating point values is correct.
 75484  **
 75485  ** (2007-08-30)  Frank van Vugt has studied this problem closely
 75486  ** and has send his findings to the SQLite developers.  Frank
 75487  ** writes that some Linux kernels offer floating point hardware
 75488  ** emulation that uses only 32-bit mantissas instead of a full 
 75489  ** 48-bits as required by the IEEE standard.  (This is the
 75490  ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
 75491  ** byte swapping becomes very complicated.  To avoid problems,
 75492  ** the necessary byte swapping is carried out using a 64-bit integer
 75493  ** rather than a 64-bit float.  Frank assures us that the code here
 75494  ** works for him.  We, the developers, have no way to independently
 75495  ** verify this, but Frank seems to know what he is talking about
 75496  ** so we trust him.
 75497  */
 75498  #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
 75499  static u64 floatSwap(u64 in){
 75500    union {
 75501      u64 r;
 75502      u32 i[2];
 75503    } u;
 75504    u32 t;
 75505  
 75506    u.r = in;
 75507    t = u.i[0];
 75508    u.i[0] = u.i[1];
 75509    u.i[1] = t;
 75510    return u.r;
 75511  }
 75512  # define swapMixedEndianFloat(X)  X = floatSwap(X)
 75513  #else
 75514  # define swapMixedEndianFloat(X)
 75515  #endif
 75516  
 75517  /*
 75518  ** Write the serialized data blob for the value stored in pMem into 
 75519  ** buf. It is assumed that the caller has allocated sufficient space.
 75520  ** Return the number of bytes written.
 75521  **
 75522  ** nBuf is the amount of space left in buf[].  The caller is responsible
 75523  ** for allocating enough space to buf[] to hold the entire field, exclusive
 75524  ** of the pMem->u.nZero bytes for a MEM_Zero value.
 75525  **
 75526  ** Return the number of bytes actually written into buf[].  The number
 75527  ** of bytes in the zero-filled tail is included in the return value only
 75528  ** if those bytes were zeroed in buf[].
 75529  */ 
 75530  SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
 75531    u32 len;
 75532  
 75533    /* Integer and Real */
 75534    if( serial_type<=7 && serial_type>0 ){
 75535      u64 v;
 75536      u32 i;
 75537      if( serial_type==7 ){
 75538        assert( sizeof(v)==sizeof(pMem->u.r) );
 75539        memcpy(&v, &pMem->u.r, sizeof(v));
 75540        swapMixedEndianFloat(v);
 75541      }else{
 75542        v = pMem->u.i;
 75543      }
 75544      len = i = sqlite3SmallTypeSizes[serial_type];
 75545      assert( i>0 );
 75546      do{
 75547        buf[--i] = (u8)(v&0xFF);
 75548        v >>= 8;
 75549      }while( i );
 75550      return len;
 75551    }
 75552  
 75553    /* String or blob */
 75554    if( serial_type>=12 ){
 75555      assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
 75556               == (int)sqlite3VdbeSerialTypeLen(serial_type) );
 75557      len = pMem->n;
 75558      if( len>0 ) memcpy(buf, pMem->z, len);
 75559      return len;
 75560    }
 75561  
 75562    /* NULL or constants 0 or 1 */
 75563    return 0;
 75564  }
 75565  
 75566  /* Input "x" is a sequence of unsigned characters that represent a
 75567  ** big-endian integer.  Return the equivalent native integer
 75568  */
 75569  #define ONE_BYTE_INT(x)    ((i8)(x)[0])
 75570  #define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
 75571  #define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
 75572  #define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
 75573  #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
 75574  
 75575  /*
 75576  ** Deserialize the data blob pointed to by buf as serial type serial_type
 75577  ** and store the result in pMem.  Return the number of bytes read.
 75578  **
 75579  ** This function is implemented as two separate routines for performance.
 75580  ** The few cases that require local variables are broken out into a separate
 75581  ** routine so that in most cases the overhead of moving the stack pointer
 75582  ** is avoided.
 75583  */ 
 75584  static u32 SQLITE_NOINLINE serialGet(
 75585    const unsigned char *buf,     /* Buffer to deserialize from */
 75586    u32 serial_type,              /* Serial type to deserialize */
 75587    Mem *pMem                     /* Memory cell to write value into */
 75588  ){
 75589    u64 x = FOUR_BYTE_UINT(buf);
 75590    u32 y = FOUR_BYTE_UINT(buf+4);
 75591    x = (x<<32) + y;
 75592    if( serial_type==6 ){
 75593      /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
 75594      ** twos-complement integer. */
 75595      pMem->u.i = *(i64*)&x;
 75596      pMem->flags = MEM_Int;
 75597      testcase( pMem->u.i<0 );
 75598    }else{
 75599      /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
 75600      ** floating point number. */
 75601  #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
 75602      /* Verify that integers and floating point values use the same
 75603      ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
 75604      ** defined that 64-bit floating point values really are mixed
 75605      ** endian.
 75606      */
 75607      static const u64 t1 = ((u64)0x3ff00000)<<32;
 75608      static const double r1 = 1.0;
 75609      u64 t2 = t1;
 75610      swapMixedEndianFloat(t2);
 75611      assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
 75612  #endif
 75613      assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
 75614      swapMixedEndianFloat(x);
 75615      memcpy(&pMem->u.r, &x, sizeof(x));
 75616      pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
 75617    }
 75618    return 8;
 75619  }
 75620  SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
 75621    const unsigned char *buf,     /* Buffer to deserialize from */
 75622    u32 serial_type,              /* Serial type to deserialize */
 75623    Mem *pMem                     /* Memory cell to write value into */
 75624  ){
 75625    switch( serial_type ){
 75626      case 10:   /* Reserved for future use */
 75627      case 11:   /* Reserved for future use */
 75628      case 0: {  /* Null */
 75629        /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
 75630        pMem->flags = MEM_Null;
 75631        break;
 75632      }
 75633      case 1: {
 75634        /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
 75635        ** integer. */
 75636        pMem->u.i = ONE_BYTE_INT(buf);
 75637        pMem->flags = MEM_Int;
 75638        testcase( pMem->u.i<0 );
 75639        return 1;
 75640      }
 75641      case 2: { /* 2-byte signed integer */
 75642        /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
 75643        ** twos-complement integer. */
 75644        pMem->u.i = TWO_BYTE_INT(buf);
 75645        pMem->flags = MEM_Int;
 75646        testcase( pMem->u.i<0 );
 75647        return 2;
 75648      }
 75649      case 3: { /* 3-byte signed integer */
 75650        /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
 75651        ** twos-complement integer. */
 75652        pMem->u.i = THREE_BYTE_INT(buf);
 75653        pMem->flags = MEM_Int;
 75654        testcase( pMem->u.i<0 );
 75655        return 3;
 75656      }
 75657      case 4: { /* 4-byte signed integer */
 75658        /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
 75659        ** twos-complement integer. */
 75660        pMem->u.i = FOUR_BYTE_INT(buf);
 75661  #ifdef __HP_cc 
 75662        /* Work around a sign-extension bug in the HP compiler for HP/UX */
 75663        if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
 75664  #endif
 75665        pMem->flags = MEM_Int;
 75666        testcase( pMem->u.i<0 );
 75667        return 4;
 75668      }
 75669      case 5: { /* 6-byte signed integer */
 75670        /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
 75671        ** twos-complement integer. */
 75672        pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
 75673        pMem->flags = MEM_Int;
 75674        testcase( pMem->u.i<0 );
 75675        return 6;
 75676      }
 75677      case 6:   /* 8-byte signed integer */
 75678      case 7: { /* IEEE floating point */
 75679        /* These use local variables, so do them in a separate routine
 75680        ** to avoid having to move the frame pointer in the common case */
 75681        return serialGet(buf,serial_type,pMem);
 75682      }
 75683      case 8:    /* Integer 0 */
 75684      case 9: {  /* Integer 1 */
 75685        /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
 75686        /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
 75687        pMem->u.i = serial_type-8;
 75688        pMem->flags = MEM_Int;
 75689        return 0;
 75690      }
 75691      default: {
 75692        /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
 75693        ** length.
 75694        ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
 75695        ** (N-13)/2 bytes in length. */
 75696        static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
 75697        pMem->z = (char *)buf;
 75698        pMem->n = (serial_type-12)/2;
 75699        pMem->flags = aFlag[serial_type&1];
 75700        return pMem->n;
 75701      }
 75702    }
 75703    return 0;
 75704  }
 75705  /*
 75706  ** This routine is used to allocate sufficient space for an UnpackedRecord
 75707  ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
 75708  ** the first argument is a pointer to KeyInfo structure pKeyInfo.
 75709  **
 75710  ** The space is either allocated using sqlite3DbMallocRaw() or from within
 75711  ** the unaligned buffer passed via the second and third arguments (presumably
 75712  ** stack space). If the former, then *ppFree is set to a pointer that should
 75713  ** be eventually freed by the caller using sqlite3DbFree(). Or, if the 
 75714  ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
 75715  ** before returning.
 75716  **
 75717  ** If an OOM error occurs, NULL is returned.
 75718  */
 75719  SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
 75720    KeyInfo *pKeyInfo               /* Description of the record */
 75721  ){
 75722    UnpackedRecord *p;              /* Unpacked record to return */
 75723    int nByte;                      /* Number of bytes required for *p */
 75724    nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
 75725    p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
 75726    if( !p ) return 0;
 75727    p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
 75728    assert( pKeyInfo->aSortOrder!=0 );
 75729    p->pKeyInfo = pKeyInfo;
 75730    p->nField = pKeyInfo->nKeyField + 1;
 75731    return p;
 75732  }
 75733  
 75734  /*
 75735  ** Given the nKey-byte encoding of a record in pKey[], populate the 
 75736  ** UnpackedRecord structure indicated by the fourth argument with the
 75737  ** contents of the decoded record.
 75738  */ 
 75739  SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
 75740    KeyInfo *pKeyInfo,     /* Information about the record format */
 75741    int nKey,              /* Size of the binary record */
 75742    const void *pKey,      /* The binary record */
 75743    UnpackedRecord *p      /* Populate this structure before returning. */
 75744  ){
 75745    const unsigned char *aKey = (const unsigned char *)pKey;
 75746    int d; 
 75747    u32 idx;                        /* Offset in aKey[] to read from */
 75748    u16 u;                          /* Unsigned loop counter */
 75749    u32 szHdr;
 75750    Mem *pMem = p->aMem;
 75751  
 75752    p->default_rc = 0;
 75753    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 75754    idx = getVarint32(aKey, szHdr);
 75755    d = szHdr;
 75756    u = 0;
 75757    while( idx<szHdr && d<=nKey ){
 75758      u32 serial_type;
 75759  
 75760      idx += getVarint32(&aKey[idx], serial_type);
 75761      pMem->enc = pKeyInfo->enc;
 75762      pMem->db = pKeyInfo->db;
 75763      /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
 75764      pMem->szMalloc = 0;
 75765      pMem->z = 0;
 75766      d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
 75767      pMem++;
 75768      if( (++u)>=p->nField ) break;
 75769    }
 75770    assert( u<=pKeyInfo->nKeyField + 1 );
 75771    p->nField = u;
 75772  }
 75773  
 75774  #ifdef SQLITE_DEBUG
 75775  /*
 75776  ** This function compares two index or table record keys in the same way
 75777  ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
 75778  ** this function deserializes and compares values using the
 75779  ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
 75780  ** in assert() statements to ensure that the optimized code in
 75781  ** sqlite3VdbeRecordCompare() returns results with these two primitives.
 75782  **
 75783  ** Return true if the result of comparison is equivalent to desiredResult.
 75784  ** Return false if there is a disagreement.
 75785  */
 75786  static int vdbeRecordCompareDebug(
 75787    int nKey1, const void *pKey1, /* Left key */
 75788    const UnpackedRecord *pPKey2, /* Right key */
 75789    int desiredResult             /* Correct answer */
 75790  ){
 75791    u32 d1;            /* Offset into aKey[] of next data element */
 75792    u32 idx1;          /* Offset into aKey[] of next header element */
 75793    u32 szHdr1;        /* Number of bytes in header */
 75794    int i = 0;
 75795    int rc = 0;
 75796    const unsigned char *aKey1 = (const unsigned char *)pKey1;
 75797    KeyInfo *pKeyInfo;
 75798    Mem mem1;
 75799  
 75800    pKeyInfo = pPKey2->pKeyInfo;
 75801    if( pKeyInfo->db==0 ) return 1;
 75802    mem1.enc = pKeyInfo->enc;
 75803    mem1.db = pKeyInfo->db;
 75804    /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
 75805    VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
 75806  
 75807    /* Compilers may complain that mem1.u.i is potentially uninitialized.
 75808    ** We could initialize it, as shown here, to silence those complaints.
 75809    ** But in fact, mem1.u.i will never actually be used uninitialized, and doing 
 75810    ** the unnecessary initialization has a measurable negative performance
 75811    ** impact, since this routine is a very high runner.  And so, we choose
 75812    ** to ignore the compiler warnings and leave this variable uninitialized.
 75813    */
 75814    /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
 75815    
 75816    idx1 = getVarint32(aKey1, szHdr1);
 75817    if( szHdr1>98307 ) return SQLITE_CORRUPT;
 75818    d1 = szHdr1;
 75819    assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
 75820    assert( pKeyInfo->aSortOrder!=0 );
 75821    assert( pKeyInfo->nKeyField>0 );
 75822    assert( idx1<=szHdr1 || CORRUPT_DB );
 75823    do{
 75824      u32 serial_type1;
 75825  
 75826      /* Read the serial types for the next element in each key. */
 75827      idx1 += getVarint32( aKey1+idx1, serial_type1 );
 75828  
 75829      /* Verify that there is enough key space remaining to avoid
 75830      ** a buffer overread.  The "d1+serial_type1+2" subexpression will
 75831      ** always be greater than or equal to the amount of required key space.
 75832      ** Use that approximation to avoid the more expensive call to
 75833      ** sqlite3VdbeSerialTypeLen() in the common case.
 75834      */
 75835      if( d1+serial_type1+2>(u32)nKey1
 75836       && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1 
 75837      ){
 75838        break;
 75839      }
 75840  
 75841      /* Extract the values to be compared.
 75842      */
 75843      d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
 75844  
 75845      /* Do the comparison
 75846      */
 75847      rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
 75848      if( rc!=0 ){
 75849        assert( mem1.szMalloc==0 );  /* See comment below */
 75850        if( pKeyInfo->aSortOrder[i] ){
 75851          rc = -rc;  /* Invert the result for DESC sort order. */
 75852        }
 75853        goto debugCompareEnd;
 75854      }
 75855      i++;
 75856    }while( idx1<szHdr1 && i<pPKey2->nField );
 75857  
 75858    /* No memory allocation is ever used on mem1.  Prove this using
 75859    ** the following assert().  If the assert() fails, it indicates a
 75860    ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
 75861    */
 75862    assert( mem1.szMalloc==0 );
 75863  
 75864    /* rc==0 here means that one of the keys ran out of fields and
 75865    ** all the fields up to that point were equal. Return the default_rc
 75866    ** value.  */
 75867    rc = pPKey2->default_rc;
 75868  
 75869  debugCompareEnd:
 75870    if( desiredResult==0 && rc==0 ) return 1;
 75871    if( desiredResult<0 && rc<0 ) return 1;
 75872    if( desiredResult>0 && rc>0 ) return 1;
 75873    if( CORRUPT_DB ) return 1;
 75874    if( pKeyInfo->db->mallocFailed ) return 1;
 75875    return 0;
 75876  }
 75877  #endif
 75878  
 75879  #ifdef SQLITE_DEBUG
 75880  /*
 75881  ** Count the number of fields (a.k.a. columns) in the record given by
 75882  ** pKey,nKey.  The verify that this count is less than or equal to the
 75883  ** limit given by pKeyInfo->nAllField.
 75884  **
 75885  ** If this constraint is not satisfied, it means that the high-speed
 75886  ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
 75887  ** not work correctly.  If this assert() ever fires, it probably means
 75888  ** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed
 75889  ** incorrectly.
 75890  */
 75891  static void vdbeAssertFieldCountWithinLimits(
 75892    int nKey, const void *pKey,   /* The record to verify */ 
 75893    const KeyInfo *pKeyInfo       /* Compare size with this KeyInfo */
 75894  ){
 75895    int nField = 0;
 75896    u32 szHdr;
 75897    u32 idx;
 75898    u32 notUsed;
 75899    const unsigned char *aKey = (const unsigned char*)pKey;
 75900  
 75901    if( CORRUPT_DB ) return;
 75902    idx = getVarint32(aKey, szHdr);
 75903    assert( nKey>=0 );
 75904    assert( szHdr<=(u32)nKey );
 75905    while( idx<szHdr ){
 75906      idx += getVarint32(aKey+idx, notUsed);
 75907      nField++;
 75908    }
 75909    assert( nField <= pKeyInfo->nAllField );
 75910  }
 75911  #else
 75912  # define vdbeAssertFieldCountWithinLimits(A,B,C)
 75913  #endif
 75914  
 75915  /*
 75916  ** Both *pMem1 and *pMem2 contain string values. Compare the two values
 75917  ** using the collation sequence pColl. As usual, return a negative , zero
 75918  ** or positive value if *pMem1 is less than, equal to or greater than 
 75919  ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
 75920  */
 75921  static int vdbeCompareMemString(
 75922    const Mem *pMem1,
 75923    const Mem *pMem2,
 75924    const CollSeq *pColl,
 75925    u8 *prcErr                      /* If an OOM occurs, set to SQLITE_NOMEM */
 75926  ){
 75927    if( pMem1->enc==pColl->enc ){
 75928      /* The strings are already in the correct encoding.  Call the
 75929       ** comparison function directly */
 75930      return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
 75931    }else{
 75932      int rc;
 75933      const void *v1, *v2;
 75934      Mem c1;
 75935      Mem c2;
 75936      sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
 75937      sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
 75938      sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
 75939      sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
 75940      v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
 75941      v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
 75942      if( (v1==0 || v2==0) ){
 75943        if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
 75944        rc = 0;
 75945      }else{
 75946        rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
 75947      }
 75948      sqlite3VdbeMemRelease(&c1);
 75949      sqlite3VdbeMemRelease(&c2);
 75950      return rc;
 75951    }
 75952  }
 75953  
 75954  /*
 75955  ** The input pBlob is guaranteed to be a Blob that is not marked
 75956  ** with MEM_Zero.  Return true if it could be a zero-blob.
 75957  */
 75958  static int isAllZero(const char *z, int n){
 75959    int i;
 75960    for(i=0; i<n; i++){
 75961      if( z[i] ) return 0;
 75962    }
 75963    return 1;
 75964  }
 75965  
 75966  /*
 75967  ** Compare two blobs.  Return negative, zero, or positive if the first
 75968  ** is less than, equal to, or greater than the second, respectively.
 75969  ** If one blob is a prefix of the other, then the shorter is the lessor.
 75970  */
 75971  static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
 75972    int c;
 75973    int n1 = pB1->n;
 75974    int n2 = pB2->n;
 75975  
 75976    /* It is possible to have a Blob value that has some non-zero content
 75977    ** followed by zero content.  But that only comes up for Blobs formed
 75978    ** by the OP_MakeRecord opcode, and such Blobs never get passed into
 75979    ** sqlite3MemCompare(). */
 75980    assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
 75981    assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
 75982  
 75983    if( (pB1->flags|pB2->flags) & MEM_Zero ){
 75984      if( pB1->flags & pB2->flags & MEM_Zero ){
 75985        return pB1->u.nZero - pB2->u.nZero;
 75986      }else if( pB1->flags & MEM_Zero ){
 75987        if( !isAllZero(pB2->z, pB2->n) ) return -1;
 75988        return pB1->u.nZero - n2;
 75989      }else{
 75990        if( !isAllZero(pB1->z, pB1->n) ) return +1;
 75991        return n1 - pB2->u.nZero;
 75992      }
 75993    }
 75994    c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
 75995    if( c ) return c;
 75996    return n1 - n2;
 75997  }
 75998  
 75999  /*
 76000  ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
 76001  ** number.  Return negative, zero, or positive if the first (i64) is less than,
 76002  ** equal to, or greater than the second (double).
 76003  */
 76004  static int sqlite3IntFloatCompare(i64 i, double r){
 76005    if( sizeof(LONGDOUBLE_TYPE)>8 ){
 76006      LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
 76007      if( x<r ) return -1;
 76008      if( x>r ) return +1;
 76009      return 0;
 76010    }else{
 76011      i64 y;
 76012      double s;
 76013      if( r<-9223372036854775808.0 ) return +1;
 76014      if( r>9223372036854775807.0 ) return -1;
 76015      y = (i64)r;
 76016      if( i<y ) return -1;
 76017      if( i>y ){
 76018        if( y==SMALLEST_INT64 && r>0.0 ) return -1;
 76019        return +1;
 76020      }
 76021      s = (double)i;
 76022      if( s<r ) return -1;
 76023      if( s>r ) return +1;
 76024      return 0;
 76025    }
 76026  }
 76027  
 76028  /*
 76029  ** Compare the values contained by the two memory cells, returning
 76030  ** negative, zero or positive if pMem1 is less than, equal to, or greater
 76031  ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
 76032  ** and reals) sorted numerically, followed by text ordered by the collating
 76033  ** sequence pColl and finally blob's ordered by memcmp().
 76034  **
 76035  ** Two NULL values are considered equal by this function.
 76036  */
 76037  SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
 76038    int f1, f2;
 76039    int combined_flags;
 76040  
 76041    f1 = pMem1->flags;
 76042    f2 = pMem2->flags;
 76043    combined_flags = f1|f2;
 76044    assert( (combined_flags & MEM_RowSet)==0 );
 76045   
 76046    /* If one value is NULL, it is less than the other. If both values
 76047    ** are NULL, return 0.
 76048    */
 76049    if( combined_flags&MEM_Null ){
 76050      return (f2&MEM_Null) - (f1&MEM_Null);
 76051    }
 76052  
 76053    /* At least one of the two values is a number
 76054    */
 76055    if( combined_flags&(MEM_Int|MEM_Real) ){
 76056      if( (f1 & f2 & MEM_Int)!=0 ){
 76057        if( pMem1->u.i < pMem2->u.i ) return -1;
 76058        if( pMem1->u.i > pMem2->u.i ) return +1;
 76059        return 0;
 76060      }
 76061      if( (f1 & f2 & MEM_Real)!=0 ){
 76062        if( pMem1->u.r < pMem2->u.r ) return -1;
 76063        if( pMem1->u.r > pMem2->u.r ) return +1;
 76064        return 0;
 76065      }
 76066      if( (f1&MEM_Int)!=0 ){
 76067        if( (f2&MEM_Real)!=0 ){
 76068          return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
 76069        }else{
 76070          return -1;
 76071        }
 76072      }
 76073      if( (f1&MEM_Real)!=0 ){
 76074        if( (f2&MEM_Int)!=0 ){
 76075          return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
 76076        }else{
 76077          return -1;
 76078        }
 76079      }
 76080      return +1;
 76081    }
 76082  
 76083    /* If one value is a string and the other is a blob, the string is less.
 76084    ** If both are strings, compare using the collating functions.
 76085    */
 76086    if( combined_flags&MEM_Str ){
 76087      if( (f1 & MEM_Str)==0 ){
 76088        return 1;
 76089      }
 76090      if( (f2 & MEM_Str)==0 ){
 76091        return -1;
 76092      }
 76093  
 76094      assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
 76095      assert( pMem1->enc==SQLITE_UTF8 || 
 76096              pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
 76097  
 76098      /* The collation sequence must be defined at this point, even if
 76099      ** the user deletes the collation sequence after the vdbe program is
 76100      ** compiled (this was not always the case).
 76101      */
 76102      assert( !pColl || pColl->xCmp );
 76103  
 76104      if( pColl ){
 76105        return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
 76106      }
 76107      /* If a NULL pointer was passed as the collate function, fall through
 76108      ** to the blob case and use memcmp().  */
 76109    }
 76110   
 76111    /* Both values must be blobs.  Compare using memcmp().  */
 76112    return sqlite3BlobCompare(pMem1, pMem2);
 76113  }
 76114  
 76115  
 76116  /*
 76117  ** The first argument passed to this function is a serial-type that
 76118  ** corresponds to an integer - all values between 1 and 9 inclusive 
 76119  ** except 7. The second points to a buffer containing an integer value
 76120  ** serialized according to serial_type. This function deserializes
 76121  ** and returns the value.
 76122  */
 76123  static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
 76124    u32 y;
 76125    assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
 76126    switch( serial_type ){
 76127      case 0:
 76128      case 1:
 76129        testcase( aKey[0]&0x80 );
 76130        return ONE_BYTE_INT(aKey);
 76131      case 2:
 76132        testcase( aKey[0]&0x80 );
 76133        return TWO_BYTE_INT(aKey);
 76134      case 3:
 76135        testcase( aKey[0]&0x80 );
 76136        return THREE_BYTE_INT(aKey);
 76137      case 4: {
 76138        testcase( aKey[0]&0x80 );
 76139        y = FOUR_BYTE_UINT(aKey);
 76140        return (i64)*(int*)&y;
 76141      }
 76142      case 5: {
 76143        testcase( aKey[0]&0x80 );
 76144        return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
 76145      }
 76146      case 6: {
 76147        u64 x = FOUR_BYTE_UINT(aKey);
 76148        testcase( aKey[0]&0x80 );
 76149        x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
 76150        return (i64)*(i64*)&x;
 76151      }
 76152    }
 76153  
 76154    return (serial_type - 8);
 76155  }
 76156  
 76157  /*
 76158  ** This function compares the two table rows or index records
 76159  ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
 76160  ** or positive integer if key1 is less than, equal to or 
 76161  ** greater than key2.  The {nKey1, pKey1} key must be a blob
 76162  ** created by the OP_MakeRecord opcode of the VDBE.  The pPKey2
 76163  ** key must be a parsed key such as obtained from
 76164  ** sqlite3VdbeParseRecord.
 76165  **
 76166  ** If argument bSkip is non-zero, it is assumed that the caller has already
 76167  ** determined that the first fields of the keys are equal.
 76168  **
 76169  ** Key1 and Key2 do not have to contain the same number of fields. If all 
 76170  ** fields that appear in both keys are equal, then pPKey2->default_rc is 
 76171  ** returned.
 76172  **
 76173  ** If database corruption is discovered, set pPKey2->errCode to 
 76174  ** SQLITE_CORRUPT and return 0. If an OOM error is encountered, 
 76175  ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
 76176  ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
 76177  */
 76178  SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
 76179    int nKey1, const void *pKey1,   /* Left key */
 76180    UnpackedRecord *pPKey2,         /* Right key */
 76181    int bSkip                       /* If true, skip the first field */
 76182  ){
 76183    u32 d1;                         /* Offset into aKey[] of next data element */
 76184    int i;                          /* Index of next field to compare */
 76185    u32 szHdr1;                     /* Size of record header in bytes */
 76186    u32 idx1;                       /* Offset of first type in header */
 76187    int rc = 0;                     /* Return value */
 76188    Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
 76189    KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
 76190    const unsigned char *aKey1 = (const unsigned char *)pKey1;
 76191    Mem mem1;
 76192  
 76193    /* If bSkip is true, then the caller has already determined that the first
 76194    ** two elements in the keys are equal. Fix the various stack variables so
 76195    ** that this routine begins comparing at the second field. */
 76196    if( bSkip ){
 76197      u32 s1;
 76198      idx1 = 1 + getVarint32(&aKey1[1], s1);
 76199      szHdr1 = aKey1[0];
 76200      d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
 76201      i = 1;
 76202      pRhs++;
 76203    }else{
 76204      idx1 = getVarint32(aKey1, szHdr1);
 76205      d1 = szHdr1;
 76206      if( d1>(unsigned)nKey1 ){ 
 76207        pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
 76208        return 0;  /* Corruption */
 76209      }
 76210      i = 0;
 76211    }
 76212  
 76213    VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
 76214    assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField 
 76215         || CORRUPT_DB );
 76216    assert( pPKey2->pKeyInfo->aSortOrder!=0 );
 76217    assert( pPKey2->pKeyInfo->nKeyField>0 );
 76218    assert( idx1<=szHdr1 || CORRUPT_DB );
 76219    do{
 76220      u32 serial_type;
 76221  
 76222      /* RHS is an integer */
 76223      if( pRhs->flags & MEM_Int ){
 76224        serial_type = aKey1[idx1];
 76225        testcase( serial_type==12 );
 76226        if( serial_type>=10 ){
 76227          rc = +1;
 76228        }else if( serial_type==0 ){
 76229          rc = -1;
 76230        }else if( serial_type==7 ){
 76231          sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
 76232          rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
 76233        }else{
 76234          i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
 76235          i64 rhs = pRhs->u.i;
 76236          if( lhs<rhs ){
 76237            rc = -1;
 76238          }else if( lhs>rhs ){
 76239            rc = +1;
 76240          }
 76241        }
 76242      }
 76243  
 76244      /* RHS is real */
 76245      else if( pRhs->flags & MEM_Real ){
 76246        serial_type = aKey1[idx1];
 76247        if( serial_type>=10 ){
 76248          /* Serial types 12 or greater are strings and blobs (greater than
 76249          ** numbers). Types 10 and 11 are currently "reserved for future 
 76250          ** use", so it doesn't really matter what the results of comparing
 76251          ** them to numberic values are.  */
 76252          rc = +1;
 76253        }else if( serial_type==0 ){
 76254          rc = -1;
 76255        }else{
 76256          sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
 76257          if( serial_type==7 ){
 76258            if( mem1.u.r<pRhs->u.r ){
 76259              rc = -1;
 76260            }else if( mem1.u.r>pRhs->u.r ){
 76261              rc = +1;
 76262            }
 76263          }else{
 76264            rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
 76265          }
 76266        }
 76267      }
 76268  
 76269      /* RHS is a string */
 76270      else if( pRhs->flags & MEM_Str ){
 76271        getVarint32(&aKey1[idx1], serial_type);
 76272        testcase( serial_type==12 );
 76273        if( serial_type<12 ){
 76274          rc = -1;
 76275        }else if( !(serial_type & 0x01) ){
 76276          rc = +1;
 76277        }else{
 76278          mem1.n = (serial_type - 12) / 2;
 76279          testcase( (d1+mem1.n)==(unsigned)nKey1 );
 76280          testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
 76281          if( (d1+mem1.n) > (unsigned)nKey1 ){
 76282            pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
 76283            return 0;                /* Corruption */
 76284          }else if( pKeyInfo->aColl[i] ){
 76285            mem1.enc = pKeyInfo->enc;
 76286            mem1.db = pKeyInfo->db;
 76287            mem1.flags = MEM_Str;
 76288            mem1.z = (char*)&aKey1[d1];
 76289            rc = vdbeCompareMemString(
 76290                &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
 76291            );
 76292          }else{
 76293            int nCmp = MIN(mem1.n, pRhs->n);
 76294            rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
 76295            if( rc==0 ) rc = mem1.n - pRhs->n; 
 76296          }
 76297        }
 76298      }
 76299  
 76300      /* RHS is a blob */
 76301      else if( pRhs->flags & MEM_Blob ){
 76302        assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
 76303        getVarint32(&aKey1[idx1], serial_type);
 76304        testcase( serial_type==12 );
 76305        if( serial_type<12 || (serial_type & 0x01) ){
 76306          rc = -1;
 76307        }else{
 76308          int nStr = (serial_type - 12) / 2;
 76309          testcase( (d1+nStr)==(unsigned)nKey1 );
 76310          testcase( (d1+nStr+1)==(unsigned)nKey1 );
 76311          if( (d1+nStr) > (unsigned)nKey1 ){
 76312            pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
 76313            return 0;                /* Corruption */
 76314          }else if( pRhs->flags & MEM_Zero ){
 76315            if( !isAllZero((const char*)&aKey1[d1],nStr) ){
 76316              rc = 1;
 76317            }else{
 76318              rc = nStr - pRhs->u.nZero;
 76319            }
 76320          }else{
 76321            int nCmp = MIN(nStr, pRhs->n);
 76322            rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
 76323            if( rc==0 ) rc = nStr - pRhs->n;
 76324          }
 76325        }
 76326      }
 76327  
 76328      /* RHS is null */
 76329      else{
 76330        serial_type = aKey1[idx1];
 76331        rc = (serial_type!=0);
 76332      }
 76333  
 76334      if( rc!=0 ){
 76335        if( pKeyInfo->aSortOrder[i] ){
 76336          rc = -rc;
 76337        }
 76338        assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
 76339        assert( mem1.szMalloc==0 );  /* See comment below */
 76340        return rc;
 76341      }
 76342  
 76343      i++;
 76344      pRhs++;
 76345      d1 += sqlite3VdbeSerialTypeLen(serial_type);
 76346      idx1 += sqlite3VarintLen(serial_type);
 76347    }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
 76348  
 76349    /* No memory allocation is ever used on mem1.  Prove this using
 76350    ** the following assert().  If the assert() fails, it indicates a
 76351    ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
 76352    assert( mem1.szMalloc==0 );
 76353  
 76354    /* rc==0 here means that one or both of the keys ran out of fields and
 76355    ** all the fields up to that point were equal. Return the default_rc
 76356    ** value.  */
 76357    assert( CORRUPT_DB 
 76358         || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc) 
 76359         || pKeyInfo->db->mallocFailed
 76360    );
 76361    pPKey2->eqSeen = 1;
 76362    return pPKey2->default_rc;
 76363  }
 76364  SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
 76365    int nKey1, const void *pKey1,   /* Left key */
 76366    UnpackedRecord *pPKey2          /* Right key */
 76367  ){
 76368    return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
 76369  }
 76370  
 76371  
 76372  /*
 76373  ** This function is an optimized version of sqlite3VdbeRecordCompare() 
 76374  ** that (a) the first field of pPKey2 is an integer, and (b) the 
 76375  ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
 76376  ** byte (i.e. is less than 128).
 76377  **
 76378  ** To avoid concerns about buffer overreads, this routine is only used
 76379  ** on schemas where the maximum valid header size is 63 bytes or less.
 76380  */
 76381  static int vdbeRecordCompareInt(
 76382    int nKey1, const void *pKey1, /* Left key */
 76383    UnpackedRecord *pPKey2        /* Right key */
 76384  ){
 76385    const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
 76386    int serial_type = ((const u8*)pKey1)[1];
 76387    int res;
 76388    u32 y;
 76389    u64 x;
 76390    i64 v;
 76391    i64 lhs;
 76392  
 76393    vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
 76394    assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
 76395    switch( serial_type ){
 76396      case 1: { /* 1-byte signed integer */
 76397        lhs = ONE_BYTE_INT(aKey);
 76398        testcase( lhs<0 );
 76399        break;
 76400      }
 76401      case 2: { /* 2-byte signed integer */
 76402        lhs = TWO_BYTE_INT(aKey);
 76403        testcase( lhs<0 );
 76404        break;
 76405      }
 76406      case 3: { /* 3-byte signed integer */
 76407        lhs = THREE_BYTE_INT(aKey);
 76408        testcase( lhs<0 );
 76409        break;
 76410      }
 76411      case 4: { /* 4-byte signed integer */
 76412        y = FOUR_BYTE_UINT(aKey);
 76413        lhs = (i64)*(int*)&y;
 76414        testcase( lhs<0 );
 76415        break;
 76416      }
 76417      case 5: { /* 6-byte signed integer */
 76418        lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
 76419        testcase( lhs<0 );
 76420        break;
 76421      }
 76422      case 6: { /* 8-byte signed integer */
 76423        x = FOUR_BYTE_UINT(aKey);
 76424        x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
 76425        lhs = *(i64*)&x;
 76426        testcase( lhs<0 );
 76427        break;
 76428      }
 76429      case 8: 
 76430        lhs = 0;
 76431        break;
 76432      case 9:
 76433        lhs = 1;
 76434        break;
 76435  
 76436      /* This case could be removed without changing the results of running
 76437      ** this code. Including it causes gcc to generate a faster switch 
 76438      ** statement (since the range of switch targets now starts at zero and
 76439      ** is contiguous) but does not cause any duplicate code to be generated
 76440      ** (as gcc is clever enough to combine the two like cases). Other 
 76441      ** compilers might be similar.  */ 
 76442      case 0: case 7:
 76443        return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
 76444  
 76445      default:
 76446        return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
 76447    }
 76448  
 76449    v = pPKey2->aMem[0].u.i;
 76450    if( v>lhs ){
 76451      res = pPKey2->r1;
 76452    }else if( v<lhs ){
 76453      res = pPKey2->r2;
 76454    }else if( pPKey2->nField>1 ){
 76455      /* The first fields of the two keys are equal. Compare the trailing 
 76456      ** fields.  */
 76457      res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
 76458    }else{
 76459      /* The first fields of the two keys are equal and there are no trailing
 76460      ** fields. Return pPKey2->default_rc in this case. */
 76461      res = pPKey2->default_rc;
 76462      pPKey2->eqSeen = 1;
 76463    }
 76464  
 76465    assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
 76466    return res;
 76467  }
 76468  
 76469  /*
 76470  ** This function is an optimized version of sqlite3VdbeRecordCompare() 
 76471  ** that (a) the first field of pPKey2 is a string, that (b) the first field
 76472  ** uses the collation sequence BINARY and (c) that the size-of-header varint 
 76473  ** at the start of (pKey1/nKey1) fits in a single byte.
 76474  */
 76475  static int vdbeRecordCompareString(
 76476    int nKey1, const void *pKey1, /* Left key */
 76477    UnpackedRecord *pPKey2        /* Right key */
 76478  ){
 76479    const u8 *aKey1 = (const u8*)pKey1;
 76480    int serial_type;
 76481    int res;
 76482  
 76483    assert( pPKey2->aMem[0].flags & MEM_Str );
 76484    vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
 76485    getVarint32(&aKey1[1], serial_type);
 76486    if( serial_type<12 ){
 76487      res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
 76488    }else if( !(serial_type & 0x01) ){ 
 76489      res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
 76490    }else{
 76491      int nCmp;
 76492      int nStr;
 76493      int szHdr = aKey1[0];
 76494  
 76495      nStr = (serial_type-12) / 2;
 76496      if( (szHdr + nStr) > nKey1 ){
 76497        pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
 76498        return 0;    /* Corruption */
 76499      }
 76500      nCmp = MIN( pPKey2->aMem[0].n, nStr );
 76501      res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
 76502  
 76503      if( res==0 ){
 76504        res = nStr - pPKey2->aMem[0].n;
 76505        if( res==0 ){
 76506          if( pPKey2->nField>1 ){
 76507            res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
 76508          }else{
 76509            res = pPKey2->default_rc;
 76510            pPKey2->eqSeen = 1;
 76511          }
 76512        }else if( res>0 ){
 76513          res = pPKey2->r2;
 76514        }else{
 76515          res = pPKey2->r1;
 76516        }
 76517      }else if( res>0 ){
 76518        res = pPKey2->r2;
 76519      }else{
 76520        res = pPKey2->r1;
 76521      }
 76522    }
 76523  
 76524    assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
 76525         || CORRUPT_DB
 76526         || pPKey2->pKeyInfo->db->mallocFailed
 76527    );
 76528    return res;
 76529  }
 76530  
 76531  /*
 76532  ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
 76533  ** suitable for comparing serialized records to the unpacked record passed
 76534  ** as the only argument.
 76535  */
 76536  SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
 76537    /* varintRecordCompareInt() and varintRecordCompareString() both assume
 76538    ** that the size-of-header varint that occurs at the start of each record
 76539    ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
 76540    ** also assumes that it is safe to overread a buffer by at least the 
 76541    ** maximum possible legal header size plus 8 bytes. Because there is
 76542    ** guaranteed to be at least 74 (but not 136) bytes of padding following each
 76543    ** buffer passed to varintRecordCompareInt() this makes it convenient to
 76544    ** limit the size of the header to 64 bytes in cases where the first field
 76545    ** is an integer.
 76546    **
 76547    ** The easiest way to enforce this limit is to consider only records with
 76548    ** 13 fields or less. If the first field is an integer, the maximum legal
 76549    ** header size is (12*5 + 1 + 1) bytes.  */
 76550    if( p->pKeyInfo->nAllField<=13 ){
 76551      int flags = p->aMem[0].flags;
 76552      if( p->pKeyInfo->aSortOrder[0] ){
 76553        p->r1 = 1;
 76554        p->r2 = -1;
 76555      }else{
 76556        p->r1 = -1;
 76557        p->r2 = 1;
 76558      }
 76559      if( (flags & MEM_Int) ){
 76560        return vdbeRecordCompareInt;
 76561      }
 76562      testcase( flags & MEM_Real );
 76563      testcase( flags & MEM_Null );
 76564      testcase( flags & MEM_Blob );
 76565      if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
 76566        assert( flags & MEM_Str );
 76567        return vdbeRecordCompareString;
 76568      }
 76569    }
 76570  
 76571    return sqlite3VdbeRecordCompare;
 76572  }
 76573  
 76574  /*
 76575  ** pCur points at an index entry created using the OP_MakeRecord opcode.
 76576  ** Read the rowid (the last field in the record) and store it in *rowid.
 76577  ** Return SQLITE_OK if everything works, or an error code otherwise.
 76578  **
 76579  ** pCur might be pointing to text obtained from a corrupt database file.
 76580  ** So the content cannot be trusted.  Do appropriate checks on the content.
 76581  */
 76582  SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
 76583    i64 nCellKey = 0;
 76584    int rc;
 76585    u32 szHdr;        /* Size of the header */
 76586    u32 typeRowid;    /* Serial type of the rowid */
 76587    u32 lenRowid;     /* Size of the rowid */
 76588    Mem m, v;
 76589  
 76590    /* Get the size of the index entry.  Only indices entries of less
 76591    ** than 2GiB are support - anything large must be database corruption.
 76592    ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
 76593    ** this code can safely assume that nCellKey is 32-bits  
 76594    */
 76595    assert( sqlite3BtreeCursorIsValid(pCur) );
 76596    nCellKey = sqlite3BtreePayloadSize(pCur);
 76597    assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
 76598  
 76599    /* Read in the complete content of the index entry */
 76600    sqlite3VdbeMemInit(&m, db, 0);
 76601    rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
 76602    if( rc ){
 76603      return rc;
 76604    }
 76605  
 76606    /* The index entry must begin with a header size */
 76607    (void)getVarint32((u8*)m.z, szHdr);
 76608    testcase( szHdr==3 );
 76609    testcase( szHdr==m.n );
 76610    if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
 76611      goto idx_rowid_corruption;
 76612    }
 76613  
 76614    /* The last field of the index should be an integer - the ROWID.
 76615    ** Verify that the last entry really is an integer. */
 76616    (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
 76617    testcase( typeRowid==1 );
 76618    testcase( typeRowid==2 );
 76619    testcase( typeRowid==3 );
 76620    testcase( typeRowid==4 );
 76621    testcase( typeRowid==5 );
 76622    testcase( typeRowid==6 );
 76623    testcase( typeRowid==8 );
 76624    testcase( typeRowid==9 );
 76625    if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
 76626      goto idx_rowid_corruption;
 76627    }
 76628    lenRowid = sqlite3SmallTypeSizes[typeRowid];
 76629    testcase( (u32)m.n==szHdr+lenRowid );
 76630    if( unlikely((u32)m.n<szHdr+lenRowid) ){
 76631      goto idx_rowid_corruption;
 76632    }
 76633  
 76634    /* Fetch the integer off the end of the index record */
 76635    sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
 76636    *rowid = v.u.i;
 76637    sqlite3VdbeMemRelease(&m);
 76638    return SQLITE_OK;
 76639  
 76640    /* Jump here if database corruption is detected after m has been
 76641    ** allocated.  Free the m object and return SQLITE_CORRUPT. */
 76642  idx_rowid_corruption:
 76643    testcase( m.szMalloc!=0 );
 76644    sqlite3VdbeMemRelease(&m);
 76645    return SQLITE_CORRUPT_BKPT;
 76646  }
 76647  
 76648  /*
 76649  ** Compare the key of the index entry that cursor pC is pointing to against
 76650  ** the key string in pUnpacked.  Write into *pRes a number
 76651  ** that is negative, zero, or positive if pC is less than, equal to,
 76652  ** or greater than pUnpacked.  Return SQLITE_OK on success.
 76653  **
 76654  ** pUnpacked is either created without a rowid or is truncated so that it
 76655  ** omits the rowid at the end.  The rowid at the end of the index entry
 76656  ** is ignored as well.  Hence, this routine only compares the prefixes 
 76657  ** of the keys prior to the final rowid, not the entire key.
 76658  */
 76659  SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
 76660    sqlite3 *db,                     /* Database connection */
 76661    VdbeCursor *pC,                  /* The cursor to compare against */
 76662    UnpackedRecord *pUnpacked,       /* Unpacked version of key */
 76663    int *res                         /* Write the comparison result here */
 76664  ){
 76665    i64 nCellKey = 0;
 76666    int rc;
 76667    BtCursor *pCur;
 76668    Mem m;
 76669  
 76670    assert( pC->eCurType==CURTYPE_BTREE );
 76671    pCur = pC->uc.pCursor;
 76672    assert( sqlite3BtreeCursorIsValid(pCur) );
 76673    nCellKey = sqlite3BtreePayloadSize(pCur);
 76674    /* nCellKey will always be between 0 and 0xffffffff because of the way
 76675    ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
 76676    if( nCellKey<=0 || nCellKey>0x7fffffff ){
 76677      *res = 0;
 76678      return SQLITE_CORRUPT_BKPT;
 76679    }
 76680    sqlite3VdbeMemInit(&m, db, 0);
 76681    rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
 76682    if( rc ){
 76683      return rc;
 76684    }
 76685    *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
 76686    sqlite3VdbeMemRelease(&m);
 76687    return SQLITE_OK;
 76688  }
 76689  
 76690  /*
 76691  ** This routine sets the value to be returned by subsequent calls to
 76692  ** sqlite3_changes() on the database handle 'db'. 
 76693  */
 76694  SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
 76695    assert( sqlite3_mutex_held(db->mutex) );
 76696    db->nChange = nChange;
 76697    db->nTotalChange += nChange;
 76698  }
 76699  
 76700  /*
 76701  ** Set a flag in the vdbe to update the change counter when it is finalised
 76702  ** or reset.
 76703  */
 76704  SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
 76705    v->changeCntOn = 1;
 76706  }
 76707  
 76708  /*
 76709  ** Mark every prepared statement associated with a database connection
 76710  ** as expired.
 76711  **
 76712  ** An expired statement means that recompilation of the statement is
 76713  ** recommend.  Statements expire when things happen that make their
 76714  ** programs obsolete.  Removing user-defined functions or collating
 76715  ** sequences, or changing an authorization function are the types of
 76716  ** things that make prepared statements obsolete.
 76717  */
 76718  SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
 76719    Vdbe *p;
 76720    for(p = db->pVdbe; p; p=p->pNext){
 76721      p->expired = 1;
 76722    }
 76723  }
 76724  
 76725  /*
 76726  ** Return the database associated with the Vdbe.
 76727  */
 76728  SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
 76729    return v->db;
 76730  }
 76731  
 76732  /*
 76733  ** Return the SQLITE_PREPARE flags for a Vdbe.
 76734  */
 76735  SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe *v){
 76736    return v->prepFlags;
 76737  }
 76738  
 76739  /*
 76740  ** Return a pointer to an sqlite3_value structure containing the value bound
 76741  ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
 76742  ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
 76743  ** constants) to the value before returning it.
 76744  **
 76745  ** The returned value must be freed by the caller using sqlite3ValueFree().
 76746  */
 76747  SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
 76748    assert( iVar>0 );
 76749    if( v ){
 76750      Mem *pMem = &v->aVar[iVar-1];
 76751      assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
 76752      if( 0==(pMem->flags & MEM_Null) ){
 76753        sqlite3_value *pRet = sqlite3ValueNew(v->db);
 76754        if( pRet ){
 76755          sqlite3VdbeMemCopy((Mem *)pRet, pMem);
 76756          sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
 76757        }
 76758        return pRet;
 76759      }
 76760    }
 76761    return 0;
 76762  }
 76763  
 76764  /*
 76765  ** Configure SQL variable iVar so that binding a new value to it signals
 76766  ** to sqlite3_reoptimize() that re-preparing the statement may result
 76767  ** in a better query plan.
 76768  */
 76769  SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
 76770    assert( iVar>0 );
 76771    assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
 76772    if( iVar>=32 ){
 76773      v->expmask |= 0x80000000;
 76774    }else{
 76775      v->expmask |= ((u32)1 << (iVar-1));
 76776    }
 76777  }
 76778  
 76779  /*
 76780  ** Cause a function to throw an error if it was call from OP_PureFunc
 76781  ** rather than OP_Function.
 76782  **
 76783  ** OP_PureFunc means that the function must be deterministic, and should
 76784  ** throw an error if it is given inputs that would make it non-deterministic.
 76785  ** This routine is invoked by date/time functions that use non-deterministic
 76786  ** features such as 'now'.
 76787  */
 76788  SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context *pCtx){
 76789  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 76790    if( pCtx->pVdbe==0 ) return 1;
 76791  #endif
 76792    if( pCtx->pVdbe->aOp[pCtx->iOp].opcode==OP_PureFunc ){
 76793      sqlite3_result_error(pCtx, 
 76794         "non-deterministic function in index expression or CHECK constraint",
 76795         -1);
 76796      return 0;
 76797    }
 76798    return 1;
 76799  }
 76800  
 76801  #ifndef SQLITE_OMIT_VIRTUALTABLE
 76802  /*
 76803  ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
 76804  ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
 76805  ** in memory obtained from sqlite3DbMalloc).
 76806  */
 76807  SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
 76808    if( pVtab->zErrMsg ){
 76809      sqlite3 *db = p->db;
 76810      sqlite3DbFree(db, p->zErrMsg);
 76811      p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
 76812      sqlite3_free(pVtab->zErrMsg);
 76813      pVtab->zErrMsg = 0;
 76814    }
 76815  }
 76816  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 76817  
 76818  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 76819  
 76820  /*
 76821  ** If the second argument is not NULL, release any allocations associated 
 76822  ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
 76823  ** structure itself, using sqlite3DbFree().
 76824  **
 76825  ** This function is used to free UnpackedRecord structures allocated by
 76826  ** the vdbeUnpackRecord() function found in vdbeapi.c.
 76827  */
 76828  static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
 76829    if( p ){
 76830      int i;
 76831      for(i=0; i<nField; i++){
 76832        Mem *pMem = &p->aMem[i];
 76833        if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
 76834      }
 76835      sqlite3DbFreeNN(db, p);
 76836    }
 76837  }
 76838  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
 76839  
 76840  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 76841  /*
 76842  ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
 76843  ** then cursor passed as the second argument should point to the row about
 76844  ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
 76845  ** the required value will be read from the row the cursor points to.
 76846  */
 76847  SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
 76848    Vdbe *v,                        /* Vdbe pre-update hook is invoked by */
 76849    VdbeCursor *pCsr,               /* Cursor to grab old.* values from */
 76850    int op,                         /* SQLITE_INSERT, UPDATE or DELETE */
 76851    const char *zDb,                /* Database name */
 76852    Table *pTab,                    /* Modified table */
 76853    i64 iKey1,                      /* Initial key value */
 76854    int iReg                        /* Register for new.* record */
 76855  ){
 76856    sqlite3 *db = v->db;
 76857    i64 iKey2;
 76858    PreUpdate preupdate;
 76859    const char *zTbl = pTab->zName;
 76860    static const u8 fakeSortOrder = 0;
 76861  
 76862    assert( db->pPreUpdate==0 );
 76863    memset(&preupdate, 0, sizeof(PreUpdate));
 76864    if( HasRowid(pTab)==0 ){
 76865      iKey1 = iKey2 = 0;
 76866      preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
 76867    }else{
 76868      if( op==SQLITE_UPDATE ){
 76869        iKey2 = v->aMem[iReg].u.i;
 76870      }else{
 76871        iKey2 = iKey1;
 76872      }
 76873    }
 76874  
 76875    assert( pCsr->nField==pTab->nCol 
 76876         || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
 76877    );
 76878  
 76879    preupdate.v = v;
 76880    preupdate.pCsr = pCsr;
 76881    preupdate.op = op;
 76882    preupdate.iNewReg = iReg;
 76883    preupdate.keyinfo.db = db;
 76884    preupdate.keyinfo.enc = ENC(db);
 76885    preupdate.keyinfo.nKeyField = pTab->nCol;
 76886    preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
 76887    preupdate.iKey1 = iKey1;
 76888    preupdate.iKey2 = iKey2;
 76889    preupdate.pTab = pTab;
 76890  
 76891    db->pPreUpdate = &preupdate;
 76892    db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
 76893    db->pPreUpdate = 0;
 76894    sqlite3DbFree(db, preupdate.aRecord);
 76895    vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);
 76896    vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);
 76897    if( preupdate.aNew ){
 76898      int i;
 76899      for(i=0; i<pCsr->nField; i++){
 76900        sqlite3VdbeMemRelease(&preupdate.aNew[i]);
 76901      }
 76902      sqlite3DbFreeNN(db, preupdate.aNew);
 76903    }
 76904  }
 76905  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
 76906  
 76907  /************** End of vdbeaux.c *********************************************/
 76908  /************** Begin file vdbeapi.c *****************************************/
 76909  /*
 76910  ** 2004 May 26
 76911  **
 76912  ** The author disclaims copyright to this source code.  In place of
 76913  ** a legal notice, here is a blessing:
 76914  **
 76915  **    May you do good and not evil.
 76916  **    May you find forgiveness for yourself and forgive others.
 76917  **    May you share freely, never taking more than you give.
 76918  **
 76919  *************************************************************************
 76920  **
 76921  ** This file contains code use to implement APIs that are part of the
 76922  ** VDBE.
 76923  */
 76924  /* #include "sqliteInt.h" */
 76925  /* #include "vdbeInt.h" */
 76926  
 76927  #ifndef SQLITE_OMIT_DEPRECATED
 76928  /*
 76929  ** Return TRUE (non-zero) of the statement supplied as an argument needs
 76930  ** to be recompiled.  A statement needs to be recompiled whenever the
 76931  ** execution environment changes in a way that would alter the program
 76932  ** that sqlite3_prepare() generates.  For example, if new functions or
 76933  ** collating sequences are registered or if an authorizer function is
 76934  ** added or changed.
 76935  */
 76936  SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
 76937    Vdbe *p = (Vdbe*)pStmt;
 76938    return p==0 || p->expired;
 76939  }
 76940  #endif
 76941  
 76942  /*
 76943  ** Check on a Vdbe to make sure it has not been finalized.  Log
 76944  ** an error and return true if it has been finalized (or is otherwise
 76945  ** invalid).  Return false if it is ok.
 76946  */
 76947  static int vdbeSafety(Vdbe *p){
 76948    if( p->db==0 ){
 76949      sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
 76950      return 1;
 76951    }else{
 76952      return 0;
 76953    }
 76954  }
 76955  static int vdbeSafetyNotNull(Vdbe *p){
 76956    if( p==0 ){
 76957      sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
 76958      return 1;
 76959    }else{
 76960      return vdbeSafety(p);
 76961    }
 76962  }
 76963  
 76964  #ifndef SQLITE_OMIT_TRACE
 76965  /*
 76966  ** Invoke the profile callback.  This routine is only called if we already
 76967  ** know that the profile callback is defined and needs to be invoked.
 76968  */
 76969  static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
 76970    sqlite3_int64 iNow;
 76971    sqlite3_int64 iElapse;
 76972    assert( p->startTime>0 );
 76973    assert( db->xProfile!=0 || (db->mTrace & SQLITE_TRACE_PROFILE)!=0 );
 76974    assert( db->init.busy==0 );
 76975    assert( p->zSql!=0 );
 76976    sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
 76977    iElapse = (iNow - p->startTime)*1000000;
 76978    if( db->xProfile ){
 76979      db->xProfile(db->pProfileArg, p->zSql, iElapse);
 76980    }
 76981    if( db->mTrace & SQLITE_TRACE_PROFILE ){
 76982      db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
 76983    }
 76984    p->startTime = 0;
 76985  }
 76986  /*
 76987  ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
 76988  ** is needed, and it invokes the callback if it is needed.
 76989  */
 76990  # define checkProfileCallback(DB,P) \
 76991     if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
 76992  #else
 76993  # define checkProfileCallback(DB,P)  /*no-op*/
 76994  #endif
 76995  
 76996  /*
 76997  ** The following routine destroys a virtual machine that is created by
 76998  ** the sqlite3_compile() routine. The integer returned is an SQLITE_
 76999  ** success/failure code that describes the result of executing the virtual
 77000  ** machine.
 77001  **
 77002  ** This routine sets the error code and string returned by
 77003  ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
 77004  */
 77005  SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
 77006    int rc;
 77007    if( pStmt==0 ){
 77008      /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
 77009      ** pointer is a harmless no-op. */
 77010      rc = SQLITE_OK;
 77011    }else{
 77012      Vdbe *v = (Vdbe*)pStmt;
 77013      sqlite3 *db = v->db;
 77014      if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
 77015      sqlite3_mutex_enter(db->mutex);
 77016      checkProfileCallback(db, v);
 77017      rc = sqlite3VdbeFinalize(v);
 77018      rc = sqlite3ApiExit(db, rc);
 77019      sqlite3LeaveMutexAndCloseZombie(db);
 77020    }
 77021    return rc;
 77022  }
 77023  
 77024  /*
 77025  ** Terminate the current execution of an SQL statement and reset it
 77026  ** back to its starting state so that it can be reused. A success code from
 77027  ** the prior execution is returned.
 77028  **
 77029  ** This routine sets the error code and string returned by
 77030  ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
 77031  */
 77032  SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
 77033    int rc;
 77034    if( pStmt==0 ){
 77035      rc = SQLITE_OK;
 77036    }else{
 77037      Vdbe *v = (Vdbe*)pStmt;
 77038      sqlite3 *db = v->db;
 77039      sqlite3_mutex_enter(db->mutex);
 77040      checkProfileCallback(db, v);
 77041      rc = sqlite3VdbeReset(v);
 77042      sqlite3VdbeRewind(v);
 77043      assert( (rc & (db->errMask))==rc );
 77044      rc = sqlite3ApiExit(db, rc);
 77045      sqlite3_mutex_leave(db->mutex);
 77046    }
 77047    return rc;
 77048  }
 77049  
 77050  /*
 77051  ** Set all the parameters in the compiled SQL statement to NULL.
 77052  */
 77053  SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
 77054    int i;
 77055    int rc = SQLITE_OK;
 77056    Vdbe *p = (Vdbe*)pStmt;
 77057  #if SQLITE_THREADSAFE
 77058    sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
 77059  #endif
 77060    sqlite3_mutex_enter(mutex);
 77061    for(i=0; i<p->nVar; i++){
 77062      sqlite3VdbeMemRelease(&p->aVar[i]);
 77063      p->aVar[i].flags = MEM_Null;
 77064    }
 77065    assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
 77066    if( p->expmask ){
 77067      p->expired = 1;
 77068    }
 77069    sqlite3_mutex_leave(mutex);
 77070    return rc;
 77071  }
 77072  
 77073  
 77074  /**************************** sqlite3_value_  *******************************
 77075  ** The following routines extract information from a Mem or sqlite3_value
 77076  ** structure.
 77077  */
 77078  SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
 77079    Mem *p = (Mem*)pVal;
 77080    if( p->flags & (MEM_Blob|MEM_Str) ){
 77081      if( ExpandBlob(p)!=SQLITE_OK ){
 77082        assert( p->flags==MEM_Null && p->z==0 );
 77083        return 0;
 77084      }
 77085      p->flags |= MEM_Blob;
 77086      return p->n ? p->z : 0;
 77087    }else{
 77088      return sqlite3_value_text(pVal);
 77089    }
 77090  }
 77091  SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
 77092    return sqlite3ValueBytes(pVal, SQLITE_UTF8);
 77093  }
 77094  SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
 77095    return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
 77096  }
 77097  SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
 77098    return sqlite3VdbeRealValue((Mem*)pVal);
 77099  }
 77100  SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
 77101    return (int)sqlite3VdbeIntValue((Mem*)pVal);
 77102  }
 77103  SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
 77104    return sqlite3VdbeIntValue((Mem*)pVal);
 77105  }
 77106  SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
 77107    Mem *pMem = (Mem*)pVal;
 77108    return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
 77109  }
 77110  SQLITE_API void *sqlite3_value_pointer(sqlite3_value *pVal, const char *zPType){
 77111    Mem *p = (Mem*)pVal;
 77112    if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
 77113                   (MEM_Null|MEM_Term|MEM_Subtype)
 77114     && zPType!=0
 77115     && p->eSubtype=='p'
 77116     && strcmp(p->u.zPType, zPType)==0
 77117    ){
 77118      return (void*)p->z;
 77119    }else{
 77120      return 0;
 77121    }
 77122  }
 77123  SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
 77124    return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
 77125  }
 77126  #ifndef SQLITE_OMIT_UTF16
 77127  SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
 77128    return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
 77129  }
 77130  SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
 77131    return sqlite3ValueText(pVal, SQLITE_UTF16BE);
 77132  }
 77133  SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
 77134    return sqlite3ValueText(pVal, SQLITE_UTF16LE);
 77135  }
 77136  #endif /* SQLITE_OMIT_UTF16 */
 77137  /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
 77138  ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
 77139  ** point number string BLOB NULL
 77140  */
 77141  SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
 77142    static const u8 aType[] = {
 77143       SQLITE_BLOB,     /* 0x00 */
 77144       SQLITE_NULL,     /* 0x01 */
 77145       SQLITE_TEXT,     /* 0x02 */
 77146       SQLITE_NULL,     /* 0x03 */
 77147       SQLITE_INTEGER,  /* 0x04 */
 77148       SQLITE_NULL,     /* 0x05 */
 77149       SQLITE_INTEGER,  /* 0x06 */
 77150       SQLITE_NULL,     /* 0x07 */
 77151       SQLITE_FLOAT,    /* 0x08 */
 77152       SQLITE_NULL,     /* 0x09 */
 77153       SQLITE_FLOAT,    /* 0x0a */
 77154       SQLITE_NULL,     /* 0x0b */
 77155       SQLITE_INTEGER,  /* 0x0c */
 77156       SQLITE_NULL,     /* 0x0d */
 77157       SQLITE_INTEGER,  /* 0x0e */
 77158       SQLITE_NULL,     /* 0x0f */
 77159       SQLITE_BLOB,     /* 0x10 */
 77160       SQLITE_NULL,     /* 0x11 */
 77161       SQLITE_TEXT,     /* 0x12 */
 77162       SQLITE_NULL,     /* 0x13 */
 77163       SQLITE_INTEGER,  /* 0x14 */
 77164       SQLITE_NULL,     /* 0x15 */
 77165       SQLITE_INTEGER,  /* 0x16 */
 77166       SQLITE_NULL,     /* 0x17 */
 77167       SQLITE_FLOAT,    /* 0x18 */
 77168       SQLITE_NULL,     /* 0x19 */
 77169       SQLITE_FLOAT,    /* 0x1a */
 77170       SQLITE_NULL,     /* 0x1b */
 77171       SQLITE_INTEGER,  /* 0x1c */
 77172       SQLITE_NULL,     /* 0x1d */
 77173       SQLITE_INTEGER,  /* 0x1e */
 77174       SQLITE_NULL,     /* 0x1f */
 77175    };
 77176    return aType[pVal->flags&MEM_AffMask];
 77177  }
 77178  
 77179  /* Make a copy of an sqlite3_value object
 77180  */
 77181  SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
 77182    sqlite3_value *pNew;
 77183    if( pOrig==0 ) return 0;
 77184    pNew = sqlite3_malloc( sizeof(*pNew) );
 77185    if( pNew==0 ) return 0;
 77186    memset(pNew, 0, sizeof(*pNew));
 77187    memcpy(pNew, pOrig, MEMCELLSIZE);
 77188    pNew->flags &= ~MEM_Dyn;
 77189    pNew->db = 0;
 77190    if( pNew->flags&(MEM_Str|MEM_Blob) ){
 77191      pNew->flags &= ~(MEM_Static|MEM_Dyn);
 77192      pNew->flags |= MEM_Ephem;
 77193      if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
 77194        sqlite3ValueFree(pNew);
 77195        pNew = 0;
 77196      }
 77197    }
 77198    return pNew;
 77199  }
 77200  
 77201  /* Destroy an sqlite3_value object previously obtained from
 77202  ** sqlite3_value_dup().
 77203  */
 77204  SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
 77205    sqlite3ValueFree(pOld);
 77206  }
 77207    
 77208  
 77209  /**************************** sqlite3_result_  *******************************
 77210  ** The following routines are used by user-defined functions to specify
 77211  ** the function result.
 77212  **
 77213  ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
 77214  ** result as a string or blob but if the string or blob is too large, it
 77215  ** then sets the error code to SQLITE_TOOBIG
 77216  **
 77217  ** The invokeValueDestructor(P,X) routine invokes destructor function X()
 77218  ** on value P is not going to be used and need to be destroyed.
 77219  */
 77220  static void setResultStrOrError(
 77221    sqlite3_context *pCtx,  /* Function context */
 77222    const char *z,          /* String pointer */
 77223    int n,                  /* Bytes in string, or negative */
 77224    u8 enc,                 /* Encoding of z.  0 for BLOBs */
 77225    void (*xDel)(void*)     /* Destructor function */
 77226  ){
 77227    if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
 77228      sqlite3_result_error_toobig(pCtx);
 77229    }
 77230  }
 77231  static int invokeValueDestructor(
 77232    const void *p,             /* Value to destroy */
 77233    void (*xDel)(void*),       /* The destructor */
 77234    sqlite3_context *pCtx      /* Set a SQLITE_TOOBIG error if no NULL */
 77235  ){
 77236    assert( xDel!=SQLITE_DYNAMIC );
 77237    if( xDel==0 ){
 77238      /* noop */
 77239    }else if( xDel==SQLITE_TRANSIENT ){
 77240      /* noop */
 77241    }else{
 77242      xDel((void*)p);
 77243    }
 77244    if( pCtx ) sqlite3_result_error_toobig(pCtx);
 77245    return SQLITE_TOOBIG;
 77246  }
 77247  SQLITE_API void sqlite3_result_blob(
 77248    sqlite3_context *pCtx, 
 77249    const void *z, 
 77250    int n, 
 77251    void (*xDel)(void *)
 77252  ){
 77253    assert( n>=0 );
 77254    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 77255    setResultStrOrError(pCtx, z, n, 0, xDel);
 77256  }
 77257  SQLITE_API void sqlite3_result_blob64(
 77258    sqlite3_context *pCtx, 
 77259    const void *z, 
 77260    sqlite3_uint64 n,
 77261    void (*xDel)(void *)
 77262  ){
 77263    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 77264    assert( xDel!=SQLITE_DYNAMIC );
 77265    if( n>0x7fffffff ){
 77266      (void)invokeValueDestructor(z, xDel, pCtx);
 77267    }else{
 77268      setResultStrOrError(pCtx, z, (int)n, 0, xDel);
 77269    }
 77270  }
 77271  SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
 77272    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 77273    sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
 77274  }
 77275  SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
 77276    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 77277    pCtx->isError = SQLITE_ERROR;
 77278    pCtx->fErrorOrAux = 1;
 77279    sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
 77280  }
 77281  #ifndef SQLITE_OMIT_UTF16
 77282  SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
 77283    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 77284    pCtx->isError = SQLITE_ERROR;
 77285    pCtx->fErrorOrAux = 1;
 77286    sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
 77287  }
 77288  #endif
 77289  SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
 77290    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 77291    sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
 77292  }
 77293  SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
 77294    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 77295    sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
 77296  }
 77297  SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
 77298    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 77299    sqlite3VdbeMemSetNull(pCtx->pOut);
 77300  }
 77301  SQLITE_API void sqlite3_result_pointer(
 77302    sqlite3_context *pCtx,
 77303    void *pPtr,
 77304    const char *zPType,
 77305    void (*xDestructor)(void*)
 77306  ){
 77307    Mem *pOut = pCtx->pOut;
 77308    assert( sqlite3_mutex_held(pOut->db->mutex) );
 77309    sqlite3VdbeMemRelease(pOut);
 77310    pOut->flags = MEM_Null;
 77311    sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);
 77312  }
 77313  SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
 77314    Mem *pOut = pCtx->pOut;
 77315    assert( sqlite3_mutex_held(pOut->db->mutex) );
 77316    pOut->eSubtype = eSubtype & 0xff;
 77317    pOut->flags |= MEM_Subtype;
 77318  }
 77319  SQLITE_API void sqlite3_result_text(
 77320    sqlite3_context *pCtx, 
 77321    const char *z, 
 77322    int n,
 77323    void (*xDel)(void *)
 77324  ){
 77325    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 77326    setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
 77327  }
 77328  SQLITE_API void sqlite3_result_text64(
 77329    sqlite3_context *pCtx, 
 77330    const char *z, 
 77331    sqlite3_uint64 n,
 77332    void (*xDel)(void *),
 77333    unsigned char enc
 77334  ){
 77335    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 77336    assert( xDel!=SQLITE_DYNAMIC );
 77337    if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
 77338    if( n>0x7fffffff ){
 77339      (void)invokeValueDestructor(z, xDel, pCtx);
 77340    }else{
 77341      setResultStrOrError(pCtx, z, (int)n, enc, xDel);
 77342    }
 77343  }
 77344  #ifndef SQLITE_OMIT_UTF16
 77345  SQLITE_API void sqlite3_result_text16(
 77346    sqlite3_context *pCtx, 
 77347    const void *z, 
 77348    int n, 
 77349    void (*xDel)(void *)
 77350  ){
 77351    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 77352    setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
 77353  }
 77354  SQLITE_API void sqlite3_result_text16be(
 77355    sqlite3_context *pCtx, 
 77356    const void *z, 
 77357    int n, 
 77358    void (*xDel)(void *)
 77359  ){
 77360    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 77361    setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
 77362  }
 77363  SQLITE_API void sqlite3_result_text16le(
 77364    sqlite3_context *pCtx, 
 77365    const void *z, 
 77366    int n, 
 77367    void (*xDel)(void *)
 77368  ){
 77369    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 77370    setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
 77371  }
 77372  #endif /* SQLITE_OMIT_UTF16 */
 77373  SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
 77374    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 77375    sqlite3VdbeMemCopy(pCtx->pOut, pValue);
 77376  }
 77377  SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
 77378    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 77379    sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
 77380  }
 77381  SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
 77382    Mem *pOut = pCtx->pOut;
 77383    assert( sqlite3_mutex_held(pOut->db->mutex) );
 77384    if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
 77385      return SQLITE_TOOBIG;
 77386    }
 77387    sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
 77388    return SQLITE_OK;
 77389  }
 77390  SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
 77391    pCtx->isError = errCode;
 77392    pCtx->fErrorOrAux = 1;
 77393  #ifdef SQLITE_DEBUG
 77394    if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
 77395  #endif
 77396    if( pCtx->pOut->flags & MEM_Null ){
 77397      sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1, 
 77398                           SQLITE_UTF8, SQLITE_STATIC);
 77399    }
 77400  }
 77401  
 77402  /* Force an SQLITE_TOOBIG error. */
 77403  SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
 77404    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 77405    pCtx->isError = SQLITE_TOOBIG;
 77406    pCtx->fErrorOrAux = 1;
 77407    sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1, 
 77408                         SQLITE_UTF8, SQLITE_STATIC);
 77409  }
 77410  
 77411  /* An SQLITE_NOMEM error. */
 77412  SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
 77413    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 77414    sqlite3VdbeMemSetNull(pCtx->pOut);
 77415    pCtx->isError = SQLITE_NOMEM_BKPT;
 77416    pCtx->fErrorOrAux = 1;
 77417    sqlite3OomFault(pCtx->pOut->db);
 77418  }
 77419  
 77420  /*
 77421  ** This function is called after a transaction has been committed. It 
 77422  ** invokes callbacks registered with sqlite3_wal_hook() as required.
 77423  */
 77424  static int doWalCallbacks(sqlite3 *db){
 77425    int rc = SQLITE_OK;
 77426  #ifndef SQLITE_OMIT_WAL
 77427    int i;
 77428    for(i=0; i<db->nDb; i++){
 77429      Btree *pBt = db->aDb[i].pBt;
 77430      if( pBt ){
 77431        int nEntry;
 77432        sqlite3BtreeEnter(pBt);
 77433        nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
 77434        sqlite3BtreeLeave(pBt);
 77435        if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){
 77436          rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
 77437        }
 77438      }
 77439    }
 77440  #endif
 77441    return rc;
 77442  }
 77443  
 77444  
 77445  /*
 77446  ** Execute the statement pStmt, either until a row of data is ready, the
 77447  ** statement is completely executed or an error occurs.
 77448  **
 77449  ** This routine implements the bulk of the logic behind the sqlite_step()
 77450  ** API.  The only thing omitted is the automatic recompile if a 
 77451  ** schema change has occurred.  That detail is handled by the
 77452  ** outer sqlite3_step() wrapper procedure.
 77453  */
 77454  static int sqlite3Step(Vdbe *p){
 77455    sqlite3 *db;
 77456    int rc;
 77457  
 77458    assert(p);
 77459    if( p->magic!=VDBE_MAGIC_RUN ){
 77460      /* We used to require that sqlite3_reset() be called before retrying
 77461      ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
 77462      ** with version 3.7.0, we changed this so that sqlite3_reset() would
 77463      ** be called automatically instead of throwing the SQLITE_MISUSE error.
 77464      ** This "automatic-reset" change is not technically an incompatibility, 
 77465      ** since any application that receives an SQLITE_MISUSE is broken by
 77466      ** definition.
 77467      **
 77468      ** Nevertheless, some published applications that were originally written
 77469      ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE 
 77470      ** returns, and those were broken by the automatic-reset change.  As a
 77471      ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
 77472      ** legacy behavior of returning SQLITE_MISUSE for cases where the 
 77473      ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
 77474      ** or SQLITE_BUSY error.
 77475      */
 77476  #ifdef SQLITE_OMIT_AUTORESET
 77477      if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
 77478        sqlite3_reset((sqlite3_stmt*)p);
 77479      }else{
 77480        return SQLITE_MISUSE_BKPT;
 77481      }
 77482  #else
 77483      sqlite3_reset((sqlite3_stmt*)p);
 77484  #endif
 77485    }
 77486  
 77487    /* Check that malloc() has not failed. If it has, return early. */
 77488    db = p->db;
 77489    if( db->mallocFailed ){
 77490      p->rc = SQLITE_NOMEM;
 77491      return SQLITE_NOMEM_BKPT;
 77492    }
 77493  
 77494    if( p->pc<=0 && p->expired ){
 77495      p->rc = SQLITE_SCHEMA;
 77496      rc = SQLITE_ERROR;
 77497      goto end_of_step;
 77498    }
 77499    if( p->pc<0 ){
 77500      /* If there are no other statements currently running, then
 77501      ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
 77502      ** from interrupting a statement that has not yet started.
 77503      */
 77504      if( db->nVdbeActive==0 ){
 77505        db->u1.isInterrupted = 0;
 77506      }
 77507  
 77508      assert( db->nVdbeWrite>0 || db->autoCommit==0 
 77509          || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
 77510      );
 77511  
 77512  #ifndef SQLITE_OMIT_TRACE
 77513      if( (db->xProfile || (db->mTrace & SQLITE_TRACE_PROFILE)!=0)
 77514          && !db->init.busy && p->zSql ){
 77515        sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
 77516      }else{
 77517        assert( p->startTime==0 );
 77518      }
 77519  #endif
 77520  
 77521      db->nVdbeActive++;
 77522      if( p->readOnly==0 ) db->nVdbeWrite++;
 77523      if( p->bIsReader ) db->nVdbeRead++;
 77524      p->pc = 0;
 77525    }
 77526  #ifdef SQLITE_DEBUG
 77527    p->rcApp = SQLITE_OK;
 77528  #endif
 77529  #ifndef SQLITE_OMIT_EXPLAIN
 77530    if( p->explain ){
 77531      rc = sqlite3VdbeList(p);
 77532    }else
 77533  #endif /* SQLITE_OMIT_EXPLAIN */
 77534    {
 77535      db->nVdbeExec++;
 77536      rc = sqlite3VdbeExec(p);
 77537      db->nVdbeExec--;
 77538    }
 77539  
 77540  #ifndef SQLITE_OMIT_TRACE
 77541    /* If the statement completed successfully, invoke the profile callback */
 77542    if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
 77543  #endif
 77544  
 77545    if( rc==SQLITE_DONE && db->autoCommit ){
 77546      assert( p->rc==SQLITE_OK );
 77547      p->rc = doWalCallbacks(db);
 77548      if( p->rc!=SQLITE_OK ){
 77549        rc = SQLITE_ERROR;
 77550      }
 77551    }
 77552  
 77553    db->errCode = rc;
 77554    if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
 77555      p->rc = SQLITE_NOMEM_BKPT;
 77556    }
 77557  end_of_step:
 77558    /* At this point local variable rc holds the value that should be 
 77559    ** returned if this statement was compiled using the legacy 
 77560    ** sqlite3_prepare() interface. According to the docs, this can only
 77561    ** be one of the values in the first assert() below. Variable p->rc 
 77562    ** contains the value that would be returned if sqlite3_finalize() 
 77563    ** were called on statement p.
 77564    */
 77565    assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
 77566         || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
 77567    );
 77568    assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
 77569    if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 
 77570     && rc!=SQLITE_ROW 
 77571     && rc!=SQLITE_DONE 
 77572    ){
 77573      /* If this statement was prepared using saved SQL and an 
 77574      ** error has occurred, then return the error code in p->rc to the
 77575      ** caller. Set the error code in the database handle to the same value.
 77576      */ 
 77577      rc = sqlite3VdbeTransferError(p);
 77578    }
 77579    return (rc&db->errMask);
 77580  }
 77581  
 77582  /*
 77583  ** This is the top-level implementation of sqlite3_step().  Call
 77584  ** sqlite3Step() to do most of the work.  If a schema error occurs,
 77585  ** call sqlite3Reprepare() and try again.
 77586  */
 77587  SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
 77588    int rc = SQLITE_OK;      /* Result from sqlite3Step() */
 77589    Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
 77590    int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
 77591    sqlite3 *db;             /* The database connection */
 77592  
 77593    if( vdbeSafetyNotNull(v) ){
 77594      return SQLITE_MISUSE_BKPT;
 77595    }
 77596    db = v->db;
 77597    sqlite3_mutex_enter(db->mutex);
 77598    v->doingRerun = 0;
 77599    while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
 77600           && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
 77601      int savedPc = v->pc;
 77602      rc = sqlite3Reprepare(v);
 77603      if( rc!=SQLITE_OK ){
 77604        /* This case occurs after failing to recompile an sql statement. 
 77605        ** The error message from the SQL compiler has already been loaded 
 77606        ** into the database handle. This block copies the error message 
 77607        ** from the database handle into the statement and sets the statement
 77608        ** program counter to 0 to ensure that when the statement is 
 77609        ** finalized or reset the parser error message is available via
 77610        ** sqlite3_errmsg() and sqlite3_errcode().
 77611        */
 77612        const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
 77613        sqlite3DbFree(db, v->zErrMsg);
 77614        if( !db->mallocFailed ){
 77615          v->zErrMsg = sqlite3DbStrDup(db, zErr);
 77616          v->rc = rc = sqlite3ApiExit(db, rc);
 77617        } else {
 77618          v->zErrMsg = 0;
 77619          v->rc = rc = SQLITE_NOMEM_BKPT;
 77620        }
 77621        break;
 77622      }
 77623      sqlite3_reset(pStmt);
 77624      if( savedPc>=0 ) v->doingRerun = 1;
 77625      assert( v->expired==0 );
 77626    }
 77627    sqlite3_mutex_leave(db->mutex);
 77628    return rc;
 77629  }
 77630  
 77631  
 77632  /*
 77633  ** Extract the user data from a sqlite3_context structure and return a
 77634  ** pointer to it.
 77635  */
 77636  SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
 77637    assert( p && p->pFunc );
 77638    return p->pFunc->pUserData;
 77639  }
 77640  
 77641  /*
 77642  ** Extract the user data from a sqlite3_context structure and return a
 77643  ** pointer to it.
 77644  **
 77645  ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
 77646  ** returns a copy of the pointer to the database connection (the 1st
 77647  ** parameter) of the sqlite3_create_function() and
 77648  ** sqlite3_create_function16() routines that originally registered the
 77649  ** application defined function.
 77650  */
 77651  SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
 77652    assert( p && p->pOut );
 77653    return p->pOut->db;
 77654  }
 77655  
 77656  /*
 77657  ** Return the current time for a statement.  If the current time
 77658  ** is requested more than once within the same run of a single prepared
 77659  ** statement, the exact same time is returned for each invocation regardless
 77660  ** of the amount of time that elapses between invocations.  In other words,
 77661  ** the time returned is always the time of the first call.
 77662  */
 77663  SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
 77664    int rc;
 77665  #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
 77666    sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
 77667    assert( p->pVdbe!=0 );
 77668  #else
 77669    sqlite3_int64 iTime = 0;
 77670    sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
 77671  #endif
 77672    if( *piTime==0 ){
 77673      rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
 77674      if( rc ) *piTime = 0;
 77675    }
 77676    return *piTime;
 77677  }
 77678  
 77679  /*
 77680  ** The following is the implementation of an SQL function that always
 77681  ** fails with an error message stating that the function is used in the
 77682  ** wrong context.  The sqlite3_overload_function() API might construct
 77683  ** SQL function that use this routine so that the functions will exist
 77684  ** for name resolution but are actually overloaded by the xFindFunction
 77685  ** method of virtual tables.
 77686  */
 77687  SQLITE_PRIVATE void sqlite3InvalidFunction(
 77688    sqlite3_context *context,  /* The function calling context */
 77689    int NotUsed,               /* Number of arguments to the function */
 77690    sqlite3_value **NotUsed2   /* Value of each argument */
 77691  ){
 77692    const char *zName = context->pFunc->zName;
 77693    char *zErr;
 77694    UNUSED_PARAMETER2(NotUsed, NotUsed2);
 77695    zErr = sqlite3_mprintf(
 77696        "unable to use function %s in the requested context", zName);
 77697    sqlite3_result_error(context, zErr, -1);
 77698    sqlite3_free(zErr);
 77699  }
 77700  
 77701  /*
 77702  ** Create a new aggregate context for p and return a pointer to
 77703  ** its pMem->z element.
 77704  */
 77705  static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
 77706    Mem *pMem = p->pMem;
 77707    assert( (pMem->flags & MEM_Agg)==0 );
 77708    if( nByte<=0 ){
 77709      sqlite3VdbeMemSetNull(pMem);
 77710      pMem->z = 0;
 77711    }else{
 77712      sqlite3VdbeMemClearAndResize(pMem, nByte);
 77713      pMem->flags = MEM_Agg;
 77714      pMem->u.pDef = p->pFunc;
 77715      if( pMem->z ){
 77716        memset(pMem->z, 0, nByte);
 77717      }
 77718    }
 77719    return (void*)pMem->z;
 77720  }
 77721  
 77722  /*
 77723  ** Allocate or return the aggregate context for a user function.  A new
 77724  ** context is allocated on the first call.  Subsequent calls return the
 77725  ** same context that was returned on prior calls.
 77726  */
 77727  SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
 77728    assert( p && p->pFunc && p->pFunc->xFinalize );
 77729    assert( sqlite3_mutex_held(p->pOut->db->mutex) );
 77730    testcase( nByte<0 );
 77731    if( (p->pMem->flags & MEM_Agg)==0 ){
 77732      return createAggContext(p, nByte);
 77733    }else{
 77734      return (void*)p->pMem->z;
 77735    }
 77736  }
 77737  
 77738  /*
 77739  ** Return the auxiliary data pointer, if any, for the iArg'th argument to
 77740  ** the user-function defined by pCtx.
 77741  **
 77742  ** The left-most argument is 0.
 77743  **
 77744  ** Undocumented behavior:  If iArg is negative then access a cache of
 77745  ** auxiliary data pointers that is available to all functions within a
 77746  ** single prepared statement.  The iArg values must match.
 77747  */
 77748  SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
 77749    AuxData *pAuxData;
 77750  
 77751    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 77752  #if SQLITE_ENABLE_STAT3_OR_STAT4
 77753    if( pCtx->pVdbe==0 ) return 0;
 77754  #else
 77755    assert( pCtx->pVdbe!=0 );
 77756  #endif
 77757    for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
 77758      if(  pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
 77759        return pAuxData->pAux;
 77760      }
 77761    }
 77762    return 0;
 77763  }
 77764  
 77765  /*
 77766  ** Set the auxiliary data pointer and delete function, for the iArg'th
 77767  ** argument to the user-function defined by pCtx. Any previous value is
 77768  ** deleted by calling the delete function specified when it was set.
 77769  **
 77770  ** The left-most argument is 0.
 77771  **
 77772  ** Undocumented behavior:  If iArg is negative then make the data available
 77773  ** to all functions within the current prepared statement using iArg as an
 77774  ** access code.
 77775  */
 77776  SQLITE_API void sqlite3_set_auxdata(
 77777    sqlite3_context *pCtx, 
 77778    int iArg, 
 77779    void *pAux, 
 77780    void (*xDelete)(void*)
 77781  ){
 77782    AuxData *pAuxData;
 77783    Vdbe *pVdbe = pCtx->pVdbe;
 77784  
 77785    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 77786  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 77787    if( pVdbe==0 ) goto failed;
 77788  #else
 77789    assert( pVdbe!=0 );
 77790  #endif
 77791  
 77792    for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
 77793      if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
 77794        break;
 77795      }
 77796    }
 77797    if( pAuxData==0 ){
 77798      pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
 77799      if( !pAuxData ) goto failed;
 77800      pAuxData->iAuxOp = pCtx->iOp;
 77801      pAuxData->iAuxArg = iArg;
 77802      pAuxData->pNextAux = pVdbe->pAuxData;
 77803      pVdbe->pAuxData = pAuxData;
 77804      if( pCtx->fErrorOrAux==0 ){
 77805        pCtx->isError = 0;
 77806        pCtx->fErrorOrAux = 1;
 77807      }
 77808    }else if( pAuxData->xDeleteAux ){
 77809      pAuxData->xDeleteAux(pAuxData->pAux);
 77810    }
 77811  
 77812    pAuxData->pAux = pAux;
 77813    pAuxData->xDeleteAux = xDelete;
 77814    return;
 77815  
 77816  failed:
 77817    if( xDelete ){
 77818      xDelete(pAux);
 77819    }
 77820  }
 77821  
 77822  #ifndef SQLITE_OMIT_DEPRECATED
 77823  /*
 77824  ** Return the number of times the Step function of an aggregate has been 
 77825  ** called.
 77826  **
 77827  ** This function is deprecated.  Do not use it for new code.  It is
 77828  ** provide only to avoid breaking legacy code.  New aggregate function
 77829  ** implementations should keep their own counts within their aggregate
 77830  ** context.
 77831  */
 77832  SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
 77833    assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
 77834    return p->pMem->n;
 77835  }
 77836  #endif
 77837  
 77838  /*
 77839  ** Return the number of columns in the result set for the statement pStmt.
 77840  */
 77841  SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
 77842    Vdbe *pVm = (Vdbe *)pStmt;
 77843    return pVm ? pVm->nResColumn : 0;
 77844  }
 77845  
 77846  /*
 77847  ** Return the number of values available from the current row of the
 77848  ** currently executing statement pStmt.
 77849  */
 77850  SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
 77851    Vdbe *pVm = (Vdbe *)pStmt;
 77852    if( pVm==0 || pVm->pResultSet==0 ) return 0;
 77853    return pVm->nResColumn;
 77854  }
 77855  
 77856  /*
 77857  ** Return a pointer to static memory containing an SQL NULL value.
 77858  */
 77859  static const Mem *columnNullValue(void){
 77860    /* Even though the Mem structure contains an element
 77861    ** of type i64, on certain architectures (x86) with certain compiler
 77862    ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
 77863    ** instead of an 8-byte one. This all works fine, except that when
 77864    ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
 77865    ** that a Mem structure is located on an 8-byte boundary. To prevent
 77866    ** these assert()s from failing, when building with SQLITE_DEBUG defined
 77867    ** using gcc, we force nullMem to be 8-byte aligned using the magical
 77868    ** __attribute__((aligned(8))) macro.  */
 77869    static const Mem nullMem 
 77870  #if defined(SQLITE_DEBUG) && defined(__GNUC__)
 77871      __attribute__((aligned(8))) 
 77872  #endif
 77873      = {
 77874          /* .u          = */ {0},
 77875          /* .flags      = */ (u16)MEM_Null,
 77876          /* .enc        = */ (u8)0,
 77877          /* .eSubtype   = */ (u8)0,
 77878          /* .n          = */ (int)0,
 77879          /* .z          = */ (char*)0,
 77880          /* .zMalloc    = */ (char*)0,
 77881          /* .szMalloc   = */ (int)0,
 77882          /* .uTemp      = */ (u32)0,
 77883          /* .db         = */ (sqlite3*)0,
 77884          /* .xDel       = */ (void(*)(void*))0,
 77885  #ifdef SQLITE_DEBUG
 77886          /* .pScopyFrom = */ (Mem*)0,
 77887          /* .pFiller    = */ (void*)0,
 77888  #endif
 77889        };
 77890    return &nullMem;
 77891  }
 77892  
 77893  /*
 77894  ** Check to see if column iCol of the given statement is valid.  If
 77895  ** it is, return a pointer to the Mem for the value of that column.
 77896  ** If iCol is not valid, return a pointer to a Mem which has a value
 77897  ** of NULL.
 77898  */
 77899  static Mem *columnMem(sqlite3_stmt *pStmt, int i){
 77900    Vdbe *pVm;
 77901    Mem *pOut;
 77902  
 77903    pVm = (Vdbe *)pStmt;
 77904    if( pVm==0 ) return (Mem*)columnNullValue();
 77905    assert( pVm->db );
 77906    sqlite3_mutex_enter(pVm->db->mutex);
 77907    if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
 77908      pOut = &pVm->pResultSet[i];
 77909    }else{
 77910      sqlite3Error(pVm->db, SQLITE_RANGE);
 77911      pOut = (Mem*)columnNullValue();
 77912    }
 77913    return pOut;
 77914  }
 77915  
 77916  /*
 77917  ** This function is called after invoking an sqlite3_value_XXX function on a 
 77918  ** column value (i.e. a value returned by evaluating an SQL expression in the
 77919  ** select list of a SELECT statement) that may cause a malloc() failure. If 
 77920  ** malloc() has failed, the threads mallocFailed flag is cleared and the result
 77921  ** code of statement pStmt set to SQLITE_NOMEM.
 77922  **
 77923  ** Specifically, this is called from within:
 77924  **
 77925  **     sqlite3_column_int()
 77926  **     sqlite3_column_int64()
 77927  **     sqlite3_column_text()
 77928  **     sqlite3_column_text16()
 77929  **     sqlite3_column_real()
 77930  **     sqlite3_column_bytes()
 77931  **     sqlite3_column_bytes16()
 77932  **     sqiite3_column_blob()
 77933  */
 77934  static void columnMallocFailure(sqlite3_stmt *pStmt)
 77935  {
 77936    /* If malloc() failed during an encoding conversion within an
 77937    ** sqlite3_column_XXX API, then set the return code of the statement to
 77938    ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
 77939    ** and _finalize() will return NOMEM.
 77940    */
 77941    Vdbe *p = (Vdbe *)pStmt;
 77942    if( p ){
 77943      assert( p->db!=0 );
 77944      assert( sqlite3_mutex_held(p->db->mutex) );
 77945      p->rc = sqlite3ApiExit(p->db, p->rc);
 77946      sqlite3_mutex_leave(p->db->mutex);
 77947    }
 77948  }
 77949  
 77950  /**************************** sqlite3_column_  *******************************
 77951  ** The following routines are used to access elements of the current row
 77952  ** in the result set.
 77953  */
 77954  SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
 77955    const void *val;
 77956    val = sqlite3_value_blob( columnMem(pStmt,i) );
 77957    /* Even though there is no encoding conversion, value_blob() might
 77958    ** need to call malloc() to expand the result of a zeroblob() 
 77959    ** expression. 
 77960    */
 77961    columnMallocFailure(pStmt);
 77962    return val;
 77963  }
 77964  SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
 77965    int val = sqlite3_value_bytes( columnMem(pStmt,i) );
 77966    columnMallocFailure(pStmt);
 77967    return val;
 77968  }
 77969  SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
 77970    int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
 77971    columnMallocFailure(pStmt);
 77972    return val;
 77973  }
 77974  SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
 77975    double val = sqlite3_value_double( columnMem(pStmt,i) );
 77976    columnMallocFailure(pStmt);
 77977    return val;
 77978  }
 77979  SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
 77980    int val = sqlite3_value_int( columnMem(pStmt,i) );
 77981    columnMallocFailure(pStmt);
 77982    return val;
 77983  }
 77984  SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
 77985    sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
 77986    columnMallocFailure(pStmt);
 77987    return val;
 77988  }
 77989  SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
 77990    const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
 77991    columnMallocFailure(pStmt);
 77992    return val;
 77993  }
 77994  SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
 77995    Mem *pOut = columnMem(pStmt, i);
 77996    if( pOut->flags&MEM_Static ){
 77997      pOut->flags &= ~MEM_Static;
 77998      pOut->flags |= MEM_Ephem;
 77999    }
 78000    columnMallocFailure(pStmt);
 78001    return (sqlite3_value *)pOut;
 78002  }
 78003  #ifndef SQLITE_OMIT_UTF16
 78004  SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
 78005    const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
 78006    columnMallocFailure(pStmt);
 78007    return val;
 78008  }
 78009  #endif /* SQLITE_OMIT_UTF16 */
 78010  SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
 78011    int iType = sqlite3_value_type( columnMem(pStmt,i) );
 78012    columnMallocFailure(pStmt);
 78013    return iType;
 78014  }
 78015  
 78016  /*
 78017  ** Convert the N-th element of pStmt->pColName[] into a string using
 78018  ** xFunc() then return that string.  If N is out of range, return 0.
 78019  **
 78020  ** There are up to 5 names for each column.  useType determines which
 78021  ** name is returned.  Here are the names:
 78022  **
 78023  **    0      The column name as it should be displayed for output
 78024  **    1      The datatype name for the column
 78025  **    2      The name of the database that the column derives from
 78026  **    3      The name of the table that the column derives from
 78027  **    4      The name of the table column that the result column derives from
 78028  **
 78029  ** If the result is not a simple column reference (if it is an expression
 78030  ** or a constant) then useTypes 2, 3, and 4 return NULL.
 78031  */
 78032  static const void *columnName(
 78033    sqlite3_stmt *pStmt,
 78034    int N,
 78035    const void *(*xFunc)(Mem*),
 78036    int useType
 78037  ){
 78038    const void *ret;
 78039    Vdbe *p;
 78040    int n;
 78041    sqlite3 *db;
 78042  #ifdef SQLITE_ENABLE_API_ARMOR
 78043    if( pStmt==0 ){
 78044      (void)SQLITE_MISUSE_BKPT;
 78045      return 0;
 78046    }
 78047  #endif
 78048    ret = 0;
 78049    p = (Vdbe *)pStmt;
 78050    db = p->db;
 78051    assert( db!=0 );
 78052    n = sqlite3_column_count(pStmt);
 78053    if( N<n && N>=0 ){
 78054      N += useType*n;
 78055      sqlite3_mutex_enter(db->mutex);
 78056      assert( db->mallocFailed==0 );
 78057      ret = xFunc(&p->aColName[N]);
 78058       /* A malloc may have failed inside of the xFunc() call. If this
 78059      ** is the case, clear the mallocFailed flag and return NULL.
 78060      */
 78061      if( db->mallocFailed ){
 78062        sqlite3OomClear(db);
 78063        ret = 0;
 78064      }
 78065      sqlite3_mutex_leave(db->mutex);
 78066    }
 78067    return ret;
 78068  }
 78069  
 78070  /*
 78071  ** Return the name of the Nth column of the result set returned by SQL
 78072  ** statement pStmt.
 78073  */
 78074  SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
 78075    return columnName(
 78076        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
 78077  }
 78078  #ifndef SQLITE_OMIT_UTF16
 78079  SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
 78080    return columnName(
 78081        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
 78082  }
 78083  #endif
 78084  
 78085  /*
 78086  ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
 78087  ** not define OMIT_DECLTYPE.
 78088  */
 78089  #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
 78090  # error "Must not define both SQLITE_OMIT_DECLTYPE \
 78091           and SQLITE_ENABLE_COLUMN_METADATA"
 78092  #endif
 78093  
 78094  #ifndef SQLITE_OMIT_DECLTYPE
 78095  /*
 78096  ** Return the column declaration type (if applicable) of the 'i'th column
 78097  ** of the result set of SQL statement pStmt.
 78098  */
 78099  SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
 78100    return columnName(
 78101        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
 78102  }
 78103  #ifndef SQLITE_OMIT_UTF16
 78104  SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
 78105    return columnName(
 78106        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
 78107  }
 78108  #endif /* SQLITE_OMIT_UTF16 */
 78109  #endif /* SQLITE_OMIT_DECLTYPE */
 78110  
 78111  #ifdef SQLITE_ENABLE_COLUMN_METADATA
 78112  /*
 78113  ** Return the name of the database from which a result column derives.
 78114  ** NULL is returned if the result column is an expression or constant or
 78115  ** anything else which is not an unambiguous reference to a database column.
 78116  */
 78117  SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
 78118    return columnName(
 78119        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
 78120  }
 78121  #ifndef SQLITE_OMIT_UTF16
 78122  SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
 78123    return columnName(
 78124        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
 78125  }
 78126  #endif /* SQLITE_OMIT_UTF16 */
 78127  
 78128  /*
 78129  ** Return the name of the table from which a result column derives.
 78130  ** NULL is returned if the result column is an expression or constant or
 78131  ** anything else which is not an unambiguous reference to a database column.
 78132  */
 78133  SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
 78134    return columnName(
 78135        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
 78136  }
 78137  #ifndef SQLITE_OMIT_UTF16
 78138  SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
 78139    return columnName(
 78140        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
 78141  }
 78142  #endif /* SQLITE_OMIT_UTF16 */
 78143  
 78144  /*
 78145  ** Return the name of the table column from which a result column derives.
 78146  ** NULL is returned if the result column is an expression or constant or
 78147  ** anything else which is not an unambiguous reference to a database column.
 78148  */
 78149  SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
 78150    return columnName(
 78151        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
 78152  }
 78153  #ifndef SQLITE_OMIT_UTF16
 78154  SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
 78155    return columnName(
 78156        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
 78157  }
 78158  #endif /* SQLITE_OMIT_UTF16 */
 78159  #endif /* SQLITE_ENABLE_COLUMN_METADATA */
 78160  
 78161  
 78162  /******************************* sqlite3_bind_  ***************************
 78163  ** 
 78164  ** Routines used to attach values to wildcards in a compiled SQL statement.
 78165  */
 78166  /*
 78167  ** Unbind the value bound to variable i in virtual machine p. This is the 
 78168  ** the same as binding a NULL value to the column. If the "i" parameter is
 78169  ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
 78170  **
 78171  ** A successful evaluation of this routine acquires the mutex on p.
 78172  ** the mutex is released if any kind of error occurs.
 78173  **
 78174  ** The error code stored in database p->db is overwritten with the return
 78175  ** value in any case.
 78176  */
 78177  static int vdbeUnbind(Vdbe *p, int i){
 78178    Mem *pVar;
 78179    if( vdbeSafetyNotNull(p) ){
 78180      return SQLITE_MISUSE_BKPT;
 78181    }
 78182    sqlite3_mutex_enter(p->db->mutex);
 78183    if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
 78184      sqlite3Error(p->db, SQLITE_MISUSE);
 78185      sqlite3_mutex_leave(p->db->mutex);
 78186      sqlite3_log(SQLITE_MISUSE, 
 78187          "bind on a busy prepared statement: [%s]", p->zSql);
 78188      return SQLITE_MISUSE_BKPT;
 78189    }
 78190    if( i<1 || i>p->nVar ){
 78191      sqlite3Error(p->db, SQLITE_RANGE);
 78192      sqlite3_mutex_leave(p->db->mutex);
 78193      return SQLITE_RANGE;
 78194    }
 78195    i--;
 78196    pVar = &p->aVar[i];
 78197    sqlite3VdbeMemRelease(pVar);
 78198    pVar->flags = MEM_Null;
 78199    sqlite3Error(p->db, SQLITE_OK);
 78200  
 78201    /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
 78202    ** binding a new value to this variable invalidates the current query plan.
 78203    **
 78204    ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
 78205    ** parameter in the WHERE clause might influence the choice of query plan
 78206    ** for a statement, then the statement will be automatically recompiled,
 78207    ** as if there had been a schema change, on the first sqlite3_step() call
 78208    ** following any change to the bindings of that parameter.
 78209    */
 78210    assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
 78211    if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
 78212      p->expired = 1;
 78213    }
 78214    return SQLITE_OK;
 78215  }
 78216  
 78217  /*
 78218  ** Bind a text or BLOB value.
 78219  */
 78220  static int bindText(
 78221    sqlite3_stmt *pStmt,   /* The statement to bind against */
 78222    int i,                 /* Index of the parameter to bind */
 78223    const void *zData,     /* Pointer to the data to be bound */
 78224    int nData,             /* Number of bytes of data to be bound */
 78225    void (*xDel)(void*),   /* Destructor for the data */
 78226    u8 encoding            /* Encoding for the data */
 78227  ){
 78228    Vdbe *p = (Vdbe *)pStmt;
 78229    Mem *pVar;
 78230    int rc;
 78231  
 78232    rc = vdbeUnbind(p, i);
 78233    if( rc==SQLITE_OK ){
 78234      if( zData!=0 ){
 78235        pVar = &p->aVar[i-1];
 78236        rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
 78237        if( rc==SQLITE_OK && encoding!=0 ){
 78238          rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
 78239        }
 78240        if( rc ){
 78241          sqlite3Error(p->db, rc);
 78242          rc = sqlite3ApiExit(p->db, rc);
 78243        }
 78244      }
 78245      sqlite3_mutex_leave(p->db->mutex);
 78246    }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
 78247      xDel((void*)zData);
 78248    }
 78249    return rc;
 78250  }
 78251  
 78252  
 78253  /*
 78254  ** Bind a blob value to an SQL statement variable.
 78255  */
 78256  SQLITE_API int sqlite3_bind_blob(
 78257    sqlite3_stmt *pStmt, 
 78258    int i, 
 78259    const void *zData, 
 78260    int nData, 
 78261    void (*xDel)(void*)
 78262  ){
 78263  #ifdef SQLITE_ENABLE_API_ARMOR
 78264    if( nData<0 ) return SQLITE_MISUSE_BKPT;
 78265  #endif
 78266    return bindText(pStmt, i, zData, nData, xDel, 0);
 78267  }
 78268  SQLITE_API int sqlite3_bind_blob64(
 78269    sqlite3_stmt *pStmt, 
 78270    int i, 
 78271    const void *zData, 
 78272    sqlite3_uint64 nData, 
 78273    void (*xDel)(void*)
 78274  ){
 78275    assert( xDel!=SQLITE_DYNAMIC );
 78276    if( nData>0x7fffffff ){
 78277      return invokeValueDestructor(zData, xDel, 0);
 78278    }else{
 78279      return bindText(pStmt, i, zData, (int)nData, xDel, 0);
 78280    }
 78281  }
 78282  SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
 78283    int rc;
 78284    Vdbe *p = (Vdbe *)pStmt;
 78285    rc = vdbeUnbind(p, i);
 78286    if( rc==SQLITE_OK ){
 78287      sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
 78288      sqlite3_mutex_leave(p->db->mutex);
 78289    }
 78290    return rc;
 78291  }
 78292  SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
 78293    return sqlite3_bind_int64(p, i, (i64)iValue);
 78294  }
 78295  SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
 78296    int rc;
 78297    Vdbe *p = (Vdbe *)pStmt;
 78298    rc = vdbeUnbind(p, i);
 78299    if( rc==SQLITE_OK ){
 78300      sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
 78301      sqlite3_mutex_leave(p->db->mutex);
 78302    }
 78303    return rc;
 78304  }
 78305  SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
 78306    int rc;
 78307    Vdbe *p = (Vdbe*)pStmt;
 78308    rc = vdbeUnbind(p, i);
 78309    if( rc==SQLITE_OK ){
 78310      sqlite3_mutex_leave(p->db->mutex);
 78311    }
 78312    return rc;
 78313  }
 78314  SQLITE_API int sqlite3_bind_pointer(
 78315    sqlite3_stmt *pStmt,
 78316    int i,
 78317    void *pPtr,
 78318    const char *zPTtype,
 78319    void (*xDestructor)(void*)
 78320  ){
 78321    int rc;
 78322    Vdbe *p = (Vdbe*)pStmt;
 78323    rc = vdbeUnbind(p, i);
 78324    if( rc==SQLITE_OK ){
 78325      sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
 78326      sqlite3_mutex_leave(p->db->mutex);
 78327    }else if( xDestructor ){
 78328      xDestructor(pPtr);
 78329    }
 78330    return rc;
 78331  }
 78332  SQLITE_API int sqlite3_bind_text( 
 78333    sqlite3_stmt *pStmt, 
 78334    int i, 
 78335    const char *zData, 
 78336    int nData, 
 78337    void (*xDel)(void*)
 78338  ){
 78339    return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
 78340  }
 78341  SQLITE_API int sqlite3_bind_text64( 
 78342    sqlite3_stmt *pStmt, 
 78343    int i, 
 78344    const char *zData, 
 78345    sqlite3_uint64 nData, 
 78346    void (*xDel)(void*),
 78347    unsigned char enc
 78348  ){
 78349    assert( xDel!=SQLITE_DYNAMIC );
 78350    if( nData>0x7fffffff ){
 78351      return invokeValueDestructor(zData, xDel, 0);
 78352    }else{
 78353      if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
 78354      return bindText(pStmt, i, zData, (int)nData, xDel, enc);
 78355    }
 78356  }
 78357  #ifndef SQLITE_OMIT_UTF16
 78358  SQLITE_API int sqlite3_bind_text16(
 78359    sqlite3_stmt *pStmt, 
 78360    int i, 
 78361    const void *zData, 
 78362    int nData, 
 78363    void (*xDel)(void*)
 78364  ){
 78365    return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
 78366  }
 78367  #endif /* SQLITE_OMIT_UTF16 */
 78368  SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
 78369    int rc;
 78370    switch( sqlite3_value_type((sqlite3_value*)pValue) ){
 78371      case SQLITE_INTEGER: {
 78372        rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
 78373        break;
 78374      }
 78375      case SQLITE_FLOAT: {
 78376        rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
 78377        break;
 78378      }
 78379      case SQLITE_BLOB: {
 78380        if( pValue->flags & MEM_Zero ){
 78381          rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
 78382        }else{
 78383          rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
 78384        }
 78385        break;
 78386      }
 78387      case SQLITE_TEXT: {
 78388        rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
 78389                                pValue->enc);
 78390        break;
 78391      }
 78392      default: {
 78393        rc = sqlite3_bind_null(pStmt, i);
 78394        break;
 78395      }
 78396    }
 78397    return rc;
 78398  }
 78399  SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
 78400    int rc;
 78401    Vdbe *p = (Vdbe *)pStmt;
 78402    rc = vdbeUnbind(p, i);
 78403    if( rc==SQLITE_OK ){
 78404      sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
 78405      sqlite3_mutex_leave(p->db->mutex);
 78406    }
 78407    return rc;
 78408  }
 78409  SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
 78410    int rc;
 78411    Vdbe *p = (Vdbe *)pStmt;
 78412    sqlite3_mutex_enter(p->db->mutex);
 78413    if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
 78414      rc = SQLITE_TOOBIG;
 78415    }else{
 78416      assert( (n & 0x7FFFFFFF)==n );
 78417      rc = sqlite3_bind_zeroblob(pStmt, i, n);
 78418    }
 78419    rc = sqlite3ApiExit(p->db, rc);
 78420    sqlite3_mutex_leave(p->db->mutex);
 78421    return rc;
 78422  }
 78423  
 78424  /*
 78425  ** Return the number of wildcards that can be potentially bound to.
 78426  ** This routine is added to support DBD::SQLite.  
 78427  */
 78428  SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
 78429    Vdbe *p = (Vdbe*)pStmt;
 78430    return p ? p->nVar : 0;
 78431  }
 78432  
 78433  /*
 78434  ** Return the name of a wildcard parameter.  Return NULL if the index
 78435  ** is out of range or if the wildcard is unnamed.
 78436  **
 78437  ** The result is always UTF-8.
 78438  */
 78439  SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
 78440    Vdbe *p = (Vdbe*)pStmt;
 78441    if( p==0 ) return 0;
 78442    return sqlite3VListNumToName(p->pVList, i);
 78443  }
 78444  
 78445  /*
 78446  ** Given a wildcard parameter name, return the index of the variable
 78447  ** with that name.  If there is no variable with the given name,
 78448  ** return 0.
 78449  */
 78450  SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
 78451    if( p==0 || zName==0 ) return 0;
 78452    return sqlite3VListNameToNum(p->pVList, zName, nName);
 78453  }
 78454  SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
 78455    return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
 78456  }
 78457  
 78458  /*
 78459  ** Transfer all bindings from the first statement over to the second.
 78460  */
 78461  SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
 78462    Vdbe *pFrom = (Vdbe*)pFromStmt;
 78463    Vdbe *pTo = (Vdbe*)pToStmt;
 78464    int i;
 78465    assert( pTo->db==pFrom->db );
 78466    assert( pTo->nVar==pFrom->nVar );
 78467    sqlite3_mutex_enter(pTo->db->mutex);
 78468    for(i=0; i<pFrom->nVar; i++){
 78469      sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
 78470    }
 78471    sqlite3_mutex_leave(pTo->db->mutex);
 78472    return SQLITE_OK;
 78473  }
 78474  
 78475  #ifndef SQLITE_OMIT_DEPRECATED
 78476  /*
 78477  ** Deprecated external interface.  Internal/core SQLite code
 78478  ** should call sqlite3TransferBindings.
 78479  **
 78480  ** It is misuse to call this routine with statements from different
 78481  ** database connections.  But as this is a deprecated interface, we
 78482  ** will not bother to check for that condition.
 78483  **
 78484  ** If the two statements contain a different number of bindings, then
 78485  ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
 78486  ** SQLITE_OK is returned.
 78487  */
 78488  SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
 78489    Vdbe *pFrom = (Vdbe*)pFromStmt;
 78490    Vdbe *pTo = (Vdbe*)pToStmt;
 78491    if( pFrom->nVar!=pTo->nVar ){
 78492      return SQLITE_ERROR;
 78493    }
 78494    assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
 78495    if( pTo->expmask ){
 78496      pTo->expired = 1;
 78497    }
 78498    assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
 78499    if( pFrom->expmask ){
 78500      pFrom->expired = 1;
 78501    }
 78502    return sqlite3TransferBindings(pFromStmt, pToStmt);
 78503  }
 78504  #endif
 78505  
 78506  /*
 78507  ** Return the sqlite3* database handle to which the prepared statement given
 78508  ** in the argument belongs.  This is the same database handle that was
 78509  ** the first argument to the sqlite3_prepare() that was used to create
 78510  ** the statement in the first place.
 78511  */
 78512  SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
 78513    return pStmt ? ((Vdbe*)pStmt)->db : 0;
 78514  }
 78515  
 78516  /*
 78517  ** Return true if the prepared statement is guaranteed to not modify the
 78518  ** database.
 78519  */
 78520  SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
 78521    return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
 78522  }
 78523  
 78524  /*
 78525  ** Return true if the prepared statement is in need of being reset.
 78526  */
 78527  SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
 78528    Vdbe *v = (Vdbe*)pStmt;
 78529    return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;
 78530  }
 78531  
 78532  /*
 78533  ** Return a pointer to the next prepared statement after pStmt associated
 78534  ** with database connection pDb.  If pStmt is NULL, return the first
 78535  ** prepared statement for the database connection.  Return NULL if there
 78536  ** are no more.
 78537  */
 78538  SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
 78539    sqlite3_stmt *pNext;
 78540  #ifdef SQLITE_ENABLE_API_ARMOR
 78541    if( !sqlite3SafetyCheckOk(pDb) ){
 78542      (void)SQLITE_MISUSE_BKPT;
 78543      return 0;
 78544    }
 78545  #endif
 78546    sqlite3_mutex_enter(pDb->mutex);
 78547    if( pStmt==0 ){
 78548      pNext = (sqlite3_stmt*)pDb->pVdbe;
 78549    }else{
 78550      pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
 78551    }
 78552    sqlite3_mutex_leave(pDb->mutex);
 78553    return pNext;
 78554  }
 78555  
 78556  /*
 78557  ** Return the value of a status counter for a prepared statement
 78558  */
 78559  SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
 78560    Vdbe *pVdbe = (Vdbe*)pStmt;
 78561    u32 v;
 78562  #ifdef SQLITE_ENABLE_API_ARMOR
 78563    if( !pStmt ){
 78564      (void)SQLITE_MISUSE_BKPT;
 78565      return 0;
 78566    }
 78567  #endif
 78568    if( op==SQLITE_STMTSTATUS_MEMUSED ){
 78569      sqlite3 *db = pVdbe->db;
 78570      sqlite3_mutex_enter(db->mutex);
 78571      v = 0;
 78572      db->pnBytesFreed = (int*)&v;
 78573      sqlite3VdbeClearObject(db, pVdbe);
 78574      sqlite3DbFree(db, pVdbe);
 78575      db->pnBytesFreed = 0;
 78576      sqlite3_mutex_leave(db->mutex);
 78577    }else{
 78578      v = pVdbe->aCounter[op];
 78579      if( resetFlag ) pVdbe->aCounter[op] = 0;
 78580    }
 78581    return (int)v;
 78582  }
 78583  
 78584  /*
 78585  ** Return the SQL associated with a prepared statement
 78586  */
 78587  SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
 78588    Vdbe *p = (Vdbe *)pStmt;
 78589    return p ? p->zSql : 0;
 78590  }
 78591  
 78592  /*
 78593  ** Return the SQL associated with a prepared statement with
 78594  ** bound parameters expanded.  Space to hold the returned string is
 78595  ** obtained from sqlite3_malloc().  The caller is responsible for
 78596  ** freeing the returned string by passing it to sqlite3_free().
 78597  **
 78598  ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
 78599  ** expanded bound parameters.
 78600  */
 78601  SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
 78602  #ifdef SQLITE_OMIT_TRACE
 78603    return 0;
 78604  #else
 78605    char *z = 0;
 78606    const char *zSql = sqlite3_sql(pStmt);
 78607    if( zSql ){
 78608      Vdbe *p = (Vdbe *)pStmt;
 78609      sqlite3_mutex_enter(p->db->mutex);
 78610      z = sqlite3VdbeExpandSql(p, zSql);
 78611      sqlite3_mutex_leave(p->db->mutex);
 78612    }
 78613    return z;
 78614  #endif
 78615  }
 78616  
 78617  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 78618  /*
 78619  ** Allocate and populate an UnpackedRecord structure based on the serialized
 78620  ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
 78621  ** if successful, or a NULL pointer if an OOM error is encountered.
 78622  */
 78623  static UnpackedRecord *vdbeUnpackRecord(
 78624    KeyInfo *pKeyInfo, 
 78625    int nKey, 
 78626    const void *pKey
 78627  ){
 78628    UnpackedRecord *pRet;           /* Return value */
 78629  
 78630    pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
 78631    if( pRet ){
 78632      memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));
 78633      sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
 78634    }
 78635    return pRet;
 78636  }
 78637  
 78638  /*
 78639  ** This function is called from within a pre-update callback to retrieve
 78640  ** a field of the row currently being updated or deleted.
 78641  */
 78642  SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
 78643    PreUpdate *p = db->pPreUpdate;
 78644    Mem *pMem;
 78645    int rc = SQLITE_OK;
 78646  
 78647    /* Test that this call is being made from within an SQLITE_DELETE or
 78648    ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
 78649    if( !p || p->op==SQLITE_INSERT ){
 78650      rc = SQLITE_MISUSE_BKPT;
 78651      goto preupdate_old_out;
 78652    }
 78653    if( p->pPk ){
 78654      iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
 78655    }
 78656    if( iIdx>=p->pCsr->nField || iIdx<0 ){
 78657      rc = SQLITE_RANGE;
 78658      goto preupdate_old_out;
 78659    }
 78660  
 78661    /* If the old.* record has not yet been loaded into memory, do so now. */
 78662    if( p->pUnpacked==0 ){
 78663      u32 nRec;
 78664      u8 *aRec;
 78665  
 78666      nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
 78667      aRec = sqlite3DbMallocRaw(db, nRec);
 78668      if( !aRec ) goto preupdate_old_out;
 78669      rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
 78670      if( rc==SQLITE_OK ){
 78671        p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
 78672        if( !p->pUnpacked ) rc = SQLITE_NOMEM;
 78673      }
 78674      if( rc!=SQLITE_OK ){
 78675        sqlite3DbFree(db, aRec);
 78676        goto preupdate_old_out;
 78677      }
 78678      p->aRecord = aRec;
 78679    }
 78680  
 78681    pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
 78682    if( iIdx==p->pTab->iPKey ){
 78683      sqlite3VdbeMemSetInt64(pMem, p->iKey1);
 78684    }else if( iIdx>=p->pUnpacked->nField ){
 78685      *ppValue = (sqlite3_value *)columnNullValue();
 78686    }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
 78687      if( pMem->flags & MEM_Int ){
 78688        sqlite3VdbeMemRealify(pMem);
 78689      }
 78690    }
 78691  
 78692   preupdate_old_out:
 78693    sqlite3Error(db, rc);
 78694    return sqlite3ApiExit(db, rc);
 78695  }
 78696  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
 78697  
 78698  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 78699  /*
 78700  ** This function is called from within a pre-update callback to retrieve
 78701  ** the number of columns in the row being updated, deleted or inserted.
 78702  */
 78703  SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
 78704    PreUpdate *p = db->pPreUpdate;
 78705    return (p ? p->keyinfo.nKeyField : 0);
 78706  }
 78707  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
 78708  
 78709  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 78710  /*
 78711  ** This function is designed to be called from within a pre-update callback
 78712  ** only. It returns zero if the change that caused the callback was made
 78713  ** immediately by a user SQL statement. Or, if the change was made by a
 78714  ** trigger program, it returns the number of trigger programs currently
 78715  ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a 
 78716  ** top-level trigger etc.).
 78717  **
 78718  ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
 78719  ** or SET DEFAULT action is considered a trigger.
 78720  */
 78721  SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
 78722    PreUpdate *p = db->pPreUpdate;
 78723    return (p ? p->v->nFrame : 0);
 78724  }
 78725  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
 78726  
 78727  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 78728  /*
 78729  ** This function is called from within a pre-update callback to retrieve
 78730  ** a field of the row currently being updated or inserted.
 78731  */
 78732  SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
 78733    PreUpdate *p = db->pPreUpdate;
 78734    int rc = SQLITE_OK;
 78735    Mem *pMem;
 78736  
 78737    if( !p || p->op==SQLITE_DELETE ){
 78738      rc = SQLITE_MISUSE_BKPT;
 78739      goto preupdate_new_out;
 78740    }
 78741    if( p->pPk && p->op!=SQLITE_UPDATE ){
 78742      iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
 78743    }
 78744    if( iIdx>=p->pCsr->nField || iIdx<0 ){
 78745      rc = SQLITE_RANGE;
 78746      goto preupdate_new_out;
 78747    }
 78748  
 78749    if( p->op==SQLITE_INSERT ){
 78750      /* For an INSERT, memory cell p->iNewReg contains the serialized record
 78751      ** that is being inserted. Deserialize it. */
 78752      UnpackedRecord *pUnpack = p->pNewUnpacked;
 78753      if( !pUnpack ){
 78754        Mem *pData = &p->v->aMem[p->iNewReg];
 78755        rc = ExpandBlob(pData);
 78756        if( rc!=SQLITE_OK ) goto preupdate_new_out;
 78757        pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
 78758        if( !pUnpack ){
 78759          rc = SQLITE_NOMEM;
 78760          goto preupdate_new_out;
 78761        }
 78762        p->pNewUnpacked = pUnpack;
 78763      }
 78764      pMem = &pUnpack->aMem[iIdx];
 78765      if( iIdx==p->pTab->iPKey ){
 78766        sqlite3VdbeMemSetInt64(pMem, p->iKey2);
 78767      }else if( iIdx>=pUnpack->nField ){
 78768        pMem = (sqlite3_value *)columnNullValue();
 78769      }
 78770    }else{
 78771      /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
 78772      ** value. Make a copy of the cell contents and return a pointer to it.
 78773      ** It is not safe to return a pointer to the memory cell itself as the
 78774      ** caller may modify the value text encoding.
 78775      */
 78776      assert( p->op==SQLITE_UPDATE );
 78777      if( !p->aNew ){
 78778        p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
 78779        if( !p->aNew ){
 78780          rc = SQLITE_NOMEM;
 78781          goto preupdate_new_out;
 78782        }
 78783      }
 78784      assert( iIdx>=0 && iIdx<p->pCsr->nField );
 78785      pMem = &p->aNew[iIdx];
 78786      if( pMem->flags==0 ){
 78787        if( iIdx==p->pTab->iPKey ){
 78788          sqlite3VdbeMemSetInt64(pMem, p->iKey2);
 78789        }else{
 78790          rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
 78791          if( rc!=SQLITE_OK ) goto preupdate_new_out;
 78792        }
 78793      }
 78794    }
 78795    *ppValue = pMem;
 78796  
 78797   preupdate_new_out:
 78798    sqlite3Error(db, rc);
 78799    return sqlite3ApiExit(db, rc);
 78800  }
 78801  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
 78802  
 78803  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 78804  /*
 78805  ** Return status data for a single loop within query pStmt.
 78806  */
 78807  SQLITE_API int sqlite3_stmt_scanstatus(
 78808    sqlite3_stmt *pStmt,            /* Prepared statement being queried */
 78809    int idx,                        /* Index of loop to report on */
 78810    int iScanStatusOp,              /* Which metric to return */
 78811    void *pOut                      /* OUT: Write the answer here */
 78812  ){
 78813    Vdbe *p = (Vdbe*)pStmt;
 78814    ScanStatus *pScan;
 78815    if( idx<0 || idx>=p->nScan ) return 1;
 78816    pScan = &p->aScan[idx];
 78817    switch( iScanStatusOp ){
 78818      case SQLITE_SCANSTAT_NLOOP: {
 78819        *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
 78820        break;
 78821      }
 78822      case SQLITE_SCANSTAT_NVISIT: {
 78823        *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
 78824        break;
 78825      }
 78826      case SQLITE_SCANSTAT_EST: {
 78827        double r = 1.0;
 78828        LogEst x = pScan->nEst;
 78829        while( x<100 ){
 78830          x += 10;
 78831          r *= 0.5;
 78832        }
 78833        *(double*)pOut = r*sqlite3LogEstToInt(x);
 78834        break;
 78835      }
 78836      case SQLITE_SCANSTAT_NAME: {
 78837        *(const char**)pOut = pScan->zName;
 78838        break;
 78839      }
 78840      case SQLITE_SCANSTAT_EXPLAIN: {
 78841        if( pScan->addrExplain ){
 78842          *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
 78843        }else{
 78844          *(const char**)pOut = 0;
 78845        }
 78846        break;
 78847      }
 78848      case SQLITE_SCANSTAT_SELECTID: {
 78849        if( pScan->addrExplain ){
 78850          *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
 78851        }else{
 78852          *(int*)pOut = -1;
 78853        }
 78854        break;
 78855      }
 78856      default: {
 78857        return 1;
 78858      }
 78859    }
 78860    return 0;
 78861  }
 78862  
 78863  /*
 78864  ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
 78865  */
 78866  SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
 78867    Vdbe *p = (Vdbe*)pStmt;
 78868    memset(p->anExec, 0, p->nOp * sizeof(i64));
 78869  }
 78870  #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
 78871  
 78872  /************** End of vdbeapi.c *********************************************/
 78873  /************** Begin file vdbetrace.c ***************************************/
 78874  /*
 78875  ** 2009 November 25
 78876  **
 78877  ** The author disclaims copyright to this source code.  In place of
 78878  ** a legal notice, here is a blessing:
 78879  **
 78880  **    May you do good and not evil.
 78881  **    May you find forgiveness for yourself and forgive others.
 78882  **    May you share freely, never taking more than you give.
 78883  **
 78884  *************************************************************************
 78885  **
 78886  ** This file contains code used to insert the values of host parameters
 78887  ** (aka "wildcards") into the SQL text output by sqlite3_trace().
 78888  **
 78889  ** The Vdbe parse-tree explainer is also found here.
 78890  */
 78891  /* #include "sqliteInt.h" */
 78892  /* #include "vdbeInt.h" */
 78893  
 78894  #ifndef SQLITE_OMIT_TRACE
 78895  
 78896  /*
 78897  ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
 78898  ** bytes in this text up to but excluding the first character in
 78899  ** a host parameter.  If the text contains no host parameters, return
 78900  ** the total number of bytes in the text.
 78901  */
 78902  static int findNextHostParameter(const char *zSql, int *pnToken){
 78903    int tokenType;
 78904    int nTotal = 0;
 78905    int n;
 78906  
 78907    *pnToken = 0;
 78908    while( zSql[0] ){
 78909      n = sqlite3GetToken((u8*)zSql, &tokenType);
 78910      assert( n>0 && tokenType!=TK_ILLEGAL );
 78911      if( tokenType==TK_VARIABLE ){
 78912        *pnToken = n;
 78913        break;
 78914      }
 78915      nTotal += n;
 78916      zSql += n;
 78917    }
 78918    return nTotal;
 78919  }
 78920  
 78921  /*
 78922  ** This function returns a pointer to a nul-terminated string in memory
 78923  ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
 78924  ** string contains a copy of zRawSql but with host parameters expanded to 
 78925  ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1, 
 78926  ** then the returned string holds a copy of zRawSql with "-- " prepended
 78927  ** to each line of text.
 78928  **
 78929  ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
 78930  ** then long strings and blobs are truncated to that many bytes.  This
 78931  ** can be used to prevent unreasonably large trace strings when dealing
 78932  ** with large (multi-megabyte) strings and blobs.
 78933  **
 78934  ** The calling function is responsible for making sure the memory returned
 78935  ** is eventually freed.
 78936  **
 78937  ** ALGORITHM:  Scan the input string looking for host parameters in any of
 78938  ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
 78939  ** string literals, quoted identifier names, and comments.  For text forms,
 78940  ** the host parameter index is found by scanning the prepared
 78941  ** statement for the corresponding OP_Variable opcode.  Once the host
 78942  ** parameter index is known, locate the value in p->aVar[].  Then render
 78943  ** the value as a literal in place of the host parameter name.
 78944  */
 78945  SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
 78946    Vdbe *p,                 /* The prepared statement being evaluated */
 78947    const char *zRawSql      /* Raw text of the SQL statement */
 78948  ){
 78949    sqlite3 *db;             /* The database connection */
 78950    int idx = 0;             /* Index of a host parameter */
 78951    int nextIndex = 1;       /* Index of next ? host parameter */
 78952    int n;                   /* Length of a token prefix */
 78953    int nToken;              /* Length of the parameter token */
 78954    int i;                   /* Loop counter */
 78955    Mem *pVar;               /* Value of a host parameter */
 78956    StrAccum out;            /* Accumulate the output here */
 78957  #ifndef SQLITE_OMIT_UTF16
 78958    Mem utf8;                /* Used to convert UTF16 into UTF8 for display */
 78959  #endif
 78960    char zBase[100];         /* Initial working space */
 78961  
 78962    db = p->db;
 78963    sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase), 
 78964                        db->aLimit[SQLITE_LIMIT_LENGTH]);
 78965    if( db->nVdbeExec>1 ){
 78966      while( *zRawSql ){
 78967        const char *zStart = zRawSql;
 78968        while( *(zRawSql++)!='\n' && *zRawSql );
 78969        sqlite3StrAccumAppend(&out, "-- ", 3);
 78970        assert( (zRawSql - zStart) > 0 );
 78971        sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
 78972      }
 78973    }else if( p->nVar==0 ){
 78974      sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
 78975    }else{
 78976      while( zRawSql[0] ){
 78977        n = findNextHostParameter(zRawSql, &nToken);
 78978        assert( n>0 );
 78979        sqlite3StrAccumAppend(&out, zRawSql, n);
 78980        zRawSql += n;
 78981        assert( zRawSql[0] || nToken==0 );
 78982        if( nToken==0 ) break;
 78983        if( zRawSql[0]=='?' ){
 78984          if( nToken>1 ){
 78985            assert( sqlite3Isdigit(zRawSql[1]) );
 78986            sqlite3GetInt32(&zRawSql[1], &idx);
 78987          }else{
 78988            idx = nextIndex;
 78989          }
 78990        }else{
 78991          assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
 78992                  zRawSql[0]=='@' || zRawSql[0]=='#' );
 78993          testcase( zRawSql[0]==':' );
 78994          testcase( zRawSql[0]=='$' );
 78995          testcase( zRawSql[0]=='@' );
 78996          testcase( zRawSql[0]=='#' );
 78997          idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
 78998          assert( idx>0 );
 78999        }
 79000        zRawSql += nToken;
 79001        nextIndex = idx + 1;
 79002        assert( idx>0 && idx<=p->nVar );
 79003        pVar = &p->aVar[idx-1];
 79004        if( pVar->flags & MEM_Null ){
 79005          sqlite3StrAccumAppend(&out, "NULL", 4);
 79006        }else if( pVar->flags & MEM_Int ){
 79007          sqlite3XPrintf(&out, "%lld", pVar->u.i);
 79008        }else if( pVar->flags & MEM_Real ){
 79009          sqlite3XPrintf(&out, "%!.15g", pVar->u.r);
 79010        }else if( pVar->flags & MEM_Str ){
 79011          int nOut;  /* Number of bytes of the string text to include in output */
 79012  #ifndef SQLITE_OMIT_UTF16
 79013          u8 enc = ENC(db);
 79014          if( enc!=SQLITE_UTF8 ){
 79015            memset(&utf8, 0, sizeof(utf8));
 79016            utf8.db = db;
 79017            sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
 79018            if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
 79019              out.accError = STRACCUM_NOMEM;
 79020              out.nAlloc = 0;
 79021            }
 79022            pVar = &utf8;
 79023          }
 79024  #endif
 79025          nOut = pVar->n;
 79026  #ifdef SQLITE_TRACE_SIZE_LIMIT
 79027          if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
 79028            nOut = SQLITE_TRACE_SIZE_LIMIT;
 79029            while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
 79030          }
 79031  #endif    
 79032          sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
 79033  #ifdef SQLITE_TRACE_SIZE_LIMIT
 79034          if( nOut<pVar->n ){
 79035            sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
 79036          }
 79037  #endif
 79038  #ifndef SQLITE_OMIT_UTF16
 79039          if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
 79040  #endif
 79041        }else if( pVar->flags & MEM_Zero ){
 79042          sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
 79043        }else{
 79044          int nOut;  /* Number of bytes of the blob to include in output */
 79045          assert( pVar->flags & MEM_Blob );
 79046          sqlite3StrAccumAppend(&out, "x'", 2);
 79047          nOut = pVar->n;
 79048  #ifdef SQLITE_TRACE_SIZE_LIMIT
 79049          if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
 79050  #endif
 79051          for(i=0; i<nOut; i++){
 79052            sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
 79053          }
 79054          sqlite3StrAccumAppend(&out, "'", 1);
 79055  #ifdef SQLITE_TRACE_SIZE_LIMIT
 79056          if( nOut<pVar->n ){
 79057            sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
 79058          }
 79059  #endif
 79060        }
 79061      }
 79062    }
 79063    if( out.accError ) sqlite3StrAccumReset(&out);
 79064    return sqlite3StrAccumFinish(&out);
 79065  }
 79066  
 79067  #endif /* #ifndef SQLITE_OMIT_TRACE */
 79068  
 79069  /************** End of vdbetrace.c *******************************************/
 79070  /************** Begin file vdbe.c ********************************************/
 79071  /*
 79072  ** 2001 September 15
 79073  **
 79074  ** The author disclaims copyright to this source code.  In place of
 79075  ** a legal notice, here is a blessing:
 79076  **
 79077  **    May you do good and not evil.
 79078  **    May you find forgiveness for yourself and forgive others.
 79079  **    May you share freely, never taking more than you give.
 79080  **
 79081  *************************************************************************
 79082  ** The code in this file implements the function that runs the
 79083  ** bytecode of a prepared statement.
 79084  **
 79085  ** Various scripts scan this source file in order to generate HTML
 79086  ** documentation, headers files, or other derived files.  The formatting
 79087  ** of the code in this file is, therefore, important.  See other comments
 79088  ** in this file for details.  If in doubt, do not deviate from existing
 79089  ** commenting and indentation practices when changing or adding code.
 79090  */
 79091  /* #include "sqliteInt.h" */
 79092  /* #include "vdbeInt.h" */
 79093  
 79094  /*
 79095  ** Invoke this macro on memory cells just prior to changing the
 79096  ** value of the cell.  This macro verifies that shallow copies are
 79097  ** not misused.  A shallow copy of a string or blob just copies a
 79098  ** pointer to the string or blob, not the content.  If the original
 79099  ** is changed while the copy is still in use, the string or blob might
 79100  ** be changed out from under the copy.  This macro verifies that nothing
 79101  ** like that ever happens.
 79102  */
 79103  #ifdef SQLITE_DEBUG
 79104  # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
 79105  #else
 79106  # define memAboutToChange(P,M)
 79107  #endif
 79108  
 79109  /*
 79110  ** The following global variable is incremented every time a cursor
 79111  ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
 79112  ** procedures use this information to make sure that indices are
 79113  ** working correctly.  This variable has no function other than to
 79114  ** help verify the correct operation of the library.
 79115  */
 79116  #ifdef SQLITE_TEST
 79117  SQLITE_API int sqlite3_search_count = 0;
 79118  #endif
 79119  
 79120  /*
 79121  ** When this global variable is positive, it gets decremented once before
 79122  ** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
 79123  ** field of the sqlite3 structure is set in order to simulate an interrupt.
 79124  **
 79125  ** This facility is used for testing purposes only.  It does not function
 79126  ** in an ordinary build.
 79127  */
 79128  #ifdef SQLITE_TEST
 79129  SQLITE_API int sqlite3_interrupt_count = 0;
 79130  #endif
 79131  
 79132  /*
 79133  ** The next global variable is incremented each type the OP_Sort opcode
 79134  ** is executed.  The test procedures use this information to make sure that
 79135  ** sorting is occurring or not occurring at appropriate times.   This variable
 79136  ** has no function other than to help verify the correct operation of the
 79137  ** library.
 79138  */
 79139  #ifdef SQLITE_TEST
 79140  SQLITE_API int sqlite3_sort_count = 0;
 79141  #endif
 79142  
 79143  /*
 79144  ** The next global variable records the size of the largest MEM_Blob
 79145  ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
 79146  ** use this information to make sure that the zero-blob functionality
 79147  ** is working correctly.   This variable has no function other than to
 79148  ** help verify the correct operation of the library.
 79149  */
 79150  #ifdef SQLITE_TEST
 79151  SQLITE_API int sqlite3_max_blobsize = 0;
 79152  static void updateMaxBlobsize(Mem *p){
 79153    if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
 79154      sqlite3_max_blobsize = p->n;
 79155    }
 79156  }
 79157  #endif
 79158  
 79159  /*
 79160  ** This macro evaluates to true if either the update hook or the preupdate
 79161  ** hook are enabled for database connect DB.
 79162  */
 79163  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 79164  # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
 79165  #else
 79166  # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
 79167  #endif
 79168  
 79169  /*
 79170  ** The next global variable is incremented each time the OP_Found opcode
 79171  ** is executed. This is used to test whether or not the foreign key
 79172  ** operation implemented using OP_FkIsZero is working. This variable
 79173  ** has no function other than to help verify the correct operation of the
 79174  ** library.
 79175  */
 79176  #ifdef SQLITE_TEST
 79177  SQLITE_API int sqlite3_found_count = 0;
 79178  #endif
 79179  
 79180  /*
 79181  ** Test a register to see if it exceeds the current maximum blob size.
 79182  ** If it does, record the new maximum blob size.
 79183  */
 79184  #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
 79185  # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
 79186  #else
 79187  # define UPDATE_MAX_BLOBSIZE(P)
 79188  #endif
 79189  
 79190  /*
 79191  ** Invoke the VDBE coverage callback, if that callback is defined.  This
 79192  ** feature is used for test suite validation only and does not appear an
 79193  ** production builds.
 79194  **
 79195  ** M is an integer, 2 or 3, that indices how many different ways the
 79196  ** branch can go.  It is usually 2.  "I" is the direction the branch
 79197  ** goes.  0 means falls through.  1 means branch is taken.  2 means the
 79198  ** second alternative branch is taken.
 79199  **
 79200  ** iSrcLine is the source code line (from the __LINE__ macro) that
 79201  ** generated the VDBE instruction.  This instrumentation assumes that all
 79202  ** source code is in a single file (the amalgamation).  Special values 1
 79203  ** and 2 for the iSrcLine parameter mean that this particular branch is
 79204  ** always taken or never taken, respectively.
 79205  */
 79206  #if !defined(SQLITE_VDBE_COVERAGE)
 79207  # define VdbeBranchTaken(I,M)
 79208  #else
 79209  # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
 79210    static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
 79211      if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
 79212        M = iSrcLine;
 79213        /* Assert the truth of VdbeCoverageAlwaysTaken() and 
 79214        ** VdbeCoverageNeverTaken() */
 79215        assert( (M & I)==I );
 79216      }else{
 79217        if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/
 79218        sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
 79219                                        iSrcLine,I,M);
 79220      }
 79221    }
 79222  #endif
 79223  
 79224  /*
 79225  ** Convert the given register into a string if it isn't one
 79226  ** already. Return non-zero if a malloc() fails.
 79227  */
 79228  #define Stringify(P, enc) \
 79229     if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
 79230       { goto no_mem; }
 79231  
 79232  /*
 79233  ** An ephemeral string value (signified by the MEM_Ephem flag) contains
 79234  ** a pointer to a dynamically allocated string where some other entity
 79235  ** is responsible for deallocating that string.  Because the register
 79236  ** does not control the string, it might be deleted without the register
 79237  ** knowing it.
 79238  **
 79239  ** This routine converts an ephemeral string into a dynamically allocated
 79240  ** string that the register itself controls.  In other words, it
 79241  ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
 79242  */
 79243  #define Deephemeralize(P) \
 79244     if( ((P)->flags&MEM_Ephem)!=0 \
 79245         && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
 79246  
 79247  /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
 79248  #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
 79249  
 79250  /*
 79251  ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
 79252  ** if we run out of memory.
 79253  */
 79254  static VdbeCursor *allocateCursor(
 79255    Vdbe *p,              /* The virtual machine */
 79256    int iCur,             /* Index of the new VdbeCursor */
 79257    int nField,           /* Number of fields in the table or index */
 79258    int iDb,              /* Database the cursor belongs to, or -1 */
 79259    u8 eCurType           /* Type of the new cursor */
 79260  ){
 79261    /* Find the memory cell that will be used to store the blob of memory
 79262    ** required for this VdbeCursor structure. It is convenient to use a 
 79263    ** vdbe memory cell to manage the memory allocation required for a
 79264    ** VdbeCursor structure for the following reasons:
 79265    **
 79266    **   * Sometimes cursor numbers are used for a couple of different
 79267    **     purposes in a vdbe program. The different uses might require
 79268    **     different sized allocations. Memory cells provide growable
 79269    **     allocations.
 79270    **
 79271    **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
 79272    **     be freed lazily via the sqlite3_release_memory() API. This
 79273    **     minimizes the number of malloc calls made by the system.
 79274    **
 79275    ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
 79276    ** the top of the register space.  Cursor 1 is at Mem[p->nMem-1].
 79277    ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
 79278    */
 79279    Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
 79280  
 79281    int nByte;
 79282    VdbeCursor *pCx = 0;
 79283    nByte = 
 79284        ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField + 
 79285        (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
 79286  
 79287    assert( iCur>=0 && iCur<p->nCursor );
 79288    if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
 79289      sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
 79290      p->apCsr[iCur] = 0;
 79291    }
 79292    if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
 79293      p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
 79294      memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
 79295      pCx->eCurType = eCurType;
 79296      pCx->iDb = iDb;
 79297      pCx->nField = nField;
 79298      pCx->aOffset = &pCx->aType[nField];
 79299      if( eCurType==CURTYPE_BTREE ){
 79300        pCx->uc.pCursor = (BtCursor*)
 79301            &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
 79302        sqlite3BtreeCursorZero(pCx->uc.pCursor);
 79303      }
 79304    }
 79305    return pCx;
 79306  }
 79307  
 79308  /*
 79309  ** Try to convert a value into a numeric representation if we can
 79310  ** do so without loss of information.  In other words, if the string
 79311  ** looks like a number, convert it into a number.  If it does not
 79312  ** look like a number, leave it alone.
 79313  **
 79314  ** If the bTryForInt flag is true, then extra effort is made to give
 79315  ** an integer representation.  Strings that look like floating point
 79316  ** values but which have no fractional component (example: '48.00')
 79317  ** will have a MEM_Int representation when bTryForInt is true.
 79318  **
 79319  ** If bTryForInt is false, then if the input string contains a decimal
 79320  ** point or exponential notation, the result is only MEM_Real, even
 79321  ** if there is an exact integer representation of the quantity.
 79322  */
 79323  static void applyNumericAffinity(Mem *pRec, int bTryForInt){
 79324    double rValue;
 79325    i64 iValue;
 79326    u8 enc = pRec->enc;
 79327    assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
 79328    if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
 79329    if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
 79330      pRec->u.i = iValue;
 79331      pRec->flags |= MEM_Int;
 79332    }else{
 79333      pRec->u.r = rValue;
 79334      pRec->flags |= MEM_Real;
 79335      if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
 79336    }
 79337  }
 79338  
 79339  /*
 79340  ** Processing is determine by the affinity parameter:
 79341  **
 79342  ** SQLITE_AFF_INTEGER:
 79343  ** SQLITE_AFF_REAL:
 79344  ** SQLITE_AFF_NUMERIC:
 79345  **    Try to convert pRec to an integer representation or a 
 79346  **    floating-point representation if an integer representation
 79347  **    is not possible.  Note that the integer representation is
 79348  **    always preferred, even if the affinity is REAL, because
 79349  **    an integer representation is more space efficient on disk.
 79350  **
 79351  ** SQLITE_AFF_TEXT:
 79352  **    Convert pRec to a text representation.
 79353  **
 79354  ** SQLITE_AFF_BLOB:
 79355  **    No-op.  pRec is unchanged.
 79356  */
 79357  static void applyAffinity(
 79358    Mem *pRec,          /* The value to apply affinity to */
 79359    char affinity,      /* The affinity to be applied */
 79360    u8 enc              /* Use this text encoding */
 79361  ){
 79362    if( affinity>=SQLITE_AFF_NUMERIC ){
 79363      assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
 79364               || affinity==SQLITE_AFF_NUMERIC );
 79365      if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
 79366        if( (pRec->flags & MEM_Real)==0 ){
 79367          if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
 79368        }else{
 79369          sqlite3VdbeIntegerAffinity(pRec);
 79370        }
 79371      }
 79372    }else if( affinity==SQLITE_AFF_TEXT ){
 79373      /* Only attempt the conversion to TEXT if there is an integer or real
 79374      ** representation (blob and NULL do not get converted) but no string
 79375      ** representation.  It would be harmless to repeat the conversion if 
 79376      ** there is already a string rep, but it is pointless to waste those
 79377      ** CPU cycles. */
 79378      if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
 79379        if( (pRec->flags&(MEM_Real|MEM_Int)) ){
 79380          sqlite3VdbeMemStringify(pRec, enc, 1);
 79381        }
 79382      }
 79383      pRec->flags &= ~(MEM_Real|MEM_Int);
 79384    }
 79385  }
 79386  
 79387  /*
 79388  ** Try to convert the type of a function argument or a result column
 79389  ** into a numeric representation.  Use either INTEGER or REAL whichever
 79390  ** is appropriate.  But only do the conversion if it is possible without
 79391  ** loss of information and return the revised type of the argument.
 79392  */
 79393  SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
 79394    int eType = sqlite3_value_type(pVal);
 79395    if( eType==SQLITE_TEXT ){
 79396      Mem *pMem = (Mem*)pVal;
 79397      applyNumericAffinity(pMem, 0);
 79398      eType = sqlite3_value_type(pVal);
 79399    }
 79400    return eType;
 79401  }
 79402  
 79403  /*
 79404  ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
 79405  ** not the internal Mem* type.
 79406  */
 79407  SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
 79408    sqlite3_value *pVal, 
 79409    u8 affinity, 
 79410    u8 enc
 79411  ){
 79412    applyAffinity((Mem *)pVal, affinity, enc);
 79413  }
 79414  
 79415  /*
 79416  ** pMem currently only holds a string type (or maybe a BLOB that we can
 79417  ** interpret as a string if we want to).  Compute its corresponding
 79418  ** numeric type, if has one.  Set the pMem->u.r and pMem->u.i fields
 79419  ** accordingly.
 79420  */
 79421  static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
 79422    assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
 79423    assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
 79424    if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
 79425      return 0;
 79426    }
 79427    if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==0 ){
 79428      return MEM_Int;
 79429    }
 79430    return MEM_Real;
 79431  }
 79432  
 79433  /*
 79434  ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
 79435  ** none.  
 79436  **
 79437  ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
 79438  ** But it does set pMem->u.r and pMem->u.i appropriately.
 79439  */
 79440  static u16 numericType(Mem *pMem){
 79441    if( pMem->flags & (MEM_Int|MEM_Real) ){
 79442      return pMem->flags & (MEM_Int|MEM_Real);
 79443    }
 79444    if( pMem->flags & (MEM_Str|MEM_Blob) ){
 79445      return computeNumericType(pMem);
 79446    }
 79447    return 0;
 79448  }
 79449  
 79450  #ifdef SQLITE_DEBUG
 79451  /*
 79452  ** Write a nice string representation of the contents of cell pMem
 79453  ** into buffer zBuf, length nBuf.
 79454  */
 79455  SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
 79456    char *zCsr = zBuf;
 79457    int f = pMem->flags;
 79458  
 79459    static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
 79460  
 79461    if( f&MEM_Blob ){
 79462      int i;
 79463      char c;
 79464      if( f & MEM_Dyn ){
 79465        c = 'z';
 79466        assert( (f & (MEM_Static|MEM_Ephem))==0 );
 79467      }else if( f & MEM_Static ){
 79468        c = 't';
 79469        assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
 79470      }else if( f & MEM_Ephem ){
 79471        c = 'e';
 79472        assert( (f & (MEM_Static|MEM_Dyn))==0 );
 79473      }else{
 79474        c = 's';
 79475      }
 79476      *(zCsr++) = c;
 79477      sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
 79478      zCsr += sqlite3Strlen30(zCsr);
 79479      for(i=0; i<16 && i<pMem->n; i++){
 79480        sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
 79481        zCsr += sqlite3Strlen30(zCsr);
 79482      }
 79483      for(i=0; i<16 && i<pMem->n; i++){
 79484        char z = pMem->z[i];
 79485        if( z<32 || z>126 ) *zCsr++ = '.';
 79486        else *zCsr++ = z;
 79487      }
 79488      *(zCsr++) = ']';
 79489      if( f & MEM_Zero ){
 79490        sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
 79491        zCsr += sqlite3Strlen30(zCsr);
 79492      }
 79493      *zCsr = '\0';
 79494    }else if( f & MEM_Str ){
 79495      int j, k;
 79496      zBuf[0] = ' ';
 79497      if( f & MEM_Dyn ){
 79498        zBuf[1] = 'z';
 79499        assert( (f & (MEM_Static|MEM_Ephem))==0 );
 79500      }else if( f & MEM_Static ){
 79501        zBuf[1] = 't';
 79502        assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
 79503      }else if( f & MEM_Ephem ){
 79504        zBuf[1] = 'e';
 79505        assert( (f & (MEM_Static|MEM_Dyn))==0 );
 79506      }else{
 79507        zBuf[1] = 's';
 79508      }
 79509      k = 2;
 79510      sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
 79511      k += sqlite3Strlen30(&zBuf[k]);
 79512      zBuf[k++] = '[';
 79513      for(j=0; j<15 && j<pMem->n; j++){
 79514        u8 c = pMem->z[j];
 79515        if( c>=0x20 && c<0x7f ){
 79516          zBuf[k++] = c;
 79517        }else{
 79518          zBuf[k++] = '.';
 79519        }
 79520      }
 79521      zBuf[k++] = ']';
 79522      sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
 79523      k += sqlite3Strlen30(&zBuf[k]);
 79524      zBuf[k++] = 0;
 79525    }
 79526  }
 79527  #endif
 79528  
 79529  #ifdef SQLITE_DEBUG
 79530  /*
 79531  ** Print the value of a register for tracing purposes:
 79532  */
 79533  static void memTracePrint(Mem *p){
 79534    if( p->flags & MEM_Undefined ){
 79535      printf(" undefined");
 79536    }else if( p->flags & MEM_Null ){
 79537      printf(" NULL");
 79538    }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
 79539      printf(" si:%lld", p->u.i);
 79540    }else if( p->flags & MEM_Int ){
 79541      printf(" i:%lld", p->u.i);
 79542  #ifndef SQLITE_OMIT_FLOATING_POINT
 79543    }else if( p->flags & MEM_Real ){
 79544      printf(" r:%g", p->u.r);
 79545  #endif
 79546    }else if( p->flags & MEM_RowSet ){
 79547      printf(" (rowset)");
 79548    }else{
 79549      char zBuf[200];
 79550      sqlite3VdbeMemPrettyPrint(p, zBuf);
 79551      printf(" %s", zBuf);
 79552    }
 79553    if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
 79554  }
 79555  static void registerTrace(int iReg, Mem *p){
 79556    printf("REG[%d] = ", iReg);
 79557    memTracePrint(p);
 79558    printf("\n");
 79559    sqlite3VdbeCheckMemInvariants(p);
 79560  }
 79561  #endif
 79562  
 79563  #ifdef SQLITE_DEBUG
 79564  #  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
 79565  #else
 79566  #  define REGISTER_TRACE(R,M)
 79567  #endif
 79568  
 79569  
 79570  #ifdef VDBE_PROFILE
 79571  
 79572  /* 
 79573  ** hwtime.h contains inline assembler code for implementing 
 79574  ** high-performance timing routines.
 79575  */
 79576  /************** Include hwtime.h in the middle of vdbe.c *********************/
 79577  /************** Begin file hwtime.h ******************************************/
 79578  /*
 79579  ** 2008 May 27
 79580  **
 79581  ** The author disclaims copyright to this source code.  In place of
 79582  ** a legal notice, here is a blessing:
 79583  **
 79584  **    May you do good and not evil.
 79585  **    May you find forgiveness for yourself and forgive others.
 79586  **    May you share freely, never taking more than you give.
 79587  **
 79588  ******************************************************************************
 79589  **
 79590  ** This file contains inline asm code for retrieving "high-performance"
 79591  ** counters for x86 class CPUs.
 79592  */
 79593  #ifndef SQLITE_HWTIME_H
 79594  #define SQLITE_HWTIME_H
 79595  
 79596  /*
 79597  ** The following routine only works on pentium-class (or newer) processors.
 79598  ** It uses the RDTSC opcode to read the cycle count value out of the
 79599  ** processor and returns that value.  This can be used for high-res
 79600  ** profiling.
 79601  */
 79602  #if (defined(__GNUC__) || defined(_MSC_VER)) && \
 79603        (defined(i386) || defined(__i386__) || defined(_M_IX86))
 79604  
 79605    #if defined(__GNUC__)
 79606  
 79607    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 79608       unsigned int lo, hi;
 79609       __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
 79610       return (sqlite_uint64)hi << 32 | lo;
 79611    }
 79612  
 79613    #elif defined(_MSC_VER)
 79614  
 79615    __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
 79616       __asm {
 79617          rdtsc
 79618          ret       ; return value at EDX:EAX
 79619       }
 79620    }
 79621  
 79622    #endif
 79623  
 79624  #elif (defined(__GNUC__) && defined(__x86_64__))
 79625  
 79626    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 79627        unsigned long val;
 79628        __asm__ __volatile__ ("rdtsc" : "=A" (val));
 79629        return val;
 79630    }
 79631   
 79632  #elif (defined(__GNUC__) && defined(__ppc__))
 79633  
 79634    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 79635        unsigned long long retval;
 79636        unsigned long junk;
 79637        __asm__ __volatile__ ("\n\
 79638            1:      mftbu   %1\n\
 79639                    mftb    %L0\n\
 79640                    mftbu   %0\n\
 79641                    cmpw    %0,%1\n\
 79642                    bne     1b"
 79643                    : "=r" (retval), "=r" (junk));
 79644        return retval;
 79645    }
 79646  
 79647  #else
 79648  
 79649    #error Need implementation of sqlite3Hwtime() for your platform.
 79650  
 79651    /*
 79652    ** To compile without implementing sqlite3Hwtime() for your platform,
 79653    ** you can remove the above #error and use the following
 79654    ** stub function.  You will lose timing support for many
 79655    ** of the debugging and testing utilities, but it should at
 79656    ** least compile and run.
 79657    */
 79658  SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
 79659  
 79660  #endif
 79661  
 79662  #endif /* !defined(SQLITE_HWTIME_H) */
 79663  
 79664  /************** End of hwtime.h **********************************************/
 79665  /************** Continuing where we left off in vdbe.c ***********************/
 79666  
 79667  #endif
 79668  
 79669  #ifndef NDEBUG
 79670  /*
 79671  ** This function is only called from within an assert() expression. It
 79672  ** checks that the sqlite3.nTransaction variable is correctly set to
 79673  ** the number of non-transaction savepoints currently in the 
 79674  ** linked list starting at sqlite3.pSavepoint.
 79675  ** 
 79676  ** Usage:
 79677  **
 79678  **     assert( checkSavepointCount(db) );
 79679  */
 79680  static int checkSavepointCount(sqlite3 *db){
 79681    int n = 0;
 79682    Savepoint *p;
 79683    for(p=db->pSavepoint; p; p=p->pNext) n++;
 79684    assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
 79685    return 1;
 79686  }
 79687  #endif
 79688  
 79689  /*
 79690  ** Return the register of pOp->p2 after first preparing it to be
 79691  ** overwritten with an integer value.
 79692  */
 79693  static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
 79694    sqlite3VdbeMemSetNull(pOut);
 79695    pOut->flags = MEM_Int;
 79696    return pOut;
 79697  }
 79698  static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
 79699    Mem *pOut;
 79700    assert( pOp->p2>0 );
 79701    assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
 79702    pOut = &p->aMem[pOp->p2];
 79703    memAboutToChange(p, pOut);
 79704    if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
 79705      return out2PrereleaseWithClear(pOut);
 79706    }else{
 79707      pOut->flags = MEM_Int;
 79708      return pOut;
 79709    }
 79710  }
 79711  
 79712  
 79713  /*
 79714  ** Execute as much of a VDBE program as we can.
 79715  ** This is the core of sqlite3_step().  
 79716  */
 79717  SQLITE_PRIVATE int sqlite3VdbeExec(
 79718    Vdbe *p                    /* The VDBE */
 79719  ){
 79720    Op *aOp = p->aOp;          /* Copy of p->aOp */
 79721    Op *pOp = aOp;             /* Current operation */
 79722  #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
 79723    Op *pOrigOp;               /* Value of pOp at the top of the loop */
 79724  #endif
 79725  #ifdef SQLITE_DEBUG
 79726    int nExtraDelete = 0;      /* Verifies FORDELETE and AUXDELETE flags */
 79727  #endif
 79728    int rc = SQLITE_OK;        /* Value to return */
 79729    sqlite3 *db = p->db;       /* The database */
 79730    u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
 79731    u8 encoding = ENC(db);     /* The database encoding */
 79732    int iCompare = 0;          /* Result of last comparison */
 79733    unsigned nVmStep = 0;      /* Number of virtual machine steps */
 79734  #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
 79735    unsigned nProgressLimit;   /* Invoke xProgress() when nVmStep reaches this */
 79736  #endif
 79737    Mem *aMem = p->aMem;       /* Copy of p->aMem */
 79738    Mem *pIn1 = 0;             /* 1st input operand */
 79739    Mem *pIn2 = 0;             /* 2nd input operand */
 79740    Mem *pIn3 = 0;             /* 3rd input operand */
 79741    Mem *pOut = 0;             /* Output operand */
 79742  #ifdef VDBE_PROFILE
 79743    u64 start;                 /* CPU clock count at start of opcode */
 79744  #endif
 79745    /*** INSERT STACK UNION HERE ***/
 79746  
 79747    assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
 79748    sqlite3VdbeEnter(p);
 79749    if( p->rc==SQLITE_NOMEM ){
 79750      /* This happens if a malloc() inside a call to sqlite3_column_text() or
 79751      ** sqlite3_column_text16() failed.  */
 79752      goto no_mem;
 79753    }
 79754    assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
 79755    assert( p->bIsReader || p->readOnly!=0 );
 79756    p->iCurrentTime = 0;
 79757    assert( p->explain==0 );
 79758    p->pResultSet = 0;
 79759    db->busyHandler.nBusy = 0;
 79760    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
 79761    sqlite3VdbeIOTraceSql(p);
 79762  #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
 79763    if( db->xProgress ){
 79764      u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
 79765      assert( 0 < db->nProgressOps );
 79766      nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
 79767    }else{
 79768      nProgressLimit = 0xffffffff;
 79769    }
 79770  #endif
 79771  #ifdef SQLITE_DEBUG
 79772    sqlite3BeginBenignMalloc();
 79773    if( p->pc==0
 79774     && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
 79775    ){
 79776      int i;
 79777      int once = 1;
 79778      sqlite3VdbePrintSql(p);
 79779      if( p->db->flags & SQLITE_VdbeListing ){
 79780        printf("VDBE Program Listing:\n");
 79781        for(i=0; i<p->nOp; i++){
 79782          sqlite3VdbePrintOp(stdout, i, &aOp[i]);
 79783        }
 79784      }
 79785      if( p->db->flags & SQLITE_VdbeEQP ){
 79786        for(i=0; i<p->nOp; i++){
 79787          if( aOp[i].opcode==OP_Explain ){
 79788            if( once ) printf("VDBE Query Plan:\n");
 79789            printf("%s\n", aOp[i].p4.z);
 79790            once = 0;
 79791          }
 79792        }
 79793      }
 79794      if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
 79795    }
 79796    sqlite3EndBenignMalloc();
 79797  #endif
 79798    for(pOp=&aOp[p->pc]; 1; pOp++){
 79799      /* Errors are detected by individual opcodes, with an immediate
 79800      ** jumps to abort_due_to_error. */
 79801      assert( rc==SQLITE_OK );
 79802  
 79803      assert( pOp>=aOp && pOp<&aOp[p->nOp]);
 79804  #ifdef VDBE_PROFILE
 79805      start = sqlite3Hwtime();
 79806  #endif
 79807      nVmStep++;
 79808  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 79809      if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
 79810  #endif
 79811  
 79812      /* Only allow tracing if SQLITE_DEBUG is defined.
 79813      */
 79814  #ifdef SQLITE_DEBUG
 79815      if( db->flags & SQLITE_VdbeTrace ){
 79816        sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
 79817      }
 79818  #endif
 79819        
 79820  
 79821      /* Check to see if we need to simulate an interrupt.  This only happens
 79822      ** if we have a special test build.
 79823      */
 79824  #ifdef SQLITE_TEST
 79825      if( sqlite3_interrupt_count>0 ){
 79826        sqlite3_interrupt_count--;
 79827        if( sqlite3_interrupt_count==0 ){
 79828          sqlite3_interrupt(db);
 79829        }
 79830      }
 79831  #endif
 79832  
 79833      /* Sanity checking on other operands */
 79834  #ifdef SQLITE_DEBUG
 79835      {
 79836        u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
 79837        if( (opProperty & OPFLG_IN1)!=0 ){
 79838          assert( pOp->p1>0 );
 79839          assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
 79840          assert( memIsValid(&aMem[pOp->p1]) );
 79841          assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
 79842          REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
 79843        }
 79844        if( (opProperty & OPFLG_IN2)!=0 ){
 79845          assert( pOp->p2>0 );
 79846          assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
 79847          assert( memIsValid(&aMem[pOp->p2]) );
 79848          assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
 79849          REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
 79850        }
 79851        if( (opProperty & OPFLG_IN3)!=0 ){
 79852          assert( pOp->p3>0 );
 79853          assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
 79854          assert( memIsValid(&aMem[pOp->p3]) );
 79855          assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
 79856          REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
 79857        }
 79858        if( (opProperty & OPFLG_OUT2)!=0 ){
 79859          assert( pOp->p2>0 );
 79860          assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
 79861          memAboutToChange(p, &aMem[pOp->p2]);
 79862        }
 79863        if( (opProperty & OPFLG_OUT3)!=0 ){
 79864          assert( pOp->p3>0 );
 79865          assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
 79866          memAboutToChange(p, &aMem[pOp->p3]);
 79867        }
 79868      }
 79869  #endif
 79870  #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
 79871      pOrigOp = pOp;
 79872  #endif
 79873    
 79874      switch( pOp->opcode ){
 79875  
 79876  /*****************************************************************************
 79877  ** What follows is a massive switch statement where each case implements a
 79878  ** separate instruction in the virtual machine.  If we follow the usual
 79879  ** indentation conventions, each case should be indented by 6 spaces.  But
 79880  ** that is a lot of wasted space on the left margin.  So the code within
 79881  ** the switch statement will break with convention and be flush-left. Another
 79882  ** big comment (similar to this one) will mark the point in the code where
 79883  ** we transition back to normal indentation.
 79884  **
 79885  ** The formatting of each case is important.  The makefile for SQLite
 79886  ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
 79887  ** file looking for lines that begin with "case OP_".  The opcodes.h files
 79888  ** will be filled with #defines that give unique integer values to each
 79889  ** opcode and the opcodes.c file is filled with an array of strings where
 79890  ** each string is the symbolic name for the corresponding opcode.  If the
 79891  ** case statement is followed by a comment of the form "/# same as ... #/"
 79892  ** that comment is used to determine the particular value of the opcode.
 79893  **
 79894  ** Other keywords in the comment that follows each case are used to
 79895  ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
 79896  ** Keywords include: in1, in2, in3, out2, out3.  See
 79897  ** the mkopcodeh.awk script for additional information.
 79898  **
 79899  ** Documentation about VDBE opcodes is generated by scanning this file
 79900  ** for lines of that contain "Opcode:".  That line and all subsequent
 79901  ** comment lines are used in the generation of the opcode.html documentation
 79902  ** file.
 79903  **
 79904  ** SUMMARY:
 79905  **
 79906  **     Formatting is important to scripts that scan this file.
 79907  **     Do not deviate from the formatting style currently in use.
 79908  **
 79909  *****************************************************************************/
 79910  
 79911  /* Opcode:  Goto * P2 * * *
 79912  **
 79913  ** An unconditional jump to address P2.
 79914  ** The next instruction executed will be 
 79915  ** the one at index P2 from the beginning of
 79916  ** the program.
 79917  **
 79918  ** The P1 parameter is not actually used by this opcode.  However, it
 79919  ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
 79920  ** that this Goto is the bottom of a loop and that the lines from P2 down
 79921  ** to the current line should be indented for EXPLAIN output.
 79922  */
 79923  case OP_Goto: {             /* jump */
 79924  jump_to_p2_and_check_for_interrupt:
 79925    pOp = &aOp[pOp->p2 - 1];
 79926  
 79927    /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
 79928    ** OP_VNext, or OP_SorterNext) all jump here upon
 79929    ** completion.  Check to see if sqlite3_interrupt() has been called
 79930    ** or if the progress callback needs to be invoked. 
 79931    **
 79932    ** This code uses unstructured "goto" statements and does not look clean.
 79933    ** But that is not due to sloppy coding habits. The code is written this
 79934    ** way for performance, to avoid having to run the interrupt and progress
 79935    ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%
 79936    ** faster according to "valgrind --tool=cachegrind" */
 79937  check_for_interrupt:
 79938    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
 79939  #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
 79940    /* Call the progress callback if it is configured and the required number
 79941    ** of VDBE ops have been executed (either since this invocation of
 79942    ** sqlite3VdbeExec() or since last time the progress callback was called).
 79943    ** If the progress callback returns non-zero, exit the virtual machine with
 79944    ** a return code SQLITE_ABORT.
 79945    */
 79946    if( nVmStep>=nProgressLimit && db->xProgress!=0 ){
 79947      assert( db->nProgressOps!=0 );
 79948      nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
 79949      if( db->xProgress(db->pProgressArg) ){
 79950        rc = SQLITE_INTERRUPT;
 79951        goto abort_due_to_error;
 79952      }
 79953    }
 79954  #endif
 79955    
 79956    break;
 79957  }
 79958  
 79959  /* Opcode:  Gosub P1 P2 * * *
 79960  **
 79961  ** Write the current address onto register P1
 79962  ** and then jump to address P2.
 79963  */
 79964  case OP_Gosub: {            /* jump */
 79965    assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
 79966    pIn1 = &aMem[pOp->p1];
 79967    assert( VdbeMemDynamic(pIn1)==0 );
 79968    memAboutToChange(p, pIn1);
 79969    pIn1->flags = MEM_Int;
 79970    pIn1->u.i = (int)(pOp-aOp);
 79971    REGISTER_TRACE(pOp->p1, pIn1);
 79972  
 79973    /* Most jump operations do a goto to this spot in order to update
 79974    ** the pOp pointer. */
 79975  jump_to_p2:
 79976    pOp = &aOp[pOp->p2 - 1];
 79977    break;
 79978  }
 79979  
 79980  /* Opcode:  Return P1 * * * *
 79981  **
 79982  ** Jump to the next instruction after the address in register P1.  After
 79983  ** the jump, register P1 becomes undefined.
 79984  */
 79985  case OP_Return: {           /* in1 */
 79986    pIn1 = &aMem[pOp->p1];
 79987    assert( pIn1->flags==MEM_Int );
 79988    pOp = &aOp[pIn1->u.i];
 79989    pIn1->flags = MEM_Undefined;
 79990    break;
 79991  }
 79992  
 79993  /* Opcode: InitCoroutine P1 P2 P3 * *
 79994  **
 79995  ** Set up register P1 so that it will Yield to the coroutine
 79996  ** located at address P3.
 79997  **
 79998  ** If P2!=0 then the coroutine implementation immediately follows
 79999  ** this opcode.  So jump over the coroutine implementation to
 80000  ** address P2.
 80001  **
 80002  ** See also: EndCoroutine
 80003  */
 80004  case OP_InitCoroutine: {     /* jump */
 80005    assert( pOp->p1>0 &&  pOp->p1<=(p->nMem+1 - p->nCursor) );
 80006    assert( pOp->p2>=0 && pOp->p2<p->nOp );
 80007    assert( pOp->p3>=0 && pOp->p3<p->nOp );
 80008    pOut = &aMem[pOp->p1];
 80009    assert( !VdbeMemDynamic(pOut) );
 80010    pOut->u.i = pOp->p3 - 1;
 80011    pOut->flags = MEM_Int;
 80012    if( pOp->p2 ) goto jump_to_p2;
 80013    break;
 80014  }
 80015  
 80016  /* Opcode:  EndCoroutine P1 * * * *
 80017  **
 80018  ** The instruction at the address in register P1 is a Yield.
 80019  ** Jump to the P2 parameter of that Yield.
 80020  ** After the jump, register P1 becomes undefined.
 80021  **
 80022  ** See also: InitCoroutine
 80023  */
 80024  case OP_EndCoroutine: {           /* in1 */
 80025    VdbeOp *pCaller;
 80026    pIn1 = &aMem[pOp->p1];
 80027    assert( pIn1->flags==MEM_Int );
 80028    assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
 80029    pCaller = &aOp[pIn1->u.i];
 80030    assert( pCaller->opcode==OP_Yield );
 80031    assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
 80032    pOp = &aOp[pCaller->p2 - 1];
 80033    pIn1->flags = MEM_Undefined;
 80034    break;
 80035  }
 80036  
 80037  /* Opcode:  Yield P1 P2 * * *
 80038  **
 80039  ** Swap the program counter with the value in register P1.  This
 80040  ** has the effect of yielding to a coroutine.
 80041  **
 80042  ** If the coroutine that is launched by this instruction ends with
 80043  ** Yield or Return then continue to the next instruction.  But if
 80044  ** the coroutine launched by this instruction ends with
 80045  ** EndCoroutine, then jump to P2 rather than continuing with the
 80046  ** next instruction.
 80047  **
 80048  ** See also: InitCoroutine
 80049  */
 80050  case OP_Yield: {            /* in1, jump */
 80051    int pcDest;
 80052    pIn1 = &aMem[pOp->p1];
 80053    assert( VdbeMemDynamic(pIn1)==0 );
 80054    pIn1->flags = MEM_Int;
 80055    pcDest = (int)pIn1->u.i;
 80056    pIn1->u.i = (int)(pOp - aOp);
 80057    REGISTER_TRACE(pOp->p1, pIn1);
 80058    pOp = &aOp[pcDest];
 80059    break;
 80060  }
 80061  
 80062  /* Opcode:  HaltIfNull  P1 P2 P3 P4 P5
 80063  ** Synopsis: if r[P3]=null halt
 80064  **
 80065  ** Check the value in register P3.  If it is NULL then Halt using
 80066  ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
 80067  ** value in register P3 is not NULL, then this routine is a no-op.
 80068  ** The P5 parameter should be 1.
 80069  */
 80070  case OP_HaltIfNull: {      /* in3 */
 80071    pIn3 = &aMem[pOp->p3];
 80072    if( (pIn3->flags & MEM_Null)==0 ) break;
 80073    /* Fall through into OP_Halt */
 80074  }
 80075  
 80076  /* Opcode:  Halt P1 P2 * P4 P5
 80077  **
 80078  ** Exit immediately.  All open cursors, etc are closed
 80079  ** automatically.
 80080  **
 80081  ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
 80082  ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
 80083  ** For errors, it can be some other value.  If P1!=0 then P2 will determine
 80084  ** whether or not to rollback the current transaction.  Do not rollback
 80085  ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
 80086  ** then back out all changes that have occurred during this execution of the
 80087  ** VDBE, but do not rollback the transaction. 
 80088  **
 80089  ** If P4 is not null then it is an error message string.
 80090  **
 80091  ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
 80092  **
 80093  **    0:  (no change)
 80094  **    1:  NOT NULL contraint failed: P4
 80095  **    2:  UNIQUE constraint failed: P4
 80096  **    3:  CHECK constraint failed: P4
 80097  **    4:  FOREIGN KEY constraint failed: P4
 80098  **
 80099  ** If P5 is not zero and P4 is NULL, then everything after the ":" is
 80100  ** omitted.
 80101  **
 80102  ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
 80103  ** every program.  So a jump past the last instruction of the program
 80104  ** is the same as executing Halt.
 80105  */
 80106  case OP_Halt: {
 80107    VdbeFrame *pFrame;
 80108    int pcx;
 80109  
 80110    pcx = (int)(pOp - aOp);
 80111    if( pOp->p1==SQLITE_OK && p->pFrame ){
 80112      /* Halt the sub-program. Return control to the parent frame. */
 80113      pFrame = p->pFrame;
 80114      p->pFrame = pFrame->pParent;
 80115      p->nFrame--;
 80116      sqlite3VdbeSetChanges(db, p->nChange);
 80117      pcx = sqlite3VdbeFrameRestore(pFrame);
 80118      if( pOp->p2==OE_Ignore ){
 80119        /* Instruction pcx is the OP_Program that invoked the sub-program 
 80120        ** currently being halted. If the p2 instruction of this OP_Halt
 80121        ** instruction is set to OE_Ignore, then the sub-program is throwing
 80122        ** an IGNORE exception. In this case jump to the address specified
 80123        ** as the p2 of the calling OP_Program.  */
 80124        pcx = p->aOp[pcx].p2-1;
 80125      }
 80126      aOp = p->aOp;
 80127      aMem = p->aMem;
 80128      pOp = &aOp[pcx];
 80129      break;
 80130    }
 80131    p->rc = pOp->p1;
 80132    p->errorAction = (u8)pOp->p2;
 80133    p->pc = pcx;
 80134    assert( pOp->p5<=4 );
 80135    if( p->rc ){
 80136      if( pOp->p5 ){
 80137        static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
 80138                                               "FOREIGN KEY" };
 80139        testcase( pOp->p5==1 );
 80140        testcase( pOp->p5==2 );
 80141        testcase( pOp->p5==3 );
 80142        testcase( pOp->p5==4 );
 80143        sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
 80144        if( pOp->p4.z ){
 80145          p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
 80146        }
 80147      }else{
 80148        sqlite3VdbeError(p, "%s", pOp->p4.z);
 80149      }
 80150      sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
 80151    }
 80152    rc = sqlite3VdbeHalt(p);
 80153    assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
 80154    if( rc==SQLITE_BUSY ){
 80155      p->rc = SQLITE_BUSY;
 80156    }else{
 80157      assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
 80158      assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
 80159      rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
 80160    }
 80161    goto vdbe_return;
 80162  }
 80163  
 80164  /* Opcode: Integer P1 P2 * * *
 80165  ** Synopsis: r[P2]=P1
 80166  **
 80167  ** The 32-bit integer value P1 is written into register P2.
 80168  */
 80169  case OP_Integer: {         /* out2 */
 80170    pOut = out2Prerelease(p, pOp);
 80171    pOut->u.i = pOp->p1;
 80172    break;
 80173  }
 80174  
 80175  /* Opcode: Int64 * P2 * P4 *
 80176  ** Synopsis: r[P2]=P4
 80177  **
 80178  ** P4 is a pointer to a 64-bit integer value.
 80179  ** Write that value into register P2.
 80180  */
 80181  case OP_Int64: {           /* out2 */
 80182    pOut = out2Prerelease(p, pOp);
 80183    assert( pOp->p4.pI64!=0 );
 80184    pOut->u.i = *pOp->p4.pI64;
 80185    break;
 80186  }
 80187  
 80188  #ifndef SQLITE_OMIT_FLOATING_POINT
 80189  /* Opcode: Real * P2 * P4 *
 80190  ** Synopsis: r[P2]=P4
 80191  **
 80192  ** P4 is a pointer to a 64-bit floating point value.
 80193  ** Write that value into register P2.
 80194  */
 80195  case OP_Real: {            /* same as TK_FLOAT, out2 */
 80196    pOut = out2Prerelease(p, pOp);
 80197    pOut->flags = MEM_Real;
 80198    assert( !sqlite3IsNaN(*pOp->p4.pReal) );
 80199    pOut->u.r = *pOp->p4.pReal;
 80200    break;
 80201  }
 80202  #endif
 80203  
 80204  /* Opcode: String8 * P2 * P4 *
 80205  ** Synopsis: r[P2]='P4'
 80206  **
 80207  ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
 80208  ** into a String opcode before it is executed for the first time.  During
 80209  ** this transformation, the length of string P4 is computed and stored
 80210  ** as the P1 parameter.
 80211  */
 80212  case OP_String8: {         /* same as TK_STRING, out2 */
 80213    assert( pOp->p4.z!=0 );
 80214    pOut = out2Prerelease(p, pOp);
 80215    pOp->opcode = OP_String;
 80216    pOp->p1 = sqlite3Strlen30(pOp->p4.z);
 80217  
 80218  #ifndef SQLITE_OMIT_UTF16
 80219    if( encoding!=SQLITE_UTF8 ){
 80220      rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
 80221      assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
 80222      if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
 80223      assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
 80224      assert( VdbeMemDynamic(pOut)==0 );
 80225      pOut->szMalloc = 0;
 80226      pOut->flags |= MEM_Static;
 80227      if( pOp->p4type==P4_DYNAMIC ){
 80228        sqlite3DbFree(db, pOp->p4.z);
 80229      }
 80230      pOp->p4type = P4_DYNAMIC;
 80231      pOp->p4.z = pOut->z;
 80232      pOp->p1 = pOut->n;
 80233    }
 80234    testcase( rc==SQLITE_TOOBIG );
 80235  #endif
 80236    if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
 80237      goto too_big;
 80238    }
 80239    assert( rc==SQLITE_OK );
 80240    /* Fall through to the next case, OP_String */
 80241  }
 80242    
 80243  /* Opcode: String P1 P2 P3 P4 P5
 80244  ** Synopsis: r[P2]='P4' (len=P1)
 80245  **
 80246  ** The string value P4 of length P1 (bytes) is stored in register P2.
 80247  **
 80248  ** If P3 is not zero and the content of register P3 is equal to P5, then
 80249  ** the datatype of the register P2 is converted to BLOB.  The content is
 80250  ** the same sequence of bytes, it is merely interpreted as a BLOB instead
 80251  ** of a string, as if it had been CAST.  In other words:
 80252  **
 80253  ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
 80254  */
 80255  case OP_String: {          /* out2 */
 80256    assert( pOp->p4.z!=0 );
 80257    pOut = out2Prerelease(p, pOp);
 80258    pOut->flags = MEM_Str|MEM_Static|MEM_Term;
 80259    pOut->z = pOp->p4.z;
 80260    pOut->n = pOp->p1;
 80261    pOut->enc = encoding;
 80262    UPDATE_MAX_BLOBSIZE(pOut);
 80263  #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
 80264    if( pOp->p3>0 ){
 80265      assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
 80266      pIn3 = &aMem[pOp->p3];
 80267      assert( pIn3->flags & MEM_Int );
 80268      if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
 80269    }
 80270  #endif
 80271    break;
 80272  }
 80273  
 80274  /* Opcode: Null P1 P2 P3 * *
 80275  ** Synopsis: r[P2..P3]=NULL
 80276  **
 80277  ** Write a NULL into registers P2.  If P3 greater than P2, then also write
 80278  ** NULL into register P3 and every register in between P2 and P3.  If P3
 80279  ** is less than P2 (typically P3 is zero) then only register P2 is
 80280  ** set to NULL.
 80281  **
 80282  ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
 80283  ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
 80284  ** OP_Ne or OP_Eq.
 80285  */
 80286  case OP_Null: {           /* out2 */
 80287    int cnt;
 80288    u16 nullFlag;
 80289    pOut = out2Prerelease(p, pOp);
 80290    cnt = pOp->p3-pOp->p2;
 80291    assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
 80292    pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
 80293    pOut->n = 0;
 80294    while( cnt>0 ){
 80295      pOut++;
 80296      memAboutToChange(p, pOut);
 80297      sqlite3VdbeMemSetNull(pOut);
 80298      pOut->flags = nullFlag;
 80299      pOut->n = 0;
 80300      cnt--;
 80301    }
 80302    break;
 80303  }
 80304  
 80305  /* Opcode: SoftNull P1 * * * *
 80306  ** Synopsis: r[P1]=NULL
 80307  **
 80308  ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
 80309  ** instruction, but do not free any string or blob memory associated with
 80310  ** the register, so that if the value was a string or blob that was
 80311  ** previously copied using OP_SCopy, the copies will continue to be valid.
 80312  */
 80313  case OP_SoftNull: {
 80314    assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
 80315    pOut = &aMem[pOp->p1];
 80316    pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
 80317    break;
 80318  }
 80319  
 80320  /* Opcode: Blob P1 P2 * P4 *
 80321  ** Synopsis: r[P2]=P4 (len=P1)
 80322  **
 80323  ** P4 points to a blob of data P1 bytes long.  Store this
 80324  ** blob in register P2.
 80325  */
 80326  case OP_Blob: {                /* out2 */
 80327    assert( pOp->p1 <= SQLITE_MAX_LENGTH );
 80328    pOut = out2Prerelease(p, pOp);
 80329    sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
 80330    pOut->enc = encoding;
 80331    UPDATE_MAX_BLOBSIZE(pOut);
 80332    break;
 80333  }
 80334  
 80335  /* Opcode: Variable P1 P2 * P4 *
 80336  ** Synopsis: r[P2]=parameter(P1,P4)
 80337  **
 80338  ** Transfer the values of bound parameter P1 into register P2
 80339  **
 80340  ** If the parameter is named, then its name appears in P4.
 80341  ** The P4 value is used by sqlite3_bind_parameter_name().
 80342  */
 80343  case OP_Variable: {            /* out2 */
 80344    Mem *pVar;       /* Value being transferred */
 80345  
 80346    assert( pOp->p1>0 && pOp->p1<=p->nVar );
 80347    assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
 80348    pVar = &p->aVar[pOp->p1 - 1];
 80349    if( sqlite3VdbeMemTooBig(pVar) ){
 80350      goto too_big;
 80351    }
 80352    pOut = &aMem[pOp->p2];
 80353    sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
 80354    UPDATE_MAX_BLOBSIZE(pOut);
 80355    break;
 80356  }
 80357  
 80358  /* Opcode: Move P1 P2 P3 * *
 80359  ** Synopsis: r[P2@P3]=r[P1@P3]
 80360  **
 80361  ** Move the P3 values in register P1..P1+P3-1 over into
 80362  ** registers P2..P2+P3-1.  Registers P1..P1+P3-1 are
 80363  ** left holding a NULL.  It is an error for register ranges
 80364  ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.  It is an error
 80365  ** for P3 to be less than 1.
 80366  */
 80367  case OP_Move: {
 80368    int n;           /* Number of registers left to copy */
 80369    int p1;          /* Register to copy from */
 80370    int p2;          /* Register to copy to */
 80371  
 80372    n = pOp->p3;
 80373    p1 = pOp->p1;
 80374    p2 = pOp->p2;
 80375    assert( n>0 && p1>0 && p2>0 );
 80376    assert( p1+n<=p2 || p2+n<=p1 );
 80377  
 80378    pIn1 = &aMem[p1];
 80379    pOut = &aMem[p2];
 80380    do{
 80381      assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
 80382      assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
 80383      assert( memIsValid(pIn1) );
 80384      memAboutToChange(p, pOut);
 80385      sqlite3VdbeMemMove(pOut, pIn1);
 80386  #ifdef SQLITE_DEBUG
 80387      if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
 80388        pOut->pScopyFrom += pOp->p2 - p1;
 80389      }
 80390  #endif
 80391      Deephemeralize(pOut);
 80392      REGISTER_TRACE(p2++, pOut);
 80393      pIn1++;
 80394      pOut++;
 80395    }while( --n );
 80396    break;
 80397  }
 80398  
 80399  /* Opcode: Copy P1 P2 P3 * *
 80400  ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
 80401  **
 80402  ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
 80403  **
 80404  ** This instruction makes a deep copy of the value.  A duplicate
 80405  ** is made of any string or blob constant.  See also OP_SCopy.
 80406  */
 80407  case OP_Copy: {
 80408    int n;
 80409  
 80410    n = pOp->p3;
 80411    pIn1 = &aMem[pOp->p1];
 80412    pOut = &aMem[pOp->p2];
 80413    assert( pOut!=pIn1 );
 80414    while( 1 ){
 80415      sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
 80416      Deephemeralize(pOut);
 80417  #ifdef SQLITE_DEBUG
 80418      pOut->pScopyFrom = 0;
 80419  #endif
 80420      REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
 80421      if( (n--)==0 ) break;
 80422      pOut++;
 80423      pIn1++;
 80424    }
 80425    break;
 80426  }
 80427  
 80428  /* Opcode: SCopy P1 P2 * * *
 80429  ** Synopsis: r[P2]=r[P1]
 80430  **
 80431  ** Make a shallow copy of register P1 into register P2.
 80432  **
 80433  ** This instruction makes a shallow copy of the value.  If the value
 80434  ** is a string or blob, then the copy is only a pointer to the
 80435  ** original and hence if the original changes so will the copy.
 80436  ** Worse, if the original is deallocated, the copy becomes invalid.
 80437  ** Thus the program must guarantee that the original will not change
 80438  ** during the lifetime of the copy.  Use OP_Copy to make a complete
 80439  ** copy.
 80440  */
 80441  case OP_SCopy: {            /* out2 */
 80442    pIn1 = &aMem[pOp->p1];
 80443    pOut = &aMem[pOp->p2];
 80444    assert( pOut!=pIn1 );
 80445    sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
 80446  #ifdef SQLITE_DEBUG
 80447    if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
 80448  #endif
 80449    break;
 80450  }
 80451  
 80452  /* Opcode: IntCopy P1 P2 * * *
 80453  ** Synopsis: r[P2]=r[P1]
 80454  **
 80455  ** Transfer the integer value held in register P1 into register P2.
 80456  **
 80457  ** This is an optimized version of SCopy that works only for integer
 80458  ** values.
 80459  */
 80460  case OP_IntCopy: {            /* out2 */
 80461    pIn1 = &aMem[pOp->p1];
 80462    assert( (pIn1->flags & MEM_Int)!=0 );
 80463    pOut = &aMem[pOp->p2];
 80464    sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
 80465    break;
 80466  }
 80467  
 80468  /* Opcode: ResultRow P1 P2 * * *
 80469  ** Synopsis: output=r[P1@P2]
 80470  **
 80471  ** The registers P1 through P1+P2-1 contain a single row of
 80472  ** results. This opcode causes the sqlite3_step() call to terminate
 80473  ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
 80474  ** structure to provide access to the r(P1)..r(P1+P2-1) values as
 80475  ** the result row.
 80476  */
 80477  case OP_ResultRow: {
 80478    Mem *pMem;
 80479    int i;
 80480    assert( p->nResColumn==pOp->p2 );
 80481    assert( pOp->p1>0 );
 80482    assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
 80483  
 80484  #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
 80485    /* Run the progress counter just before returning.
 80486    */
 80487    if( db->xProgress!=0
 80488     && nVmStep>=nProgressLimit 
 80489     && db->xProgress(db->pProgressArg)!=0
 80490    ){
 80491      rc = SQLITE_INTERRUPT;
 80492      goto abort_due_to_error;
 80493    }
 80494  #endif
 80495  
 80496    /* If this statement has violated immediate foreign key constraints, do
 80497    ** not return the number of rows modified. And do not RELEASE the statement
 80498    ** transaction. It needs to be rolled back.  */
 80499    if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
 80500      assert( db->flags&SQLITE_CountRows );
 80501      assert( p->usesStmtJournal );
 80502      goto abort_due_to_error;
 80503    }
 80504  
 80505    /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then 
 80506    ** DML statements invoke this opcode to return the number of rows 
 80507    ** modified to the user. This is the only way that a VM that
 80508    ** opens a statement transaction may invoke this opcode.
 80509    **
 80510    ** In case this is such a statement, close any statement transaction
 80511    ** opened by this VM before returning control to the user. This is to
 80512    ** ensure that statement-transactions are always nested, not overlapping.
 80513    ** If the open statement-transaction is not closed here, then the user
 80514    ** may step another VM that opens its own statement transaction. This
 80515    ** may lead to overlapping statement transactions.
 80516    **
 80517    ** The statement transaction is never a top-level transaction.  Hence
 80518    ** the RELEASE call below can never fail.
 80519    */
 80520    assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
 80521    rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
 80522    assert( rc==SQLITE_OK );
 80523  
 80524    /* Invalidate all ephemeral cursor row caches */
 80525    p->cacheCtr = (p->cacheCtr + 2)|1;
 80526  
 80527    /* Make sure the results of the current row are \000 terminated
 80528    ** and have an assigned type.  The results are de-ephemeralized as
 80529    ** a side effect.
 80530    */
 80531    pMem = p->pResultSet = &aMem[pOp->p1];
 80532    for(i=0; i<pOp->p2; i++){
 80533      assert( memIsValid(&pMem[i]) );
 80534      Deephemeralize(&pMem[i]);
 80535      assert( (pMem[i].flags & MEM_Ephem)==0
 80536              || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
 80537      sqlite3VdbeMemNulTerminate(&pMem[i]);
 80538      REGISTER_TRACE(pOp->p1+i, &pMem[i]);
 80539    }
 80540    if( db->mallocFailed ) goto no_mem;
 80541  
 80542    if( db->mTrace & SQLITE_TRACE_ROW ){
 80543      db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
 80544    }
 80545  
 80546    /* Return SQLITE_ROW
 80547    */
 80548    p->pc = (int)(pOp - aOp) + 1;
 80549    rc = SQLITE_ROW;
 80550    goto vdbe_return;
 80551  }
 80552  
 80553  /* Opcode: Concat P1 P2 P3 * *
 80554  ** Synopsis: r[P3]=r[P2]+r[P1]
 80555  **
 80556  ** Add the text in register P1 onto the end of the text in
 80557  ** register P2 and store the result in register P3.
 80558  ** If either the P1 or P2 text are NULL then store NULL in P3.
 80559  **
 80560  **   P3 = P2 || P1
 80561  **
 80562  ** It is illegal for P1 and P3 to be the same register. Sometimes,
 80563  ** if P3 is the same register as P2, the implementation is able
 80564  ** to avoid a memcpy().
 80565  */
 80566  case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
 80567    i64 nByte;
 80568  
 80569    pIn1 = &aMem[pOp->p1];
 80570    pIn2 = &aMem[pOp->p2];
 80571    pOut = &aMem[pOp->p3];
 80572    assert( pIn1!=pOut );
 80573    if( (pIn1->flags | pIn2->flags) & MEM_Null ){
 80574      sqlite3VdbeMemSetNull(pOut);
 80575      break;
 80576    }
 80577    if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
 80578    Stringify(pIn1, encoding);
 80579    Stringify(pIn2, encoding);
 80580    nByte = pIn1->n + pIn2->n;
 80581    if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
 80582      goto too_big;
 80583    }
 80584    if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
 80585      goto no_mem;
 80586    }
 80587    MemSetTypeFlag(pOut, MEM_Str);
 80588    if( pOut!=pIn2 ){
 80589      memcpy(pOut->z, pIn2->z, pIn2->n);
 80590    }
 80591    memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
 80592    pOut->z[nByte]=0;
 80593    pOut->z[nByte+1] = 0;
 80594    pOut->flags |= MEM_Term;
 80595    pOut->n = (int)nByte;
 80596    pOut->enc = encoding;
 80597    UPDATE_MAX_BLOBSIZE(pOut);
 80598    break;
 80599  }
 80600  
 80601  /* Opcode: Add P1 P2 P3 * *
 80602  ** Synopsis: r[P3]=r[P1]+r[P2]
 80603  **
 80604  ** Add the value in register P1 to the value in register P2
 80605  ** and store the result in register P3.
 80606  ** If either input is NULL, the result is NULL.
 80607  */
 80608  /* Opcode: Multiply P1 P2 P3 * *
 80609  ** Synopsis: r[P3]=r[P1]*r[P2]
 80610  **
 80611  **
 80612  ** Multiply the value in register P1 by the value in register P2
 80613  ** and store the result in register P3.
 80614  ** If either input is NULL, the result is NULL.
 80615  */
 80616  /* Opcode: Subtract P1 P2 P3 * *
 80617  ** Synopsis: r[P3]=r[P2]-r[P1]
 80618  **
 80619  ** Subtract the value in register P1 from the value in register P2
 80620  ** and store the result in register P3.
 80621  ** If either input is NULL, the result is NULL.
 80622  */
 80623  /* Opcode: Divide P1 P2 P3 * *
 80624  ** Synopsis: r[P3]=r[P2]/r[P1]
 80625  **
 80626  ** Divide the value in register P1 by the value in register P2
 80627  ** and store the result in register P3 (P3=P2/P1). If the value in 
 80628  ** register P1 is zero, then the result is NULL. If either input is 
 80629  ** NULL, the result is NULL.
 80630  */
 80631  /* Opcode: Remainder P1 P2 P3 * *
 80632  ** Synopsis: r[P3]=r[P2]%r[P1]
 80633  **
 80634  ** Compute the remainder after integer register P2 is divided by 
 80635  ** register P1 and store the result in register P3. 
 80636  ** If the value in register P1 is zero the result is NULL.
 80637  ** If either operand is NULL, the result is NULL.
 80638  */
 80639  case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
 80640  case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
 80641  case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
 80642  case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
 80643  case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
 80644    char bIntint;   /* Started out as two integer operands */
 80645    u16 flags;      /* Combined MEM_* flags from both inputs */
 80646    u16 type1;      /* Numeric type of left operand */
 80647    u16 type2;      /* Numeric type of right operand */
 80648    i64 iA;         /* Integer value of left operand */
 80649    i64 iB;         /* Integer value of right operand */
 80650    double rA;      /* Real value of left operand */
 80651    double rB;      /* Real value of right operand */
 80652  
 80653    pIn1 = &aMem[pOp->p1];
 80654    type1 = numericType(pIn1);
 80655    pIn2 = &aMem[pOp->p2];
 80656    type2 = numericType(pIn2);
 80657    pOut = &aMem[pOp->p3];
 80658    flags = pIn1->flags | pIn2->flags;
 80659    if( (type1 & type2 & MEM_Int)!=0 ){
 80660      iA = pIn1->u.i;
 80661      iB = pIn2->u.i;
 80662      bIntint = 1;
 80663      switch( pOp->opcode ){
 80664        case OP_Add:       if( sqlite3AddInt64(&iB,iA) ) goto fp_math;  break;
 80665        case OP_Subtract:  if( sqlite3SubInt64(&iB,iA) ) goto fp_math;  break;
 80666        case OP_Multiply:  if( sqlite3MulInt64(&iB,iA) ) goto fp_math;  break;
 80667        case OP_Divide: {
 80668          if( iA==0 ) goto arithmetic_result_is_null;
 80669          if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
 80670          iB /= iA;
 80671          break;
 80672        }
 80673        default: {
 80674          if( iA==0 ) goto arithmetic_result_is_null;
 80675          if( iA==-1 ) iA = 1;
 80676          iB %= iA;
 80677          break;
 80678        }
 80679      }
 80680      pOut->u.i = iB;
 80681      MemSetTypeFlag(pOut, MEM_Int);
 80682    }else if( (flags & MEM_Null)!=0 ){
 80683      goto arithmetic_result_is_null;
 80684    }else{
 80685      bIntint = 0;
 80686  fp_math:
 80687      rA = sqlite3VdbeRealValue(pIn1);
 80688      rB = sqlite3VdbeRealValue(pIn2);
 80689      switch( pOp->opcode ){
 80690        case OP_Add:         rB += rA;       break;
 80691        case OP_Subtract:    rB -= rA;       break;
 80692        case OP_Multiply:    rB *= rA;       break;
 80693        case OP_Divide: {
 80694          /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
 80695          if( rA==(double)0 ) goto arithmetic_result_is_null;
 80696          rB /= rA;
 80697          break;
 80698        }
 80699        default: {
 80700          iA = (i64)rA;
 80701          iB = (i64)rB;
 80702          if( iA==0 ) goto arithmetic_result_is_null;
 80703          if( iA==-1 ) iA = 1;
 80704          rB = (double)(iB % iA);
 80705          break;
 80706        }
 80707      }
 80708  #ifdef SQLITE_OMIT_FLOATING_POINT
 80709      pOut->u.i = rB;
 80710      MemSetTypeFlag(pOut, MEM_Int);
 80711  #else
 80712      if( sqlite3IsNaN(rB) ){
 80713        goto arithmetic_result_is_null;
 80714      }
 80715      pOut->u.r = rB;
 80716      MemSetTypeFlag(pOut, MEM_Real);
 80717      if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
 80718        sqlite3VdbeIntegerAffinity(pOut);
 80719      }
 80720  #endif
 80721    }
 80722    break;
 80723  
 80724  arithmetic_result_is_null:
 80725    sqlite3VdbeMemSetNull(pOut);
 80726    break;
 80727  }
 80728  
 80729  /* Opcode: CollSeq P1 * * P4
 80730  **
 80731  ** P4 is a pointer to a CollSeq object. If the next call to a user function
 80732  ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
 80733  ** be returned. This is used by the built-in min(), max() and nullif()
 80734  ** functions.
 80735  **
 80736  ** If P1 is not zero, then it is a register that a subsequent min() or
 80737  ** max() aggregate will set to 1 if the current row is not the minimum or
 80738  ** maximum.  The P1 register is initialized to 0 by this instruction.
 80739  **
 80740  ** The interface used by the implementation of the aforementioned functions
 80741  ** to retrieve the collation sequence set by this opcode is not available
 80742  ** publicly.  Only built-in functions have access to this feature.
 80743  */
 80744  case OP_CollSeq: {
 80745    assert( pOp->p4type==P4_COLLSEQ );
 80746    if( pOp->p1 ){
 80747      sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
 80748    }
 80749    break;
 80750  }
 80751  
 80752  /* Opcode: BitAnd P1 P2 P3 * *
 80753  ** Synopsis: r[P3]=r[P1]&r[P2]
 80754  **
 80755  ** Take the bit-wise AND of the values in register P1 and P2 and
 80756  ** store the result in register P3.
 80757  ** If either input is NULL, the result is NULL.
 80758  */
 80759  /* Opcode: BitOr P1 P2 P3 * *
 80760  ** Synopsis: r[P3]=r[P1]|r[P2]
 80761  **
 80762  ** Take the bit-wise OR of the values in register P1 and P2 and
 80763  ** store the result in register P3.
 80764  ** If either input is NULL, the result is NULL.
 80765  */
 80766  /* Opcode: ShiftLeft P1 P2 P3 * *
 80767  ** Synopsis: r[P3]=r[P2]<<r[P1]
 80768  **
 80769  ** Shift the integer value in register P2 to the left by the
 80770  ** number of bits specified by the integer in register P1.
 80771  ** Store the result in register P3.
 80772  ** If either input is NULL, the result is NULL.
 80773  */
 80774  /* Opcode: ShiftRight P1 P2 P3 * *
 80775  ** Synopsis: r[P3]=r[P2]>>r[P1]
 80776  **
 80777  ** Shift the integer value in register P2 to the right by the
 80778  ** number of bits specified by the integer in register P1.
 80779  ** Store the result in register P3.
 80780  ** If either input is NULL, the result is NULL.
 80781  */
 80782  case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
 80783  case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
 80784  case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
 80785  case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
 80786    i64 iA;
 80787    u64 uA;
 80788    i64 iB;
 80789    u8 op;
 80790  
 80791    pIn1 = &aMem[pOp->p1];
 80792    pIn2 = &aMem[pOp->p2];
 80793    pOut = &aMem[pOp->p3];
 80794    if( (pIn1->flags | pIn2->flags) & MEM_Null ){
 80795      sqlite3VdbeMemSetNull(pOut);
 80796      break;
 80797    }
 80798    iA = sqlite3VdbeIntValue(pIn2);
 80799    iB = sqlite3VdbeIntValue(pIn1);
 80800    op = pOp->opcode;
 80801    if( op==OP_BitAnd ){
 80802      iA &= iB;
 80803    }else if( op==OP_BitOr ){
 80804      iA |= iB;
 80805    }else if( iB!=0 ){
 80806      assert( op==OP_ShiftRight || op==OP_ShiftLeft );
 80807  
 80808      /* If shifting by a negative amount, shift in the other direction */
 80809      if( iB<0 ){
 80810        assert( OP_ShiftRight==OP_ShiftLeft+1 );
 80811        op = 2*OP_ShiftLeft + 1 - op;
 80812        iB = iB>(-64) ? -iB : 64;
 80813      }
 80814  
 80815      if( iB>=64 ){
 80816        iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
 80817      }else{
 80818        memcpy(&uA, &iA, sizeof(uA));
 80819        if( op==OP_ShiftLeft ){
 80820          uA <<= iB;
 80821        }else{
 80822          uA >>= iB;
 80823          /* Sign-extend on a right shift of a negative number */
 80824          if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
 80825        }
 80826        memcpy(&iA, &uA, sizeof(iA));
 80827      }
 80828    }
 80829    pOut->u.i = iA;
 80830    MemSetTypeFlag(pOut, MEM_Int);
 80831    break;
 80832  }
 80833  
 80834  /* Opcode: AddImm  P1 P2 * * *
 80835  ** Synopsis: r[P1]=r[P1]+P2
 80836  ** 
 80837  ** Add the constant P2 to the value in register P1.
 80838  ** The result is always an integer.
 80839  **
 80840  ** To force any register to be an integer, just add 0.
 80841  */
 80842  case OP_AddImm: {            /* in1 */
 80843    pIn1 = &aMem[pOp->p1];
 80844    memAboutToChange(p, pIn1);
 80845    sqlite3VdbeMemIntegerify(pIn1);
 80846    pIn1->u.i += pOp->p2;
 80847    break;
 80848  }
 80849  
 80850  /* Opcode: MustBeInt P1 P2 * * *
 80851  ** 
 80852  ** Force the value in register P1 to be an integer.  If the value
 80853  ** in P1 is not an integer and cannot be converted into an integer
 80854  ** without data loss, then jump immediately to P2, or if P2==0
 80855  ** raise an SQLITE_MISMATCH exception.
 80856  */
 80857  case OP_MustBeInt: {            /* jump, in1 */
 80858    pIn1 = &aMem[pOp->p1];
 80859    if( (pIn1->flags & MEM_Int)==0 ){
 80860      applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
 80861      VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
 80862      if( (pIn1->flags & MEM_Int)==0 ){
 80863        if( pOp->p2==0 ){
 80864          rc = SQLITE_MISMATCH;
 80865          goto abort_due_to_error;
 80866        }else{
 80867          goto jump_to_p2;
 80868        }
 80869      }
 80870    }
 80871    MemSetTypeFlag(pIn1, MEM_Int);
 80872    break;
 80873  }
 80874  
 80875  #ifndef SQLITE_OMIT_FLOATING_POINT
 80876  /* Opcode: RealAffinity P1 * * * *
 80877  **
 80878  ** If register P1 holds an integer convert it to a real value.
 80879  **
 80880  ** This opcode is used when extracting information from a column that
 80881  ** has REAL affinity.  Such column values may still be stored as
 80882  ** integers, for space efficiency, but after extraction we want them
 80883  ** to have only a real value.
 80884  */
 80885  case OP_RealAffinity: {                  /* in1 */
 80886    pIn1 = &aMem[pOp->p1];
 80887    if( pIn1->flags & MEM_Int ){
 80888      sqlite3VdbeMemRealify(pIn1);
 80889    }
 80890    break;
 80891  }
 80892  #endif
 80893  
 80894  #ifndef SQLITE_OMIT_CAST
 80895  /* Opcode: Cast P1 P2 * * *
 80896  ** Synopsis: affinity(r[P1])
 80897  **
 80898  ** Force the value in register P1 to be the type defined by P2.
 80899  ** 
 80900  ** <ul>
 80901  ** <li> P2=='A' &rarr; BLOB
 80902  ** <li> P2=='B' &rarr; TEXT
 80903  ** <li> P2=='C' &rarr; NUMERIC
 80904  ** <li> P2=='D' &rarr; INTEGER
 80905  ** <li> P2=='E' &rarr; REAL
 80906  ** </ul>
 80907  **
 80908  ** A NULL value is not changed by this routine.  It remains NULL.
 80909  */
 80910  case OP_Cast: {                  /* in1 */
 80911    assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
 80912    testcase( pOp->p2==SQLITE_AFF_TEXT );
 80913    testcase( pOp->p2==SQLITE_AFF_BLOB );
 80914    testcase( pOp->p2==SQLITE_AFF_NUMERIC );
 80915    testcase( pOp->p2==SQLITE_AFF_INTEGER );
 80916    testcase( pOp->p2==SQLITE_AFF_REAL );
 80917    pIn1 = &aMem[pOp->p1];
 80918    memAboutToChange(p, pIn1);
 80919    rc = ExpandBlob(pIn1);
 80920    sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
 80921    UPDATE_MAX_BLOBSIZE(pIn1);
 80922    if( rc ) goto abort_due_to_error;
 80923    break;
 80924  }
 80925  #endif /* SQLITE_OMIT_CAST */
 80926  
 80927  /* Opcode: Eq P1 P2 P3 P4 P5
 80928  ** Synopsis: IF r[P3]==r[P1]
 80929  **
 80930  ** Compare the values in register P1 and P3.  If reg(P3)==reg(P1) then
 80931  ** jump to address P2.  Or if the SQLITE_STOREP2 flag is set in P5, then
 80932  ** store the result of comparison in register P2.
 80933  **
 80934  ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
 80935  ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
 80936  ** to coerce both inputs according to this affinity before the
 80937  ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
 80938  ** affinity is used. Note that the affinity conversions are stored
 80939  ** back into the input registers P1 and P3.  So this opcode can cause
 80940  ** persistent changes to registers P1 and P3.
 80941  **
 80942  ** Once any conversions have taken place, and neither value is NULL, 
 80943  ** the values are compared. If both values are blobs then memcmp() is
 80944  ** used to determine the results of the comparison.  If both values
 80945  ** are text, then the appropriate collating function specified in
 80946  ** P4 is used to do the comparison.  If P4 is not specified then
 80947  ** memcmp() is used to compare text string.  If both values are
 80948  ** numeric, then a numeric comparison is used. If the two values
 80949  ** are of different types, then numbers are considered less than
 80950  ** strings and strings are considered less than blobs.
 80951  **
 80952  ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
 80953  ** true or false and is never NULL.  If both operands are NULL then the result
 80954  ** of comparison is true.  If either operand is NULL then the result is false.
 80955  ** If neither operand is NULL the result is the same as it would be if
 80956  ** the SQLITE_NULLEQ flag were omitted from P5.
 80957  **
 80958  ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
 80959  ** content of r[P2] is only changed if the new value is NULL or 0 (false).
 80960  ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
 80961  */
 80962  /* Opcode: Ne P1 P2 P3 P4 P5
 80963  ** Synopsis: IF r[P3]!=r[P1]
 80964  **
 80965  ** This works just like the Eq opcode except that the jump is taken if
 80966  ** the operands in registers P1 and P3 are not equal.  See the Eq opcode for
 80967  ** additional information.
 80968  **
 80969  ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
 80970  ** content of r[P2] is only changed if the new value is NULL or 1 (true).
 80971  ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
 80972  */
 80973  /* Opcode: Lt P1 P2 P3 P4 P5
 80974  ** Synopsis: IF r[P3]<r[P1]
 80975  **
 80976  ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
 80977  ** jump to address P2.  Or if the SQLITE_STOREP2 flag is set in P5 store
 80978  ** the result of comparison (0 or 1 or NULL) into register P2.
 80979  **
 80980  ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
 80981  ** reg(P3) is NULL then the take the jump.  If the SQLITE_JUMPIFNULL 
 80982  ** bit is clear then fall through if either operand is NULL.
 80983  **
 80984  ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
 80985  ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
 80986  ** to coerce both inputs according to this affinity before the
 80987  ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
 80988  ** affinity is used. Note that the affinity conversions are stored
 80989  ** back into the input registers P1 and P3.  So this opcode can cause
 80990  ** persistent changes to registers P1 and P3.
 80991  **
 80992  ** Once any conversions have taken place, and neither value is NULL, 
 80993  ** the values are compared. If both values are blobs then memcmp() is
 80994  ** used to determine the results of the comparison.  If both values
 80995  ** are text, then the appropriate collating function specified in
 80996  ** P4 is  used to do the comparison.  If P4 is not specified then
 80997  ** memcmp() is used to compare text string.  If both values are
 80998  ** numeric, then a numeric comparison is used. If the two values
 80999  ** are of different types, then numbers are considered less than
 81000  ** strings and strings are considered less than blobs.
 81001  */
 81002  /* Opcode: Le P1 P2 P3 P4 P5
 81003  ** Synopsis: IF r[P3]<=r[P1]
 81004  **
 81005  ** This works just like the Lt opcode except that the jump is taken if
 81006  ** the content of register P3 is less than or equal to the content of
 81007  ** register P1.  See the Lt opcode for additional information.
 81008  */
 81009  /* Opcode: Gt P1 P2 P3 P4 P5
 81010  ** Synopsis: IF r[P3]>r[P1]
 81011  **
 81012  ** This works just like the Lt opcode except that the jump is taken if
 81013  ** the content of register P3 is greater than the content of
 81014  ** register P1.  See the Lt opcode for additional information.
 81015  */
 81016  /* Opcode: Ge P1 P2 P3 P4 P5
 81017  ** Synopsis: IF r[P3]>=r[P1]
 81018  **
 81019  ** This works just like the Lt opcode except that the jump is taken if
 81020  ** the content of register P3 is greater than or equal to the content of
 81021  ** register P1.  See the Lt opcode for additional information.
 81022  */
 81023  case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
 81024  case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
 81025  case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
 81026  case OP_Le:               /* same as TK_LE, jump, in1, in3 */
 81027  case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
 81028  case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
 81029    int res, res2;      /* Result of the comparison of pIn1 against pIn3 */
 81030    char affinity;      /* Affinity to use for comparison */
 81031    u16 flags1;         /* Copy of initial value of pIn1->flags */
 81032    u16 flags3;         /* Copy of initial value of pIn3->flags */
 81033  
 81034    pIn1 = &aMem[pOp->p1];
 81035    pIn3 = &aMem[pOp->p3];
 81036    flags1 = pIn1->flags;
 81037    flags3 = pIn3->flags;
 81038    if( (flags1 | flags3)&MEM_Null ){
 81039      /* One or both operands are NULL */
 81040      if( pOp->p5 & SQLITE_NULLEQ ){
 81041        /* If SQLITE_NULLEQ is set (which will only happen if the operator is
 81042        ** OP_Eq or OP_Ne) then take the jump or not depending on whether
 81043        ** or not both operands are null.
 81044        */
 81045        assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
 81046        assert( (flags1 & MEM_Cleared)==0 );
 81047        assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
 81048        if( (flags1&flags3&MEM_Null)!=0
 81049         && (flags3&MEM_Cleared)==0
 81050        ){
 81051          res = 0;  /* Operands are equal */
 81052        }else{
 81053          res = 1;  /* Operands are not equal */
 81054        }
 81055      }else{
 81056        /* SQLITE_NULLEQ is clear and at least one operand is NULL,
 81057        ** then the result is always NULL.
 81058        ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
 81059        */
 81060        if( pOp->p5 & SQLITE_STOREP2 ){
 81061          pOut = &aMem[pOp->p2];
 81062          iCompare = 1;    /* Operands are not equal */
 81063          memAboutToChange(p, pOut);
 81064          MemSetTypeFlag(pOut, MEM_Null);
 81065          REGISTER_TRACE(pOp->p2, pOut);
 81066        }else{
 81067          VdbeBranchTaken(2,3);
 81068          if( pOp->p5 & SQLITE_JUMPIFNULL ){
 81069            goto jump_to_p2;
 81070          }
 81071        }
 81072        break;
 81073      }
 81074    }else{
 81075      /* Neither operand is NULL.  Do a comparison. */
 81076      affinity = pOp->p5 & SQLITE_AFF_MASK;
 81077      if( affinity>=SQLITE_AFF_NUMERIC ){
 81078        if( (flags1 | flags3)&MEM_Str ){
 81079          if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
 81080            applyNumericAffinity(pIn1,0);
 81081            testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */
 81082            flags3 = pIn3->flags;
 81083          }
 81084          if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
 81085            applyNumericAffinity(pIn3,0);
 81086          }
 81087        }
 81088        /* Handle the common case of integer comparison here, as an
 81089        ** optimization, to avoid a call to sqlite3MemCompare() */
 81090        if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
 81091          if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
 81092          if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
 81093          res = 0;
 81094          goto compare_op;
 81095        }
 81096      }else if( affinity==SQLITE_AFF_TEXT ){
 81097        if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
 81098          testcase( pIn1->flags & MEM_Int );
 81099          testcase( pIn1->flags & MEM_Real );
 81100          sqlite3VdbeMemStringify(pIn1, encoding, 1);
 81101          testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
 81102          flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
 81103          assert( pIn1!=pIn3 );
 81104        }
 81105        if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
 81106          testcase( pIn3->flags & MEM_Int );
 81107          testcase( pIn3->flags & MEM_Real );
 81108          sqlite3VdbeMemStringify(pIn3, encoding, 1);
 81109          testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
 81110          flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
 81111        }
 81112      }
 81113      assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
 81114      res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
 81115    }
 81116  compare_op:
 81117    /* At this point, res is negative, zero, or positive if reg[P1] is
 81118    ** less than, equal to, or greater than reg[P3], respectively.  Compute
 81119    ** the answer to this operator in res2, depending on what the comparison
 81120    ** operator actually is.  The next block of code depends on the fact
 81121    ** that the 6 comparison operators are consecutive integers in this
 81122    ** order:  NE, EQ, GT, LE, LT, GE */
 81123    assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
 81124    assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
 81125    if( res<0 ){                        /* ne, eq, gt, le, lt, ge */
 81126      static const unsigned char aLTb[] = { 1,  0,  0,  1,  1,  0 };
 81127      res2 = aLTb[pOp->opcode - OP_Ne];
 81128    }else if( res==0 ){
 81129      static const unsigned char aEQb[] = { 0,  1,  0,  1,  0,  1 };
 81130      res2 = aEQb[pOp->opcode - OP_Ne];
 81131    }else{
 81132      static const unsigned char aGTb[] = { 1,  0,  1,  0,  0,  1 };
 81133      res2 = aGTb[pOp->opcode - OP_Ne];
 81134    }
 81135  
 81136    /* Undo any changes made by applyAffinity() to the input registers. */
 81137    assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
 81138    pIn1->flags = flags1;
 81139    assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
 81140    pIn3->flags = flags3;
 81141  
 81142    if( pOp->p5 & SQLITE_STOREP2 ){
 81143      pOut = &aMem[pOp->p2];
 81144      iCompare = res;
 81145      if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
 81146        /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
 81147        ** and prevents OP_Ne from overwriting NULL with 0.  This flag
 81148        ** is only used in contexts where either:
 81149        **   (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
 81150        **   (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
 81151        ** Therefore it is not necessary to check the content of r[P2] for
 81152        ** NULL. */
 81153        assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
 81154        assert( res2==0 || res2==1 );
 81155        testcase( res2==0 && pOp->opcode==OP_Eq );
 81156        testcase( res2==1 && pOp->opcode==OP_Eq );
 81157        testcase( res2==0 && pOp->opcode==OP_Ne );
 81158        testcase( res2==1 && pOp->opcode==OP_Ne );
 81159        if( (pOp->opcode==OP_Eq)==res2 ) break;
 81160      }
 81161      memAboutToChange(p, pOut);
 81162      MemSetTypeFlag(pOut, MEM_Int);
 81163      pOut->u.i = res2;
 81164      REGISTER_TRACE(pOp->p2, pOut);
 81165    }else{
 81166      VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
 81167      if( res2 ){
 81168        goto jump_to_p2;
 81169      }
 81170    }
 81171    break;
 81172  }
 81173  
 81174  /* Opcode: ElseNotEq * P2 * * *
 81175  **
 81176  ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
 81177  ** If result of an OP_Eq comparison on the same two operands
 81178  ** would have be NULL or false (0), then then jump to P2. 
 81179  ** If the result of an OP_Eq comparison on the two previous operands
 81180  ** would have been true (1), then fall through.
 81181  */
 81182  case OP_ElseNotEq: {       /* same as TK_ESCAPE, jump */
 81183    assert( pOp>aOp );
 81184    assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
 81185    assert( pOp[-1].p5 & SQLITE_STOREP2 );
 81186    VdbeBranchTaken(iCompare!=0, 2);
 81187    if( iCompare!=0 ) goto jump_to_p2;
 81188    break;
 81189  }
 81190  
 81191  
 81192  /* Opcode: Permutation * * * P4 *
 81193  **
 81194  ** Set the permutation used by the OP_Compare operator in the next
 81195  ** instruction.  The permutation is stored in the P4 operand.
 81196  **
 81197  ** The permutation is only valid until the next OP_Compare that has
 81198  ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should 
 81199  ** occur immediately prior to the OP_Compare.
 81200  **
 81201  ** The first integer in the P4 integer array is the length of the array
 81202  ** and does not become part of the permutation.
 81203  */
 81204  case OP_Permutation: {
 81205    assert( pOp->p4type==P4_INTARRAY );
 81206    assert( pOp->p4.ai );
 81207    assert( pOp[1].opcode==OP_Compare );
 81208    assert( pOp[1].p5 & OPFLAG_PERMUTE );
 81209    break;
 81210  }
 81211  
 81212  /* Opcode: Compare P1 P2 P3 P4 P5
 81213  ** Synopsis: r[P1@P3] <-> r[P2@P3]
 81214  **
 81215  ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
 81216  ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
 81217  ** the comparison for use by the next OP_Jump instruct.
 81218  **
 81219  ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
 81220  ** determined by the most recent OP_Permutation operator.  If the
 81221  ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
 81222  ** order.
 81223  **
 81224  ** P4 is a KeyInfo structure that defines collating sequences and sort
 81225  ** orders for the comparison.  The permutation applies to registers
 81226  ** only.  The KeyInfo elements are used sequentially.
 81227  **
 81228  ** The comparison is a sort comparison, so NULLs compare equal,
 81229  ** NULLs are less than numbers, numbers are less than strings,
 81230  ** and strings are less than blobs.
 81231  */
 81232  case OP_Compare: {
 81233    int n;
 81234    int i;
 81235    int p1;
 81236    int p2;
 81237    const KeyInfo *pKeyInfo;
 81238    int idx;
 81239    CollSeq *pColl;    /* Collating sequence to use on this term */
 81240    int bRev;          /* True for DESCENDING sort order */
 81241    int *aPermute;     /* The permutation */
 81242  
 81243    if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
 81244      aPermute = 0;
 81245    }else{
 81246      assert( pOp>aOp );
 81247      assert( pOp[-1].opcode==OP_Permutation );
 81248      assert( pOp[-1].p4type==P4_INTARRAY );
 81249      aPermute = pOp[-1].p4.ai + 1;
 81250      assert( aPermute!=0 );
 81251    }
 81252    n = pOp->p3;
 81253    pKeyInfo = pOp->p4.pKeyInfo;
 81254    assert( n>0 );
 81255    assert( pKeyInfo!=0 );
 81256    p1 = pOp->p1;
 81257    p2 = pOp->p2;
 81258  #ifdef SQLITE_DEBUG
 81259    if( aPermute ){
 81260      int k, mx = 0;
 81261      for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
 81262      assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
 81263      assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
 81264    }else{
 81265      assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
 81266      assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
 81267    }
 81268  #endif /* SQLITE_DEBUG */
 81269    for(i=0; i<n; i++){
 81270      idx = aPermute ? aPermute[i] : i;
 81271      assert( memIsValid(&aMem[p1+idx]) );
 81272      assert( memIsValid(&aMem[p2+idx]) );
 81273      REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
 81274      REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
 81275      assert( i<pKeyInfo->nKeyField );
 81276      pColl = pKeyInfo->aColl[i];
 81277      bRev = pKeyInfo->aSortOrder[i];
 81278      iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
 81279      if( iCompare ){
 81280        if( bRev ) iCompare = -iCompare;
 81281        break;
 81282      }
 81283    }
 81284    break;
 81285  }
 81286  
 81287  /* Opcode: Jump P1 P2 P3 * *
 81288  **
 81289  ** Jump to the instruction at address P1, P2, or P3 depending on whether
 81290  ** in the most recent OP_Compare instruction the P1 vector was less than
 81291  ** equal to, or greater than the P2 vector, respectively.
 81292  */
 81293  case OP_Jump: {             /* jump */
 81294    if( iCompare<0 ){
 81295      VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
 81296    }else if( iCompare==0 ){
 81297      VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
 81298    }else{
 81299      VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
 81300    }
 81301    break;
 81302  }
 81303  
 81304  /* Opcode: And P1 P2 P3 * *
 81305  ** Synopsis: r[P3]=(r[P1] && r[P2])
 81306  **
 81307  ** Take the logical AND of the values in registers P1 and P2 and
 81308  ** write the result into register P3.
 81309  **
 81310  ** If either P1 or P2 is 0 (false) then the result is 0 even if
 81311  ** the other input is NULL.  A NULL and true or two NULLs give
 81312  ** a NULL output.
 81313  */
 81314  /* Opcode: Or P1 P2 P3 * *
 81315  ** Synopsis: r[P3]=(r[P1] || r[P2])
 81316  **
 81317  ** Take the logical OR of the values in register P1 and P2 and
 81318  ** store the answer in register P3.
 81319  **
 81320  ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
 81321  ** even if the other input is NULL.  A NULL and false or two NULLs
 81322  ** give a NULL output.
 81323  */
 81324  case OP_And:              /* same as TK_AND, in1, in2, out3 */
 81325  case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
 81326    int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
 81327    int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
 81328  
 81329    pIn1 = &aMem[pOp->p1];
 81330    if( pIn1->flags & MEM_Null ){
 81331      v1 = 2;
 81332    }else{
 81333      v1 = sqlite3VdbeIntValue(pIn1)!=0;
 81334    }
 81335    pIn2 = &aMem[pOp->p2];
 81336    if( pIn2->flags & MEM_Null ){
 81337      v2 = 2;
 81338    }else{
 81339      v2 = sqlite3VdbeIntValue(pIn2)!=0;
 81340    }
 81341    if( pOp->opcode==OP_And ){
 81342      static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
 81343      v1 = and_logic[v1*3+v2];
 81344    }else{
 81345      static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
 81346      v1 = or_logic[v1*3+v2];
 81347    }
 81348    pOut = &aMem[pOp->p3];
 81349    if( v1==2 ){
 81350      MemSetTypeFlag(pOut, MEM_Null);
 81351    }else{
 81352      pOut->u.i = v1;
 81353      MemSetTypeFlag(pOut, MEM_Int);
 81354    }
 81355    break;
 81356  }
 81357  
 81358  /* Opcode: Not P1 P2 * * *
 81359  ** Synopsis: r[P2]= !r[P1]
 81360  **
 81361  ** Interpret the value in register P1 as a boolean value.  Store the
 81362  ** boolean complement in register P2.  If the value in register P1 is 
 81363  ** NULL, then a NULL is stored in P2.
 81364  */
 81365  case OP_Not: {                /* same as TK_NOT, in1, out2 */
 81366    pIn1 = &aMem[pOp->p1];
 81367    pOut = &aMem[pOp->p2];
 81368    sqlite3VdbeMemSetNull(pOut);
 81369    if( (pIn1->flags & MEM_Null)==0 ){
 81370      pOut->flags = MEM_Int;
 81371      pOut->u.i = !sqlite3VdbeIntValue(pIn1);
 81372    }
 81373    break;
 81374  }
 81375  
 81376  /* Opcode: BitNot P1 P2 * * *
 81377  ** Synopsis: r[P1]= ~r[P1]
 81378  **
 81379  ** Interpret the content of register P1 as an integer.  Store the
 81380  ** ones-complement of the P1 value into register P2.  If P1 holds
 81381  ** a NULL then store a NULL in P2.
 81382  */
 81383  case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
 81384    pIn1 = &aMem[pOp->p1];
 81385    pOut = &aMem[pOp->p2];
 81386    sqlite3VdbeMemSetNull(pOut);
 81387    if( (pIn1->flags & MEM_Null)==0 ){
 81388      pOut->flags = MEM_Int;
 81389      pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
 81390    }
 81391    break;
 81392  }
 81393  
 81394  /* Opcode: Once P1 P2 * * *
 81395  **
 81396  ** Fall through to the next instruction the first time this opcode is
 81397  ** encountered on each invocation of the byte-code program.  Jump to P2
 81398  ** on the second and all subsequent encounters during the same invocation.
 81399  **
 81400  ** Top-level programs determine first invocation by comparing the P1
 81401  ** operand against the P1 operand on the OP_Init opcode at the beginning
 81402  ** of the program.  If the P1 values differ, then fall through and make
 81403  ** the P1 of this opcode equal to the P1 of OP_Init.  If P1 values are
 81404  ** the same then take the jump.
 81405  **
 81406  ** For subprograms, there is a bitmask in the VdbeFrame that determines
 81407  ** whether or not the jump should be taken.  The bitmask is necessary
 81408  ** because the self-altering code trick does not work for recursive
 81409  ** triggers.
 81410  */
 81411  case OP_Once: {             /* jump */
 81412    u32 iAddr;                /* Address of this instruction */
 81413    assert( p->aOp[0].opcode==OP_Init );
 81414    if( p->pFrame ){
 81415      iAddr = (int)(pOp - p->aOp);
 81416      if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
 81417        VdbeBranchTaken(1, 2);
 81418        goto jump_to_p2;
 81419      }
 81420      p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
 81421    }else{
 81422      if( p->aOp[0].p1==pOp->p1 ){
 81423        VdbeBranchTaken(1, 2);
 81424        goto jump_to_p2;
 81425      }
 81426    }
 81427    VdbeBranchTaken(0, 2);
 81428    pOp->p1 = p->aOp[0].p1;
 81429    break;
 81430  }
 81431  
 81432  /* Opcode: If P1 P2 P3 * *
 81433  **
 81434  ** Jump to P2 if the value in register P1 is true.  The value
 81435  ** is considered true if it is numeric and non-zero.  If the value
 81436  ** in P1 is NULL then take the jump if and only if P3 is non-zero.
 81437  */
 81438  /* Opcode: IfNot P1 P2 P3 * *
 81439  **
 81440  ** Jump to P2 if the value in register P1 is False.  The value
 81441  ** is considered false if it has a numeric value of zero.  If the value
 81442  ** in P1 is NULL then take the jump if and only if P3 is non-zero.
 81443  */
 81444  case OP_If:                 /* jump, in1 */
 81445  case OP_IfNot: {            /* jump, in1 */
 81446    int c;
 81447    pIn1 = &aMem[pOp->p1];
 81448    if( pIn1->flags & MEM_Null ){
 81449      c = pOp->p3;
 81450    }else{
 81451  #ifdef SQLITE_OMIT_FLOATING_POINT
 81452      c = sqlite3VdbeIntValue(pIn1)!=0;
 81453  #else
 81454      c = sqlite3VdbeRealValue(pIn1)!=0.0;
 81455  #endif
 81456      if( pOp->opcode==OP_IfNot ) c = !c;
 81457    }
 81458    VdbeBranchTaken(c!=0, 2);
 81459    if( c ){
 81460      goto jump_to_p2;
 81461    }
 81462    break;
 81463  }
 81464  
 81465  /* Opcode: IsNull P1 P2 * * *
 81466  ** Synopsis: if r[P1]==NULL goto P2
 81467  **
 81468  ** Jump to P2 if the value in register P1 is NULL.
 81469  */
 81470  case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
 81471    pIn1 = &aMem[pOp->p1];
 81472    VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
 81473    if( (pIn1->flags & MEM_Null)!=0 ){
 81474      goto jump_to_p2;
 81475    }
 81476    break;
 81477  }
 81478  
 81479  /* Opcode: NotNull P1 P2 * * *
 81480  ** Synopsis: if r[P1]!=NULL goto P2
 81481  **
 81482  ** Jump to P2 if the value in register P1 is not NULL.  
 81483  */
 81484  case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
 81485    pIn1 = &aMem[pOp->p1];
 81486    VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
 81487    if( (pIn1->flags & MEM_Null)==0 ){
 81488      goto jump_to_p2;
 81489    }
 81490    break;
 81491  }
 81492  
 81493  /* Opcode: IfNullRow P1 P2 P3 * *
 81494  ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
 81495  **
 81496  ** Check the cursor P1 to see if it is currently pointing at a NULL row.
 81497  ** If it is, then set register P3 to NULL and jump immediately to P2.
 81498  ** If P1 is not on a NULL row, then fall through without making any
 81499  ** changes.
 81500  */
 81501  case OP_IfNullRow: {         /* jump */
 81502    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 81503    assert( p->apCsr[pOp->p1]!=0 );
 81504    if( p->apCsr[pOp->p1]->nullRow ){
 81505      sqlite3VdbeMemSetNull(aMem + pOp->p3);
 81506      goto jump_to_p2;
 81507    }
 81508    break;
 81509  }
 81510  
 81511  /* Opcode: Column P1 P2 P3 P4 P5
 81512  ** Synopsis: r[P3]=PX
 81513  **
 81514  ** Interpret the data that cursor P1 points to as a structure built using
 81515  ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
 81516  ** information about the format of the data.)  Extract the P2-th column
 81517  ** from this record.  If there are less that (P2+1) 
 81518  ** values in the record, extract a NULL.
 81519  **
 81520  ** The value extracted is stored in register P3.
 81521  **
 81522  ** If the record contains fewer than P2 fields, then extract a NULL.  Or,
 81523  ** if the P4 argument is a P4_MEM use the value of the P4 argument as
 81524  ** the result.
 81525  **
 81526  ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
 81527  ** then the cache of the cursor is reset prior to extracting the column.
 81528  ** The first OP_Column against a pseudo-table after the value of the content
 81529  ** register has changed should have this bit set.
 81530  **
 81531  ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
 81532  ** the result is guaranteed to only be used as the argument of a length()
 81533  ** or typeof() function, respectively.  The loading of large blobs can be
 81534  ** skipped for length() and all content loading can be skipped for typeof().
 81535  */
 81536  case OP_Column: {
 81537    int p2;            /* column number to retrieve */
 81538    VdbeCursor *pC;    /* The VDBE cursor */
 81539    BtCursor *pCrsr;   /* The BTree cursor */
 81540    u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
 81541    int len;           /* The length of the serialized data for the column */
 81542    int i;             /* Loop counter */
 81543    Mem *pDest;        /* Where to write the extracted value */
 81544    Mem sMem;          /* For storing the record being decoded */
 81545    const u8 *zData;   /* Part of the record being decoded */
 81546    const u8 *zHdr;    /* Next unparsed byte of the header */
 81547    const u8 *zEndHdr; /* Pointer to first byte after the header */
 81548    u64 offset64;      /* 64-bit offset */
 81549    u32 t;             /* A type code from the record header */
 81550    Mem *pReg;         /* PseudoTable input register */
 81551  
 81552    pC = p->apCsr[pOp->p1];
 81553    p2 = pOp->p2;
 81554  
 81555    /* If the cursor cache is stale (meaning it is not currently point at
 81556    ** the correct row) then bring it up-to-date by doing the necessary 
 81557    ** B-Tree seek. */
 81558    rc = sqlite3VdbeCursorMoveto(&pC, &p2);
 81559    if( rc ) goto abort_due_to_error;
 81560  
 81561    assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
 81562    pDest = &aMem[pOp->p3];
 81563    memAboutToChange(p, pDest);
 81564    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 81565    assert( pC!=0 );
 81566    assert( p2<pC->nField );
 81567    aOffset = pC->aOffset;
 81568    assert( pC->eCurType!=CURTYPE_VTAB );
 81569    assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
 81570    assert( pC->eCurType!=CURTYPE_SORTER );
 81571  
 81572    if( pC->cacheStatus!=p->cacheCtr ){                /*OPTIMIZATION-IF-FALSE*/
 81573      if( pC->nullRow ){
 81574        if( pC->eCurType==CURTYPE_PSEUDO ){
 81575          /* For the special case of as pseudo-cursor, the seekResult field
 81576          ** identifies the register that holds the record */
 81577          assert( pC->seekResult>0 );
 81578          pReg = &aMem[pC->seekResult];
 81579          assert( pReg->flags & MEM_Blob );
 81580          assert( memIsValid(pReg) );
 81581          pC->payloadSize = pC->szRow = pReg->n;
 81582          pC->aRow = (u8*)pReg->z;
 81583        }else{
 81584          sqlite3VdbeMemSetNull(pDest);
 81585          goto op_column_out;
 81586        }
 81587      }else{
 81588        pCrsr = pC->uc.pCursor;
 81589        assert( pC->eCurType==CURTYPE_BTREE );
 81590        assert( pCrsr );
 81591        assert( sqlite3BtreeCursorIsValid(pCrsr) );
 81592        pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
 81593        pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
 81594        assert( pC->szRow<=pC->payloadSize );
 81595        assert( pC->szRow<=65536 );  /* Maximum page size is 64KiB */
 81596        if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
 81597          goto too_big;
 81598        }
 81599      }
 81600      pC->cacheStatus = p->cacheCtr;
 81601      pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]);
 81602      pC->nHdrParsed = 0;
 81603  
 81604  
 81605      if( pC->szRow<aOffset[0] ){      /*OPTIMIZATION-IF-FALSE*/
 81606        /* pC->aRow does not have to hold the entire row, but it does at least
 81607        ** need to cover the header of the record.  If pC->aRow does not contain
 81608        ** the complete header, then set it to zero, forcing the header to be
 81609        ** dynamically allocated. */
 81610        pC->aRow = 0;
 81611        pC->szRow = 0;
 81612  
 81613        /* Make sure a corrupt database has not given us an oversize header.
 81614        ** Do this now to avoid an oversize memory allocation.
 81615        **
 81616        ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
 81617        ** types use so much data space that there can only be 4096 and 32 of
 81618        ** them, respectively.  So the maximum header length results from a
 81619        ** 3-byte type for each of the maximum of 32768 columns plus three
 81620        ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
 81621        */
 81622        if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
 81623          goto op_column_corrupt;
 81624        }
 81625      }else{
 81626        /* This is an optimization.  By skipping over the first few tests
 81627        ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
 81628        ** measurable performance gain.
 81629        **
 81630        ** This branch is taken even if aOffset[0]==0.  Such a record is never
 81631        ** generated by SQLite, and could be considered corruption, but we
 81632        ** accept it for historical reasons.  When aOffset[0]==0, the code this
 81633        ** branch jumps to reads past the end of the record, but never more
 81634        ** than a few bytes.  Even if the record occurs at the end of the page
 81635        ** content area, the "page header" comes after the page content and so
 81636        ** this overread is harmless.  Similar overreads can occur for a corrupt
 81637        ** database file.
 81638        */
 81639        zData = pC->aRow;
 81640        assert( pC->nHdrParsed<=p2 );         /* Conditional skipped */
 81641        testcase( aOffset[0]==0 );
 81642        goto op_column_read_header;
 81643      }
 81644    }
 81645  
 81646    /* Make sure at least the first p2+1 entries of the header have been
 81647    ** parsed and valid information is in aOffset[] and pC->aType[].
 81648    */
 81649    if( pC->nHdrParsed<=p2 ){
 81650      /* If there is more header available for parsing in the record, try
 81651      ** to extract additional fields up through the p2+1-th field 
 81652      */
 81653      if( pC->iHdrOffset<aOffset[0] ){
 81654        /* Make sure zData points to enough of the record to cover the header. */
 81655        if( pC->aRow==0 ){
 81656          memset(&sMem, 0, sizeof(sMem));
 81657          rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem);
 81658          if( rc!=SQLITE_OK ) goto abort_due_to_error;
 81659          zData = (u8*)sMem.z;
 81660        }else{
 81661          zData = pC->aRow;
 81662        }
 81663    
 81664        /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
 81665      op_column_read_header:
 81666        i = pC->nHdrParsed;
 81667        offset64 = aOffset[i];
 81668        zHdr = zData + pC->iHdrOffset;
 81669        zEndHdr = zData + aOffset[0];
 81670        testcase( zHdr>=zEndHdr );
 81671        do{
 81672          if( (t = zHdr[0])<0x80 ){
 81673            zHdr++;
 81674            offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
 81675          }else{
 81676            zHdr += sqlite3GetVarint32(zHdr, &t);
 81677            offset64 += sqlite3VdbeSerialTypeLen(t);
 81678          }
 81679          pC->aType[i++] = t;
 81680          aOffset[i] = (u32)(offset64 & 0xffffffff);
 81681        }while( i<=p2 && zHdr<zEndHdr );
 81682  
 81683        /* The record is corrupt if any of the following are true:
 81684        ** (1) the bytes of the header extend past the declared header size
 81685        ** (2) the entire header was used but not all data was used
 81686        ** (3) the end of the data extends beyond the end of the record.
 81687        */
 81688        if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
 81689         || (offset64 > pC->payloadSize)
 81690        ){
 81691          if( aOffset[0]==0 ){
 81692            i = 0;
 81693            zHdr = zEndHdr;
 81694          }else{
 81695            if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
 81696            goto op_column_corrupt;
 81697          }
 81698        }
 81699  
 81700        pC->nHdrParsed = i;
 81701        pC->iHdrOffset = (u32)(zHdr - zData);
 81702        if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
 81703      }else{
 81704        t = 0;
 81705      }
 81706  
 81707      /* If after trying to extract new entries from the header, nHdrParsed is
 81708      ** still not up to p2, that means that the record has fewer than p2
 81709      ** columns.  So the result will be either the default value or a NULL.
 81710      */
 81711      if( pC->nHdrParsed<=p2 ){
 81712        if( pOp->p4type==P4_MEM ){
 81713          sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
 81714        }else{
 81715          sqlite3VdbeMemSetNull(pDest);
 81716        }
 81717        goto op_column_out;
 81718      }
 81719    }else{
 81720      t = pC->aType[p2];
 81721    }
 81722  
 81723    /* Extract the content for the p2+1-th column.  Control can only
 81724    ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
 81725    ** all valid.
 81726    */
 81727    assert( p2<pC->nHdrParsed );
 81728    assert( rc==SQLITE_OK );
 81729    assert( sqlite3VdbeCheckMemInvariants(pDest) );
 81730    if( VdbeMemDynamic(pDest) ){
 81731      sqlite3VdbeMemSetNull(pDest);
 81732    }
 81733    assert( t==pC->aType[p2] );
 81734    if( pC->szRow>=aOffset[p2+1] ){
 81735      /* This is the common case where the desired content fits on the original
 81736      ** page - where the content is not on an overflow page */
 81737      zData = pC->aRow + aOffset[p2];
 81738      if( t<12 ){
 81739        sqlite3VdbeSerialGet(zData, t, pDest);
 81740      }else{
 81741        /* If the column value is a string, we need a persistent value, not
 81742        ** a MEM_Ephem value.  This branch is a fast short-cut that is equivalent
 81743        ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
 81744        */
 81745        static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
 81746        pDest->n = len = (t-12)/2;
 81747        pDest->enc = encoding;
 81748        if( pDest->szMalloc < len+2 ){
 81749          pDest->flags = MEM_Null;
 81750          if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
 81751        }else{
 81752          pDest->z = pDest->zMalloc;
 81753        }
 81754        memcpy(pDest->z, zData, len);
 81755        pDest->z[len] = 0;
 81756        pDest->z[len+1] = 0;
 81757        pDest->flags = aFlag[t&1];
 81758      }
 81759    }else{
 81760      pDest->enc = encoding;
 81761      /* This branch happens only when content is on overflow pages */
 81762      if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
 81763            && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
 81764       || (len = sqlite3VdbeSerialTypeLen(t))==0
 81765      ){
 81766        /* Content is irrelevant for
 81767        **    1. the typeof() function,
 81768        **    2. the length(X) function if X is a blob, and
 81769        **    3. if the content length is zero.
 81770        ** So we might as well use bogus content rather than reading
 81771        ** content from disk. 
 81772        **
 81773        ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
 81774        ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
 81775        ** read up to 16. So 16 bytes of bogus content is supplied.
 81776        */
 81777        static u8 aZero[16];  /* This is the bogus content */
 81778        sqlite3VdbeSerialGet(aZero, t, pDest);
 81779      }else{
 81780        rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
 81781        if( rc!=SQLITE_OK ) goto abort_due_to_error;
 81782        sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
 81783        pDest->flags &= ~MEM_Ephem;
 81784      }
 81785    }
 81786  
 81787  op_column_out:
 81788    UPDATE_MAX_BLOBSIZE(pDest);
 81789    REGISTER_TRACE(pOp->p3, pDest);
 81790    break;
 81791  
 81792  op_column_corrupt:
 81793    if( aOp[0].p3>0 ){
 81794      pOp = &aOp[aOp[0].p3-1];
 81795      break;
 81796    }else{
 81797      rc = SQLITE_CORRUPT_BKPT;
 81798      goto abort_due_to_error;
 81799    }
 81800  }
 81801  
 81802  /* Opcode: Affinity P1 P2 * P4 *
 81803  ** Synopsis: affinity(r[P1@P2])
 81804  **
 81805  ** Apply affinities to a range of P2 registers starting with P1.
 81806  **
 81807  ** P4 is a string that is P2 characters long. The N-th character of the
 81808  ** string indicates the column affinity that should be used for the N-th
 81809  ** memory cell in the range.
 81810  */
 81811  case OP_Affinity: {
 81812    const char *zAffinity;   /* The affinity to be applied */
 81813  
 81814    zAffinity = pOp->p4.z;
 81815    assert( zAffinity!=0 );
 81816    assert( pOp->p2>0 );
 81817    assert( zAffinity[pOp->p2]==0 );
 81818    pIn1 = &aMem[pOp->p1];
 81819    do{
 81820      assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
 81821      assert( memIsValid(pIn1) );
 81822      applyAffinity(pIn1, *(zAffinity++), encoding);
 81823      pIn1++;
 81824    }while( zAffinity[0] );
 81825    break;
 81826  }
 81827  
 81828  /* Opcode: MakeRecord P1 P2 P3 P4 *
 81829  ** Synopsis: r[P3]=mkrec(r[P1@P2])
 81830  **
 81831  ** Convert P2 registers beginning with P1 into the [record format]
 81832  ** use as a data record in a database table or as a key
 81833  ** in an index.  The OP_Column opcode can decode the record later.
 81834  **
 81835  ** P4 may be a string that is P2 characters long.  The N-th character of the
 81836  ** string indicates the column affinity that should be used for the N-th
 81837  ** field of the index key.
 81838  **
 81839  ** The mapping from character to affinity is given by the SQLITE_AFF_
 81840  ** macros defined in sqliteInt.h.
 81841  **
 81842  ** If P4 is NULL then all index fields have the affinity BLOB.
 81843  */
 81844  case OP_MakeRecord: {
 81845    u8 *zNewRecord;        /* A buffer to hold the data for the new record */
 81846    Mem *pRec;             /* The new record */
 81847    u64 nData;             /* Number of bytes of data space */
 81848    int nHdr;              /* Number of bytes of header space */
 81849    i64 nByte;             /* Data space required for this record */
 81850    i64 nZero;             /* Number of zero bytes at the end of the record */
 81851    int nVarint;           /* Number of bytes in a varint */
 81852    u32 serial_type;       /* Type field */
 81853    Mem *pData0;           /* First field to be combined into the record */
 81854    Mem *pLast;            /* Last field of the record */
 81855    int nField;            /* Number of fields in the record */
 81856    char *zAffinity;       /* The affinity string for the record */
 81857    int file_format;       /* File format to use for encoding */
 81858    int i;                 /* Space used in zNewRecord[] header */
 81859    int j;                 /* Space used in zNewRecord[] content */
 81860    u32 len;               /* Length of a field */
 81861  
 81862    /* Assuming the record contains N fields, the record format looks
 81863    ** like this:
 81864    **
 81865    ** ------------------------------------------------------------------------
 81866    ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | 
 81867    ** ------------------------------------------------------------------------
 81868    **
 81869    ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
 81870    ** and so forth.
 81871    **
 81872    ** Each type field is a varint representing the serial type of the 
 81873    ** corresponding data element (see sqlite3VdbeSerialType()). The
 81874    ** hdr-size field is also a varint which is the offset from the beginning
 81875    ** of the record to data0.
 81876    */
 81877    nData = 0;         /* Number of bytes of data space */
 81878    nHdr = 0;          /* Number of bytes of header space */
 81879    nZero = 0;         /* Number of zero bytes at the end of the record */
 81880    nField = pOp->p1;
 81881    zAffinity = pOp->p4.z;
 81882    assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
 81883    pData0 = &aMem[nField];
 81884    nField = pOp->p2;
 81885    pLast = &pData0[nField-1];
 81886    file_format = p->minWriteFileFormat;
 81887  
 81888    /* Identify the output register */
 81889    assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
 81890    pOut = &aMem[pOp->p3];
 81891    memAboutToChange(p, pOut);
 81892  
 81893    /* Apply the requested affinity to all inputs
 81894    */
 81895    assert( pData0<=pLast );
 81896    if( zAffinity ){
 81897      pRec = pData0;
 81898      do{
 81899        applyAffinity(pRec++, *(zAffinity++), encoding);
 81900        assert( zAffinity[0]==0 || pRec<=pLast );
 81901      }while( zAffinity[0] );
 81902    }
 81903  
 81904  #ifdef SQLITE_ENABLE_NULL_TRIM
 81905    /* NULLs can be safely trimmed from the end of the record, as long as
 81906    ** as the schema format is 2 or more and none of the omitted columns
 81907    ** have a non-NULL default value.  Also, the record must be left with
 81908    ** at least one field.  If P5>0 then it will be one more than the
 81909    ** index of the right-most column with a non-NULL default value */
 81910    if( pOp->p5 ){
 81911      while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
 81912        pLast--;
 81913        nField--;
 81914      }
 81915    }
 81916  #endif
 81917  
 81918    /* Loop through the elements that will make up the record to figure
 81919    ** out how much space is required for the new record.
 81920    */
 81921    pRec = pLast;
 81922    do{
 81923      assert( memIsValid(pRec) );
 81924      pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
 81925      if( pRec->flags & MEM_Zero ){
 81926        if( nData ){
 81927          if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
 81928        }else{
 81929          nZero += pRec->u.nZero;
 81930          len -= pRec->u.nZero;
 81931        }
 81932      }
 81933      nData += len;
 81934      testcase( serial_type==127 );
 81935      testcase( serial_type==128 );
 81936      nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
 81937      if( pRec==pData0 ) break;
 81938      pRec--;
 81939    }while(1);
 81940  
 81941    /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
 81942    ** which determines the total number of bytes in the header. The varint
 81943    ** value is the size of the header in bytes including the size varint
 81944    ** itself. */
 81945    testcase( nHdr==126 );
 81946    testcase( nHdr==127 );
 81947    if( nHdr<=126 ){
 81948      /* The common case */
 81949      nHdr += 1;
 81950    }else{
 81951      /* Rare case of a really large header */
 81952      nVarint = sqlite3VarintLen(nHdr);
 81953      nHdr += nVarint;
 81954      if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
 81955    }
 81956    nByte = nHdr+nData;
 81957    if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
 81958      goto too_big;
 81959    }
 81960  
 81961    /* Make sure the output register has a buffer large enough to store 
 81962    ** the new record. The output register (pOp->p3) is not allowed to
 81963    ** be one of the input registers (because the following call to
 81964    ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
 81965    */
 81966    if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
 81967      goto no_mem;
 81968    }
 81969    zNewRecord = (u8 *)pOut->z;
 81970  
 81971    /* Write the record */
 81972    i = putVarint32(zNewRecord, nHdr);
 81973    j = nHdr;
 81974    assert( pData0<=pLast );
 81975    pRec = pData0;
 81976    do{
 81977      serial_type = pRec->uTemp;
 81978      /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
 81979      ** additional varints, one per column. */
 81980      i += putVarint32(&zNewRecord[i], serial_type);            /* serial type */
 81981      /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
 81982      ** immediately follow the header. */
 81983      j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
 81984    }while( (++pRec)<=pLast );
 81985    assert( i==nHdr );
 81986    assert( j==nByte );
 81987  
 81988    assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
 81989    pOut->n = (int)nByte;
 81990    pOut->flags = MEM_Blob;
 81991    if( nZero ){
 81992      pOut->u.nZero = nZero;
 81993      pOut->flags |= MEM_Zero;
 81994    }
 81995    REGISTER_TRACE(pOp->p3, pOut);
 81996    UPDATE_MAX_BLOBSIZE(pOut);
 81997    break;
 81998  }
 81999  
 82000  /* Opcode: Count P1 P2 * * *
 82001  ** Synopsis: r[P2]=count()
 82002  **
 82003  ** Store the number of entries (an integer value) in the table or index 
 82004  ** opened by cursor P1 in register P2
 82005  */
 82006  #ifndef SQLITE_OMIT_BTREECOUNT
 82007  case OP_Count: {         /* out2 */
 82008    i64 nEntry;
 82009    BtCursor *pCrsr;
 82010  
 82011    assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
 82012    pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
 82013    assert( pCrsr );
 82014    nEntry = 0;  /* Not needed.  Only used to silence a warning. */
 82015    rc = sqlite3BtreeCount(pCrsr, &nEntry);
 82016    if( rc ) goto abort_due_to_error;
 82017    pOut = out2Prerelease(p, pOp);
 82018    pOut->u.i = nEntry;
 82019    break;
 82020  }
 82021  #endif
 82022  
 82023  /* Opcode: Savepoint P1 * * P4 *
 82024  **
 82025  ** Open, release or rollback the savepoint named by parameter P4, depending
 82026  ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
 82027  ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
 82028  */
 82029  case OP_Savepoint: {
 82030    int p1;                         /* Value of P1 operand */
 82031    char *zName;                    /* Name of savepoint */
 82032    int nName;
 82033    Savepoint *pNew;
 82034    Savepoint *pSavepoint;
 82035    Savepoint *pTmp;
 82036    int iSavepoint;
 82037    int ii;
 82038  
 82039    p1 = pOp->p1;
 82040    zName = pOp->p4.z;
 82041  
 82042    /* Assert that the p1 parameter is valid. Also that if there is no open
 82043    ** transaction, then there cannot be any savepoints. 
 82044    */
 82045    assert( db->pSavepoint==0 || db->autoCommit==0 );
 82046    assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
 82047    assert( db->pSavepoint || db->isTransactionSavepoint==0 );
 82048    assert( checkSavepointCount(db) );
 82049    assert( p->bIsReader );
 82050  
 82051    if( p1==SAVEPOINT_BEGIN ){
 82052      if( db->nVdbeWrite>0 ){
 82053        /* A new savepoint cannot be created if there are active write 
 82054        ** statements (i.e. open read/write incremental blob handles).
 82055        */
 82056        sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
 82057        rc = SQLITE_BUSY;
 82058      }else{
 82059        nName = sqlite3Strlen30(zName);
 82060  
 82061  #ifndef SQLITE_OMIT_VIRTUALTABLE
 82062        /* This call is Ok even if this savepoint is actually a transaction
 82063        ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
 82064        ** If this is a transaction savepoint being opened, it is guaranteed
 82065        ** that the db->aVTrans[] array is empty.  */
 82066        assert( db->autoCommit==0 || db->nVTrans==0 );
 82067        rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
 82068                                  db->nStatement+db->nSavepoint);
 82069        if( rc!=SQLITE_OK ) goto abort_due_to_error;
 82070  #endif
 82071  
 82072        /* Create a new savepoint structure. */
 82073        pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
 82074        if( pNew ){
 82075          pNew->zName = (char *)&pNew[1];
 82076          memcpy(pNew->zName, zName, nName+1);
 82077      
 82078          /* If there is no open transaction, then mark this as a special
 82079          ** "transaction savepoint". */
 82080          if( db->autoCommit ){
 82081            db->autoCommit = 0;
 82082            db->isTransactionSavepoint = 1;
 82083          }else{
 82084            db->nSavepoint++;
 82085          }
 82086  
 82087          /* Link the new savepoint into the database handle's list. */
 82088          pNew->pNext = db->pSavepoint;
 82089          db->pSavepoint = pNew;
 82090          pNew->nDeferredCons = db->nDeferredCons;
 82091          pNew->nDeferredImmCons = db->nDeferredImmCons;
 82092        }
 82093      }
 82094    }else{
 82095      iSavepoint = 0;
 82096  
 82097      /* Find the named savepoint. If there is no such savepoint, then an
 82098      ** an error is returned to the user.  */
 82099      for(
 82100        pSavepoint = db->pSavepoint; 
 82101        pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
 82102        pSavepoint = pSavepoint->pNext
 82103      ){
 82104        iSavepoint++;
 82105      }
 82106      if( !pSavepoint ){
 82107        sqlite3VdbeError(p, "no such savepoint: %s", zName);
 82108        rc = SQLITE_ERROR;
 82109      }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
 82110        /* It is not possible to release (commit) a savepoint if there are 
 82111        ** active write statements.
 82112        */
 82113        sqlite3VdbeError(p, "cannot release savepoint - "
 82114                            "SQL statements in progress");
 82115        rc = SQLITE_BUSY;
 82116      }else{
 82117  
 82118        /* Determine whether or not this is a transaction savepoint. If so,
 82119        ** and this is a RELEASE command, then the current transaction 
 82120        ** is committed. 
 82121        */
 82122        int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
 82123        if( isTransaction && p1==SAVEPOINT_RELEASE ){
 82124          if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
 82125            goto vdbe_return;
 82126          }
 82127          db->autoCommit = 1;
 82128          if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
 82129            p->pc = (int)(pOp - aOp);
 82130            db->autoCommit = 0;
 82131            p->rc = rc = SQLITE_BUSY;
 82132            goto vdbe_return;
 82133          }
 82134          db->isTransactionSavepoint = 0;
 82135          rc = p->rc;
 82136        }else{
 82137          int isSchemaChange;
 82138          iSavepoint = db->nSavepoint - iSavepoint - 1;
 82139          if( p1==SAVEPOINT_ROLLBACK ){
 82140            isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
 82141            for(ii=0; ii<db->nDb; ii++){
 82142              rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
 82143                                         SQLITE_ABORT_ROLLBACK,
 82144                                         isSchemaChange==0);
 82145              if( rc!=SQLITE_OK ) goto abort_due_to_error;
 82146            }
 82147          }else{
 82148            isSchemaChange = 0;
 82149          }
 82150          for(ii=0; ii<db->nDb; ii++){
 82151            rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
 82152            if( rc!=SQLITE_OK ){
 82153              goto abort_due_to_error;
 82154            }
 82155          }
 82156          if( isSchemaChange ){
 82157            sqlite3ExpirePreparedStatements(db);
 82158            sqlite3ResetAllSchemasOfConnection(db);
 82159            db->mDbFlags |= DBFLAG_SchemaChange;
 82160          }
 82161        }
 82162    
 82163        /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all 
 82164        ** savepoints nested inside of the savepoint being operated on. */
 82165        while( db->pSavepoint!=pSavepoint ){
 82166          pTmp = db->pSavepoint;
 82167          db->pSavepoint = pTmp->pNext;
 82168          sqlite3DbFree(db, pTmp);
 82169          db->nSavepoint--;
 82170        }
 82171  
 82172        /* If it is a RELEASE, then destroy the savepoint being operated on 
 82173        ** too. If it is a ROLLBACK TO, then set the number of deferred 
 82174        ** constraint violations present in the database to the value stored
 82175        ** when the savepoint was created.  */
 82176        if( p1==SAVEPOINT_RELEASE ){
 82177          assert( pSavepoint==db->pSavepoint );
 82178          db->pSavepoint = pSavepoint->pNext;
 82179          sqlite3DbFree(db, pSavepoint);
 82180          if( !isTransaction ){
 82181            db->nSavepoint--;
 82182          }
 82183        }else{
 82184          db->nDeferredCons = pSavepoint->nDeferredCons;
 82185          db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
 82186        }
 82187  
 82188        if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
 82189          rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
 82190          if( rc!=SQLITE_OK ) goto abort_due_to_error;
 82191        }
 82192      }
 82193    }
 82194    if( rc ) goto abort_due_to_error;
 82195  
 82196    break;
 82197  }
 82198  
 82199  /* Opcode: AutoCommit P1 P2 * * *
 82200  **
 82201  ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
 82202  ** back any currently active btree transactions. If there are any active
 82203  ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
 82204  ** there are active writing VMs or active VMs that use shared cache.
 82205  **
 82206  ** This instruction causes the VM to halt.
 82207  */
 82208  case OP_AutoCommit: {
 82209    int desiredAutoCommit;
 82210    int iRollback;
 82211  
 82212    desiredAutoCommit = pOp->p1;
 82213    iRollback = pOp->p2;
 82214    assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
 82215    assert( desiredAutoCommit==1 || iRollback==0 );
 82216    assert( db->nVdbeActive>0 );  /* At least this one VM is active */
 82217    assert( p->bIsReader );
 82218  
 82219    if( desiredAutoCommit!=db->autoCommit ){
 82220      if( iRollback ){
 82221        assert( desiredAutoCommit==1 );
 82222        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
 82223        db->autoCommit = 1;
 82224      }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
 82225        /* If this instruction implements a COMMIT and other VMs are writing
 82226        ** return an error indicating that the other VMs must complete first. 
 82227        */
 82228        sqlite3VdbeError(p, "cannot commit transaction - "
 82229                            "SQL statements in progress");
 82230        rc = SQLITE_BUSY;
 82231        goto abort_due_to_error;
 82232      }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
 82233        goto vdbe_return;
 82234      }else{
 82235        db->autoCommit = (u8)desiredAutoCommit;
 82236      }
 82237      if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
 82238        p->pc = (int)(pOp - aOp);
 82239        db->autoCommit = (u8)(1-desiredAutoCommit);
 82240        p->rc = rc = SQLITE_BUSY;
 82241        goto vdbe_return;
 82242      }
 82243      assert( db->nStatement==0 );
 82244      sqlite3CloseSavepoints(db);
 82245      if( p->rc==SQLITE_OK ){
 82246        rc = SQLITE_DONE;
 82247      }else{
 82248        rc = SQLITE_ERROR;
 82249      }
 82250      goto vdbe_return;
 82251    }else{
 82252      sqlite3VdbeError(p,
 82253          (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
 82254          (iRollback)?"cannot rollback - no transaction is active":
 82255                     "cannot commit - no transaction is active"));
 82256           
 82257      rc = SQLITE_ERROR;
 82258      goto abort_due_to_error;
 82259    }
 82260    break;
 82261  }
 82262  
 82263  /* Opcode: Transaction P1 P2 P3 P4 P5
 82264  **
 82265  ** Begin a transaction on database P1 if a transaction is not already
 82266  ** active.
 82267  ** If P2 is non-zero, then a write-transaction is started, or if a 
 82268  ** read-transaction is already active, it is upgraded to a write-transaction.
 82269  ** If P2 is zero, then a read-transaction is started.
 82270  **
 82271  ** P1 is the index of the database file on which the transaction is
 82272  ** started.  Index 0 is the main database file and index 1 is the
 82273  ** file used for temporary tables.  Indices of 2 or more are used for
 82274  ** attached databases.
 82275  **
 82276  ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
 82277  ** true (this flag is set if the Vdbe may modify more than one row and may
 82278  ** throw an ABORT exception), a statement transaction may also be opened.
 82279  ** More specifically, a statement transaction is opened iff the database
 82280  ** connection is currently not in autocommit mode, or if there are other
 82281  ** active statements. A statement transaction allows the changes made by this
 82282  ** VDBE to be rolled back after an error without having to roll back the
 82283  ** entire transaction. If no error is encountered, the statement transaction
 82284  ** will automatically commit when the VDBE halts.
 82285  **
 82286  ** If P5!=0 then this opcode also checks the schema cookie against P3
 82287  ** and the schema generation counter against P4.
 82288  ** The cookie changes its value whenever the database schema changes.
 82289  ** This operation is used to detect when that the cookie has changed
 82290  ** and that the current process needs to reread the schema.  If the schema
 82291  ** cookie in P3 differs from the schema cookie in the database header or
 82292  ** if the schema generation counter in P4 differs from the current
 82293  ** generation counter, then an SQLITE_SCHEMA error is raised and execution
 82294  ** halts.  The sqlite3_step() wrapper function might then reprepare the
 82295  ** statement and rerun it from the beginning.
 82296  */
 82297  case OP_Transaction: {
 82298    Btree *pBt;
 82299    int iMeta;
 82300    int iGen;
 82301  
 82302    assert( p->bIsReader );
 82303    assert( p->readOnly==0 || pOp->p2==0 );
 82304    assert( pOp->p1>=0 && pOp->p1<db->nDb );
 82305    assert( DbMaskTest(p->btreeMask, pOp->p1) );
 82306    if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
 82307      rc = SQLITE_READONLY;
 82308      goto abort_due_to_error;
 82309    }
 82310    pBt = db->aDb[pOp->p1].pBt;
 82311  
 82312    if( pBt ){
 82313      rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
 82314      testcase( rc==SQLITE_BUSY_SNAPSHOT );
 82315      testcase( rc==SQLITE_BUSY_RECOVERY );
 82316      if( rc!=SQLITE_OK ){
 82317        if( (rc&0xff)==SQLITE_BUSY ){
 82318          p->pc = (int)(pOp - aOp);
 82319          p->rc = rc;
 82320          goto vdbe_return;
 82321        }
 82322        goto abort_due_to_error;
 82323      }
 82324  
 82325      if( pOp->p2 && p->usesStmtJournal 
 82326       && (db->autoCommit==0 || db->nVdbeRead>1) 
 82327      ){
 82328        assert( sqlite3BtreeIsInTrans(pBt) );
 82329        if( p->iStatement==0 ){
 82330          assert( db->nStatement>=0 && db->nSavepoint>=0 );
 82331          db->nStatement++; 
 82332          p->iStatement = db->nSavepoint + db->nStatement;
 82333        }
 82334  
 82335        rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
 82336        if( rc==SQLITE_OK ){
 82337          rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
 82338        }
 82339  
 82340        /* Store the current value of the database handles deferred constraint
 82341        ** counter. If the statement transaction needs to be rolled back,
 82342        ** the value of this counter needs to be restored too.  */
 82343        p->nStmtDefCons = db->nDeferredCons;
 82344        p->nStmtDefImmCons = db->nDeferredImmCons;
 82345      }
 82346  
 82347      /* Gather the schema version number for checking:
 82348      ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
 82349      ** version is checked to ensure that the schema has not changed since the
 82350      ** SQL statement was prepared.
 82351      */
 82352      sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
 82353      iGen = db->aDb[pOp->p1].pSchema->iGeneration;
 82354    }else{
 82355      iGen = iMeta = 0;
 82356    }
 82357    assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
 82358    if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
 82359      sqlite3DbFree(db, p->zErrMsg);
 82360      p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
 82361      /* If the schema-cookie from the database file matches the cookie 
 82362      ** stored with the in-memory representation of the schema, do
 82363      ** not reload the schema from the database file.
 82364      **
 82365      ** If virtual-tables are in use, this is not just an optimization.
 82366      ** Often, v-tables store their data in other SQLite tables, which
 82367      ** are queried from within xNext() and other v-table methods using
 82368      ** prepared queries. If such a query is out-of-date, we do not want to
 82369      ** discard the database schema, as the user code implementing the
 82370      ** v-table would have to be ready for the sqlite3_vtab structure itself
 82371      ** to be invalidated whenever sqlite3_step() is called from within 
 82372      ** a v-table method.
 82373      */
 82374      if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
 82375        sqlite3ResetOneSchema(db, pOp->p1);
 82376      }
 82377      p->expired = 1;
 82378      rc = SQLITE_SCHEMA;
 82379    }
 82380    if( rc ) goto abort_due_to_error;
 82381    break;
 82382  }
 82383  
 82384  /* Opcode: ReadCookie P1 P2 P3 * *
 82385  **
 82386  ** Read cookie number P3 from database P1 and write it into register P2.
 82387  ** P3==1 is the schema version.  P3==2 is the database format.
 82388  ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
 82389  ** the main database file and P1==1 is the database file used to store
 82390  ** temporary tables.
 82391  **
 82392  ** There must be a read-lock on the database (either a transaction
 82393  ** must be started or there must be an open cursor) before
 82394  ** executing this instruction.
 82395  */
 82396  case OP_ReadCookie: {               /* out2 */
 82397    int iMeta;
 82398    int iDb;
 82399    int iCookie;
 82400  
 82401    assert( p->bIsReader );
 82402    iDb = pOp->p1;
 82403    iCookie = pOp->p3;
 82404    assert( pOp->p3<SQLITE_N_BTREE_META );
 82405    assert( iDb>=0 && iDb<db->nDb );
 82406    assert( db->aDb[iDb].pBt!=0 );
 82407    assert( DbMaskTest(p->btreeMask, iDb) );
 82408  
 82409    sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
 82410    pOut = out2Prerelease(p, pOp);
 82411    pOut->u.i = iMeta;
 82412    break;
 82413  }
 82414  
 82415  /* Opcode: SetCookie P1 P2 P3 * *
 82416  **
 82417  ** Write the integer value P3 into cookie number P2 of database P1.
 82418  ** P2==1 is the schema version.  P2==2 is the database format.
 82419  ** P2==3 is the recommended pager cache 
 82420  ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
 82421  ** database file used to store temporary tables.
 82422  **
 82423  ** A transaction must be started before executing this opcode.
 82424  */
 82425  case OP_SetCookie: {
 82426    Db *pDb;
 82427    assert( pOp->p2<SQLITE_N_BTREE_META );
 82428    assert( pOp->p1>=0 && pOp->p1<db->nDb );
 82429    assert( DbMaskTest(p->btreeMask, pOp->p1) );
 82430    assert( p->readOnly==0 );
 82431    pDb = &db->aDb[pOp->p1];
 82432    assert( pDb->pBt!=0 );
 82433    assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
 82434    /* See note about index shifting on OP_ReadCookie */
 82435    rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
 82436    if( pOp->p2==BTREE_SCHEMA_VERSION ){
 82437      /* When the schema cookie changes, record the new cookie internally */
 82438      pDb->pSchema->schema_cookie = pOp->p3;
 82439      db->mDbFlags |= DBFLAG_SchemaChange;
 82440    }else if( pOp->p2==BTREE_FILE_FORMAT ){
 82441      /* Record changes in the file format */
 82442      pDb->pSchema->file_format = pOp->p3;
 82443    }
 82444    if( pOp->p1==1 ){
 82445      /* Invalidate all prepared statements whenever the TEMP database
 82446      ** schema is changed.  Ticket #1644 */
 82447      sqlite3ExpirePreparedStatements(db);
 82448      p->expired = 0;
 82449    }
 82450    if( rc ) goto abort_due_to_error;
 82451    break;
 82452  }
 82453  
 82454  /* Opcode: OpenRead P1 P2 P3 P4 P5
 82455  ** Synopsis: root=P2 iDb=P3
 82456  **
 82457  ** Open a read-only cursor for the database table whose root page is
 82458  ** P2 in a database file.  The database file is determined by P3. 
 82459  ** P3==0 means the main database, P3==1 means the database used for 
 82460  ** temporary tables, and P3>1 means used the corresponding attached
 82461  ** database.  Give the new cursor an identifier of P1.  The P1
 82462  ** values need not be contiguous but all P1 values should be small integers.
 82463  ** It is an error for P1 to be negative.
 82464  **
 82465  ** If P5!=0 then use the content of register P2 as the root page, not
 82466  ** the value of P2 itself.
 82467  **
 82468  ** There will be a read lock on the database whenever there is an
 82469  ** open cursor.  If the database was unlocked prior to this instruction
 82470  ** then a read lock is acquired as part of this instruction.  A read
 82471  ** lock allows other processes to read the database but prohibits
 82472  ** any other process from modifying the database.  The read lock is
 82473  ** released when all cursors are closed.  If this instruction attempts
 82474  ** to get a read lock but fails, the script terminates with an
 82475  ** SQLITE_BUSY error code.
 82476  **
 82477  ** The P4 value may be either an integer (P4_INT32) or a pointer to
 82478  ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
 82479  ** structure, then said structure defines the content and collating 
 82480  ** sequence of the index being opened. Otherwise, if P4 is an integer 
 82481  ** value, it is set to the number of columns in the table.
 82482  **
 82483  ** See also: OpenWrite, ReopenIdx
 82484  */
 82485  /* Opcode: ReopenIdx P1 P2 P3 P4 P5
 82486  ** Synopsis: root=P2 iDb=P3
 82487  **
 82488  ** The ReopenIdx opcode works exactly like ReadOpen except that it first
 82489  ** checks to see if the cursor on P1 is already open with a root page
 82490  ** number of P2 and if it is this opcode becomes a no-op.  In other words,
 82491  ** if the cursor is already open, do not reopen it.
 82492  **
 82493  ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
 82494  ** a P4_KEYINFO object.  Furthermore, the P3 value must be the same as
 82495  ** every other ReopenIdx or OpenRead for the same cursor number.
 82496  **
 82497  ** See the OpenRead opcode documentation for additional information.
 82498  */
 82499  /* Opcode: OpenWrite P1 P2 P3 P4 P5
 82500  ** Synopsis: root=P2 iDb=P3
 82501  **
 82502  ** Open a read/write cursor named P1 on the table or index whose root
 82503  ** page is P2.  Or if P5!=0 use the content of register P2 to find the
 82504  ** root page.
 82505  **
 82506  ** The P4 value may be either an integer (P4_INT32) or a pointer to
 82507  ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
 82508  ** structure, then said structure defines the content and collating 
 82509  ** sequence of the index being opened. Otherwise, if P4 is an integer 
 82510  ** value, it is set to the number of columns in the table, or to the
 82511  ** largest index of any column of the table that is actually used.
 82512  **
 82513  ** This instruction works just like OpenRead except that it opens the cursor
 82514  ** in read/write mode.  For a given table, there can be one or more read-only
 82515  ** cursors or a single read/write cursor but not both.
 82516  **
 82517  ** See also OpenRead.
 82518  */
 82519  case OP_ReopenIdx: {
 82520    int nField;
 82521    KeyInfo *pKeyInfo;
 82522    int p2;
 82523    int iDb;
 82524    int wrFlag;
 82525    Btree *pX;
 82526    VdbeCursor *pCur;
 82527    Db *pDb;
 82528  
 82529    assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
 82530    assert( pOp->p4type==P4_KEYINFO );
 82531    pCur = p->apCsr[pOp->p1];
 82532    if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
 82533      assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
 82534      goto open_cursor_set_hints;
 82535    }
 82536    /* If the cursor is not currently open or is open on a different
 82537    ** index, then fall through into OP_OpenRead to force a reopen */
 82538  case OP_OpenRead:
 82539  case OP_OpenWrite:
 82540  
 82541    assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
 82542    assert( p->bIsReader );
 82543    assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
 82544            || p->readOnly==0 );
 82545  
 82546    if( p->expired ){
 82547      rc = SQLITE_ABORT_ROLLBACK;
 82548      goto abort_due_to_error;
 82549    }
 82550  
 82551    nField = 0;
 82552    pKeyInfo = 0;
 82553    p2 = pOp->p2;
 82554    iDb = pOp->p3;
 82555    assert( iDb>=0 && iDb<db->nDb );
 82556    assert( DbMaskTest(p->btreeMask, iDb) );
 82557    pDb = &db->aDb[iDb];
 82558    pX = pDb->pBt;
 82559    assert( pX!=0 );
 82560    if( pOp->opcode==OP_OpenWrite ){
 82561      assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
 82562      wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
 82563      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 82564      if( pDb->pSchema->file_format < p->minWriteFileFormat ){
 82565        p->minWriteFileFormat = pDb->pSchema->file_format;
 82566      }
 82567    }else{
 82568      wrFlag = 0;
 82569    }
 82570    if( pOp->p5 & OPFLAG_P2ISREG ){
 82571      assert( p2>0 );
 82572      assert( p2<=(p->nMem+1 - p->nCursor) );
 82573      pIn2 = &aMem[p2];
 82574      assert( memIsValid(pIn2) );
 82575      assert( (pIn2->flags & MEM_Int)!=0 );
 82576      sqlite3VdbeMemIntegerify(pIn2);
 82577      p2 = (int)pIn2->u.i;
 82578      /* The p2 value always comes from a prior OP_CreateBtree opcode and
 82579      ** that opcode will always set the p2 value to 2 or more or else fail.
 82580      ** If there were a failure, the prepared statement would have halted
 82581      ** before reaching this instruction. */
 82582      assert( p2>=2 );
 82583    }
 82584    if( pOp->p4type==P4_KEYINFO ){
 82585      pKeyInfo = pOp->p4.pKeyInfo;
 82586      assert( pKeyInfo->enc==ENC(db) );
 82587      assert( pKeyInfo->db==db );
 82588      nField = pKeyInfo->nAllField;
 82589    }else if( pOp->p4type==P4_INT32 ){
 82590      nField = pOp->p4.i;
 82591    }
 82592    assert( pOp->p1>=0 );
 82593    assert( nField>=0 );
 82594    testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
 82595    pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
 82596    if( pCur==0 ) goto no_mem;
 82597    pCur->nullRow = 1;
 82598    pCur->isOrdered = 1;
 82599    pCur->pgnoRoot = p2;
 82600  #ifdef SQLITE_DEBUG
 82601    pCur->wrFlag = wrFlag;
 82602  #endif
 82603    rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
 82604    pCur->pKeyInfo = pKeyInfo;
 82605    /* Set the VdbeCursor.isTable variable. Previous versions of
 82606    ** SQLite used to check if the root-page flags were sane at this point
 82607    ** and report database corruption if they were not, but this check has
 82608    ** since moved into the btree layer.  */  
 82609    pCur->isTable = pOp->p4type!=P4_KEYINFO;
 82610  
 82611  open_cursor_set_hints:
 82612    assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
 82613    assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
 82614    testcase( pOp->p5 & OPFLAG_BULKCSR );
 82615  #ifdef SQLITE_ENABLE_CURSOR_HINTS
 82616    testcase( pOp->p2 & OPFLAG_SEEKEQ );
 82617  #endif
 82618    sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
 82619                                 (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
 82620    if( rc ) goto abort_due_to_error;
 82621    break;
 82622  }
 82623  
 82624  /* Opcode: OpenDup P1 P2 * * *
 82625  **
 82626  ** Open a new cursor P1 that points to the same ephemeral table as
 82627  ** cursor P2.  The P2 cursor must have been opened by a prior OP_OpenEphemeral
 82628  ** opcode.  Only ephemeral cursors may be duplicated.
 82629  **
 82630  ** Duplicate ephemeral cursors are used for self-joins of materialized views.
 82631  */
 82632  case OP_OpenDup: {
 82633    VdbeCursor *pOrig;    /* The original cursor to be duplicated */
 82634    VdbeCursor *pCx;      /* The new cursor */
 82635  
 82636    pOrig = p->apCsr[pOp->p2];
 82637    assert( pOrig->pBtx!=0 );  /* Only ephemeral cursors can be duplicated */
 82638  
 82639    pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
 82640    if( pCx==0 ) goto no_mem;
 82641    pCx->nullRow = 1;
 82642    pCx->isEphemeral = 1;
 82643    pCx->pKeyInfo = pOrig->pKeyInfo;
 82644    pCx->isTable = pOrig->isTable;
 82645    rc = sqlite3BtreeCursor(pOrig->pBtx, MASTER_ROOT, BTREE_WRCSR,
 82646                            pCx->pKeyInfo, pCx->uc.pCursor);
 82647    /* The sqlite3BtreeCursor() routine can only fail for the first cursor
 82648    ** opened for a database.  Since there is already an open cursor when this
 82649    ** opcode is run, the sqlite3BtreeCursor() cannot fail */
 82650    assert( rc==SQLITE_OK );
 82651    break;
 82652  }
 82653  
 82654  
 82655  /* Opcode: OpenEphemeral P1 P2 * P4 P5
 82656  ** Synopsis: nColumn=P2
 82657  **
 82658  ** Open a new cursor P1 to a transient table.
 82659  ** The cursor is always opened read/write even if 
 82660  ** the main database is read-only.  The ephemeral
 82661  ** table is deleted automatically when the cursor is closed.
 82662  **
 82663  ** P2 is the number of columns in the ephemeral table.
 82664  ** The cursor points to a BTree table if P4==0 and to a BTree index
 82665  ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
 82666  ** that defines the format of keys in the index.
 82667  **
 82668  ** The P5 parameter can be a mask of the BTREE_* flags defined
 82669  ** in btree.h.  These flags control aspects of the operation of
 82670  ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
 82671  ** added automatically.
 82672  */
 82673  /* Opcode: OpenAutoindex P1 P2 * P4 *
 82674  ** Synopsis: nColumn=P2
 82675  **
 82676  ** This opcode works the same as OP_OpenEphemeral.  It has a
 82677  ** different name to distinguish its use.  Tables created using
 82678  ** by this opcode will be used for automatically created transient
 82679  ** indices in joins.
 82680  */
 82681  case OP_OpenAutoindex: 
 82682  case OP_OpenEphemeral: {
 82683    VdbeCursor *pCx;
 82684    KeyInfo *pKeyInfo;
 82685  
 82686    static const int vfsFlags = 
 82687        SQLITE_OPEN_READWRITE |
 82688        SQLITE_OPEN_CREATE |
 82689        SQLITE_OPEN_EXCLUSIVE |
 82690        SQLITE_OPEN_DELETEONCLOSE |
 82691        SQLITE_OPEN_TRANSIENT_DB;
 82692    assert( pOp->p1>=0 );
 82693    assert( pOp->p2>=0 );
 82694    pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
 82695    if( pCx==0 ) goto no_mem;
 82696    pCx->nullRow = 1;
 82697    pCx->isEphemeral = 1;
 82698    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx, 
 82699                          BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
 82700    if( rc==SQLITE_OK ){
 82701      rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1);
 82702    }
 82703    if( rc==SQLITE_OK ){
 82704      /* If a transient index is required, create it by calling
 82705      ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
 82706      ** opening it. If a transient table is required, just use the
 82707      ** automatically created table with root-page 1 (an BLOB_INTKEY table).
 82708      */
 82709      if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
 82710        int pgno;
 82711        assert( pOp->p4type==P4_KEYINFO );
 82712        rc = sqlite3BtreeCreateTable(pCx->pBtx, &pgno, BTREE_BLOBKEY | pOp->p5); 
 82713        if( rc==SQLITE_OK ){
 82714          assert( pgno==MASTER_ROOT+1 );
 82715          assert( pKeyInfo->db==db );
 82716          assert( pKeyInfo->enc==ENC(db) );
 82717          rc = sqlite3BtreeCursor(pCx->pBtx, pgno, BTREE_WRCSR,
 82718                                  pKeyInfo, pCx->uc.pCursor);
 82719        }
 82720        pCx->isTable = 0;
 82721      }else{
 82722        rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
 82723                                0, pCx->uc.pCursor);
 82724        pCx->isTable = 1;
 82725      }
 82726    }
 82727    if( rc ) goto abort_due_to_error;
 82728    pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
 82729    break;
 82730  }
 82731  
 82732  /* Opcode: SorterOpen P1 P2 P3 P4 *
 82733  **
 82734  ** This opcode works like OP_OpenEphemeral except that it opens
 82735  ** a transient index that is specifically designed to sort large
 82736  ** tables using an external merge-sort algorithm.
 82737  **
 82738  ** If argument P3 is non-zero, then it indicates that the sorter may
 82739  ** assume that a stable sort considering the first P3 fields of each
 82740  ** key is sufficient to produce the required results.
 82741  */
 82742  case OP_SorterOpen: {
 82743    VdbeCursor *pCx;
 82744  
 82745    assert( pOp->p1>=0 );
 82746    assert( pOp->p2>=0 );
 82747    pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
 82748    if( pCx==0 ) goto no_mem;
 82749    pCx->pKeyInfo = pOp->p4.pKeyInfo;
 82750    assert( pCx->pKeyInfo->db==db );
 82751    assert( pCx->pKeyInfo->enc==ENC(db) );
 82752    rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
 82753    if( rc ) goto abort_due_to_error;
 82754    break;
 82755  }
 82756  
 82757  /* Opcode: SequenceTest P1 P2 * * *
 82758  ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
 82759  **
 82760  ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
 82761  ** to P2. Regardless of whether or not the jump is taken, increment the
 82762  ** the sequence value.
 82763  */
 82764  case OP_SequenceTest: {
 82765    VdbeCursor *pC;
 82766    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 82767    pC = p->apCsr[pOp->p1];
 82768    assert( isSorter(pC) );
 82769    if( (pC->seqCount++)==0 ){
 82770      goto jump_to_p2;
 82771    }
 82772    break;
 82773  }
 82774  
 82775  /* Opcode: OpenPseudo P1 P2 P3 * *
 82776  ** Synopsis: P3 columns in r[P2]
 82777  **
 82778  ** Open a new cursor that points to a fake table that contains a single
 82779  ** row of data.  The content of that one row is the content of memory
 82780  ** register P2.  In other words, cursor P1 becomes an alias for the 
 82781  ** MEM_Blob content contained in register P2.
 82782  **
 82783  ** A pseudo-table created by this opcode is used to hold a single
 82784  ** row output from the sorter so that the row can be decomposed into
 82785  ** individual columns using the OP_Column opcode.  The OP_Column opcode
 82786  ** is the only cursor opcode that works with a pseudo-table.
 82787  **
 82788  ** P3 is the number of fields in the records that will be stored by
 82789  ** the pseudo-table.
 82790  */
 82791  case OP_OpenPseudo: {
 82792    VdbeCursor *pCx;
 82793  
 82794    assert( pOp->p1>=0 );
 82795    assert( pOp->p3>=0 );
 82796    pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
 82797    if( pCx==0 ) goto no_mem;
 82798    pCx->nullRow = 1;
 82799    pCx->seekResult = pOp->p2;
 82800    pCx->isTable = 1;
 82801    /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
 82802    ** can be safely passed to sqlite3VdbeCursorMoveto().  This avoids a test
 82803    ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
 82804    ** which is a performance optimization */
 82805    pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
 82806    assert( pOp->p5==0 );
 82807    break;
 82808  }
 82809  
 82810  /* Opcode: Close P1 * * * *
 82811  **
 82812  ** Close a cursor previously opened as P1.  If P1 is not
 82813  ** currently open, this instruction is a no-op.
 82814  */
 82815  case OP_Close: {
 82816    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 82817    sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
 82818    p->apCsr[pOp->p1] = 0;
 82819    break;
 82820  }
 82821  
 82822  #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
 82823  /* Opcode: ColumnsUsed P1 * * P4 *
 82824  **
 82825  ** This opcode (which only exists if SQLite was compiled with
 82826  ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
 82827  ** table or index for cursor P1 are used.  P4 is a 64-bit integer
 82828  ** (P4_INT64) in which the first 63 bits are one for each of the
 82829  ** first 63 columns of the table or index that are actually used
 82830  ** by the cursor.  The high-order bit is set if any column after
 82831  ** the 64th is used.
 82832  */
 82833  case OP_ColumnsUsed: {
 82834    VdbeCursor *pC;
 82835    pC = p->apCsr[pOp->p1];
 82836    assert( pC->eCurType==CURTYPE_BTREE );
 82837    pC->maskUsed = *(u64*)pOp->p4.pI64;
 82838    break;
 82839  }
 82840  #endif
 82841  
 82842  /* Opcode: SeekGE P1 P2 P3 P4 *
 82843  ** Synopsis: key=r[P3@P4]
 82844  **
 82845  ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
 82846  ** use the value in register P3 as the key.  If cursor P1 refers 
 82847  ** to an SQL index, then P3 is the first in an array of P4 registers 
 82848  ** that are used as an unpacked index key. 
 82849  **
 82850  ** Reposition cursor P1 so that  it points to the smallest entry that 
 82851  ** is greater than or equal to the key value. If there are no records 
 82852  ** greater than or equal to the key and P2 is not zero, then jump to P2.
 82853  **
 82854  ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
 82855  ** opcode will always land on a record that equally equals the key, or
 82856  ** else jump immediately to P2.  When the cursor is OPFLAG_SEEKEQ, this
 82857  ** opcode must be followed by an IdxLE opcode with the same arguments.
 82858  ** The IdxLE opcode will be skipped if this opcode succeeds, but the
 82859  ** IdxLE opcode will be used on subsequent loop iterations.
 82860  **
 82861  ** This opcode leaves the cursor configured to move in forward order,
 82862  ** from the beginning toward the end.  In other words, the cursor is
 82863  ** configured to use Next, not Prev.
 82864  **
 82865  ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
 82866  */
 82867  /* Opcode: SeekGT P1 P2 P3 P4 *
 82868  ** Synopsis: key=r[P3@P4]
 82869  **
 82870  ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
 82871  ** use the value in register P3 as a key. If cursor P1 refers 
 82872  ** to an SQL index, then P3 is the first in an array of P4 registers 
 82873  ** that are used as an unpacked index key. 
 82874  **
 82875  ** Reposition cursor P1 so that  it points to the smallest entry that 
 82876  ** is greater than the key value. If there are no records greater than 
 82877  ** the key and P2 is not zero, then jump to P2.
 82878  **
 82879  ** This opcode leaves the cursor configured to move in forward order,
 82880  ** from the beginning toward the end.  In other words, the cursor is
 82881  ** configured to use Next, not Prev.
 82882  **
 82883  ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
 82884  */
 82885  /* Opcode: SeekLT P1 P2 P3 P4 * 
 82886  ** Synopsis: key=r[P3@P4]
 82887  **
 82888  ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
 82889  ** use the value in register P3 as a key. If cursor P1 refers 
 82890  ** to an SQL index, then P3 is the first in an array of P4 registers 
 82891  ** that are used as an unpacked index key. 
 82892  **
 82893  ** Reposition cursor P1 so that  it points to the largest entry that 
 82894  ** is less than the key value. If there are no records less than 
 82895  ** the key and P2 is not zero, then jump to P2.
 82896  **
 82897  ** This opcode leaves the cursor configured to move in reverse order,
 82898  ** from the end toward the beginning.  In other words, the cursor is
 82899  ** configured to use Prev, not Next.
 82900  **
 82901  ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
 82902  */
 82903  /* Opcode: SeekLE P1 P2 P3 P4 *
 82904  ** Synopsis: key=r[P3@P4]
 82905  **
 82906  ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
 82907  ** use the value in register P3 as a key. If cursor P1 refers 
 82908  ** to an SQL index, then P3 is the first in an array of P4 registers 
 82909  ** that are used as an unpacked index key. 
 82910  **
 82911  ** Reposition cursor P1 so that it points to the largest entry that 
 82912  ** is less than or equal to the key value. If there are no records 
 82913  ** less than or equal to the key and P2 is not zero, then jump to P2.
 82914  **
 82915  ** This opcode leaves the cursor configured to move in reverse order,
 82916  ** from the end toward the beginning.  In other words, the cursor is
 82917  ** configured to use Prev, not Next.
 82918  **
 82919  ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
 82920  ** opcode will always land on a record that equally equals the key, or
 82921  ** else jump immediately to P2.  When the cursor is OPFLAG_SEEKEQ, this
 82922  ** opcode must be followed by an IdxGE opcode with the same arguments.
 82923  ** The IdxGE opcode will be skipped if this opcode succeeds, but the
 82924  ** IdxGE opcode will be used on subsequent loop iterations.
 82925  **
 82926  ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
 82927  */
 82928  case OP_SeekLT:         /* jump, in3 */
 82929  case OP_SeekLE:         /* jump, in3 */
 82930  case OP_SeekGE:         /* jump, in3 */
 82931  case OP_SeekGT: {       /* jump, in3 */
 82932    int res;           /* Comparison result */
 82933    int oc;            /* Opcode */
 82934    VdbeCursor *pC;    /* The cursor to seek */
 82935    UnpackedRecord r;  /* The key to seek for */
 82936    int nField;        /* Number of columns or fields in the key */
 82937    i64 iKey;          /* The rowid we are to seek to */
 82938    int eqOnly;        /* Only interested in == results */
 82939  
 82940    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 82941    assert( pOp->p2!=0 );
 82942    pC = p->apCsr[pOp->p1];
 82943    assert( pC!=0 );
 82944    assert( pC->eCurType==CURTYPE_BTREE );
 82945    assert( OP_SeekLE == OP_SeekLT+1 );
 82946    assert( OP_SeekGE == OP_SeekLT+2 );
 82947    assert( OP_SeekGT == OP_SeekLT+3 );
 82948    assert( pC->isOrdered );
 82949    assert( pC->uc.pCursor!=0 );
 82950    oc = pOp->opcode;
 82951    eqOnly = 0;
 82952    pC->nullRow = 0;
 82953  #ifdef SQLITE_DEBUG
 82954    pC->seekOp = pOp->opcode;
 82955  #endif
 82956  
 82957    if( pC->isTable ){
 82958      /* The BTREE_SEEK_EQ flag is only set on index cursors */
 82959      assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
 82960                || CORRUPT_DB );
 82961  
 82962      /* The input value in P3 might be of any type: integer, real, string,
 82963      ** blob, or NULL.  But it needs to be an integer before we can do
 82964      ** the seek, so convert it. */
 82965      pIn3 = &aMem[pOp->p3];
 82966      if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
 82967        applyNumericAffinity(pIn3, 0);
 82968      }
 82969      iKey = sqlite3VdbeIntValue(pIn3);
 82970  
 82971      /* If the P3 value could not be converted into an integer without
 82972      ** loss of information, then special processing is required... */
 82973      if( (pIn3->flags & MEM_Int)==0 ){
 82974        if( (pIn3->flags & MEM_Real)==0 ){
 82975          /* If the P3 value cannot be converted into any kind of a number,
 82976          ** then the seek is not possible, so jump to P2 */
 82977          VdbeBranchTaken(1,2); goto jump_to_p2;
 82978          break;
 82979        }
 82980  
 82981        /* If the approximation iKey is larger than the actual real search
 82982        ** term, substitute >= for > and < for <=. e.g. if the search term
 82983        ** is 4.9 and the integer approximation 5:
 82984        **
 82985        **        (x >  4.9)    ->     (x >= 5)
 82986        **        (x <= 4.9)    ->     (x <  5)
 82987        */
 82988        if( pIn3->u.r<(double)iKey ){
 82989          assert( OP_SeekGE==(OP_SeekGT-1) );
 82990          assert( OP_SeekLT==(OP_SeekLE-1) );
 82991          assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
 82992          if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
 82993        }
 82994  
 82995        /* If the approximation iKey is smaller than the actual real search
 82996        ** term, substitute <= for < and > for >=.  */
 82997        else if( pIn3->u.r>(double)iKey ){
 82998          assert( OP_SeekLE==(OP_SeekLT+1) );
 82999          assert( OP_SeekGT==(OP_SeekGE+1) );
 83000          assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
 83001          if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
 83002        }
 83003      } 
 83004      rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
 83005      pC->movetoTarget = iKey;  /* Used by OP_Delete */
 83006      if( rc!=SQLITE_OK ){
 83007        goto abort_due_to_error;
 83008      }
 83009    }else{
 83010      /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
 83011      ** OP_SeekLE opcodes are allowed, and these must be immediately followed
 83012      ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
 83013      */
 83014      if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
 83015        eqOnly = 1;
 83016        assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
 83017        assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
 83018        assert( pOp[1].p1==pOp[0].p1 );
 83019        assert( pOp[1].p2==pOp[0].p2 );
 83020        assert( pOp[1].p3==pOp[0].p3 );
 83021        assert( pOp[1].p4.i==pOp[0].p4.i );
 83022      }
 83023  
 83024      nField = pOp->p4.i;
 83025      assert( pOp->p4type==P4_INT32 );
 83026      assert( nField>0 );
 83027      r.pKeyInfo = pC->pKeyInfo;
 83028      r.nField = (u16)nField;
 83029  
 83030      /* The next line of code computes as follows, only faster:
 83031      **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
 83032      **     r.default_rc = -1;
 83033      **   }else{
 83034      **     r.default_rc = +1;
 83035      **   }
 83036      */
 83037      r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
 83038      assert( oc!=OP_SeekGT || r.default_rc==-1 );
 83039      assert( oc!=OP_SeekLE || r.default_rc==-1 );
 83040      assert( oc!=OP_SeekGE || r.default_rc==+1 );
 83041      assert( oc!=OP_SeekLT || r.default_rc==+1 );
 83042  
 83043      r.aMem = &aMem[pOp->p3];
 83044  #ifdef SQLITE_DEBUG
 83045      { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
 83046  #endif
 83047      r.eqSeen = 0;
 83048      rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
 83049      if( rc!=SQLITE_OK ){
 83050        goto abort_due_to_error;
 83051      }
 83052      if( eqOnly && r.eqSeen==0 ){
 83053        assert( res!=0 );
 83054        goto seek_not_found;
 83055      }
 83056    }
 83057    pC->deferredMoveto = 0;
 83058    pC->cacheStatus = CACHE_STALE;
 83059  #ifdef SQLITE_TEST
 83060    sqlite3_search_count++;
 83061  #endif
 83062    if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
 83063      if( res<0 || (res==0 && oc==OP_SeekGT) ){
 83064        res = 0;
 83065        rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
 83066        if( rc!=SQLITE_OK ){
 83067          if( rc==SQLITE_DONE ){
 83068            rc = SQLITE_OK;
 83069            res = 1;
 83070          }else{
 83071            goto abort_due_to_error;
 83072          }
 83073        }
 83074      }else{
 83075        res = 0;
 83076      }
 83077    }else{
 83078      assert( oc==OP_SeekLT || oc==OP_SeekLE );
 83079      if( res>0 || (res==0 && oc==OP_SeekLT) ){
 83080        res = 0;
 83081        rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
 83082        if( rc!=SQLITE_OK ){
 83083          if( rc==SQLITE_DONE ){
 83084            rc = SQLITE_OK;
 83085            res = 1;
 83086          }else{
 83087            goto abort_due_to_error;
 83088          }
 83089        }
 83090      }else{
 83091        /* res might be negative because the table is empty.  Check to
 83092        ** see if this is the case.
 83093        */
 83094        res = sqlite3BtreeEof(pC->uc.pCursor);
 83095      }
 83096    }
 83097  seek_not_found:
 83098    assert( pOp->p2>0 );
 83099    VdbeBranchTaken(res!=0,2);
 83100    if( res ){
 83101      goto jump_to_p2;
 83102    }else if( eqOnly ){
 83103      assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
 83104      pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
 83105    }
 83106    break;
 83107  }
 83108  
 83109  /* Opcode: Found P1 P2 P3 P4 *
 83110  ** Synopsis: key=r[P3@P4]
 83111  **
 83112  ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
 83113  ** P4>0 then register P3 is the first of P4 registers that form an unpacked
 83114  ** record.
 83115  **
 83116  ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
 83117  ** is a prefix of any entry in P1 then a jump is made to P2 and
 83118  ** P1 is left pointing at the matching entry.
 83119  **
 83120  ** This operation leaves the cursor in a state where it can be
 83121  ** advanced in the forward direction.  The Next instruction will work,
 83122  ** but not the Prev instruction.
 83123  **
 83124  ** See also: NotFound, NoConflict, NotExists. SeekGe
 83125  */
 83126  /* Opcode: NotFound P1 P2 P3 P4 *
 83127  ** Synopsis: key=r[P3@P4]
 83128  **
 83129  ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
 83130  ** P4>0 then register P3 is the first of P4 registers that form an unpacked
 83131  ** record.
 83132  ** 
 83133  ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
 83134  ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
 83135  ** does contain an entry whose prefix matches the P3/P4 record then control
 83136  ** falls through to the next instruction and P1 is left pointing at the
 83137  ** matching entry.
 83138  **
 83139  ** This operation leaves the cursor in a state where it cannot be
 83140  ** advanced in either direction.  In other words, the Next and Prev
 83141  ** opcodes do not work after this operation.
 83142  **
 83143  ** See also: Found, NotExists, NoConflict
 83144  */
 83145  /* Opcode: NoConflict P1 P2 P3 P4 *
 83146  ** Synopsis: key=r[P3@P4]
 83147  **
 83148  ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
 83149  ** P4>0 then register P3 is the first of P4 registers that form an unpacked
 83150  ** record.
 83151  ** 
 83152  ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
 83153  ** contains any NULL value, jump immediately to P2.  If all terms of the
 83154  ** record are not-NULL then a check is done to determine if any row in the
 83155  ** P1 index btree has a matching key prefix.  If there are no matches, jump
 83156  ** immediately to P2.  If there is a match, fall through and leave the P1
 83157  ** cursor pointing to the matching row.
 83158  **
 83159  ** This opcode is similar to OP_NotFound with the exceptions that the
 83160  ** branch is always taken if any part of the search key input is NULL.
 83161  **
 83162  ** This operation leaves the cursor in a state where it cannot be
 83163  ** advanced in either direction.  In other words, the Next and Prev
 83164  ** opcodes do not work after this operation.
 83165  **
 83166  ** See also: NotFound, Found, NotExists
 83167  */
 83168  case OP_NoConflict:     /* jump, in3 */
 83169  case OP_NotFound:       /* jump, in3 */
 83170  case OP_Found: {        /* jump, in3 */
 83171    int alreadyExists;
 83172    int takeJump;
 83173    int ii;
 83174    VdbeCursor *pC;
 83175    int res;
 83176    UnpackedRecord *pFree;
 83177    UnpackedRecord *pIdxKey;
 83178    UnpackedRecord r;
 83179  
 83180  #ifdef SQLITE_TEST
 83181    if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
 83182  #endif
 83183  
 83184    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 83185    assert( pOp->p4type==P4_INT32 );
 83186    pC = p->apCsr[pOp->p1];
 83187    assert( pC!=0 );
 83188  #ifdef SQLITE_DEBUG
 83189    pC->seekOp = pOp->opcode;
 83190  #endif
 83191    pIn3 = &aMem[pOp->p3];
 83192    assert( pC->eCurType==CURTYPE_BTREE );
 83193    assert( pC->uc.pCursor!=0 );
 83194    assert( pC->isTable==0 );
 83195    if( pOp->p4.i>0 ){
 83196      r.pKeyInfo = pC->pKeyInfo;
 83197      r.nField = (u16)pOp->p4.i;
 83198      r.aMem = pIn3;
 83199  #ifdef SQLITE_DEBUG
 83200      for(ii=0; ii<r.nField; ii++){
 83201        assert( memIsValid(&r.aMem[ii]) );
 83202        assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
 83203        if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
 83204      }
 83205  #endif
 83206      pIdxKey = &r;
 83207      pFree = 0;
 83208    }else{
 83209      assert( pIn3->flags & MEM_Blob );
 83210      rc = ExpandBlob(pIn3);
 83211      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
 83212      if( rc ) goto no_mem;
 83213      pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
 83214      if( pIdxKey==0 ) goto no_mem;
 83215      sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
 83216    }
 83217    pIdxKey->default_rc = 0;
 83218    takeJump = 0;
 83219    if( pOp->opcode==OP_NoConflict ){
 83220      /* For the OP_NoConflict opcode, take the jump if any of the
 83221      ** input fields are NULL, since any key with a NULL will not
 83222      ** conflict */
 83223      for(ii=0; ii<pIdxKey->nField; ii++){
 83224        if( pIdxKey->aMem[ii].flags & MEM_Null ){
 83225          takeJump = 1;
 83226          break;
 83227        }
 83228      }
 83229    }
 83230    rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
 83231    if( pFree ) sqlite3DbFreeNN(db, pFree);
 83232    if( rc!=SQLITE_OK ){
 83233      goto abort_due_to_error;
 83234    }
 83235    pC->seekResult = res;
 83236    alreadyExists = (res==0);
 83237    pC->nullRow = 1-alreadyExists;
 83238    pC->deferredMoveto = 0;
 83239    pC->cacheStatus = CACHE_STALE;
 83240    if( pOp->opcode==OP_Found ){
 83241      VdbeBranchTaken(alreadyExists!=0,2);
 83242      if( alreadyExists ) goto jump_to_p2;
 83243    }else{
 83244      VdbeBranchTaken(takeJump||alreadyExists==0,2);
 83245      if( takeJump || !alreadyExists ) goto jump_to_p2;
 83246    }
 83247    break;
 83248  }
 83249  
 83250  /* Opcode: SeekRowid P1 P2 P3 * *
 83251  ** Synopsis: intkey=r[P3]
 83252  **
 83253  ** P1 is the index of a cursor open on an SQL table btree (with integer
 83254  ** keys).  If register P3 does not contain an integer or if P1 does not
 83255  ** contain a record with rowid P3 then jump immediately to P2.  
 83256  ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
 83257  ** a record with rowid P3 then 
 83258  ** leave the cursor pointing at that record and fall through to the next
 83259  ** instruction.
 83260  **
 83261  ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
 83262  ** the P3 register must be guaranteed to contain an integer value.  With this
 83263  ** opcode, register P3 might not contain an integer.
 83264  **
 83265  ** The OP_NotFound opcode performs the same operation on index btrees
 83266  ** (with arbitrary multi-value keys).
 83267  **
 83268  ** This opcode leaves the cursor in a state where it cannot be advanced
 83269  ** in either direction.  In other words, the Next and Prev opcodes will
 83270  ** not work following this opcode.
 83271  **
 83272  ** See also: Found, NotFound, NoConflict, SeekRowid
 83273  */
 83274  /* Opcode: NotExists P1 P2 P3 * *
 83275  ** Synopsis: intkey=r[P3]
 83276  **
 83277  ** P1 is the index of a cursor open on an SQL table btree (with integer
 83278  ** keys).  P3 is an integer rowid.  If P1 does not contain a record with
 83279  ** rowid P3 then jump immediately to P2.  Or, if P2 is 0, raise an
 83280  ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then 
 83281  ** leave the cursor pointing at that record and fall through to the next
 83282  ** instruction.
 83283  **
 83284  ** The OP_SeekRowid opcode performs the same operation but also allows the
 83285  ** P3 register to contain a non-integer value, in which case the jump is
 83286  ** always taken.  This opcode requires that P3 always contain an integer.
 83287  **
 83288  ** The OP_NotFound opcode performs the same operation on index btrees
 83289  ** (with arbitrary multi-value keys).
 83290  **
 83291  ** This opcode leaves the cursor in a state where it cannot be advanced
 83292  ** in either direction.  In other words, the Next and Prev opcodes will
 83293  ** not work following this opcode.
 83294  **
 83295  ** See also: Found, NotFound, NoConflict, SeekRowid
 83296  */
 83297  case OP_SeekRowid: {        /* jump, in3 */
 83298    VdbeCursor *pC;
 83299    BtCursor *pCrsr;
 83300    int res;
 83301    u64 iKey;
 83302  
 83303    pIn3 = &aMem[pOp->p3];
 83304    if( (pIn3->flags & MEM_Int)==0 ){
 83305      applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
 83306      if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2;
 83307    }
 83308    /* Fall through into OP_NotExists */
 83309  case OP_NotExists:          /* jump, in3 */
 83310    pIn3 = &aMem[pOp->p3];
 83311    assert( pIn3->flags & MEM_Int );
 83312    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 83313    pC = p->apCsr[pOp->p1];
 83314    assert( pC!=0 );
 83315  #ifdef SQLITE_DEBUG
 83316    pC->seekOp = 0;
 83317  #endif
 83318    assert( pC->isTable );
 83319    assert( pC->eCurType==CURTYPE_BTREE );
 83320    pCrsr = pC->uc.pCursor;
 83321    assert( pCrsr!=0 );
 83322    res = 0;
 83323    iKey = pIn3->u.i;
 83324    rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
 83325    assert( rc==SQLITE_OK || res==0 );
 83326    pC->movetoTarget = iKey;  /* Used by OP_Delete */
 83327    pC->nullRow = 0;
 83328    pC->cacheStatus = CACHE_STALE;
 83329    pC->deferredMoveto = 0;
 83330    VdbeBranchTaken(res!=0,2);
 83331    pC->seekResult = res;
 83332    if( res!=0 ){
 83333      assert( rc==SQLITE_OK );
 83334      if( pOp->p2==0 ){
 83335        rc = SQLITE_CORRUPT_BKPT;
 83336      }else{
 83337        goto jump_to_p2;
 83338      }
 83339    }
 83340    if( rc ) goto abort_due_to_error;
 83341    break;
 83342  }
 83343  
 83344  /* Opcode: Sequence P1 P2 * * *
 83345  ** Synopsis: r[P2]=cursor[P1].ctr++
 83346  **
 83347  ** Find the next available sequence number for cursor P1.
 83348  ** Write the sequence number into register P2.
 83349  ** The sequence number on the cursor is incremented after this
 83350  ** instruction.  
 83351  */
 83352  case OP_Sequence: {           /* out2 */
 83353    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 83354    assert( p->apCsr[pOp->p1]!=0 );
 83355    assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
 83356    pOut = out2Prerelease(p, pOp);
 83357    pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
 83358    break;
 83359  }
 83360  
 83361  
 83362  /* Opcode: NewRowid P1 P2 P3 * *
 83363  ** Synopsis: r[P2]=rowid
 83364  **
 83365  ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
 83366  ** The record number is not previously used as a key in the database
 83367  ** table that cursor P1 points to.  The new record number is written
 83368  ** written to register P2.
 83369  **
 83370  ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
 83371  ** the largest previously generated record number. No new record numbers are
 83372  ** allowed to be less than this value. When this value reaches its maximum, 
 83373  ** an SQLITE_FULL error is generated. The P3 register is updated with the '
 83374  ** generated record number. This P3 mechanism is used to help implement the
 83375  ** AUTOINCREMENT feature.
 83376  */
 83377  case OP_NewRowid: {           /* out2 */
 83378    i64 v;                 /* The new rowid */
 83379    VdbeCursor *pC;        /* Cursor of table to get the new rowid */
 83380    int res;               /* Result of an sqlite3BtreeLast() */
 83381    int cnt;               /* Counter to limit the number of searches */
 83382    Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
 83383    VdbeFrame *pFrame;     /* Root frame of VDBE */
 83384  
 83385    v = 0;
 83386    res = 0;
 83387    pOut = out2Prerelease(p, pOp);
 83388    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 83389    pC = p->apCsr[pOp->p1];
 83390    assert( pC!=0 );
 83391    assert( pC->eCurType==CURTYPE_BTREE );
 83392    assert( pC->uc.pCursor!=0 );
 83393    {
 83394      /* The next rowid or record number (different terms for the same
 83395      ** thing) is obtained in a two-step algorithm.
 83396      **
 83397      ** First we attempt to find the largest existing rowid and add one
 83398      ** to that.  But if the largest existing rowid is already the maximum
 83399      ** positive integer, we have to fall through to the second
 83400      ** probabilistic algorithm
 83401      **
 83402      ** The second algorithm is to select a rowid at random and see if
 83403      ** it already exists in the table.  If it does not exist, we have
 83404      ** succeeded.  If the random rowid does exist, we select a new one
 83405      ** and try again, up to 100 times.
 83406      */
 83407      assert( pC->isTable );
 83408  
 83409  #ifdef SQLITE_32BIT_ROWID
 83410  #   define MAX_ROWID 0x7fffffff
 83411  #else
 83412      /* Some compilers complain about constants of the form 0x7fffffffffffffff.
 83413      ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
 83414      ** to provide the constant while making all compilers happy.
 83415      */
 83416  #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
 83417  #endif
 83418  
 83419      if( !pC->useRandomRowid ){
 83420        rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
 83421        if( rc!=SQLITE_OK ){
 83422          goto abort_due_to_error;
 83423        }
 83424        if( res ){
 83425          v = 1;   /* IMP: R-61914-48074 */
 83426        }else{
 83427          assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
 83428          v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
 83429          if( v>=MAX_ROWID ){
 83430            pC->useRandomRowid = 1;
 83431          }else{
 83432            v++;   /* IMP: R-29538-34987 */
 83433          }
 83434        }
 83435      }
 83436  
 83437  #ifndef SQLITE_OMIT_AUTOINCREMENT
 83438      if( pOp->p3 ){
 83439        /* Assert that P3 is a valid memory cell. */
 83440        assert( pOp->p3>0 );
 83441        if( p->pFrame ){
 83442          for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
 83443          /* Assert that P3 is a valid memory cell. */
 83444          assert( pOp->p3<=pFrame->nMem );
 83445          pMem = &pFrame->aMem[pOp->p3];
 83446        }else{
 83447          /* Assert that P3 is a valid memory cell. */
 83448          assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
 83449          pMem = &aMem[pOp->p3];
 83450          memAboutToChange(p, pMem);
 83451        }
 83452        assert( memIsValid(pMem) );
 83453  
 83454        REGISTER_TRACE(pOp->p3, pMem);
 83455        sqlite3VdbeMemIntegerify(pMem);
 83456        assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
 83457        if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
 83458          rc = SQLITE_FULL;   /* IMP: R-17817-00630 */
 83459          goto abort_due_to_error;
 83460        }
 83461        if( v<pMem->u.i+1 ){
 83462          v = pMem->u.i + 1;
 83463        }
 83464        pMem->u.i = v;
 83465      }
 83466  #endif
 83467      if( pC->useRandomRowid ){
 83468        /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
 83469        ** largest possible integer (9223372036854775807) then the database
 83470        ** engine starts picking positive candidate ROWIDs at random until
 83471        ** it finds one that is not previously used. */
 83472        assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
 83473                               ** an AUTOINCREMENT table. */
 83474        cnt = 0;
 83475        do{
 83476          sqlite3_randomness(sizeof(v), &v);
 83477          v &= (MAX_ROWID>>1); v++;  /* Ensure that v is greater than zero */
 83478        }while(  ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
 83479                                                   0, &res))==SQLITE_OK)
 83480              && (res==0)
 83481              && (++cnt<100));
 83482        if( rc ) goto abort_due_to_error;
 83483        if( res==0 ){
 83484          rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
 83485          goto abort_due_to_error;
 83486        }
 83487        assert( v>0 );  /* EV: R-40812-03570 */
 83488      }
 83489      pC->deferredMoveto = 0;
 83490      pC->cacheStatus = CACHE_STALE;
 83491    }
 83492    pOut->u.i = v;
 83493    break;
 83494  }
 83495  
 83496  /* Opcode: Insert P1 P2 P3 P4 P5
 83497  ** Synopsis: intkey=r[P3] data=r[P2]
 83498  **
 83499  ** Write an entry into the table of cursor P1.  A new entry is
 83500  ** created if it doesn't already exist or the data for an existing
 83501  ** entry is overwritten.  The data is the value MEM_Blob stored in register
 83502  ** number P2. The key is stored in register P3. The key must
 83503  ** be a MEM_Int.
 83504  **
 83505  ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
 83506  ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
 83507  ** then rowid is stored for subsequent return by the
 83508  ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
 83509  **
 83510  ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
 83511  ** run faster by avoiding an unnecessary seek on cursor P1.  However,
 83512  ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
 83513  ** seeks on the cursor or if the most recent seek used a key equal to P3.
 83514  **
 83515  ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
 83516  ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
 83517  ** is part of an INSERT operation.  The difference is only important to
 83518  ** the update hook.
 83519  **
 83520  ** Parameter P4 may point to a Table structure, or may be NULL. If it is 
 83521  ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked 
 83522  ** following a successful insert.
 83523  **
 83524  ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
 83525  ** allocated, then ownership of P2 is transferred to the pseudo-cursor
 83526  ** and register P2 becomes ephemeral.  If the cursor is changed, the
 83527  ** value of register P2 will then change.  Make sure this does not
 83528  ** cause any problems.)
 83529  **
 83530  ** This instruction only works on tables.  The equivalent instruction
 83531  ** for indices is OP_IdxInsert.
 83532  */
 83533  /* Opcode: InsertInt P1 P2 P3 P4 P5
 83534  ** Synopsis: intkey=P3 data=r[P2]
 83535  **
 83536  ** This works exactly like OP_Insert except that the key is the
 83537  ** integer value P3, not the value of the integer stored in register P3.
 83538  */
 83539  case OP_Insert: 
 83540  case OP_InsertInt: {
 83541    Mem *pData;       /* MEM cell holding data for the record to be inserted */
 83542    Mem *pKey;        /* MEM cell holding key  for the record */
 83543    VdbeCursor *pC;   /* Cursor to table into which insert is written */
 83544    int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
 83545    const char *zDb;  /* database name - used by the update hook */
 83546    Table *pTab;      /* Table structure - used by update and pre-update hooks */
 83547    int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
 83548    BtreePayload x;   /* Payload to be inserted */
 83549  
 83550    op = 0;
 83551    pData = &aMem[pOp->p2];
 83552    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 83553    assert( memIsValid(pData) );
 83554    pC = p->apCsr[pOp->p1];
 83555    assert( pC!=0 );
 83556    assert( pC->eCurType==CURTYPE_BTREE );
 83557    assert( pC->uc.pCursor!=0 );
 83558    assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
 83559    assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
 83560    REGISTER_TRACE(pOp->p2, pData);
 83561  
 83562    if( pOp->opcode==OP_Insert ){
 83563      pKey = &aMem[pOp->p3];
 83564      assert( pKey->flags & MEM_Int );
 83565      assert( memIsValid(pKey) );
 83566      REGISTER_TRACE(pOp->p3, pKey);
 83567      x.nKey = pKey->u.i;
 83568    }else{
 83569      assert( pOp->opcode==OP_InsertInt );
 83570      x.nKey = pOp->p3;
 83571    }
 83572  
 83573    if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
 83574      assert( pC->iDb>=0 );
 83575      zDb = db->aDb[pC->iDb].zDbSName;
 83576      pTab = pOp->p4.pTab;
 83577      assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
 83578      op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
 83579    }else{
 83580      pTab = 0; /* Not needed.  Silence a compiler warning. */
 83581      zDb = 0;  /* Not needed.  Silence a compiler warning. */
 83582    }
 83583  
 83584  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 83585    /* Invoke the pre-update hook, if any */
 83586    if( db->xPreUpdateCallback 
 83587     && pOp->p4type==P4_TABLE
 83588     && !(pOp->p5 & OPFLAG_ISUPDATE)
 83589    ){
 83590      sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey, pOp->p2);
 83591    }
 83592    if( pOp->p5 & OPFLAG_ISNOOP ) break;
 83593  #endif
 83594  
 83595    if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
 83596    if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
 83597    assert( pData->flags & (MEM_Blob|MEM_Str) );
 83598    x.pData = pData->z;
 83599    x.nData = pData->n;
 83600    seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
 83601    if( pData->flags & MEM_Zero ){
 83602      x.nZero = pData->u.nZero;
 83603    }else{
 83604      x.nZero = 0;
 83605    }
 83606    x.pKey = 0;
 83607    rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
 83608        (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
 83609    );
 83610    pC->deferredMoveto = 0;
 83611    pC->cacheStatus = CACHE_STALE;
 83612  
 83613    /* Invoke the update-hook if required. */
 83614    if( rc ) goto abort_due_to_error;
 83615    if( db->xUpdateCallback && op ){
 83616      db->xUpdateCallback(db->pUpdateArg, op, zDb, pTab->zName, x.nKey);
 83617    }
 83618    break;
 83619  }
 83620  
 83621  /* Opcode: Delete P1 P2 P3 P4 P5
 83622  **
 83623  ** Delete the record at which the P1 cursor is currently pointing.
 83624  **
 83625  ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
 83626  ** the cursor will be left pointing at  either the next or the previous
 83627  ** record in the table. If it is left pointing at the next record, then
 83628  ** the next Next instruction will be a no-op. As a result, in this case
 83629  ** it is ok to delete a record from within a Next loop. If 
 83630  ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
 83631  ** left in an undefined state.
 83632  **
 83633  ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
 83634  ** delete one of several associated with deleting a table row and all its
 83635  ** associated index entries.  Exactly one of those deletes is the "primary"
 83636  ** delete.  The others are all on OPFLAG_FORDELETE cursors or else are
 83637  ** marked with the AUXDELETE flag.
 83638  **
 83639  ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
 83640  ** change count is incremented (otherwise not).
 83641  **
 83642  ** P1 must not be pseudo-table.  It has to be a real table with
 83643  ** multiple rows.
 83644  **
 83645  ** If P4 is not NULL then it points to a Table object. In this case either 
 83646  ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
 83647  ** have been positioned using OP_NotFound prior to invoking this opcode in 
 83648  ** this case. Specifically, if one is configured, the pre-update hook is 
 83649  ** invoked if P4 is not NULL. The update-hook is invoked if one is configured, 
 83650  ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
 83651  **
 83652  ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
 83653  ** of the memory cell that contains the value that the rowid of the row will
 83654  ** be set to by the update.
 83655  */
 83656  case OP_Delete: {
 83657    VdbeCursor *pC;
 83658    const char *zDb;
 83659    Table *pTab;
 83660    int opflags;
 83661  
 83662    opflags = pOp->p2;
 83663    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 83664    pC = p->apCsr[pOp->p1];
 83665    assert( pC!=0 );
 83666    assert( pC->eCurType==CURTYPE_BTREE );
 83667    assert( pC->uc.pCursor!=0 );
 83668    assert( pC->deferredMoveto==0 );
 83669  
 83670  #ifdef SQLITE_DEBUG
 83671    if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
 83672      /* If p5 is zero, the seek operation that positioned the cursor prior to
 83673      ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
 83674      ** the row that is being deleted */
 83675      i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
 83676      assert( pC->movetoTarget==iKey );
 83677    }
 83678  #endif
 83679  
 83680    /* If the update-hook or pre-update-hook will be invoked, set zDb to
 83681    ** the name of the db to pass as to it. Also set local pTab to a copy
 83682    ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
 83683    ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set 
 83684    ** VdbeCursor.movetoTarget to the current rowid.  */
 83685    if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
 83686      assert( pC->iDb>=0 );
 83687      assert( pOp->p4.pTab!=0 );
 83688      zDb = db->aDb[pC->iDb].zDbSName;
 83689      pTab = pOp->p4.pTab;
 83690      if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
 83691        pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
 83692      }
 83693    }else{
 83694      zDb = 0;   /* Not needed.  Silence a compiler warning. */
 83695      pTab = 0;  /* Not needed.  Silence a compiler warning. */
 83696    }
 83697  
 83698  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 83699    /* Invoke the pre-update-hook if required. */
 83700    if( db->xPreUpdateCallback && pOp->p4.pTab ){
 83701      assert( !(opflags & OPFLAG_ISUPDATE) 
 83702           || HasRowid(pTab)==0 
 83703           || (aMem[pOp->p3].flags & MEM_Int) 
 83704      );
 83705      sqlite3VdbePreUpdateHook(p, pC,
 83706          (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE, 
 83707          zDb, pTab, pC->movetoTarget,
 83708          pOp->p3
 83709      );
 83710    }
 83711    if( opflags & OPFLAG_ISNOOP ) break;
 83712  #endif
 83713   
 83714    /* Only flags that can be set are SAVEPOISTION and AUXDELETE */ 
 83715    assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
 83716    assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
 83717    assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
 83718  
 83719  #ifdef SQLITE_DEBUG
 83720    if( p->pFrame==0 ){
 83721      if( pC->isEphemeral==0
 83722          && (pOp->p5 & OPFLAG_AUXDELETE)==0
 83723          && (pC->wrFlag & OPFLAG_FORDELETE)==0
 83724        ){
 83725        nExtraDelete++;
 83726      }
 83727      if( pOp->p2 & OPFLAG_NCHANGE ){
 83728        nExtraDelete--;
 83729      }
 83730    }
 83731  #endif
 83732  
 83733    rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
 83734    pC->cacheStatus = CACHE_STALE;
 83735    pC->seekResult = 0;
 83736    if( rc ) goto abort_due_to_error;
 83737  
 83738    /* Invoke the update-hook if required. */
 83739    if( opflags & OPFLAG_NCHANGE ){
 83740      p->nChange++;
 83741      if( db->xUpdateCallback && HasRowid(pTab) ){
 83742        db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
 83743            pC->movetoTarget);
 83744        assert( pC->iDb>=0 );
 83745      }
 83746    }
 83747  
 83748    break;
 83749  }
 83750  /* Opcode: ResetCount * * * * *
 83751  **
 83752  ** The value of the change counter is copied to the database handle
 83753  ** change counter (returned by subsequent calls to sqlite3_changes()).
 83754  ** Then the VMs internal change counter resets to 0.
 83755  ** This is used by trigger programs.
 83756  */
 83757  case OP_ResetCount: {
 83758    sqlite3VdbeSetChanges(db, p->nChange);
 83759    p->nChange = 0;
 83760    break;
 83761  }
 83762  
 83763  /* Opcode: SorterCompare P1 P2 P3 P4
 83764  ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
 83765  **
 83766  ** P1 is a sorter cursor. This instruction compares a prefix of the
 83767  ** record blob in register P3 against a prefix of the entry that 
 83768  ** the sorter cursor currently points to.  Only the first P4 fields
 83769  ** of r[P3] and the sorter record are compared.
 83770  **
 83771  ** If either P3 or the sorter contains a NULL in one of their significant
 83772  ** fields (not counting the P4 fields at the end which are ignored) then
 83773  ** the comparison is assumed to be equal.
 83774  **
 83775  ** Fall through to next instruction if the two records compare equal to
 83776  ** each other.  Jump to P2 if they are different.
 83777  */
 83778  case OP_SorterCompare: {
 83779    VdbeCursor *pC;
 83780    int res;
 83781    int nKeyCol;
 83782  
 83783    pC = p->apCsr[pOp->p1];
 83784    assert( isSorter(pC) );
 83785    assert( pOp->p4type==P4_INT32 );
 83786    pIn3 = &aMem[pOp->p3];
 83787    nKeyCol = pOp->p4.i;
 83788    res = 0;
 83789    rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
 83790    VdbeBranchTaken(res!=0,2);
 83791    if( rc ) goto abort_due_to_error;
 83792    if( res ) goto jump_to_p2;
 83793    break;
 83794  };
 83795  
 83796  /* Opcode: SorterData P1 P2 P3 * *
 83797  ** Synopsis: r[P2]=data
 83798  **
 83799  ** Write into register P2 the current sorter data for sorter cursor P1.
 83800  ** Then clear the column header cache on cursor P3.
 83801  **
 83802  ** This opcode is normally use to move a record out of the sorter and into
 83803  ** a register that is the source for a pseudo-table cursor created using
 83804  ** OpenPseudo.  That pseudo-table cursor is the one that is identified by
 83805  ** parameter P3.  Clearing the P3 column cache as part of this opcode saves
 83806  ** us from having to issue a separate NullRow instruction to clear that cache.
 83807  */
 83808  case OP_SorterData: {
 83809    VdbeCursor *pC;
 83810  
 83811    pOut = &aMem[pOp->p2];
 83812    pC = p->apCsr[pOp->p1];
 83813    assert( isSorter(pC) );
 83814    rc = sqlite3VdbeSorterRowkey(pC, pOut);
 83815    assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
 83816    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 83817    if( rc ) goto abort_due_to_error;
 83818    p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
 83819    break;
 83820  }
 83821  
 83822  /* Opcode: RowData P1 P2 P3 * *
 83823  ** Synopsis: r[P2]=data
 83824  **
 83825  ** Write into register P2 the complete row content for the row at 
 83826  ** which cursor P1 is currently pointing.
 83827  ** There is no interpretation of the data.  
 83828  ** It is just copied onto the P2 register exactly as 
 83829  ** it is found in the database file.
 83830  **
 83831  ** If cursor P1 is an index, then the content is the key of the row.
 83832  ** If cursor P2 is a table, then the content extracted is the data.
 83833  **
 83834  ** If the P1 cursor must be pointing to a valid row (not a NULL row)
 83835  ** of a real table, not a pseudo-table.
 83836  **
 83837  ** If P3!=0 then this opcode is allowed to make an ephermeral pointer
 83838  ** into the database page.  That means that the content of the output
 83839  ** register will be invalidated as soon as the cursor moves - including
 83840  ** moves caused by other cursors that "save" the the current cursors
 83841  ** position in order that they can write to the same table.  If P3==0
 83842  ** then a copy of the data is made into memory.  P3!=0 is faster, but
 83843  ** P3==0 is safer.
 83844  **
 83845  ** If P3!=0 then the content of the P2 register is unsuitable for use
 83846  ** in OP_Result and any OP_Result will invalidate the P2 register content.
 83847  ** The P2 register content is invalidated by opcodes like OP_Function or
 83848  ** by any use of another cursor pointing to the same table.
 83849  */
 83850  case OP_RowData: {
 83851    VdbeCursor *pC;
 83852    BtCursor *pCrsr;
 83853    u32 n;
 83854  
 83855    pOut = out2Prerelease(p, pOp);
 83856  
 83857    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 83858    pC = p->apCsr[pOp->p1];
 83859    assert( pC!=0 );
 83860    assert( pC->eCurType==CURTYPE_BTREE );
 83861    assert( isSorter(pC)==0 );
 83862    assert( pC->nullRow==0 );
 83863    assert( pC->uc.pCursor!=0 );
 83864    pCrsr = pC->uc.pCursor;
 83865  
 83866    /* The OP_RowData opcodes always follow OP_NotExists or
 83867    ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
 83868    ** that might invalidate the cursor.
 83869    ** If this where not the case, on of the following assert()s
 83870    ** would fail.  Should this ever change (because of changes in the code
 83871    ** generator) then the fix would be to insert a call to
 83872    ** sqlite3VdbeCursorMoveto().
 83873    */
 83874    assert( pC->deferredMoveto==0 );
 83875    assert( sqlite3BtreeCursorIsValid(pCrsr) );
 83876  #if 0  /* Not required due to the previous to assert() statements */
 83877    rc = sqlite3VdbeCursorMoveto(pC);
 83878    if( rc!=SQLITE_OK ) goto abort_due_to_error;
 83879  #endif
 83880  
 83881    n = sqlite3BtreePayloadSize(pCrsr);
 83882    if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
 83883      goto too_big;
 83884    }
 83885    testcase( n==0 );
 83886    rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut);
 83887    if( rc ) goto abort_due_to_error;
 83888    if( !pOp->p3 ) Deephemeralize(pOut);
 83889    UPDATE_MAX_BLOBSIZE(pOut);
 83890    REGISTER_TRACE(pOp->p2, pOut);
 83891    break;
 83892  }
 83893  
 83894  /* Opcode: Rowid P1 P2 * * *
 83895  ** Synopsis: r[P2]=rowid
 83896  **
 83897  ** Store in register P2 an integer which is the key of the table entry that
 83898  ** P1 is currently point to.
 83899  **
 83900  ** P1 can be either an ordinary table or a virtual table.  There used to
 83901  ** be a separate OP_VRowid opcode for use with virtual tables, but this
 83902  ** one opcode now works for both table types.
 83903  */
 83904  case OP_Rowid: {                 /* out2 */
 83905    VdbeCursor *pC;
 83906    i64 v;
 83907    sqlite3_vtab *pVtab;
 83908    const sqlite3_module *pModule;
 83909  
 83910    pOut = out2Prerelease(p, pOp);
 83911    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 83912    pC = p->apCsr[pOp->p1];
 83913    assert( pC!=0 );
 83914    assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
 83915    if( pC->nullRow ){
 83916      pOut->flags = MEM_Null;
 83917      break;
 83918    }else if( pC->deferredMoveto ){
 83919      v = pC->movetoTarget;
 83920  #ifndef SQLITE_OMIT_VIRTUALTABLE
 83921    }else if( pC->eCurType==CURTYPE_VTAB ){
 83922      assert( pC->uc.pVCur!=0 );
 83923      pVtab = pC->uc.pVCur->pVtab;
 83924      pModule = pVtab->pModule;
 83925      assert( pModule->xRowid );
 83926      rc = pModule->xRowid(pC->uc.pVCur, &v);
 83927      sqlite3VtabImportErrmsg(p, pVtab);
 83928      if( rc ) goto abort_due_to_error;
 83929  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 83930    }else{
 83931      assert( pC->eCurType==CURTYPE_BTREE );
 83932      assert( pC->uc.pCursor!=0 );
 83933      rc = sqlite3VdbeCursorRestore(pC);
 83934      if( rc ) goto abort_due_to_error;
 83935      if( pC->nullRow ){
 83936        pOut->flags = MEM_Null;
 83937        break;
 83938      }
 83939      v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
 83940    }
 83941    pOut->u.i = v;
 83942    break;
 83943  }
 83944  
 83945  /* Opcode: NullRow P1 * * * *
 83946  **
 83947  ** Move the cursor P1 to a null row.  Any OP_Column operations
 83948  ** that occur while the cursor is on the null row will always
 83949  ** write a NULL.
 83950  */
 83951  case OP_NullRow: {
 83952    VdbeCursor *pC;
 83953  
 83954    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 83955    pC = p->apCsr[pOp->p1];
 83956    assert( pC!=0 );
 83957    pC->nullRow = 1;
 83958    pC->cacheStatus = CACHE_STALE;
 83959    if( pC->eCurType==CURTYPE_BTREE ){
 83960      assert( pC->uc.pCursor!=0 );
 83961      sqlite3BtreeClearCursor(pC->uc.pCursor);
 83962    }
 83963    break;
 83964  }
 83965  
 83966  /* Opcode: SeekEnd P1 * * * *
 83967  **
 83968  ** Position cursor P1 at the end of the btree for the purpose of
 83969  ** appending a new entry onto the btree.
 83970  **
 83971  ** It is assumed that the cursor is used only for appending and so
 83972  ** if the cursor is valid, then the cursor must already be pointing
 83973  ** at the end of the btree and so no changes are made to
 83974  ** the cursor.
 83975  */
 83976  /* Opcode: Last P1 P2 * * *
 83977  **
 83978  ** The next use of the Rowid or Column or Prev instruction for P1 
 83979  ** will refer to the last entry in the database table or index.
 83980  ** If the table or index is empty and P2>0, then jump immediately to P2.
 83981  ** If P2 is 0 or if the table or index is not empty, fall through
 83982  ** to the following instruction.
 83983  **
 83984  ** This opcode leaves the cursor configured to move in reverse order,
 83985  ** from the end toward the beginning.  In other words, the cursor is
 83986  ** configured to use Prev, not Next.
 83987  */
 83988  case OP_SeekEnd:
 83989  case OP_Last: {        /* jump */
 83990    VdbeCursor *pC;
 83991    BtCursor *pCrsr;
 83992    int res;
 83993  
 83994    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 83995    pC = p->apCsr[pOp->p1];
 83996    assert( pC!=0 );
 83997    assert( pC->eCurType==CURTYPE_BTREE );
 83998    pCrsr = pC->uc.pCursor;
 83999    res = 0;
 84000    assert( pCrsr!=0 );
 84001  #ifdef SQLITE_DEBUG
 84002    pC->seekOp = pOp->opcode;
 84003  #endif
 84004    if( pOp->opcode==OP_SeekEnd ){
 84005      assert( pOp->p2==0 );
 84006      pC->seekResult = -1;
 84007      if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
 84008        break;
 84009      }
 84010    }
 84011    rc = sqlite3BtreeLast(pCrsr, &res);
 84012    pC->nullRow = (u8)res;
 84013    pC->deferredMoveto = 0;
 84014    pC->cacheStatus = CACHE_STALE;
 84015    if( rc ) goto abort_due_to_error;
 84016    if( pOp->p2>0 ){
 84017      VdbeBranchTaken(res!=0,2);
 84018      if( res ) goto jump_to_p2;
 84019    }
 84020    break;
 84021  }
 84022  
 84023  /* Opcode: IfSmaller P1 P2 P3 * *
 84024  **
 84025  ** Estimate the number of rows in the table P1.  Jump to P2 if that
 84026  ** estimate is less than approximately 2**(0.1*P3).
 84027  */
 84028  case OP_IfSmaller: {        /* jump */
 84029    VdbeCursor *pC;
 84030    BtCursor *pCrsr;
 84031    int res;
 84032    i64 sz;
 84033  
 84034    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 84035    pC = p->apCsr[pOp->p1];
 84036    assert( pC!=0 );
 84037    pCrsr = pC->uc.pCursor;
 84038    assert( pCrsr );
 84039    rc = sqlite3BtreeFirst(pCrsr, &res);
 84040    if( rc ) goto abort_due_to_error;
 84041    if( res==0 ){
 84042      sz = sqlite3BtreeRowCountEst(pCrsr);
 84043      if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
 84044    }
 84045    VdbeBranchTaken(res!=0,2);
 84046    if( res ) goto jump_to_p2;
 84047    break;
 84048  }
 84049  
 84050  
 84051  /* Opcode: SorterSort P1 P2 * * *
 84052  **
 84053  ** After all records have been inserted into the Sorter object
 84054  ** identified by P1, invoke this opcode to actually do the sorting.
 84055  ** Jump to P2 if there are no records to be sorted.
 84056  **
 84057  ** This opcode is an alias for OP_Sort and OP_Rewind that is used
 84058  ** for Sorter objects.
 84059  */
 84060  /* Opcode: Sort P1 P2 * * *
 84061  **
 84062  ** This opcode does exactly the same thing as OP_Rewind except that
 84063  ** it increments an undocumented global variable used for testing.
 84064  **
 84065  ** Sorting is accomplished by writing records into a sorting index,
 84066  ** then rewinding that index and playing it back from beginning to
 84067  ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
 84068  ** rewinding so that the global variable will be incremented and
 84069  ** regression tests can determine whether or not the optimizer is
 84070  ** correctly optimizing out sorts.
 84071  */
 84072  case OP_SorterSort:    /* jump */
 84073  case OP_Sort: {        /* jump */
 84074  #ifdef SQLITE_TEST
 84075    sqlite3_sort_count++;
 84076    sqlite3_search_count--;
 84077  #endif
 84078    p->aCounter[SQLITE_STMTSTATUS_SORT]++;
 84079    /* Fall through into OP_Rewind */
 84080  }
 84081  /* Opcode: Rewind P1 P2 * * *
 84082  **
 84083  ** The next use of the Rowid or Column or Next instruction for P1 
 84084  ** will refer to the first entry in the database table or index.
 84085  ** If the table or index is empty, jump immediately to P2.
 84086  ** If the table or index is not empty, fall through to the following 
 84087  ** instruction.
 84088  **
 84089  ** This opcode leaves the cursor configured to move in forward order,
 84090  ** from the beginning toward the end.  In other words, the cursor is
 84091  ** configured to use Next, not Prev.
 84092  */
 84093  case OP_Rewind: {        /* jump */
 84094    VdbeCursor *pC;
 84095    BtCursor *pCrsr;
 84096    int res;
 84097  
 84098    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 84099    pC = p->apCsr[pOp->p1];
 84100    assert( pC!=0 );
 84101    assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
 84102    res = 1;
 84103  #ifdef SQLITE_DEBUG
 84104    pC->seekOp = OP_Rewind;
 84105  #endif
 84106    if( isSorter(pC) ){
 84107      rc = sqlite3VdbeSorterRewind(pC, &res);
 84108    }else{
 84109      assert( pC->eCurType==CURTYPE_BTREE );
 84110      pCrsr = pC->uc.pCursor;
 84111      assert( pCrsr );
 84112      rc = sqlite3BtreeFirst(pCrsr, &res);
 84113      pC->deferredMoveto = 0;
 84114      pC->cacheStatus = CACHE_STALE;
 84115    }
 84116    if( rc ) goto abort_due_to_error;
 84117    pC->nullRow = (u8)res;
 84118    assert( pOp->p2>0 && pOp->p2<p->nOp );
 84119    VdbeBranchTaken(res!=0,2);
 84120    if( res ) goto jump_to_p2;
 84121    break;
 84122  }
 84123  
 84124  /* Opcode: Next P1 P2 P3 P4 P5
 84125  **
 84126  ** Advance cursor P1 so that it points to the next key/data pair in its
 84127  ** table or index.  If there are no more key/value pairs then fall through
 84128  ** to the following instruction.  But if the cursor advance was successful,
 84129  ** jump immediately to P2.
 84130  **
 84131  ** The Next opcode is only valid following an SeekGT, SeekGE, or
 84132  ** OP_Rewind opcode used to position the cursor.  Next is not allowed
 84133  ** to follow SeekLT, SeekLE, or OP_Last.
 84134  **
 84135  ** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
 84136  ** been opened prior to this opcode or the program will segfault.
 84137  **
 84138  ** The P3 value is a hint to the btree implementation. If P3==1, that
 84139  ** means P1 is an SQL index and that this instruction could have been
 84140  ** omitted if that index had been unique.  P3 is usually 0.  P3 is
 84141  ** always either 0 or 1.
 84142  **
 84143  ** P4 is always of type P4_ADVANCE. The function pointer points to
 84144  ** sqlite3BtreeNext().
 84145  **
 84146  ** If P5 is positive and the jump is taken, then event counter
 84147  ** number P5-1 in the prepared statement is incremented.
 84148  **
 84149  ** See also: Prev, NextIfOpen
 84150  */
 84151  /* Opcode: NextIfOpen P1 P2 P3 P4 P5
 84152  **
 84153  ** This opcode works just like Next except that if cursor P1 is not
 84154  ** open it behaves a no-op.
 84155  */
 84156  /* Opcode: Prev P1 P2 P3 P4 P5
 84157  **
 84158  ** Back up cursor P1 so that it points to the previous key/data pair in its
 84159  ** table or index.  If there is no previous key/value pairs then fall through
 84160  ** to the following instruction.  But if the cursor backup was successful,
 84161  ** jump immediately to P2.
 84162  **
 84163  **
 84164  ** The Prev opcode is only valid following an SeekLT, SeekLE, or
 84165  ** OP_Last opcode used to position the cursor.  Prev is not allowed
 84166  ** to follow SeekGT, SeekGE, or OP_Rewind.
 84167  **
 84168  ** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
 84169  ** not open then the behavior is undefined.
 84170  **
 84171  ** The P3 value is a hint to the btree implementation. If P3==1, that
 84172  ** means P1 is an SQL index and that this instruction could have been
 84173  ** omitted if that index had been unique.  P3 is usually 0.  P3 is
 84174  ** always either 0 or 1.
 84175  **
 84176  ** P4 is always of type P4_ADVANCE. The function pointer points to
 84177  ** sqlite3BtreePrevious().
 84178  **
 84179  ** If P5 is positive and the jump is taken, then event counter
 84180  ** number P5-1 in the prepared statement is incremented.
 84181  */
 84182  /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
 84183  **
 84184  ** This opcode works just like Prev except that if cursor P1 is not
 84185  ** open it behaves a no-op.
 84186  */
 84187  /* Opcode: SorterNext P1 P2 * * P5
 84188  **
 84189  ** This opcode works just like OP_Next except that P1 must be a
 84190  ** sorter object for which the OP_SorterSort opcode has been
 84191  ** invoked.  This opcode advances the cursor to the next sorted
 84192  ** record, or jumps to P2 if there are no more sorted records.
 84193  */
 84194  case OP_SorterNext: {  /* jump */
 84195    VdbeCursor *pC;
 84196  
 84197    pC = p->apCsr[pOp->p1];
 84198    assert( isSorter(pC) );
 84199    rc = sqlite3VdbeSorterNext(db, pC);
 84200    goto next_tail;
 84201  case OP_PrevIfOpen:    /* jump */
 84202  case OP_NextIfOpen:    /* jump */
 84203    if( p->apCsr[pOp->p1]==0 ) break;
 84204    /* Fall through */
 84205  case OP_Prev:          /* jump */
 84206  case OP_Next:          /* jump */
 84207    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 84208    assert( pOp->p5<ArraySize(p->aCounter) );
 84209    pC = p->apCsr[pOp->p1];
 84210    assert( pC!=0 );
 84211    assert( pC->deferredMoveto==0 );
 84212    assert( pC->eCurType==CURTYPE_BTREE );
 84213    assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
 84214    assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
 84215    assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
 84216    assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
 84217  
 84218    /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
 84219    ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
 84220    assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
 84221         || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
 84222         || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
 84223    assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
 84224         || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
 84225         || pC->seekOp==OP_Last );
 84226  
 84227    rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
 84228  next_tail:
 84229    pC->cacheStatus = CACHE_STALE;
 84230    VdbeBranchTaken(rc==SQLITE_OK,2);
 84231    if( rc==SQLITE_OK ){
 84232      pC->nullRow = 0;
 84233      p->aCounter[pOp->p5]++;
 84234  #ifdef SQLITE_TEST
 84235      sqlite3_search_count++;
 84236  #endif
 84237      goto jump_to_p2_and_check_for_interrupt;
 84238    }
 84239    if( rc!=SQLITE_DONE ) goto abort_due_to_error;
 84240    rc = SQLITE_OK;
 84241    pC->nullRow = 1;
 84242    goto check_for_interrupt;
 84243  }
 84244  
 84245  /* Opcode: IdxInsert P1 P2 P3 P4 P5
 84246  ** Synopsis: key=r[P2]
 84247  **
 84248  ** Register P2 holds an SQL index key made using the
 84249  ** MakeRecord instructions.  This opcode writes that key
 84250  ** into the index P1.  Data for the entry is nil.
 84251  **
 84252  ** If P4 is not zero, then it is the number of values in the unpacked
 84253  ** key of reg(P2).  In that case, P3 is the index of the first register
 84254  ** for the unpacked key.  The availability of the unpacked key can sometimes
 84255  ** be an optimization.
 84256  **
 84257  ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
 84258  ** that this insert is likely to be an append.
 84259  **
 84260  ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
 84261  ** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
 84262  ** then the change counter is unchanged.
 84263  **
 84264  ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
 84265  ** run faster by avoiding an unnecessary seek on cursor P1.  However,
 84266  ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
 84267  ** seeks on the cursor or if the most recent seek used a key equivalent
 84268  ** to P2. 
 84269  **
 84270  ** This instruction only works for indices.  The equivalent instruction
 84271  ** for tables is OP_Insert.
 84272  */
 84273  /* Opcode: SorterInsert P1 P2 * * *
 84274  ** Synopsis: key=r[P2]
 84275  **
 84276  ** Register P2 holds an SQL index key made using the
 84277  ** MakeRecord instructions.  This opcode writes that key
 84278  ** into the sorter P1.  Data for the entry is nil.
 84279  */
 84280  case OP_SorterInsert:       /* in2 */
 84281  case OP_IdxInsert: {        /* in2 */
 84282    VdbeCursor *pC;
 84283    BtreePayload x;
 84284  
 84285    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 84286    pC = p->apCsr[pOp->p1];
 84287    assert( pC!=0 );
 84288    assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
 84289    pIn2 = &aMem[pOp->p2];
 84290    assert( pIn2->flags & MEM_Blob );
 84291    if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
 84292    assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
 84293    assert( pC->isTable==0 );
 84294    rc = ExpandBlob(pIn2);
 84295    if( rc ) goto abort_due_to_error;
 84296    if( pOp->opcode==OP_SorterInsert ){
 84297      rc = sqlite3VdbeSorterWrite(pC, pIn2);
 84298    }else{
 84299      x.nKey = pIn2->n;
 84300      x.pKey = pIn2->z;
 84301      x.aMem = aMem + pOp->p3;
 84302      x.nMem = (u16)pOp->p4.i;
 84303      rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
 84304           (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), 
 84305          ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
 84306          );
 84307      assert( pC->deferredMoveto==0 );
 84308      pC->cacheStatus = CACHE_STALE;
 84309    }
 84310    if( rc) goto abort_due_to_error;
 84311    break;
 84312  }
 84313  
 84314  /* Opcode: IdxDelete P1 P2 P3 * *
 84315  ** Synopsis: key=r[P2@P3]
 84316  **
 84317  ** The content of P3 registers starting at register P2 form
 84318  ** an unpacked index key. This opcode removes that entry from the 
 84319  ** index opened by cursor P1.
 84320  */
 84321  case OP_IdxDelete: {
 84322    VdbeCursor *pC;
 84323    BtCursor *pCrsr;
 84324    int res;
 84325    UnpackedRecord r;
 84326  
 84327    assert( pOp->p3>0 );
 84328    assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
 84329    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 84330    pC = p->apCsr[pOp->p1];
 84331    assert( pC!=0 );
 84332    assert( pC->eCurType==CURTYPE_BTREE );
 84333    pCrsr = pC->uc.pCursor;
 84334    assert( pCrsr!=0 );
 84335    assert( pOp->p5==0 );
 84336    r.pKeyInfo = pC->pKeyInfo;
 84337    r.nField = (u16)pOp->p3;
 84338    r.default_rc = 0;
 84339    r.aMem = &aMem[pOp->p2];
 84340    rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
 84341    if( rc ) goto abort_due_to_error;
 84342    if( res==0 ){
 84343      rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
 84344      if( rc ) goto abort_due_to_error;
 84345    }
 84346    assert( pC->deferredMoveto==0 );
 84347    pC->cacheStatus = CACHE_STALE;
 84348    pC->seekResult = 0;
 84349    break;
 84350  }
 84351  
 84352  /* Opcode: DeferredSeek P1 * P3 P4 *
 84353  ** Synopsis: Move P3 to P1.rowid if needed
 84354  **
 84355  ** P1 is an open index cursor and P3 is a cursor on the corresponding
 84356  ** table.  This opcode does a deferred seek of the P3 table cursor
 84357  ** to the row that corresponds to the current row of P1.
 84358  **
 84359  ** This is a deferred seek.  Nothing actually happens until
 84360  ** the cursor is used to read a record.  That way, if no reads
 84361  ** occur, no unnecessary I/O happens.
 84362  **
 84363  ** P4 may be an array of integers (type P4_INTARRAY) containing
 84364  ** one entry for each column in the P3 table.  If array entry a(i)
 84365  ** is non-zero, then reading column a(i)-1 from cursor P3 is 
 84366  ** equivalent to performing the deferred seek and then reading column i 
 84367  ** from P1.  This information is stored in P3 and used to redirect
 84368  ** reads against P3 over to P1, thus possibly avoiding the need to
 84369  ** seek and read cursor P3.
 84370  */
 84371  /* Opcode: IdxRowid P1 P2 * * *
 84372  ** Synopsis: r[P2]=rowid
 84373  **
 84374  ** Write into register P2 an integer which is the last entry in the record at
 84375  ** the end of the index key pointed to by cursor P1.  This integer should be
 84376  ** the rowid of the table entry to which this index entry points.
 84377  **
 84378  ** See also: Rowid, MakeRecord.
 84379  */
 84380  case OP_DeferredSeek:
 84381  case OP_IdxRowid: {           /* out2 */
 84382    VdbeCursor *pC;             /* The P1 index cursor */
 84383    VdbeCursor *pTabCur;        /* The P2 table cursor (OP_DeferredSeek only) */
 84384    i64 rowid;                  /* Rowid that P1 current points to */
 84385  
 84386    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 84387    pC = p->apCsr[pOp->p1];
 84388    assert( pC!=0 );
 84389    assert( pC->eCurType==CURTYPE_BTREE );
 84390    assert( pC->uc.pCursor!=0 );
 84391    assert( pC->isTable==0 );
 84392    assert( pC->deferredMoveto==0 );
 84393    assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
 84394  
 84395    /* The IdxRowid and Seek opcodes are combined because of the commonality
 84396    ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
 84397    rc = sqlite3VdbeCursorRestore(pC);
 84398  
 84399    /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
 84400    ** out from under the cursor.  That will never happens for an IdxRowid
 84401    ** or Seek opcode */
 84402    if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
 84403  
 84404    if( !pC->nullRow ){
 84405      rowid = 0;  /* Not needed.  Only used to silence a warning. */
 84406      rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
 84407      if( rc!=SQLITE_OK ){
 84408        goto abort_due_to_error;
 84409      }
 84410      if( pOp->opcode==OP_DeferredSeek ){
 84411        assert( pOp->p3>=0 && pOp->p3<p->nCursor );
 84412        pTabCur = p->apCsr[pOp->p3];
 84413        assert( pTabCur!=0 );
 84414        assert( pTabCur->eCurType==CURTYPE_BTREE );
 84415        assert( pTabCur->uc.pCursor!=0 );
 84416        assert( pTabCur->isTable );
 84417        pTabCur->nullRow = 0;
 84418        pTabCur->movetoTarget = rowid;
 84419        pTabCur->deferredMoveto = 1;
 84420        assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
 84421        pTabCur->aAltMap = pOp->p4.ai;
 84422        pTabCur->pAltCursor = pC;
 84423      }else{
 84424        pOut = out2Prerelease(p, pOp);
 84425        pOut->u.i = rowid;
 84426      }
 84427    }else{
 84428      assert( pOp->opcode==OP_IdxRowid );
 84429      sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
 84430    }
 84431    break;
 84432  }
 84433  
 84434  /* Opcode: IdxGE P1 P2 P3 P4 P5
 84435  ** Synopsis: key=r[P3@P4]
 84436  **
 84437  ** The P4 register values beginning with P3 form an unpacked index 
 84438  ** key that omits the PRIMARY KEY.  Compare this key value against the index 
 84439  ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID 
 84440  ** fields at the end.
 84441  **
 84442  ** If the P1 index entry is greater than or equal to the key value
 84443  ** then jump to P2.  Otherwise fall through to the next instruction.
 84444  */
 84445  /* Opcode: IdxGT P1 P2 P3 P4 P5
 84446  ** Synopsis: key=r[P3@P4]
 84447  **
 84448  ** The P4 register values beginning with P3 form an unpacked index 
 84449  ** key that omits the PRIMARY KEY.  Compare this key value against the index 
 84450  ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID 
 84451  ** fields at the end.
 84452  **
 84453  ** If the P1 index entry is greater than the key value
 84454  ** then jump to P2.  Otherwise fall through to the next instruction.
 84455  */
 84456  /* Opcode: IdxLT P1 P2 P3 P4 P5
 84457  ** Synopsis: key=r[P3@P4]
 84458  **
 84459  ** The P4 register values beginning with P3 form an unpacked index 
 84460  ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
 84461  ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
 84462  ** ROWID on the P1 index.
 84463  **
 84464  ** If the P1 index entry is less than the key value then jump to P2.
 84465  ** Otherwise fall through to the next instruction.
 84466  */
 84467  /* Opcode: IdxLE P1 P2 P3 P4 P5
 84468  ** Synopsis: key=r[P3@P4]
 84469  **
 84470  ** The P4 register values beginning with P3 form an unpacked index 
 84471  ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
 84472  ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
 84473  ** ROWID on the P1 index.
 84474  **
 84475  ** If the P1 index entry is less than or equal to the key value then jump
 84476  ** to P2. Otherwise fall through to the next instruction.
 84477  */
 84478  case OP_IdxLE:          /* jump */
 84479  case OP_IdxGT:          /* jump */
 84480  case OP_IdxLT:          /* jump */
 84481  case OP_IdxGE:  {       /* jump */
 84482    VdbeCursor *pC;
 84483    int res;
 84484    UnpackedRecord r;
 84485  
 84486    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 84487    pC = p->apCsr[pOp->p1];
 84488    assert( pC!=0 );
 84489    assert( pC->isOrdered );
 84490    assert( pC->eCurType==CURTYPE_BTREE );
 84491    assert( pC->uc.pCursor!=0);
 84492    assert( pC->deferredMoveto==0 );
 84493    assert( pOp->p5==0 || pOp->p5==1 );
 84494    assert( pOp->p4type==P4_INT32 );
 84495    r.pKeyInfo = pC->pKeyInfo;
 84496    r.nField = (u16)pOp->p4.i;
 84497    if( pOp->opcode<OP_IdxLT ){
 84498      assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
 84499      r.default_rc = -1;
 84500    }else{
 84501      assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
 84502      r.default_rc = 0;
 84503    }
 84504    r.aMem = &aMem[pOp->p3];
 84505  #ifdef SQLITE_DEBUG
 84506    { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
 84507  #endif
 84508    res = 0;  /* Not needed.  Only used to silence a warning. */
 84509    rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
 84510    assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
 84511    if( (pOp->opcode&1)==(OP_IdxLT&1) ){
 84512      assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
 84513      res = -res;
 84514    }else{
 84515      assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
 84516      res++;
 84517    }
 84518    VdbeBranchTaken(res>0,2);
 84519    if( rc ) goto abort_due_to_error;
 84520    if( res>0 ) goto jump_to_p2;
 84521    break;
 84522  }
 84523  
 84524  /* Opcode: Destroy P1 P2 P3 * *
 84525  **
 84526  ** Delete an entire database table or index whose root page in the database
 84527  ** file is given by P1.
 84528  **
 84529  ** The table being destroyed is in the main database file if P3==0.  If
 84530  ** P3==1 then the table to be clear is in the auxiliary database file
 84531  ** that is used to store tables create using CREATE TEMPORARY TABLE.
 84532  **
 84533  ** If AUTOVACUUM is enabled then it is possible that another root page
 84534  ** might be moved into the newly deleted root page in order to keep all
 84535  ** root pages contiguous at the beginning of the database.  The former
 84536  ** value of the root page that moved - its value before the move occurred -
 84537  ** is stored in register P2. If no page movement was required (because the
 84538  ** table being dropped was already the last one in the database) then a 
 84539  ** zero is stored in register P2.  If AUTOVACUUM is disabled then a zero 
 84540  ** is stored in register P2.
 84541  **
 84542  ** This opcode throws an error if there are any active reader VMs when
 84543  ** it is invoked. This is done to avoid the difficulty associated with 
 84544  ** updating existing cursors when a root page is moved in an AUTOVACUUM 
 84545  ** database. This error is thrown even if the database is not an AUTOVACUUM 
 84546  ** db in order to avoid introducing an incompatibility between autovacuum 
 84547  ** and non-autovacuum modes.
 84548  **
 84549  ** See also: Clear
 84550  */
 84551  case OP_Destroy: {     /* out2 */
 84552    int iMoved;
 84553    int iDb;
 84554  
 84555    assert( p->readOnly==0 );
 84556    assert( pOp->p1>1 );
 84557    pOut = out2Prerelease(p, pOp);
 84558    pOut->flags = MEM_Null;
 84559    if( db->nVdbeRead > db->nVDestroy+1 ){
 84560      rc = SQLITE_LOCKED;
 84561      p->errorAction = OE_Abort;
 84562      goto abort_due_to_error;
 84563    }else{
 84564      iDb = pOp->p3;
 84565      assert( DbMaskTest(p->btreeMask, iDb) );
 84566      iMoved = 0;  /* Not needed.  Only to silence a warning. */
 84567      rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
 84568      pOut->flags = MEM_Int;
 84569      pOut->u.i = iMoved;
 84570      if( rc ) goto abort_due_to_error;
 84571  #ifndef SQLITE_OMIT_AUTOVACUUM
 84572      if( iMoved!=0 ){
 84573        sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
 84574        /* All OP_Destroy operations occur on the same btree */
 84575        assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
 84576        resetSchemaOnFault = iDb+1;
 84577      }
 84578  #endif
 84579    }
 84580    break;
 84581  }
 84582  
 84583  /* Opcode: Clear P1 P2 P3
 84584  **
 84585  ** Delete all contents of the database table or index whose root page
 84586  ** in the database file is given by P1.  But, unlike Destroy, do not
 84587  ** remove the table or index from the database file.
 84588  **
 84589  ** The table being clear is in the main database file if P2==0.  If
 84590  ** P2==1 then the table to be clear is in the auxiliary database file
 84591  ** that is used to store tables create using CREATE TEMPORARY TABLE.
 84592  **
 84593  ** If the P3 value is non-zero, then the table referred to must be an
 84594  ** intkey table (an SQL table, not an index). In this case the row change 
 84595  ** count is incremented by the number of rows in the table being cleared. 
 84596  ** If P3 is greater than zero, then the value stored in register P3 is
 84597  ** also incremented by the number of rows in the table being cleared.
 84598  **
 84599  ** See also: Destroy
 84600  */
 84601  case OP_Clear: {
 84602    int nChange;
 84603   
 84604    nChange = 0;
 84605    assert( p->readOnly==0 );
 84606    assert( DbMaskTest(p->btreeMask, pOp->p2) );
 84607    rc = sqlite3BtreeClearTable(
 84608        db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
 84609    );
 84610    if( pOp->p3 ){
 84611      p->nChange += nChange;
 84612      if( pOp->p3>0 ){
 84613        assert( memIsValid(&aMem[pOp->p3]) );
 84614        memAboutToChange(p, &aMem[pOp->p3]);
 84615        aMem[pOp->p3].u.i += nChange;
 84616      }
 84617    }
 84618    if( rc ) goto abort_due_to_error;
 84619    break;
 84620  }
 84621  
 84622  /* Opcode: ResetSorter P1 * * * *
 84623  **
 84624  ** Delete all contents from the ephemeral table or sorter
 84625  ** that is open on cursor P1.
 84626  **
 84627  ** This opcode only works for cursors used for sorting and
 84628  ** opened with OP_OpenEphemeral or OP_SorterOpen.
 84629  */
 84630  case OP_ResetSorter: {
 84631    VdbeCursor *pC;
 84632   
 84633    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 84634    pC = p->apCsr[pOp->p1];
 84635    assert( pC!=0 );
 84636    if( isSorter(pC) ){
 84637      sqlite3VdbeSorterReset(db, pC->uc.pSorter);
 84638    }else{
 84639      assert( pC->eCurType==CURTYPE_BTREE );
 84640      assert( pC->isEphemeral );
 84641      rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
 84642      if( rc ) goto abort_due_to_error;
 84643    }
 84644    break;
 84645  }
 84646  
 84647  /* Opcode: CreateBtree P1 P2 P3 * *
 84648  ** Synopsis: r[P2]=root iDb=P1 flags=P3
 84649  **
 84650  ** Allocate a new b-tree in the main database file if P1==0 or in the
 84651  ** TEMP database file if P1==1 or in an attached database if
 84652  ** P1>1.  The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
 84653  ** it must be 2 (BTREE_BLOBKEY) for a index or WITHOUT ROWID table.
 84654  ** The root page number of the new b-tree is stored in register P2.
 84655  */
 84656  case OP_CreateBtree: {          /* out2 */
 84657    int pgno;
 84658    Db *pDb;
 84659  
 84660    pOut = out2Prerelease(p, pOp);
 84661    pgno = 0;
 84662    assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
 84663    assert( pOp->p1>=0 && pOp->p1<db->nDb );
 84664    assert( DbMaskTest(p->btreeMask, pOp->p1) );
 84665    assert( p->readOnly==0 );
 84666    pDb = &db->aDb[pOp->p1];
 84667    assert( pDb->pBt!=0 );
 84668    rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
 84669    if( rc ) goto abort_due_to_error;
 84670    pOut->u.i = pgno;
 84671    break;
 84672  }
 84673  
 84674  /* Opcode: SqlExec * * * P4 *
 84675  **
 84676  ** Run the SQL statement or statements specified in the P4 string.
 84677  */
 84678  case OP_SqlExec: {
 84679    db->nSqlExec++;
 84680    rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
 84681    db->nSqlExec--;
 84682    if( rc ) goto abort_due_to_error;
 84683    break;
 84684  }
 84685  
 84686  /* Opcode: ParseSchema P1 * * P4 *
 84687  **
 84688  ** Read and parse all entries from the SQLITE_MASTER table of database P1
 84689  ** that match the WHERE clause P4. 
 84690  **
 84691  ** This opcode invokes the parser to create a new virtual machine,
 84692  ** then runs the new virtual machine.  It is thus a re-entrant opcode.
 84693  */
 84694  case OP_ParseSchema: {
 84695    int iDb;
 84696    const char *zMaster;
 84697    char *zSql;
 84698    InitData initData;
 84699  
 84700    /* Any prepared statement that invokes this opcode will hold mutexes
 84701    ** on every btree.  This is a prerequisite for invoking 
 84702    ** sqlite3InitCallback().
 84703    */
 84704  #ifdef SQLITE_DEBUG
 84705    for(iDb=0; iDb<db->nDb; iDb++){
 84706      assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
 84707    }
 84708  #endif
 84709  
 84710    iDb = pOp->p1;
 84711    assert( iDb>=0 && iDb<db->nDb );
 84712    assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
 84713    /* Used to be a conditional */ {
 84714      zMaster = MASTER_NAME;
 84715      initData.db = db;
 84716      initData.iDb = pOp->p1;
 84717      initData.pzErrMsg = &p->zErrMsg;
 84718      zSql = sqlite3MPrintf(db,
 84719         "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
 84720         db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
 84721      if( zSql==0 ){
 84722        rc = SQLITE_NOMEM_BKPT;
 84723      }else{
 84724        assert( db->init.busy==0 );
 84725        db->init.busy = 1;
 84726        initData.rc = SQLITE_OK;
 84727        assert( !db->mallocFailed );
 84728        rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
 84729        if( rc==SQLITE_OK ) rc = initData.rc;
 84730        sqlite3DbFreeNN(db, zSql);
 84731        db->init.busy = 0;
 84732      }
 84733    }
 84734    if( rc ){
 84735      sqlite3ResetAllSchemasOfConnection(db);
 84736      if( rc==SQLITE_NOMEM ){
 84737        goto no_mem;
 84738      }
 84739      goto abort_due_to_error;
 84740    }
 84741    break;  
 84742  }
 84743  
 84744  #if !defined(SQLITE_OMIT_ANALYZE)
 84745  /* Opcode: LoadAnalysis P1 * * * *
 84746  **
 84747  ** Read the sqlite_stat1 table for database P1 and load the content
 84748  ** of that table into the internal index hash table.  This will cause
 84749  ** the analysis to be used when preparing all subsequent queries.
 84750  */
 84751  case OP_LoadAnalysis: {
 84752    assert( pOp->p1>=0 && pOp->p1<db->nDb );
 84753    rc = sqlite3AnalysisLoad(db, pOp->p1);
 84754    if( rc ) goto abort_due_to_error;
 84755    break;  
 84756  }
 84757  #endif /* !defined(SQLITE_OMIT_ANALYZE) */
 84758  
 84759  /* Opcode: DropTable P1 * * P4 *
 84760  **
 84761  ** Remove the internal (in-memory) data structures that describe
 84762  ** the table named P4 in database P1.  This is called after a table
 84763  ** is dropped from disk (using the Destroy opcode) in order to keep 
 84764  ** the internal representation of the
 84765  ** schema consistent with what is on disk.
 84766  */
 84767  case OP_DropTable: {
 84768    sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
 84769    break;
 84770  }
 84771  
 84772  /* Opcode: DropIndex P1 * * P4 *
 84773  **
 84774  ** Remove the internal (in-memory) data structures that describe
 84775  ** the index named P4 in database P1.  This is called after an index
 84776  ** is dropped from disk (using the Destroy opcode)
 84777  ** in order to keep the internal representation of the
 84778  ** schema consistent with what is on disk.
 84779  */
 84780  case OP_DropIndex: {
 84781    sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
 84782    break;
 84783  }
 84784  
 84785  /* Opcode: DropTrigger P1 * * P4 *
 84786  **
 84787  ** Remove the internal (in-memory) data structures that describe
 84788  ** the trigger named P4 in database P1.  This is called after a trigger
 84789  ** is dropped from disk (using the Destroy opcode) in order to keep 
 84790  ** the internal representation of the
 84791  ** schema consistent with what is on disk.
 84792  */
 84793  case OP_DropTrigger: {
 84794    sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
 84795    break;
 84796  }
 84797  
 84798  
 84799  #ifndef SQLITE_OMIT_INTEGRITY_CHECK
 84800  /* Opcode: IntegrityCk P1 P2 P3 P4 P5
 84801  **
 84802  ** Do an analysis of the currently open database.  Store in
 84803  ** register P1 the text of an error message describing any problems.
 84804  ** If no problems are found, store a NULL in register P1.
 84805  **
 84806  ** The register P3 contains one less than the maximum number of allowed errors.
 84807  ** At most reg(P3) errors will be reported.
 84808  ** In other words, the analysis stops as soon as reg(P1) errors are 
 84809  ** seen.  Reg(P1) is updated with the number of errors remaining.
 84810  **
 84811  ** The root page numbers of all tables in the database are integers
 84812  ** stored in P4_INTARRAY argument.
 84813  **
 84814  ** If P5 is not zero, the check is done on the auxiliary database
 84815  ** file, not the main database file.
 84816  **
 84817  ** This opcode is used to implement the integrity_check pragma.
 84818  */
 84819  case OP_IntegrityCk: {
 84820    int nRoot;      /* Number of tables to check.  (Number of root pages.) */
 84821    int *aRoot;     /* Array of rootpage numbers for tables to be checked */
 84822    int nErr;       /* Number of errors reported */
 84823    char *z;        /* Text of the error report */
 84824    Mem *pnErr;     /* Register keeping track of errors remaining */
 84825  
 84826    assert( p->bIsReader );
 84827    nRoot = pOp->p2;
 84828    aRoot = pOp->p4.ai;
 84829    assert( nRoot>0 );
 84830    assert( aRoot[0]==nRoot );
 84831    assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
 84832    pnErr = &aMem[pOp->p3];
 84833    assert( (pnErr->flags & MEM_Int)!=0 );
 84834    assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
 84835    pIn1 = &aMem[pOp->p1];
 84836    assert( pOp->p5<db->nDb );
 84837    assert( DbMaskTest(p->btreeMask, pOp->p5) );
 84838    z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
 84839                                   (int)pnErr->u.i+1, &nErr);
 84840    sqlite3VdbeMemSetNull(pIn1);
 84841    if( nErr==0 ){
 84842      assert( z==0 );
 84843    }else if( z==0 ){
 84844      goto no_mem;
 84845    }else{
 84846      pnErr->u.i -= nErr-1;
 84847      sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
 84848    }
 84849    UPDATE_MAX_BLOBSIZE(pIn1);
 84850    sqlite3VdbeChangeEncoding(pIn1, encoding);
 84851    break;
 84852  }
 84853  #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
 84854  
 84855  /* Opcode: RowSetAdd P1 P2 * * *
 84856  ** Synopsis: rowset(P1)=r[P2]
 84857  **
 84858  ** Insert the integer value held by register P2 into a RowSet object
 84859  ** held in register P1.
 84860  **
 84861  ** An assertion fails if P2 is not an integer.
 84862  */
 84863  case OP_RowSetAdd: {       /* in1, in2 */
 84864    pIn1 = &aMem[pOp->p1];
 84865    pIn2 = &aMem[pOp->p2];
 84866    assert( (pIn2->flags & MEM_Int)!=0 );
 84867    if( (pIn1->flags & MEM_RowSet)==0 ){
 84868      sqlite3VdbeMemSetRowSet(pIn1);
 84869      if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
 84870    }
 84871    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
 84872    break;
 84873  }
 84874  
 84875  /* Opcode: RowSetRead P1 P2 P3 * *
 84876  ** Synopsis: r[P3]=rowset(P1)
 84877  **
 84878  ** Extract the smallest value from the RowSet object in P1
 84879  ** and put that value into register P3.
 84880  ** Or, if RowSet object P1 is initially empty, leave P3
 84881  ** unchanged and jump to instruction P2.
 84882  */
 84883  case OP_RowSetRead: {       /* jump, in1, out3 */
 84884    i64 val;
 84885  
 84886    pIn1 = &aMem[pOp->p1];
 84887    if( (pIn1->flags & MEM_RowSet)==0 
 84888     || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
 84889    ){
 84890      /* The boolean index is empty */
 84891      sqlite3VdbeMemSetNull(pIn1);
 84892      VdbeBranchTaken(1,2);
 84893      goto jump_to_p2_and_check_for_interrupt;
 84894    }else{
 84895      /* A value was pulled from the index */
 84896      VdbeBranchTaken(0,2);
 84897      sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
 84898    }
 84899    goto check_for_interrupt;
 84900  }
 84901  
 84902  /* Opcode: RowSetTest P1 P2 P3 P4
 84903  ** Synopsis: if r[P3] in rowset(P1) goto P2
 84904  **
 84905  ** Register P3 is assumed to hold a 64-bit integer value. If register P1
 84906  ** contains a RowSet object and that RowSet object contains
 84907  ** the value held in P3, jump to register P2. Otherwise, insert the
 84908  ** integer in P3 into the RowSet and continue on to the
 84909  ** next opcode.
 84910  **
 84911  ** The RowSet object is optimized for the case where sets of integers
 84912  ** are inserted in distinct phases, which each set contains no duplicates.
 84913  ** Each set is identified by a unique P4 value. The first set
 84914  ** must have P4==0, the final set must have P4==-1, and for all other sets
 84915  ** must have P4>0.
 84916  **
 84917  ** This allows optimizations: (a) when P4==0 there is no need to test
 84918  ** the RowSet object for P3, as it is guaranteed not to contain it,
 84919  ** (b) when P4==-1 there is no need to insert the value, as it will
 84920  ** never be tested for, and (c) when a value that is part of set X is
 84921  ** inserted, there is no need to search to see if the same value was
 84922  ** previously inserted as part of set X (only if it was previously
 84923  ** inserted as part of some other set).
 84924  */
 84925  case OP_RowSetTest: {                     /* jump, in1, in3 */
 84926    int iSet;
 84927    int exists;
 84928  
 84929    pIn1 = &aMem[pOp->p1];
 84930    pIn3 = &aMem[pOp->p3];
 84931    iSet = pOp->p4.i;
 84932    assert( pIn3->flags&MEM_Int );
 84933  
 84934    /* If there is anything other than a rowset object in memory cell P1,
 84935    ** delete it now and initialize P1 with an empty rowset
 84936    */
 84937    if( (pIn1->flags & MEM_RowSet)==0 ){
 84938      sqlite3VdbeMemSetRowSet(pIn1);
 84939      if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
 84940    }
 84941  
 84942    assert( pOp->p4type==P4_INT32 );
 84943    assert( iSet==-1 || iSet>=0 );
 84944    if( iSet ){
 84945      exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
 84946      VdbeBranchTaken(exists!=0,2);
 84947      if( exists ) goto jump_to_p2;
 84948    }
 84949    if( iSet>=0 ){
 84950      sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
 84951    }
 84952    break;
 84953  }
 84954  
 84955  
 84956  #ifndef SQLITE_OMIT_TRIGGER
 84957  
 84958  /* Opcode: Program P1 P2 P3 P4 P5
 84959  **
 84960  ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
 84961  **
 84962  ** P1 contains the address of the memory cell that contains the first memory 
 84963  ** cell in an array of values used as arguments to the sub-program. P2 
 84964  ** contains the address to jump to if the sub-program throws an IGNORE 
 84965  ** exception using the RAISE() function. Register P3 contains the address 
 84966  ** of a memory cell in this (the parent) VM that is used to allocate the 
 84967  ** memory required by the sub-vdbe at runtime.
 84968  **
 84969  ** P4 is a pointer to the VM containing the trigger program.
 84970  **
 84971  ** If P5 is non-zero, then recursive program invocation is enabled.
 84972  */
 84973  case OP_Program: {        /* jump */
 84974    int nMem;               /* Number of memory registers for sub-program */
 84975    int nByte;              /* Bytes of runtime space required for sub-program */
 84976    Mem *pRt;               /* Register to allocate runtime space */
 84977    Mem *pMem;              /* Used to iterate through memory cells */
 84978    Mem *pEnd;              /* Last memory cell in new array */
 84979    VdbeFrame *pFrame;      /* New vdbe frame to execute in */
 84980    SubProgram *pProgram;   /* Sub-program to execute */
 84981    void *t;                /* Token identifying trigger */
 84982  
 84983    pProgram = pOp->p4.pProgram;
 84984    pRt = &aMem[pOp->p3];
 84985    assert( pProgram->nOp>0 );
 84986    
 84987    /* If the p5 flag is clear, then recursive invocation of triggers is 
 84988    ** disabled for backwards compatibility (p5 is set if this sub-program
 84989    ** is really a trigger, not a foreign key action, and the flag set
 84990    ** and cleared by the "PRAGMA recursive_triggers" command is clear).
 84991    ** 
 84992    ** It is recursive invocation of triggers, at the SQL level, that is 
 84993    ** disabled. In some cases a single trigger may generate more than one 
 84994    ** SubProgram (if the trigger may be executed with more than one different 
 84995    ** ON CONFLICT algorithm). SubProgram structures associated with a
 84996    ** single trigger all have the same value for the SubProgram.token 
 84997    ** variable.  */
 84998    if( pOp->p5 ){
 84999      t = pProgram->token;
 85000      for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
 85001      if( pFrame ) break;
 85002    }
 85003  
 85004    if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
 85005      rc = SQLITE_ERROR;
 85006      sqlite3VdbeError(p, "too many levels of trigger recursion");
 85007      goto abort_due_to_error;
 85008    }
 85009  
 85010    /* Register pRt is used to store the memory required to save the state
 85011    ** of the current program, and the memory required at runtime to execute
 85012    ** the trigger program. If this trigger has been fired before, then pRt 
 85013    ** is already allocated. Otherwise, it must be initialized.  */
 85014    if( (pRt->flags&MEM_Frame)==0 ){
 85015      /* SubProgram.nMem is set to the number of memory cells used by the 
 85016      ** program stored in SubProgram.aOp. As well as these, one memory
 85017      ** cell is required for each cursor used by the program. Set local
 85018      ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
 85019      */
 85020      nMem = pProgram->nMem + pProgram->nCsr;
 85021      assert( nMem>0 );
 85022      if( pProgram->nCsr==0 ) nMem++;
 85023      nByte = ROUND8(sizeof(VdbeFrame))
 85024                + nMem * sizeof(Mem)
 85025                + pProgram->nCsr * sizeof(VdbeCursor*)
 85026                + (pProgram->nOp + 7)/8;
 85027      pFrame = sqlite3DbMallocZero(db, nByte);
 85028      if( !pFrame ){
 85029        goto no_mem;
 85030      }
 85031      sqlite3VdbeMemRelease(pRt);
 85032      pRt->flags = MEM_Frame;
 85033      pRt->u.pFrame = pFrame;
 85034  
 85035      pFrame->v = p;
 85036      pFrame->nChildMem = nMem;
 85037      pFrame->nChildCsr = pProgram->nCsr;
 85038      pFrame->pc = (int)(pOp - aOp);
 85039      pFrame->aMem = p->aMem;
 85040      pFrame->nMem = p->nMem;
 85041      pFrame->apCsr = p->apCsr;
 85042      pFrame->nCursor = p->nCursor;
 85043      pFrame->aOp = p->aOp;
 85044      pFrame->nOp = p->nOp;
 85045      pFrame->token = pProgram->token;
 85046  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 85047      pFrame->anExec = p->anExec;
 85048  #endif
 85049  
 85050      pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
 85051      for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
 85052        pMem->flags = MEM_Undefined;
 85053        pMem->db = db;
 85054      }
 85055    }else{
 85056      pFrame = pRt->u.pFrame;
 85057      assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem 
 85058          || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
 85059      assert( pProgram->nCsr==pFrame->nChildCsr );
 85060      assert( (int)(pOp - aOp)==pFrame->pc );
 85061    }
 85062  
 85063    p->nFrame++;
 85064    pFrame->pParent = p->pFrame;
 85065    pFrame->lastRowid = db->lastRowid;
 85066    pFrame->nChange = p->nChange;
 85067    pFrame->nDbChange = p->db->nChange;
 85068    assert( pFrame->pAuxData==0 );
 85069    pFrame->pAuxData = p->pAuxData;
 85070    p->pAuxData = 0;
 85071    p->nChange = 0;
 85072    p->pFrame = pFrame;
 85073    p->aMem = aMem = VdbeFrameMem(pFrame);
 85074    p->nMem = pFrame->nChildMem;
 85075    p->nCursor = (u16)pFrame->nChildCsr;
 85076    p->apCsr = (VdbeCursor **)&aMem[p->nMem];
 85077    pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
 85078    memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
 85079    p->aOp = aOp = pProgram->aOp;
 85080    p->nOp = pProgram->nOp;
 85081  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 85082    p->anExec = 0;
 85083  #endif
 85084    pOp = &aOp[-1];
 85085  
 85086    break;
 85087  }
 85088  
 85089  /* Opcode: Param P1 P2 * * *
 85090  **
 85091  ** This opcode is only ever present in sub-programs called via the 
 85092  ** OP_Program instruction. Copy a value currently stored in a memory 
 85093  ** cell of the calling (parent) frame to cell P2 in the current frames 
 85094  ** address space. This is used by trigger programs to access the new.* 
 85095  ** and old.* values.
 85096  **
 85097  ** The address of the cell in the parent frame is determined by adding
 85098  ** the value of the P1 argument to the value of the P1 argument to the
 85099  ** calling OP_Program instruction.
 85100  */
 85101  case OP_Param: {           /* out2 */
 85102    VdbeFrame *pFrame;
 85103    Mem *pIn;
 85104    pOut = out2Prerelease(p, pOp);
 85105    pFrame = p->pFrame;
 85106    pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];   
 85107    sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
 85108    break;
 85109  }
 85110  
 85111  #endif /* #ifndef SQLITE_OMIT_TRIGGER */
 85112  
 85113  #ifndef SQLITE_OMIT_FOREIGN_KEY
 85114  /* Opcode: FkCounter P1 P2 * * *
 85115  ** Synopsis: fkctr[P1]+=P2
 85116  **
 85117  ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
 85118  ** If P1 is non-zero, the database constraint counter is incremented 
 85119  ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
 85120  ** statement counter is incremented (immediate foreign key constraints).
 85121  */
 85122  case OP_FkCounter: {
 85123    if( db->flags & SQLITE_DeferFKs ){
 85124      db->nDeferredImmCons += pOp->p2;
 85125    }else if( pOp->p1 ){
 85126      db->nDeferredCons += pOp->p2;
 85127    }else{
 85128      p->nFkConstraint += pOp->p2;
 85129    }
 85130    break;
 85131  }
 85132  
 85133  /* Opcode: FkIfZero P1 P2 * * *
 85134  ** Synopsis: if fkctr[P1]==0 goto P2
 85135  **
 85136  ** This opcode tests if a foreign key constraint-counter is currently zero.
 85137  ** If so, jump to instruction P2. Otherwise, fall through to the next 
 85138  ** instruction.
 85139  **
 85140  ** If P1 is non-zero, then the jump is taken if the database constraint-counter
 85141  ** is zero (the one that counts deferred constraint violations). If P1 is
 85142  ** zero, the jump is taken if the statement constraint-counter is zero
 85143  ** (immediate foreign key constraint violations).
 85144  */
 85145  case OP_FkIfZero: {         /* jump */
 85146    if( pOp->p1 ){
 85147      VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
 85148      if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
 85149    }else{
 85150      VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
 85151      if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
 85152    }
 85153    break;
 85154  }
 85155  #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
 85156  
 85157  #ifndef SQLITE_OMIT_AUTOINCREMENT
 85158  /* Opcode: MemMax P1 P2 * * *
 85159  ** Synopsis: r[P1]=max(r[P1],r[P2])
 85160  **
 85161  ** P1 is a register in the root frame of this VM (the root frame is
 85162  ** different from the current frame if this instruction is being executed
 85163  ** within a sub-program). Set the value of register P1 to the maximum of 
 85164  ** its current value and the value in register P2.
 85165  **
 85166  ** This instruction throws an error if the memory cell is not initially
 85167  ** an integer.
 85168  */
 85169  case OP_MemMax: {        /* in2 */
 85170    VdbeFrame *pFrame;
 85171    if( p->pFrame ){
 85172      for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
 85173      pIn1 = &pFrame->aMem[pOp->p1];
 85174    }else{
 85175      pIn1 = &aMem[pOp->p1];
 85176    }
 85177    assert( memIsValid(pIn1) );
 85178    sqlite3VdbeMemIntegerify(pIn1);
 85179    pIn2 = &aMem[pOp->p2];
 85180    sqlite3VdbeMemIntegerify(pIn2);
 85181    if( pIn1->u.i<pIn2->u.i){
 85182      pIn1->u.i = pIn2->u.i;
 85183    }
 85184    break;
 85185  }
 85186  #endif /* SQLITE_OMIT_AUTOINCREMENT */
 85187  
 85188  /* Opcode: IfPos P1 P2 P3 * *
 85189  ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
 85190  **
 85191  ** Register P1 must contain an integer.
 85192  ** If the value of register P1 is 1 or greater, subtract P3 from the
 85193  ** value in P1 and jump to P2.
 85194  **
 85195  ** If the initial value of register P1 is less than 1, then the
 85196  ** value is unchanged and control passes through to the next instruction.
 85197  */
 85198  case OP_IfPos: {        /* jump, in1 */
 85199    pIn1 = &aMem[pOp->p1];
 85200    assert( pIn1->flags&MEM_Int );
 85201    VdbeBranchTaken( pIn1->u.i>0, 2);
 85202    if( pIn1->u.i>0 ){
 85203      pIn1->u.i -= pOp->p3;
 85204      goto jump_to_p2;
 85205    }
 85206    break;
 85207  }
 85208  
 85209  /* Opcode: OffsetLimit P1 P2 P3 * *
 85210  ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
 85211  **
 85212  ** This opcode performs a commonly used computation associated with
 85213  ** LIMIT and OFFSET process.  r[P1] holds the limit counter.  r[P3]
 85214  ** holds the offset counter.  The opcode computes the combined value
 85215  ** of the LIMIT and OFFSET and stores that value in r[P2].  The r[P2]
 85216  ** value computed is the total number of rows that will need to be
 85217  ** visited in order to complete the query.
 85218  **
 85219  ** If r[P3] is zero or negative, that means there is no OFFSET
 85220  ** and r[P2] is set to be the value of the LIMIT, r[P1].
 85221  **
 85222  ** if r[P1] is zero or negative, that means there is no LIMIT
 85223  ** and r[P2] is set to -1. 
 85224  **
 85225  ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
 85226  */
 85227  case OP_OffsetLimit: {    /* in1, out2, in3 */
 85228    i64 x;
 85229    pIn1 = &aMem[pOp->p1];
 85230    pIn3 = &aMem[pOp->p3];
 85231    pOut = out2Prerelease(p, pOp);
 85232    assert( pIn1->flags & MEM_Int );
 85233    assert( pIn3->flags & MEM_Int );
 85234    x = pIn1->u.i;
 85235    if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
 85236      /* If the LIMIT is less than or equal to zero, loop forever.  This
 85237      ** is documented.  But also, if the LIMIT+OFFSET exceeds 2^63 then
 85238      ** also loop forever.  This is undocumented.  In fact, one could argue
 85239      ** that the loop should terminate.  But assuming 1 billion iterations
 85240      ** per second (far exceeding the capabilities of any current hardware)
 85241      ** it would take nearly 300 years to actually reach the limit.  So
 85242      ** looping forever is a reasonable approximation. */
 85243      pOut->u.i = -1;
 85244    }else{
 85245      pOut->u.i = x;
 85246    }
 85247    break;
 85248  }
 85249  
 85250  /* Opcode: IfNotZero P1 P2 * * *
 85251  ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
 85252  **
 85253  ** Register P1 must contain an integer.  If the content of register P1 is
 85254  ** initially greater than zero, then decrement the value in register P1.
 85255  ** If it is non-zero (negative or positive) and then also jump to P2.  
 85256  ** If register P1 is initially zero, leave it unchanged and fall through.
 85257  */
 85258  case OP_IfNotZero: {        /* jump, in1 */
 85259    pIn1 = &aMem[pOp->p1];
 85260    assert( pIn1->flags&MEM_Int );
 85261    VdbeBranchTaken(pIn1->u.i<0, 2);
 85262    if( pIn1->u.i ){
 85263       if( pIn1->u.i>0 ) pIn1->u.i--;
 85264       goto jump_to_p2;
 85265    }
 85266    break;
 85267  }
 85268  
 85269  /* Opcode: DecrJumpZero P1 P2 * * *
 85270  ** Synopsis: if (--r[P1])==0 goto P2
 85271  **
 85272  ** Register P1 must hold an integer.  Decrement the value in P1
 85273  ** and jump to P2 if the new value is exactly zero.
 85274  */
 85275  case OP_DecrJumpZero: {      /* jump, in1 */
 85276    pIn1 = &aMem[pOp->p1];
 85277    assert( pIn1->flags&MEM_Int );
 85278    if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
 85279    VdbeBranchTaken(pIn1->u.i==0, 2);
 85280    if( pIn1->u.i==0 ) goto jump_to_p2;
 85281    break;
 85282  }
 85283  
 85284  
 85285  /* Opcode: AggStep0 * P2 P3 P4 P5
 85286  ** Synopsis: accum=r[P3] step(r[P2@P5])
 85287  **
 85288  ** Execute the step function for an aggregate.  The
 85289  ** function has P5 arguments.   P4 is a pointer to the FuncDef
 85290  ** structure that specifies the function.  Register P3 is the
 85291  ** accumulator.
 85292  **
 85293  ** The P5 arguments are taken from register P2 and its
 85294  ** successors.
 85295  */
 85296  /* Opcode: AggStep * P2 P3 P4 P5
 85297  ** Synopsis: accum=r[P3] step(r[P2@P5])
 85298  **
 85299  ** Execute the step function for an aggregate.  The
 85300  ** function has P5 arguments.   P4 is a pointer to an sqlite3_context
 85301  ** object that is used to run the function.  Register P3 is
 85302  ** as the accumulator.
 85303  **
 85304  ** The P5 arguments are taken from register P2 and its
 85305  ** successors.
 85306  **
 85307  ** This opcode is initially coded as OP_AggStep0.  On first evaluation,
 85308  ** the FuncDef stored in P4 is converted into an sqlite3_context and
 85309  ** the opcode is changed.  In this way, the initialization of the
 85310  ** sqlite3_context only happens once, instead of on each call to the
 85311  ** step function.
 85312  */
 85313  case OP_AggStep0: {
 85314    int n;
 85315    sqlite3_context *pCtx;
 85316  
 85317    assert( pOp->p4type==P4_FUNCDEF );
 85318    n = pOp->p5;
 85319    assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
 85320    assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
 85321    assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
 85322    pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
 85323    if( pCtx==0 ) goto no_mem;
 85324    pCtx->pMem = 0;
 85325    pCtx->pFunc = pOp->p4.pFunc;
 85326    pCtx->iOp = (int)(pOp - aOp);
 85327    pCtx->pVdbe = p;
 85328    pCtx->argc = n;
 85329    pOp->p4type = P4_FUNCCTX;
 85330    pOp->p4.pCtx = pCtx;
 85331    pOp->opcode = OP_AggStep;
 85332    /* Fall through into OP_AggStep */
 85333  }
 85334  case OP_AggStep: {
 85335    int i;
 85336    sqlite3_context *pCtx;
 85337    Mem *pMem;
 85338    Mem t;
 85339  
 85340    assert( pOp->p4type==P4_FUNCCTX );
 85341    pCtx = pOp->p4.pCtx;
 85342    pMem = &aMem[pOp->p3];
 85343  
 85344    /* If this function is inside of a trigger, the register array in aMem[]
 85345    ** might change from one evaluation to the next.  The next block of code
 85346    ** checks to see if the register array has changed, and if so it
 85347    ** reinitializes the relavant parts of the sqlite3_context object */
 85348    if( pCtx->pMem != pMem ){
 85349      pCtx->pMem = pMem;
 85350      for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
 85351    }
 85352  
 85353  #ifdef SQLITE_DEBUG
 85354    for(i=0; i<pCtx->argc; i++){
 85355      assert( memIsValid(pCtx->argv[i]) );
 85356      REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
 85357    }
 85358  #endif
 85359  
 85360    pMem->n++;
 85361    sqlite3VdbeMemInit(&t, db, MEM_Null);
 85362    pCtx->pOut = &t;
 85363    pCtx->fErrorOrAux = 0;
 85364    pCtx->skipFlag = 0;
 85365    (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
 85366    if( pCtx->fErrorOrAux ){
 85367      if( pCtx->isError ){
 85368        sqlite3VdbeError(p, "%s", sqlite3_value_text(&t));
 85369        rc = pCtx->isError;
 85370      }
 85371      sqlite3VdbeMemRelease(&t);
 85372      if( rc ) goto abort_due_to_error;
 85373    }else{
 85374      assert( t.flags==MEM_Null );
 85375    }
 85376    if( pCtx->skipFlag ){
 85377      assert( pOp[-1].opcode==OP_CollSeq );
 85378      i = pOp[-1].p1;
 85379      if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
 85380    }
 85381    break;
 85382  }
 85383  
 85384  /* Opcode: AggFinal P1 P2 * P4 *
 85385  ** Synopsis: accum=r[P1] N=P2
 85386  **
 85387  ** Execute the finalizer function for an aggregate.  P1 is
 85388  ** the memory location that is the accumulator for the aggregate.
 85389  **
 85390  ** P2 is the number of arguments that the step function takes and
 85391  ** P4 is a pointer to the FuncDef for this function.  The P2
 85392  ** argument is not used by this opcode.  It is only there to disambiguate
 85393  ** functions that can take varying numbers of arguments.  The
 85394  ** P4 argument is only needed for the degenerate case where
 85395  ** the step function was not previously called.
 85396  */
 85397  case OP_AggFinal: {
 85398    Mem *pMem;
 85399    assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
 85400    pMem = &aMem[pOp->p1];
 85401    assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
 85402    rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
 85403    if( rc ){
 85404      sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
 85405      goto abort_due_to_error;
 85406    }
 85407    sqlite3VdbeChangeEncoding(pMem, encoding);
 85408    UPDATE_MAX_BLOBSIZE(pMem);
 85409    if( sqlite3VdbeMemTooBig(pMem) ){
 85410      goto too_big;
 85411    }
 85412    break;
 85413  }
 85414  
 85415  #ifndef SQLITE_OMIT_WAL
 85416  /* Opcode: Checkpoint P1 P2 P3 * *
 85417  **
 85418  ** Checkpoint database P1. This is a no-op if P1 is not currently in
 85419  ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
 85420  ** RESTART, or TRUNCATE.  Write 1 or 0 into mem[P3] if the checkpoint returns
 85421  ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
 85422  ** WAL after the checkpoint into mem[P3+1] and the number of pages
 85423  ** in the WAL that have been checkpointed after the checkpoint
 85424  ** completes into mem[P3+2].  However on an error, mem[P3+1] and
 85425  ** mem[P3+2] are initialized to -1.
 85426  */
 85427  case OP_Checkpoint: {
 85428    int i;                          /* Loop counter */
 85429    int aRes[3];                    /* Results */
 85430    Mem *pMem;                      /* Write results here */
 85431  
 85432    assert( p->readOnly==0 );
 85433    aRes[0] = 0;
 85434    aRes[1] = aRes[2] = -1;
 85435    assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
 85436         || pOp->p2==SQLITE_CHECKPOINT_FULL
 85437         || pOp->p2==SQLITE_CHECKPOINT_RESTART
 85438         || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
 85439    );
 85440    rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
 85441    if( rc ){
 85442      if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
 85443      rc = SQLITE_OK;
 85444      aRes[0] = 1;
 85445    }
 85446    for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
 85447      sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
 85448    }    
 85449    break;
 85450  };  
 85451  #endif
 85452  
 85453  #ifndef SQLITE_OMIT_PRAGMA
 85454  /* Opcode: JournalMode P1 P2 P3 * *
 85455  **
 85456  ** Change the journal mode of database P1 to P3. P3 must be one of the
 85457  ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
 85458  ** modes (delete, truncate, persist, off and memory), this is a simple
 85459  ** operation. No IO is required.
 85460  **
 85461  ** If changing into or out of WAL mode the procedure is more complicated.
 85462  **
 85463  ** Write a string containing the final journal-mode to register P2.
 85464  */
 85465  case OP_JournalMode: {    /* out2 */
 85466    Btree *pBt;                     /* Btree to change journal mode of */
 85467    Pager *pPager;                  /* Pager associated with pBt */
 85468    int eNew;                       /* New journal mode */
 85469    int eOld;                       /* The old journal mode */
 85470  #ifndef SQLITE_OMIT_WAL
 85471    const char *zFilename;          /* Name of database file for pPager */
 85472  #endif
 85473  
 85474    pOut = out2Prerelease(p, pOp);
 85475    eNew = pOp->p3;
 85476    assert( eNew==PAGER_JOURNALMODE_DELETE 
 85477         || eNew==PAGER_JOURNALMODE_TRUNCATE 
 85478         || eNew==PAGER_JOURNALMODE_PERSIST 
 85479         || eNew==PAGER_JOURNALMODE_OFF
 85480         || eNew==PAGER_JOURNALMODE_MEMORY
 85481         || eNew==PAGER_JOURNALMODE_WAL
 85482         || eNew==PAGER_JOURNALMODE_QUERY
 85483    );
 85484    assert( pOp->p1>=0 && pOp->p1<db->nDb );
 85485    assert( p->readOnly==0 );
 85486  
 85487    pBt = db->aDb[pOp->p1].pBt;
 85488    pPager = sqlite3BtreePager(pBt);
 85489    eOld = sqlite3PagerGetJournalMode(pPager);
 85490    if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
 85491    if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
 85492  
 85493  #ifndef SQLITE_OMIT_WAL
 85494    zFilename = sqlite3PagerFilename(pPager, 1);
 85495  
 85496    /* Do not allow a transition to journal_mode=WAL for a database
 85497    ** in temporary storage or if the VFS does not support shared memory 
 85498    */
 85499    if( eNew==PAGER_JOURNALMODE_WAL
 85500     && (sqlite3Strlen30(zFilename)==0           /* Temp file */
 85501         || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
 85502    ){
 85503      eNew = eOld;
 85504    }
 85505  
 85506    if( (eNew!=eOld)
 85507     && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
 85508    ){
 85509      if( !db->autoCommit || db->nVdbeRead>1 ){
 85510        rc = SQLITE_ERROR;
 85511        sqlite3VdbeError(p,
 85512            "cannot change %s wal mode from within a transaction",
 85513            (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
 85514        );
 85515        goto abort_due_to_error;
 85516      }else{
 85517   
 85518        if( eOld==PAGER_JOURNALMODE_WAL ){
 85519          /* If leaving WAL mode, close the log file. If successful, the call
 85520          ** to PagerCloseWal() checkpoints and deletes the write-ahead-log 
 85521          ** file. An EXCLUSIVE lock may still be held on the database file 
 85522          ** after a successful return. 
 85523          */
 85524          rc = sqlite3PagerCloseWal(pPager, db);
 85525          if( rc==SQLITE_OK ){
 85526            sqlite3PagerSetJournalMode(pPager, eNew);
 85527          }
 85528        }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
 85529          /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
 85530          ** as an intermediate */
 85531          sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
 85532        }
 85533    
 85534        /* Open a transaction on the database file. Regardless of the journal
 85535        ** mode, this transaction always uses a rollback journal.
 85536        */
 85537        assert( sqlite3BtreeIsInTrans(pBt)==0 );
 85538        if( rc==SQLITE_OK ){
 85539          rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
 85540        }
 85541      }
 85542    }
 85543  #endif /* ifndef SQLITE_OMIT_WAL */
 85544  
 85545    if( rc ) eNew = eOld;
 85546    eNew = sqlite3PagerSetJournalMode(pPager, eNew);
 85547  
 85548    pOut->flags = MEM_Str|MEM_Static|MEM_Term;
 85549    pOut->z = (char *)sqlite3JournalModename(eNew);
 85550    pOut->n = sqlite3Strlen30(pOut->z);
 85551    pOut->enc = SQLITE_UTF8;
 85552    sqlite3VdbeChangeEncoding(pOut, encoding);
 85553    if( rc ) goto abort_due_to_error;
 85554    break;
 85555  };
 85556  #endif /* SQLITE_OMIT_PRAGMA */
 85557  
 85558  #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
 85559  /* Opcode: Vacuum P1 * * * *
 85560  **
 85561  ** Vacuum the entire database P1.  P1 is 0 for "main", and 2 or more
 85562  ** for an attached database.  The "temp" database may not be vacuumed.
 85563  */
 85564  case OP_Vacuum: {
 85565    assert( p->readOnly==0 );
 85566    rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1);
 85567    if( rc ) goto abort_due_to_error;
 85568    break;
 85569  }
 85570  #endif
 85571  
 85572  #if !defined(SQLITE_OMIT_AUTOVACUUM)
 85573  /* Opcode: IncrVacuum P1 P2 * * *
 85574  **
 85575  ** Perform a single step of the incremental vacuum procedure on
 85576  ** the P1 database. If the vacuum has finished, jump to instruction
 85577  ** P2. Otherwise, fall through to the next instruction.
 85578  */
 85579  case OP_IncrVacuum: {        /* jump */
 85580    Btree *pBt;
 85581  
 85582    assert( pOp->p1>=0 && pOp->p1<db->nDb );
 85583    assert( DbMaskTest(p->btreeMask, pOp->p1) );
 85584    assert( p->readOnly==0 );
 85585    pBt = db->aDb[pOp->p1].pBt;
 85586    rc = sqlite3BtreeIncrVacuum(pBt);
 85587    VdbeBranchTaken(rc==SQLITE_DONE,2);
 85588    if( rc ){
 85589      if( rc!=SQLITE_DONE ) goto abort_due_to_error;
 85590      rc = SQLITE_OK;
 85591      goto jump_to_p2;
 85592    }
 85593    break;
 85594  }
 85595  #endif
 85596  
 85597  /* Opcode: Expire P1 * * * *
 85598  **
 85599  ** Cause precompiled statements to expire.  When an expired statement
 85600  ** is executed using sqlite3_step() it will either automatically
 85601  ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
 85602  ** or it will fail with SQLITE_SCHEMA.
 85603  ** 
 85604  ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
 85605  ** then only the currently executing statement is expired.
 85606  */
 85607  case OP_Expire: {
 85608    if( !pOp->p1 ){
 85609      sqlite3ExpirePreparedStatements(db);
 85610    }else{
 85611      p->expired = 1;
 85612    }
 85613    break;
 85614  }
 85615  
 85616  #ifndef SQLITE_OMIT_SHARED_CACHE
 85617  /* Opcode: TableLock P1 P2 P3 P4 *
 85618  ** Synopsis: iDb=P1 root=P2 write=P3
 85619  **
 85620  ** Obtain a lock on a particular table. This instruction is only used when
 85621  ** the shared-cache feature is enabled. 
 85622  **
 85623  ** P1 is the index of the database in sqlite3.aDb[] of the database
 85624  ** on which the lock is acquired.  A readlock is obtained if P3==0 or
 85625  ** a write lock if P3==1.
 85626  **
 85627  ** P2 contains the root-page of the table to lock.
 85628  **
 85629  ** P4 contains a pointer to the name of the table being locked. This is only
 85630  ** used to generate an error message if the lock cannot be obtained.
 85631  */
 85632  case OP_TableLock: {
 85633    u8 isWriteLock = (u8)pOp->p3;
 85634    if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
 85635      int p1 = pOp->p1; 
 85636      assert( p1>=0 && p1<db->nDb );
 85637      assert( DbMaskTest(p->btreeMask, p1) );
 85638      assert( isWriteLock==0 || isWriteLock==1 );
 85639      rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
 85640      if( rc ){
 85641        if( (rc&0xFF)==SQLITE_LOCKED ){
 85642          const char *z = pOp->p4.z;
 85643          sqlite3VdbeError(p, "database table is locked: %s", z);
 85644        }
 85645        goto abort_due_to_error;
 85646      }
 85647    }
 85648    break;
 85649  }
 85650  #endif /* SQLITE_OMIT_SHARED_CACHE */
 85651  
 85652  #ifndef SQLITE_OMIT_VIRTUALTABLE
 85653  /* Opcode: VBegin * * * P4 *
 85654  **
 85655  ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
 85656  ** xBegin method for that table.
 85657  **
 85658  ** Also, whether or not P4 is set, check that this is not being called from
 85659  ** within a callback to a virtual table xSync() method. If it is, the error
 85660  ** code will be set to SQLITE_LOCKED.
 85661  */
 85662  case OP_VBegin: {
 85663    VTable *pVTab;
 85664    pVTab = pOp->p4.pVtab;
 85665    rc = sqlite3VtabBegin(db, pVTab);
 85666    if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
 85667    if( rc ) goto abort_due_to_error;
 85668    break;
 85669  }
 85670  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 85671  
 85672  #ifndef SQLITE_OMIT_VIRTUALTABLE
 85673  /* Opcode: VCreate P1 P2 * * *
 85674  **
 85675  ** P2 is a register that holds the name of a virtual table in database 
 85676  ** P1. Call the xCreate method for that table.
 85677  */
 85678  case OP_VCreate: {
 85679    Mem sMem;          /* For storing the record being decoded */
 85680    const char *zTab;  /* Name of the virtual table */
 85681  
 85682    memset(&sMem, 0, sizeof(sMem));
 85683    sMem.db = db;
 85684    /* Because P2 is always a static string, it is impossible for the
 85685    ** sqlite3VdbeMemCopy() to fail */
 85686    assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
 85687    assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
 85688    rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
 85689    assert( rc==SQLITE_OK );
 85690    zTab = (const char*)sqlite3_value_text(&sMem);
 85691    assert( zTab || db->mallocFailed );
 85692    if( zTab ){
 85693      rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
 85694    }
 85695    sqlite3VdbeMemRelease(&sMem);
 85696    if( rc ) goto abort_due_to_error;
 85697    break;
 85698  }
 85699  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 85700  
 85701  #ifndef SQLITE_OMIT_VIRTUALTABLE
 85702  /* Opcode: VDestroy P1 * * P4 *
 85703  **
 85704  ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
 85705  ** of that table.
 85706  */
 85707  case OP_VDestroy: {
 85708    db->nVDestroy++;
 85709    rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
 85710    db->nVDestroy--;
 85711    if( rc ) goto abort_due_to_error;
 85712    break;
 85713  }
 85714  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 85715  
 85716  #ifndef SQLITE_OMIT_VIRTUALTABLE
 85717  /* Opcode: VOpen P1 * * P4 *
 85718  **
 85719  ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
 85720  ** P1 is a cursor number.  This opcode opens a cursor to the virtual
 85721  ** table and stores that cursor in P1.
 85722  */
 85723  case OP_VOpen: {
 85724    VdbeCursor *pCur;
 85725    sqlite3_vtab_cursor *pVCur;
 85726    sqlite3_vtab *pVtab;
 85727    const sqlite3_module *pModule;
 85728  
 85729    assert( p->bIsReader );
 85730    pCur = 0;
 85731    pVCur = 0;
 85732    pVtab = pOp->p4.pVtab->pVtab;
 85733    if( pVtab==0 || NEVER(pVtab->pModule==0) ){
 85734      rc = SQLITE_LOCKED;
 85735      goto abort_due_to_error;
 85736    }
 85737    pModule = pVtab->pModule;
 85738    rc = pModule->xOpen(pVtab, &pVCur);
 85739    sqlite3VtabImportErrmsg(p, pVtab);
 85740    if( rc ) goto abort_due_to_error;
 85741  
 85742    /* Initialize sqlite3_vtab_cursor base class */
 85743    pVCur->pVtab = pVtab;
 85744  
 85745    /* Initialize vdbe cursor object */
 85746    pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
 85747    if( pCur ){
 85748      pCur->uc.pVCur = pVCur;
 85749      pVtab->nRef++;
 85750    }else{
 85751      assert( db->mallocFailed );
 85752      pModule->xClose(pVCur);
 85753      goto no_mem;
 85754    }
 85755    break;
 85756  }
 85757  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 85758  
 85759  #ifndef SQLITE_OMIT_VIRTUALTABLE
 85760  /* Opcode: VFilter P1 P2 P3 P4 *
 85761  ** Synopsis: iplan=r[P3] zplan='P4'
 85762  **
 85763  ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
 85764  ** the filtered result set is empty.
 85765  **
 85766  ** P4 is either NULL or a string that was generated by the xBestIndex
 85767  ** method of the module.  The interpretation of the P4 string is left
 85768  ** to the module implementation.
 85769  **
 85770  ** This opcode invokes the xFilter method on the virtual table specified
 85771  ** by P1.  The integer query plan parameter to xFilter is stored in register
 85772  ** P3. Register P3+1 stores the argc parameter to be passed to the
 85773  ** xFilter method. Registers P3+2..P3+1+argc are the argc
 85774  ** additional parameters which are passed to
 85775  ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
 85776  **
 85777  ** A jump is made to P2 if the result set after filtering would be empty.
 85778  */
 85779  case OP_VFilter: {   /* jump */
 85780    int nArg;
 85781    int iQuery;
 85782    const sqlite3_module *pModule;
 85783    Mem *pQuery;
 85784    Mem *pArgc;
 85785    sqlite3_vtab_cursor *pVCur;
 85786    sqlite3_vtab *pVtab;
 85787    VdbeCursor *pCur;
 85788    int res;
 85789    int i;
 85790    Mem **apArg;
 85791  
 85792    pQuery = &aMem[pOp->p3];
 85793    pArgc = &pQuery[1];
 85794    pCur = p->apCsr[pOp->p1];
 85795    assert( memIsValid(pQuery) );
 85796    REGISTER_TRACE(pOp->p3, pQuery);
 85797    assert( pCur->eCurType==CURTYPE_VTAB );
 85798    pVCur = pCur->uc.pVCur;
 85799    pVtab = pVCur->pVtab;
 85800    pModule = pVtab->pModule;
 85801  
 85802    /* Grab the index number and argc parameters */
 85803    assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
 85804    nArg = (int)pArgc->u.i;
 85805    iQuery = (int)pQuery->u.i;
 85806  
 85807    /* Invoke the xFilter method */
 85808    res = 0;
 85809    apArg = p->apArg;
 85810    for(i = 0; i<nArg; i++){
 85811      apArg[i] = &pArgc[i+1];
 85812    }
 85813    rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
 85814    sqlite3VtabImportErrmsg(p, pVtab);
 85815    if( rc ) goto abort_due_to_error;
 85816    res = pModule->xEof(pVCur);
 85817    pCur->nullRow = 0;
 85818    VdbeBranchTaken(res!=0,2);
 85819    if( res ) goto jump_to_p2;
 85820    break;
 85821  }
 85822  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 85823  
 85824  #ifndef SQLITE_OMIT_VIRTUALTABLE
 85825  /* Opcode: VColumn P1 P2 P3 * *
 85826  ** Synopsis: r[P3]=vcolumn(P2)
 85827  **
 85828  ** Store the value of the P2-th column of
 85829  ** the row of the virtual-table that the 
 85830  ** P1 cursor is pointing to into register P3.
 85831  */
 85832  case OP_VColumn: {
 85833    sqlite3_vtab *pVtab;
 85834    const sqlite3_module *pModule;
 85835    Mem *pDest;
 85836    sqlite3_context sContext;
 85837  
 85838    VdbeCursor *pCur = p->apCsr[pOp->p1];
 85839    assert( pCur->eCurType==CURTYPE_VTAB );
 85840    assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
 85841    pDest = &aMem[pOp->p3];
 85842    memAboutToChange(p, pDest);
 85843    if( pCur->nullRow ){
 85844      sqlite3VdbeMemSetNull(pDest);
 85845      break;
 85846    }
 85847    pVtab = pCur->uc.pVCur->pVtab;
 85848    pModule = pVtab->pModule;
 85849    assert( pModule->xColumn );
 85850    memset(&sContext, 0, sizeof(sContext));
 85851    sContext.pOut = pDest;
 85852    MemSetTypeFlag(pDest, MEM_Null);
 85853    rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
 85854    sqlite3VtabImportErrmsg(p, pVtab);
 85855    if( sContext.isError ){
 85856      rc = sContext.isError;
 85857    }
 85858    sqlite3VdbeChangeEncoding(pDest, encoding);
 85859    REGISTER_TRACE(pOp->p3, pDest);
 85860    UPDATE_MAX_BLOBSIZE(pDest);
 85861  
 85862    if( sqlite3VdbeMemTooBig(pDest) ){
 85863      goto too_big;
 85864    }
 85865    if( rc ) goto abort_due_to_error;
 85866    break;
 85867  }
 85868  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 85869  
 85870  #ifndef SQLITE_OMIT_VIRTUALTABLE
 85871  /* Opcode: VNext P1 P2 * * *
 85872  **
 85873  ** Advance virtual table P1 to the next row in its result set and
 85874  ** jump to instruction P2.  Or, if the virtual table has reached
 85875  ** the end of its result set, then fall through to the next instruction.
 85876  */
 85877  case OP_VNext: {   /* jump */
 85878    sqlite3_vtab *pVtab;
 85879    const sqlite3_module *pModule;
 85880    int res;
 85881    VdbeCursor *pCur;
 85882  
 85883    res = 0;
 85884    pCur = p->apCsr[pOp->p1];
 85885    assert( pCur->eCurType==CURTYPE_VTAB );
 85886    if( pCur->nullRow ){
 85887      break;
 85888    }
 85889    pVtab = pCur->uc.pVCur->pVtab;
 85890    pModule = pVtab->pModule;
 85891    assert( pModule->xNext );
 85892  
 85893    /* Invoke the xNext() method of the module. There is no way for the
 85894    ** underlying implementation to return an error if one occurs during
 85895    ** xNext(). Instead, if an error occurs, true is returned (indicating that 
 85896    ** data is available) and the error code returned when xColumn or
 85897    ** some other method is next invoked on the save virtual table cursor.
 85898    */
 85899    rc = pModule->xNext(pCur->uc.pVCur);
 85900    sqlite3VtabImportErrmsg(p, pVtab);
 85901    if( rc ) goto abort_due_to_error;
 85902    res = pModule->xEof(pCur->uc.pVCur);
 85903    VdbeBranchTaken(!res,2);
 85904    if( !res ){
 85905      /* If there is data, jump to P2 */
 85906      goto jump_to_p2_and_check_for_interrupt;
 85907    }
 85908    goto check_for_interrupt;
 85909  }
 85910  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 85911  
 85912  #ifndef SQLITE_OMIT_VIRTUALTABLE
 85913  /* Opcode: VRename P1 * * P4 *
 85914  **
 85915  ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
 85916  ** This opcode invokes the corresponding xRename method. The value
 85917  ** in register P1 is passed as the zName argument to the xRename method.
 85918  */
 85919  case OP_VRename: {
 85920    sqlite3_vtab *pVtab;
 85921    Mem *pName;
 85922  
 85923    pVtab = pOp->p4.pVtab->pVtab;
 85924    pName = &aMem[pOp->p1];
 85925    assert( pVtab->pModule->xRename );
 85926    assert( memIsValid(pName) );
 85927    assert( p->readOnly==0 );
 85928    REGISTER_TRACE(pOp->p1, pName);
 85929    assert( pName->flags & MEM_Str );
 85930    testcase( pName->enc==SQLITE_UTF8 );
 85931    testcase( pName->enc==SQLITE_UTF16BE );
 85932    testcase( pName->enc==SQLITE_UTF16LE );
 85933    rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
 85934    if( rc ) goto abort_due_to_error;
 85935    rc = pVtab->pModule->xRename(pVtab, pName->z);
 85936    sqlite3VtabImportErrmsg(p, pVtab);
 85937    p->expired = 0;
 85938    if( rc ) goto abort_due_to_error;
 85939    break;
 85940  }
 85941  #endif
 85942  
 85943  #ifndef SQLITE_OMIT_VIRTUALTABLE
 85944  /* Opcode: VUpdate P1 P2 P3 P4 P5
 85945  ** Synopsis: data=r[P3@P2]
 85946  **
 85947  ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
 85948  ** This opcode invokes the corresponding xUpdate method. P2 values
 85949  ** are contiguous memory cells starting at P3 to pass to the xUpdate 
 85950  ** invocation. The value in register (P3+P2-1) corresponds to the 
 85951  ** p2th element of the argv array passed to xUpdate.
 85952  **
 85953  ** The xUpdate method will do a DELETE or an INSERT or both.
 85954  ** The argv[0] element (which corresponds to memory cell P3)
 85955  ** is the rowid of a row to delete.  If argv[0] is NULL then no 
 85956  ** deletion occurs.  The argv[1] element is the rowid of the new 
 85957  ** row.  This can be NULL to have the virtual table select the new 
 85958  ** rowid for itself.  The subsequent elements in the array are 
 85959  ** the values of columns in the new row.
 85960  **
 85961  ** If P2==1 then no insert is performed.  argv[0] is the rowid of
 85962  ** a row to delete.
 85963  **
 85964  ** P1 is a boolean flag. If it is set to true and the xUpdate call
 85965  ** is successful, then the value returned by sqlite3_last_insert_rowid() 
 85966  ** is set to the value of the rowid for the row just inserted.
 85967  **
 85968  ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
 85969  ** apply in the case of a constraint failure on an insert or update.
 85970  */
 85971  case OP_VUpdate: {
 85972    sqlite3_vtab *pVtab;
 85973    const sqlite3_module *pModule;
 85974    int nArg;
 85975    int i;
 85976    sqlite_int64 rowid;
 85977    Mem **apArg;
 85978    Mem *pX;
 85979  
 85980    assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback 
 85981         || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
 85982    );
 85983    assert( p->readOnly==0 );
 85984    pVtab = pOp->p4.pVtab->pVtab;
 85985    if( pVtab==0 || NEVER(pVtab->pModule==0) ){
 85986      rc = SQLITE_LOCKED;
 85987      goto abort_due_to_error;
 85988    }
 85989    pModule = pVtab->pModule;
 85990    nArg = pOp->p2;
 85991    assert( pOp->p4type==P4_VTAB );
 85992    if( ALWAYS(pModule->xUpdate) ){
 85993      u8 vtabOnConflict = db->vtabOnConflict;
 85994      apArg = p->apArg;
 85995      pX = &aMem[pOp->p3];
 85996      for(i=0; i<nArg; i++){
 85997        assert( memIsValid(pX) );
 85998        memAboutToChange(p, pX);
 85999        apArg[i] = pX;
 86000        pX++;
 86001      }
 86002      db->vtabOnConflict = pOp->p5;
 86003      rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
 86004      db->vtabOnConflict = vtabOnConflict;
 86005      sqlite3VtabImportErrmsg(p, pVtab);
 86006      if( rc==SQLITE_OK && pOp->p1 ){
 86007        assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
 86008        db->lastRowid = rowid;
 86009      }
 86010      if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
 86011        if( pOp->p5==OE_Ignore ){
 86012          rc = SQLITE_OK;
 86013        }else{
 86014          p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
 86015        }
 86016      }else{
 86017        p->nChange++;
 86018      }
 86019      if( rc ) goto abort_due_to_error;
 86020    }
 86021    break;
 86022  }
 86023  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 86024  
 86025  #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
 86026  /* Opcode: Pagecount P1 P2 * * *
 86027  **
 86028  ** Write the current number of pages in database P1 to memory cell P2.
 86029  */
 86030  case OP_Pagecount: {            /* out2 */
 86031    pOut = out2Prerelease(p, pOp);
 86032    pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
 86033    break;
 86034  }
 86035  #endif
 86036  
 86037  
 86038  #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
 86039  /* Opcode: MaxPgcnt P1 P2 P3 * *
 86040  **
 86041  ** Try to set the maximum page count for database P1 to the value in P3.
 86042  ** Do not let the maximum page count fall below the current page count and
 86043  ** do not change the maximum page count value if P3==0.
 86044  **
 86045  ** Store the maximum page count after the change in register P2.
 86046  */
 86047  case OP_MaxPgcnt: {            /* out2 */
 86048    unsigned int newMax;
 86049    Btree *pBt;
 86050  
 86051    pOut = out2Prerelease(p, pOp);
 86052    pBt = db->aDb[pOp->p1].pBt;
 86053    newMax = 0;
 86054    if( pOp->p3 ){
 86055      newMax = sqlite3BtreeLastPage(pBt);
 86056      if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
 86057    }
 86058    pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
 86059    break;
 86060  }
 86061  #endif
 86062  
 86063  /* Opcode: Function0 P1 P2 P3 P4 P5
 86064  ** Synopsis: r[P3]=func(r[P2@P5])
 86065  **
 86066  ** Invoke a user function (P4 is a pointer to a FuncDef object that
 86067  ** defines the function) with P5 arguments taken from register P2 and
 86068  ** successors.  The result of the function is stored in register P3.
 86069  ** Register P3 must not be one of the function inputs.
 86070  **
 86071  ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
 86072  ** function was determined to be constant at compile time. If the first
 86073  ** argument was constant then bit 0 of P1 is set. This is used to determine
 86074  ** whether meta data associated with a user function argument using the
 86075  ** sqlite3_set_auxdata() API may be safely retained until the next
 86076  ** invocation of this opcode.
 86077  **
 86078  ** See also: Function, AggStep, AggFinal
 86079  */
 86080  /* Opcode: Function P1 P2 P3 P4 P5
 86081  ** Synopsis: r[P3]=func(r[P2@P5])
 86082  **
 86083  ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
 86084  ** contains a pointer to the function to be run) with P5 arguments taken
 86085  ** from register P2 and successors.  The result of the function is stored
 86086  ** in register P3.  Register P3 must not be one of the function inputs.
 86087  **
 86088  ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
 86089  ** function was determined to be constant at compile time. If the first
 86090  ** argument was constant then bit 0 of P1 is set. This is used to determine
 86091  ** whether meta data associated with a user function argument using the
 86092  ** sqlite3_set_auxdata() API may be safely retained until the next
 86093  ** invocation of this opcode.
 86094  **
 86095  ** SQL functions are initially coded as OP_Function0 with P4 pointing
 86096  ** to a FuncDef object.  But on first evaluation, the P4 operand is
 86097  ** automatically converted into an sqlite3_context object and the operation
 86098  ** changed to this OP_Function opcode.  In this way, the initialization of
 86099  ** the sqlite3_context object occurs only once, rather than once for each
 86100  ** evaluation of the function.
 86101  **
 86102  ** See also: Function0, AggStep, AggFinal
 86103  */
 86104  case OP_PureFunc0:
 86105  case OP_Function0: {
 86106    int n;
 86107    sqlite3_context *pCtx;
 86108  
 86109    assert( pOp->p4type==P4_FUNCDEF );
 86110    n = pOp->p5;
 86111    assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
 86112    assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
 86113    assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
 86114    pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
 86115    if( pCtx==0 ) goto no_mem;
 86116    pCtx->pOut = 0;
 86117    pCtx->pFunc = pOp->p4.pFunc;
 86118    pCtx->iOp = (int)(pOp - aOp);
 86119    pCtx->pVdbe = p;
 86120    pCtx->argc = n;
 86121    pOp->p4type = P4_FUNCCTX;
 86122    pOp->p4.pCtx = pCtx;
 86123    assert( OP_PureFunc == OP_PureFunc0+2 );
 86124    assert( OP_Function == OP_Function0+2 );
 86125    pOp->opcode += 2;
 86126    /* Fall through into OP_Function */
 86127  }
 86128  case OP_PureFunc:
 86129  case OP_Function: {
 86130    int i;
 86131    sqlite3_context *pCtx;
 86132  
 86133    assert( pOp->p4type==P4_FUNCCTX );
 86134    pCtx = pOp->p4.pCtx;
 86135  
 86136    /* If this function is inside of a trigger, the register array in aMem[]
 86137    ** might change from one evaluation to the next.  The next block of code
 86138    ** checks to see if the register array has changed, and if so it
 86139    ** reinitializes the relavant parts of the sqlite3_context object */
 86140    pOut = &aMem[pOp->p3];
 86141    if( pCtx->pOut != pOut ){
 86142      pCtx->pOut = pOut;
 86143      for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
 86144    }
 86145  
 86146    memAboutToChange(p, pOut);
 86147  #ifdef SQLITE_DEBUG
 86148    for(i=0; i<pCtx->argc; i++){
 86149      assert( memIsValid(pCtx->argv[i]) );
 86150      REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
 86151    }
 86152  #endif
 86153    MemSetTypeFlag(pOut, MEM_Null);
 86154    pCtx->fErrorOrAux = 0;
 86155    (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
 86156  
 86157    /* If the function returned an error, throw an exception */
 86158    if( pCtx->fErrorOrAux ){
 86159      if( pCtx->isError ){
 86160        sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
 86161        rc = pCtx->isError;
 86162      }
 86163      sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
 86164      if( rc ) goto abort_due_to_error;
 86165    }
 86166  
 86167    /* Copy the result of the function into register P3 */
 86168    if( pOut->flags & (MEM_Str|MEM_Blob) ){
 86169      sqlite3VdbeChangeEncoding(pOut, encoding);
 86170      if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
 86171    }
 86172  
 86173    REGISTER_TRACE(pOp->p3, pOut);
 86174    UPDATE_MAX_BLOBSIZE(pOut);
 86175    break;
 86176  }
 86177  
 86178  
 86179  /* Opcode: Init P1 P2 P3 P4 *
 86180  ** Synopsis: Start at P2
 86181  **
 86182  ** Programs contain a single instance of this opcode as the very first
 86183  ** opcode.
 86184  **
 86185  ** If tracing is enabled (by the sqlite3_trace()) interface, then
 86186  ** the UTF-8 string contained in P4 is emitted on the trace callback.
 86187  ** Or if P4 is blank, use the string returned by sqlite3_sql().
 86188  **
 86189  ** If P2 is not zero, jump to instruction P2.
 86190  **
 86191  ** Increment the value of P1 so that OP_Once opcodes will jump the
 86192  ** first time they are evaluated for this run.
 86193  **
 86194  ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
 86195  ** error is encountered.
 86196  */
 86197  case OP_Init: {          /* jump */
 86198    char *zTrace;
 86199    int i;
 86200  
 86201    /* If the P4 argument is not NULL, then it must be an SQL comment string.
 86202    ** The "--" string is broken up to prevent false-positives with srcck1.c.
 86203    **
 86204    ** This assert() provides evidence for:
 86205    ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
 86206    ** would have been returned by the legacy sqlite3_trace() interface by
 86207    ** using the X argument when X begins with "--" and invoking
 86208    ** sqlite3_expanded_sql(P) otherwise.
 86209    */
 86210    assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
 86211    assert( pOp==p->aOp );  /* Always instruction 0 */
 86212  
 86213  #ifndef SQLITE_OMIT_TRACE
 86214    if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
 86215     && !p->doingRerun
 86216     && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
 86217    ){
 86218  #ifndef SQLITE_OMIT_DEPRECATED
 86219      if( db->mTrace & SQLITE_TRACE_LEGACY ){
 86220        void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
 86221        char *z = sqlite3VdbeExpandSql(p, zTrace);
 86222        x(db->pTraceArg, z);
 86223        sqlite3_free(z);
 86224      }else
 86225  #endif
 86226      if( db->nVdbeExec>1 ){
 86227        char *z = sqlite3MPrintf(db, "-- %s", zTrace);
 86228        (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
 86229        sqlite3DbFree(db, z);
 86230      }else{
 86231        (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
 86232      }
 86233    }
 86234  #ifdef SQLITE_USE_FCNTL_TRACE
 86235    zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
 86236    if( zTrace ){
 86237      int j;
 86238      for(j=0; j<db->nDb; j++){
 86239        if( DbMaskTest(p->btreeMask, j)==0 ) continue;
 86240        sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
 86241      }
 86242    }
 86243  #endif /* SQLITE_USE_FCNTL_TRACE */
 86244  #ifdef SQLITE_DEBUG
 86245    if( (db->flags & SQLITE_SqlTrace)!=0
 86246     && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
 86247    ){
 86248      sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
 86249    }
 86250  #endif /* SQLITE_DEBUG */
 86251  #endif /* SQLITE_OMIT_TRACE */
 86252    assert( pOp->p2>0 );
 86253    if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
 86254      for(i=1; i<p->nOp; i++){
 86255        if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
 86256      }
 86257      pOp->p1 = 0;
 86258    }
 86259    pOp->p1++;
 86260    p->aCounter[SQLITE_STMTSTATUS_RUN]++;
 86261    goto jump_to_p2;
 86262  }
 86263  
 86264  #ifdef SQLITE_ENABLE_CURSOR_HINTS
 86265  /* Opcode: CursorHint P1 * * P4 *
 86266  **
 86267  ** Provide a hint to cursor P1 that it only needs to return rows that
 86268  ** satisfy the Expr in P4.  TK_REGISTER terms in the P4 expression refer
 86269  ** to values currently held in registers.  TK_COLUMN terms in the P4
 86270  ** expression refer to columns in the b-tree to which cursor P1 is pointing.
 86271  */
 86272  case OP_CursorHint: {
 86273    VdbeCursor *pC;
 86274  
 86275    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 86276    assert( pOp->p4type==P4_EXPR );
 86277    pC = p->apCsr[pOp->p1];
 86278    if( pC ){
 86279      assert( pC->eCurType==CURTYPE_BTREE );
 86280      sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
 86281                             pOp->p4.pExpr, aMem);
 86282    }
 86283    break;
 86284  }
 86285  #endif /* SQLITE_ENABLE_CURSOR_HINTS */
 86286  
 86287  /* Opcode: Noop * * * * *
 86288  **
 86289  ** Do nothing.  This instruction is often useful as a jump
 86290  ** destination.
 86291  */
 86292  /*
 86293  ** The magic Explain opcode are only inserted when explain==2 (which
 86294  ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
 86295  ** This opcode records information from the optimizer.  It is the
 86296  ** the same as a no-op.  This opcodesnever appears in a real VM program.
 86297  */
 86298  default: {          /* This is really OP_Noop and OP_Explain */
 86299    assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
 86300    break;
 86301  }
 86302  
 86303  /*****************************************************************************
 86304  ** The cases of the switch statement above this line should all be indented
 86305  ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
 86306  ** readability.  From this point on down, the normal indentation rules are
 86307  ** restored.
 86308  *****************************************************************************/
 86309      }
 86310  
 86311  #ifdef VDBE_PROFILE
 86312      {
 86313        u64 endTime = sqlite3Hwtime();
 86314        if( endTime>start ) pOrigOp->cycles += endTime - start;
 86315        pOrigOp->cnt++;
 86316      }
 86317  #endif
 86318  
 86319      /* The following code adds nothing to the actual functionality
 86320      ** of the program.  It is only here for testing and debugging.
 86321      ** On the other hand, it does burn CPU cycles every time through
 86322      ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
 86323      */
 86324  #ifndef NDEBUG
 86325      assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
 86326  
 86327  #ifdef SQLITE_DEBUG
 86328      if( db->flags & SQLITE_VdbeTrace ){
 86329        u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
 86330        if( rc!=0 ) printf("rc=%d\n",rc);
 86331        if( opProperty & (OPFLG_OUT2) ){
 86332          registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
 86333        }
 86334        if( opProperty & OPFLG_OUT3 ){
 86335          registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
 86336        }
 86337      }
 86338  #endif  /* SQLITE_DEBUG */
 86339  #endif  /* NDEBUG */
 86340    }  /* The end of the for(;;) loop the loops through opcodes */
 86341  
 86342    /* If we reach this point, it means that execution is finished with
 86343    ** an error of some kind.
 86344    */
 86345  abort_due_to_error:
 86346    if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
 86347    assert( rc );
 86348    if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
 86349      sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
 86350    }
 86351    p->rc = rc;
 86352    sqlite3SystemError(db, rc);
 86353    testcase( sqlite3GlobalConfig.xLog!=0 );
 86354    sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
 86355                     (int)(pOp - aOp), p->zSql, p->zErrMsg);
 86356    sqlite3VdbeHalt(p);
 86357    if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
 86358    rc = SQLITE_ERROR;
 86359    if( resetSchemaOnFault>0 ){
 86360      sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
 86361    }
 86362  
 86363    /* This is the only way out of this procedure.  We have to
 86364    ** release the mutexes on btrees that were acquired at the
 86365    ** top. */
 86366  vdbe_return:
 86367    testcase( nVmStep>0 );
 86368    p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
 86369    sqlite3VdbeLeave(p);
 86370    assert( rc!=SQLITE_OK || nExtraDelete==0 
 86371         || sqlite3_strlike("DELETE%",p->zSql,0)!=0 
 86372    );
 86373    return rc;
 86374  
 86375    /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
 86376    ** is encountered.
 86377    */
 86378  too_big:
 86379    sqlite3VdbeError(p, "string or blob too big");
 86380    rc = SQLITE_TOOBIG;
 86381    goto abort_due_to_error;
 86382  
 86383    /* Jump to here if a malloc() fails.
 86384    */
 86385  no_mem:
 86386    sqlite3OomFault(db);
 86387    sqlite3VdbeError(p, "out of memory");
 86388    rc = SQLITE_NOMEM_BKPT;
 86389    goto abort_due_to_error;
 86390  
 86391    /* Jump to here if the sqlite3_interrupt() API sets the interrupt
 86392    ** flag.
 86393    */
 86394  abort_due_to_interrupt:
 86395    assert( db->u1.isInterrupted );
 86396    rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
 86397    p->rc = rc;
 86398    sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
 86399    goto abort_due_to_error;
 86400  }
 86401  
 86402  
 86403  /************** End of vdbe.c ************************************************/
 86404  /************** Begin file vdbeblob.c ****************************************/
 86405  /*
 86406  ** 2007 May 1
 86407  **
 86408  ** The author disclaims copyright to this source code.  In place of
 86409  ** a legal notice, here is a blessing:
 86410  **
 86411  **    May you do good and not evil.
 86412  **    May you find forgiveness for yourself and forgive others.
 86413  **    May you share freely, never taking more than you give.
 86414  **
 86415  *************************************************************************
 86416  **
 86417  ** This file contains code used to implement incremental BLOB I/O.
 86418  */
 86419  
 86420  /* #include "sqliteInt.h" */
 86421  /* #include "vdbeInt.h" */
 86422  
 86423  #ifndef SQLITE_OMIT_INCRBLOB
 86424  
 86425  /*
 86426  ** Valid sqlite3_blob* handles point to Incrblob structures.
 86427  */
 86428  typedef struct Incrblob Incrblob;
 86429  struct Incrblob {
 86430    int nByte;              /* Size of open blob, in bytes */
 86431    int iOffset;            /* Byte offset of blob in cursor data */
 86432    u16 iCol;               /* Table column this handle is open on */
 86433    BtCursor *pCsr;         /* Cursor pointing at blob row */
 86434    sqlite3_stmt *pStmt;    /* Statement holding cursor open */
 86435    sqlite3 *db;            /* The associated database */
 86436    char *zDb;              /* Database name */
 86437    Table *pTab;            /* Table object */
 86438  };
 86439  
 86440  
 86441  /*
 86442  ** This function is used by both blob_open() and blob_reopen(). It seeks
 86443  ** the b-tree cursor associated with blob handle p to point to row iRow.
 86444  ** If successful, SQLITE_OK is returned and subsequent calls to
 86445  ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
 86446  **
 86447  ** If an error occurs, or if the specified row does not exist or does not
 86448  ** contain a value of type TEXT or BLOB in the column nominated when the
 86449  ** blob handle was opened, then an error code is returned and *pzErr may
 86450  ** be set to point to a buffer containing an error message. It is the
 86451  ** responsibility of the caller to free the error message buffer using
 86452  ** sqlite3DbFree().
 86453  **
 86454  ** If an error does occur, then the b-tree cursor is closed. All subsequent
 86455  ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will 
 86456  ** immediately return SQLITE_ABORT.
 86457  */
 86458  static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
 86459    int rc;                         /* Error code */
 86460    char *zErr = 0;                 /* Error message */
 86461    Vdbe *v = (Vdbe *)p->pStmt;
 86462  
 86463    /* Set the value of register r[1] in the SQL statement to integer iRow. 
 86464    ** This is done directly as a performance optimization
 86465    */
 86466    v->aMem[1].flags = MEM_Int;
 86467    v->aMem[1].u.i = iRow;
 86468  
 86469    /* If the statement has been run before (and is paused at the OP_ResultRow)
 86470    ** then back it up to the point where it does the OP_NotExists.  This could
 86471    ** have been down with an extra OP_Goto, but simply setting the program
 86472    ** counter is faster. */
 86473    if( v->pc>4 ){
 86474      v->pc = 4;
 86475      assert( v->aOp[v->pc].opcode==OP_NotExists );
 86476      rc = sqlite3VdbeExec(v);
 86477    }else{
 86478      rc = sqlite3_step(p->pStmt);
 86479    }
 86480    if( rc==SQLITE_ROW ){
 86481      VdbeCursor *pC = v->apCsr[0];
 86482      u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
 86483      testcase( pC->nHdrParsed==p->iCol );
 86484      testcase( pC->nHdrParsed==p->iCol+1 );
 86485      if( type<12 ){
 86486        zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
 86487            type==0?"null": type==7?"real": "integer"
 86488        );
 86489        rc = SQLITE_ERROR;
 86490        sqlite3_finalize(p->pStmt);
 86491        p->pStmt = 0;
 86492      }else{
 86493        p->iOffset = pC->aType[p->iCol + pC->nField];
 86494        p->nByte = sqlite3VdbeSerialTypeLen(type);
 86495        p->pCsr =  pC->uc.pCursor;
 86496        sqlite3BtreeIncrblobCursor(p->pCsr);
 86497      }
 86498    }
 86499  
 86500    if( rc==SQLITE_ROW ){
 86501      rc = SQLITE_OK;
 86502    }else if( p->pStmt ){
 86503      rc = sqlite3_finalize(p->pStmt);
 86504      p->pStmt = 0;
 86505      if( rc==SQLITE_OK ){
 86506        zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
 86507        rc = SQLITE_ERROR;
 86508      }else{
 86509        zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
 86510      }
 86511    }
 86512  
 86513    assert( rc!=SQLITE_OK || zErr==0 );
 86514    assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
 86515  
 86516    *pzErr = zErr;
 86517    return rc;
 86518  }
 86519  
 86520  /*
 86521  ** Open a blob handle.
 86522  */
 86523  SQLITE_API int sqlite3_blob_open(
 86524    sqlite3* db,            /* The database connection */
 86525    const char *zDb,        /* The attached database containing the blob */
 86526    const char *zTable,     /* The table containing the blob */
 86527    const char *zColumn,    /* The column containing the blob */
 86528    sqlite_int64 iRow,      /* The row containing the glob */
 86529    int wrFlag,             /* True -> read/write access, false -> read-only */
 86530    sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
 86531  ){
 86532    int nAttempt = 0;
 86533    int iCol;               /* Index of zColumn in row-record */
 86534    int rc = SQLITE_OK;
 86535    char *zErr = 0;
 86536    Table *pTab;
 86537    Incrblob *pBlob = 0;
 86538    Parse sParse;
 86539  
 86540  #ifdef SQLITE_ENABLE_API_ARMOR
 86541    if( ppBlob==0 ){
 86542      return SQLITE_MISUSE_BKPT;
 86543    }
 86544  #endif
 86545    *ppBlob = 0;
 86546  #ifdef SQLITE_ENABLE_API_ARMOR
 86547    if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
 86548      return SQLITE_MISUSE_BKPT;
 86549    }
 86550  #endif
 86551    wrFlag = !!wrFlag;                /* wrFlag = (wrFlag ? 1 : 0); */
 86552  
 86553    sqlite3_mutex_enter(db->mutex);
 86554  
 86555    pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
 86556    do {
 86557      memset(&sParse, 0, sizeof(Parse));
 86558      if( !pBlob ) goto blob_open_out;
 86559      sParse.db = db;
 86560      sqlite3DbFree(db, zErr);
 86561      zErr = 0;
 86562  
 86563      sqlite3BtreeEnterAll(db);
 86564      pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
 86565      if( pTab && IsVirtual(pTab) ){
 86566        pTab = 0;
 86567        sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
 86568      }
 86569      if( pTab && !HasRowid(pTab) ){
 86570        pTab = 0;
 86571        sqlite3ErrorMsg(&sParse, "cannot open table without rowid: %s", zTable);
 86572      }
 86573  #ifndef SQLITE_OMIT_VIEW
 86574      if( pTab && pTab->pSelect ){
 86575        pTab = 0;
 86576        sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
 86577      }
 86578  #endif
 86579      if( !pTab ){
 86580        if( sParse.zErrMsg ){
 86581          sqlite3DbFree(db, zErr);
 86582          zErr = sParse.zErrMsg;
 86583          sParse.zErrMsg = 0;
 86584        }
 86585        rc = SQLITE_ERROR;
 86586        sqlite3BtreeLeaveAll(db);
 86587        goto blob_open_out;
 86588      }
 86589      pBlob->pTab = pTab;
 86590      pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
 86591  
 86592      /* Now search pTab for the exact column. */
 86593      for(iCol=0; iCol<pTab->nCol; iCol++) {
 86594        if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
 86595          break;
 86596        }
 86597      }
 86598      if( iCol==pTab->nCol ){
 86599        sqlite3DbFree(db, zErr);
 86600        zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
 86601        rc = SQLITE_ERROR;
 86602        sqlite3BtreeLeaveAll(db);
 86603        goto blob_open_out;
 86604      }
 86605  
 86606      /* If the value is being opened for writing, check that the
 86607      ** column is not indexed, and that it is not part of a foreign key. 
 86608      */
 86609      if( wrFlag ){
 86610        const char *zFault = 0;
 86611        Index *pIdx;
 86612  #ifndef SQLITE_OMIT_FOREIGN_KEY
 86613        if( db->flags&SQLITE_ForeignKeys ){
 86614          /* Check that the column is not part of an FK child key definition. It
 86615          ** is not necessary to check if it is part of a parent key, as parent
 86616          ** key columns must be indexed. The check below will pick up this 
 86617          ** case.  */
 86618          FKey *pFKey;
 86619          for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
 86620            int j;
 86621            for(j=0; j<pFKey->nCol; j++){
 86622              if( pFKey->aCol[j].iFrom==iCol ){
 86623                zFault = "foreign key";
 86624              }
 86625            }
 86626          }
 86627        }
 86628  #endif
 86629        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
 86630          int j;
 86631          for(j=0; j<pIdx->nKeyCol; j++){
 86632            /* FIXME: Be smarter about indexes that use expressions */
 86633            if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
 86634              zFault = "indexed";
 86635            }
 86636          }
 86637        }
 86638        if( zFault ){
 86639          sqlite3DbFree(db, zErr);
 86640          zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
 86641          rc = SQLITE_ERROR;
 86642          sqlite3BtreeLeaveAll(db);
 86643          goto blob_open_out;
 86644        }
 86645      }
 86646  
 86647      pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(&sParse);
 86648      assert( pBlob->pStmt || db->mallocFailed );
 86649      if( pBlob->pStmt ){
 86650        
 86651        /* This VDBE program seeks a btree cursor to the identified 
 86652        ** db/table/row entry. The reason for using a vdbe program instead
 86653        ** of writing code to use the b-tree layer directly is that the
 86654        ** vdbe program will take advantage of the various transaction,
 86655        ** locking and error handling infrastructure built into the vdbe.
 86656        **
 86657        ** After seeking the cursor, the vdbe executes an OP_ResultRow.
 86658        ** Code external to the Vdbe then "borrows" the b-tree cursor and
 86659        ** uses it to implement the blob_read(), blob_write() and 
 86660        ** blob_bytes() functions.
 86661        **
 86662        ** The sqlite3_blob_close() function finalizes the vdbe program,
 86663        ** which closes the b-tree cursor and (possibly) commits the 
 86664        ** transaction.
 86665        */
 86666        static const int iLn = VDBE_OFFSET_LINENO(2);
 86667        static const VdbeOpList openBlob[] = {
 86668          {OP_TableLock,      0, 0, 0},  /* 0: Acquire a read or write lock */
 86669          {OP_OpenRead,       0, 0, 0},  /* 1: Open a cursor */
 86670          /* blobSeekToRow() will initialize r[1] to the desired rowid */
 86671          {OP_NotExists,      0, 5, 1},  /* 2: Seek the cursor to rowid=r[1] */
 86672          {OP_Column,         0, 0, 1},  /* 3  */
 86673          {OP_ResultRow,      1, 0, 0},  /* 4  */
 86674          {OP_Halt,           0, 0, 0},  /* 5  */
 86675        };
 86676        Vdbe *v = (Vdbe *)pBlob->pStmt;
 86677        int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
 86678        VdbeOp *aOp;
 86679  
 86680        sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag, 
 86681                             pTab->pSchema->schema_cookie,
 86682                             pTab->pSchema->iGeneration);
 86683        sqlite3VdbeChangeP5(v, 1);
 86684        assert( sqlite3VdbeCurrentAddr(v)==2 || db->mallocFailed );
 86685        aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
 86686  
 86687        /* Make sure a mutex is held on the table to be accessed */
 86688        sqlite3VdbeUsesBtree(v, iDb); 
 86689  
 86690        if( db->mallocFailed==0 ){
 86691          assert( aOp!=0 );
 86692          /* Configure the OP_TableLock instruction */
 86693  #ifdef SQLITE_OMIT_SHARED_CACHE
 86694          aOp[0].opcode = OP_Noop;
 86695  #else
 86696          aOp[0].p1 = iDb;
 86697          aOp[0].p2 = pTab->tnum;
 86698          aOp[0].p3 = wrFlag;
 86699          sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
 86700        }
 86701        if( db->mallocFailed==0 ){
 86702  #endif
 86703  
 86704          /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
 86705          ** parameter of the other to pTab->tnum.  */
 86706          if( wrFlag ) aOp[1].opcode = OP_OpenWrite;
 86707          aOp[1].p2 = pTab->tnum;
 86708          aOp[1].p3 = iDb;   
 86709  
 86710          /* Configure the number of columns. Configure the cursor to
 86711          ** think that the table has one more column than it really
 86712          ** does. An OP_Column to retrieve this imaginary column will
 86713          ** always return an SQL NULL. This is useful because it means
 86714          ** we can invoke OP_Column to fill in the vdbe cursors type 
 86715          ** and offset cache without causing any IO.
 86716          */
 86717          aOp[1].p4type = P4_INT32;
 86718          aOp[1].p4.i = pTab->nCol+1;
 86719          aOp[3].p2 = pTab->nCol;
 86720  
 86721          sParse.nVar = 0;
 86722          sParse.nMem = 1;
 86723          sParse.nTab = 1;
 86724          sqlite3VdbeMakeReady(v, &sParse);
 86725        }
 86726      }
 86727     
 86728      pBlob->iCol = iCol;
 86729      pBlob->db = db;
 86730      sqlite3BtreeLeaveAll(db);
 86731      if( db->mallocFailed ){
 86732        goto blob_open_out;
 86733      }
 86734      rc = blobSeekToRow(pBlob, iRow, &zErr);
 86735    } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
 86736  
 86737  blob_open_out:
 86738    if( rc==SQLITE_OK && db->mallocFailed==0 ){
 86739      *ppBlob = (sqlite3_blob *)pBlob;
 86740    }else{
 86741      if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
 86742      sqlite3DbFree(db, pBlob);
 86743    }
 86744    sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
 86745    sqlite3DbFree(db, zErr);
 86746    sqlite3ParserReset(&sParse);
 86747    rc = sqlite3ApiExit(db, rc);
 86748    sqlite3_mutex_leave(db->mutex);
 86749    return rc;
 86750  }
 86751  
 86752  /*
 86753  ** Close a blob handle that was previously created using
 86754  ** sqlite3_blob_open().
 86755  */
 86756  SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
 86757    Incrblob *p = (Incrblob *)pBlob;
 86758    int rc;
 86759    sqlite3 *db;
 86760  
 86761    if( p ){
 86762      db = p->db;
 86763      sqlite3_mutex_enter(db->mutex);
 86764      rc = sqlite3_finalize(p->pStmt);
 86765      sqlite3DbFree(db, p);
 86766      sqlite3_mutex_leave(db->mutex);
 86767    }else{
 86768      rc = SQLITE_OK;
 86769    }
 86770    return rc;
 86771  }
 86772  
 86773  /*
 86774  ** Perform a read or write operation on a blob
 86775  */
 86776  static int blobReadWrite(
 86777    sqlite3_blob *pBlob, 
 86778    void *z, 
 86779    int n, 
 86780    int iOffset, 
 86781    int (*xCall)(BtCursor*, u32, u32, void*)
 86782  ){
 86783    int rc;
 86784    Incrblob *p = (Incrblob *)pBlob;
 86785    Vdbe *v;
 86786    sqlite3 *db;
 86787  
 86788    if( p==0 ) return SQLITE_MISUSE_BKPT;
 86789    db = p->db;
 86790    sqlite3_mutex_enter(db->mutex);
 86791    v = (Vdbe*)p->pStmt;
 86792  
 86793    if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
 86794      /* Request is out of range. Return a transient error. */
 86795      rc = SQLITE_ERROR;
 86796    }else if( v==0 ){
 86797      /* If there is no statement handle, then the blob-handle has
 86798      ** already been invalidated. Return SQLITE_ABORT in this case.
 86799      */
 86800      rc = SQLITE_ABORT;
 86801    }else{
 86802      /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
 86803      ** returned, clean-up the statement handle.
 86804      */
 86805      assert( db == v->db );
 86806      sqlite3BtreeEnterCursor(p->pCsr);
 86807  
 86808  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 86809      if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
 86810        /* If a pre-update hook is registered and this is a write cursor, 
 86811        ** invoke it here. 
 86812        ** 
 86813        ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
 86814        ** operation should really be an SQLITE_UPDATE. This is probably
 86815        ** incorrect, but is convenient because at this point the new.* values 
 86816        ** are not easily obtainable. And for the sessions module, an 
 86817        ** SQLITE_UPDATE where the PK columns do not change is handled in the 
 86818        ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
 86819        ** slightly more efficient). Since you cannot write to a PK column
 86820        ** using the incremental-blob API, this works. For the sessions module
 86821        ** anyhow.
 86822        */
 86823        sqlite3_int64 iKey;
 86824        iKey = sqlite3BtreeIntegerKey(p->pCsr);
 86825        sqlite3VdbePreUpdateHook(
 86826            v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
 86827        );
 86828      }
 86829  #endif
 86830  
 86831      rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
 86832      sqlite3BtreeLeaveCursor(p->pCsr);
 86833      if( rc==SQLITE_ABORT ){
 86834        sqlite3VdbeFinalize(v);
 86835        p->pStmt = 0;
 86836      }else{
 86837        v->rc = rc;
 86838      }
 86839    }
 86840    sqlite3Error(db, rc);
 86841    rc = sqlite3ApiExit(db, rc);
 86842    sqlite3_mutex_leave(db->mutex);
 86843    return rc;
 86844  }
 86845  
 86846  /*
 86847  ** Read data from a blob handle.
 86848  */
 86849  SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
 86850    return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked);
 86851  }
 86852  
 86853  /*
 86854  ** Write data to a blob handle.
 86855  */
 86856  SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
 86857    return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
 86858  }
 86859  
 86860  /*
 86861  ** Query a blob handle for the size of the data.
 86862  **
 86863  ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
 86864  ** so no mutex is required for access.
 86865  */
 86866  SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
 86867    Incrblob *p = (Incrblob *)pBlob;
 86868    return (p && p->pStmt) ? p->nByte : 0;
 86869  }
 86870  
 86871  /*
 86872  ** Move an existing blob handle to point to a different row of the same
 86873  ** database table.
 86874  **
 86875  ** If an error occurs, or if the specified row does not exist or does not
 86876  ** contain a blob or text value, then an error code is returned and the
 86877  ** database handle error code and message set. If this happens, then all 
 86878  ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) 
 86879  ** immediately return SQLITE_ABORT.
 86880  */
 86881  SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
 86882    int rc;
 86883    Incrblob *p = (Incrblob *)pBlob;
 86884    sqlite3 *db;
 86885  
 86886    if( p==0 ) return SQLITE_MISUSE_BKPT;
 86887    db = p->db;
 86888    sqlite3_mutex_enter(db->mutex);
 86889  
 86890    if( p->pStmt==0 ){
 86891      /* If there is no statement handle, then the blob-handle has
 86892      ** already been invalidated. Return SQLITE_ABORT in this case.
 86893      */
 86894      rc = SQLITE_ABORT;
 86895    }else{
 86896      char *zErr;
 86897      rc = blobSeekToRow(p, iRow, &zErr);
 86898      if( rc!=SQLITE_OK ){
 86899        sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
 86900        sqlite3DbFree(db, zErr);
 86901      }
 86902      assert( rc!=SQLITE_SCHEMA );
 86903    }
 86904  
 86905    rc = sqlite3ApiExit(db, rc);
 86906    assert( rc==SQLITE_OK || p->pStmt==0 );
 86907    sqlite3_mutex_leave(db->mutex);
 86908    return rc;
 86909  }
 86910  
 86911  #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
 86912  
 86913  /************** End of vdbeblob.c ********************************************/
 86914  /************** Begin file vdbesort.c ****************************************/
 86915  /*
 86916  ** 2011-07-09
 86917  **
 86918  ** The author disclaims copyright to this source code.  In place of
 86919  ** a legal notice, here is a blessing:
 86920  **
 86921  **    May you do good and not evil.
 86922  **    May you find forgiveness for yourself and forgive others.
 86923  **    May you share freely, never taking more than you give.
 86924  **
 86925  *************************************************************************
 86926  ** This file contains code for the VdbeSorter object, used in concert with
 86927  ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
 86928  ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
 86929  ** using indexes and without LIMIT clauses.
 86930  **
 86931  ** The VdbeSorter object implements a multi-threaded external merge sort
 86932  ** algorithm that is efficient even if the number of elements being sorted
 86933  ** exceeds the available memory.
 86934  **
 86935  ** Here is the (internal, non-API) interface between this module and the
 86936  ** rest of the SQLite system:
 86937  **
 86938  **    sqlite3VdbeSorterInit()       Create a new VdbeSorter object.
 86939  **
 86940  **    sqlite3VdbeSorterWrite()      Add a single new row to the VdbeSorter
 86941  **                                  object.  The row is a binary blob in the
 86942  **                                  OP_MakeRecord format that contains both
 86943  **                                  the ORDER BY key columns and result columns
 86944  **                                  in the case of a SELECT w/ ORDER BY, or
 86945  **                                  the complete record for an index entry
 86946  **                                  in the case of a CREATE INDEX.
 86947  **
 86948  **    sqlite3VdbeSorterRewind()     Sort all content previously added.
 86949  **                                  Position the read cursor on the
 86950  **                                  first sorted element.
 86951  **
 86952  **    sqlite3VdbeSorterNext()       Advance the read cursor to the next sorted
 86953  **                                  element.
 86954  **
 86955  **    sqlite3VdbeSorterRowkey()     Return the complete binary blob for the
 86956  **                                  row currently under the read cursor.
 86957  **
 86958  **    sqlite3VdbeSorterCompare()    Compare the binary blob for the row
 86959  **                                  currently under the read cursor against
 86960  **                                  another binary blob X and report if
 86961  **                                  X is strictly less than the read cursor.
 86962  **                                  Used to enforce uniqueness in a
 86963  **                                  CREATE UNIQUE INDEX statement.
 86964  **
 86965  **    sqlite3VdbeSorterClose()      Close the VdbeSorter object and reclaim
 86966  **                                  all resources.
 86967  **
 86968  **    sqlite3VdbeSorterReset()      Refurbish the VdbeSorter for reuse.  This
 86969  **                                  is like Close() followed by Init() only
 86970  **                                  much faster.
 86971  **
 86972  ** The interfaces above must be called in a particular order.  Write() can 
 86973  ** only occur in between Init()/Reset() and Rewind().  Next(), Rowkey(), and
 86974  ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
 86975  **
 86976  **   Init()
 86977  **   for each record: Write()
 86978  **   Rewind()
 86979  **     Rowkey()/Compare()
 86980  **   Next() 
 86981  **   Close()
 86982  **
 86983  ** Algorithm:
 86984  **
 86985  ** Records passed to the sorter via calls to Write() are initially held 
 86986  ** unsorted in main memory. Assuming the amount of memory used never exceeds
 86987  ** a threshold, when Rewind() is called the set of records is sorted using
 86988  ** an in-memory merge sort. In this case, no temporary files are required
 86989  ** and subsequent calls to Rowkey(), Next() and Compare() read records 
 86990  ** directly from main memory.
 86991  **
 86992  ** If the amount of space used to store records in main memory exceeds the
 86993  ** threshold, then the set of records currently in memory are sorted and
 86994  ** written to a temporary file in "Packed Memory Array" (PMA) format.
 86995  ** A PMA created at this point is known as a "level-0 PMA". Higher levels
 86996  ** of PMAs may be created by merging existing PMAs together - for example
 86997  ** merging two or more level-0 PMAs together creates a level-1 PMA.
 86998  **
 86999  ** The threshold for the amount of main memory to use before flushing 
 87000  ** records to a PMA is roughly the same as the limit configured for the
 87001  ** page-cache of the main database. Specifically, the threshold is set to 
 87002  ** the value returned by "PRAGMA main.page_size" multipled by 
 87003  ** that returned by "PRAGMA main.cache_size", in bytes.
 87004  **
 87005  ** If the sorter is running in single-threaded mode, then all PMAs generated
 87006  ** are appended to a single temporary file. Or, if the sorter is running in
 87007  ** multi-threaded mode then up to (N+1) temporary files may be opened, where
 87008  ** N is the configured number of worker threads. In this case, instead of
 87009  ** sorting the records and writing the PMA to a temporary file itself, the
 87010  ** calling thread usually launches a worker thread to do so. Except, if
 87011  ** there are already N worker threads running, the main thread does the work
 87012  ** itself.
 87013  **
 87014  ** The sorter is running in multi-threaded mode if (a) the library was built
 87015  ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
 87016  ** than zero, and (b) worker threads have been enabled at runtime by calling
 87017  ** "PRAGMA threads=N" with some value of N greater than 0.
 87018  **
 87019  ** When Rewind() is called, any data remaining in memory is flushed to a 
 87020  ** final PMA. So at this point the data is stored in some number of sorted
 87021  ** PMAs within temporary files on disk.
 87022  **
 87023  ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
 87024  ** sorter is running in single-threaded mode, then these PMAs are merged
 87025  ** incrementally as keys are retreived from the sorter by the VDBE.  The
 87026  ** MergeEngine object, described in further detail below, performs this
 87027  ** merge.
 87028  **
 87029  ** Or, if running in multi-threaded mode, then a background thread is
 87030  ** launched to merge the existing PMAs. Once the background thread has
 87031  ** merged T bytes of data into a single sorted PMA, the main thread 
 87032  ** begins reading keys from that PMA while the background thread proceeds
 87033  ** with merging the next T bytes of data. And so on.
 87034  **
 87035  ** Parameter T is set to half the value of the memory threshold used 
 87036  ** by Write() above to determine when to create a new PMA.
 87037  **
 87038  ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when 
 87039  ** Rewind() is called, then a hierarchy of incremental-merges is used. 
 87040  ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on 
 87041  ** disk are merged together. Then T bytes of data from the second set, and
 87042  ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
 87043  ** PMAs at a time. This done is to improve locality.
 87044  **
 87045  ** If running in multi-threaded mode and there are more than
 87046  ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
 87047  ** than one background thread may be created. Specifically, there may be
 87048  ** one background thread for each temporary file on disk, and one background
 87049  ** thread to merge the output of each of the others to a single PMA for
 87050  ** the main thread to read from.
 87051  */
 87052  /* #include "sqliteInt.h" */
 87053  /* #include "vdbeInt.h" */
 87054  
 87055  /* 
 87056  ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
 87057  ** messages to stderr that may be helpful in understanding the performance
 87058  ** characteristics of the sorter in multi-threaded mode.
 87059  */
 87060  #if 0
 87061  # define SQLITE_DEBUG_SORTER_THREADS 1
 87062  #endif
 87063  
 87064  /*
 87065  ** Hard-coded maximum amount of data to accumulate in memory before flushing
 87066  ** to a level 0 PMA. The purpose of this limit is to prevent various integer
 87067  ** overflows. 512MiB.
 87068  */
 87069  #define SQLITE_MAX_PMASZ    (1<<29)
 87070  
 87071  /*
 87072  ** Private objects used by the sorter
 87073  */
 87074  typedef struct MergeEngine MergeEngine;     /* Merge PMAs together */
 87075  typedef struct PmaReader PmaReader;         /* Incrementally read one PMA */
 87076  typedef struct PmaWriter PmaWriter;         /* Incrementally write one PMA */
 87077  typedef struct SorterRecord SorterRecord;   /* A record being sorted */
 87078  typedef struct SortSubtask SortSubtask;     /* A sub-task in the sort process */
 87079  typedef struct SorterFile SorterFile;       /* Temporary file object wrapper */
 87080  typedef struct SorterList SorterList;       /* In-memory list of records */
 87081  typedef struct IncrMerger IncrMerger;       /* Read & merge multiple PMAs */
 87082  
 87083  /*
 87084  ** A container for a temp file handle and the current amount of data 
 87085  ** stored in the file.
 87086  */
 87087  struct SorterFile {
 87088    sqlite3_file *pFd;              /* File handle */
 87089    i64 iEof;                       /* Bytes of data stored in pFd */
 87090  };
 87091  
 87092  /*
 87093  ** An in-memory list of objects to be sorted.
 87094  **
 87095  ** If aMemory==0 then each object is allocated separately and the objects
 87096  ** are connected using SorterRecord.u.pNext.  If aMemory!=0 then all objects
 87097  ** are stored in the aMemory[] bulk memory, one right after the other, and
 87098  ** are connected using SorterRecord.u.iNext.
 87099  */
 87100  struct SorterList {
 87101    SorterRecord *pList;            /* Linked list of records */
 87102    u8 *aMemory;                    /* If non-NULL, bulk memory to hold pList */
 87103    int szPMA;                      /* Size of pList as PMA in bytes */
 87104  };
 87105  
 87106  /*
 87107  ** The MergeEngine object is used to combine two or more smaller PMAs into
 87108  ** one big PMA using a merge operation.  Separate PMAs all need to be
 87109  ** combined into one big PMA in order to be able to step through the sorted
 87110  ** records in order.
 87111  **
 87112  ** The aReadr[] array contains a PmaReader object for each of the PMAs being
 87113  ** merged.  An aReadr[] object either points to a valid key or else is at EOF.
 87114  ** ("EOF" means "End Of File".  When aReadr[] is at EOF there is no more data.)
 87115  ** For the purposes of the paragraphs below, we assume that the array is
 87116  ** actually N elements in size, where N is the smallest power of 2 greater
 87117  ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
 87118  ** are treated as if they are empty (always at EOF).
 87119  **
 87120  ** The aTree[] array is also N elements in size. The value of N is stored in
 87121  ** the MergeEngine.nTree variable.
 87122  **
 87123  ** The final (N/2) elements of aTree[] contain the results of comparing
 87124  ** pairs of PMA keys together. Element i contains the result of 
 87125  ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
 87126  ** aTree element is set to the index of it. 
 87127  **
 87128  ** For the purposes of this comparison, EOF is considered greater than any
 87129  ** other key value. If the keys are equal (only possible with two EOF
 87130  ** values), it doesn't matter which index is stored.
 87131  **
 87132  ** The (N/4) elements of aTree[] that precede the final (N/2) described 
 87133  ** above contains the index of the smallest of each block of 4 PmaReaders
 87134  ** And so on. So that aTree[1] contains the index of the PmaReader that 
 87135  ** currently points to the smallest key value. aTree[0] is unused.
 87136  **
 87137  ** Example:
 87138  **
 87139  **     aReadr[0] -> Banana
 87140  **     aReadr[1] -> Feijoa
 87141  **     aReadr[2] -> Elderberry
 87142  **     aReadr[3] -> Currant
 87143  **     aReadr[4] -> Grapefruit
 87144  **     aReadr[5] -> Apple
 87145  **     aReadr[6] -> Durian
 87146  **     aReadr[7] -> EOF
 87147  **
 87148  **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
 87149  **
 87150  ** The current element is "Apple" (the value of the key indicated by 
 87151  ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
 87152  ** be advanced to the next key in its segment. Say the next key is
 87153  ** "Eggplant":
 87154  **
 87155  **     aReadr[5] -> Eggplant
 87156  **
 87157  ** The contents of aTree[] are updated first by comparing the new PmaReader
 87158  ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
 87159  ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
 87160  ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
 87161  ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
 87162  ** so the value written into element 1 of the array is 0. As follows:
 87163  **
 87164  **     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
 87165  **
 87166  ** In other words, each time we advance to the next sorter element, log2(N)
 87167  ** key comparison operations are required, where N is the number of segments
 87168  ** being merged (rounded up to the next power of 2).
 87169  */
 87170  struct MergeEngine {
 87171    int nTree;                 /* Used size of aTree/aReadr (power of 2) */
 87172    SortSubtask *pTask;        /* Used by this thread only */
 87173    int *aTree;                /* Current state of incremental merge */
 87174    PmaReader *aReadr;         /* Array of PmaReaders to merge data from */
 87175  };
 87176  
 87177  /*
 87178  ** This object represents a single thread of control in a sort operation.
 87179  ** Exactly VdbeSorter.nTask instances of this object are allocated
 87180  ** as part of each VdbeSorter object. Instances are never allocated any
 87181  ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
 87182  ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread).  Thus for
 87183  ** single-threaded operation, there is exactly one instance of this object
 87184  ** and for multi-threaded operation there are two or more instances.
 87185  **
 87186  ** Essentially, this structure contains all those fields of the VdbeSorter
 87187  ** structure for which each thread requires a separate instance. For example,
 87188  ** each thread requries its own UnpackedRecord object to unpack records in
 87189  ** as part of comparison operations.
 87190  **
 87191  ** Before a background thread is launched, variable bDone is set to 0. Then, 
 87192  ** right before it exits, the thread itself sets bDone to 1. This is used for 
 87193  ** two purposes:
 87194  **
 87195  **   1. When flushing the contents of memory to a level-0 PMA on disk, to
 87196  **      attempt to select a SortSubtask for which there is not already an
 87197  **      active background thread (since doing so causes the main thread
 87198  **      to block until it finishes).
 87199  **
 87200  **   2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
 87201  **      to sqlite3ThreadJoin() is likely to block. Cases that are likely to
 87202  **      block provoke debugging output.
 87203  **
 87204  ** In both cases, the effects of the main thread seeing (bDone==0) even
 87205  ** after the thread has finished are not dire. So we don't worry about
 87206  ** memory barriers and such here.
 87207  */
 87208  typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
 87209  struct SortSubtask {
 87210    SQLiteThread *pThread;          /* Background thread, if any */
 87211    int bDone;                      /* Set if thread is finished but not joined */
 87212    VdbeSorter *pSorter;            /* Sorter that owns this sub-task */
 87213    UnpackedRecord *pUnpacked;      /* Space to unpack a record */
 87214    SorterList list;                /* List for thread to write to a PMA */
 87215    int nPMA;                       /* Number of PMAs currently in file */
 87216    SorterCompare xCompare;         /* Compare function to use */
 87217    SorterFile file;                /* Temp file for level-0 PMAs */
 87218    SorterFile file2;               /* Space for other PMAs */
 87219  };
 87220  
 87221  
 87222  /*
 87223  ** Main sorter structure. A single instance of this is allocated for each 
 87224  ** sorter cursor created by the VDBE.
 87225  **
 87226  ** mxKeysize:
 87227  **   As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
 87228  **   this variable is updated so as to be set to the size on disk of the
 87229  **   largest record in the sorter.
 87230  */
 87231  struct VdbeSorter {
 87232    int mnPmaSize;                  /* Minimum PMA size, in bytes */
 87233    int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
 87234    int mxKeysize;                  /* Largest serialized key seen so far */
 87235    int pgsz;                       /* Main database page size */
 87236    PmaReader *pReader;             /* Readr data from here after Rewind() */
 87237    MergeEngine *pMerger;           /* Or here, if bUseThreads==0 */
 87238    sqlite3 *db;                    /* Database connection */
 87239    KeyInfo *pKeyInfo;              /* How to compare records */
 87240    UnpackedRecord *pUnpacked;      /* Used by VdbeSorterCompare() */
 87241    SorterList list;                /* List of in-memory records */
 87242    int iMemory;                    /* Offset of free space in list.aMemory */
 87243    int nMemory;                    /* Size of list.aMemory allocation in bytes */
 87244    u8 bUsePMA;                     /* True if one or more PMAs created */
 87245    u8 bUseThreads;                 /* True to use background threads */
 87246    u8 iPrev;                       /* Previous thread used to flush PMA */
 87247    u8 nTask;                       /* Size of aTask[] array */
 87248    u8 typeMask;
 87249    SortSubtask aTask[1];           /* One or more subtasks */
 87250  };
 87251  
 87252  #define SORTER_TYPE_INTEGER 0x01
 87253  #define SORTER_TYPE_TEXT    0x02
 87254  
 87255  /*
 87256  ** An instance of the following object is used to read records out of a
 87257  ** PMA, in sorted order.  The next key to be read is cached in nKey/aKey.
 87258  ** aKey might point into aMap or into aBuffer.  If neither of those locations
 87259  ** contain a contiguous representation of the key, then aAlloc is allocated
 87260  ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
 87261  **
 87262  ** pFd==0 at EOF.
 87263  */
 87264  struct PmaReader {
 87265    i64 iReadOff;               /* Current read offset */
 87266    i64 iEof;                   /* 1 byte past EOF for this PmaReader */
 87267    int nAlloc;                 /* Bytes of space at aAlloc */
 87268    int nKey;                   /* Number of bytes in key */
 87269    sqlite3_file *pFd;          /* File handle we are reading from */
 87270    u8 *aAlloc;                 /* Space for aKey if aBuffer and pMap wont work */
 87271    u8 *aKey;                   /* Pointer to current key */
 87272    u8 *aBuffer;                /* Current read buffer */
 87273    int nBuffer;                /* Size of read buffer in bytes */
 87274    u8 *aMap;                   /* Pointer to mapping of entire file */
 87275    IncrMerger *pIncr;          /* Incremental merger */
 87276  };
 87277  
 87278  /*
 87279  ** Normally, a PmaReader object iterates through an existing PMA stored 
 87280  ** within a temp file. However, if the PmaReader.pIncr variable points to
 87281  ** an object of the following type, it may be used to iterate/merge through
 87282  ** multiple PMAs simultaneously.
 87283  **
 87284  ** There are two types of IncrMerger object - single (bUseThread==0) and 
 87285  ** multi-threaded (bUseThread==1). 
 87286  **
 87287  ** A multi-threaded IncrMerger object uses two temporary files - aFile[0] 
 87288  ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in 
 87289  ** size. When the IncrMerger is initialized, it reads enough data from 
 87290  ** pMerger to populate aFile[0]. It then sets variables within the 
 87291  ** corresponding PmaReader object to read from that file and kicks off 
 87292  ** a background thread to populate aFile[1] with the next mxSz bytes of 
 87293  ** sorted record data from pMerger. 
 87294  **
 87295  ** When the PmaReader reaches the end of aFile[0], it blocks until the
 87296  ** background thread has finished populating aFile[1]. It then exchanges
 87297  ** the contents of the aFile[0] and aFile[1] variables within this structure,
 87298  ** sets the PmaReader fields to read from the new aFile[0] and kicks off
 87299  ** another background thread to populate the new aFile[1]. And so on, until
 87300  ** the contents of pMerger are exhausted.
 87301  **
 87302  ** A single-threaded IncrMerger does not open any temporary files of its
 87303  ** own. Instead, it has exclusive access to mxSz bytes of space beginning
 87304  ** at offset iStartOff of file pTask->file2. And instead of using a 
 87305  ** background thread to prepare data for the PmaReader, with a single
 87306  ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
 87307  ** keys from pMerger by the calling thread whenever the PmaReader runs out
 87308  ** of data.
 87309  */
 87310  struct IncrMerger {
 87311    SortSubtask *pTask;             /* Task that owns this merger */
 87312    MergeEngine *pMerger;           /* Merge engine thread reads data from */
 87313    i64 iStartOff;                  /* Offset to start writing file at */
 87314    int mxSz;                       /* Maximum bytes of data to store */
 87315    int bEof;                       /* Set to true when merge is finished */
 87316    int bUseThread;                 /* True to use a bg thread for this object */
 87317    SorterFile aFile[2];            /* aFile[0] for reading, [1] for writing */
 87318  };
 87319  
 87320  /*
 87321  ** An instance of this object is used for writing a PMA.
 87322  **
 87323  ** The PMA is written one record at a time.  Each record is of an arbitrary
 87324  ** size.  But I/O is more efficient if it occurs in page-sized blocks where
 87325  ** each block is aligned on a page boundary.  This object caches writes to
 87326  ** the PMA so that aligned, page-size blocks are written.
 87327  */
 87328  struct PmaWriter {
 87329    int eFWErr;                     /* Non-zero if in an error state */
 87330    u8 *aBuffer;                    /* Pointer to write buffer */
 87331    int nBuffer;                    /* Size of write buffer in bytes */
 87332    int iBufStart;                  /* First byte of buffer to write */
 87333    int iBufEnd;                    /* Last byte of buffer to write */
 87334    i64 iWriteOff;                  /* Offset of start of buffer in file */
 87335    sqlite3_file *pFd;              /* File handle to write to */
 87336  };
 87337  
 87338  /*
 87339  ** This object is the header on a single record while that record is being
 87340  ** held in memory and prior to being written out as part of a PMA.
 87341  **
 87342  ** How the linked list is connected depends on how memory is being managed
 87343  ** by this module. If using a separate allocation for each in-memory record
 87344  ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
 87345  ** SorterRecord.u.pNext pointers.
 87346  **
 87347  ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
 87348  ** then while records are being accumulated the list is linked using the
 87349  ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
 87350  ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
 87351  ** has finished passing records to the sorter, or when the in-memory buffer
 87352  ** is full, the list is sorted. As part of the sorting process, it is
 87353  ** converted to use the SorterRecord.u.pNext pointers. See function
 87354  ** vdbeSorterSort() for details.
 87355  */
 87356  struct SorterRecord {
 87357    int nVal;                       /* Size of the record in bytes */
 87358    union {
 87359      SorterRecord *pNext;          /* Pointer to next record in list */
 87360      int iNext;                    /* Offset within aMemory of next record */
 87361    } u;
 87362    /* The data for the record immediately follows this header */
 87363  };
 87364  
 87365  /* Return a pointer to the buffer containing the record data for SorterRecord
 87366  ** object p. Should be used as if:
 87367  **
 87368  **   void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
 87369  */
 87370  #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
 87371  
 87372  
 87373  /* Maximum number of PMAs that a single MergeEngine can merge */
 87374  #define SORTER_MAX_MERGE_COUNT 16
 87375  
 87376  static int vdbeIncrSwap(IncrMerger*);
 87377  static void vdbeIncrFree(IncrMerger *);
 87378  
 87379  /*
 87380  ** Free all memory belonging to the PmaReader object passed as the
 87381  ** argument. All structure fields are set to zero before returning.
 87382  */
 87383  static void vdbePmaReaderClear(PmaReader *pReadr){
 87384    sqlite3_free(pReadr->aAlloc);
 87385    sqlite3_free(pReadr->aBuffer);
 87386    if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
 87387    vdbeIncrFree(pReadr->pIncr);
 87388    memset(pReadr, 0, sizeof(PmaReader));
 87389  }
 87390  
 87391  /*
 87392  ** Read the next nByte bytes of data from the PMA p.
 87393  ** If successful, set *ppOut to point to a buffer containing the data
 87394  ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
 87395  ** error code.
 87396  **
 87397  ** The buffer returned in *ppOut is only valid until the
 87398  ** next call to this function.
 87399  */
 87400  static int vdbePmaReadBlob(
 87401    PmaReader *p,                   /* PmaReader from which to take the blob */
 87402    int nByte,                      /* Bytes of data to read */
 87403    u8 **ppOut                      /* OUT: Pointer to buffer containing data */
 87404  ){
 87405    int iBuf;                       /* Offset within buffer to read from */
 87406    int nAvail;                     /* Bytes of data available in buffer */
 87407  
 87408    if( p->aMap ){
 87409      *ppOut = &p->aMap[p->iReadOff];
 87410      p->iReadOff += nByte;
 87411      return SQLITE_OK;
 87412    }
 87413  
 87414    assert( p->aBuffer );
 87415  
 87416    /* If there is no more data to be read from the buffer, read the next 
 87417    ** p->nBuffer bytes of data from the file into it. Or, if there are less
 87418    ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
 87419    iBuf = p->iReadOff % p->nBuffer;
 87420    if( iBuf==0 ){
 87421      int nRead;                    /* Bytes to read from disk */
 87422      int rc;                       /* sqlite3OsRead() return code */
 87423  
 87424      /* Determine how many bytes of data to read. */
 87425      if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
 87426        nRead = p->nBuffer;
 87427      }else{
 87428        nRead = (int)(p->iEof - p->iReadOff);
 87429      }
 87430      assert( nRead>0 );
 87431  
 87432      /* Readr data from the file. Return early if an error occurs. */
 87433      rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
 87434      assert( rc!=SQLITE_IOERR_SHORT_READ );
 87435      if( rc!=SQLITE_OK ) return rc;
 87436    }
 87437    nAvail = p->nBuffer - iBuf; 
 87438  
 87439    if( nByte<=nAvail ){
 87440      /* The requested data is available in the in-memory buffer. In this
 87441      ** case there is no need to make a copy of the data, just return a 
 87442      ** pointer into the buffer to the caller.  */
 87443      *ppOut = &p->aBuffer[iBuf];
 87444      p->iReadOff += nByte;
 87445    }else{
 87446      /* The requested data is not all available in the in-memory buffer.
 87447      ** In this case, allocate space at p->aAlloc[] to copy the requested
 87448      ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
 87449      int nRem;                     /* Bytes remaining to copy */
 87450  
 87451      /* Extend the p->aAlloc[] allocation if required. */
 87452      if( p->nAlloc<nByte ){
 87453        u8 *aNew;
 87454        int nNew = MAX(128, p->nAlloc*2);
 87455        while( nByte>nNew ) nNew = nNew*2;
 87456        aNew = sqlite3Realloc(p->aAlloc, nNew);
 87457        if( !aNew ) return SQLITE_NOMEM_BKPT;
 87458        p->nAlloc = nNew;
 87459        p->aAlloc = aNew;
 87460      }
 87461  
 87462      /* Copy as much data as is available in the buffer into the start of
 87463      ** p->aAlloc[].  */
 87464      memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
 87465      p->iReadOff += nAvail;
 87466      nRem = nByte - nAvail;
 87467  
 87468      /* The following loop copies up to p->nBuffer bytes per iteration into
 87469      ** the p->aAlloc[] buffer.  */
 87470      while( nRem>0 ){
 87471        int rc;                     /* vdbePmaReadBlob() return code */
 87472        int nCopy;                  /* Number of bytes to copy */
 87473        u8 *aNext;                  /* Pointer to buffer to copy data from */
 87474  
 87475        nCopy = nRem;
 87476        if( nRem>p->nBuffer ) nCopy = p->nBuffer;
 87477        rc = vdbePmaReadBlob(p, nCopy, &aNext);
 87478        if( rc!=SQLITE_OK ) return rc;
 87479        assert( aNext!=p->aAlloc );
 87480        memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
 87481        nRem -= nCopy;
 87482      }
 87483  
 87484      *ppOut = p->aAlloc;
 87485    }
 87486  
 87487    return SQLITE_OK;
 87488  }
 87489  
 87490  /*
 87491  ** Read a varint from the stream of data accessed by p. Set *pnOut to
 87492  ** the value read.
 87493  */
 87494  static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
 87495    int iBuf;
 87496  
 87497    if( p->aMap ){
 87498      p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
 87499    }else{
 87500      iBuf = p->iReadOff % p->nBuffer;
 87501      if( iBuf && (p->nBuffer-iBuf)>=9 ){
 87502        p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
 87503      }else{
 87504        u8 aVarint[16], *a;
 87505        int i = 0, rc;
 87506        do{
 87507          rc = vdbePmaReadBlob(p, 1, &a);
 87508          if( rc ) return rc;
 87509          aVarint[(i++)&0xf] = a[0];
 87510        }while( (a[0]&0x80)!=0 );
 87511        sqlite3GetVarint(aVarint, pnOut);
 87512      }
 87513    }
 87514  
 87515    return SQLITE_OK;
 87516  }
 87517  
 87518  /*
 87519  ** Attempt to memory map file pFile. If successful, set *pp to point to the
 87520  ** new mapping and return SQLITE_OK. If the mapping is not attempted 
 87521  ** (because the file is too large or the VFS layer is configured not to use
 87522  ** mmap), return SQLITE_OK and set *pp to NULL.
 87523  **
 87524  ** Or, if an error occurs, return an SQLite error code. The final value of
 87525  ** *pp is undefined in this case.
 87526  */
 87527  static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
 87528    int rc = SQLITE_OK;
 87529    if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
 87530      sqlite3_file *pFd = pFile->pFd;
 87531      if( pFd->pMethods->iVersion>=3 ){
 87532        rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
 87533        testcase( rc!=SQLITE_OK );
 87534      }
 87535    }
 87536    return rc;
 87537  }
 87538  
 87539  /*
 87540  ** Attach PmaReader pReadr to file pFile (if it is not already attached to
 87541  ** that file) and seek it to offset iOff within the file.  Return SQLITE_OK 
 87542  ** if successful, or an SQLite error code if an error occurs.
 87543  */
 87544  static int vdbePmaReaderSeek(
 87545    SortSubtask *pTask,             /* Task context */
 87546    PmaReader *pReadr,              /* Reader whose cursor is to be moved */
 87547    SorterFile *pFile,              /* Sorter file to read from */
 87548    i64 iOff                        /* Offset in pFile */
 87549  ){
 87550    int rc = SQLITE_OK;
 87551  
 87552    assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
 87553  
 87554    if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
 87555    if( pReadr->aMap ){
 87556      sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
 87557      pReadr->aMap = 0;
 87558    }
 87559    pReadr->iReadOff = iOff;
 87560    pReadr->iEof = pFile->iEof;
 87561    pReadr->pFd = pFile->pFd;
 87562  
 87563    rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
 87564    if( rc==SQLITE_OK && pReadr->aMap==0 ){
 87565      int pgsz = pTask->pSorter->pgsz;
 87566      int iBuf = pReadr->iReadOff % pgsz;
 87567      if( pReadr->aBuffer==0 ){
 87568        pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
 87569        if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
 87570        pReadr->nBuffer = pgsz;
 87571      }
 87572      if( rc==SQLITE_OK && iBuf ){
 87573        int nRead = pgsz - iBuf;
 87574        if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
 87575          nRead = (int)(pReadr->iEof - pReadr->iReadOff);
 87576        }
 87577        rc = sqlite3OsRead(
 87578            pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
 87579        );
 87580        testcase( rc!=SQLITE_OK );
 87581      }
 87582    }
 87583  
 87584    return rc;
 87585  }
 87586  
 87587  /*
 87588  ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
 87589  ** no error occurs, or an SQLite error code if one does.
 87590  */
 87591  static int vdbePmaReaderNext(PmaReader *pReadr){
 87592    int rc = SQLITE_OK;             /* Return Code */
 87593    u64 nRec = 0;                   /* Size of record in bytes */
 87594  
 87595  
 87596    if( pReadr->iReadOff>=pReadr->iEof ){
 87597      IncrMerger *pIncr = pReadr->pIncr;
 87598      int bEof = 1;
 87599      if( pIncr ){
 87600        rc = vdbeIncrSwap(pIncr);
 87601        if( rc==SQLITE_OK && pIncr->bEof==0 ){
 87602          rc = vdbePmaReaderSeek(
 87603              pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
 87604          );
 87605          bEof = 0;
 87606        }
 87607      }
 87608  
 87609      if( bEof ){
 87610        /* This is an EOF condition */
 87611        vdbePmaReaderClear(pReadr);
 87612        testcase( rc!=SQLITE_OK );
 87613        return rc;
 87614      }
 87615    }
 87616  
 87617    if( rc==SQLITE_OK ){
 87618      rc = vdbePmaReadVarint(pReadr, &nRec);
 87619    }
 87620    if( rc==SQLITE_OK ){
 87621      pReadr->nKey = (int)nRec;
 87622      rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
 87623      testcase( rc!=SQLITE_OK );
 87624    }
 87625  
 87626    return rc;
 87627  }
 87628  
 87629  /*
 87630  ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
 87631  ** starting at offset iStart and ending at offset iEof-1. This function 
 87632  ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the 
 87633  ** PMA is empty).
 87634  **
 87635  ** If the pnByte parameter is NULL, then it is assumed that the file 
 87636  ** contains a single PMA, and that that PMA omits the initial length varint.
 87637  */
 87638  static int vdbePmaReaderInit(
 87639    SortSubtask *pTask,             /* Task context */
 87640    SorterFile *pFile,              /* Sorter file to read from */
 87641    i64 iStart,                     /* Start offset in pFile */
 87642    PmaReader *pReadr,              /* PmaReader to populate */
 87643    i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
 87644  ){
 87645    int rc;
 87646  
 87647    assert( pFile->iEof>iStart );
 87648    assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
 87649    assert( pReadr->aBuffer==0 );
 87650    assert( pReadr->aMap==0 );
 87651  
 87652    rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
 87653    if( rc==SQLITE_OK ){
 87654      u64 nByte = 0;                 /* Size of PMA in bytes */
 87655      rc = vdbePmaReadVarint(pReadr, &nByte);
 87656      pReadr->iEof = pReadr->iReadOff + nByte;
 87657      *pnByte += nByte;
 87658    }
 87659  
 87660    if( rc==SQLITE_OK ){
 87661      rc = vdbePmaReaderNext(pReadr);
 87662    }
 87663    return rc;
 87664  }
 87665  
 87666  /*
 87667  ** A version of vdbeSorterCompare() that assumes that it has already been
 87668  ** determined that the first field of key1 is equal to the first field of 
 87669  ** key2.
 87670  */
 87671  static int vdbeSorterCompareTail(
 87672    SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
 87673    int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
 87674    const void *pKey1, int nKey1,   /* Left side of comparison */
 87675    const void *pKey2, int nKey2    /* Right side of comparison */
 87676  ){
 87677    UnpackedRecord *r2 = pTask->pUnpacked;
 87678    if( *pbKey2Cached==0 ){
 87679      sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
 87680      *pbKey2Cached = 1;
 87681    }
 87682    return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
 87683  }
 87684  
 87685  /*
 87686  ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2, 
 87687  ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
 87688  ** used by the comparison. Return the result of the comparison.
 87689  **
 87690  ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
 87691  ** it is assumed that (pTask->pUnpacked) contains the unpacked version
 87692  ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
 87693  ** version of key2 and *pbKey2Cached set to true before returning.
 87694  **
 87695  ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
 87696  ** to SQLITE_NOMEM.
 87697  */
 87698  static int vdbeSorterCompare(
 87699    SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
 87700    int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
 87701    const void *pKey1, int nKey1,   /* Left side of comparison */
 87702    const void *pKey2, int nKey2    /* Right side of comparison */
 87703  ){
 87704    UnpackedRecord *r2 = pTask->pUnpacked;
 87705    if( !*pbKey2Cached ){
 87706      sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
 87707      *pbKey2Cached = 1;
 87708    }
 87709    return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
 87710  }
 87711  
 87712  /*
 87713  ** A specially optimized version of vdbeSorterCompare() that assumes that
 87714  ** the first field of each key is a TEXT value and that the collation
 87715  ** sequence to compare them with is BINARY.
 87716  */
 87717  static int vdbeSorterCompareText(
 87718    SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
 87719    int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
 87720    const void *pKey1, int nKey1,   /* Left side of comparison */
 87721    const void *pKey2, int nKey2    /* Right side of comparison */
 87722  ){
 87723    const u8 * const p1 = (const u8 * const)pKey1;
 87724    const u8 * const p2 = (const u8 * const)pKey2;
 87725    const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
 87726    const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
 87727  
 87728    int n1;
 87729    int n2;
 87730    int res;
 87731  
 87732    getVarint32(&p1[1], n1);
 87733    getVarint32(&p2[1], n2);
 87734    res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2);
 87735    if( res==0 ){
 87736      res = n1 - n2;
 87737    }
 87738  
 87739    if( res==0 ){
 87740      if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
 87741        res = vdbeSorterCompareTail(
 87742            pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
 87743        );
 87744      }
 87745    }else{
 87746      if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
 87747        res = res * -1;
 87748      }
 87749    }
 87750  
 87751    return res;
 87752  }
 87753  
 87754  /*
 87755  ** A specially optimized version of vdbeSorterCompare() that assumes that
 87756  ** the first field of each key is an INTEGER value.
 87757  */
 87758  static int vdbeSorterCompareInt(
 87759    SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
 87760    int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
 87761    const void *pKey1, int nKey1,   /* Left side of comparison */
 87762    const void *pKey2, int nKey2    /* Right side of comparison */
 87763  ){
 87764    const u8 * const p1 = (const u8 * const)pKey1;
 87765    const u8 * const p2 = (const u8 * const)pKey2;
 87766    const int s1 = p1[1];                 /* Left hand serial type */
 87767    const int s2 = p2[1];                 /* Right hand serial type */
 87768    const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
 87769    const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
 87770    int res;                              /* Return value */
 87771  
 87772    assert( (s1>0 && s1<7) || s1==8 || s1==9 );
 87773    assert( (s2>0 && s2<7) || s2==8 || s2==9 );
 87774  
 87775    if( s1==s2 ){
 87776      /* The two values have the same sign. Compare using memcmp(). */
 87777      static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8, 0, 0, 0 };
 87778      const u8 n = aLen[s1];
 87779      int i;
 87780      res = 0;
 87781      for(i=0; i<n; i++){
 87782        if( (res = v1[i] - v2[i])!=0 ){
 87783          if( ((v1[0] ^ v2[0]) & 0x80)!=0 ){
 87784            res = v1[0] & 0x80 ? -1 : +1;
 87785          }
 87786          break;
 87787        }
 87788      }
 87789    }else if( s1>7 && s2>7 ){
 87790      res = s1 - s2;
 87791    }else{
 87792      if( s2>7 ){
 87793        res = +1;
 87794      }else if( s1>7 ){
 87795        res = -1;
 87796      }else{
 87797        res = s1 - s2;
 87798      }
 87799      assert( res!=0 );
 87800  
 87801      if( res>0 ){
 87802        if( *v1 & 0x80 ) res = -1;
 87803      }else{
 87804        if( *v2 & 0x80 ) res = +1;
 87805      }
 87806    }
 87807  
 87808    if( res==0 ){
 87809      if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
 87810        res = vdbeSorterCompareTail(
 87811            pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
 87812        );
 87813      }
 87814    }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
 87815      res = res * -1;
 87816    }
 87817  
 87818    return res;
 87819  }
 87820  
 87821  /*
 87822  ** Initialize the temporary index cursor just opened as a sorter cursor.
 87823  **
 87824  ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nKeyField)
 87825  ** to determine the number of fields that should be compared from the
 87826  ** records being sorted. However, if the value passed as argument nField
 87827  ** is non-zero and the sorter is able to guarantee a stable sort, nField
 87828  ** is used instead. This is used when sorting records for a CREATE INDEX
 87829  ** statement. In this case, keys are always delivered to the sorter in
 87830  ** order of the primary key, which happens to be make up the final part 
 87831  ** of the records being sorted. So if the sort is stable, there is never
 87832  ** any reason to compare PK fields and they can be ignored for a small
 87833  ** performance boost.
 87834  **
 87835  ** The sorter can guarantee a stable sort when running in single-threaded
 87836  ** mode, but not in multi-threaded mode.
 87837  **
 87838  ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
 87839  */
 87840  SQLITE_PRIVATE int sqlite3VdbeSorterInit(
 87841    sqlite3 *db,                    /* Database connection (for malloc()) */
 87842    int nField,                     /* Number of key fields in each record */
 87843    VdbeCursor *pCsr                /* Cursor that holds the new sorter */
 87844  ){
 87845    int pgsz;                       /* Page size of main database */
 87846    int i;                          /* Used to iterate through aTask[] */
 87847    VdbeSorter *pSorter;            /* The new sorter */
 87848    KeyInfo *pKeyInfo;              /* Copy of pCsr->pKeyInfo with db==0 */
 87849    int szKeyInfo;                  /* Size of pCsr->pKeyInfo in bytes */
 87850    int sz;                         /* Size of pSorter in bytes */
 87851    int rc = SQLITE_OK;
 87852  #if SQLITE_MAX_WORKER_THREADS==0
 87853  # define nWorker 0
 87854  #else
 87855    int nWorker;
 87856  #endif
 87857  
 87858    /* Initialize the upper limit on the number of worker threads */
 87859  #if SQLITE_MAX_WORKER_THREADS>0
 87860    if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
 87861      nWorker = 0;
 87862    }else{
 87863      nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
 87864    }
 87865  #endif
 87866  
 87867    /* Do not allow the total number of threads (main thread + all workers)
 87868    ** to exceed the maximum merge count */
 87869  #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
 87870    if( nWorker>=SORTER_MAX_MERGE_COUNT ){
 87871      nWorker = SORTER_MAX_MERGE_COUNT-1;
 87872    }
 87873  #endif
 87874  
 87875    assert( pCsr->pKeyInfo && pCsr->pBtx==0 );
 87876    assert( pCsr->eCurType==CURTYPE_SORTER );
 87877    szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nKeyField-1)*sizeof(CollSeq*);
 87878    sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
 87879  
 87880    pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
 87881    pCsr->uc.pSorter = pSorter;
 87882    if( pSorter==0 ){
 87883      rc = SQLITE_NOMEM_BKPT;
 87884    }else{
 87885      pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
 87886      memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
 87887      pKeyInfo->db = 0;
 87888      if( nField && nWorker==0 ){
 87889        pKeyInfo->nKeyField = nField;
 87890      }
 87891      pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
 87892      pSorter->nTask = nWorker + 1;
 87893      pSorter->iPrev = (u8)(nWorker - 1);
 87894      pSorter->bUseThreads = (pSorter->nTask>1);
 87895      pSorter->db = db;
 87896      for(i=0; i<pSorter->nTask; i++){
 87897        SortSubtask *pTask = &pSorter->aTask[i];
 87898        pTask->pSorter = pSorter;
 87899      }
 87900  
 87901      if( !sqlite3TempInMemory(db) ){
 87902        i64 mxCache;                /* Cache size in bytes*/
 87903        u32 szPma = sqlite3GlobalConfig.szPma;
 87904        pSorter->mnPmaSize = szPma * pgsz;
 87905  
 87906        mxCache = db->aDb[0].pSchema->cache_size;
 87907        if( mxCache<0 ){
 87908          /* A negative cache-size value C indicates that the cache is abs(C)
 87909          ** KiB in size.  */
 87910          mxCache = mxCache * -1024;
 87911        }else{
 87912          mxCache = mxCache * pgsz;
 87913        }
 87914        mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
 87915        pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
 87916  
 87917        /* Avoid large memory allocations if the application has requested
 87918        ** SQLITE_CONFIG_SMALL_MALLOC. */
 87919        if( sqlite3GlobalConfig.bSmallMalloc==0 ){
 87920          assert( pSorter->iMemory==0 );
 87921          pSorter->nMemory = pgsz;
 87922          pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
 87923          if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
 87924        }
 87925      }
 87926  
 87927      if( pKeyInfo->nAllField<13 
 87928       && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
 87929      ){
 87930        pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
 87931      }
 87932    }
 87933  
 87934    return rc;
 87935  }
 87936  #undef nWorker   /* Defined at the top of this function */
 87937  
 87938  /*
 87939  ** Free the list of sorted records starting at pRecord.
 87940  */
 87941  static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
 87942    SorterRecord *p;
 87943    SorterRecord *pNext;
 87944    for(p=pRecord; p; p=pNext){
 87945      pNext = p->u.pNext;
 87946      sqlite3DbFree(db, p);
 87947    }
 87948  }
 87949  
 87950  /*
 87951  ** Free all resources owned by the object indicated by argument pTask. All 
 87952  ** fields of *pTask are zeroed before returning.
 87953  */
 87954  static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
 87955    sqlite3DbFree(db, pTask->pUnpacked);
 87956  #if SQLITE_MAX_WORKER_THREADS>0
 87957    /* pTask->list.aMemory can only be non-zero if it was handed memory
 87958    ** from the main thread.  That only occurs SQLITE_MAX_WORKER_THREADS>0 */
 87959    if( pTask->list.aMemory ){
 87960      sqlite3_free(pTask->list.aMemory);
 87961    }else
 87962  #endif
 87963    {
 87964      assert( pTask->list.aMemory==0 );
 87965      vdbeSorterRecordFree(0, pTask->list.pList);
 87966    }
 87967    if( pTask->file.pFd ){
 87968      sqlite3OsCloseFree(pTask->file.pFd);
 87969    }
 87970    if( pTask->file2.pFd ){
 87971      sqlite3OsCloseFree(pTask->file2.pFd);
 87972    }
 87973    memset(pTask, 0, sizeof(SortSubtask));
 87974  }
 87975  
 87976  #ifdef SQLITE_DEBUG_SORTER_THREADS
 87977  static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
 87978    i64 t;
 87979    int iTask = (pTask - pTask->pSorter->aTask);
 87980    sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
 87981    fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
 87982  }
 87983  static void vdbeSorterRewindDebug(const char *zEvent){
 87984    i64 t;
 87985    sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
 87986    fprintf(stderr, "%lld:X %s\n", t, zEvent);
 87987  }
 87988  static void vdbeSorterPopulateDebug(
 87989    SortSubtask *pTask,
 87990    const char *zEvent
 87991  ){
 87992    i64 t;
 87993    int iTask = (pTask - pTask->pSorter->aTask);
 87994    sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
 87995    fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
 87996  }
 87997  static void vdbeSorterBlockDebug(
 87998    SortSubtask *pTask,
 87999    int bBlocked,
 88000    const char *zEvent
 88001  ){
 88002    if( bBlocked ){
 88003      i64 t;
 88004      sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
 88005      fprintf(stderr, "%lld:main %s\n", t, zEvent);
 88006    }
 88007  }
 88008  #else
 88009  # define vdbeSorterWorkDebug(x,y)
 88010  # define vdbeSorterRewindDebug(y)
 88011  # define vdbeSorterPopulateDebug(x,y)
 88012  # define vdbeSorterBlockDebug(x,y,z)
 88013  #endif
 88014  
 88015  #if SQLITE_MAX_WORKER_THREADS>0
 88016  /*
 88017  ** Join thread pTask->thread.
 88018  */
 88019  static int vdbeSorterJoinThread(SortSubtask *pTask){
 88020    int rc = SQLITE_OK;
 88021    if( pTask->pThread ){
 88022  #ifdef SQLITE_DEBUG_SORTER_THREADS
 88023      int bDone = pTask->bDone;
 88024  #endif
 88025      void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
 88026      vdbeSorterBlockDebug(pTask, !bDone, "enter");
 88027      (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
 88028      vdbeSorterBlockDebug(pTask, !bDone, "exit");
 88029      rc = SQLITE_PTR_TO_INT(pRet);
 88030      assert( pTask->bDone==1 );
 88031      pTask->bDone = 0;
 88032      pTask->pThread = 0;
 88033    }
 88034    return rc;
 88035  }
 88036  
 88037  /*
 88038  ** Launch a background thread to run xTask(pIn).
 88039  */
 88040  static int vdbeSorterCreateThread(
 88041    SortSubtask *pTask,             /* Thread will use this task object */
 88042    void *(*xTask)(void*),          /* Routine to run in a separate thread */
 88043    void *pIn                       /* Argument passed into xTask() */
 88044  ){
 88045    assert( pTask->pThread==0 && pTask->bDone==0 );
 88046    return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
 88047  }
 88048  
 88049  /*
 88050  ** Join all outstanding threads launched by SorterWrite() to create 
 88051  ** level-0 PMAs.
 88052  */
 88053  static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
 88054    int rc = rcin;
 88055    int i;
 88056  
 88057    /* This function is always called by the main user thread.
 88058    **
 88059    ** If this function is being called after SorterRewind() has been called, 
 88060    ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
 88061    ** is currently attempt to join one of the other threads. To avoid a race
 88062    ** condition where this thread also attempts to join the same object, join 
 88063    ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
 88064    for(i=pSorter->nTask-1; i>=0; i--){
 88065      SortSubtask *pTask = &pSorter->aTask[i];
 88066      int rc2 = vdbeSorterJoinThread(pTask);
 88067      if( rc==SQLITE_OK ) rc = rc2;
 88068    }
 88069    return rc;
 88070  }
 88071  #else
 88072  # define vdbeSorterJoinAll(x,rcin) (rcin)
 88073  # define vdbeSorterJoinThread(pTask) SQLITE_OK
 88074  #endif
 88075  
 88076  /*
 88077  ** Allocate a new MergeEngine object capable of handling up to
 88078  ** nReader PmaReader inputs.
 88079  **
 88080  ** nReader is automatically rounded up to the next power of two.
 88081  ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
 88082  */
 88083  static MergeEngine *vdbeMergeEngineNew(int nReader){
 88084    int N = 2;                      /* Smallest power of two >= nReader */
 88085    int nByte;                      /* Total bytes of space to allocate */
 88086    MergeEngine *pNew;              /* Pointer to allocated object to return */
 88087  
 88088    assert( nReader<=SORTER_MAX_MERGE_COUNT );
 88089  
 88090    while( N<nReader ) N += N;
 88091    nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
 88092  
 88093    pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
 88094    if( pNew ){
 88095      pNew->nTree = N;
 88096      pNew->pTask = 0;
 88097      pNew->aReadr = (PmaReader*)&pNew[1];
 88098      pNew->aTree = (int*)&pNew->aReadr[N];
 88099    }
 88100    return pNew;
 88101  }
 88102  
 88103  /*
 88104  ** Free the MergeEngine object passed as the only argument.
 88105  */
 88106  static void vdbeMergeEngineFree(MergeEngine *pMerger){
 88107    int i;
 88108    if( pMerger ){
 88109      for(i=0; i<pMerger->nTree; i++){
 88110        vdbePmaReaderClear(&pMerger->aReadr[i]);
 88111      }
 88112    }
 88113    sqlite3_free(pMerger);
 88114  }
 88115  
 88116  /*
 88117  ** Free all resources associated with the IncrMerger object indicated by
 88118  ** the first argument.
 88119  */
 88120  static void vdbeIncrFree(IncrMerger *pIncr){
 88121    if( pIncr ){
 88122  #if SQLITE_MAX_WORKER_THREADS>0
 88123      if( pIncr->bUseThread ){
 88124        vdbeSorterJoinThread(pIncr->pTask);
 88125        if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
 88126        if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
 88127      }
 88128  #endif
 88129      vdbeMergeEngineFree(pIncr->pMerger);
 88130      sqlite3_free(pIncr);
 88131    }
 88132  }
 88133  
 88134  /*
 88135  ** Reset a sorting cursor back to its original empty state.
 88136  */
 88137  SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
 88138    int i;
 88139    (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
 88140    assert( pSorter->bUseThreads || pSorter->pReader==0 );
 88141  #if SQLITE_MAX_WORKER_THREADS>0
 88142    if( pSorter->pReader ){
 88143      vdbePmaReaderClear(pSorter->pReader);
 88144      sqlite3DbFree(db, pSorter->pReader);
 88145      pSorter->pReader = 0;
 88146    }
 88147  #endif
 88148    vdbeMergeEngineFree(pSorter->pMerger);
 88149    pSorter->pMerger = 0;
 88150    for(i=0; i<pSorter->nTask; i++){
 88151      SortSubtask *pTask = &pSorter->aTask[i];
 88152      vdbeSortSubtaskCleanup(db, pTask);
 88153      pTask->pSorter = pSorter;
 88154    }
 88155    if( pSorter->list.aMemory==0 ){
 88156      vdbeSorterRecordFree(0, pSorter->list.pList);
 88157    }
 88158    pSorter->list.pList = 0;
 88159    pSorter->list.szPMA = 0;
 88160    pSorter->bUsePMA = 0;
 88161    pSorter->iMemory = 0;
 88162    pSorter->mxKeysize = 0;
 88163    sqlite3DbFree(db, pSorter->pUnpacked);
 88164    pSorter->pUnpacked = 0;
 88165  }
 88166  
 88167  /*
 88168  ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
 88169  */
 88170  SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
 88171    VdbeSorter *pSorter;
 88172    assert( pCsr->eCurType==CURTYPE_SORTER );
 88173    pSorter = pCsr->uc.pSorter;
 88174    if( pSorter ){
 88175      sqlite3VdbeSorterReset(db, pSorter);
 88176      sqlite3_free(pSorter->list.aMemory);
 88177      sqlite3DbFree(db, pSorter);
 88178      pCsr->uc.pSorter = 0;
 88179    }
 88180  }
 88181  
 88182  #if SQLITE_MAX_MMAP_SIZE>0
 88183  /*
 88184  ** The first argument is a file-handle open on a temporary file. The file
 88185  ** is guaranteed to be nByte bytes or smaller in size. This function
 88186  ** attempts to extend the file to nByte bytes in size and to ensure that
 88187  ** the VFS has memory mapped it.
 88188  **
 88189  ** Whether or not the file does end up memory mapped of course depends on
 88190  ** the specific VFS implementation.
 88191  */
 88192  static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
 88193    if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
 88194      void *p = 0;
 88195      int chunksize = 4*1024;
 88196      sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
 88197      sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
 88198      sqlite3OsFetch(pFd, 0, (int)nByte, &p);
 88199      sqlite3OsUnfetch(pFd, 0, p);
 88200    }
 88201  }
 88202  #else
 88203  # define vdbeSorterExtendFile(x,y,z)
 88204  #endif
 88205  
 88206  /*
 88207  ** Allocate space for a file-handle and open a temporary file. If successful,
 88208  ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
 88209  ** Otherwise, set *ppFd to 0 and return an SQLite error code.
 88210  */
 88211  static int vdbeSorterOpenTempFile(
 88212    sqlite3 *db,                    /* Database handle doing sort */
 88213    i64 nExtend,                    /* Attempt to extend file to this size */
 88214    sqlite3_file **ppFd
 88215  ){
 88216    int rc;
 88217    if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
 88218    rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
 88219        SQLITE_OPEN_TEMP_JOURNAL |
 88220        SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
 88221        SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &rc
 88222    );
 88223    if( rc==SQLITE_OK ){
 88224      i64 max = SQLITE_MAX_MMAP_SIZE;
 88225      sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
 88226      if( nExtend>0 ){
 88227        vdbeSorterExtendFile(db, *ppFd, nExtend);
 88228      }
 88229    }
 88230    return rc;
 88231  }
 88232  
 88233  /*
 88234  ** If it has not already been allocated, allocate the UnpackedRecord 
 88235  ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or 
 88236  ** if no allocation was required), or SQLITE_NOMEM otherwise.
 88237  */
 88238  static int vdbeSortAllocUnpacked(SortSubtask *pTask){
 88239    if( pTask->pUnpacked==0 ){
 88240      pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo);
 88241      if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT;
 88242      pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nKeyField;
 88243      pTask->pUnpacked->errCode = 0;
 88244    }
 88245    return SQLITE_OK;
 88246  }
 88247  
 88248  
 88249  /*
 88250  ** Merge the two sorted lists p1 and p2 into a single list.
 88251  */
 88252  static SorterRecord *vdbeSorterMerge(
 88253    SortSubtask *pTask,             /* Calling thread context */
 88254    SorterRecord *p1,               /* First list to merge */
 88255    SorterRecord *p2                /* Second list to merge */
 88256  ){
 88257    SorterRecord *pFinal = 0;
 88258    SorterRecord **pp = &pFinal;
 88259    int bCached = 0;
 88260  
 88261    assert( p1!=0 && p2!=0 );
 88262    for(;;){
 88263      int res;
 88264      res = pTask->xCompare(
 88265          pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
 88266      );
 88267  
 88268      if( res<=0 ){
 88269        *pp = p1;
 88270        pp = &p1->u.pNext;
 88271        p1 = p1->u.pNext;
 88272        if( p1==0 ){
 88273          *pp = p2;
 88274          break;
 88275        }
 88276      }else{
 88277        *pp = p2;
 88278        pp = &p2->u.pNext;
 88279        p2 = p2->u.pNext;
 88280        bCached = 0;
 88281        if( p2==0 ){
 88282          *pp = p1;
 88283          break;
 88284        }
 88285      }
 88286    }
 88287    return pFinal;
 88288  }
 88289  
 88290  /*
 88291  ** Return the SorterCompare function to compare values collected by the
 88292  ** sorter object passed as the only argument.
 88293  */
 88294  static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
 88295    if( p->typeMask==SORTER_TYPE_INTEGER ){
 88296      return vdbeSorterCompareInt;
 88297    }else if( p->typeMask==SORTER_TYPE_TEXT ){
 88298      return vdbeSorterCompareText; 
 88299    }
 88300    return vdbeSorterCompare;
 88301  }
 88302  
 88303  /*
 88304  ** Sort the linked list of records headed at pTask->pList. Return 
 88305  ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if 
 88306  ** an error occurs.
 88307  */
 88308  static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
 88309    int i;
 88310    SorterRecord **aSlot;
 88311    SorterRecord *p;
 88312    int rc;
 88313  
 88314    rc = vdbeSortAllocUnpacked(pTask);
 88315    if( rc!=SQLITE_OK ) return rc;
 88316  
 88317    p = pList->pList;
 88318    pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
 88319  
 88320    aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
 88321    if( !aSlot ){
 88322      return SQLITE_NOMEM_BKPT;
 88323    }
 88324  
 88325    while( p ){
 88326      SorterRecord *pNext;
 88327      if( pList->aMemory ){
 88328        if( (u8*)p==pList->aMemory ){
 88329          pNext = 0;
 88330        }else{
 88331          assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
 88332          pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
 88333        }
 88334      }else{
 88335        pNext = p->u.pNext;
 88336      }
 88337  
 88338      p->u.pNext = 0;
 88339      for(i=0; aSlot[i]; i++){
 88340        p = vdbeSorterMerge(pTask, p, aSlot[i]);
 88341        aSlot[i] = 0;
 88342      }
 88343      aSlot[i] = p;
 88344      p = pNext;
 88345    }
 88346  
 88347    p = 0;
 88348    for(i=0; i<64; i++){
 88349      if( aSlot[i]==0 ) continue;
 88350      p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
 88351    }
 88352    pList->pList = p;
 88353  
 88354    sqlite3_free(aSlot);
 88355    assert( pTask->pUnpacked->errCode==SQLITE_OK 
 88356         || pTask->pUnpacked->errCode==SQLITE_NOMEM 
 88357    );
 88358    return pTask->pUnpacked->errCode;
 88359  }
 88360  
 88361  /*
 88362  ** Initialize a PMA-writer object.
 88363  */
 88364  static void vdbePmaWriterInit(
 88365    sqlite3_file *pFd,              /* File handle to write to */
 88366    PmaWriter *p,                   /* Object to populate */
 88367    int nBuf,                       /* Buffer size */
 88368    i64 iStart                      /* Offset of pFd to begin writing at */
 88369  ){
 88370    memset(p, 0, sizeof(PmaWriter));
 88371    p->aBuffer = (u8*)sqlite3Malloc(nBuf);
 88372    if( !p->aBuffer ){
 88373      p->eFWErr = SQLITE_NOMEM_BKPT;
 88374    }else{
 88375      p->iBufEnd = p->iBufStart = (iStart % nBuf);
 88376      p->iWriteOff = iStart - p->iBufStart;
 88377      p->nBuffer = nBuf;
 88378      p->pFd = pFd;
 88379    }
 88380  }
 88381  
 88382  /*
 88383  ** Write nData bytes of data to the PMA. Return SQLITE_OK
 88384  ** if successful, or an SQLite error code if an error occurs.
 88385  */
 88386  static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
 88387    int nRem = nData;
 88388    while( nRem>0 && p->eFWErr==0 ){
 88389      int nCopy = nRem;
 88390      if( nCopy>(p->nBuffer - p->iBufEnd) ){
 88391        nCopy = p->nBuffer - p->iBufEnd;
 88392      }
 88393  
 88394      memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
 88395      p->iBufEnd += nCopy;
 88396      if( p->iBufEnd==p->nBuffer ){
 88397        p->eFWErr = sqlite3OsWrite(p->pFd, 
 88398            &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 
 88399            p->iWriteOff + p->iBufStart
 88400        );
 88401        p->iBufStart = p->iBufEnd = 0;
 88402        p->iWriteOff += p->nBuffer;
 88403      }
 88404      assert( p->iBufEnd<p->nBuffer );
 88405  
 88406      nRem -= nCopy;
 88407    }
 88408  }
 88409  
 88410  /*
 88411  ** Flush any buffered data to disk and clean up the PMA-writer object.
 88412  ** The results of using the PMA-writer after this call are undefined.
 88413  ** Return SQLITE_OK if flushing the buffered data succeeds or is not 
 88414  ** required. Otherwise, return an SQLite error code.
 88415  **
 88416  ** Before returning, set *piEof to the offset immediately following the
 88417  ** last byte written to the file.
 88418  */
 88419  static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
 88420    int rc;
 88421    if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
 88422      p->eFWErr = sqlite3OsWrite(p->pFd, 
 88423          &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 
 88424          p->iWriteOff + p->iBufStart
 88425      );
 88426    }
 88427    *piEof = (p->iWriteOff + p->iBufEnd);
 88428    sqlite3_free(p->aBuffer);
 88429    rc = p->eFWErr;
 88430    memset(p, 0, sizeof(PmaWriter));
 88431    return rc;
 88432  }
 88433  
 88434  /*
 88435  ** Write value iVal encoded as a varint to the PMA. Return 
 88436  ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
 88437  */
 88438  static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
 88439    int nByte; 
 88440    u8 aByte[10];
 88441    nByte = sqlite3PutVarint(aByte, iVal);
 88442    vdbePmaWriteBlob(p, aByte, nByte);
 88443  }
 88444  
 88445  /*
 88446  ** Write the current contents of in-memory linked-list pList to a level-0
 88447  ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if 
 88448  ** successful, or an SQLite error code otherwise.
 88449  **
 88450  ** The format of a PMA is:
 88451  **
 88452  **     * A varint. This varint contains the total number of bytes of content
 88453  **       in the PMA (not including the varint itself).
 88454  **
 88455  **     * One or more records packed end-to-end in order of ascending keys. 
 88456  **       Each record consists of a varint followed by a blob of data (the 
 88457  **       key). The varint is the number of bytes in the blob of data.
 88458  */
 88459  static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
 88460    sqlite3 *db = pTask->pSorter->db;
 88461    int rc = SQLITE_OK;             /* Return code */
 88462    PmaWriter writer;               /* Object used to write to the file */
 88463  
 88464  #ifdef SQLITE_DEBUG
 88465    /* Set iSz to the expected size of file pTask->file after writing the PMA. 
 88466    ** This is used by an assert() statement at the end of this function.  */
 88467    i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
 88468  #endif
 88469  
 88470    vdbeSorterWorkDebug(pTask, "enter");
 88471    memset(&writer, 0, sizeof(PmaWriter));
 88472    assert( pList->szPMA>0 );
 88473  
 88474    /* If the first temporary PMA file has not been opened, open it now. */
 88475    if( pTask->file.pFd==0 ){
 88476      rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
 88477      assert( rc!=SQLITE_OK || pTask->file.pFd );
 88478      assert( pTask->file.iEof==0 );
 88479      assert( pTask->nPMA==0 );
 88480    }
 88481  
 88482    /* Try to get the file to memory map */
 88483    if( rc==SQLITE_OK ){
 88484      vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
 88485    }
 88486  
 88487    /* Sort the list */
 88488    if( rc==SQLITE_OK ){
 88489      rc = vdbeSorterSort(pTask, pList);
 88490    }
 88491  
 88492    if( rc==SQLITE_OK ){
 88493      SorterRecord *p;
 88494      SorterRecord *pNext = 0;
 88495  
 88496      vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
 88497                        pTask->file.iEof);
 88498      pTask->nPMA++;
 88499      vdbePmaWriteVarint(&writer, pList->szPMA);
 88500      for(p=pList->pList; p; p=pNext){
 88501        pNext = p->u.pNext;
 88502        vdbePmaWriteVarint(&writer, p->nVal);
 88503        vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
 88504        if( pList->aMemory==0 ) sqlite3_free(p);
 88505      }
 88506      pList->pList = p;
 88507      rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
 88508    }
 88509  
 88510    vdbeSorterWorkDebug(pTask, "exit");
 88511    assert( rc!=SQLITE_OK || pList->pList==0 );
 88512    assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
 88513    return rc;
 88514  }
 88515  
 88516  /*
 88517  ** Advance the MergeEngine to its next entry.
 88518  ** Set *pbEof to true there is no next entry because
 88519  ** the MergeEngine has reached the end of all its inputs.
 88520  **
 88521  ** Return SQLITE_OK if successful or an error code if an error occurs.
 88522  */
 88523  static int vdbeMergeEngineStep(
 88524    MergeEngine *pMerger,      /* The merge engine to advance to the next row */
 88525    int *pbEof                 /* Set TRUE at EOF.  Set false for more content */
 88526  ){
 88527    int rc;
 88528    int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
 88529    SortSubtask *pTask = pMerger->pTask;
 88530  
 88531    /* Advance the current PmaReader */
 88532    rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
 88533  
 88534    /* Update contents of aTree[] */
 88535    if( rc==SQLITE_OK ){
 88536      int i;                      /* Index of aTree[] to recalculate */
 88537      PmaReader *pReadr1;         /* First PmaReader to compare */
 88538      PmaReader *pReadr2;         /* Second PmaReader to compare */
 88539      int bCached = 0;
 88540  
 88541      /* Find the first two PmaReaders to compare. The one that was just
 88542      ** advanced (iPrev) and the one next to it in the array.  */
 88543      pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
 88544      pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
 88545  
 88546      for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
 88547        /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
 88548        int iRes;
 88549        if( pReadr1->pFd==0 ){
 88550          iRes = +1;
 88551        }else if( pReadr2->pFd==0 ){
 88552          iRes = -1;
 88553        }else{
 88554          iRes = pTask->xCompare(pTask, &bCached,
 88555              pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
 88556          );
 88557        }
 88558  
 88559        /* If pReadr1 contained the smaller value, set aTree[i] to its index.
 88560        ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
 88561        ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
 88562        ** pKey2 to point to the record belonging to pReadr2.
 88563        **
 88564        ** Alternatively, if pReadr2 contains the smaller of the two values,
 88565        ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
 88566        ** was actually called above, then pTask->pUnpacked now contains
 88567        ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
 88568        ** vdbeSorterCompare() from decoding pReadr2 again.
 88569        **
 88570        ** If the two values were equal, then the value from the oldest
 88571        ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
 88572        ** is sorted from oldest to newest, so pReadr1 contains older values
 88573        ** than pReadr2 iff (pReadr1<pReadr2).  */
 88574        if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
 88575          pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
 88576          pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
 88577          bCached = 0;
 88578        }else{
 88579          if( pReadr1->pFd ) bCached = 0;
 88580          pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
 88581          pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
 88582        }
 88583      }
 88584      *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
 88585    }
 88586  
 88587    return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
 88588  }
 88589  
 88590  #if SQLITE_MAX_WORKER_THREADS>0
 88591  /*
 88592  ** The main routine for background threads that write level-0 PMAs.
 88593  */
 88594  static void *vdbeSorterFlushThread(void *pCtx){
 88595    SortSubtask *pTask = (SortSubtask*)pCtx;
 88596    int rc;                         /* Return code */
 88597    assert( pTask->bDone==0 );
 88598    rc = vdbeSorterListToPMA(pTask, &pTask->list);
 88599    pTask->bDone = 1;
 88600    return SQLITE_INT_TO_PTR(rc);
 88601  }
 88602  #endif /* SQLITE_MAX_WORKER_THREADS>0 */
 88603  
 88604  /*
 88605  ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
 88606  ** using a background thread.
 88607  */
 88608  static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
 88609  #if SQLITE_MAX_WORKER_THREADS==0
 88610    pSorter->bUsePMA = 1;
 88611    return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
 88612  #else
 88613    int rc = SQLITE_OK;
 88614    int i;
 88615    SortSubtask *pTask = 0;    /* Thread context used to create new PMA */
 88616    int nWorker = (pSorter->nTask-1);
 88617  
 88618    /* Set the flag to indicate that at least one PMA has been written. 
 88619    ** Or will be, anyhow.  */
 88620    pSorter->bUsePMA = 1;
 88621  
 88622    /* Select a sub-task to sort and flush the current list of in-memory
 88623    ** records to disk. If the sorter is running in multi-threaded mode,
 88624    ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
 88625    ** the background thread from a sub-tasks previous turn is still running,
 88626    ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
 88627    ** fall back to using the final sub-task. The first (pSorter->nTask-1)
 88628    ** sub-tasks are prefered as they use background threads - the final 
 88629    ** sub-task uses the main thread. */
 88630    for(i=0; i<nWorker; i++){
 88631      int iTest = (pSorter->iPrev + i + 1) % nWorker;
 88632      pTask = &pSorter->aTask[iTest];
 88633      if( pTask->bDone ){
 88634        rc = vdbeSorterJoinThread(pTask);
 88635      }
 88636      if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
 88637    }
 88638  
 88639    if( rc==SQLITE_OK ){
 88640      if( i==nWorker ){
 88641        /* Use the foreground thread for this operation */
 88642        rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
 88643      }else{
 88644        /* Launch a background thread for this operation */
 88645        u8 *aMem = pTask->list.aMemory;
 88646        void *pCtx = (void*)pTask;
 88647  
 88648        assert( pTask->pThread==0 && pTask->bDone==0 );
 88649        assert( pTask->list.pList==0 );
 88650        assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
 88651  
 88652        pSorter->iPrev = (u8)(pTask - pSorter->aTask);
 88653        pTask->list = pSorter->list;
 88654        pSorter->list.pList = 0;
 88655        pSorter->list.szPMA = 0;
 88656        if( aMem ){
 88657          pSorter->list.aMemory = aMem;
 88658          pSorter->nMemory = sqlite3MallocSize(aMem);
 88659        }else if( pSorter->list.aMemory ){
 88660          pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
 88661          if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
 88662        }
 88663  
 88664        rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
 88665      }
 88666    }
 88667  
 88668    return rc;
 88669  #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
 88670  }
 88671  
 88672  /*
 88673  ** Add a record to the sorter.
 88674  */
 88675  SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
 88676    const VdbeCursor *pCsr,         /* Sorter cursor */
 88677    Mem *pVal                       /* Memory cell containing record */
 88678  ){
 88679    VdbeSorter *pSorter;
 88680    int rc = SQLITE_OK;             /* Return Code */
 88681    SorterRecord *pNew;             /* New list element */
 88682    int bFlush;                     /* True to flush contents of memory to PMA */
 88683    int nReq;                       /* Bytes of memory required */
 88684    int nPMA;                       /* Bytes of PMA space required */
 88685    int t;                          /* serial type of first record field */
 88686  
 88687    assert( pCsr->eCurType==CURTYPE_SORTER );
 88688    pSorter = pCsr->uc.pSorter;
 88689    getVarint32((const u8*)&pVal->z[1], t);
 88690    if( t>0 && t<10 && t!=7 ){
 88691      pSorter->typeMask &= SORTER_TYPE_INTEGER;
 88692    }else if( t>10 && (t & 0x01) ){
 88693      pSorter->typeMask &= SORTER_TYPE_TEXT;
 88694    }else{
 88695      pSorter->typeMask = 0;
 88696    }
 88697  
 88698    assert( pSorter );
 88699  
 88700    /* Figure out whether or not the current contents of memory should be
 88701    ** flushed to a PMA before continuing. If so, do so.
 88702    **
 88703    ** If using the single large allocation mode (pSorter->aMemory!=0), then
 88704    ** flush the contents of memory to a new PMA if (a) at least one value is
 88705    ** already in memory and (b) the new value will not fit in memory.
 88706    ** 
 88707    ** Or, if using separate allocations for each record, flush the contents
 88708    ** of memory to a PMA if either of the following are true:
 88709    **
 88710    **   * The total memory allocated for the in-memory list is greater 
 88711    **     than (page-size * cache-size), or
 88712    **
 88713    **   * The total memory allocated for the in-memory list is greater 
 88714    **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
 88715    */
 88716    nReq = pVal->n + sizeof(SorterRecord);
 88717    nPMA = pVal->n + sqlite3VarintLen(pVal->n);
 88718    if( pSorter->mxPmaSize ){
 88719      if( pSorter->list.aMemory ){
 88720        bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
 88721      }else{
 88722        bFlush = (
 88723            (pSorter->list.szPMA > pSorter->mxPmaSize)
 88724         || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
 88725        );
 88726      }
 88727      if( bFlush ){
 88728        rc = vdbeSorterFlushPMA(pSorter);
 88729        pSorter->list.szPMA = 0;
 88730        pSorter->iMemory = 0;
 88731        assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
 88732      }
 88733    }
 88734  
 88735    pSorter->list.szPMA += nPMA;
 88736    if( nPMA>pSorter->mxKeysize ){
 88737      pSorter->mxKeysize = nPMA;
 88738    }
 88739  
 88740    if( pSorter->list.aMemory ){
 88741      int nMin = pSorter->iMemory + nReq;
 88742  
 88743      if( nMin>pSorter->nMemory ){
 88744        u8 *aNew;
 88745        int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
 88746        int nNew = pSorter->nMemory * 2;
 88747        while( nNew < nMin ) nNew = nNew*2;
 88748        if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
 88749        if( nNew < nMin ) nNew = nMin;
 88750  
 88751        aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
 88752        if( !aNew ) return SQLITE_NOMEM_BKPT;
 88753        pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
 88754        pSorter->list.aMemory = aNew;
 88755        pSorter->nMemory = nNew;
 88756      }
 88757  
 88758      pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
 88759      pSorter->iMemory += ROUND8(nReq);
 88760      if( pSorter->list.pList ){
 88761        pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
 88762      }
 88763    }else{
 88764      pNew = (SorterRecord *)sqlite3Malloc(nReq);
 88765      if( pNew==0 ){
 88766        return SQLITE_NOMEM_BKPT;
 88767      }
 88768      pNew->u.pNext = pSorter->list.pList;
 88769    }
 88770  
 88771    memcpy(SRVAL(pNew), pVal->z, pVal->n);
 88772    pNew->nVal = pVal->n;
 88773    pSorter->list.pList = pNew;
 88774  
 88775    return rc;
 88776  }
 88777  
 88778  /*
 88779  ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
 88780  ** of the data stored in aFile[1] is the same as that used by regular PMAs,
 88781  ** except that the number-of-bytes varint is omitted from the start.
 88782  */
 88783  static int vdbeIncrPopulate(IncrMerger *pIncr){
 88784    int rc = SQLITE_OK;
 88785    int rc2;
 88786    i64 iStart = pIncr->iStartOff;
 88787    SorterFile *pOut = &pIncr->aFile[1];
 88788    SortSubtask *pTask = pIncr->pTask;
 88789    MergeEngine *pMerger = pIncr->pMerger;
 88790    PmaWriter writer;
 88791    assert( pIncr->bEof==0 );
 88792  
 88793    vdbeSorterPopulateDebug(pTask, "enter");
 88794  
 88795    vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
 88796    while( rc==SQLITE_OK ){
 88797      int dummy;
 88798      PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
 88799      int nKey = pReader->nKey;
 88800      i64 iEof = writer.iWriteOff + writer.iBufEnd;
 88801  
 88802      /* Check if the output file is full or if the input has been exhausted.
 88803      ** In either case exit the loop. */
 88804      if( pReader->pFd==0 ) break;
 88805      if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
 88806  
 88807      /* Write the next key to the output. */
 88808      vdbePmaWriteVarint(&writer, nKey);
 88809      vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
 88810      assert( pIncr->pMerger->pTask==pTask );
 88811      rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
 88812    }
 88813  
 88814    rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
 88815    if( rc==SQLITE_OK ) rc = rc2;
 88816    vdbeSorterPopulateDebug(pTask, "exit");
 88817    return rc;
 88818  }
 88819  
 88820  #if SQLITE_MAX_WORKER_THREADS>0
 88821  /*
 88822  ** The main routine for background threads that populate aFile[1] of
 88823  ** multi-threaded IncrMerger objects.
 88824  */
 88825  static void *vdbeIncrPopulateThread(void *pCtx){
 88826    IncrMerger *pIncr = (IncrMerger*)pCtx;
 88827    void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
 88828    pIncr->pTask->bDone = 1;
 88829    return pRet;
 88830  }
 88831  
 88832  /*
 88833  ** Launch a background thread to populate aFile[1] of pIncr.
 88834  */
 88835  static int vdbeIncrBgPopulate(IncrMerger *pIncr){
 88836    void *p = (void*)pIncr;
 88837    assert( pIncr->bUseThread );
 88838    return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
 88839  }
 88840  #endif
 88841  
 88842  /*
 88843  ** This function is called when the PmaReader corresponding to pIncr has
 88844  ** finished reading the contents of aFile[0]. Its purpose is to "refill"
 88845  ** aFile[0] such that the PmaReader should start rereading it from the
 88846  ** beginning.
 88847  **
 88848  ** For single-threaded objects, this is accomplished by literally reading 
 88849  ** keys from pIncr->pMerger and repopulating aFile[0]. 
 88850  **
 88851  ** For multi-threaded objects, all that is required is to wait until the 
 88852  ** background thread is finished (if it is not already) and then swap 
 88853  ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
 88854  ** been exhausted, this function also launches a new background thread
 88855  ** to populate the new aFile[1].
 88856  **
 88857  ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
 88858  */
 88859  static int vdbeIncrSwap(IncrMerger *pIncr){
 88860    int rc = SQLITE_OK;
 88861  
 88862  #if SQLITE_MAX_WORKER_THREADS>0
 88863    if( pIncr->bUseThread ){
 88864      rc = vdbeSorterJoinThread(pIncr->pTask);
 88865  
 88866      if( rc==SQLITE_OK ){
 88867        SorterFile f0 = pIncr->aFile[0];
 88868        pIncr->aFile[0] = pIncr->aFile[1];
 88869        pIncr->aFile[1] = f0;
 88870      }
 88871  
 88872      if( rc==SQLITE_OK ){
 88873        if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
 88874          pIncr->bEof = 1;
 88875        }else{
 88876          rc = vdbeIncrBgPopulate(pIncr);
 88877        }
 88878      }
 88879    }else
 88880  #endif
 88881    {
 88882      rc = vdbeIncrPopulate(pIncr);
 88883      pIncr->aFile[0] = pIncr->aFile[1];
 88884      if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
 88885        pIncr->bEof = 1;
 88886      }
 88887    }
 88888  
 88889    return rc;
 88890  }
 88891  
 88892  /*
 88893  ** Allocate and return a new IncrMerger object to read data from pMerger.
 88894  **
 88895  ** If an OOM condition is encountered, return NULL. In this case free the
 88896  ** pMerger argument before returning.
 88897  */
 88898  static int vdbeIncrMergerNew(
 88899    SortSubtask *pTask,     /* The thread that will be using the new IncrMerger */
 88900    MergeEngine *pMerger,   /* The MergeEngine that the IncrMerger will control */
 88901    IncrMerger **ppOut      /* Write the new IncrMerger here */
 88902  ){
 88903    int rc = SQLITE_OK;
 88904    IncrMerger *pIncr = *ppOut = (IncrMerger*)
 88905         (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
 88906    if( pIncr ){
 88907      pIncr->pMerger = pMerger;
 88908      pIncr->pTask = pTask;
 88909      pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
 88910      pTask->file2.iEof += pIncr->mxSz;
 88911    }else{
 88912      vdbeMergeEngineFree(pMerger);
 88913      rc = SQLITE_NOMEM_BKPT;
 88914    }
 88915    return rc;
 88916  }
 88917  
 88918  #if SQLITE_MAX_WORKER_THREADS>0
 88919  /*
 88920  ** Set the "use-threads" flag on object pIncr.
 88921  */
 88922  static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
 88923    pIncr->bUseThread = 1;
 88924    pIncr->pTask->file2.iEof -= pIncr->mxSz;
 88925  }
 88926  #endif /* SQLITE_MAX_WORKER_THREADS>0 */
 88927  
 88928  
 88929  
 88930  /*
 88931  ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
 88932  ** two PmaReaders that feed that entry.  Neither of the PmaReaders
 88933  ** are advanced.  This routine merely does the comparison.
 88934  */
 88935  static void vdbeMergeEngineCompare(
 88936    MergeEngine *pMerger,  /* Merge engine containing PmaReaders to compare */
 88937    int iOut               /* Store the result in pMerger->aTree[iOut] */
 88938  ){
 88939    int i1;
 88940    int i2;
 88941    int iRes;
 88942    PmaReader *p1;
 88943    PmaReader *p2;
 88944  
 88945    assert( iOut<pMerger->nTree && iOut>0 );
 88946  
 88947    if( iOut>=(pMerger->nTree/2) ){
 88948      i1 = (iOut - pMerger->nTree/2) * 2;
 88949      i2 = i1 + 1;
 88950    }else{
 88951      i1 = pMerger->aTree[iOut*2];
 88952      i2 = pMerger->aTree[iOut*2+1];
 88953    }
 88954  
 88955    p1 = &pMerger->aReadr[i1];
 88956    p2 = &pMerger->aReadr[i2];
 88957  
 88958    if( p1->pFd==0 ){
 88959      iRes = i2;
 88960    }else if( p2->pFd==0 ){
 88961      iRes = i1;
 88962    }else{
 88963      SortSubtask *pTask = pMerger->pTask;
 88964      int bCached = 0;
 88965      int res;
 88966      assert( pTask->pUnpacked!=0 );  /* from vdbeSortSubtaskMain() */
 88967      res = pTask->xCompare(
 88968          pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
 88969      );
 88970      if( res<=0 ){
 88971        iRes = i1;
 88972      }else{
 88973        iRes = i2;
 88974      }
 88975    }
 88976  
 88977    pMerger->aTree[iOut] = iRes;
 88978  }
 88979  
 88980  /*
 88981  ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
 88982  ** and vdbePmaReaderIncrMergeInit().
 88983  **
 88984  ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
 88985  ** SQLITE_MAX_WORKER_THREADS==0).  The other values are only used
 88986  ** when there exists one or more separate worker threads.
 88987  */
 88988  #define INCRINIT_NORMAL 0
 88989  #define INCRINIT_TASK   1
 88990  #define INCRINIT_ROOT   2
 88991  
 88992  /* 
 88993  ** Forward reference required as the vdbeIncrMergeInit() and
 88994  ** vdbePmaReaderIncrInit() routines are called mutually recursively when
 88995  ** building a merge tree.
 88996  */
 88997  static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
 88998  
 88999  /*
 89000  ** Initialize the MergeEngine object passed as the second argument. Once this
 89001  ** function returns, the first key of merged data may be read from the 
 89002  ** MergeEngine object in the usual fashion.
 89003  **
 89004  ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
 89005  ** objects attached to the PmaReader objects that the merger reads from have
 89006  ** already been populated, but that they have not yet populated aFile[0] and
 89007  ** set the PmaReader objects up to read from it. In this case all that is
 89008  ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
 89009  ** its first key.
 89010  **
 89011  ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use 
 89012  ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data 
 89013  ** to pMerger.
 89014  **
 89015  ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
 89016  */
 89017  static int vdbeMergeEngineInit(
 89018    SortSubtask *pTask,             /* Thread that will run pMerger */
 89019    MergeEngine *pMerger,           /* MergeEngine to initialize */
 89020    int eMode                       /* One of the INCRINIT_XXX constants */
 89021  ){
 89022    int rc = SQLITE_OK;             /* Return code */
 89023    int i;                          /* For looping over PmaReader objects */
 89024    int nTree = pMerger->nTree;
 89025  
 89026    /* eMode is always INCRINIT_NORMAL in single-threaded mode */
 89027    assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
 89028  
 89029    /* Verify that the MergeEngine is assigned to a single thread */
 89030    assert( pMerger->pTask==0 );
 89031    pMerger->pTask = pTask;
 89032  
 89033    for(i=0; i<nTree; i++){
 89034      if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
 89035        /* PmaReaders should be normally initialized in order, as if they are
 89036        ** reading from the same temp file this makes for more linear file IO.
 89037        ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
 89038        ** in use it will block the vdbePmaReaderNext() call while it uses
 89039        ** the main thread to fill its buffer. So calling PmaReaderNext()
 89040        ** on this PmaReader before any of the multi-threaded PmaReaders takes
 89041        ** better advantage of multi-processor hardware. */
 89042        rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
 89043      }else{
 89044        rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
 89045      }
 89046      if( rc!=SQLITE_OK ) return rc;
 89047    }
 89048  
 89049    for(i=pMerger->nTree-1; i>0; i--){
 89050      vdbeMergeEngineCompare(pMerger, i);
 89051    }
 89052    return pTask->pUnpacked->errCode;
 89053  }
 89054  
 89055  /*
 89056  ** The PmaReader passed as the first argument is guaranteed to be an
 89057  ** incremental-reader (pReadr->pIncr!=0). This function serves to open
 89058  ** and/or initialize the temp file related fields of the IncrMerge
 89059  ** object at (pReadr->pIncr).
 89060  **
 89061  ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
 89062  ** in the sub-tree headed by pReadr are also initialized. Data is then 
 89063  ** loaded into the buffers belonging to pReadr and it is set to point to 
 89064  ** the first key in its range.
 89065  **
 89066  ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
 89067  ** to be a multi-threaded PmaReader and this function is being called in a
 89068  ** background thread. In this case all PmaReaders in the sub-tree are 
 89069  ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
 89070  ** pReadr is populated. However, pReadr itself is not set up to point
 89071  ** to its first key. A call to vdbePmaReaderNext() is still required to do
 89072  ** that. 
 89073  **
 89074  ** The reason this function does not call vdbePmaReaderNext() immediately 
 89075  ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
 89076  ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
 89077  ** this entire function is being run by thread (pTask->thread), that will
 89078  ** lead to the current background thread attempting to join itself.
 89079  **
 89080  ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
 89081  ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
 89082  ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
 89083  ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
 89084  ** the current PmaReader set to point to the first key in its range.
 89085  **
 89086  ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
 89087  */
 89088  static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
 89089    int rc = SQLITE_OK;
 89090    IncrMerger *pIncr = pReadr->pIncr;
 89091    SortSubtask *pTask = pIncr->pTask;
 89092    sqlite3 *db = pTask->pSorter->db;
 89093  
 89094    /* eMode is always INCRINIT_NORMAL in single-threaded mode */
 89095    assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
 89096  
 89097    rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
 89098  
 89099    /* Set up the required files for pIncr. A multi-theaded IncrMerge object
 89100    ** requires two temp files to itself, whereas a single-threaded object
 89101    ** only requires a region of pTask->file2. */
 89102    if( rc==SQLITE_OK ){
 89103      int mxSz = pIncr->mxSz;
 89104  #if SQLITE_MAX_WORKER_THREADS>0
 89105      if( pIncr->bUseThread ){
 89106        rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
 89107        if( rc==SQLITE_OK ){
 89108          rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
 89109        }
 89110      }else
 89111  #endif
 89112      /*if( !pIncr->bUseThread )*/{
 89113        if( pTask->file2.pFd==0 ){
 89114          assert( pTask->file2.iEof>0 );
 89115          rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
 89116          pTask->file2.iEof = 0;
 89117        }
 89118        if( rc==SQLITE_OK ){
 89119          pIncr->aFile[1].pFd = pTask->file2.pFd;
 89120          pIncr->iStartOff = pTask->file2.iEof;
 89121          pTask->file2.iEof += mxSz;
 89122        }
 89123      }
 89124    }
 89125  
 89126  #if SQLITE_MAX_WORKER_THREADS>0
 89127    if( rc==SQLITE_OK && pIncr->bUseThread ){
 89128      /* Use the current thread to populate aFile[1], even though this
 89129      ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
 89130      ** then this function is already running in background thread 
 89131      ** pIncr->pTask->thread. 
 89132      **
 89133      ** If this is the INCRINIT_ROOT object, then it is running in the 
 89134      ** main VDBE thread. But that is Ok, as that thread cannot return
 89135      ** control to the VDBE or proceed with anything useful until the 
 89136      ** first results are ready from this merger object anyway.
 89137      */
 89138      assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
 89139      rc = vdbeIncrPopulate(pIncr);
 89140    }
 89141  #endif
 89142  
 89143    if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
 89144      rc = vdbePmaReaderNext(pReadr);
 89145    }
 89146  
 89147    return rc;
 89148  }
 89149  
 89150  #if SQLITE_MAX_WORKER_THREADS>0
 89151  /*
 89152  ** The main routine for vdbePmaReaderIncrMergeInit() operations run in 
 89153  ** background threads.
 89154  */
 89155  static void *vdbePmaReaderBgIncrInit(void *pCtx){
 89156    PmaReader *pReader = (PmaReader*)pCtx;
 89157    void *pRet = SQLITE_INT_TO_PTR(
 89158                    vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
 89159                 );
 89160    pReader->pIncr->pTask->bDone = 1;
 89161    return pRet;
 89162  }
 89163  #endif
 89164  
 89165  /*
 89166  ** If the PmaReader passed as the first argument is not an incremental-reader
 89167  ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
 89168  ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
 89169  ** this routine to initialize the incremental merge.
 89170  ** 
 89171  ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1), 
 89172  ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
 89173  ** Or, if the IncrMerger is single threaded, the same function is called
 89174  ** using the current thread.
 89175  */
 89176  static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
 89177    IncrMerger *pIncr = pReadr->pIncr;   /* Incremental merger */
 89178    int rc = SQLITE_OK;                  /* Return code */
 89179    if( pIncr ){
 89180  #if SQLITE_MAX_WORKER_THREADS>0
 89181      assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
 89182      if( pIncr->bUseThread ){
 89183        void *pCtx = (void*)pReadr;
 89184        rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
 89185      }else
 89186  #endif
 89187      {
 89188        rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
 89189      }
 89190    }
 89191    return rc;
 89192  }
 89193  
 89194  /*
 89195  ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
 89196  ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
 89197  ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
 89198  ** to NULL and return an SQLite error code.
 89199  **
 89200  ** When this function is called, *piOffset is set to the offset of the
 89201  ** first PMA to read from pTask->file. Assuming no error occurs, it is 
 89202  ** set to the offset immediately following the last byte of the last
 89203  ** PMA before returning. If an error does occur, then the final value of
 89204  ** *piOffset is undefined.
 89205  */
 89206  static int vdbeMergeEngineLevel0(
 89207    SortSubtask *pTask,             /* Sorter task to read from */
 89208    int nPMA,                       /* Number of PMAs to read */
 89209    i64 *piOffset,                  /* IN/OUT: Readr offset in pTask->file */
 89210    MergeEngine **ppOut             /* OUT: New merge-engine */
 89211  ){
 89212    MergeEngine *pNew;              /* Merge engine to return */
 89213    i64 iOff = *piOffset;
 89214    int i;
 89215    int rc = SQLITE_OK;
 89216  
 89217    *ppOut = pNew = vdbeMergeEngineNew(nPMA);
 89218    if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
 89219  
 89220    for(i=0; i<nPMA && rc==SQLITE_OK; i++){
 89221      i64 nDummy = 0;
 89222      PmaReader *pReadr = &pNew->aReadr[i];
 89223      rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
 89224      iOff = pReadr->iEof;
 89225    }
 89226  
 89227    if( rc!=SQLITE_OK ){
 89228      vdbeMergeEngineFree(pNew);
 89229      *ppOut = 0;
 89230    }
 89231    *piOffset = iOff;
 89232    return rc;
 89233  }
 89234  
 89235  /*
 89236  ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
 89237  ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
 89238  **
 89239  ** i.e.
 89240  **
 89241  **   nPMA<=16    -> TreeDepth() == 0
 89242  **   nPMA<=256   -> TreeDepth() == 1
 89243  **   nPMA<=65536 -> TreeDepth() == 2
 89244  */
 89245  static int vdbeSorterTreeDepth(int nPMA){
 89246    int nDepth = 0;
 89247    i64 nDiv = SORTER_MAX_MERGE_COUNT;
 89248    while( nDiv < (i64)nPMA ){
 89249      nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
 89250      nDepth++;
 89251    }
 89252    return nDepth;
 89253  }
 89254  
 89255  /*
 89256  ** pRoot is the root of an incremental merge-tree with depth nDepth (according
 89257  ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
 89258  ** tree, counting from zero. This function adds pLeaf to the tree.
 89259  **
 89260  ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
 89261  ** code is returned and pLeaf is freed.
 89262  */
 89263  static int vdbeSorterAddToTree(
 89264    SortSubtask *pTask,             /* Task context */
 89265    int nDepth,                     /* Depth of tree according to TreeDepth() */
 89266    int iSeq,                       /* Sequence number of leaf within tree */
 89267    MergeEngine *pRoot,             /* Root of tree */
 89268    MergeEngine *pLeaf              /* Leaf to add to tree */
 89269  ){
 89270    int rc = SQLITE_OK;
 89271    int nDiv = 1;
 89272    int i;
 89273    MergeEngine *p = pRoot;
 89274    IncrMerger *pIncr;
 89275  
 89276    rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
 89277  
 89278    for(i=1; i<nDepth; i++){
 89279      nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
 89280    }
 89281  
 89282    for(i=1; i<nDepth && rc==SQLITE_OK; i++){
 89283      int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
 89284      PmaReader *pReadr = &p->aReadr[iIter];
 89285  
 89286      if( pReadr->pIncr==0 ){
 89287        MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
 89288        if( pNew==0 ){
 89289          rc = SQLITE_NOMEM_BKPT;
 89290        }else{
 89291          rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
 89292        }
 89293      }
 89294      if( rc==SQLITE_OK ){
 89295        p = pReadr->pIncr->pMerger;
 89296        nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
 89297      }
 89298    }
 89299  
 89300    if( rc==SQLITE_OK ){
 89301      p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
 89302    }else{
 89303      vdbeIncrFree(pIncr);
 89304    }
 89305    return rc;
 89306  }
 89307  
 89308  /*
 89309  ** This function is called as part of a SorterRewind() operation on a sorter
 89310  ** that has already written two or more level-0 PMAs to one or more temp
 89311  ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that 
 89312  ** can be used to incrementally merge all PMAs on disk.
 89313  **
 89314  ** If successful, SQLITE_OK is returned and *ppOut set to point to the
 89315  ** MergeEngine object at the root of the tree before returning. Or, if an
 89316  ** error occurs, an SQLite error code is returned and the final value 
 89317  ** of *ppOut is undefined.
 89318  */
 89319  static int vdbeSorterMergeTreeBuild(
 89320    VdbeSorter *pSorter,       /* The VDBE cursor that implements the sort */
 89321    MergeEngine **ppOut        /* Write the MergeEngine here */
 89322  ){
 89323    MergeEngine *pMain = 0;
 89324    int rc = SQLITE_OK;
 89325    int iTask;
 89326  
 89327  #if SQLITE_MAX_WORKER_THREADS>0
 89328    /* If the sorter uses more than one task, then create the top-level 
 89329    ** MergeEngine here. This MergeEngine will read data from exactly 
 89330    ** one PmaReader per sub-task.  */
 89331    assert( pSorter->bUseThreads || pSorter->nTask==1 );
 89332    if( pSorter->nTask>1 ){
 89333      pMain = vdbeMergeEngineNew(pSorter->nTask);
 89334      if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
 89335    }
 89336  #endif
 89337  
 89338    for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
 89339      SortSubtask *pTask = &pSorter->aTask[iTask];
 89340      assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
 89341      if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
 89342        MergeEngine *pRoot = 0;     /* Root node of tree for this task */
 89343        int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
 89344        i64 iReadOff = 0;
 89345  
 89346        if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
 89347          rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
 89348        }else{
 89349          int i;
 89350          int iSeq = 0;
 89351          pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
 89352          if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
 89353          for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
 89354            MergeEngine *pMerger = 0; /* New level-0 PMA merger */
 89355            int nReader;              /* Number of level-0 PMAs to merge */
 89356  
 89357            nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
 89358            rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
 89359            if( rc==SQLITE_OK ){
 89360              rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
 89361            }
 89362          }
 89363        }
 89364  
 89365        if( rc==SQLITE_OK ){
 89366  #if SQLITE_MAX_WORKER_THREADS>0
 89367          if( pMain!=0 ){
 89368            rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
 89369          }else
 89370  #endif
 89371          {
 89372            assert( pMain==0 );
 89373            pMain = pRoot;
 89374          }
 89375        }else{
 89376          vdbeMergeEngineFree(pRoot);
 89377        }
 89378      }
 89379    }
 89380  
 89381    if( rc!=SQLITE_OK ){
 89382      vdbeMergeEngineFree(pMain);
 89383      pMain = 0;
 89384    }
 89385    *ppOut = pMain;
 89386    return rc;
 89387  }
 89388  
 89389  /*
 89390  ** This function is called as part of an sqlite3VdbeSorterRewind() operation
 89391  ** on a sorter that has written two or more PMAs to temporary files. It sets
 89392  ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
 89393  ** (for multi-threaded sorters) so that it can be used to iterate through
 89394  ** all records stored in the sorter.
 89395  **
 89396  ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
 89397  */
 89398  static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
 89399    int rc;                         /* Return code */
 89400    SortSubtask *pTask0 = &pSorter->aTask[0];
 89401    MergeEngine *pMain = 0;
 89402  #if SQLITE_MAX_WORKER_THREADS
 89403    sqlite3 *db = pTask0->pSorter->db;
 89404    int i;
 89405    SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
 89406    for(i=0; i<pSorter->nTask; i++){
 89407      pSorter->aTask[i].xCompare = xCompare;
 89408    }
 89409  #endif
 89410  
 89411    rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
 89412    if( rc==SQLITE_OK ){
 89413  #if SQLITE_MAX_WORKER_THREADS
 89414      assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
 89415      if( pSorter->bUseThreads ){
 89416        int iTask;
 89417        PmaReader *pReadr = 0;
 89418        SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
 89419        rc = vdbeSortAllocUnpacked(pLast);
 89420        if( rc==SQLITE_OK ){
 89421          pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
 89422          pSorter->pReader = pReadr;
 89423          if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
 89424        }
 89425        if( rc==SQLITE_OK ){
 89426          rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
 89427          if( rc==SQLITE_OK ){
 89428            vdbeIncrMergerSetThreads(pReadr->pIncr);
 89429            for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
 89430              IncrMerger *pIncr;
 89431              if( (pIncr = pMain->aReadr[iTask].pIncr) ){
 89432                vdbeIncrMergerSetThreads(pIncr);
 89433                assert( pIncr->pTask!=pLast );
 89434              }
 89435            }
 89436            for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
 89437              /* Check that:
 89438              **   
 89439              **   a) The incremental merge object is configured to use the
 89440              **      right task, and
 89441              **   b) If it is using task (nTask-1), it is configured to run
 89442              **      in single-threaded mode. This is important, as the
 89443              **      root merge (INCRINIT_ROOT) will be using the same task
 89444              **      object.
 89445              */
 89446              PmaReader *p = &pMain->aReadr[iTask];
 89447              assert( p->pIncr==0 || (
 89448                  (p->pIncr->pTask==&pSorter->aTask[iTask])             /* a */
 89449               && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0)  /* b */
 89450              ));
 89451              rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
 89452            }
 89453          }
 89454          pMain = 0;
 89455        }
 89456        if( rc==SQLITE_OK ){
 89457          rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
 89458        }
 89459      }else
 89460  #endif
 89461      {
 89462        rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
 89463        pSorter->pMerger = pMain;
 89464        pMain = 0;
 89465      }
 89466    }
 89467  
 89468    if( rc!=SQLITE_OK ){
 89469      vdbeMergeEngineFree(pMain);
 89470    }
 89471    return rc;
 89472  }
 89473  
 89474  
 89475  /*
 89476  ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
 89477  ** this function is called to prepare for iterating through the records
 89478  ** in sorted order.
 89479  */
 89480  SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
 89481    VdbeSorter *pSorter;
 89482    int rc = SQLITE_OK;             /* Return code */
 89483  
 89484    assert( pCsr->eCurType==CURTYPE_SORTER );
 89485    pSorter = pCsr->uc.pSorter;
 89486    assert( pSorter );
 89487  
 89488    /* If no data has been written to disk, then do not do so now. Instead,
 89489    ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
 89490    ** from the in-memory list.  */
 89491    if( pSorter->bUsePMA==0 ){
 89492      if( pSorter->list.pList ){
 89493        *pbEof = 0;
 89494        rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
 89495      }else{
 89496        *pbEof = 1;
 89497      }
 89498      return rc;
 89499    }
 89500  
 89501    /* Write the current in-memory list to a PMA. When the VdbeSorterWrite() 
 89502    ** function flushes the contents of memory to disk, it immediately always
 89503    ** creates a new list consisting of a single key immediately afterwards.
 89504    ** So the list is never empty at this point.  */
 89505    assert( pSorter->list.pList );
 89506    rc = vdbeSorterFlushPMA(pSorter);
 89507  
 89508    /* Join all threads */
 89509    rc = vdbeSorterJoinAll(pSorter, rc);
 89510  
 89511    vdbeSorterRewindDebug("rewind");
 89512  
 89513    /* Assuming no errors have occurred, set up a merger structure to 
 89514    ** incrementally read and merge all remaining PMAs.  */
 89515    assert( pSorter->pReader==0 );
 89516    if( rc==SQLITE_OK ){
 89517      rc = vdbeSorterSetupMerge(pSorter);
 89518      *pbEof = 0;
 89519    }
 89520  
 89521    vdbeSorterRewindDebug("rewinddone");
 89522    return rc;
 89523  }
 89524  
 89525  /*
 89526  ** Advance to the next element in the sorter.  Return value:
 89527  **
 89528  **    SQLITE_OK     success
 89529  **    SQLITE_DONE   end of data
 89530  **    otherwise     some kind of error.
 89531  */
 89532  SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr){
 89533    VdbeSorter *pSorter;
 89534    int rc;                         /* Return code */
 89535  
 89536    assert( pCsr->eCurType==CURTYPE_SORTER );
 89537    pSorter = pCsr->uc.pSorter;
 89538    assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
 89539    if( pSorter->bUsePMA ){
 89540      assert( pSorter->pReader==0 || pSorter->pMerger==0 );
 89541      assert( pSorter->bUseThreads==0 || pSorter->pReader );
 89542      assert( pSorter->bUseThreads==1 || pSorter->pMerger );
 89543  #if SQLITE_MAX_WORKER_THREADS>0
 89544      if( pSorter->bUseThreads ){
 89545        rc = vdbePmaReaderNext(pSorter->pReader);
 89546        if( rc==SQLITE_OK && pSorter->pReader->pFd==0 ) rc = SQLITE_DONE;
 89547      }else
 89548  #endif
 89549      /*if( !pSorter->bUseThreads )*/ {
 89550        int res = 0;
 89551        assert( pSorter->pMerger!=0 );
 89552        assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
 89553        rc = vdbeMergeEngineStep(pSorter->pMerger, &res);
 89554        if( rc==SQLITE_OK && res ) rc = SQLITE_DONE;
 89555      }
 89556    }else{
 89557      SorterRecord *pFree = pSorter->list.pList;
 89558      pSorter->list.pList = pFree->u.pNext;
 89559      pFree->u.pNext = 0;
 89560      if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
 89561      rc = pSorter->list.pList ? SQLITE_OK : SQLITE_DONE;
 89562    }
 89563    return rc;
 89564  }
 89565  
 89566  /*
 89567  ** Return a pointer to a buffer owned by the sorter that contains the 
 89568  ** current key.
 89569  */
 89570  static void *vdbeSorterRowkey(
 89571    const VdbeSorter *pSorter,      /* Sorter object */
 89572    int *pnKey                      /* OUT: Size of current key in bytes */
 89573  ){
 89574    void *pKey;
 89575    if( pSorter->bUsePMA ){
 89576      PmaReader *pReader;
 89577  #if SQLITE_MAX_WORKER_THREADS>0
 89578      if( pSorter->bUseThreads ){
 89579        pReader = pSorter->pReader;
 89580      }else
 89581  #endif
 89582      /*if( !pSorter->bUseThreads )*/{
 89583        pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
 89584      }
 89585      *pnKey = pReader->nKey;
 89586      pKey = pReader->aKey;
 89587    }else{
 89588      *pnKey = pSorter->list.pList->nVal;
 89589      pKey = SRVAL(pSorter->list.pList);
 89590    }
 89591    return pKey;
 89592  }
 89593  
 89594  /*
 89595  ** Copy the current sorter key into the memory cell pOut.
 89596  */
 89597  SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
 89598    VdbeSorter *pSorter;
 89599    void *pKey; int nKey;           /* Sorter key to copy into pOut */
 89600  
 89601    assert( pCsr->eCurType==CURTYPE_SORTER );
 89602    pSorter = pCsr->uc.pSorter;
 89603    pKey = vdbeSorterRowkey(pSorter, &nKey);
 89604    if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
 89605      return SQLITE_NOMEM_BKPT;
 89606    }
 89607    pOut->n = nKey;
 89608    MemSetTypeFlag(pOut, MEM_Blob);
 89609    memcpy(pOut->z, pKey, nKey);
 89610  
 89611    return SQLITE_OK;
 89612  }
 89613  
 89614  /*
 89615  ** Compare the key in memory cell pVal with the key that the sorter cursor
 89616  ** passed as the first argument currently points to. For the purposes of
 89617  ** the comparison, ignore the rowid field at the end of each record.
 89618  **
 89619  ** If the sorter cursor key contains any NULL values, consider it to be
 89620  ** less than pVal. Even if pVal also contains NULL values.
 89621  **
 89622  ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
 89623  ** Otherwise, set *pRes to a negative, zero or positive value if the
 89624  ** key in pVal is smaller than, equal to or larger than the current sorter
 89625  ** key.
 89626  **
 89627  ** This routine forms the core of the OP_SorterCompare opcode, which in
 89628  ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
 89629  */
 89630  SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
 89631    const VdbeCursor *pCsr,         /* Sorter cursor */
 89632    Mem *pVal,                      /* Value to compare to current sorter key */
 89633    int nKeyCol,                    /* Compare this many columns */
 89634    int *pRes                       /* OUT: Result of comparison */
 89635  ){
 89636    VdbeSorter *pSorter;
 89637    UnpackedRecord *r2;
 89638    KeyInfo *pKeyInfo;
 89639    int i;
 89640    void *pKey; int nKey;           /* Sorter key to compare pVal with */
 89641  
 89642    assert( pCsr->eCurType==CURTYPE_SORTER );
 89643    pSorter = pCsr->uc.pSorter;
 89644    r2 = pSorter->pUnpacked;
 89645    pKeyInfo = pCsr->pKeyInfo;
 89646    if( r2==0 ){
 89647      r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
 89648      if( r2==0 ) return SQLITE_NOMEM_BKPT;
 89649      r2->nField = nKeyCol;
 89650    }
 89651    assert( r2->nField==nKeyCol );
 89652  
 89653    pKey = vdbeSorterRowkey(pSorter, &nKey);
 89654    sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
 89655    for(i=0; i<nKeyCol; i++){
 89656      if( r2->aMem[i].flags & MEM_Null ){
 89657        *pRes = -1;
 89658        return SQLITE_OK;
 89659      }
 89660    }
 89661  
 89662    *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
 89663    return SQLITE_OK;
 89664  }
 89665  
 89666  /************** End of vdbesort.c ********************************************/
 89667  /************** Begin file memjournal.c **************************************/
 89668  /*
 89669  ** 2008 October 7
 89670  **
 89671  ** The author disclaims copyright to this source code.  In place of
 89672  ** a legal notice, here is a blessing:
 89673  **
 89674  **    May you do good and not evil.
 89675  **    May you find forgiveness for yourself and forgive others.
 89676  **    May you share freely, never taking more than you give.
 89677  **
 89678  *************************************************************************
 89679  **
 89680  ** This file contains code use to implement an in-memory rollback journal.
 89681  ** The in-memory rollback journal is used to journal transactions for
 89682  ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
 89683  **
 89684  ** Update:  The in-memory journal is also used to temporarily cache
 89685  ** smaller journals that are not critical for power-loss recovery.
 89686  ** For example, statement journals that are not too big will be held
 89687  ** entirely in memory, thus reducing the number of file I/O calls, and
 89688  ** more importantly, reducing temporary file creation events.  If these
 89689  ** journals become too large for memory, they are spilled to disk.  But
 89690  ** in the common case, they are usually small and no file I/O needs to
 89691  ** occur.
 89692  */
 89693  /* #include "sqliteInt.h" */
 89694  
 89695  /* Forward references to internal structures */
 89696  typedef struct MemJournal MemJournal;
 89697  typedef struct FilePoint FilePoint;
 89698  typedef struct FileChunk FileChunk;
 89699  
 89700  /*
 89701  ** The rollback journal is composed of a linked list of these structures.
 89702  **
 89703  ** The zChunk array is always at least 8 bytes in size - usually much more.
 89704  ** Its actual size is stored in the MemJournal.nChunkSize variable.
 89705  */
 89706  struct FileChunk {
 89707    FileChunk *pNext;               /* Next chunk in the journal */
 89708    u8 zChunk[8];                   /* Content of this chunk */
 89709  };
 89710  
 89711  /*
 89712  ** By default, allocate this many bytes of memory for each FileChunk object.
 89713  */
 89714  #define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
 89715  
 89716  /*
 89717  ** For chunk size nChunkSize, return the number of bytes that should
 89718  ** be allocated for each FileChunk structure.
 89719  */
 89720  #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
 89721  
 89722  /*
 89723  ** An instance of this object serves as a cursor into the rollback journal.
 89724  ** The cursor can be either for reading or writing.
 89725  */
 89726  struct FilePoint {
 89727    sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
 89728    FileChunk *pChunk;              /* Specific chunk into which cursor points */
 89729  };
 89730  
 89731  /*
 89732  ** This structure is a subclass of sqlite3_file. Each open memory-journal
 89733  ** is an instance of this class.
 89734  */
 89735  struct MemJournal {
 89736    const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
 89737    int nChunkSize;                 /* In-memory chunk-size */
 89738  
 89739    int nSpill;                     /* Bytes of data before flushing */
 89740    int nSize;                      /* Bytes of data currently in memory */
 89741    FileChunk *pFirst;              /* Head of in-memory chunk-list */
 89742    FilePoint endpoint;             /* Pointer to the end of the file */
 89743    FilePoint readpoint;            /* Pointer to the end of the last xRead() */
 89744  
 89745    int flags;                      /* xOpen flags */
 89746    sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
 89747    const char *zJournal;           /* Name of the journal file */
 89748  };
 89749  
 89750  /*
 89751  ** Read data from the in-memory journal file.  This is the implementation
 89752  ** of the sqlite3_vfs.xRead method.
 89753  */
 89754  static int memjrnlRead(
 89755    sqlite3_file *pJfd,    /* The journal file from which to read */
 89756    void *zBuf,            /* Put the results here */
 89757    int iAmt,              /* Number of bytes to read */
 89758    sqlite_int64 iOfst     /* Begin reading at this offset */
 89759  ){
 89760    MemJournal *p = (MemJournal *)pJfd;
 89761    u8 *zOut = zBuf;
 89762    int nRead = iAmt;
 89763    int iChunkOffset;
 89764    FileChunk *pChunk;
 89765  
 89766  #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
 89767   || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
 89768    if( (iAmt+iOfst)>p->endpoint.iOffset ){
 89769      return SQLITE_IOERR_SHORT_READ;
 89770    }
 89771  #endif
 89772  
 89773    assert( (iAmt+iOfst)<=p->endpoint.iOffset );
 89774    assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
 89775    if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
 89776      sqlite3_int64 iOff = 0;
 89777      for(pChunk=p->pFirst; 
 89778          ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
 89779          pChunk=pChunk->pNext
 89780      ){
 89781        iOff += p->nChunkSize;
 89782      }
 89783    }else{
 89784      pChunk = p->readpoint.pChunk;
 89785      assert( pChunk!=0 );
 89786    }
 89787  
 89788    iChunkOffset = (int)(iOfst%p->nChunkSize);
 89789    do {
 89790      int iSpace = p->nChunkSize - iChunkOffset;
 89791      int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
 89792      memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
 89793      zOut += nCopy;
 89794      nRead -= iSpace;
 89795      iChunkOffset = 0;
 89796    } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
 89797    p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
 89798    p->readpoint.pChunk = pChunk;
 89799  
 89800    return SQLITE_OK;
 89801  }
 89802  
 89803  /*
 89804  ** Free the list of FileChunk structures headed at MemJournal.pFirst.
 89805  */
 89806  static void memjrnlFreeChunks(MemJournal *p){
 89807    FileChunk *pIter;
 89808    FileChunk *pNext;
 89809    for(pIter=p->pFirst; pIter; pIter=pNext){
 89810      pNext = pIter->pNext;
 89811      sqlite3_free(pIter);
 89812    } 
 89813    p->pFirst = 0;
 89814  }
 89815  
 89816  /*
 89817  ** Flush the contents of memory to a real file on disk.
 89818  */
 89819  static int memjrnlCreateFile(MemJournal *p){
 89820    int rc;
 89821    sqlite3_file *pReal = (sqlite3_file*)p;
 89822    MemJournal copy = *p;
 89823  
 89824    memset(p, 0, sizeof(MemJournal));
 89825    rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
 89826    if( rc==SQLITE_OK ){
 89827      int nChunk = copy.nChunkSize;
 89828      i64 iOff = 0;
 89829      FileChunk *pIter;
 89830      for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
 89831        if( iOff + nChunk > copy.endpoint.iOffset ){
 89832          nChunk = copy.endpoint.iOffset - iOff;
 89833        }
 89834        rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
 89835        if( rc ) break;
 89836        iOff += nChunk;
 89837      }
 89838      if( rc==SQLITE_OK ){
 89839        /* No error has occurred. Free the in-memory buffers. */
 89840        memjrnlFreeChunks(&copy);
 89841      }
 89842    }
 89843    if( rc!=SQLITE_OK ){
 89844      /* If an error occurred while creating or writing to the file, restore
 89845      ** the original before returning. This way, SQLite uses the in-memory
 89846      ** journal data to roll back changes made to the internal page-cache
 89847      ** before this function was called.  */
 89848      sqlite3OsClose(pReal);
 89849      *p = copy;
 89850    }
 89851    return rc;
 89852  }
 89853  
 89854  
 89855  /*
 89856  ** Write data to the file.
 89857  */
 89858  static int memjrnlWrite(
 89859    sqlite3_file *pJfd,    /* The journal file into which to write */
 89860    const void *zBuf,      /* Take data to be written from here */
 89861    int iAmt,              /* Number of bytes to write */
 89862    sqlite_int64 iOfst     /* Begin writing at this offset into the file */
 89863  ){
 89864    MemJournal *p = (MemJournal *)pJfd;
 89865    int nWrite = iAmt;
 89866    u8 *zWrite = (u8 *)zBuf;
 89867  
 89868    /* If the file should be created now, create it and write the new data
 89869    ** into the file on disk. */
 89870    if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
 89871      int rc = memjrnlCreateFile(p);
 89872      if( rc==SQLITE_OK ){
 89873        rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
 89874      }
 89875      return rc;
 89876    }
 89877  
 89878    /* If the contents of this write should be stored in memory */
 89879    else{
 89880      /* An in-memory journal file should only ever be appended to. Random
 89881      ** access writes are not required. The only exception to this is when
 89882      ** the in-memory journal is being used by a connection using the
 89883      ** atomic-write optimization. In this case the first 28 bytes of the
 89884      ** journal file may be written as part of committing the transaction. */ 
 89885      assert( iOfst==p->endpoint.iOffset || iOfst==0 );
 89886  #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
 89887   || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
 89888      if( iOfst==0 && p->pFirst ){
 89889        assert( p->nChunkSize>iAmt );
 89890        memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
 89891      }else
 89892  #else
 89893      assert( iOfst>0 || p->pFirst==0 );
 89894  #endif
 89895      {
 89896        while( nWrite>0 ){
 89897          FileChunk *pChunk = p->endpoint.pChunk;
 89898          int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
 89899          int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
 89900  
 89901          if( iChunkOffset==0 ){
 89902            /* New chunk is required to extend the file. */
 89903            FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
 89904            if( !pNew ){
 89905              return SQLITE_IOERR_NOMEM_BKPT;
 89906            }
 89907            pNew->pNext = 0;
 89908            if( pChunk ){
 89909              assert( p->pFirst );
 89910              pChunk->pNext = pNew;
 89911            }else{
 89912              assert( !p->pFirst );
 89913              p->pFirst = pNew;
 89914            }
 89915            p->endpoint.pChunk = pNew;
 89916          }
 89917  
 89918          memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
 89919          zWrite += iSpace;
 89920          nWrite -= iSpace;
 89921          p->endpoint.iOffset += iSpace;
 89922        }
 89923        p->nSize = iAmt + iOfst;
 89924      }
 89925    }
 89926  
 89927    return SQLITE_OK;
 89928  }
 89929  
 89930  /*
 89931  ** Truncate the file.
 89932  **
 89933  ** If the journal file is already on disk, truncate it there. Or, if it
 89934  ** is still in main memory but is being truncated to zero bytes in size,
 89935  ** ignore 
 89936  */
 89937  static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
 89938    MemJournal *p = (MemJournal *)pJfd;
 89939    if( ALWAYS(size==0) ){
 89940      memjrnlFreeChunks(p);
 89941      p->nSize = 0;
 89942      p->endpoint.pChunk = 0;
 89943      p->endpoint.iOffset = 0;
 89944      p->readpoint.pChunk = 0;
 89945      p->readpoint.iOffset = 0;
 89946    }
 89947    return SQLITE_OK;
 89948  }
 89949  
 89950  /*
 89951  ** Close the file.
 89952  */
 89953  static int memjrnlClose(sqlite3_file *pJfd){
 89954    MemJournal *p = (MemJournal *)pJfd;
 89955    memjrnlFreeChunks(p);
 89956    return SQLITE_OK;
 89957  }
 89958  
 89959  /*
 89960  ** Sync the file.
 89961  **
 89962  ** If the real file has been created, call its xSync method. Otherwise, 
 89963  ** syncing an in-memory journal is a no-op. 
 89964  */
 89965  static int memjrnlSync(sqlite3_file *pJfd, int flags){
 89966    UNUSED_PARAMETER2(pJfd, flags);
 89967    return SQLITE_OK;
 89968  }
 89969  
 89970  /*
 89971  ** Query the size of the file in bytes.
 89972  */
 89973  static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
 89974    MemJournal *p = (MemJournal *)pJfd;
 89975    *pSize = (sqlite_int64) p->endpoint.iOffset;
 89976    return SQLITE_OK;
 89977  }
 89978  
 89979  /*
 89980  ** Table of methods for MemJournal sqlite3_file object.
 89981  */
 89982  static const struct sqlite3_io_methods MemJournalMethods = {
 89983    1,                /* iVersion */
 89984    memjrnlClose,     /* xClose */
 89985    memjrnlRead,      /* xRead */
 89986    memjrnlWrite,     /* xWrite */
 89987    memjrnlTruncate,  /* xTruncate */
 89988    memjrnlSync,      /* xSync */
 89989    memjrnlFileSize,  /* xFileSize */
 89990    0,                /* xLock */
 89991    0,                /* xUnlock */
 89992    0,                /* xCheckReservedLock */
 89993    0,                /* xFileControl */
 89994    0,                /* xSectorSize */
 89995    0,                /* xDeviceCharacteristics */
 89996    0,                /* xShmMap */
 89997    0,                /* xShmLock */
 89998    0,                /* xShmBarrier */
 89999    0,                /* xShmUnmap */
 90000    0,                /* xFetch */
 90001    0                 /* xUnfetch */
 90002  };
 90003  
 90004  /* 
 90005  ** Open a journal file. 
 90006  **
 90007  ** The behaviour of the journal file depends on the value of parameter 
 90008  ** nSpill. If nSpill is 0, then the journal file is always create and 
 90009  ** accessed using the underlying VFS. If nSpill is less than zero, then
 90010  ** all content is always stored in main-memory. Finally, if nSpill is a
 90011  ** positive value, then the journal file is initially created in-memory
 90012  ** but may be flushed to disk later on. In this case the journal file is
 90013  ** flushed to disk either when it grows larger than nSpill bytes in size,
 90014  ** or when sqlite3JournalCreate() is called.
 90015  */
 90016  SQLITE_PRIVATE int sqlite3JournalOpen(
 90017    sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
 90018    const char *zName,         /* Name of the journal file */
 90019    sqlite3_file *pJfd,        /* Preallocated, blank file handle */
 90020    int flags,                 /* Opening flags */
 90021    int nSpill                 /* Bytes buffered before opening the file */
 90022  ){
 90023    MemJournal *p = (MemJournal*)pJfd;
 90024  
 90025    /* Zero the file-handle object. If nSpill was passed zero, initialize
 90026    ** it using the sqlite3OsOpen() function of the underlying VFS. In this
 90027    ** case none of the code in this module is executed as a result of calls
 90028    ** made on the journal file-handle.  */
 90029    memset(p, 0, sizeof(MemJournal));
 90030    if( nSpill==0 ){
 90031      return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
 90032    }
 90033  
 90034    if( nSpill>0 ){
 90035      p->nChunkSize = nSpill;
 90036    }else{
 90037      p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
 90038      assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
 90039    }
 90040  
 90041    p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
 90042    p->nSpill = nSpill;
 90043    p->flags = flags;
 90044    p->zJournal = zName;
 90045    p->pVfs = pVfs;
 90046    return SQLITE_OK;
 90047  }
 90048  
 90049  /*
 90050  ** Open an in-memory journal file.
 90051  */
 90052  SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
 90053    sqlite3JournalOpen(0, 0, pJfd, 0, -1);
 90054  }
 90055  
 90056  #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
 90057   || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
 90058  /*
 90059  ** If the argument p points to a MemJournal structure that is not an 
 90060  ** in-memory-only journal file (i.e. is one that was opened with a +ve
 90061  ** nSpill parameter or as SQLITE_OPEN_MAIN_JOURNAL), and the underlying 
 90062  ** file has not yet been created, create it now.
 90063  */
 90064  SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *pJfd){
 90065    int rc = SQLITE_OK;
 90066    MemJournal *p = (MemJournal*)pJfd;
 90067    if( p->pMethod==&MemJournalMethods && (
 90068  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
 90069       p->nSpill>0
 90070  #else
 90071       /* While this appears to not be possible without ATOMIC_WRITE, the
 90072       ** paths are complex, so it seems prudent to leave the test in as
 90073       ** a NEVER(), in case our analysis is subtly flawed. */
 90074       NEVER(p->nSpill>0)
 90075  #endif
 90076  #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
 90077       || (p->flags & SQLITE_OPEN_MAIN_JOURNAL)
 90078  #endif
 90079    )){
 90080      rc = memjrnlCreateFile(p);
 90081    }
 90082    return rc;
 90083  }
 90084  #endif
 90085  
 90086  /*
 90087  ** The file-handle passed as the only argument is open on a journal file.
 90088  ** Return true if this "journal file" is currently stored in heap memory,
 90089  ** or false otherwise.
 90090  */
 90091  SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
 90092    return p->pMethods==&MemJournalMethods;
 90093  }
 90094  
 90095  /* 
 90096  ** Return the number of bytes required to store a JournalFile that uses vfs
 90097  ** pVfs to create the underlying on-disk files.
 90098  */
 90099  SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
 90100    return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
 90101  }
 90102  
 90103  /************** End of memjournal.c ******************************************/
 90104  /************** Begin file walker.c ******************************************/
 90105  /*
 90106  ** 2008 August 16
 90107  **
 90108  ** The author disclaims copyright to this source code.  In place of
 90109  ** a legal notice, here is a blessing:
 90110  **
 90111  **    May you do good and not evil.
 90112  **    May you find forgiveness for yourself and forgive others.
 90113  **    May you share freely, never taking more than you give.
 90114  **
 90115  *************************************************************************
 90116  ** This file contains routines used for walking the parser tree for
 90117  ** an SQL statement.
 90118  */
 90119  /* #include "sqliteInt.h" */
 90120  /* #include <stdlib.h> */
 90121  /* #include <string.h> */
 90122  
 90123  
 90124  /*
 90125  ** Walk an expression tree.  Invoke the callback once for each node
 90126  ** of the expression, while descending.  (In other words, the callback
 90127  ** is invoked before visiting children.)
 90128  **
 90129  ** The return value from the callback should be one of the WRC_*
 90130  ** constants to specify how to proceed with the walk.
 90131  **
 90132  **    WRC_Continue      Continue descending down the tree.
 90133  **
 90134  **    WRC_Prune         Do not descend into child nodes, but allow
 90135  **                      the walk to continue with sibling nodes.
 90136  **
 90137  **    WRC_Abort         Do no more callbacks.  Unwind the stack and
 90138  **                      return from the top-level walk call.
 90139  **
 90140  ** The return value from this routine is WRC_Abort to abandon the tree walk
 90141  ** and WRC_Continue to continue.
 90142  */
 90143  static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
 90144    int rc;
 90145    testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
 90146    testcase( ExprHasProperty(pExpr, EP_Reduced) );
 90147    while(1){
 90148      rc = pWalker->xExprCallback(pWalker, pExpr);
 90149      if( rc ) return rc & WRC_Abort;
 90150      if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
 90151        if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
 90152         assert( pExpr->x.pList==0 || pExpr->pRight==0 );
 90153        if( pExpr->pRight ){
 90154          pExpr = pExpr->pRight;
 90155          continue;
 90156        }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
 90157          if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
 90158        }else if( pExpr->x.pList ){
 90159          if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
 90160        }
 90161      }
 90162      break;
 90163    }
 90164    return WRC_Continue;
 90165  }
 90166  SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
 90167    return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
 90168  }
 90169  
 90170  /*
 90171  ** Call sqlite3WalkExpr() for every expression in list p or until
 90172  ** an abort request is seen.
 90173  */
 90174  SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
 90175    int i;
 90176    struct ExprList_item *pItem;
 90177    if( p ){
 90178      for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
 90179        if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
 90180      }
 90181    }
 90182    return WRC_Continue;
 90183  }
 90184  
 90185  /*
 90186  ** Walk all expressions associated with SELECT statement p.  Do
 90187  ** not invoke the SELECT callback on p, but do (of course) invoke
 90188  ** any expr callbacks and SELECT callbacks that come from subqueries.
 90189  ** Return WRC_Abort or WRC_Continue.
 90190  */
 90191  SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
 90192    if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
 90193    if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
 90194    if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
 90195    if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
 90196    if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
 90197    if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
 90198    if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
 90199    return WRC_Continue;
 90200  }
 90201  
 90202  /*
 90203  ** Walk the parse trees associated with all subqueries in the
 90204  ** FROM clause of SELECT statement p.  Do not invoke the select
 90205  ** callback on p, but do invoke it on each FROM clause subquery
 90206  ** and on any subqueries further down in the tree.  Return 
 90207  ** WRC_Abort or WRC_Continue;
 90208  */
 90209  SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
 90210    SrcList *pSrc;
 90211    int i;
 90212    struct SrcList_item *pItem;
 90213  
 90214    pSrc = p->pSrc;
 90215    if( ALWAYS(pSrc) ){
 90216      for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
 90217        if( pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect) ){
 90218          return WRC_Abort;
 90219        }
 90220        if( pItem->fg.isTabFunc
 90221         && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
 90222        ){
 90223          return WRC_Abort;
 90224        }
 90225      }
 90226    }
 90227    return WRC_Continue;
 90228  } 
 90229  
 90230  /*
 90231  ** Call sqlite3WalkExpr() for every expression in Select statement p.
 90232  ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
 90233  ** on the compound select chain, p->pPrior. 
 90234  **
 90235  ** If it is not NULL, the xSelectCallback() callback is invoked before
 90236  ** the walk of the expressions and FROM clause. The xSelectCallback2()
 90237  ** method is invoked following the walk of the expressions and FROM clause,
 90238  ** but only if both xSelectCallback and xSelectCallback2 are both non-NULL
 90239  ** and if the expressions and FROM clause both return WRC_Continue;
 90240  **
 90241  ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
 90242  ** there is an abort request.
 90243  **
 90244  ** If the Walker does not have an xSelectCallback() then this routine
 90245  ** is a no-op returning WRC_Continue.
 90246  */
 90247  SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
 90248    int rc;
 90249    if( p==0 ) return WRC_Continue;
 90250    if( pWalker->xSelectCallback==0 ) return WRC_Continue;
 90251    do{
 90252      rc = pWalker->xSelectCallback(pWalker, p);
 90253      if( rc ) return rc & WRC_Abort;
 90254      if( sqlite3WalkSelectExpr(pWalker, p)
 90255       || sqlite3WalkSelectFrom(pWalker, p)
 90256      ){
 90257        return WRC_Abort;
 90258      }
 90259      if( pWalker->xSelectCallback2 ){
 90260        pWalker->xSelectCallback2(pWalker, p);
 90261      }
 90262      p = p->pPrior;
 90263    }while( p!=0 );
 90264    return WRC_Continue;
 90265  }
 90266  
 90267  /************** End of walker.c **********************************************/
 90268  /************** Begin file resolve.c *****************************************/
 90269  /*
 90270  ** 2008 August 18
 90271  **
 90272  ** The author disclaims copyright to this source code.  In place of
 90273  ** a legal notice, here is a blessing:
 90274  **
 90275  **    May you do good and not evil.
 90276  **    May you find forgiveness for yourself and forgive others.
 90277  **    May you share freely, never taking more than you give.
 90278  **
 90279  *************************************************************************
 90280  **
 90281  ** This file contains routines used for walking the parser tree and
 90282  ** resolve all identifiers by associating them with a particular
 90283  ** table and column.
 90284  */
 90285  /* #include "sqliteInt.h" */
 90286  
 90287  /*
 90288  ** Walk the expression tree pExpr and increase the aggregate function
 90289  ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
 90290  ** This needs to occur when copying a TK_AGG_FUNCTION node from an
 90291  ** outer query into an inner subquery.
 90292  **
 90293  ** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
 90294  ** is a helper function - a callback for the tree walker.
 90295  */
 90296  static int incrAggDepth(Walker *pWalker, Expr *pExpr){
 90297    if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
 90298    return WRC_Continue;
 90299  }
 90300  static void incrAggFunctionDepth(Expr *pExpr, int N){
 90301    if( N>0 ){
 90302      Walker w;
 90303      memset(&w, 0, sizeof(w));
 90304      w.xExprCallback = incrAggDepth;
 90305      w.u.n = N;
 90306      sqlite3WalkExpr(&w, pExpr);
 90307    }
 90308  }
 90309  
 90310  /*
 90311  ** Turn the pExpr expression into an alias for the iCol-th column of the
 90312  ** result set in pEList.
 90313  **
 90314  ** If the reference is followed by a COLLATE operator, then make sure
 90315  ** the COLLATE operator is preserved.  For example:
 90316  **
 90317  **     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
 90318  **
 90319  ** Should be transformed into:
 90320  **
 90321  **     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
 90322  **
 90323  ** The nSubquery parameter specifies how many levels of subquery the
 90324  ** alias is removed from the original expression.  The usual value is
 90325  ** zero but it might be more if the alias is contained within a subquery
 90326  ** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
 90327  ** structures must be increased by the nSubquery amount.
 90328  */
 90329  static void resolveAlias(
 90330    Parse *pParse,         /* Parsing context */
 90331    ExprList *pEList,      /* A result set */
 90332    int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
 90333    Expr *pExpr,           /* Transform this into an alias to the result set */
 90334    const char *zType,     /* "GROUP" or "ORDER" or "" */
 90335    int nSubquery          /* Number of subqueries that the label is moving */
 90336  ){
 90337    Expr *pOrig;           /* The iCol-th column of the result set */
 90338    Expr *pDup;            /* Copy of pOrig */
 90339    sqlite3 *db;           /* The database connection */
 90340  
 90341    assert( iCol>=0 && iCol<pEList->nExpr );
 90342    pOrig = pEList->a[iCol].pExpr;
 90343    assert( pOrig!=0 );
 90344    db = pParse->db;
 90345    pDup = sqlite3ExprDup(db, pOrig, 0);
 90346    if( pDup==0 ) return;
 90347    if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
 90348    if( pExpr->op==TK_COLLATE ){
 90349      pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
 90350    }
 90351    ExprSetProperty(pDup, EP_Alias);
 90352  
 90353    /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
 90354    ** prevents ExprDelete() from deleting the Expr structure itself,
 90355    ** allowing it to be repopulated by the memcpy() on the following line.
 90356    ** The pExpr->u.zToken might point into memory that will be freed by the
 90357    ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
 90358    ** make a copy of the token before doing the sqlite3DbFree().
 90359    */
 90360    ExprSetProperty(pExpr, EP_Static);
 90361    sqlite3ExprDelete(db, pExpr);
 90362    memcpy(pExpr, pDup, sizeof(*pExpr));
 90363    if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
 90364      assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
 90365      pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
 90366      pExpr->flags |= EP_MemToken;
 90367    }
 90368    sqlite3DbFree(db, pDup);
 90369  }
 90370  
 90371  
 90372  /*
 90373  ** Return TRUE if the name zCol occurs anywhere in the USING clause.
 90374  **
 90375  ** Return FALSE if the USING clause is NULL or if it does not contain
 90376  ** zCol.
 90377  */
 90378  static int nameInUsingClause(IdList *pUsing, const char *zCol){
 90379    if( pUsing ){
 90380      int k;
 90381      for(k=0; k<pUsing->nId; k++){
 90382        if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
 90383      }
 90384    }
 90385    return 0;
 90386  }
 90387  
 90388  /*
 90389  ** Subqueries stores the original database, table and column names for their
 90390  ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
 90391  ** Check to see if the zSpan given to this routine matches the zDb, zTab,
 90392  ** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
 90393  ** match anything.
 90394  */
 90395  SQLITE_PRIVATE int sqlite3MatchSpanName(
 90396    const char *zSpan,
 90397    const char *zCol,
 90398    const char *zTab,
 90399    const char *zDb
 90400  ){
 90401    int n;
 90402    for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
 90403    if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
 90404      return 0;
 90405    }
 90406    zSpan += n+1;
 90407    for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
 90408    if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
 90409      return 0;
 90410    }
 90411    zSpan += n+1;
 90412    if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
 90413      return 0;
 90414    }
 90415    return 1;
 90416  }
 90417  
 90418  /*
 90419  ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
 90420  ** that name in the set of source tables in pSrcList and make the pExpr 
 90421  ** expression node refer back to that source column.  The following changes
 90422  ** are made to pExpr:
 90423  **
 90424  **    pExpr->iDb           Set the index in db->aDb[] of the database X
 90425  **                         (even if X is implied).
 90426  **    pExpr->iTable        Set to the cursor number for the table obtained
 90427  **                         from pSrcList.
 90428  **    pExpr->pTab          Points to the Table structure of X.Y (even if
 90429  **                         X and/or Y are implied.)
 90430  **    pExpr->iColumn       Set to the column number within the table.
 90431  **    pExpr->op            Set to TK_COLUMN.
 90432  **    pExpr->pLeft         Any expression this points to is deleted
 90433  **    pExpr->pRight        Any expression this points to is deleted.
 90434  **
 90435  ** The zDb variable is the name of the database (the "X").  This value may be
 90436  ** NULL meaning that name is of the form Y.Z or Z.  Any available database
 90437  ** can be used.  The zTable variable is the name of the table (the "Y").  This
 90438  ** value can be NULL if zDb is also NULL.  If zTable is NULL it
 90439  ** means that the form of the name is Z and that columns from any table
 90440  ** can be used.
 90441  **
 90442  ** If the name cannot be resolved unambiguously, leave an error message
 90443  ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
 90444  */
 90445  static int lookupName(
 90446    Parse *pParse,       /* The parsing context */
 90447    const char *zDb,     /* Name of the database containing table, or NULL */
 90448    const char *zTab,    /* Name of table containing column, or NULL */
 90449    const char *zCol,    /* Name of the column. */
 90450    NameContext *pNC,    /* The name context used to resolve the name */
 90451    Expr *pExpr          /* Make this EXPR node point to the selected column */
 90452  ){
 90453    int i, j;                         /* Loop counters */
 90454    int cnt = 0;                      /* Number of matching column names */
 90455    int cntTab = 0;                   /* Number of matching table names */
 90456    int nSubquery = 0;                /* How many levels of subquery */
 90457    sqlite3 *db = pParse->db;         /* The database connection */
 90458    struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
 90459    struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
 90460    NameContext *pTopNC = pNC;        /* First namecontext in the list */
 90461    Schema *pSchema = 0;              /* Schema of the expression */
 90462    int isTrigger = 0;                /* True if resolved to a trigger column */
 90463    Table *pTab = 0;                  /* Table hold the row */
 90464    Column *pCol;                     /* A column of pTab */
 90465  
 90466    assert( pNC );     /* the name context cannot be NULL. */
 90467    assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
 90468    assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
 90469  
 90470    /* Initialize the node to no-match */
 90471    pExpr->iTable = -1;
 90472    pExpr->pTab = 0;
 90473    ExprSetVVAProperty(pExpr, EP_NoReduce);
 90474  
 90475    /* Translate the schema name in zDb into a pointer to the corresponding
 90476    ** schema.  If not found, pSchema will remain NULL and nothing will match
 90477    ** resulting in an appropriate error message toward the end of this routine
 90478    */
 90479    if( zDb ){
 90480      testcase( pNC->ncFlags & NC_PartIdx );
 90481      testcase( pNC->ncFlags & NC_IsCheck );
 90482      if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
 90483        /* Silently ignore database qualifiers inside CHECK constraints and
 90484        ** partial indices.  Do not raise errors because that might break
 90485        ** legacy and because it does not hurt anything to just ignore the
 90486        ** database name. */
 90487        zDb = 0;
 90488      }else{
 90489        for(i=0; i<db->nDb; i++){
 90490          assert( db->aDb[i].zDbSName );
 90491          if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
 90492            pSchema = db->aDb[i].pSchema;
 90493            break;
 90494          }
 90495        }
 90496      }
 90497    }
 90498  
 90499    /* Start at the inner-most context and move outward until a match is found */
 90500    assert( pNC && cnt==0 );
 90501    do{
 90502      ExprList *pEList;
 90503      SrcList *pSrcList = pNC->pSrcList;
 90504  
 90505      if( pSrcList ){
 90506        for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
 90507          pTab = pItem->pTab;
 90508          assert( pTab!=0 && pTab->zName!=0 );
 90509          assert( pTab->nCol>0 );
 90510          if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
 90511            int hit = 0;
 90512            pEList = pItem->pSelect->pEList;
 90513            for(j=0; j<pEList->nExpr; j++){
 90514              if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
 90515                cnt++;
 90516                cntTab = 2;
 90517                pMatch = pItem;
 90518                pExpr->iColumn = j;
 90519                hit = 1;
 90520              }
 90521            }
 90522            if( hit || zTab==0 ) continue;
 90523          }
 90524          if( zDb && pTab->pSchema!=pSchema ){
 90525            continue;
 90526          }
 90527          if( zTab ){
 90528            const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
 90529            assert( zTabName!=0 );
 90530            if( sqlite3StrICmp(zTabName, zTab)!=0 ){
 90531              continue;
 90532            }
 90533          }
 90534          if( 0==(cntTab++) ){
 90535            pMatch = pItem;
 90536          }
 90537          for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
 90538            if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
 90539              /* If there has been exactly one prior match and this match
 90540              ** is for the right-hand table of a NATURAL JOIN or is in a 
 90541              ** USING clause, then skip this match.
 90542              */
 90543              if( cnt==1 ){
 90544                if( pItem->fg.jointype & JT_NATURAL ) continue;
 90545                if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
 90546              }
 90547              cnt++;
 90548              pMatch = pItem;
 90549              /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
 90550              pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
 90551              break;
 90552            }
 90553          }
 90554        }
 90555        if( pMatch ){
 90556          pExpr->iTable = pMatch->iCursor;
 90557          pExpr->pTab = pMatch->pTab;
 90558          /* RIGHT JOIN not (yet) supported */
 90559          assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
 90560          if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
 90561            ExprSetProperty(pExpr, EP_CanBeNull);
 90562          }
 90563          pSchema = pExpr->pTab->pSchema;
 90564        }
 90565      } /* if( pSrcList ) */
 90566  
 90567  #ifndef SQLITE_OMIT_TRIGGER
 90568      /* If we have not already resolved the name, then maybe 
 90569      ** it is a new.* or old.* trigger argument reference
 90570      */
 90571      if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
 90572        int op = pParse->eTriggerOp;
 90573        assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
 90574        if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
 90575          pExpr->iTable = 1;
 90576          pTab = pParse->pTriggerTab;
 90577        }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
 90578          pExpr->iTable = 0;
 90579          pTab = pParse->pTriggerTab;
 90580        }else{
 90581          pTab = 0;
 90582        }
 90583  
 90584        if( pTab ){ 
 90585          int iCol;
 90586          pSchema = pTab->pSchema;
 90587          cntTab++;
 90588          for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
 90589            if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
 90590              if( iCol==pTab->iPKey ){
 90591                iCol = -1;
 90592              }
 90593              break;
 90594            }
 90595          }
 90596          if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
 90597            /* IMP: R-51414-32910 */
 90598            iCol = -1;
 90599          }
 90600          if( iCol<pTab->nCol ){
 90601            cnt++;
 90602            if( iCol<0 ){
 90603              pExpr->affinity = SQLITE_AFF_INTEGER;
 90604            }else if( pExpr->iTable==0 ){
 90605              testcase( iCol==31 );
 90606              testcase( iCol==32 );
 90607              pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
 90608            }else{
 90609              testcase( iCol==31 );
 90610              testcase( iCol==32 );
 90611              pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
 90612            }
 90613            pExpr->iColumn = (i16)iCol;
 90614            pExpr->pTab = pTab;
 90615            isTrigger = 1;
 90616          }
 90617        }
 90618      }
 90619  #endif /* !defined(SQLITE_OMIT_TRIGGER) */
 90620  
 90621      /*
 90622      ** Perhaps the name is a reference to the ROWID
 90623      */
 90624      if( cnt==0
 90625       && cntTab==1
 90626       && pMatch
 90627       && (pNC->ncFlags & NC_IdxExpr)==0
 90628       && sqlite3IsRowid(zCol)
 90629       && VisibleRowid(pMatch->pTab)
 90630      ){
 90631        cnt = 1;
 90632        pExpr->iColumn = -1;
 90633        pExpr->affinity = SQLITE_AFF_INTEGER;
 90634      }
 90635  
 90636      /*
 90637      ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
 90638      ** might refer to an result-set alias.  This happens, for example, when
 90639      ** we are resolving names in the WHERE clause of the following command:
 90640      **
 90641      **     SELECT a+b AS x FROM table WHERE x<10;
 90642      **
 90643      ** In cases like this, replace pExpr with a copy of the expression that
 90644      ** forms the result set entry ("a+b" in the example) and return immediately.
 90645      ** Note that the expression in the result set should have already been
 90646      ** resolved by the time the WHERE clause is resolved.
 90647      **
 90648      ** The ability to use an output result-set column in the WHERE, GROUP BY,
 90649      ** or HAVING clauses, or as part of a larger expression in the ORDER BY
 90650      ** clause is not standard SQL.  This is a (goofy) SQLite extension, that
 90651      ** is supported for backwards compatibility only. Hence, we issue a warning
 90652      ** on sqlite3_log() whenever the capability is used.
 90653      */
 90654      if( (pEList = pNC->pEList)!=0
 90655       && zTab==0
 90656       && cnt==0
 90657      ){
 90658        for(j=0; j<pEList->nExpr; j++){
 90659          char *zAs = pEList->a[j].zName;
 90660          if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
 90661            Expr *pOrig;
 90662            assert( pExpr->pLeft==0 && pExpr->pRight==0 );
 90663            assert( pExpr->x.pList==0 );
 90664            assert( pExpr->x.pSelect==0 );
 90665            pOrig = pEList->a[j].pExpr;
 90666            if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
 90667              sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
 90668              return WRC_Abort;
 90669            }
 90670            if( sqlite3ExprVectorSize(pOrig)!=1 ){
 90671              sqlite3ErrorMsg(pParse, "row value misused");
 90672              return WRC_Abort;
 90673            }
 90674            resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
 90675            cnt = 1;
 90676            pMatch = 0;
 90677            assert( zTab==0 && zDb==0 );
 90678            goto lookupname_end;
 90679          }
 90680        } 
 90681      }
 90682  
 90683      /* Advance to the next name context.  The loop will exit when either
 90684      ** we have a match (cnt>0) or when we run out of name contexts.
 90685      */
 90686      if( cnt ) break;
 90687      pNC = pNC->pNext;
 90688      nSubquery++;
 90689    }while( pNC );
 90690  
 90691  
 90692    /*
 90693    ** If X and Y are NULL (in other words if only the column name Z is
 90694    ** supplied) and the value of Z is enclosed in double-quotes, then
 90695    ** Z is a string literal if it doesn't match any column names.  In that
 90696    ** case, we need to return right away and not make any changes to
 90697    ** pExpr.
 90698    **
 90699    ** Because no reference was made to outer contexts, the pNC->nRef
 90700    ** fields are not changed in any context.
 90701    */
 90702    if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
 90703      pExpr->op = TK_STRING;
 90704      pExpr->pTab = 0;
 90705      return WRC_Prune;
 90706    }
 90707  
 90708    /*
 90709    ** cnt==0 means there was not match.  cnt>1 means there were two or
 90710    ** more matches.  Either way, we have an error.
 90711    */
 90712    if( cnt!=1 ){
 90713      const char *zErr;
 90714      zErr = cnt==0 ? "no such column" : "ambiguous column name";
 90715      if( zDb ){
 90716        sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
 90717      }else if( zTab ){
 90718        sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
 90719      }else{
 90720        sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
 90721      }
 90722      pParse->checkSchema = 1;
 90723      pTopNC->nErr++;
 90724    }
 90725  
 90726    /* If a column from a table in pSrcList is referenced, then record
 90727    ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
 90728    ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
 90729    ** column number is greater than the number of bits in the bitmask
 90730    ** then set the high-order bit of the bitmask.
 90731    */
 90732    if( pExpr->iColumn>=0 && pMatch!=0 ){
 90733      int n = pExpr->iColumn;
 90734      testcase( n==BMS-1 );
 90735      if( n>=BMS ){
 90736        n = BMS-1;
 90737      }
 90738      assert( pMatch->iCursor==pExpr->iTable );
 90739      pMatch->colUsed |= ((Bitmask)1)<<n;
 90740    }
 90741  
 90742    /* Clean up and return
 90743    */
 90744    sqlite3ExprDelete(db, pExpr->pLeft);
 90745    pExpr->pLeft = 0;
 90746    sqlite3ExprDelete(db, pExpr->pRight);
 90747    pExpr->pRight = 0;
 90748    pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
 90749    ExprSetProperty(pExpr, EP_Leaf);
 90750  lookupname_end:
 90751    if( cnt==1 ){
 90752      assert( pNC!=0 );
 90753      if( !ExprHasProperty(pExpr, EP_Alias) ){
 90754        sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
 90755      }
 90756      /* Increment the nRef value on all name contexts from TopNC up to
 90757      ** the point where the name matched. */
 90758      for(;;){
 90759        assert( pTopNC!=0 );
 90760        pTopNC->nRef++;
 90761        if( pTopNC==pNC ) break;
 90762        pTopNC = pTopNC->pNext;
 90763      }
 90764      return WRC_Prune;
 90765    } else {
 90766      return WRC_Abort;
 90767    }
 90768  }
 90769  
 90770  /*
 90771  ** Allocate and return a pointer to an expression to load the column iCol
 90772  ** from datasource iSrc in SrcList pSrc.
 90773  */
 90774  SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
 90775    Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
 90776    if( p ){
 90777      struct SrcList_item *pItem = &pSrc->a[iSrc];
 90778      p->pTab = pItem->pTab;
 90779      p->iTable = pItem->iCursor;
 90780      if( p->pTab->iPKey==iCol ){
 90781        p->iColumn = -1;
 90782      }else{
 90783        p->iColumn = (ynVar)iCol;
 90784        testcase( iCol==BMS );
 90785        testcase( iCol==BMS-1 );
 90786        pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
 90787      }
 90788    }
 90789    return p;
 90790  }
 90791  
 90792  /*
 90793  ** Report an error that an expression is not valid for some set of
 90794  ** pNC->ncFlags values determined by validMask.
 90795  */
 90796  static void notValid(
 90797    Parse *pParse,       /* Leave error message here */
 90798    NameContext *pNC,    /* The name context */
 90799    const char *zMsg,    /* Type of error */
 90800    int validMask        /* Set of contexts for which prohibited */
 90801  ){
 90802    assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
 90803    if( (pNC->ncFlags & validMask)!=0 ){
 90804      const char *zIn = "partial index WHERE clauses";
 90805      if( pNC->ncFlags & NC_IdxExpr )      zIn = "index expressions";
 90806  #ifndef SQLITE_OMIT_CHECK
 90807      else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
 90808  #endif
 90809      sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
 90810    }
 90811  }
 90812  
 90813  /*
 90814  ** Expression p should encode a floating point value between 1.0 and 0.0.
 90815  ** Return 1024 times this value.  Or return -1 if p is not a floating point
 90816  ** value between 1.0 and 0.0.
 90817  */
 90818  static int exprProbability(Expr *p){
 90819    double r = -1.0;
 90820    if( p->op!=TK_FLOAT ) return -1;
 90821    sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
 90822    assert( r>=0.0 );
 90823    if( r>1.0 ) return -1;
 90824    return (int)(r*134217728.0);
 90825  }
 90826  
 90827  /*
 90828  ** This routine is callback for sqlite3WalkExpr().
 90829  **
 90830  ** Resolve symbolic names into TK_COLUMN operators for the current
 90831  ** node in the expression tree.  Return 0 to continue the search down
 90832  ** the tree or 2 to abort the tree walk.
 90833  **
 90834  ** This routine also does error checking and name resolution for
 90835  ** function names.  The operator for aggregate functions is changed
 90836  ** to TK_AGG_FUNCTION.
 90837  */
 90838  static int resolveExprStep(Walker *pWalker, Expr *pExpr){
 90839    NameContext *pNC;
 90840    Parse *pParse;
 90841  
 90842    pNC = pWalker->u.pNC;
 90843    assert( pNC!=0 );
 90844    pParse = pNC->pParse;
 90845    assert( pParse==pWalker->pParse );
 90846  
 90847  #ifndef NDEBUG
 90848    if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
 90849      SrcList *pSrcList = pNC->pSrcList;
 90850      int i;
 90851      for(i=0; i<pNC->pSrcList->nSrc; i++){
 90852        assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
 90853      }
 90854    }
 90855  #endif
 90856    switch( pExpr->op ){
 90857  
 90858  #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
 90859      /* The special operator TK_ROW means use the rowid for the first
 90860      ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
 90861      ** clause processing on UPDATE and DELETE statements.
 90862      */
 90863      case TK_ROW: {
 90864        SrcList *pSrcList = pNC->pSrcList;
 90865        struct SrcList_item *pItem;
 90866        assert( pSrcList && pSrcList->nSrc==1 );
 90867        pItem = pSrcList->a; 
 90868        pExpr->op = TK_COLUMN;
 90869        pExpr->pTab = pItem->pTab;
 90870        pExpr->iTable = pItem->iCursor;
 90871        pExpr->iColumn = -1;
 90872        pExpr->affinity = SQLITE_AFF_INTEGER;
 90873        break;
 90874      }
 90875  #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
 90876            && !defined(SQLITE_OMIT_SUBQUERY) */
 90877  
 90878      /* A column name:                    ID
 90879      ** Or table name and column name:    ID.ID
 90880      ** Or a database, table and column:  ID.ID.ID
 90881      **
 90882      ** The TK_ID and TK_OUT cases are combined so that there will only
 90883      ** be one call to lookupName().  Then the compiler will in-line 
 90884      ** lookupName() for a size reduction and performance increase.
 90885      */
 90886      case TK_ID:
 90887      case TK_DOT: {
 90888        const char *zColumn;
 90889        const char *zTable;
 90890        const char *zDb;
 90891        Expr *pRight;
 90892  
 90893        if( pExpr->op==TK_ID ){
 90894          zDb = 0;
 90895          zTable = 0;
 90896          zColumn = pExpr->u.zToken;
 90897        }else{
 90898          notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
 90899          pRight = pExpr->pRight;
 90900          if( pRight->op==TK_ID ){
 90901            zDb = 0;
 90902            zTable = pExpr->pLeft->u.zToken;
 90903            zColumn = pRight->u.zToken;
 90904          }else{
 90905            assert( pRight->op==TK_DOT );
 90906            zDb = pExpr->pLeft->u.zToken;
 90907            zTable = pRight->pLeft->u.zToken;
 90908            zColumn = pRight->pRight->u.zToken;
 90909          }
 90910        }
 90911        return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
 90912      }
 90913  
 90914      /* Resolve function names
 90915      */
 90916      case TK_FUNCTION: {
 90917        ExprList *pList = pExpr->x.pList;    /* The argument list */
 90918        int n = pList ? pList->nExpr : 0;    /* Number of arguments */
 90919        int no_such_func = 0;       /* True if no such function exists */
 90920        int wrong_num_args = 0;     /* True if wrong number of arguments */
 90921        int is_agg = 0;             /* True if is an aggregate function */
 90922        int nId;                    /* Number of characters in function name */
 90923        const char *zId;            /* The function name. */
 90924        FuncDef *pDef;              /* Information about the function */
 90925        u8 enc = ENC(pParse->db);   /* The database encoding */
 90926  
 90927        assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
 90928        zId = pExpr->u.zToken;
 90929        nId = sqlite3Strlen30(zId);
 90930        pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
 90931        if( pDef==0 ){
 90932          pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
 90933          if( pDef==0 ){
 90934            no_such_func = 1;
 90935          }else{
 90936            wrong_num_args = 1;
 90937          }
 90938        }else{
 90939          is_agg = pDef->xFinalize!=0;
 90940          if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
 90941            ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
 90942            if( n==2 ){
 90943              pExpr->iTable = exprProbability(pList->a[1].pExpr);
 90944              if( pExpr->iTable<0 ){
 90945                sqlite3ErrorMsg(pParse,
 90946                  "second argument to likelihood() must be a "
 90947                  "constant between 0.0 and 1.0");
 90948                pNC->nErr++;
 90949              }
 90950            }else{
 90951              /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
 90952              ** equivalent to likelihood(X, 0.0625).
 90953              ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
 90954              ** short-hand for likelihood(X,0.0625).
 90955              ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
 90956              ** for likelihood(X,0.9375).
 90957              ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
 90958              ** to likelihood(X,0.9375). */
 90959              /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */
 90960              pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
 90961            }             
 90962          }
 90963  #ifndef SQLITE_OMIT_AUTHORIZATION
 90964          {
 90965            int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
 90966            if( auth!=SQLITE_OK ){
 90967              if( auth==SQLITE_DENY ){
 90968                sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
 90969                                        pDef->zName);
 90970                pNC->nErr++;
 90971              }
 90972              pExpr->op = TK_NULL;
 90973              return WRC_Prune;
 90974            }
 90975          }
 90976  #endif
 90977          if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
 90978            /* For the purposes of the EP_ConstFunc flag, date and time
 90979            ** functions and other functions that change slowly are considered
 90980            ** constant because they are constant for the duration of one query */
 90981            ExprSetProperty(pExpr,EP_ConstFunc);
 90982          }
 90983          if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
 90984            /* Date/time functions that use 'now', and other functions like
 90985            ** sqlite_version() that might change over time cannot be used
 90986            ** in an index. */
 90987            notValid(pParse, pNC, "non-deterministic functions",
 90988                     NC_IdxExpr|NC_PartIdx);
 90989          }
 90990        }
 90991        if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
 90992          sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
 90993          pNC->nErr++;
 90994          is_agg = 0;
 90995        }else if( no_such_func && pParse->db->init.busy==0
 90996  #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
 90997                  && pParse->explain==0
 90998  #endif
 90999        ){
 91000          sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
 91001          pNC->nErr++;
 91002        }else if( wrong_num_args ){
 91003          sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
 91004               nId, zId);
 91005          pNC->nErr++;
 91006        }
 91007        if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
 91008        sqlite3WalkExprList(pWalker, pList);
 91009        if( is_agg ){
 91010          NameContext *pNC2 = pNC;
 91011          pExpr->op = TK_AGG_FUNCTION;
 91012          pExpr->op2 = 0;
 91013          while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
 91014            pExpr->op2++;
 91015            pNC2 = pNC2->pNext;
 91016          }
 91017          assert( pDef!=0 );
 91018          if( pNC2 ){
 91019            assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
 91020            testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
 91021            pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
 91022  
 91023          }
 91024          pNC->ncFlags |= NC_AllowAgg;
 91025        }
 91026        /* FIX ME:  Compute pExpr->affinity based on the expected return
 91027        ** type of the function 
 91028        */
 91029        return WRC_Prune;
 91030      }
 91031  #ifndef SQLITE_OMIT_SUBQUERY
 91032      case TK_SELECT:
 91033      case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
 91034  #endif
 91035      case TK_IN: {
 91036        testcase( pExpr->op==TK_IN );
 91037        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
 91038          int nRef = pNC->nRef;
 91039          notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
 91040          sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
 91041          assert( pNC->nRef>=nRef );
 91042          if( nRef!=pNC->nRef ){
 91043            ExprSetProperty(pExpr, EP_VarSelect);
 91044            pNC->ncFlags |= NC_VarSelect;
 91045          }
 91046        }
 91047        break;
 91048      }
 91049      case TK_VARIABLE: {
 91050        notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
 91051        break;
 91052      }
 91053      case TK_BETWEEN:
 91054      case TK_EQ:
 91055      case TK_NE:
 91056      case TK_LT:
 91057      case TK_LE:
 91058      case TK_GT:
 91059      case TK_GE:
 91060      case TK_IS:
 91061      case TK_ISNOT: {
 91062        int nLeft, nRight;
 91063        if( pParse->db->mallocFailed ) break;
 91064        assert( pExpr->pLeft!=0 );
 91065        nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
 91066        if( pExpr->op==TK_BETWEEN ){
 91067          nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
 91068          if( nRight==nLeft ){
 91069            nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
 91070          }
 91071        }else{
 91072          assert( pExpr->pRight!=0 );
 91073          nRight = sqlite3ExprVectorSize(pExpr->pRight);
 91074        }
 91075        if( nLeft!=nRight ){
 91076          testcase( pExpr->op==TK_EQ );
 91077          testcase( pExpr->op==TK_NE );
 91078          testcase( pExpr->op==TK_LT );
 91079          testcase( pExpr->op==TK_LE );
 91080          testcase( pExpr->op==TK_GT );
 91081          testcase( pExpr->op==TK_GE );
 91082          testcase( pExpr->op==TK_IS );
 91083          testcase( pExpr->op==TK_ISNOT );
 91084          testcase( pExpr->op==TK_BETWEEN );
 91085          sqlite3ErrorMsg(pParse, "row value misused");
 91086        }
 91087        break; 
 91088      }
 91089    }
 91090    return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
 91091  }
 91092  
 91093  /*
 91094  ** pEList is a list of expressions which are really the result set of the
 91095  ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
 91096  ** This routine checks to see if pE is a simple identifier which corresponds
 91097  ** to the AS-name of one of the terms of the expression list.  If it is,
 91098  ** this routine return an integer between 1 and N where N is the number of
 91099  ** elements in pEList, corresponding to the matching entry.  If there is
 91100  ** no match, or if pE is not a simple identifier, then this routine
 91101  ** return 0.
 91102  **
 91103  ** pEList has been resolved.  pE has not.
 91104  */
 91105  static int resolveAsName(
 91106    Parse *pParse,     /* Parsing context for error messages */
 91107    ExprList *pEList,  /* List of expressions to scan */
 91108    Expr *pE           /* Expression we are trying to match */
 91109  ){
 91110    int i;             /* Loop counter */
 91111  
 91112    UNUSED_PARAMETER(pParse);
 91113  
 91114    if( pE->op==TK_ID ){
 91115      char *zCol = pE->u.zToken;
 91116      for(i=0; i<pEList->nExpr; i++){
 91117        char *zAs = pEList->a[i].zName;
 91118        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
 91119          return i+1;
 91120        }
 91121      }
 91122    }
 91123    return 0;
 91124  }
 91125  
 91126  /*
 91127  ** pE is a pointer to an expression which is a single term in the
 91128  ** ORDER BY of a compound SELECT.  The expression has not been
 91129  ** name resolved.
 91130  **
 91131  ** At the point this routine is called, we already know that the
 91132  ** ORDER BY term is not an integer index into the result set.  That
 91133  ** case is handled by the calling routine.
 91134  **
 91135  ** Attempt to match pE against result set columns in the left-most
 91136  ** SELECT statement.  Return the index i of the matching column,
 91137  ** as an indication to the caller that it should sort by the i-th column.
 91138  ** The left-most column is 1.  In other words, the value returned is the
 91139  ** same integer value that would be used in the SQL statement to indicate
 91140  ** the column.
 91141  **
 91142  ** If there is no match, return 0.  Return -1 if an error occurs.
 91143  */
 91144  static int resolveOrderByTermToExprList(
 91145    Parse *pParse,     /* Parsing context for error messages */
 91146    Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
 91147    Expr *pE           /* The specific ORDER BY term */
 91148  ){
 91149    int i;             /* Loop counter */
 91150    ExprList *pEList;  /* The columns of the result set */
 91151    NameContext nc;    /* Name context for resolving pE */
 91152    sqlite3 *db;       /* Database connection */
 91153    int rc;            /* Return code from subprocedures */
 91154    u8 savedSuppErr;   /* Saved value of db->suppressErr */
 91155  
 91156    assert( sqlite3ExprIsInteger(pE, &i)==0 );
 91157    pEList = pSelect->pEList;
 91158  
 91159    /* Resolve all names in the ORDER BY term expression
 91160    */
 91161    memset(&nc, 0, sizeof(nc));
 91162    nc.pParse = pParse;
 91163    nc.pSrcList = pSelect->pSrc;
 91164    nc.pEList = pEList;
 91165    nc.ncFlags = NC_AllowAgg;
 91166    nc.nErr = 0;
 91167    db = pParse->db;
 91168    savedSuppErr = db->suppressErr;
 91169    db->suppressErr = 1;
 91170    rc = sqlite3ResolveExprNames(&nc, pE);
 91171    db->suppressErr = savedSuppErr;
 91172    if( rc ) return 0;
 91173  
 91174    /* Try to match the ORDER BY expression against an expression
 91175    ** in the result set.  Return an 1-based index of the matching
 91176    ** result-set entry.
 91177    */
 91178    for(i=0; i<pEList->nExpr; i++){
 91179      if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
 91180        return i+1;
 91181      }
 91182    }
 91183  
 91184    /* If no match, return 0. */
 91185    return 0;
 91186  }
 91187  
 91188  /*
 91189  ** Generate an ORDER BY or GROUP BY term out-of-range error.
 91190  */
 91191  static void resolveOutOfRangeError(
 91192    Parse *pParse,         /* The error context into which to write the error */
 91193    const char *zType,     /* "ORDER" or "GROUP" */
 91194    int i,                 /* The index (1-based) of the term out of range */
 91195    int mx                 /* Largest permissible value of i */
 91196  ){
 91197    sqlite3ErrorMsg(pParse, 
 91198      "%r %s BY term out of range - should be "
 91199      "between 1 and %d", i, zType, mx);
 91200  }
 91201  
 91202  /*
 91203  ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
 91204  ** each term of the ORDER BY clause is a constant integer between 1
 91205  ** and N where N is the number of columns in the compound SELECT.
 91206  **
 91207  ** ORDER BY terms that are already an integer between 1 and N are
 91208  ** unmodified.  ORDER BY terms that are integers outside the range of
 91209  ** 1 through N generate an error.  ORDER BY terms that are expressions
 91210  ** are matched against result set expressions of compound SELECT
 91211  ** beginning with the left-most SELECT and working toward the right.
 91212  ** At the first match, the ORDER BY expression is transformed into
 91213  ** the integer column number.
 91214  **
 91215  ** Return the number of errors seen.
 91216  */
 91217  static int resolveCompoundOrderBy(
 91218    Parse *pParse,        /* Parsing context.  Leave error messages here */
 91219    Select *pSelect       /* The SELECT statement containing the ORDER BY */
 91220  ){
 91221    int i;
 91222    ExprList *pOrderBy;
 91223    ExprList *pEList;
 91224    sqlite3 *db;
 91225    int moreToDo = 1;
 91226  
 91227    pOrderBy = pSelect->pOrderBy;
 91228    if( pOrderBy==0 ) return 0;
 91229    db = pParse->db;
 91230    if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
 91231      sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
 91232      return 1;
 91233    }
 91234    for(i=0; i<pOrderBy->nExpr; i++){
 91235      pOrderBy->a[i].done = 0;
 91236    }
 91237    pSelect->pNext = 0;
 91238    while( pSelect->pPrior ){
 91239      pSelect->pPrior->pNext = pSelect;
 91240      pSelect = pSelect->pPrior;
 91241    }
 91242    while( pSelect && moreToDo ){
 91243      struct ExprList_item *pItem;
 91244      moreToDo = 0;
 91245      pEList = pSelect->pEList;
 91246      assert( pEList!=0 );
 91247      for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
 91248        int iCol = -1;
 91249        Expr *pE, *pDup;
 91250        if( pItem->done ) continue;
 91251        pE = sqlite3ExprSkipCollate(pItem->pExpr);
 91252        if( sqlite3ExprIsInteger(pE, &iCol) ){
 91253          if( iCol<=0 || iCol>pEList->nExpr ){
 91254            resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
 91255            return 1;
 91256          }
 91257        }else{
 91258          iCol = resolveAsName(pParse, pEList, pE);
 91259          if( iCol==0 ){
 91260            pDup = sqlite3ExprDup(db, pE, 0);
 91261            if( !db->mallocFailed ){
 91262              assert(pDup);
 91263              iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
 91264            }
 91265            sqlite3ExprDelete(db, pDup);
 91266          }
 91267        }
 91268        if( iCol>0 ){
 91269          /* Convert the ORDER BY term into an integer column number iCol,
 91270          ** taking care to preserve the COLLATE clause if it exists */
 91271          Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
 91272          if( pNew==0 ) return 1;
 91273          pNew->flags |= EP_IntValue;
 91274          pNew->u.iValue = iCol;
 91275          if( pItem->pExpr==pE ){
 91276            pItem->pExpr = pNew;
 91277          }else{
 91278            Expr *pParent = pItem->pExpr;
 91279            assert( pParent->op==TK_COLLATE );
 91280            while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
 91281            assert( pParent->pLeft==pE );
 91282            pParent->pLeft = pNew;
 91283          }
 91284          sqlite3ExprDelete(db, pE);
 91285          pItem->u.x.iOrderByCol = (u16)iCol;
 91286          pItem->done = 1;
 91287        }else{
 91288          moreToDo = 1;
 91289        }
 91290      }
 91291      pSelect = pSelect->pNext;
 91292    }
 91293    for(i=0; i<pOrderBy->nExpr; i++){
 91294      if( pOrderBy->a[i].done==0 ){
 91295        sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
 91296              "column in the result set", i+1);
 91297        return 1;
 91298      }
 91299    }
 91300    return 0;
 91301  }
 91302  
 91303  /*
 91304  ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
 91305  ** the SELECT statement pSelect.  If any term is reference to a
 91306  ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
 91307  ** field) then convert that term into a copy of the corresponding result set
 91308  ** column.
 91309  **
 91310  ** If any errors are detected, add an error message to pParse and
 91311  ** return non-zero.  Return zero if no errors are seen.
 91312  */
 91313  SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
 91314    Parse *pParse,        /* Parsing context.  Leave error messages here */
 91315    Select *pSelect,      /* The SELECT statement containing the clause */
 91316    ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
 91317    const char *zType     /* "ORDER" or "GROUP" */
 91318  ){
 91319    int i;
 91320    sqlite3 *db = pParse->db;
 91321    ExprList *pEList;
 91322    struct ExprList_item *pItem;
 91323  
 91324    if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
 91325    if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
 91326      sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
 91327      return 1;
 91328    }
 91329    pEList = pSelect->pEList;
 91330    assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
 91331    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
 91332      if( pItem->u.x.iOrderByCol ){
 91333        if( pItem->u.x.iOrderByCol>pEList->nExpr ){
 91334          resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
 91335          return 1;
 91336        }
 91337        resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
 91338                     zType,0);
 91339      }
 91340    }
 91341    return 0;
 91342  }
 91343  
 91344  /*
 91345  ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
 91346  ** The Name context of the SELECT statement is pNC.  zType is either
 91347  ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
 91348  **
 91349  ** This routine resolves each term of the clause into an expression.
 91350  ** If the order-by term is an integer I between 1 and N (where N is the
 91351  ** number of columns in the result set of the SELECT) then the expression
 91352  ** in the resolution is a copy of the I-th result-set expression.  If
 91353  ** the order-by term is an identifier that corresponds to the AS-name of
 91354  ** a result-set expression, then the term resolves to a copy of the
 91355  ** result-set expression.  Otherwise, the expression is resolved in
 91356  ** the usual way - using sqlite3ResolveExprNames().
 91357  **
 91358  ** This routine returns the number of errors.  If errors occur, then
 91359  ** an appropriate error message might be left in pParse.  (OOM errors
 91360  ** excepted.)
 91361  */
 91362  static int resolveOrderGroupBy(
 91363    NameContext *pNC,     /* The name context of the SELECT statement */
 91364    Select *pSelect,      /* The SELECT statement holding pOrderBy */
 91365    ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
 91366    const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
 91367  ){
 91368    int i, j;                      /* Loop counters */
 91369    int iCol;                      /* Column number */
 91370    struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
 91371    Parse *pParse;                 /* Parsing context */
 91372    int nResult;                   /* Number of terms in the result set */
 91373  
 91374    if( pOrderBy==0 ) return 0;
 91375    nResult = pSelect->pEList->nExpr;
 91376    pParse = pNC->pParse;
 91377    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
 91378      Expr *pE = pItem->pExpr;
 91379      Expr *pE2 = sqlite3ExprSkipCollate(pE);
 91380      if( zType[0]!='G' ){
 91381        iCol = resolveAsName(pParse, pSelect->pEList, pE2);
 91382        if( iCol>0 ){
 91383          /* If an AS-name match is found, mark this ORDER BY column as being
 91384          ** a copy of the iCol-th result-set column.  The subsequent call to
 91385          ** sqlite3ResolveOrderGroupBy() will convert the expression to a
 91386          ** copy of the iCol-th result-set expression. */
 91387          pItem->u.x.iOrderByCol = (u16)iCol;
 91388          continue;
 91389        }
 91390      }
 91391      if( sqlite3ExprIsInteger(pE2, &iCol) ){
 91392        /* The ORDER BY term is an integer constant.  Again, set the column
 91393        ** number so that sqlite3ResolveOrderGroupBy() will convert the
 91394        ** order-by term to a copy of the result-set expression */
 91395        if( iCol<1 || iCol>0xffff ){
 91396          resolveOutOfRangeError(pParse, zType, i+1, nResult);
 91397          return 1;
 91398        }
 91399        pItem->u.x.iOrderByCol = (u16)iCol;
 91400        continue;
 91401      }
 91402  
 91403      /* Otherwise, treat the ORDER BY term as an ordinary expression */
 91404      pItem->u.x.iOrderByCol = 0;
 91405      if( sqlite3ResolveExprNames(pNC, pE) ){
 91406        return 1;
 91407      }
 91408      for(j=0; j<pSelect->pEList->nExpr; j++){
 91409        if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
 91410          pItem->u.x.iOrderByCol = j+1;
 91411        }
 91412      }
 91413    }
 91414    return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
 91415  }
 91416  
 91417  /*
 91418  ** Resolve names in the SELECT statement p and all of its descendants.
 91419  */
 91420  static int resolveSelectStep(Walker *pWalker, Select *p){
 91421    NameContext *pOuterNC;  /* Context that contains this SELECT */
 91422    NameContext sNC;        /* Name context of this SELECT */
 91423    int isCompound;         /* True if p is a compound select */
 91424    int nCompound;          /* Number of compound terms processed so far */
 91425    Parse *pParse;          /* Parsing context */
 91426    int i;                  /* Loop counter */
 91427    ExprList *pGroupBy;     /* The GROUP BY clause */
 91428    Select *pLeftmost;      /* Left-most of SELECT of a compound */
 91429    sqlite3 *db;            /* Database connection */
 91430    
 91431  
 91432    assert( p!=0 );
 91433    if( p->selFlags & SF_Resolved ){
 91434      return WRC_Prune;
 91435    }
 91436    pOuterNC = pWalker->u.pNC;
 91437    pParse = pWalker->pParse;
 91438    db = pParse->db;
 91439  
 91440    /* Normally sqlite3SelectExpand() will be called first and will have
 91441    ** already expanded this SELECT.  However, if this is a subquery within
 91442    ** an expression, sqlite3ResolveExprNames() will be called without a
 91443    ** prior call to sqlite3SelectExpand().  When that happens, let
 91444    ** sqlite3SelectPrep() do all of the processing for this SELECT.
 91445    ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
 91446    ** this routine in the correct order.
 91447    */
 91448    if( (p->selFlags & SF_Expanded)==0 ){
 91449      sqlite3SelectPrep(pParse, p, pOuterNC);
 91450      return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
 91451    }
 91452  
 91453    isCompound = p->pPrior!=0;
 91454    nCompound = 0;
 91455    pLeftmost = p;
 91456    while( p ){
 91457      assert( (p->selFlags & SF_Expanded)!=0 );
 91458      assert( (p->selFlags & SF_Resolved)==0 );
 91459      p->selFlags |= SF_Resolved;
 91460  
 91461      /* Resolve the expressions in the LIMIT and OFFSET clauses. These
 91462      ** are not allowed to refer to any names, so pass an empty NameContext.
 91463      */
 91464      memset(&sNC, 0, sizeof(sNC));
 91465      sNC.pParse = pParse;
 91466      if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
 91467          sqlite3ResolveExprNames(&sNC, p->pOffset) ){
 91468        return WRC_Abort;
 91469      }
 91470  
 91471      /* If the SF_Converted flags is set, then this Select object was
 91472      ** was created by the convertCompoundSelectToSubquery() function.
 91473      ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
 91474      ** as if it were part of the sub-query, not the parent. This block
 91475      ** moves the pOrderBy down to the sub-query. It will be moved back
 91476      ** after the names have been resolved.  */
 91477      if( p->selFlags & SF_Converted ){
 91478        Select *pSub = p->pSrc->a[0].pSelect;
 91479        assert( p->pSrc->nSrc==1 && p->pOrderBy );
 91480        assert( pSub->pPrior && pSub->pOrderBy==0 );
 91481        pSub->pOrderBy = p->pOrderBy;
 91482        p->pOrderBy = 0;
 91483      }
 91484    
 91485      /* Recursively resolve names in all subqueries
 91486      */
 91487      for(i=0; i<p->pSrc->nSrc; i++){
 91488        struct SrcList_item *pItem = &p->pSrc->a[i];
 91489        if( pItem->pSelect ){
 91490          NameContext *pNC;         /* Used to iterate name contexts */
 91491          int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
 91492          const char *zSavedContext = pParse->zAuthContext;
 91493  
 91494          /* Count the total number of references to pOuterNC and all of its
 91495          ** parent contexts. After resolving references to expressions in
 91496          ** pItem->pSelect, check if this value has changed. If so, then
 91497          ** SELECT statement pItem->pSelect must be correlated. Set the
 91498          ** pItem->fg.isCorrelated flag if this is the case. */
 91499          for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
 91500  
 91501          if( pItem->zName ) pParse->zAuthContext = pItem->zName;
 91502          sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
 91503          pParse->zAuthContext = zSavedContext;
 91504          if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
 91505  
 91506          for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
 91507          assert( pItem->fg.isCorrelated==0 && nRef<=0 );
 91508          pItem->fg.isCorrelated = (nRef!=0);
 91509        }
 91510      }
 91511    
 91512      /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
 91513      ** resolve the result-set expression list.
 91514      */
 91515      sNC.ncFlags = NC_AllowAgg;
 91516      sNC.pSrcList = p->pSrc;
 91517      sNC.pNext = pOuterNC;
 91518    
 91519      /* Resolve names in the result set. */
 91520      if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
 91521    
 91522      /* If there are no aggregate functions in the result-set, and no GROUP BY 
 91523      ** expression, do not allow aggregates in any of the other expressions.
 91524      */
 91525      assert( (p->selFlags & SF_Aggregate)==0 );
 91526      pGroupBy = p->pGroupBy;
 91527      if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
 91528        assert( NC_MinMaxAgg==SF_MinMaxAgg );
 91529        p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
 91530      }else{
 91531        sNC.ncFlags &= ~NC_AllowAgg;
 91532      }
 91533    
 91534      /* If a HAVING clause is present, then there must be a GROUP BY clause.
 91535      */
 91536      if( p->pHaving && !pGroupBy ){
 91537        sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
 91538        return WRC_Abort;
 91539      }
 91540    
 91541      /* Add the output column list to the name-context before parsing the
 91542      ** other expressions in the SELECT statement. This is so that
 91543      ** expressions in the WHERE clause (etc.) can refer to expressions by
 91544      ** aliases in the result set.
 91545      **
 91546      ** Minor point: If this is the case, then the expression will be
 91547      ** re-evaluated for each reference to it.
 91548      */
 91549      sNC.pEList = p->pEList;
 91550      if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
 91551      if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
 91552  
 91553      /* Resolve names in table-valued-function arguments */
 91554      for(i=0; i<p->pSrc->nSrc; i++){
 91555        struct SrcList_item *pItem = &p->pSrc->a[i];
 91556        if( pItem->fg.isTabFunc
 91557         && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg) 
 91558        ){
 91559          return WRC_Abort;
 91560        }
 91561      }
 91562  
 91563      /* The ORDER BY and GROUP BY clauses may not refer to terms in
 91564      ** outer queries 
 91565      */
 91566      sNC.pNext = 0;
 91567      sNC.ncFlags |= NC_AllowAgg;
 91568  
 91569      /* If this is a converted compound query, move the ORDER BY clause from 
 91570      ** the sub-query back to the parent query. At this point each term
 91571      ** within the ORDER BY clause has been transformed to an integer value.
 91572      ** These integers will be replaced by copies of the corresponding result
 91573      ** set expressions by the call to resolveOrderGroupBy() below.  */
 91574      if( p->selFlags & SF_Converted ){
 91575        Select *pSub = p->pSrc->a[0].pSelect;
 91576        p->pOrderBy = pSub->pOrderBy;
 91577        pSub->pOrderBy = 0;
 91578      }
 91579  
 91580      /* Process the ORDER BY clause for singleton SELECT statements.
 91581      ** The ORDER BY clause for compounds SELECT statements is handled
 91582      ** below, after all of the result-sets for all of the elements of
 91583      ** the compound have been resolved.
 91584      **
 91585      ** If there is an ORDER BY clause on a term of a compound-select other
 91586      ** than the right-most term, then that is a syntax error.  But the error
 91587      ** is not detected until much later, and so we need to go ahead and
 91588      ** resolve those symbols on the incorrect ORDER BY for consistency.
 91589      */
 91590      if( isCompound<=nCompound  /* Defer right-most ORDER BY of a compound */
 91591       && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
 91592      ){
 91593        return WRC_Abort;
 91594      }
 91595      if( db->mallocFailed ){
 91596        return WRC_Abort;
 91597      }
 91598    
 91599      /* Resolve the GROUP BY clause.  At the same time, make sure 
 91600      ** the GROUP BY clause does not contain aggregate functions.
 91601      */
 91602      if( pGroupBy ){
 91603        struct ExprList_item *pItem;
 91604      
 91605        if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
 91606          return WRC_Abort;
 91607        }
 91608        for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
 91609          if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
 91610            sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
 91611                "the GROUP BY clause");
 91612            return WRC_Abort;
 91613          }
 91614        }
 91615      }
 91616  
 91617      /* If this is part of a compound SELECT, check that it has the right
 91618      ** number of expressions in the select list. */
 91619      if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
 91620        sqlite3SelectWrongNumTermsError(pParse, p->pNext);
 91621        return WRC_Abort;
 91622      }
 91623  
 91624      /* Advance to the next term of the compound
 91625      */
 91626      p = p->pPrior;
 91627      nCompound++;
 91628    }
 91629  
 91630    /* Resolve the ORDER BY on a compound SELECT after all terms of
 91631    ** the compound have been resolved.
 91632    */
 91633    if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
 91634      return WRC_Abort;
 91635    }
 91636  
 91637    return WRC_Prune;
 91638  }
 91639  
 91640  /*
 91641  ** This routine walks an expression tree and resolves references to
 91642  ** table columns and result-set columns.  At the same time, do error
 91643  ** checking on function usage and set a flag if any aggregate functions
 91644  ** are seen.
 91645  **
 91646  ** To resolve table columns references we look for nodes (or subtrees) of the 
 91647  ** form X.Y.Z or Y.Z or just Z where
 91648  **
 91649  **      X:   The name of a database.  Ex:  "main" or "temp" or
 91650  **           the symbolic name assigned to an ATTACH-ed database.
 91651  **
 91652  **      Y:   The name of a table in a FROM clause.  Or in a trigger
 91653  **           one of the special names "old" or "new".
 91654  **
 91655  **      Z:   The name of a column in table Y.
 91656  **
 91657  ** The node at the root of the subtree is modified as follows:
 91658  **
 91659  **    Expr.op        Changed to TK_COLUMN
 91660  **    Expr.pTab      Points to the Table object for X.Y
 91661  **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
 91662  **    Expr.iTable    The VDBE cursor number for X.Y
 91663  **
 91664  **
 91665  ** To resolve result-set references, look for expression nodes of the
 91666  ** form Z (with no X and Y prefix) where the Z matches the right-hand
 91667  ** size of an AS clause in the result-set of a SELECT.  The Z expression
 91668  ** is replaced by a copy of the left-hand side of the result-set expression.
 91669  ** Table-name and function resolution occurs on the substituted expression
 91670  ** tree.  For example, in:
 91671  **
 91672  **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
 91673  **
 91674  ** The "x" term of the order by is replaced by "a+b" to render:
 91675  **
 91676  **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
 91677  **
 91678  ** Function calls are checked to make sure that the function is 
 91679  ** defined and that the correct number of arguments are specified.
 91680  ** If the function is an aggregate function, then the NC_HasAgg flag is
 91681  ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
 91682  ** If an expression contains aggregate functions then the EP_Agg
 91683  ** property on the expression is set.
 91684  **
 91685  ** An error message is left in pParse if anything is amiss.  The number
 91686  ** if errors is returned.
 91687  */
 91688  SQLITE_PRIVATE int sqlite3ResolveExprNames( 
 91689    NameContext *pNC,       /* Namespace to resolve expressions in. */
 91690    Expr *pExpr             /* The expression to be analyzed. */
 91691  ){
 91692    u16 savedHasAgg;
 91693    Walker w;
 91694  
 91695    if( pExpr==0 ) return SQLITE_OK;
 91696    savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
 91697    pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
 91698    w.pParse = pNC->pParse;
 91699    w.xExprCallback = resolveExprStep;
 91700    w.xSelectCallback = resolveSelectStep;
 91701    w.xSelectCallback2 = 0;
 91702    w.u.pNC = pNC;
 91703  #if SQLITE_MAX_EXPR_DEPTH>0
 91704    w.pParse->nHeight += pExpr->nHeight;
 91705    if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
 91706      return SQLITE_ERROR;
 91707    }
 91708  #endif
 91709    sqlite3WalkExpr(&w, pExpr);
 91710  #if SQLITE_MAX_EXPR_DEPTH>0
 91711    w.pParse->nHeight -= pExpr->nHeight;
 91712  #endif
 91713    if( pNC->ncFlags & NC_HasAgg ){
 91714      ExprSetProperty(pExpr, EP_Agg);
 91715    }
 91716    pNC->ncFlags |= savedHasAgg;
 91717    return pNC->nErr>0 || w.pParse->nErr>0;
 91718  }
 91719  
 91720  /*
 91721  ** Resolve all names for all expression in an expression list.  This is
 91722  ** just like sqlite3ResolveExprNames() except that it works for an expression
 91723  ** list rather than a single expression.
 91724  */
 91725  SQLITE_PRIVATE int sqlite3ResolveExprListNames( 
 91726    NameContext *pNC,       /* Namespace to resolve expressions in. */
 91727    ExprList *pList         /* The expression list to be analyzed. */
 91728  ){
 91729    int i;
 91730    if( pList ){
 91731      for(i=0; i<pList->nExpr; i++){
 91732        if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
 91733      }
 91734    }
 91735    return WRC_Continue;
 91736  }
 91737  
 91738  /*
 91739  ** Resolve all names in all expressions of a SELECT and in all
 91740  ** decendents of the SELECT, including compounds off of p->pPrior,
 91741  ** subqueries in expressions, and subqueries used as FROM clause
 91742  ** terms.
 91743  **
 91744  ** See sqlite3ResolveExprNames() for a description of the kinds of
 91745  ** transformations that occur.
 91746  **
 91747  ** All SELECT statements should have been expanded using
 91748  ** sqlite3SelectExpand() prior to invoking this routine.
 91749  */
 91750  SQLITE_PRIVATE void sqlite3ResolveSelectNames(
 91751    Parse *pParse,         /* The parser context */
 91752    Select *p,             /* The SELECT statement being coded. */
 91753    NameContext *pOuterNC  /* Name context for parent SELECT statement */
 91754  ){
 91755    Walker w;
 91756  
 91757    assert( p!=0 );
 91758    w.xExprCallback = resolveExprStep;
 91759    w.xSelectCallback = resolveSelectStep;
 91760    w.xSelectCallback2 = 0;
 91761    w.pParse = pParse;
 91762    w.u.pNC = pOuterNC;
 91763    sqlite3WalkSelect(&w, p);
 91764  }
 91765  
 91766  /*
 91767  ** Resolve names in expressions that can only reference a single table:
 91768  **
 91769  **    *   CHECK constraints
 91770  **    *   WHERE clauses on partial indices
 91771  **
 91772  ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
 91773  ** is set to -1 and the Expr.iColumn value is set to the column number.
 91774  **
 91775  ** Any errors cause an error message to be set in pParse.
 91776  */
 91777  SQLITE_PRIVATE void sqlite3ResolveSelfReference(
 91778    Parse *pParse,      /* Parsing context */
 91779    Table *pTab,        /* The table being referenced */
 91780    int type,           /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
 91781    Expr *pExpr,        /* Expression to resolve.  May be NULL. */
 91782    ExprList *pList     /* Expression list to resolve.  May be NUL. */
 91783  ){
 91784    SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
 91785    NameContext sNC;                /* Name context for pParse->pNewTable */
 91786  
 91787    assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
 91788    memset(&sNC, 0, sizeof(sNC));
 91789    memset(&sSrc, 0, sizeof(sSrc));
 91790    sSrc.nSrc = 1;
 91791    sSrc.a[0].zName = pTab->zName;
 91792    sSrc.a[0].pTab = pTab;
 91793    sSrc.a[0].iCursor = -1;
 91794    sNC.pParse = pParse;
 91795    sNC.pSrcList = &sSrc;
 91796    sNC.ncFlags = type;
 91797    if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
 91798    if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
 91799  }
 91800  
 91801  /************** End of resolve.c *********************************************/
 91802  /************** Begin file expr.c ********************************************/
 91803  /*
 91804  ** 2001 September 15
 91805  **
 91806  ** The author disclaims copyright to this source code.  In place of
 91807  ** a legal notice, here is a blessing:
 91808  **
 91809  **    May you do good and not evil.
 91810  **    May you find forgiveness for yourself and forgive others.
 91811  **    May you share freely, never taking more than you give.
 91812  **
 91813  *************************************************************************
 91814  ** This file contains routines used for analyzing expressions and
 91815  ** for generating VDBE code that evaluates expressions in SQLite.
 91816  */
 91817  /* #include "sqliteInt.h" */
 91818  
 91819  /* Forward declarations */
 91820  static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
 91821  static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
 91822  
 91823  /*
 91824  ** Return the affinity character for a single column of a table.
 91825  */
 91826  SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){
 91827    assert( iCol<pTab->nCol );
 91828    return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
 91829  }
 91830  
 91831  /*
 91832  ** Return the 'affinity' of the expression pExpr if any.
 91833  **
 91834  ** If pExpr is a column, a reference to a column via an 'AS' alias,
 91835  ** or a sub-select with a column as the return value, then the 
 91836  ** affinity of that column is returned. Otherwise, 0x00 is returned,
 91837  ** indicating no affinity for the expression.
 91838  **
 91839  ** i.e. the WHERE clause expressions in the following statements all
 91840  ** have an affinity:
 91841  **
 91842  ** CREATE TABLE t1(a);
 91843  ** SELECT * FROM t1 WHERE a;
 91844  ** SELECT a AS b FROM t1 WHERE b;
 91845  ** SELECT * FROM t1 WHERE (select a from t1);
 91846  */
 91847  SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
 91848    int op;
 91849    pExpr = sqlite3ExprSkipCollate(pExpr);
 91850    if( pExpr->flags & EP_Generic ) return 0;
 91851    op = pExpr->op;
 91852    if( op==TK_SELECT ){
 91853      assert( pExpr->flags&EP_xIsSelect );
 91854      return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
 91855    }
 91856    if( op==TK_REGISTER ) op = pExpr->op2;
 91857  #ifndef SQLITE_OMIT_CAST
 91858    if( op==TK_CAST ){
 91859      assert( !ExprHasProperty(pExpr, EP_IntValue) );
 91860      return sqlite3AffinityType(pExpr->u.zToken, 0);
 91861    }
 91862  #endif
 91863    if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->pTab ){
 91864      return sqlite3TableColumnAffinity(pExpr->pTab, pExpr->iColumn);
 91865    }
 91866    if( op==TK_SELECT_COLUMN ){
 91867      assert( pExpr->pLeft->flags&EP_xIsSelect );
 91868      return sqlite3ExprAffinity(
 91869          pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
 91870      );
 91871    }
 91872    return pExpr->affinity;
 91873  }
 91874  
 91875  /*
 91876  ** Set the collating sequence for expression pExpr to be the collating
 91877  ** sequence named by pToken.   Return a pointer to a new Expr node that
 91878  ** implements the COLLATE operator.
 91879  **
 91880  ** If a memory allocation error occurs, that fact is recorded in pParse->db
 91881  ** and the pExpr parameter is returned unchanged.
 91882  */
 91883  SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
 91884    Parse *pParse,           /* Parsing context */
 91885    Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
 91886    const Token *pCollName,  /* Name of collating sequence */
 91887    int dequote              /* True to dequote pCollName */
 91888  ){
 91889    if( pCollName->n>0 ){
 91890      Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
 91891      if( pNew ){
 91892        pNew->pLeft = pExpr;
 91893        pNew->flags |= EP_Collate|EP_Skip;
 91894        pExpr = pNew;
 91895      }
 91896    }
 91897    return pExpr;
 91898  }
 91899  SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
 91900    Token s;
 91901    assert( zC!=0 );
 91902    sqlite3TokenInit(&s, (char*)zC);
 91903    return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
 91904  }
 91905  
 91906  /*
 91907  ** Skip over any TK_COLLATE operators and any unlikely()
 91908  ** or likelihood() function at the root of an expression.
 91909  */
 91910  SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
 91911    while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
 91912      if( ExprHasProperty(pExpr, EP_Unlikely) ){
 91913        assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
 91914        assert( pExpr->x.pList->nExpr>0 );
 91915        assert( pExpr->op==TK_FUNCTION );
 91916        pExpr = pExpr->x.pList->a[0].pExpr;
 91917      }else{
 91918        assert( pExpr->op==TK_COLLATE );
 91919        pExpr = pExpr->pLeft;
 91920      }
 91921    }   
 91922    return pExpr;
 91923  }
 91924  
 91925  /*
 91926  ** Return the collation sequence for the expression pExpr. If
 91927  ** there is no defined collating sequence, return NULL.
 91928  **
 91929  ** See also: sqlite3ExprNNCollSeq()
 91930  **
 91931  ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
 91932  ** default collation if pExpr has no defined collation.
 91933  **
 91934  ** The collating sequence might be determined by a COLLATE operator
 91935  ** or by the presence of a column with a defined collating sequence.
 91936  ** COLLATE operators take first precedence.  Left operands take
 91937  ** precedence over right operands.
 91938  */
 91939  SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
 91940    sqlite3 *db = pParse->db;
 91941    CollSeq *pColl = 0;
 91942    Expr *p = pExpr;
 91943    while( p ){
 91944      int op = p->op;
 91945      if( p->flags & EP_Generic ) break;
 91946      if( op==TK_CAST || op==TK_UPLUS ){
 91947        p = p->pLeft;
 91948        continue;
 91949      }
 91950      if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
 91951        pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
 91952        break;
 91953      }
 91954      if( (op==TK_AGG_COLUMN || op==TK_COLUMN
 91955            || op==TK_REGISTER || op==TK_TRIGGER)
 91956       && p->pTab!=0
 91957      ){
 91958        /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
 91959        ** a TK_COLUMN but was previously evaluated and cached in a register */
 91960        int j = p->iColumn;
 91961        if( j>=0 ){
 91962          const char *zColl = p->pTab->aCol[j].zColl;
 91963          pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
 91964        }
 91965        break;
 91966      }
 91967      if( p->flags & EP_Collate ){
 91968        if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
 91969          p = p->pLeft;
 91970        }else{
 91971          Expr *pNext  = p->pRight;
 91972          /* The Expr.x union is never used at the same time as Expr.pRight */
 91973          assert( p->x.pList==0 || p->pRight==0 );
 91974          /* p->flags holds EP_Collate and p->pLeft->flags does not.  And
 91975          ** p->x.pSelect cannot.  So if p->x.pLeft exists, it must hold at
 91976          ** least one EP_Collate. Thus the following two ALWAYS. */
 91977          if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
 91978            int i;
 91979            for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
 91980              if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
 91981                pNext = p->x.pList->a[i].pExpr;
 91982                break;
 91983              }
 91984            }
 91985          }
 91986          p = pNext;
 91987        }
 91988      }else{
 91989        break;
 91990      }
 91991    }
 91992    if( sqlite3CheckCollSeq(pParse, pColl) ){ 
 91993      pColl = 0;
 91994    }
 91995    return pColl;
 91996  }
 91997  
 91998  /*
 91999  ** Return the collation sequence for the expression pExpr. If
 92000  ** there is no defined collating sequence, return a pointer to the
 92001  ** defautl collation sequence.
 92002  **
 92003  ** See also: sqlite3ExprCollSeq()
 92004  **
 92005  ** The sqlite3ExprCollSeq() routine works the same except that it
 92006  ** returns NULL if there is no defined collation.
 92007  */
 92008  SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){
 92009    CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
 92010    if( p==0 ) p = pParse->db->pDfltColl;
 92011    assert( p!=0 );
 92012    return p;
 92013  }
 92014  
 92015  /*
 92016  ** Return TRUE if the two expressions have equivalent collating sequences.
 92017  */
 92018  SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){
 92019    CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
 92020    CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
 92021    return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
 92022  }
 92023  
 92024  /*
 92025  ** pExpr is an operand of a comparison operator.  aff2 is the
 92026  ** type affinity of the other operand.  This routine returns the
 92027  ** type affinity that should be used for the comparison operator.
 92028  */
 92029  SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
 92030    char aff1 = sqlite3ExprAffinity(pExpr);
 92031    if( aff1 && aff2 ){
 92032      /* Both sides of the comparison are columns. If one has numeric
 92033      ** affinity, use that. Otherwise use no affinity.
 92034      */
 92035      if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
 92036        return SQLITE_AFF_NUMERIC;
 92037      }else{
 92038        return SQLITE_AFF_BLOB;
 92039      }
 92040    }else if( !aff1 && !aff2 ){
 92041      /* Neither side of the comparison is a column.  Compare the
 92042      ** results directly.
 92043      */
 92044      return SQLITE_AFF_BLOB;
 92045    }else{
 92046      /* One side is a column, the other is not. Use the columns affinity. */
 92047      assert( aff1==0 || aff2==0 );
 92048      return (aff1 + aff2);
 92049    }
 92050  }
 92051  
 92052  /*
 92053  ** pExpr is a comparison operator.  Return the type affinity that should
 92054  ** be applied to both operands prior to doing the comparison.
 92055  */
 92056  static char comparisonAffinity(Expr *pExpr){
 92057    char aff;
 92058    assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
 92059            pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
 92060            pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
 92061    assert( pExpr->pLeft );
 92062    aff = sqlite3ExprAffinity(pExpr->pLeft);
 92063    if( pExpr->pRight ){
 92064      aff = sqlite3CompareAffinity(pExpr->pRight, aff);
 92065    }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
 92066      aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
 92067    }else if( aff==0 ){
 92068      aff = SQLITE_AFF_BLOB;
 92069    }
 92070    return aff;
 92071  }
 92072  
 92073  /*
 92074  ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
 92075  ** idx_affinity is the affinity of an indexed column. Return true
 92076  ** if the index with affinity idx_affinity may be used to implement
 92077  ** the comparison in pExpr.
 92078  */
 92079  SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
 92080    char aff = comparisonAffinity(pExpr);
 92081    switch( aff ){
 92082      case SQLITE_AFF_BLOB:
 92083        return 1;
 92084      case SQLITE_AFF_TEXT:
 92085        return idx_affinity==SQLITE_AFF_TEXT;
 92086      default:
 92087        return sqlite3IsNumericAffinity(idx_affinity);
 92088    }
 92089  }
 92090  
 92091  /*
 92092  ** Return the P5 value that should be used for a binary comparison
 92093  ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
 92094  */
 92095  static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
 92096    u8 aff = (char)sqlite3ExprAffinity(pExpr2);
 92097    aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
 92098    return aff;
 92099  }
 92100  
 92101  /*
 92102  ** Return a pointer to the collation sequence that should be used by
 92103  ** a binary comparison operator comparing pLeft and pRight.
 92104  **
 92105  ** If the left hand expression has a collating sequence type, then it is
 92106  ** used. Otherwise the collation sequence for the right hand expression
 92107  ** is used, or the default (BINARY) if neither expression has a collating
 92108  ** type.
 92109  **
 92110  ** Argument pRight (but not pLeft) may be a null pointer. In this case,
 92111  ** it is not considered.
 92112  */
 92113  SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
 92114    Parse *pParse, 
 92115    Expr *pLeft, 
 92116    Expr *pRight
 92117  ){
 92118    CollSeq *pColl;
 92119    assert( pLeft );
 92120    if( pLeft->flags & EP_Collate ){
 92121      pColl = sqlite3ExprCollSeq(pParse, pLeft);
 92122    }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
 92123      pColl = sqlite3ExprCollSeq(pParse, pRight);
 92124    }else{
 92125      pColl = sqlite3ExprCollSeq(pParse, pLeft);
 92126      if( !pColl ){
 92127        pColl = sqlite3ExprCollSeq(pParse, pRight);
 92128      }
 92129    }
 92130    return pColl;
 92131  }
 92132  
 92133  /*
 92134  ** Generate code for a comparison operator.
 92135  */
 92136  static int codeCompare(
 92137    Parse *pParse,    /* The parsing (and code generating) context */
 92138    Expr *pLeft,      /* The left operand */
 92139    Expr *pRight,     /* The right operand */
 92140    int opcode,       /* The comparison opcode */
 92141    int in1, int in2, /* Register holding operands */
 92142    int dest,         /* Jump here if true.  */
 92143    int jumpIfNull    /* If true, jump if either operand is NULL */
 92144  ){
 92145    int p5;
 92146    int addr;
 92147    CollSeq *p4;
 92148  
 92149    p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
 92150    p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
 92151    addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
 92152                             (void*)p4, P4_COLLSEQ);
 92153    sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
 92154    return addr;
 92155  }
 92156  
 92157  /*
 92158  ** Return true if expression pExpr is a vector, or false otherwise.
 92159  **
 92160  ** A vector is defined as any expression that results in two or more
 92161  ** columns of result.  Every TK_VECTOR node is an vector because the
 92162  ** parser will not generate a TK_VECTOR with fewer than two entries.
 92163  ** But a TK_SELECT might be either a vector or a scalar. It is only
 92164  ** considered a vector if it has two or more result columns.
 92165  */
 92166  SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){
 92167    return sqlite3ExprVectorSize(pExpr)>1;
 92168  }
 92169  
 92170  /*
 92171  ** If the expression passed as the only argument is of type TK_VECTOR 
 92172  ** return the number of expressions in the vector. Or, if the expression
 92173  ** is a sub-select, return the number of columns in the sub-select. For
 92174  ** any other type of expression, return 1.
 92175  */
 92176  SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){
 92177    u8 op = pExpr->op;
 92178    if( op==TK_REGISTER ) op = pExpr->op2;
 92179    if( op==TK_VECTOR ){
 92180      return pExpr->x.pList->nExpr;
 92181    }else if( op==TK_SELECT ){
 92182      return pExpr->x.pSelect->pEList->nExpr;
 92183    }else{
 92184      return 1;
 92185    }
 92186  }
 92187  
 92188  /*
 92189  ** Return a pointer to a subexpression of pVector that is the i-th
 92190  ** column of the vector (numbered starting with 0).  The caller must
 92191  ** ensure that i is within range.
 92192  **
 92193  ** If pVector is really a scalar (and "scalar" here includes subqueries
 92194  ** that return a single column!) then return pVector unmodified.
 92195  **
 92196  ** pVector retains ownership of the returned subexpression.
 92197  **
 92198  ** If the vector is a (SELECT ...) then the expression returned is
 92199  ** just the expression for the i-th term of the result set, and may
 92200  ** not be ready for evaluation because the table cursor has not yet
 92201  ** been positioned.
 92202  */
 92203  SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
 92204    assert( i<sqlite3ExprVectorSize(pVector) );
 92205    if( sqlite3ExprIsVector(pVector) ){
 92206      assert( pVector->op2==0 || pVector->op==TK_REGISTER );
 92207      if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
 92208        return pVector->x.pSelect->pEList->a[i].pExpr;
 92209      }else{
 92210        return pVector->x.pList->a[i].pExpr;
 92211      }
 92212    }
 92213    return pVector;
 92214  }
 92215  
 92216  /*
 92217  ** Compute and return a new Expr object which when passed to
 92218  ** sqlite3ExprCode() will generate all necessary code to compute
 92219  ** the iField-th column of the vector expression pVector.
 92220  **
 92221  ** It is ok for pVector to be a scalar (as long as iField==0).  
 92222  ** In that case, this routine works like sqlite3ExprDup().
 92223  **
 92224  ** The caller owns the returned Expr object and is responsible for
 92225  ** ensuring that the returned value eventually gets freed.
 92226  **
 92227  ** The caller retains ownership of pVector.  If pVector is a TK_SELECT,
 92228  ** then the returned object will reference pVector and so pVector must remain
 92229  ** valid for the life of the returned object.  If pVector is a TK_VECTOR
 92230  ** or a scalar expression, then it can be deleted as soon as this routine
 92231  ** returns.
 92232  **
 92233  ** A trick to cause a TK_SELECT pVector to be deleted together with
 92234  ** the returned Expr object is to attach the pVector to the pRight field
 92235  ** of the returned TK_SELECT_COLUMN Expr object.
 92236  */
 92237  SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
 92238    Parse *pParse,       /* Parsing context */
 92239    Expr *pVector,       /* The vector.  List of expressions or a sub-SELECT */
 92240    int iField           /* Which column of the vector to return */
 92241  ){
 92242    Expr *pRet;
 92243    if( pVector->op==TK_SELECT ){
 92244      assert( pVector->flags & EP_xIsSelect );
 92245      /* The TK_SELECT_COLUMN Expr node:
 92246      **
 92247      ** pLeft:           pVector containing TK_SELECT.  Not deleted.
 92248      ** pRight:          not used.  But recursively deleted.
 92249      ** iColumn:         Index of a column in pVector
 92250      ** iTable:          0 or the number of columns on the LHS of an assignment
 92251      ** pLeft->iTable:   First in an array of register holding result, or 0
 92252      **                  if the result is not yet computed.
 92253      **
 92254      ** sqlite3ExprDelete() specifically skips the recursive delete of
 92255      ** pLeft on TK_SELECT_COLUMN nodes.  But pRight is followed, so pVector
 92256      ** can be attached to pRight to cause this node to take ownership of
 92257      ** pVector.  Typically there will be multiple TK_SELECT_COLUMN nodes
 92258      ** with the same pLeft pointer to the pVector, but only one of them
 92259      ** will own the pVector.
 92260      */
 92261      pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
 92262      if( pRet ){
 92263        pRet->iColumn = iField;
 92264        pRet->pLeft = pVector;
 92265      }
 92266      assert( pRet==0 || pRet->iTable==0 );
 92267    }else{
 92268      if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
 92269      pRet = sqlite3ExprDup(pParse->db, pVector, 0);
 92270    }
 92271    return pRet;
 92272  }
 92273  
 92274  /*
 92275  ** If expression pExpr is of type TK_SELECT, generate code to evaluate
 92276  ** it. Return the register in which the result is stored (or, if the 
 92277  ** sub-select returns more than one column, the first in an array
 92278  ** of registers in which the result is stored).
 92279  **
 92280  ** If pExpr is not a TK_SELECT expression, return 0.
 92281  */
 92282  static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
 92283    int reg = 0;
 92284  #ifndef SQLITE_OMIT_SUBQUERY
 92285    if( pExpr->op==TK_SELECT ){
 92286      reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
 92287    }
 92288  #endif
 92289    return reg;
 92290  }
 92291  
 92292  /*
 92293  ** Argument pVector points to a vector expression - either a TK_VECTOR
 92294  ** or TK_SELECT that returns more than one column. This function returns
 92295  ** the register number of a register that contains the value of
 92296  ** element iField of the vector.
 92297  **
 92298  ** If pVector is a TK_SELECT expression, then code for it must have 
 92299  ** already been generated using the exprCodeSubselect() routine. In this
 92300  ** case parameter regSelect should be the first in an array of registers
 92301  ** containing the results of the sub-select. 
 92302  **
 92303  ** If pVector is of type TK_VECTOR, then code for the requested field
 92304  ** is generated. In this case (*pRegFree) may be set to the number of
 92305  ** a temporary register to be freed by the caller before returning.
 92306  **
 92307  ** Before returning, output parameter (*ppExpr) is set to point to the
 92308  ** Expr object corresponding to element iElem of the vector.
 92309  */
 92310  static int exprVectorRegister(
 92311    Parse *pParse,                  /* Parse context */
 92312    Expr *pVector,                  /* Vector to extract element from */
 92313    int iField,                     /* Field to extract from pVector */
 92314    int regSelect,                  /* First in array of registers */
 92315    Expr **ppExpr,                  /* OUT: Expression element */
 92316    int *pRegFree                   /* OUT: Temp register to free */
 92317  ){
 92318    u8 op = pVector->op;
 92319    assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
 92320    if( op==TK_REGISTER ){
 92321      *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
 92322      return pVector->iTable+iField;
 92323    }
 92324    if( op==TK_SELECT ){
 92325      *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
 92326       return regSelect+iField;
 92327    }
 92328    *ppExpr = pVector->x.pList->a[iField].pExpr;
 92329    return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
 92330  }
 92331  
 92332  /*
 92333  ** Expression pExpr is a comparison between two vector values. Compute
 92334  ** the result of the comparison (1, 0, or NULL) and write that
 92335  ** result into register dest.
 92336  **
 92337  ** The caller must satisfy the following preconditions:
 92338  **
 92339  **    if pExpr->op==TK_IS:      op==TK_EQ and p5==SQLITE_NULLEQ
 92340  **    if pExpr->op==TK_ISNOT:   op==TK_NE and p5==SQLITE_NULLEQ
 92341  **    otherwise:                op==pExpr->op and p5==0
 92342  */
 92343  static void codeVectorCompare(
 92344    Parse *pParse,        /* Code generator context */
 92345    Expr *pExpr,          /* The comparison operation */
 92346    int dest,             /* Write results into this register */
 92347    u8 op,                /* Comparison operator */
 92348    u8 p5                 /* SQLITE_NULLEQ or zero */
 92349  ){
 92350    Vdbe *v = pParse->pVdbe;
 92351    Expr *pLeft = pExpr->pLeft;
 92352    Expr *pRight = pExpr->pRight;
 92353    int nLeft = sqlite3ExprVectorSize(pLeft);
 92354    int i;
 92355    int regLeft = 0;
 92356    int regRight = 0;
 92357    u8 opx = op;
 92358    int addrDone = sqlite3VdbeMakeLabel(v);
 92359  
 92360    if( nLeft!=sqlite3ExprVectorSize(pRight) ){
 92361      sqlite3ErrorMsg(pParse, "row value misused");
 92362      return;
 92363    }
 92364    assert( pExpr->op==TK_EQ || pExpr->op==TK_NE 
 92365         || pExpr->op==TK_IS || pExpr->op==TK_ISNOT 
 92366         || pExpr->op==TK_LT || pExpr->op==TK_GT 
 92367         || pExpr->op==TK_LE || pExpr->op==TK_GE 
 92368    );
 92369    assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
 92370              || (pExpr->op==TK_ISNOT && op==TK_NE) );
 92371    assert( p5==0 || pExpr->op!=op );
 92372    assert( p5==SQLITE_NULLEQ || pExpr->op==op );
 92373  
 92374    p5 |= SQLITE_STOREP2;
 92375    if( opx==TK_LE ) opx = TK_LT;
 92376    if( opx==TK_GE ) opx = TK_GT;
 92377  
 92378    regLeft = exprCodeSubselect(pParse, pLeft);
 92379    regRight = exprCodeSubselect(pParse, pRight);
 92380  
 92381    for(i=0; 1 /*Loop exits by "break"*/; i++){
 92382      int regFree1 = 0, regFree2 = 0;
 92383      Expr *pL, *pR; 
 92384      int r1, r2;
 92385      assert( i>=0 && i<nLeft );
 92386      if( i>0 ) sqlite3ExprCachePush(pParse);
 92387      r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
 92388      r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
 92389      codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
 92390      testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
 92391      testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
 92392      testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
 92393      testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
 92394      testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
 92395      testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
 92396      sqlite3ReleaseTempReg(pParse, regFree1);
 92397      sqlite3ReleaseTempReg(pParse, regFree2);
 92398      if( i>0 ) sqlite3ExprCachePop(pParse);
 92399      if( i==nLeft-1 ){
 92400        break;
 92401      }
 92402      if( opx==TK_EQ ){
 92403        sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
 92404        p5 |= SQLITE_KEEPNULL;
 92405      }else if( opx==TK_NE ){
 92406        sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
 92407        p5 |= SQLITE_KEEPNULL;
 92408      }else{
 92409        assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
 92410        sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
 92411        VdbeCoverageIf(v, op==TK_LT);
 92412        VdbeCoverageIf(v, op==TK_GT);
 92413        VdbeCoverageIf(v, op==TK_LE);
 92414        VdbeCoverageIf(v, op==TK_GE);
 92415        if( i==nLeft-2 ) opx = op;
 92416      }
 92417    }
 92418    sqlite3VdbeResolveLabel(v, addrDone);
 92419  }
 92420  
 92421  #if SQLITE_MAX_EXPR_DEPTH>0
 92422  /*
 92423  ** Check that argument nHeight is less than or equal to the maximum
 92424  ** expression depth allowed. If it is not, leave an error message in
 92425  ** pParse.
 92426  */
 92427  SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
 92428    int rc = SQLITE_OK;
 92429    int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
 92430    if( nHeight>mxHeight ){
 92431      sqlite3ErrorMsg(pParse, 
 92432         "Expression tree is too large (maximum depth %d)", mxHeight
 92433      );
 92434      rc = SQLITE_ERROR;
 92435    }
 92436    return rc;
 92437  }
 92438  
 92439  /* The following three functions, heightOfExpr(), heightOfExprList()
 92440  ** and heightOfSelect(), are used to determine the maximum height
 92441  ** of any expression tree referenced by the structure passed as the
 92442  ** first argument.
 92443  **
 92444  ** If this maximum height is greater than the current value pointed
 92445  ** to by pnHeight, the second parameter, then set *pnHeight to that
 92446  ** value.
 92447  */
 92448  static void heightOfExpr(Expr *p, int *pnHeight){
 92449    if( p ){
 92450      if( p->nHeight>*pnHeight ){
 92451        *pnHeight = p->nHeight;
 92452      }
 92453    }
 92454  }
 92455  static void heightOfExprList(ExprList *p, int *pnHeight){
 92456    if( p ){
 92457      int i;
 92458      for(i=0; i<p->nExpr; i++){
 92459        heightOfExpr(p->a[i].pExpr, pnHeight);
 92460      }
 92461    }
 92462  }
 92463  static void heightOfSelect(Select *p, int *pnHeight){
 92464    if( p ){
 92465      heightOfExpr(p->pWhere, pnHeight);
 92466      heightOfExpr(p->pHaving, pnHeight);
 92467      heightOfExpr(p->pLimit, pnHeight);
 92468      heightOfExpr(p->pOffset, pnHeight);
 92469      heightOfExprList(p->pEList, pnHeight);
 92470      heightOfExprList(p->pGroupBy, pnHeight);
 92471      heightOfExprList(p->pOrderBy, pnHeight);
 92472      heightOfSelect(p->pPrior, pnHeight);
 92473    }
 92474  }
 92475  
 92476  /*
 92477  ** Set the Expr.nHeight variable in the structure passed as an 
 92478  ** argument. An expression with no children, Expr.pList or 
 92479  ** Expr.pSelect member has a height of 1. Any other expression
 92480  ** has a height equal to the maximum height of any other 
 92481  ** referenced Expr plus one.
 92482  **
 92483  ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
 92484  ** if appropriate.
 92485  */
 92486  static void exprSetHeight(Expr *p){
 92487    int nHeight = 0;
 92488    heightOfExpr(p->pLeft, &nHeight);
 92489    heightOfExpr(p->pRight, &nHeight);
 92490    if( ExprHasProperty(p, EP_xIsSelect) ){
 92491      heightOfSelect(p->x.pSelect, &nHeight);
 92492    }else if( p->x.pList ){
 92493      heightOfExprList(p->x.pList, &nHeight);
 92494      p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
 92495    }
 92496    p->nHeight = nHeight + 1;
 92497  }
 92498  
 92499  /*
 92500  ** Set the Expr.nHeight variable using the exprSetHeight() function. If
 92501  ** the height is greater than the maximum allowed expression depth,
 92502  ** leave an error in pParse.
 92503  **
 92504  ** Also propagate all EP_Propagate flags from the Expr.x.pList into
 92505  ** Expr.flags. 
 92506  */
 92507  SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
 92508    if( pParse->nErr ) return;
 92509    exprSetHeight(p);
 92510    sqlite3ExprCheckHeight(pParse, p->nHeight);
 92511  }
 92512  
 92513  /*
 92514  ** Return the maximum height of any expression tree referenced
 92515  ** by the select statement passed as an argument.
 92516  */
 92517  SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
 92518    int nHeight = 0;
 92519    heightOfSelect(p, &nHeight);
 92520    return nHeight;
 92521  }
 92522  #else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
 92523  /*
 92524  ** Propagate all EP_Propagate flags from the Expr.x.pList into
 92525  ** Expr.flags. 
 92526  */
 92527  SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
 92528    if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
 92529      p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
 92530    }
 92531  }
 92532  #define exprSetHeight(y)
 92533  #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
 92534  
 92535  /*
 92536  ** This routine is the core allocator for Expr nodes.
 92537  **
 92538  ** Construct a new expression node and return a pointer to it.  Memory
 92539  ** for this node and for the pToken argument is a single allocation
 92540  ** obtained from sqlite3DbMalloc().  The calling function
 92541  ** is responsible for making sure the node eventually gets freed.
 92542  **
 92543  ** If dequote is true, then the token (if it exists) is dequoted.
 92544  ** If dequote is false, no dequoting is performed.  The deQuote
 92545  ** parameter is ignored if pToken is NULL or if the token does not
 92546  ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
 92547  ** then the EP_DblQuoted flag is set on the expression node.
 92548  **
 92549  ** Special case:  If op==TK_INTEGER and pToken points to a string that
 92550  ** can be translated into a 32-bit integer, then the token is not
 92551  ** stored in u.zToken.  Instead, the integer values is written
 92552  ** into u.iValue and the EP_IntValue flag is set.  No extra storage
 92553  ** is allocated to hold the integer text and the dequote flag is ignored.
 92554  */
 92555  SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
 92556    sqlite3 *db,            /* Handle for sqlite3DbMallocRawNN() */
 92557    int op,                 /* Expression opcode */
 92558    const Token *pToken,    /* Token argument.  Might be NULL */
 92559    int dequote             /* True to dequote */
 92560  ){
 92561    Expr *pNew;
 92562    int nExtra = 0;
 92563    int iValue = 0;
 92564  
 92565    assert( db!=0 );
 92566    if( pToken ){
 92567      if( op!=TK_INTEGER || pToken->z==0
 92568            || sqlite3GetInt32(pToken->z, &iValue)==0 ){
 92569        nExtra = pToken->n+1;
 92570        assert( iValue>=0 );
 92571      }
 92572    }
 92573    pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
 92574    if( pNew ){
 92575      memset(pNew, 0, sizeof(Expr));
 92576      pNew->op = (u8)op;
 92577      pNew->iAgg = -1;
 92578      if( pToken ){
 92579        if( nExtra==0 ){
 92580          pNew->flags |= EP_IntValue|EP_Leaf;
 92581          pNew->u.iValue = iValue;
 92582        }else{
 92583          pNew->u.zToken = (char*)&pNew[1];
 92584          assert( pToken->z!=0 || pToken->n==0 );
 92585          if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
 92586          pNew->u.zToken[pToken->n] = 0;
 92587          if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
 92588            if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
 92589            sqlite3Dequote(pNew->u.zToken);
 92590          }
 92591        }
 92592      }
 92593  #if SQLITE_MAX_EXPR_DEPTH>0
 92594      pNew->nHeight = 1;
 92595  #endif  
 92596    }
 92597    return pNew;
 92598  }
 92599  
 92600  /*
 92601  ** Allocate a new expression node from a zero-terminated token that has
 92602  ** already been dequoted.
 92603  */
 92604  SQLITE_PRIVATE Expr *sqlite3Expr(
 92605    sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
 92606    int op,                 /* Expression opcode */
 92607    const char *zToken      /* Token argument.  Might be NULL */
 92608  ){
 92609    Token x;
 92610    x.z = zToken;
 92611    x.n = sqlite3Strlen30(zToken);
 92612    return sqlite3ExprAlloc(db, op, &x, 0);
 92613  }
 92614  
 92615  /*
 92616  ** Attach subtrees pLeft and pRight to the Expr node pRoot.
 92617  **
 92618  ** If pRoot==NULL that means that a memory allocation error has occurred.
 92619  ** In that case, delete the subtrees pLeft and pRight.
 92620  */
 92621  SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
 92622    sqlite3 *db,
 92623    Expr *pRoot,
 92624    Expr *pLeft,
 92625    Expr *pRight
 92626  ){
 92627    if( pRoot==0 ){
 92628      assert( db->mallocFailed );
 92629      sqlite3ExprDelete(db, pLeft);
 92630      sqlite3ExprDelete(db, pRight);
 92631    }else{
 92632      if( pRight ){
 92633        pRoot->pRight = pRight;
 92634        pRoot->flags |= EP_Propagate & pRight->flags;
 92635      }
 92636      if( pLeft ){
 92637        pRoot->pLeft = pLeft;
 92638        pRoot->flags |= EP_Propagate & pLeft->flags;
 92639      }
 92640      exprSetHeight(pRoot);
 92641    }
 92642  }
 92643  
 92644  /*
 92645  ** Allocate an Expr node which joins as many as two subtrees.
 92646  **
 92647  ** One or both of the subtrees can be NULL.  Return a pointer to the new
 92648  ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
 92649  ** free the subtrees and return NULL.
 92650  */
 92651  SQLITE_PRIVATE Expr *sqlite3PExpr(
 92652    Parse *pParse,          /* Parsing context */
 92653    int op,                 /* Expression opcode */
 92654    Expr *pLeft,            /* Left operand */
 92655    Expr *pRight            /* Right operand */
 92656  ){
 92657    Expr *p;
 92658    if( op==TK_AND && pParse->nErr==0 ){
 92659      /* Take advantage of short-circuit false optimization for AND */
 92660      p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
 92661    }else{
 92662      p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
 92663      if( p ){
 92664        memset(p, 0, sizeof(Expr));
 92665        p->op = op & TKFLG_MASK;
 92666        p->iAgg = -1;
 92667      }
 92668      sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
 92669    }
 92670    if( p ) {
 92671      sqlite3ExprCheckHeight(pParse, p->nHeight);
 92672    }
 92673    return p;
 92674  }
 92675  
 92676  /*
 92677  ** Add pSelect to the Expr.x.pSelect field.  Or, if pExpr is NULL (due
 92678  ** do a memory allocation failure) then delete the pSelect object.
 92679  */
 92680  SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
 92681    if( pExpr ){
 92682      pExpr->x.pSelect = pSelect;
 92683      ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
 92684      sqlite3ExprSetHeightAndFlags(pParse, pExpr);
 92685    }else{
 92686      assert( pParse->db->mallocFailed );
 92687      sqlite3SelectDelete(pParse->db, pSelect);
 92688    }
 92689  }
 92690  
 92691  
 92692  /*
 92693  ** If the expression is always either TRUE or FALSE (respectively),
 92694  ** then return 1.  If one cannot determine the truth value of the
 92695  ** expression at compile-time return 0.
 92696  **
 92697  ** This is an optimization.  If is OK to return 0 here even if
 92698  ** the expression really is always false or false (a false negative).
 92699  ** But it is a bug to return 1 if the expression might have different
 92700  ** boolean values in different circumstances (a false positive.)
 92701  **
 92702  ** Note that if the expression is part of conditional for a
 92703  ** LEFT JOIN, then we cannot determine at compile-time whether or not
 92704  ** is it true or false, so always return 0.
 92705  */
 92706  static int exprAlwaysTrue(Expr *p){
 92707    int v = 0;
 92708    if( ExprHasProperty(p, EP_FromJoin) ) return 0;
 92709    if( !sqlite3ExprIsInteger(p, &v) ) return 0;
 92710    return v!=0;
 92711  }
 92712  static int exprAlwaysFalse(Expr *p){
 92713    int v = 0;
 92714    if( ExprHasProperty(p, EP_FromJoin) ) return 0;
 92715    if( !sqlite3ExprIsInteger(p, &v) ) return 0;
 92716    return v==0;
 92717  }
 92718  
 92719  /*
 92720  ** Join two expressions using an AND operator.  If either expression is
 92721  ** NULL, then just return the other expression.
 92722  **
 92723  ** If one side or the other of the AND is known to be false, then instead
 92724  ** of returning an AND expression, just return a constant expression with
 92725  ** a value of false.
 92726  */
 92727  SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
 92728    if( pLeft==0 ){
 92729      return pRight;
 92730    }else if( pRight==0 ){
 92731      return pLeft;
 92732    }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
 92733      sqlite3ExprDelete(db, pLeft);
 92734      sqlite3ExprDelete(db, pRight);
 92735      return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
 92736    }else{
 92737      Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
 92738      sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
 92739      return pNew;
 92740    }
 92741  }
 92742  
 92743  /*
 92744  ** Construct a new expression node for a function with multiple
 92745  ** arguments.
 92746  */
 92747  SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
 92748    Expr *pNew;
 92749    sqlite3 *db = pParse->db;
 92750    assert( pToken );
 92751    pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
 92752    if( pNew==0 ){
 92753      sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
 92754      return 0;
 92755    }
 92756    pNew->x.pList = pList;
 92757    assert( !ExprHasProperty(pNew, EP_xIsSelect) );
 92758    sqlite3ExprSetHeightAndFlags(pParse, pNew);
 92759    return pNew;
 92760  }
 92761  
 92762  /*
 92763  ** Assign a variable number to an expression that encodes a wildcard
 92764  ** in the original SQL statement.  
 92765  **
 92766  ** Wildcards consisting of a single "?" are assigned the next sequential
 92767  ** variable number.
 92768  **
 92769  ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
 92770  ** sure "nnn" is not too big to avoid a denial of service attack when
 92771  ** the SQL statement comes from an external source.
 92772  **
 92773  ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
 92774  ** as the previous instance of the same wildcard.  Or if this is the first
 92775  ** instance of the wildcard, the next sequential variable number is
 92776  ** assigned.
 92777  */
 92778  SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
 92779    sqlite3 *db = pParse->db;
 92780    const char *z;
 92781    ynVar x;
 92782  
 92783    if( pExpr==0 ) return;
 92784    assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
 92785    z = pExpr->u.zToken;
 92786    assert( z!=0 );
 92787    assert( z[0]!=0 );
 92788    assert( n==(u32)sqlite3Strlen30(z) );
 92789    if( z[1]==0 ){
 92790      /* Wildcard of the form "?".  Assign the next variable number */
 92791      assert( z[0]=='?' );
 92792      x = (ynVar)(++pParse->nVar);
 92793    }else{
 92794      int doAdd = 0;
 92795      if( z[0]=='?' ){
 92796        /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
 92797        ** use it as the variable number */
 92798        i64 i;
 92799        int bOk;
 92800        if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
 92801          i = z[1]-'0';  /* The common case of ?N for a single digit N */
 92802          bOk = 1;
 92803        }else{
 92804          bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
 92805        }
 92806        testcase( i==0 );
 92807        testcase( i==1 );
 92808        testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
 92809        testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
 92810        if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
 92811          sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
 92812              db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
 92813          return;
 92814        }
 92815        x = (ynVar)i;
 92816        if( x>pParse->nVar ){
 92817          pParse->nVar = (int)x;
 92818          doAdd = 1;
 92819        }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
 92820          doAdd = 1;
 92821        }
 92822      }else{
 92823        /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
 92824        ** number as the prior appearance of the same name, or if the name
 92825        ** has never appeared before, reuse the same variable number
 92826        */
 92827        x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
 92828        if( x==0 ){
 92829          x = (ynVar)(++pParse->nVar);
 92830          doAdd = 1;
 92831        }
 92832      }
 92833      if( doAdd ){
 92834        pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
 92835      }
 92836    }
 92837    pExpr->iColumn = x;
 92838    if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
 92839      sqlite3ErrorMsg(pParse, "too many SQL variables");
 92840    }
 92841  }
 92842  
 92843  /*
 92844  ** Recursively delete an expression tree.
 92845  */
 92846  static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
 92847    assert( p!=0 );
 92848    /* Sanity check: Assert that the IntValue is non-negative if it exists */
 92849    assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
 92850  #ifdef SQLITE_DEBUG
 92851    if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
 92852      assert( p->pLeft==0 );
 92853      assert( p->pRight==0 );
 92854      assert( p->x.pSelect==0 );
 92855    }
 92856  #endif
 92857    if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
 92858      /* The Expr.x union is never used at the same time as Expr.pRight */
 92859      assert( p->x.pList==0 || p->pRight==0 );
 92860      if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
 92861      if( p->pRight ){
 92862        sqlite3ExprDeleteNN(db, p->pRight);
 92863      }else if( ExprHasProperty(p, EP_xIsSelect) ){
 92864        sqlite3SelectDelete(db, p->x.pSelect);
 92865      }else{
 92866        sqlite3ExprListDelete(db, p->x.pList);
 92867      }
 92868    }
 92869    if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
 92870    if( !ExprHasProperty(p, EP_Static) ){
 92871      sqlite3DbFreeNN(db, p);
 92872    }
 92873  }
 92874  SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
 92875    if( p ) sqlite3ExprDeleteNN(db, p);
 92876  }
 92877  
 92878  /*
 92879  ** Return the number of bytes allocated for the expression structure 
 92880  ** passed as the first argument. This is always one of EXPR_FULLSIZE,
 92881  ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
 92882  */
 92883  static int exprStructSize(Expr *p){
 92884    if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
 92885    if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
 92886    return EXPR_FULLSIZE;
 92887  }
 92888  
 92889  /*
 92890  ** The dupedExpr*Size() routines each return the number of bytes required
 92891  ** to store a copy of an expression or expression tree.  They differ in
 92892  ** how much of the tree is measured.
 92893  **
 92894  **     dupedExprStructSize()     Size of only the Expr structure 
 92895  **     dupedExprNodeSize()       Size of Expr + space for token
 92896  **     dupedExprSize()           Expr + token + subtree components
 92897  **
 92898  ***************************************************************************
 92899  **
 92900  ** The dupedExprStructSize() function returns two values OR-ed together:  
 92901  ** (1) the space required for a copy of the Expr structure only and 
 92902  ** (2) the EP_xxx flags that indicate what the structure size should be.
 92903  ** The return values is always one of:
 92904  **
 92905  **      EXPR_FULLSIZE
 92906  **      EXPR_REDUCEDSIZE   | EP_Reduced
 92907  **      EXPR_TOKENONLYSIZE | EP_TokenOnly
 92908  **
 92909  ** The size of the structure can be found by masking the return value
 92910  ** of this routine with 0xfff.  The flags can be found by masking the
 92911  ** return value with EP_Reduced|EP_TokenOnly.
 92912  **
 92913  ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
 92914  ** (unreduced) Expr objects as they or originally constructed by the parser.
 92915  ** During expression analysis, extra information is computed and moved into
 92916  ** later parts of teh Expr object and that extra information might get chopped
 92917  ** off if the expression is reduced.  Note also that it does not work to
 92918  ** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
 92919  ** to reduce a pristine expression tree from the parser.  The implementation
 92920  ** of dupedExprStructSize() contain multiple assert() statements that attempt
 92921  ** to enforce this constraint.
 92922  */
 92923  static int dupedExprStructSize(Expr *p, int flags){
 92924    int nSize;
 92925    assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
 92926    assert( EXPR_FULLSIZE<=0xfff );
 92927    assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
 92928    if( 0==flags || p->op==TK_SELECT_COLUMN ){
 92929      nSize = EXPR_FULLSIZE;
 92930    }else{
 92931      assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
 92932      assert( !ExprHasProperty(p, EP_FromJoin) ); 
 92933      assert( !ExprHasProperty(p, EP_MemToken) );
 92934      assert( !ExprHasProperty(p, EP_NoReduce) );
 92935      if( p->pLeft || p->x.pList ){
 92936        nSize = EXPR_REDUCEDSIZE | EP_Reduced;
 92937      }else{
 92938        assert( p->pRight==0 );
 92939        nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
 92940      }
 92941    }
 92942    return nSize;
 92943  }
 92944  
 92945  /*
 92946  ** This function returns the space in bytes required to store the copy 
 92947  ** of the Expr structure and a copy of the Expr.u.zToken string (if that
 92948  ** string is defined.)
 92949  */
 92950  static int dupedExprNodeSize(Expr *p, int flags){
 92951    int nByte = dupedExprStructSize(p, flags) & 0xfff;
 92952    if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
 92953      nByte += sqlite3Strlen30(p->u.zToken)+1;
 92954    }
 92955    return ROUND8(nByte);
 92956  }
 92957  
 92958  /*
 92959  ** Return the number of bytes required to create a duplicate of the 
 92960  ** expression passed as the first argument. The second argument is a
 92961  ** mask containing EXPRDUP_XXX flags.
 92962  **
 92963  ** The value returned includes space to create a copy of the Expr struct
 92964  ** itself and the buffer referred to by Expr.u.zToken, if any.
 92965  **
 92966  ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
 92967  ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
 92968  ** and Expr.pRight variables (but not for any structures pointed to or 
 92969  ** descended from the Expr.x.pList or Expr.x.pSelect variables).
 92970  */
 92971  static int dupedExprSize(Expr *p, int flags){
 92972    int nByte = 0;
 92973    if( p ){
 92974      nByte = dupedExprNodeSize(p, flags);
 92975      if( flags&EXPRDUP_REDUCE ){
 92976        nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
 92977      }
 92978    }
 92979    return nByte;
 92980  }
 92981  
 92982  /*
 92983  ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
 92984  ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
 92985  ** to store the copy of expression p, the copies of p->u.zToken
 92986  ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
 92987  ** if any. Before returning, *pzBuffer is set to the first byte past the
 92988  ** portion of the buffer copied into by this function.
 92989  */
 92990  static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
 92991    Expr *pNew;           /* Value to return */
 92992    u8 *zAlloc;           /* Memory space from which to build Expr object */
 92993    u32 staticFlag;       /* EP_Static if space not obtained from malloc */
 92994  
 92995    assert( db!=0 );
 92996    assert( p );
 92997    assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
 92998    assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
 92999  
 93000    /* Figure out where to write the new Expr structure. */
 93001    if( pzBuffer ){
 93002      zAlloc = *pzBuffer;
 93003      staticFlag = EP_Static;
 93004    }else{
 93005      zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
 93006      staticFlag = 0;
 93007    }
 93008    pNew = (Expr *)zAlloc;
 93009  
 93010    if( pNew ){
 93011      /* Set nNewSize to the size allocated for the structure pointed to
 93012      ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
 93013      ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
 93014      ** by the copy of the p->u.zToken string (if any).
 93015      */
 93016      const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
 93017      const int nNewSize = nStructSize & 0xfff;
 93018      int nToken;
 93019      if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
 93020        nToken = sqlite3Strlen30(p->u.zToken) + 1;
 93021      }else{
 93022        nToken = 0;
 93023      }
 93024      if( dupFlags ){
 93025        assert( ExprHasProperty(p, EP_Reduced)==0 );
 93026        memcpy(zAlloc, p, nNewSize);
 93027      }else{
 93028        u32 nSize = (u32)exprStructSize(p);
 93029        memcpy(zAlloc, p, nSize);
 93030        if( nSize<EXPR_FULLSIZE ){ 
 93031          memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
 93032        }
 93033      }
 93034  
 93035      /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
 93036      pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
 93037      pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
 93038      pNew->flags |= staticFlag;
 93039  
 93040      /* Copy the p->u.zToken string, if any. */
 93041      if( nToken ){
 93042        char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
 93043        memcpy(zToken, p->u.zToken, nToken);
 93044      }
 93045  
 93046      if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
 93047        /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
 93048        if( ExprHasProperty(p, EP_xIsSelect) ){
 93049          pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
 93050        }else{
 93051          pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
 93052        }
 93053      }
 93054  
 93055      /* Fill in pNew->pLeft and pNew->pRight. */
 93056      if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
 93057        zAlloc += dupedExprNodeSize(p, dupFlags);
 93058        if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
 93059          pNew->pLeft = p->pLeft ?
 93060                        exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
 93061          pNew->pRight = p->pRight ?
 93062                         exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
 93063        }
 93064        if( pzBuffer ){
 93065          *pzBuffer = zAlloc;
 93066        }
 93067      }else{
 93068        if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
 93069          if( pNew->op==TK_SELECT_COLUMN ){
 93070            pNew->pLeft = p->pLeft;
 93071            assert( p->iColumn==0 || p->pRight==0 );
 93072            assert( p->pRight==0  || p->pRight==p->pLeft );
 93073          }else{
 93074            pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
 93075          }
 93076          pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
 93077        }
 93078      }
 93079    }
 93080    return pNew;
 93081  }
 93082  
 93083  /*
 93084  ** Create and return a deep copy of the object passed as the second 
 93085  ** argument. If an OOM condition is encountered, NULL is returned
 93086  ** and the db->mallocFailed flag set.
 93087  */
 93088  #ifndef SQLITE_OMIT_CTE
 93089  static With *withDup(sqlite3 *db, With *p){
 93090    With *pRet = 0;
 93091    if( p ){
 93092      int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
 93093      pRet = sqlite3DbMallocZero(db, nByte);
 93094      if( pRet ){
 93095        int i;
 93096        pRet->nCte = p->nCte;
 93097        for(i=0; i<p->nCte; i++){
 93098          pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
 93099          pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
 93100          pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
 93101        }
 93102      }
 93103    }
 93104    return pRet;
 93105  }
 93106  #else
 93107  # define withDup(x,y) 0
 93108  #endif
 93109  
 93110  /*
 93111  ** The following group of routines make deep copies of expressions,
 93112  ** expression lists, ID lists, and select statements.  The copies can
 93113  ** be deleted (by being passed to their respective ...Delete() routines)
 93114  ** without effecting the originals.
 93115  **
 93116  ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
 93117  ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
 93118  ** by subsequent calls to sqlite*ListAppend() routines.
 93119  **
 93120  ** Any tables that the SrcList might point to are not duplicated.
 93121  **
 93122  ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
 93123  ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
 93124  ** truncated version of the usual Expr structure that will be stored as
 93125  ** part of the in-memory representation of the database schema.
 93126  */
 93127  SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
 93128    assert( flags==0 || flags==EXPRDUP_REDUCE );
 93129    return p ? exprDup(db, p, flags, 0) : 0;
 93130  }
 93131  SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
 93132    ExprList *pNew;
 93133    struct ExprList_item *pItem, *pOldItem;
 93134    int i;
 93135    Expr *pPriorSelectCol = 0;
 93136    assert( db!=0 );
 93137    if( p==0 ) return 0;
 93138    pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
 93139    if( pNew==0 ) return 0;
 93140    pNew->nExpr = p->nExpr;
 93141    pItem = pNew->a;
 93142    pOldItem = p->a;
 93143    for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
 93144      Expr *pOldExpr = pOldItem->pExpr;
 93145      Expr *pNewExpr;
 93146      pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
 93147      if( pOldExpr 
 93148       && pOldExpr->op==TK_SELECT_COLUMN
 93149       && (pNewExpr = pItem->pExpr)!=0 
 93150      ){
 93151        assert( pNewExpr->iColumn==0 || i>0 );
 93152        if( pNewExpr->iColumn==0 ){
 93153          assert( pOldExpr->pLeft==pOldExpr->pRight );
 93154          pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
 93155        }else{
 93156          assert( i>0 );
 93157          assert( pItem[-1].pExpr!=0 );
 93158          assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
 93159          assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
 93160          pNewExpr->pLeft = pPriorSelectCol;
 93161        }
 93162      }
 93163      pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
 93164      pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
 93165      pItem->sortOrder = pOldItem->sortOrder;
 93166      pItem->done = 0;
 93167      pItem->bSpanIsTab = pOldItem->bSpanIsTab;
 93168      pItem->u = pOldItem->u;
 93169    }
 93170    return pNew;
 93171  }
 93172  
 93173  /*
 93174  ** If cursors, triggers, views and subqueries are all omitted from
 93175  ** the build, then none of the following routines, except for 
 93176  ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
 93177  ** called with a NULL argument.
 93178  */
 93179  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
 93180   || !defined(SQLITE_OMIT_SUBQUERY)
 93181  SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
 93182    SrcList *pNew;
 93183    int i;
 93184    int nByte;
 93185    assert( db!=0 );
 93186    if( p==0 ) return 0;
 93187    nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
 93188    pNew = sqlite3DbMallocRawNN(db, nByte );
 93189    if( pNew==0 ) return 0;
 93190    pNew->nSrc = pNew->nAlloc = p->nSrc;
 93191    for(i=0; i<p->nSrc; i++){
 93192      struct SrcList_item *pNewItem = &pNew->a[i];
 93193      struct SrcList_item *pOldItem = &p->a[i];
 93194      Table *pTab;
 93195      pNewItem->pSchema = pOldItem->pSchema;
 93196      pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
 93197      pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
 93198      pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
 93199      pNewItem->fg = pOldItem->fg;
 93200      pNewItem->iCursor = pOldItem->iCursor;
 93201      pNewItem->addrFillSub = pOldItem->addrFillSub;
 93202      pNewItem->regReturn = pOldItem->regReturn;
 93203      if( pNewItem->fg.isIndexedBy ){
 93204        pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
 93205      }
 93206      pNewItem->pIBIndex = pOldItem->pIBIndex;
 93207      if( pNewItem->fg.isTabFunc ){
 93208        pNewItem->u1.pFuncArg = 
 93209            sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
 93210      }
 93211      pTab = pNewItem->pTab = pOldItem->pTab;
 93212      if( pTab ){
 93213        pTab->nTabRef++;
 93214      }
 93215      pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
 93216      pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
 93217      pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
 93218      pNewItem->colUsed = pOldItem->colUsed;
 93219    }
 93220    return pNew;
 93221  }
 93222  SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
 93223    IdList *pNew;
 93224    int i;
 93225    assert( db!=0 );
 93226    if( p==0 ) return 0;
 93227    pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
 93228    if( pNew==0 ) return 0;
 93229    pNew->nId = p->nId;
 93230    pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
 93231    if( pNew->a==0 ){
 93232      sqlite3DbFreeNN(db, pNew);
 93233      return 0;
 93234    }
 93235    /* Note that because the size of the allocation for p->a[] is not
 93236    ** necessarily a power of two, sqlite3IdListAppend() may not be called
 93237    ** on the duplicate created by this function. */
 93238    for(i=0; i<p->nId; i++){
 93239      struct IdList_item *pNewItem = &pNew->a[i];
 93240      struct IdList_item *pOldItem = &p->a[i];
 93241      pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
 93242      pNewItem->idx = pOldItem->idx;
 93243    }
 93244    return pNew;
 93245  }
 93246  SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
 93247    Select *pRet = 0;
 93248    Select *pNext = 0;
 93249    Select **pp = &pRet;
 93250    Select *p;
 93251  
 93252    assert( db!=0 );
 93253    for(p=pDup; p; p=p->pPrior){
 93254      Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
 93255      if( pNew==0 ) break;
 93256      pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
 93257      pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
 93258      pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
 93259      pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
 93260      pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
 93261      pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
 93262      pNew->op = p->op;
 93263      pNew->pNext = pNext;
 93264      pNew->pPrior = 0;
 93265      pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
 93266      pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
 93267      pNew->iLimit = 0;
 93268      pNew->iOffset = 0;
 93269      pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
 93270      pNew->addrOpenEphm[0] = -1;
 93271      pNew->addrOpenEphm[1] = -1;
 93272      pNew->nSelectRow = p->nSelectRow;
 93273      pNew->pWith = withDup(db, p->pWith);
 93274      sqlite3SelectSetName(pNew, p->zSelName);
 93275      *pp = pNew;
 93276      pp = &pNew->pPrior;
 93277      pNext = pNew;
 93278    }
 93279  
 93280    return pRet;
 93281  }
 93282  #else
 93283  SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
 93284    assert( p==0 );
 93285    return 0;
 93286  }
 93287  #endif
 93288  
 93289  
 93290  /*
 93291  ** Add a new element to the end of an expression list.  If pList is
 93292  ** initially NULL, then create a new expression list.
 93293  **
 93294  ** The pList argument must be either NULL or a pointer to an ExprList
 93295  ** obtained from a prior call to sqlite3ExprListAppend().  This routine
 93296  ** may not be used with an ExprList obtained from sqlite3ExprListDup().
 93297  ** Reason:  This routine assumes that the number of slots in pList->a[]
 93298  ** is a power of two.  That is true for sqlite3ExprListAppend() returns
 93299  ** but is not necessarily true from the return value of sqlite3ExprListDup().
 93300  **
 93301  ** If a memory allocation error occurs, the entire list is freed and
 93302  ** NULL is returned.  If non-NULL is returned, then it is guaranteed
 93303  ** that the new entry was successfully appended.
 93304  */
 93305  SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
 93306    Parse *pParse,          /* Parsing context */
 93307    ExprList *pList,        /* List to which to append. Might be NULL */
 93308    Expr *pExpr             /* Expression to be appended. Might be NULL */
 93309  ){
 93310    struct ExprList_item *pItem;
 93311    sqlite3 *db = pParse->db;
 93312    assert( db!=0 );
 93313    if( pList==0 ){
 93314      pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
 93315      if( pList==0 ){
 93316        goto no_mem;
 93317      }
 93318      pList->nExpr = 0;
 93319    }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
 93320      ExprList *pNew;
 93321      pNew = sqlite3DbRealloc(db, pList, 
 93322               sizeof(*pList)+(2*pList->nExpr - 1)*sizeof(pList->a[0]));
 93323      if( pNew==0 ){
 93324        goto no_mem;
 93325      }
 93326      pList = pNew;
 93327    }
 93328    pItem = &pList->a[pList->nExpr++];
 93329    assert( offsetof(struct ExprList_item,zName)==sizeof(pItem->pExpr) );
 93330    assert( offsetof(struct ExprList_item,pExpr)==0 );
 93331    memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName));
 93332    pItem->pExpr = pExpr;
 93333    return pList;
 93334  
 93335  no_mem:     
 93336    /* Avoid leaking memory if malloc has failed. */
 93337    sqlite3ExprDelete(db, pExpr);
 93338    sqlite3ExprListDelete(db, pList);
 93339    return 0;
 93340  }
 93341  
 93342  /*
 93343  ** pColumns and pExpr form a vector assignment which is part of the SET
 93344  ** clause of an UPDATE statement.  Like this:
 93345  **
 93346  **        (a,b,c) = (expr1,expr2,expr3)
 93347  ** Or:    (a,b,c) = (SELECT x,y,z FROM ....)
 93348  **
 93349  ** For each term of the vector assignment, append new entries to the
 93350  ** expression list pList.  In the case of a subquery on the RHS, append
 93351  ** TK_SELECT_COLUMN expressions.
 93352  */
 93353  SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
 93354    Parse *pParse,         /* Parsing context */
 93355    ExprList *pList,       /* List to which to append. Might be NULL */
 93356    IdList *pColumns,      /* List of names of LHS of the assignment */
 93357    Expr *pExpr            /* Vector expression to be appended. Might be NULL */
 93358  ){
 93359    sqlite3 *db = pParse->db;
 93360    int n;
 93361    int i;
 93362    int iFirst = pList ? pList->nExpr : 0;
 93363    /* pColumns can only be NULL due to an OOM but an OOM will cause an
 93364    ** exit prior to this routine being invoked */
 93365    if( NEVER(pColumns==0) ) goto vector_append_error;
 93366    if( pExpr==0 ) goto vector_append_error;
 93367  
 93368    /* If the RHS is a vector, then we can immediately check to see that 
 93369    ** the size of the RHS and LHS match.  But if the RHS is a SELECT, 
 93370    ** wildcards ("*") in the result set of the SELECT must be expanded before
 93371    ** we can do the size check, so defer the size check until code generation.
 93372    */
 93373    if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
 93374      sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
 93375                      pColumns->nId, n);
 93376      goto vector_append_error;
 93377    }
 93378  
 93379    for(i=0; i<pColumns->nId; i++){
 93380      Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
 93381      pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
 93382      if( pList ){
 93383        assert( pList->nExpr==iFirst+i+1 );
 93384        pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
 93385        pColumns->a[i].zName = 0;
 93386      }
 93387    }
 93388  
 93389    if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
 93390      Expr *pFirst = pList->a[iFirst].pExpr;
 93391      assert( pFirst!=0 );
 93392      assert( pFirst->op==TK_SELECT_COLUMN );
 93393       
 93394      /* Store the SELECT statement in pRight so it will be deleted when
 93395      ** sqlite3ExprListDelete() is called */
 93396      pFirst->pRight = pExpr;
 93397      pExpr = 0;
 93398  
 93399      /* Remember the size of the LHS in iTable so that we can check that
 93400      ** the RHS and LHS sizes match during code generation. */
 93401      pFirst->iTable = pColumns->nId;
 93402    }
 93403  
 93404  vector_append_error:
 93405    sqlite3ExprDelete(db, pExpr);
 93406    sqlite3IdListDelete(db, pColumns);
 93407    return pList;
 93408  }
 93409  
 93410  /*
 93411  ** Set the sort order for the last element on the given ExprList.
 93412  */
 93413  SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
 93414    if( p==0 ) return;
 93415    assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
 93416    assert( p->nExpr>0 );
 93417    if( iSortOrder<0 ){
 93418      assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
 93419      return;
 93420    }
 93421    p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
 93422  }
 93423  
 93424  /*
 93425  ** Set the ExprList.a[].zName element of the most recently added item
 93426  ** on the expression list.
 93427  **
 93428  ** pList might be NULL following an OOM error.  But pName should never be
 93429  ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
 93430  ** is set.
 93431  */
 93432  SQLITE_PRIVATE void sqlite3ExprListSetName(
 93433    Parse *pParse,          /* Parsing context */
 93434    ExprList *pList,        /* List to which to add the span. */
 93435    Token *pName,           /* Name to be added */
 93436    int dequote             /* True to cause the name to be dequoted */
 93437  ){
 93438    assert( pList!=0 || pParse->db->mallocFailed!=0 );
 93439    if( pList ){
 93440      struct ExprList_item *pItem;
 93441      assert( pList->nExpr>0 );
 93442      pItem = &pList->a[pList->nExpr-1];
 93443      assert( pItem->zName==0 );
 93444      pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
 93445      if( dequote ) sqlite3Dequote(pItem->zName);
 93446    }
 93447  }
 93448  
 93449  /*
 93450  ** Set the ExprList.a[].zSpan element of the most recently added item
 93451  ** on the expression list.
 93452  **
 93453  ** pList might be NULL following an OOM error.  But pSpan should never be
 93454  ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
 93455  ** is set.
 93456  */
 93457  SQLITE_PRIVATE void sqlite3ExprListSetSpan(
 93458    Parse *pParse,          /* Parsing context */
 93459    ExprList *pList,        /* List to which to add the span. */
 93460    ExprSpan *pSpan         /* The span to be added */
 93461  ){
 93462    sqlite3 *db = pParse->db;
 93463    assert( pList!=0 || db->mallocFailed!=0 );
 93464    if( pList ){
 93465      struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
 93466      assert( pList->nExpr>0 );
 93467      assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
 93468      sqlite3DbFree(db, pItem->zSpan);
 93469      pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
 93470                                      (int)(pSpan->zEnd - pSpan->zStart));
 93471    }
 93472  }
 93473  
 93474  /*
 93475  ** If the expression list pEList contains more than iLimit elements,
 93476  ** leave an error message in pParse.
 93477  */
 93478  SQLITE_PRIVATE void sqlite3ExprListCheckLength(
 93479    Parse *pParse,
 93480    ExprList *pEList,
 93481    const char *zObject
 93482  ){
 93483    int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
 93484    testcase( pEList && pEList->nExpr==mx );
 93485    testcase( pEList && pEList->nExpr==mx+1 );
 93486    if( pEList && pEList->nExpr>mx ){
 93487      sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
 93488    }
 93489  }
 93490  
 93491  /*
 93492  ** Delete an entire expression list.
 93493  */
 93494  static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
 93495    int i = pList->nExpr;
 93496    struct ExprList_item *pItem =  pList->a;
 93497    assert( pList->nExpr>0 );
 93498    do{
 93499      sqlite3ExprDelete(db, pItem->pExpr);
 93500      sqlite3DbFree(db, pItem->zName);
 93501      sqlite3DbFree(db, pItem->zSpan);
 93502      pItem++;
 93503    }while( --i>0 );
 93504    sqlite3DbFreeNN(db, pList);
 93505  }
 93506  SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
 93507    if( pList ) exprListDeleteNN(db, pList);
 93508  }
 93509  
 93510  /*
 93511  ** Return the bitwise-OR of all Expr.flags fields in the given
 93512  ** ExprList.
 93513  */
 93514  SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
 93515    int i;
 93516    u32 m = 0;
 93517    assert( pList!=0 );
 93518    for(i=0; i<pList->nExpr; i++){
 93519       Expr *pExpr = pList->a[i].pExpr;
 93520       assert( pExpr!=0 );
 93521       m |= pExpr->flags;
 93522    }
 93523    return m;
 93524  }
 93525  
 93526  /*
 93527  ** This is a SELECT-node callback for the expression walker that
 93528  ** always "fails".  By "fail" in this case, we mean set
 93529  ** pWalker->eCode to zero and abort.
 93530  **
 93531  ** This callback is used by multiple expression walkers.
 93532  */
 93533  SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
 93534    UNUSED_PARAMETER(NotUsed);
 93535    pWalker->eCode = 0;
 93536    return WRC_Abort;
 93537  }
 93538  
 93539  /*
 93540  ** These routines are Walker callbacks used to check expressions to
 93541  ** see if they are "constant" for some definition of constant.  The
 93542  ** Walker.eCode value determines the type of "constant" we are looking
 93543  ** for.
 93544  **
 93545  ** These callback routines are used to implement the following:
 93546  **
 93547  **     sqlite3ExprIsConstant()                  pWalker->eCode==1
 93548  **     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
 93549  **     sqlite3ExprIsTableConstant()             pWalker->eCode==3
 93550  **     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
 93551  **
 93552  ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
 93553  ** is found to not be a constant.
 93554  **
 93555  ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
 93556  ** in a CREATE TABLE statement.  The Walker.eCode value is 5 when parsing
 93557  ** an existing schema and 4 when processing a new statement.  A bound
 93558  ** parameter raises an error for new statements, but is silently converted
 93559  ** to NULL for existing schemas.  This allows sqlite_master tables that 
 93560  ** contain a bound parameter because they were generated by older versions
 93561  ** of SQLite to be parsed by newer versions of SQLite without raising a
 93562  ** malformed schema error.
 93563  */
 93564  static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
 93565  
 93566    /* If pWalker->eCode is 2 then any term of the expression that comes from
 93567    ** the ON or USING clauses of a left join disqualifies the expression
 93568    ** from being considered constant. */
 93569    if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
 93570      pWalker->eCode = 0;
 93571      return WRC_Abort;
 93572    }
 93573  
 93574    switch( pExpr->op ){
 93575      /* Consider functions to be constant if all their arguments are constant
 93576      ** and either pWalker->eCode==4 or 5 or the function has the
 93577      ** SQLITE_FUNC_CONST flag. */
 93578      case TK_FUNCTION:
 93579        if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
 93580          return WRC_Continue;
 93581        }else{
 93582          pWalker->eCode = 0;
 93583          return WRC_Abort;
 93584        }
 93585      case TK_ID:
 93586      case TK_COLUMN:
 93587      case TK_AGG_FUNCTION:
 93588      case TK_AGG_COLUMN:
 93589        testcase( pExpr->op==TK_ID );
 93590        testcase( pExpr->op==TK_COLUMN );
 93591        testcase( pExpr->op==TK_AGG_FUNCTION );
 93592        testcase( pExpr->op==TK_AGG_COLUMN );
 93593        if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
 93594          return WRC_Continue;
 93595        }
 93596        /* Fall through */
 93597      case TK_IF_NULL_ROW:
 93598        testcase( pExpr->op==TK_IF_NULL_ROW );
 93599        pWalker->eCode = 0;
 93600        return WRC_Abort;
 93601      case TK_VARIABLE:
 93602        if( pWalker->eCode==5 ){
 93603          /* Silently convert bound parameters that appear inside of CREATE
 93604          ** statements into a NULL when parsing the CREATE statement text out
 93605          ** of the sqlite_master table */
 93606          pExpr->op = TK_NULL;
 93607        }else if( pWalker->eCode==4 ){
 93608          /* A bound parameter in a CREATE statement that originates from
 93609          ** sqlite3_prepare() causes an error */
 93610          pWalker->eCode = 0;
 93611          return WRC_Abort;
 93612        }
 93613        /* Fall through */
 93614      default:
 93615        testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail will disallow */
 93616        testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail will disallow */
 93617        return WRC_Continue;
 93618    }
 93619  }
 93620  static int exprIsConst(Expr *p, int initFlag, int iCur){
 93621    Walker w;
 93622    w.eCode = initFlag;
 93623    w.xExprCallback = exprNodeIsConstant;
 93624    w.xSelectCallback = sqlite3SelectWalkFail;
 93625  #ifdef SQLITE_DEBUG
 93626    w.xSelectCallback2 = sqlite3SelectWalkAssert2;
 93627  #endif
 93628    w.u.iCur = iCur;
 93629    sqlite3WalkExpr(&w, p);
 93630    return w.eCode;
 93631  }
 93632  
 93633  /*
 93634  ** Walk an expression tree.  Return non-zero if the expression is constant
 93635  ** and 0 if it involves variables or function calls.
 93636  **
 93637  ** For the purposes of this function, a double-quoted string (ex: "abc")
 93638  ** is considered a variable but a single-quoted string (ex: 'abc') is
 93639  ** a constant.
 93640  */
 93641  SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
 93642    return exprIsConst(p, 1, 0);
 93643  }
 93644  
 93645  /*
 93646  ** Walk an expression tree.  Return non-zero if the expression is constant
 93647  ** that does no originate from the ON or USING clauses of a join.
 93648  ** Return 0 if it involves variables or function calls or terms from
 93649  ** an ON or USING clause.
 93650  */
 93651  SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
 93652    return exprIsConst(p, 2, 0);
 93653  }
 93654  
 93655  /*
 93656  ** Walk an expression tree.  Return non-zero if the expression is constant
 93657  ** for any single row of the table with cursor iCur.  In other words, the
 93658  ** expression must not refer to any non-deterministic function nor any
 93659  ** table other than iCur.
 93660  */
 93661  SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
 93662    return exprIsConst(p, 3, iCur);
 93663  }
 93664  
 93665  
 93666  /*
 93667  ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
 93668  */
 93669  static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
 93670    ExprList *pGroupBy = pWalker->u.pGroupBy;
 93671    int i;
 93672  
 93673    /* Check if pExpr is identical to any GROUP BY term. If so, consider
 93674    ** it constant.  */
 93675    for(i=0; i<pGroupBy->nExpr; i++){
 93676      Expr *p = pGroupBy->a[i].pExpr;
 93677      if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
 93678        CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
 93679        if( sqlite3_stricmp("BINARY", pColl->zName)==0 ){
 93680          return WRC_Prune;
 93681        }
 93682      }
 93683    }
 93684  
 93685    /* Check if pExpr is a sub-select. If so, consider it variable. */
 93686    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
 93687      pWalker->eCode = 0;
 93688      return WRC_Abort;
 93689    }
 93690  
 93691    return exprNodeIsConstant(pWalker, pExpr);
 93692  }
 93693  
 93694  /*
 93695  ** Walk the expression tree passed as the first argument. Return non-zero
 93696  ** if the expression consists entirely of constants or copies of terms 
 93697  ** in pGroupBy that sort with the BINARY collation sequence.
 93698  **
 93699  ** This routine is used to determine if a term of the HAVING clause can
 93700  ** be promoted into the WHERE clause.  In order for such a promotion to work,
 93701  ** the value of the HAVING clause term must be the same for all members of
 93702  ** a "group".  The requirement that the GROUP BY term must be BINARY
 93703  ** assumes that no other collating sequence will have a finer-grained
 93704  ** grouping than binary.  In other words (A=B COLLATE binary) implies
 93705  ** A=B in every other collating sequence.  The requirement that the
 93706  ** GROUP BY be BINARY is stricter than necessary.  It would also work
 93707  ** to promote HAVING clauses that use the same alternative collating
 93708  ** sequence as the GROUP BY term, but that is much harder to check,
 93709  ** alternative collating sequences are uncommon, and this is only an
 93710  ** optimization, so we take the easy way out and simply require the
 93711  ** GROUP BY to use the BINARY collating sequence.
 93712  */
 93713  SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
 93714    Walker w;
 93715    w.eCode = 1;
 93716    w.xExprCallback = exprNodeIsConstantOrGroupBy;
 93717    w.xSelectCallback = 0;
 93718    w.u.pGroupBy = pGroupBy;
 93719    w.pParse = pParse;
 93720    sqlite3WalkExpr(&w, p);
 93721    return w.eCode;
 93722  }
 93723  
 93724  /*
 93725  ** Walk an expression tree.  Return non-zero if the expression is constant
 93726  ** or a function call with constant arguments.  Return and 0 if there
 93727  ** are any variables.
 93728  **
 93729  ** For the purposes of this function, a double-quoted string (ex: "abc")
 93730  ** is considered a variable but a single-quoted string (ex: 'abc') is
 93731  ** a constant.
 93732  */
 93733  SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
 93734    assert( isInit==0 || isInit==1 );
 93735    return exprIsConst(p, 4+isInit, 0);
 93736  }
 93737  
 93738  #ifdef SQLITE_ENABLE_CURSOR_HINTS
 93739  /*
 93740  ** Walk an expression tree.  Return 1 if the expression contains a
 93741  ** subquery of some kind.  Return 0 if there are no subqueries.
 93742  */
 93743  SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
 93744    Walker w;
 93745    w.eCode = 1;
 93746    w.xExprCallback = sqlite3ExprWalkNoop;
 93747    w.xSelectCallback = sqlite3SelectWalkFail;
 93748  #ifdef SQLITE_DEBUG
 93749    w.xSelectCallback2 = sqlite3SelectWalkAssert2;
 93750  #endif
 93751    sqlite3WalkExpr(&w, p);
 93752    return w.eCode==0;
 93753  }
 93754  #endif
 93755  
 93756  /*
 93757  ** If the expression p codes a constant integer that is small enough
 93758  ** to fit in a 32-bit integer, return 1 and put the value of the integer
 93759  ** in *pValue.  If the expression is not an integer or if it is too big
 93760  ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
 93761  */
 93762  SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
 93763    int rc = 0;
 93764    if( p==0 ) return 0;  /* Can only happen following on OOM */
 93765  
 93766    /* If an expression is an integer literal that fits in a signed 32-bit
 93767    ** integer, then the EP_IntValue flag will have already been set */
 93768    assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
 93769             || sqlite3GetInt32(p->u.zToken, &rc)==0 );
 93770  
 93771    if( p->flags & EP_IntValue ){
 93772      *pValue = p->u.iValue;
 93773      return 1;
 93774    }
 93775    switch( p->op ){
 93776      case TK_UPLUS: {
 93777        rc = sqlite3ExprIsInteger(p->pLeft, pValue);
 93778        break;
 93779      }
 93780      case TK_UMINUS: {
 93781        int v;
 93782        if( sqlite3ExprIsInteger(p->pLeft, &v) ){
 93783          assert( v!=(-2147483647-1) );
 93784          *pValue = -v;
 93785          rc = 1;
 93786        }
 93787        break;
 93788      }
 93789      default: break;
 93790    }
 93791    return rc;
 93792  }
 93793  
 93794  /*
 93795  ** Return FALSE if there is no chance that the expression can be NULL.
 93796  **
 93797  ** If the expression might be NULL or if the expression is too complex
 93798  ** to tell return TRUE.  
 93799  **
 93800  ** This routine is used as an optimization, to skip OP_IsNull opcodes
 93801  ** when we know that a value cannot be NULL.  Hence, a false positive
 93802  ** (returning TRUE when in fact the expression can never be NULL) might
 93803  ** be a small performance hit but is otherwise harmless.  On the other
 93804  ** hand, a false negative (returning FALSE when the result could be NULL)
 93805  ** will likely result in an incorrect answer.  So when in doubt, return
 93806  ** TRUE.
 93807  */
 93808  SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
 93809    u8 op;
 93810    while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
 93811    op = p->op;
 93812    if( op==TK_REGISTER ) op = p->op2;
 93813    switch( op ){
 93814      case TK_INTEGER:
 93815      case TK_STRING:
 93816      case TK_FLOAT:
 93817      case TK_BLOB:
 93818        return 0;
 93819      case TK_COLUMN:
 93820        return ExprHasProperty(p, EP_CanBeNull) ||
 93821               p->pTab==0 ||  /* Reference to column of index on expression */
 93822               (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
 93823      default:
 93824        return 1;
 93825    }
 93826  }
 93827  
 93828  /*
 93829  ** Return TRUE if the given expression is a constant which would be
 93830  ** unchanged by OP_Affinity with the affinity given in the second
 93831  ** argument.
 93832  **
 93833  ** This routine is used to determine if the OP_Affinity operation
 93834  ** can be omitted.  When in doubt return FALSE.  A false negative
 93835  ** is harmless.  A false positive, however, can result in the wrong
 93836  ** answer.
 93837  */
 93838  SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
 93839    u8 op;
 93840    if( aff==SQLITE_AFF_BLOB ) return 1;
 93841    while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
 93842    op = p->op;
 93843    if( op==TK_REGISTER ) op = p->op2;
 93844    switch( op ){
 93845      case TK_INTEGER: {
 93846        return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
 93847      }
 93848      case TK_FLOAT: {
 93849        return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
 93850      }
 93851      case TK_STRING: {
 93852        return aff==SQLITE_AFF_TEXT;
 93853      }
 93854      case TK_BLOB: {
 93855        return 1;
 93856      }
 93857      case TK_COLUMN: {
 93858        assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
 93859        return p->iColumn<0
 93860            && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
 93861      }
 93862      default: {
 93863        return 0;
 93864      }
 93865    }
 93866  }
 93867  
 93868  /*
 93869  ** Return TRUE if the given string is a row-id column name.
 93870  */
 93871  SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
 93872    if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
 93873    if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
 93874    if( sqlite3StrICmp(z, "OID")==0 ) return 1;
 93875    return 0;
 93876  }
 93877  
 93878  /*
 93879  ** pX is the RHS of an IN operator.  If pX is a SELECT statement 
 93880  ** that can be simplified to a direct table access, then return
 93881  ** a pointer to the SELECT statement.  If pX is not a SELECT statement,
 93882  ** or if the SELECT statement needs to be manifested into a transient
 93883  ** table, then return NULL.
 93884  */
 93885  #ifndef SQLITE_OMIT_SUBQUERY
 93886  static Select *isCandidateForInOpt(Expr *pX){
 93887    Select *p;
 93888    SrcList *pSrc;
 93889    ExprList *pEList;
 93890    Table *pTab;
 93891    int i;
 93892    if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0;  /* Not a subquery */
 93893    if( ExprHasProperty(pX, EP_VarSelect)  ) return 0;  /* Correlated subq */
 93894    p = pX->x.pSelect;
 93895    if( p->pPrior ) return 0;              /* Not a compound SELECT */
 93896    if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
 93897      testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
 93898      testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
 93899      return 0; /* No DISTINCT keyword and no aggregate functions */
 93900    }
 93901    assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
 93902    if( p->pLimit ) return 0;              /* Has no LIMIT clause */
 93903    assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
 93904    if( p->pWhere ) return 0;              /* Has no WHERE clause */
 93905    pSrc = p->pSrc;
 93906    assert( pSrc!=0 );
 93907    if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
 93908    if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
 93909    pTab = pSrc->a[0].pTab;
 93910    assert( pTab!=0 );
 93911    assert( pTab->pSelect==0 );            /* FROM clause is not a view */
 93912    if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
 93913    pEList = p->pEList;
 93914    assert( pEList!=0 );
 93915    /* All SELECT results must be columns. */
 93916    for(i=0; i<pEList->nExpr; i++){
 93917      Expr *pRes = pEList->a[i].pExpr;
 93918      if( pRes->op!=TK_COLUMN ) return 0;
 93919      assert( pRes->iTable==pSrc->a[0].iCursor );  /* Not a correlated subquery */
 93920    }
 93921    return p;
 93922  }
 93923  #endif /* SQLITE_OMIT_SUBQUERY */
 93924  
 93925  #ifndef SQLITE_OMIT_SUBQUERY
 93926  /*
 93927  ** Generate code that checks the left-most column of index table iCur to see if
 93928  ** it contains any NULL entries.  Cause the register at regHasNull to be set
 93929  ** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
 93930  ** to be set to NULL if iCur contains one or more NULL values.
 93931  */
 93932  static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
 93933    int addr1;
 93934    sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
 93935    addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
 93936    sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
 93937    sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
 93938    VdbeComment((v, "first_entry_in(%d)", iCur));
 93939    sqlite3VdbeJumpHere(v, addr1);
 93940  }
 93941  #endif
 93942  
 93943  
 93944  #ifndef SQLITE_OMIT_SUBQUERY
 93945  /*
 93946  ** The argument is an IN operator with a list (not a subquery) on the 
 93947  ** right-hand side.  Return TRUE if that list is constant.
 93948  */
 93949  static int sqlite3InRhsIsConstant(Expr *pIn){
 93950    Expr *pLHS;
 93951    int res;
 93952    assert( !ExprHasProperty(pIn, EP_xIsSelect) );
 93953    pLHS = pIn->pLeft;
 93954    pIn->pLeft = 0;
 93955    res = sqlite3ExprIsConstant(pIn);
 93956    pIn->pLeft = pLHS;
 93957    return res;
 93958  }
 93959  #endif
 93960  
 93961  /*
 93962  ** This function is used by the implementation of the IN (...) operator.
 93963  ** The pX parameter is the expression on the RHS of the IN operator, which
 93964  ** might be either a list of expressions or a subquery.
 93965  **
 93966  ** The job of this routine is to find or create a b-tree object that can
 93967  ** be used either to test for membership in the RHS set or to iterate through
 93968  ** all members of the RHS set, skipping duplicates.
 93969  **
 93970  ** A cursor is opened on the b-tree object that is the RHS of the IN operator
 93971  ** and pX->iTable is set to the index of that cursor.
 93972  **
 93973  ** The returned value of this function indicates the b-tree type, as follows:
 93974  **
 93975  **   IN_INDEX_ROWID      - The cursor was opened on a database table.
 93976  **   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
 93977  **   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
 93978  **   IN_INDEX_EPH        - The cursor was opened on a specially created and
 93979  **                         populated epheremal table.
 93980  **   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
 93981  **                         implemented as a sequence of comparisons.
 93982  **
 93983  ** An existing b-tree might be used if the RHS expression pX is a simple
 93984  ** subquery such as:
 93985  **
 93986  **     SELECT <column1>, <column2>... FROM <table>
 93987  **
 93988  ** If the RHS of the IN operator is a list or a more complex subquery, then
 93989  ** an ephemeral table might need to be generated from the RHS and then
 93990  ** pX->iTable made to point to the ephemeral table instead of an
 93991  ** existing table.
 93992  **
 93993  ** The inFlags parameter must contain exactly one of the bits
 93994  ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP.  If inFlags contains
 93995  ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
 93996  ** fast membership test.  When the IN_INDEX_LOOP bit is set, the
 93997  ** IN index will be used to loop over all values of the RHS of the
 93998  ** IN operator.
 93999  **
 94000  ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
 94001  ** through the set members) then the b-tree must not contain duplicates.
 94002  ** An epheremal table must be used unless the selected columns are guaranteed
 94003  ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
 94004  ** a UNIQUE constraint or index.
 94005  **
 94006  ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used 
 94007  ** for fast set membership tests) then an epheremal table must 
 94008  ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an 
 94009  ** index can be found with the specified <columns> as its left-most.
 94010  **
 94011  ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
 94012  ** if the RHS of the IN operator is a list (not a subquery) then this
 94013  ** routine might decide that creating an ephemeral b-tree for membership
 94014  ** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
 94015  ** calling routine should implement the IN operator using a sequence
 94016  ** of Eq or Ne comparison operations.
 94017  **
 94018  ** When the b-tree is being used for membership tests, the calling function
 94019  ** might need to know whether or not the RHS side of the IN operator
 94020  ** contains a NULL.  If prRhsHasNull is not a NULL pointer and 
 94021  ** if there is any chance that the (...) might contain a NULL value at
 94022  ** runtime, then a register is allocated and the register number written
 94023  ** to *prRhsHasNull. If there is no chance that the (...) contains a
 94024  ** NULL value, then *prRhsHasNull is left unchanged.
 94025  **
 94026  ** If a register is allocated and its location stored in *prRhsHasNull, then
 94027  ** the value in that register will be NULL if the b-tree contains one or more
 94028  ** NULL values, and it will be some non-NULL value if the b-tree contains no
 94029  ** NULL values.
 94030  **
 94031  ** If the aiMap parameter is not NULL, it must point to an array containing
 94032  ** one element for each column returned by the SELECT statement on the RHS
 94033  ** of the IN(...) operator. The i'th entry of the array is populated with the
 94034  ** offset of the index column that matches the i'th column returned by the
 94035  ** SELECT. For example, if the expression and selected index are:
 94036  **
 94037  **   (?,?,?) IN (SELECT a, b, c FROM t1)
 94038  **   CREATE INDEX i1 ON t1(b, c, a);
 94039  **
 94040  ** then aiMap[] is populated with {2, 0, 1}.
 94041  */
 94042  #ifndef SQLITE_OMIT_SUBQUERY
 94043  SQLITE_PRIVATE int sqlite3FindInIndex(
 94044    Parse *pParse,             /* Parsing context */
 94045    Expr *pX,                  /* The right-hand side (RHS) of the IN operator */
 94046    u32 inFlags,               /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
 94047    int *prRhsHasNull,         /* Register holding NULL status.  See notes */
 94048    int *aiMap                 /* Mapping from Index fields to RHS fields */
 94049  ){
 94050    Select *p;                            /* SELECT to the right of IN operator */
 94051    int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
 94052    int iTab = pParse->nTab++;            /* Cursor of the RHS table */
 94053    int mustBeUnique;                     /* True if RHS must be unique */
 94054    Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
 94055  
 94056    assert( pX->op==TK_IN );
 94057    mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
 94058  
 94059    /* If the RHS of this IN(...) operator is a SELECT, and if it matters 
 94060    ** whether or not the SELECT result contains NULL values, check whether
 94061    ** or not NULL is actually possible (it may not be, for example, due 
 94062    ** to NOT NULL constraints in the schema). If no NULL values are possible,
 94063    ** set prRhsHasNull to 0 before continuing.  */
 94064    if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
 94065      int i;
 94066      ExprList *pEList = pX->x.pSelect->pEList;
 94067      for(i=0; i<pEList->nExpr; i++){
 94068        if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
 94069      }
 94070      if( i==pEList->nExpr ){
 94071        prRhsHasNull = 0;
 94072      }
 94073    }
 94074  
 94075    /* Check to see if an existing table or index can be used to
 94076    ** satisfy the query.  This is preferable to generating a new 
 94077    ** ephemeral table.  */
 94078    if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
 94079      sqlite3 *db = pParse->db;              /* Database connection */
 94080      Table *pTab;                           /* Table <table>. */
 94081      i16 iDb;                               /* Database idx for pTab */
 94082      ExprList *pEList = p->pEList;
 94083      int nExpr = pEList->nExpr;
 94084  
 94085      assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
 94086      assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
 94087      assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
 94088      pTab = p->pSrc->a[0].pTab;
 94089  
 94090      /* Code an OP_Transaction and OP_TableLock for <table>. */
 94091      iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
 94092      sqlite3CodeVerifySchema(pParse, iDb);
 94093      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
 94094  
 94095      assert(v);  /* sqlite3GetVdbe() has always been previously called */
 94096      if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
 94097        /* The "x IN (SELECT rowid FROM table)" case */
 94098        int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
 94099        VdbeCoverage(v);
 94100  
 94101        sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
 94102        eType = IN_INDEX_ROWID;
 94103  
 94104        sqlite3VdbeJumpHere(v, iAddr);
 94105      }else{
 94106        Index *pIdx;                         /* Iterator variable */
 94107        int affinity_ok = 1;
 94108        int i;
 94109  
 94110        /* Check that the affinity that will be used to perform each 
 94111        ** comparison is the same as the affinity of each column in table
 94112        ** on the RHS of the IN operator.  If it not, it is not possible to
 94113        ** use any index of the RHS table.  */
 94114        for(i=0; i<nExpr && affinity_ok; i++){
 94115          Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
 94116          int iCol = pEList->a[i].pExpr->iColumn;
 94117          char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
 94118          char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
 94119          testcase( cmpaff==SQLITE_AFF_BLOB );
 94120          testcase( cmpaff==SQLITE_AFF_TEXT );
 94121          switch( cmpaff ){
 94122            case SQLITE_AFF_BLOB:
 94123              break;
 94124            case SQLITE_AFF_TEXT:
 94125              /* sqlite3CompareAffinity() only returns TEXT if one side or the
 94126              ** other has no affinity and the other side is TEXT.  Hence,
 94127              ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
 94128              ** and for the term on the LHS of the IN to have no affinity. */
 94129              assert( idxaff==SQLITE_AFF_TEXT );
 94130              break;
 94131            default:
 94132              affinity_ok = sqlite3IsNumericAffinity(idxaff);
 94133          }
 94134        }
 94135  
 94136        if( affinity_ok ){
 94137          /* Search for an existing index that will work for this IN operator */
 94138          for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
 94139            Bitmask colUsed;      /* Columns of the index used */
 94140            Bitmask mCol;         /* Mask for the current column */
 94141            if( pIdx->nColumn<nExpr ) continue;
 94142            /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
 94143            ** BITMASK(nExpr) without overflowing */
 94144            testcase( pIdx->nColumn==BMS-2 );
 94145            testcase( pIdx->nColumn==BMS-1 );
 94146            if( pIdx->nColumn>=BMS-1 ) continue;
 94147            if( mustBeUnique ){
 94148              if( pIdx->nKeyCol>nExpr
 94149               ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
 94150              ){
 94151                continue;  /* This index is not unique over the IN RHS columns */
 94152              }
 94153            }
 94154    
 94155            colUsed = 0;   /* Columns of index used so far */
 94156            for(i=0; i<nExpr; i++){
 94157              Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
 94158              Expr *pRhs = pEList->a[i].pExpr;
 94159              CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
 94160              int j;
 94161    
 94162              assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
 94163              for(j=0; j<nExpr; j++){
 94164                if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
 94165                assert( pIdx->azColl[j] );
 94166                if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
 94167                  continue;
 94168                }
 94169                break;
 94170              }
 94171              if( j==nExpr ) break;
 94172              mCol = MASKBIT(j);
 94173              if( mCol & colUsed ) break; /* Each column used only once */
 94174              colUsed |= mCol;
 94175              if( aiMap ) aiMap[i] = j;
 94176            }
 94177    
 94178            assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
 94179            if( colUsed==(MASKBIT(nExpr)-1) ){
 94180              /* If we reach this point, that means the index pIdx is usable */
 94181              int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
 94182  #ifndef SQLITE_OMIT_EXPLAIN
 94183              sqlite3VdbeAddOp4(v, OP_Explain, 0, 0, 0,
 94184                sqlite3MPrintf(db, "USING INDEX %s FOR IN-OPERATOR",pIdx->zName),
 94185                P4_DYNAMIC);
 94186  #endif
 94187              sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
 94188              sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
 94189              VdbeComment((v, "%s", pIdx->zName));
 94190              assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
 94191              eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
 94192    
 94193              if( prRhsHasNull ){
 94194  #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
 94195                i64 mask = (1<<nExpr)-1;
 94196                sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, 
 94197                    iTab, 0, 0, (u8*)&mask, P4_INT64);
 94198  #endif
 94199                *prRhsHasNull = ++pParse->nMem;
 94200                if( nExpr==1 ){
 94201                  sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
 94202                }
 94203              }
 94204              sqlite3VdbeJumpHere(v, iAddr);
 94205            }
 94206          } /* End loop over indexes */
 94207        } /* End if( affinity_ok ) */
 94208      } /* End if not an rowid index */
 94209    } /* End attempt to optimize using an index */
 94210  
 94211    /* If no preexisting index is available for the IN clause
 94212    ** and IN_INDEX_NOOP is an allowed reply
 94213    ** and the RHS of the IN operator is a list, not a subquery
 94214    ** and the RHS is not constant or has two or fewer terms,
 94215    ** then it is not worth creating an ephemeral table to evaluate
 94216    ** the IN operator so return IN_INDEX_NOOP.
 94217    */
 94218    if( eType==0
 94219     && (inFlags & IN_INDEX_NOOP_OK)
 94220     && !ExprHasProperty(pX, EP_xIsSelect)
 94221     && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
 94222    ){
 94223      eType = IN_INDEX_NOOP;
 94224    }
 94225  
 94226    if( eType==0 ){
 94227      /* Could not find an existing table or index to use as the RHS b-tree.
 94228      ** We will have to generate an ephemeral table to do the job.
 94229      */
 94230      u32 savedNQueryLoop = pParse->nQueryLoop;
 94231      int rMayHaveNull = 0;
 94232      eType = IN_INDEX_EPH;
 94233      if( inFlags & IN_INDEX_LOOP ){
 94234        pParse->nQueryLoop = 0;
 94235        if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
 94236          eType = IN_INDEX_ROWID;
 94237        }
 94238      }else if( prRhsHasNull ){
 94239        *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
 94240      }
 94241      sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
 94242      pParse->nQueryLoop = savedNQueryLoop;
 94243    }else{
 94244      pX->iTable = iTab;
 94245    }
 94246  
 94247    if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
 94248      int i, n;
 94249      n = sqlite3ExprVectorSize(pX->pLeft);
 94250      for(i=0; i<n; i++) aiMap[i] = i;
 94251    }
 94252    return eType;
 94253  }
 94254  #endif
 94255  
 94256  #ifndef SQLITE_OMIT_SUBQUERY
 94257  /*
 94258  ** Argument pExpr is an (?, ?...) IN(...) expression. This 
 94259  ** function allocates and returns a nul-terminated string containing 
 94260  ** the affinities to be used for each column of the comparison.
 94261  **
 94262  ** It is the responsibility of the caller to ensure that the returned
 94263  ** string is eventually freed using sqlite3DbFree().
 94264  */
 94265  static char *exprINAffinity(Parse *pParse, Expr *pExpr){
 94266    Expr *pLeft = pExpr->pLeft;
 94267    int nVal = sqlite3ExprVectorSize(pLeft);
 94268    Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
 94269    char *zRet;
 94270  
 94271    assert( pExpr->op==TK_IN );
 94272    zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
 94273    if( zRet ){
 94274      int i;
 94275      for(i=0; i<nVal; i++){
 94276        Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
 94277        char a = sqlite3ExprAffinity(pA);
 94278        if( pSelect ){
 94279          zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
 94280        }else{
 94281          zRet[i] = a;
 94282        }
 94283      }
 94284      zRet[nVal] = '\0';
 94285    }
 94286    return zRet;
 94287  }
 94288  #endif
 94289  
 94290  #ifndef SQLITE_OMIT_SUBQUERY
 94291  /*
 94292  ** Load the Parse object passed as the first argument with an error 
 94293  ** message of the form:
 94294  **
 94295  **   "sub-select returns N columns - expected M"
 94296  */   
 94297  SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
 94298    const char *zFmt = "sub-select returns %d columns - expected %d";
 94299    sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
 94300  }
 94301  #endif
 94302  
 94303  /*
 94304  ** Expression pExpr is a vector that has been used in a context where
 94305  ** it is not permitted. If pExpr is a sub-select vector, this routine 
 94306  ** loads the Parse object with a message of the form:
 94307  **
 94308  **   "sub-select returns N columns - expected 1"
 94309  **
 94310  ** Or, if it is a regular scalar vector:
 94311  **
 94312  **   "row value misused"
 94313  */   
 94314  SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
 94315  #ifndef SQLITE_OMIT_SUBQUERY
 94316    if( pExpr->flags & EP_xIsSelect ){
 94317      sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
 94318    }else
 94319  #endif
 94320    {
 94321      sqlite3ErrorMsg(pParse, "row value misused");
 94322    }
 94323  }
 94324  
 94325  /*
 94326  ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
 94327  ** or IN operators.  Examples:
 94328  **
 94329  **     (SELECT a FROM b)          -- subquery
 94330  **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
 94331  **     x IN (4,5,11)              -- IN operator with list on right-hand side
 94332  **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
 94333  **
 94334  ** The pExpr parameter describes the expression that contains the IN
 94335  ** operator or subquery.
 94336  **
 94337  ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
 94338  ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
 94339  ** to some integer key column of a table B-Tree. In this case, use an
 94340  ** intkey B-Tree to store the set of IN(...) values instead of the usual
 94341  ** (slower) variable length keys B-Tree.
 94342  **
 94343  ** If rMayHaveNull is non-zero, that means that the operation is an IN
 94344  ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
 94345  ** All this routine does is initialize the register given by rMayHaveNull
 94346  ** to NULL.  Calling routines will take care of changing this register
 94347  ** value to non-NULL if the RHS is NULL-free.
 94348  **
 94349  ** For a SELECT or EXISTS operator, return the register that holds the
 94350  ** result.  For a multi-column SELECT, the result is stored in a contiguous
 94351  ** array of registers and the return value is the register of the left-most
 94352  ** result column.  Return 0 for IN operators or if an error occurs.
 94353  */
 94354  #ifndef SQLITE_OMIT_SUBQUERY
 94355  SQLITE_PRIVATE int sqlite3CodeSubselect(
 94356    Parse *pParse,          /* Parsing context */
 94357    Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
 94358    int rHasNullFlag,       /* Register that records whether NULLs exist in RHS */
 94359    int isRowid             /* If true, LHS of IN operator is a rowid */
 94360  ){
 94361    int jmpIfDynamic = -1;                      /* One-time test address */
 94362    int rReg = 0;                           /* Register storing resulting */
 94363    Vdbe *v = sqlite3GetVdbe(pParse);
 94364    if( NEVER(v==0) ) return 0;
 94365    sqlite3ExprCachePush(pParse);
 94366  
 94367    /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
 94368    ** is encountered if any of the following is true:
 94369    **
 94370    **    *  The right-hand side is a correlated subquery
 94371    **    *  The right-hand side is an expression list containing variables
 94372    **    *  We are inside a trigger
 94373    **
 94374    ** If all of the above are false, then we can run this code just once
 94375    ** save the results, and reuse the same result on subsequent invocations.
 94376    */
 94377    if( !ExprHasProperty(pExpr, EP_VarSelect) ){
 94378      jmpIfDynamic = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
 94379    }
 94380  
 94381  #ifndef SQLITE_OMIT_EXPLAIN
 94382    if( pParse->explain==2 ){
 94383      char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
 94384          jmpIfDynamic>=0?"":"CORRELATED ",
 94385          pExpr->op==TK_IN?"LIST":"SCALAR",
 94386          pParse->iNextSelectId
 94387      );
 94388      sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
 94389    }
 94390  #endif
 94391  
 94392    switch( pExpr->op ){
 94393      case TK_IN: {
 94394        int addr;                   /* Address of OP_OpenEphemeral instruction */
 94395        Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
 94396        KeyInfo *pKeyInfo = 0;      /* Key information */
 94397        int nVal;                   /* Size of vector pLeft */
 94398        
 94399        nVal = sqlite3ExprVectorSize(pLeft);
 94400        assert( !isRowid || nVal==1 );
 94401  
 94402        /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
 94403        ** expression it is handled the same way.  An ephemeral table is 
 94404        ** filled with index keys representing the results from the 
 94405        ** SELECT or the <exprlist>.
 94406        **
 94407        ** If the 'x' expression is a column value, or the SELECT...
 94408        ** statement returns a column value, then the affinity of that
 94409        ** column is used to build the index keys. If both 'x' and the
 94410        ** SELECT... statement are columns, then numeric affinity is used
 94411        ** if either column has NUMERIC or INTEGER affinity. If neither
 94412        ** 'x' nor the SELECT... statement are columns, then numeric affinity
 94413        ** is used.
 94414        */
 94415        pExpr->iTable = pParse->nTab++;
 94416        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, 
 94417            pExpr->iTable, (isRowid?0:nVal));
 94418        pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
 94419  
 94420        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
 94421          /* Case 1:     expr IN (SELECT ...)
 94422          **
 94423          ** Generate code to write the results of the select into the temporary
 94424          ** table allocated and opened above.
 94425          */
 94426          Select *pSelect = pExpr->x.pSelect;
 94427          ExprList *pEList = pSelect->pEList;
 94428  
 94429          assert( !isRowid );
 94430          /* If the LHS and RHS of the IN operator do not match, that
 94431          ** error will have been caught long before we reach this point. */
 94432          if( ALWAYS(pEList->nExpr==nVal) ){
 94433            SelectDest dest;
 94434            int i;
 94435            sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
 94436            dest.zAffSdst = exprINAffinity(pParse, pExpr);
 94437            pSelect->iLimit = 0;
 94438            testcase( pSelect->selFlags & SF_Distinct );
 94439            testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
 94440            if( sqlite3Select(pParse, pSelect, &dest) ){
 94441              sqlite3DbFree(pParse->db, dest.zAffSdst);
 94442              sqlite3KeyInfoUnref(pKeyInfo);
 94443              return 0;
 94444            }
 94445            sqlite3DbFree(pParse->db, dest.zAffSdst);
 94446            assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
 94447            assert( pEList!=0 );
 94448            assert( pEList->nExpr>0 );
 94449            assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
 94450            for(i=0; i<nVal; i++){
 94451              Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
 94452              pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
 94453                  pParse, p, pEList->a[i].pExpr
 94454              );
 94455            }
 94456          }
 94457        }else if( ALWAYS(pExpr->x.pList!=0) ){
 94458          /* Case 2:     expr IN (exprlist)
 94459          **
 94460          ** For each expression, build an index key from the evaluation and
 94461          ** store it in the temporary table. If <expr> is a column, then use
 94462          ** that columns affinity when building index keys. If <expr> is not
 94463          ** a column, use numeric affinity.
 94464          */
 94465          char affinity;            /* Affinity of the LHS of the IN */
 94466          int i;
 94467          ExprList *pList = pExpr->x.pList;
 94468          struct ExprList_item *pItem;
 94469          int r1, r2, r3;
 94470  
 94471          affinity = sqlite3ExprAffinity(pLeft);
 94472          if( !affinity ){
 94473            affinity = SQLITE_AFF_BLOB;
 94474          }
 94475          if( pKeyInfo ){
 94476            assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
 94477            pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
 94478          }
 94479  
 94480          /* Loop through each expression in <exprlist>. */
 94481          r1 = sqlite3GetTempReg(pParse);
 94482          r2 = sqlite3GetTempReg(pParse);
 94483          if( isRowid ) sqlite3VdbeAddOp4(v, OP_Blob, 0, r2, 0, "", P4_STATIC);
 94484          for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
 94485            Expr *pE2 = pItem->pExpr;
 94486            int iValToIns;
 94487  
 94488            /* If the expression is not constant then we will need to
 94489            ** disable the test that was generated above that makes sure
 94490            ** this code only executes once.  Because for a non-constant
 94491            ** expression we need to rerun this code each time.
 94492            */
 94493            if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
 94494              sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
 94495              jmpIfDynamic = -1;
 94496            }
 94497  
 94498            /* Evaluate the expression and insert it into the temp table */
 94499            if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
 94500              sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
 94501            }else{
 94502              r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
 94503              if( isRowid ){
 94504                sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
 94505                                  sqlite3VdbeCurrentAddr(v)+2);
 94506                VdbeCoverage(v);
 94507                sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
 94508              }else{
 94509                sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
 94510                sqlite3ExprCacheAffinityChange(pParse, r3, 1);
 94511                sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pExpr->iTable, r2, r3, 1);
 94512              }
 94513            }
 94514          }
 94515          sqlite3ReleaseTempReg(pParse, r1);
 94516          sqlite3ReleaseTempReg(pParse, r2);
 94517        }
 94518        if( pKeyInfo ){
 94519          sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
 94520        }
 94521        break;
 94522      }
 94523  
 94524      case TK_EXISTS:
 94525      case TK_SELECT:
 94526      default: {
 94527        /* Case 3:    (SELECT ... FROM ...)
 94528        **     or:    EXISTS(SELECT ... FROM ...)
 94529        **
 94530        ** For a SELECT, generate code to put the values for all columns of
 94531        ** the first row into an array of registers and return the index of
 94532        ** the first register.
 94533        **
 94534        ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
 94535        ** into a register and return that register number.
 94536        **
 94537        ** In both cases, the query is augmented with "LIMIT 1".  Any 
 94538        ** preexisting limit is discarded in place of the new LIMIT 1.
 94539        */
 94540        Select *pSel;                         /* SELECT statement to encode */
 94541        SelectDest dest;                      /* How to deal with SELECT result */
 94542        int nReg;                             /* Registers to allocate */
 94543  
 94544        testcase( pExpr->op==TK_EXISTS );
 94545        testcase( pExpr->op==TK_SELECT );
 94546        assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
 94547        assert( ExprHasProperty(pExpr, EP_xIsSelect) );
 94548  
 94549        pSel = pExpr->x.pSelect;
 94550        nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
 94551        sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
 94552        pParse->nMem += nReg;
 94553        if( pExpr->op==TK_SELECT ){
 94554          dest.eDest = SRT_Mem;
 94555          dest.iSdst = dest.iSDParm;
 94556          dest.nSdst = nReg;
 94557          sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
 94558          VdbeComment((v, "Init subquery result"));
 94559        }else{
 94560          dest.eDest = SRT_Exists;
 94561          sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
 94562          VdbeComment((v, "Init EXISTS result"));
 94563        }
 94564        sqlite3ExprDelete(pParse->db, pSel->pLimit);
 94565        pSel->pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,
 94566                                    &sqlite3IntTokens[1], 0);
 94567        pSel->iLimit = 0;
 94568        pSel->selFlags &= ~SF_MultiValue;
 94569        if( sqlite3Select(pParse, pSel, &dest) ){
 94570          return 0;
 94571        }
 94572        rReg = dest.iSDParm;
 94573        ExprSetVVAProperty(pExpr, EP_NoReduce);
 94574        break;
 94575      }
 94576    }
 94577  
 94578    if( rHasNullFlag ){
 94579      sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
 94580    }
 94581  
 94582    if( jmpIfDynamic>=0 ){
 94583      sqlite3VdbeJumpHere(v, jmpIfDynamic);
 94584    }
 94585    sqlite3ExprCachePop(pParse);
 94586  
 94587    return rReg;
 94588  }
 94589  #endif /* SQLITE_OMIT_SUBQUERY */
 94590  
 94591  #ifndef SQLITE_OMIT_SUBQUERY
 94592  /*
 94593  ** Expr pIn is an IN(...) expression. This function checks that the 
 94594  ** sub-select on the RHS of the IN() operator has the same number of 
 94595  ** columns as the vector on the LHS. Or, if the RHS of the IN() is not 
 94596  ** a sub-query, that the LHS is a vector of size 1.
 94597  */
 94598  SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
 94599    int nVector = sqlite3ExprVectorSize(pIn->pLeft);
 94600    if( (pIn->flags & EP_xIsSelect) ){
 94601      if( nVector!=pIn->x.pSelect->pEList->nExpr ){
 94602        sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
 94603        return 1;
 94604      }
 94605    }else if( nVector!=1 ){
 94606      sqlite3VectorErrorMsg(pParse, pIn->pLeft);
 94607      return 1;
 94608    }
 94609    return 0;
 94610  }
 94611  #endif
 94612  
 94613  #ifndef SQLITE_OMIT_SUBQUERY
 94614  /*
 94615  ** Generate code for an IN expression.
 94616  **
 94617  **      x IN (SELECT ...)
 94618  **      x IN (value, value, ...)
 94619  **
 94620  ** The left-hand side (LHS) is a scalar or vector expression.  The 
 94621  ** right-hand side (RHS) is an array of zero or more scalar values, or a
 94622  ** subquery.  If the RHS is a subquery, the number of result columns must
 94623  ** match the number of columns in the vector on the LHS.  If the RHS is
 94624  ** a list of values, the LHS must be a scalar. 
 94625  **
 94626  ** The IN operator is true if the LHS value is contained within the RHS.
 94627  ** The result is false if the LHS is definitely not in the RHS.  The 
 94628  ** result is NULL if the presence of the LHS in the RHS cannot be 
 94629  ** determined due to NULLs.
 94630  **
 94631  ** This routine generates code that jumps to destIfFalse if the LHS is not 
 94632  ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
 94633  ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
 94634  ** within the RHS then fall through.
 94635  **
 94636  ** See the separate in-operator.md documentation file in the canonical
 94637  ** SQLite source tree for additional information.
 94638  */
 94639  static void sqlite3ExprCodeIN(
 94640    Parse *pParse,        /* Parsing and code generating context */
 94641    Expr *pExpr,          /* The IN expression */
 94642    int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
 94643    int destIfNull        /* Jump here if the results are unknown due to NULLs */
 94644  ){
 94645    int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
 94646    int eType;            /* Type of the RHS */
 94647    int rLhs;             /* Register(s) holding the LHS values */
 94648    int rLhsOrig;         /* LHS values prior to reordering by aiMap[] */
 94649    Vdbe *v;              /* Statement under construction */
 94650    int *aiMap = 0;       /* Map from vector field to index column */
 94651    char *zAff = 0;       /* Affinity string for comparisons */
 94652    int nVector;          /* Size of vectors for this IN operator */
 94653    int iDummy;           /* Dummy parameter to exprCodeVector() */
 94654    Expr *pLeft;          /* The LHS of the IN operator */
 94655    int i;                /* loop counter */
 94656    int destStep2;        /* Where to jump when NULLs seen in step 2 */
 94657    int destStep6 = 0;    /* Start of code for Step 6 */
 94658    int addrTruthOp;      /* Address of opcode that determines the IN is true */
 94659    int destNotNull;      /* Jump here if a comparison is not true in step 6 */
 94660    int addrTop;          /* Top of the step-6 loop */ 
 94661  
 94662    pLeft = pExpr->pLeft;
 94663    if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
 94664    zAff = exprINAffinity(pParse, pExpr);
 94665    nVector = sqlite3ExprVectorSize(pExpr->pLeft);
 94666    aiMap = (int*)sqlite3DbMallocZero(
 94667        pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
 94668    );
 94669    if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
 94670  
 94671    /* Attempt to compute the RHS. After this step, if anything other than
 94672    ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable 
 94673    ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
 94674    ** the RHS has not yet been coded.  */
 94675    v = pParse->pVdbe;
 94676    assert( v!=0 );       /* OOM detected prior to this routine */
 94677    VdbeNoopComment((v, "begin IN expr"));
 94678    eType = sqlite3FindInIndex(pParse, pExpr,
 94679                               IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
 94680                               destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
 94681  
 94682    assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
 94683         || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC 
 94684    );
 94685  #ifdef SQLITE_DEBUG
 94686    /* Confirm that aiMap[] contains nVector integer values between 0 and
 94687    ** nVector-1. */
 94688    for(i=0; i<nVector; i++){
 94689      int j, cnt;
 94690      for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
 94691      assert( cnt==1 );
 94692    }
 94693  #endif
 94694  
 94695    /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a 
 94696    ** vector, then it is stored in an array of nVector registers starting 
 94697    ** at r1.
 94698    **
 94699    ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
 94700    ** so that the fields are in the same order as an existing index.   The
 94701    ** aiMap[] array contains a mapping from the original LHS field order to
 94702    ** the field order that matches the RHS index.
 94703    */
 94704    sqlite3ExprCachePush(pParse);
 94705    rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
 94706    for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
 94707    if( i==nVector ){
 94708      /* LHS fields are not reordered */
 94709      rLhs = rLhsOrig;
 94710    }else{
 94711      /* Need to reorder the LHS fields according to aiMap */
 94712      rLhs = sqlite3GetTempRange(pParse, nVector);
 94713      for(i=0; i<nVector; i++){
 94714        sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
 94715      }
 94716    }
 94717  
 94718    /* If sqlite3FindInIndex() did not find or create an index that is
 94719    ** suitable for evaluating the IN operator, then evaluate using a
 94720    ** sequence of comparisons.
 94721    **
 94722    ** This is step (1) in the in-operator.md optimized algorithm.
 94723    */
 94724    if( eType==IN_INDEX_NOOP ){
 94725      ExprList *pList = pExpr->x.pList;
 94726      CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
 94727      int labelOk = sqlite3VdbeMakeLabel(v);
 94728      int r2, regToFree;
 94729      int regCkNull = 0;
 94730      int ii;
 94731      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
 94732      if( destIfNull!=destIfFalse ){
 94733        regCkNull = sqlite3GetTempReg(pParse);
 94734        sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
 94735      }
 94736      for(ii=0; ii<pList->nExpr; ii++){
 94737        r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
 94738        if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
 94739          sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
 94740        }
 94741        if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
 94742          sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
 94743                            (void*)pColl, P4_COLLSEQ);
 94744          VdbeCoverageIf(v, ii<pList->nExpr-1);
 94745          VdbeCoverageIf(v, ii==pList->nExpr-1);
 94746          sqlite3VdbeChangeP5(v, zAff[0]);
 94747        }else{
 94748          assert( destIfNull==destIfFalse );
 94749          sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
 94750                            (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
 94751          sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
 94752        }
 94753        sqlite3ReleaseTempReg(pParse, regToFree);
 94754      }
 94755      if( regCkNull ){
 94756        sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
 94757        sqlite3VdbeGoto(v, destIfFalse);
 94758      }
 94759      sqlite3VdbeResolveLabel(v, labelOk);
 94760      sqlite3ReleaseTempReg(pParse, regCkNull);
 94761      goto sqlite3ExprCodeIN_finished;
 94762    }
 94763  
 94764    /* Step 2: Check to see if the LHS contains any NULL columns.  If the
 94765    ** LHS does contain NULLs then the result must be either FALSE or NULL.
 94766    ** We will then skip the binary search of the RHS.
 94767    */
 94768    if( destIfNull==destIfFalse ){
 94769      destStep2 = destIfFalse;
 94770    }else{
 94771      destStep2 = destStep6 = sqlite3VdbeMakeLabel(v);
 94772    }
 94773    for(i=0; i<nVector; i++){
 94774      Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
 94775      if( sqlite3ExprCanBeNull(p) ){
 94776        sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
 94777        VdbeCoverage(v);
 94778      }
 94779    }
 94780  
 94781    /* Step 3.  The LHS is now known to be non-NULL.  Do the binary search
 94782    ** of the RHS using the LHS as a probe.  If found, the result is
 94783    ** true.
 94784    */
 94785    if( eType==IN_INDEX_ROWID ){
 94786      /* In this case, the RHS is the ROWID of table b-tree and so we also
 94787      ** know that the RHS is non-NULL.  Hence, we combine steps 3 and 4
 94788      ** into a single opcode. */
 94789      sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, rLhs);
 94790      VdbeCoverage(v);
 94791      addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto);  /* Return True */
 94792    }else{
 94793      sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
 94794      if( destIfFalse==destIfNull ){
 94795        /* Combine Step 3 and Step 5 into a single opcode */
 94796        sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse,
 94797                             rLhs, nVector); VdbeCoverage(v);
 94798        goto sqlite3ExprCodeIN_finished;
 94799      }
 94800      /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
 94801      addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0,
 94802                                        rLhs, nVector); VdbeCoverage(v);
 94803    }
 94804  
 94805    /* Step 4.  If the RHS is known to be non-NULL and we did not find
 94806    ** an match on the search above, then the result must be FALSE.
 94807    */
 94808    if( rRhsHasNull && nVector==1 ){
 94809      sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
 94810      VdbeCoverage(v);
 94811    }
 94812  
 94813    /* Step 5.  If we do not care about the difference between NULL and
 94814    ** FALSE, then just return false. 
 94815    */
 94816    if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
 94817  
 94818    /* Step 6: Loop through rows of the RHS.  Compare each row to the LHS.
 94819    ** If any comparison is NULL, then the result is NULL.  If all
 94820    ** comparisons are FALSE then the final result is FALSE.
 94821    **
 94822    ** For a scalar LHS, it is sufficient to check just the first row
 94823    ** of the RHS.
 94824    */
 94825    if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
 94826    addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
 94827    VdbeCoverage(v);
 94828    if( nVector>1 ){
 94829      destNotNull = sqlite3VdbeMakeLabel(v);
 94830    }else{
 94831      /* For nVector==1, combine steps 6 and 7 by immediately returning
 94832      ** FALSE if the first comparison is not NULL */
 94833      destNotNull = destIfFalse;
 94834    }
 94835    for(i=0; i<nVector; i++){
 94836      Expr *p;
 94837      CollSeq *pColl;
 94838      int r3 = sqlite3GetTempReg(pParse);
 94839      p = sqlite3VectorFieldSubexpr(pLeft, i);
 94840      pColl = sqlite3ExprCollSeq(pParse, p);
 94841      sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, i, r3);
 94842      sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
 94843                        (void*)pColl, P4_COLLSEQ);
 94844      VdbeCoverage(v);
 94845      sqlite3ReleaseTempReg(pParse, r3);
 94846    }
 94847    sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
 94848    if( nVector>1 ){
 94849      sqlite3VdbeResolveLabel(v, destNotNull);
 94850      sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, addrTop+1);
 94851      VdbeCoverage(v);
 94852  
 94853      /* Step 7:  If we reach this point, we know that the result must
 94854      ** be false. */
 94855      sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
 94856    }
 94857  
 94858    /* Jumps here in order to return true. */
 94859    sqlite3VdbeJumpHere(v, addrTruthOp);
 94860  
 94861  sqlite3ExprCodeIN_finished:
 94862    if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
 94863    sqlite3ExprCachePop(pParse);
 94864    VdbeComment((v, "end IN expr"));
 94865  sqlite3ExprCodeIN_oom_error:
 94866    sqlite3DbFree(pParse->db, aiMap);
 94867    sqlite3DbFree(pParse->db, zAff);
 94868  }
 94869  #endif /* SQLITE_OMIT_SUBQUERY */
 94870  
 94871  #ifndef SQLITE_OMIT_FLOATING_POINT
 94872  /*
 94873  ** Generate an instruction that will put the floating point
 94874  ** value described by z[0..n-1] into register iMem.
 94875  **
 94876  ** The z[] string will probably not be zero-terminated.  But the 
 94877  ** z[n] character is guaranteed to be something that does not look
 94878  ** like the continuation of the number.
 94879  */
 94880  static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
 94881    if( ALWAYS(z!=0) ){
 94882      double value;
 94883      sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
 94884      assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
 94885      if( negateFlag ) value = -value;
 94886      sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
 94887    }
 94888  }
 94889  #endif
 94890  
 94891  
 94892  /*
 94893  ** Generate an instruction that will put the integer describe by
 94894  ** text z[0..n-1] into register iMem.
 94895  **
 94896  ** Expr.u.zToken is always UTF8 and zero-terminated.
 94897  */
 94898  static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
 94899    Vdbe *v = pParse->pVdbe;
 94900    if( pExpr->flags & EP_IntValue ){
 94901      int i = pExpr->u.iValue;
 94902      assert( i>=0 );
 94903      if( negFlag ) i = -i;
 94904      sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
 94905    }else{
 94906      int c;
 94907      i64 value;
 94908      const char *z = pExpr->u.zToken;
 94909      assert( z!=0 );
 94910      c = sqlite3DecOrHexToI64(z, &value);
 94911      if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
 94912  #ifdef SQLITE_OMIT_FLOATING_POINT
 94913        sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
 94914  #else
 94915  #ifndef SQLITE_OMIT_HEX_INTEGER
 94916        if( sqlite3_strnicmp(z,"0x",2)==0 ){
 94917          sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
 94918        }else
 94919  #endif
 94920        {
 94921          codeReal(v, z, negFlag, iMem);
 94922        }
 94923  #endif
 94924      }else{
 94925        if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
 94926        sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
 94927      }
 94928    }
 94929  }
 94930  
 94931  /*
 94932  ** Erase column-cache entry number i
 94933  */
 94934  static void cacheEntryClear(Parse *pParse, int i){
 94935    if( pParse->aColCache[i].tempReg ){
 94936      if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
 94937        pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
 94938      }
 94939    }
 94940    pParse->nColCache--;
 94941    if( i<pParse->nColCache ){
 94942      pParse->aColCache[i] = pParse->aColCache[pParse->nColCache];
 94943    }
 94944  }
 94945  
 94946  
 94947  /*
 94948  ** Record in the column cache that a particular column from a
 94949  ** particular table is stored in a particular register.
 94950  */
 94951  SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
 94952    int i;
 94953    int minLru;
 94954    int idxLru;
 94955    struct yColCache *p;
 94956  
 94957    /* Unless an error has occurred, register numbers are always positive. */
 94958    assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
 94959    assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
 94960  
 94961    /* The SQLITE_ColumnCache flag disables the column cache.  This is used
 94962    ** for testing only - to verify that SQLite always gets the same answer
 94963    ** with and without the column cache.
 94964    */
 94965    if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
 94966  
 94967    /* First replace any existing entry.
 94968    **
 94969    ** Actually, the way the column cache is currently used, we are guaranteed
 94970    ** that the object will never already be in cache.  Verify this guarantee.
 94971    */
 94972  #ifndef NDEBUG
 94973    for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
 94974      assert( p->iTable!=iTab || p->iColumn!=iCol );
 94975    }
 94976  #endif
 94977  
 94978    /* If the cache is already full, delete the least recently used entry */
 94979    if( pParse->nColCache>=SQLITE_N_COLCACHE ){
 94980      minLru = 0x7fffffff;
 94981      idxLru = -1;
 94982      for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
 94983        if( p->lru<minLru ){
 94984          idxLru = i;
 94985          minLru = p->lru;
 94986        }
 94987      }
 94988      p = &pParse->aColCache[idxLru];
 94989    }else{
 94990      p = &pParse->aColCache[pParse->nColCache++];
 94991    }
 94992  
 94993    /* Add the new entry to the end of the cache */
 94994    p->iLevel = pParse->iCacheLevel;
 94995    p->iTable = iTab;
 94996    p->iColumn = iCol;
 94997    p->iReg = iReg;
 94998    p->tempReg = 0;
 94999    p->lru = pParse->iCacheCnt++;
 95000  }
 95001  
 95002  /*
 95003  ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
 95004  ** Purge the range of registers from the column cache.
 95005  */
 95006  SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
 95007    int i = 0;
 95008    while( i<pParse->nColCache ){
 95009      struct yColCache *p = &pParse->aColCache[i];
 95010      if( p->iReg >= iReg && p->iReg < iReg+nReg ){
 95011        cacheEntryClear(pParse, i);
 95012      }else{
 95013        i++;
 95014      }
 95015    }
 95016  }
 95017  
 95018  /*
 95019  ** Remember the current column cache context.  Any new entries added
 95020  ** added to the column cache after this call are removed when the
 95021  ** corresponding pop occurs.
 95022  */
 95023  SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
 95024    pParse->iCacheLevel++;
 95025  #ifdef SQLITE_DEBUG
 95026    if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
 95027      printf("PUSH to %d\n", pParse->iCacheLevel);
 95028    }
 95029  #endif
 95030  }
 95031  
 95032  /*
 95033  ** Remove from the column cache any entries that were added since the
 95034  ** the previous sqlite3ExprCachePush operation.  In other words, restore
 95035  ** the cache to the state it was in prior the most recent Push.
 95036  */
 95037  SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
 95038    int i = 0;
 95039    assert( pParse->iCacheLevel>=1 );
 95040    pParse->iCacheLevel--;
 95041  #ifdef SQLITE_DEBUG
 95042    if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
 95043      printf("POP  to %d\n", pParse->iCacheLevel);
 95044    }
 95045  #endif
 95046    while( i<pParse->nColCache ){
 95047      if( pParse->aColCache[i].iLevel>pParse->iCacheLevel ){
 95048        cacheEntryClear(pParse, i);
 95049      }else{
 95050        i++;
 95051      }
 95052    }
 95053  }
 95054  
 95055  /*
 95056  ** When a cached column is reused, make sure that its register is
 95057  ** no longer available as a temp register.  ticket #3879:  that same
 95058  ** register might be in the cache in multiple places, so be sure to
 95059  ** get them all.
 95060  */
 95061  static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
 95062    int i;
 95063    struct yColCache *p;
 95064    for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
 95065      if( p->iReg==iReg ){
 95066        p->tempReg = 0;
 95067      }
 95068    }
 95069  }
 95070  
 95071  /* Generate code that will load into register regOut a value that is
 95072  ** appropriate for the iIdxCol-th column of index pIdx.
 95073  */
 95074  SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
 95075    Parse *pParse,  /* The parsing context */
 95076    Index *pIdx,    /* The index whose column is to be loaded */
 95077    int iTabCur,    /* Cursor pointing to a table row */
 95078    int iIdxCol,    /* The column of the index to be loaded */
 95079    int regOut      /* Store the index column value in this register */
 95080  ){
 95081    i16 iTabCol = pIdx->aiColumn[iIdxCol];
 95082    if( iTabCol==XN_EXPR ){
 95083      assert( pIdx->aColExpr );
 95084      assert( pIdx->aColExpr->nExpr>iIdxCol );
 95085      pParse->iSelfTab = iTabCur + 1;
 95086      sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
 95087      pParse->iSelfTab = 0;
 95088    }else{
 95089      sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
 95090                                      iTabCol, regOut);
 95091    }
 95092  }
 95093  
 95094  /*
 95095  ** Generate code to extract the value of the iCol-th column of a table.
 95096  */
 95097  SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
 95098    Vdbe *v,        /* The VDBE under construction */
 95099    Table *pTab,    /* The table containing the value */
 95100    int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
 95101    int iCol,       /* Index of the column to extract */
 95102    int regOut      /* Extract the value into this register */
 95103  ){
 95104    if( pTab==0 ){
 95105      sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
 95106      return;
 95107    }
 95108    if( iCol<0 || iCol==pTab->iPKey ){
 95109      sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
 95110    }else{
 95111      int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
 95112      int x = iCol;
 95113      if( !HasRowid(pTab) && !IsVirtual(pTab) ){
 95114        x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
 95115      }
 95116      sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
 95117    }
 95118    if( iCol>=0 ){
 95119      sqlite3ColumnDefault(v, pTab, iCol, regOut);
 95120    }
 95121  }
 95122  
 95123  /*
 95124  ** Generate code that will extract the iColumn-th column from
 95125  ** table pTab and store the column value in a register. 
 95126  **
 95127  ** An effort is made to store the column value in register iReg.  This
 95128  ** is not garanteeed for GetColumn() - the result can be stored in
 95129  ** any register.  But the result is guaranteed to land in register iReg
 95130  ** for GetColumnToReg().
 95131  **
 95132  ** There must be an open cursor to pTab in iTable when this routine
 95133  ** is called.  If iColumn<0 then code is generated that extracts the rowid.
 95134  */
 95135  SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
 95136    Parse *pParse,   /* Parsing and code generating context */
 95137    Table *pTab,     /* Description of the table we are reading from */
 95138    int iColumn,     /* Index of the table column */
 95139    int iTable,      /* The cursor pointing to the table */
 95140    int iReg,        /* Store results here */
 95141    u8 p5            /* P5 value for OP_Column + FLAGS */
 95142  ){
 95143    Vdbe *v = pParse->pVdbe;
 95144    int i;
 95145    struct yColCache *p;
 95146  
 95147    for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
 95148      if( p->iTable==iTable && p->iColumn==iColumn ){
 95149        p->lru = pParse->iCacheCnt++;
 95150        sqlite3ExprCachePinRegister(pParse, p->iReg);
 95151        return p->iReg;
 95152      }
 95153    }  
 95154    assert( v!=0 );
 95155    sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
 95156    if( p5 ){
 95157      sqlite3VdbeChangeP5(v, p5);
 95158    }else{   
 95159      sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
 95160    }
 95161    return iReg;
 95162  }
 95163  SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(
 95164    Parse *pParse,   /* Parsing and code generating context */
 95165    Table *pTab,     /* Description of the table we are reading from */
 95166    int iColumn,     /* Index of the table column */
 95167    int iTable,      /* The cursor pointing to the table */
 95168    int iReg         /* Store results here */
 95169  ){
 95170    int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
 95171    if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
 95172  }
 95173  
 95174  
 95175  /*
 95176  ** Clear all column cache entries.
 95177  */
 95178  SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
 95179    int i;
 95180  
 95181  #ifdef SQLITE_DEBUG
 95182    if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
 95183      printf("CLEAR\n");
 95184    }
 95185  #endif
 95186    for(i=0; i<pParse->nColCache; i++){
 95187      if( pParse->aColCache[i].tempReg
 95188       && pParse->nTempReg<ArraySize(pParse->aTempReg)
 95189      ){
 95190         pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
 95191      }
 95192    }
 95193    pParse->nColCache = 0;
 95194  }
 95195  
 95196  /*
 95197  ** Record the fact that an affinity change has occurred on iCount
 95198  ** registers starting with iStart.
 95199  */
 95200  SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
 95201    sqlite3ExprCacheRemove(pParse, iStart, iCount);
 95202  }
 95203  
 95204  /*
 95205  ** Generate code to move content from registers iFrom...iFrom+nReg-1
 95206  ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
 95207  */
 95208  SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
 95209    assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
 95210    sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
 95211    sqlite3ExprCacheRemove(pParse, iFrom, nReg);
 95212  }
 95213  
 95214  #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
 95215  /*
 95216  ** Return true if any register in the range iFrom..iTo (inclusive)
 95217  ** is used as part of the column cache.
 95218  **
 95219  ** This routine is used within assert() and testcase() macros only
 95220  ** and does not appear in a normal build.
 95221  */
 95222  static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
 95223    int i;
 95224    struct yColCache *p;
 95225    for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
 95226      int r = p->iReg;
 95227      if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
 95228    }
 95229    return 0;
 95230  }
 95231  #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
 95232  
 95233  
 95234  /*
 95235  ** Convert a scalar expression node to a TK_REGISTER referencing
 95236  ** register iReg.  The caller must ensure that iReg already contains
 95237  ** the correct value for the expression.
 95238  */
 95239  static void exprToRegister(Expr *p, int iReg){
 95240    p->op2 = p->op;
 95241    p->op = TK_REGISTER;
 95242    p->iTable = iReg;
 95243    ExprClearProperty(p, EP_Skip);
 95244  }
 95245  
 95246  /*
 95247  ** Evaluate an expression (either a vector or a scalar expression) and store
 95248  ** the result in continguous temporary registers.  Return the index of
 95249  ** the first register used to store the result.
 95250  **
 95251  ** If the returned result register is a temporary scalar, then also write
 95252  ** that register number into *piFreeable.  If the returned result register
 95253  ** is not a temporary or if the expression is a vector set *piFreeable
 95254  ** to 0.
 95255  */
 95256  static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
 95257    int iResult;
 95258    int nResult = sqlite3ExprVectorSize(p);
 95259    if( nResult==1 ){
 95260      iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
 95261    }else{
 95262      *piFreeable = 0;
 95263      if( p->op==TK_SELECT ){
 95264  #if SQLITE_OMIT_SUBQUERY
 95265        iResult = 0;
 95266  #else
 95267        iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
 95268  #endif
 95269      }else{
 95270        int i;
 95271        iResult = pParse->nMem+1;
 95272        pParse->nMem += nResult;
 95273        for(i=0; i<nResult; i++){
 95274          sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
 95275        }
 95276      }
 95277    }
 95278    return iResult;
 95279  }
 95280  
 95281  
 95282  /*
 95283  ** Generate code into the current Vdbe to evaluate the given
 95284  ** expression.  Attempt to store the results in register "target".
 95285  ** Return the register where results are stored.
 95286  **
 95287  ** With this routine, there is no guarantee that results will
 95288  ** be stored in target.  The result might be stored in some other
 95289  ** register if it is convenient to do so.  The calling function
 95290  ** must check the return code and move the results to the desired
 95291  ** register.
 95292  */
 95293  SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
 95294    Vdbe *v = pParse->pVdbe;  /* The VM under construction */
 95295    int op;                   /* The opcode being coded */
 95296    int inReg = target;       /* Results stored in register inReg */
 95297    int regFree1 = 0;         /* If non-zero free this temporary register */
 95298    int regFree2 = 0;         /* If non-zero free this temporary register */
 95299    int r1, r2;               /* Various register numbers */
 95300    Expr tempX;               /* Temporary expression node */
 95301    int p5 = 0;
 95302  
 95303    assert( target>0 && target<=pParse->nMem );
 95304    if( v==0 ){
 95305      assert( pParse->db->mallocFailed );
 95306      return 0;
 95307    }
 95308  
 95309    if( pExpr==0 ){
 95310      op = TK_NULL;
 95311    }else{
 95312      op = pExpr->op;
 95313    }
 95314    switch( op ){
 95315      case TK_AGG_COLUMN: {
 95316        AggInfo *pAggInfo = pExpr->pAggInfo;
 95317        struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
 95318        if( !pAggInfo->directMode ){
 95319          assert( pCol->iMem>0 );
 95320          return pCol->iMem;
 95321        }else if( pAggInfo->useSortingIdx ){
 95322          sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
 95323                                pCol->iSorterColumn, target);
 95324          return target;
 95325        }
 95326        /* Otherwise, fall thru into the TK_COLUMN case */
 95327      }
 95328      case TK_COLUMN: {
 95329        int iTab = pExpr->iTable;
 95330        if( iTab<0 ){
 95331          if( pParse->iSelfTab<0 ){
 95332            /* Generating CHECK constraints or inserting into partial index */
 95333            return pExpr->iColumn - pParse->iSelfTab;
 95334          }else{
 95335            /* Coding an expression that is part of an index where column names
 95336            ** in the index refer to the table to which the index belongs */
 95337            iTab = pParse->iSelfTab - 1;
 95338          }
 95339        }
 95340        return sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
 95341                                 pExpr->iColumn, iTab, target,
 95342                                 pExpr->op2);
 95343      }
 95344      case TK_INTEGER: {
 95345        codeInteger(pParse, pExpr, 0, target);
 95346        return target;
 95347      }
 95348  #ifndef SQLITE_OMIT_FLOATING_POINT
 95349      case TK_FLOAT: {
 95350        assert( !ExprHasProperty(pExpr, EP_IntValue) );
 95351        codeReal(v, pExpr->u.zToken, 0, target);
 95352        return target;
 95353      }
 95354  #endif
 95355      case TK_STRING: {
 95356        assert( !ExprHasProperty(pExpr, EP_IntValue) );
 95357        sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
 95358        return target;
 95359      }
 95360      case TK_NULL: {
 95361        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
 95362        return target;
 95363      }
 95364  #ifndef SQLITE_OMIT_BLOB_LITERAL
 95365      case TK_BLOB: {
 95366        int n;
 95367        const char *z;
 95368        char *zBlob;
 95369        assert( !ExprHasProperty(pExpr, EP_IntValue) );
 95370        assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
 95371        assert( pExpr->u.zToken[1]=='\'' );
 95372        z = &pExpr->u.zToken[2];
 95373        n = sqlite3Strlen30(z) - 1;
 95374        assert( z[n]=='\'' );
 95375        zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
 95376        sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
 95377        return target;
 95378      }
 95379  #endif
 95380      case TK_VARIABLE: {
 95381        assert( !ExprHasProperty(pExpr, EP_IntValue) );
 95382        assert( pExpr->u.zToken!=0 );
 95383        assert( pExpr->u.zToken[0]!=0 );
 95384        sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
 95385        if( pExpr->u.zToken[1]!=0 ){
 95386          const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
 95387          assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
 95388          pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
 95389          sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
 95390        }
 95391        return target;
 95392      }
 95393      case TK_REGISTER: {
 95394        return pExpr->iTable;
 95395      }
 95396  #ifndef SQLITE_OMIT_CAST
 95397      case TK_CAST: {
 95398        /* Expressions of the form:   CAST(pLeft AS token) */
 95399        inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
 95400        if( inReg!=target ){
 95401          sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
 95402          inReg = target;
 95403        }
 95404        sqlite3VdbeAddOp2(v, OP_Cast, target,
 95405                          sqlite3AffinityType(pExpr->u.zToken, 0));
 95406        testcase( usedAsColumnCache(pParse, inReg, inReg) );
 95407        sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
 95408        return inReg;
 95409      }
 95410  #endif /* SQLITE_OMIT_CAST */
 95411      case TK_IS:
 95412      case TK_ISNOT:
 95413        op = (op==TK_IS) ? TK_EQ : TK_NE;
 95414        p5 = SQLITE_NULLEQ;
 95415        /* fall-through */
 95416      case TK_LT:
 95417      case TK_LE:
 95418      case TK_GT:
 95419      case TK_GE:
 95420      case TK_NE:
 95421      case TK_EQ: {
 95422        Expr *pLeft = pExpr->pLeft;
 95423        if( sqlite3ExprIsVector(pLeft) ){
 95424          codeVectorCompare(pParse, pExpr, target, op, p5);
 95425        }else{
 95426          r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
 95427          r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
 95428          codeCompare(pParse, pLeft, pExpr->pRight, op,
 95429              r1, r2, inReg, SQLITE_STOREP2 | p5);
 95430          assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
 95431          assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
 95432          assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
 95433          assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
 95434          assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
 95435          assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
 95436          testcase( regFree1==0 );
 95437          testcase( regFree2==0 );
 95438        }
 95439        break;
 95440      }
 95441      case TK_AND:
 95442      case TK_OR:
 95443      case TK_PLUS:
 95444      case TK_STAR:
 95445      case TK_MINUS:
 95446      case TK_REM:
 95447      case TK_BITAND:
 95448      case TK_BITOR:
 95449      case TK_SLASH:
 95450      case TK_LSHIFT:
 95451      case TK_RSHIFT: 
 95452      case TK_CONCAT: {
 95453        assert( TK_AND==OP_And );            testcase( op==TK_AND );
 95454        assert( TK_OR==OP_Or );              testcase( op==TK_OR );
 95455        assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
 95456        assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
 95457        assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
 95458        assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
 95459        assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
 95460        assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
 95461        assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
 95462        assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
 95463        assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
 95464        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
 95465        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
 95466        sqlite3VdbeAddOp3(v, op, r2, r1, target);
 95467        testcase( regFree1==0 );
 95468        testcase( regFree2==0 );
 95469        break;
 95470      }
 95471      case TK_UMINUS: {
 95472        Expr *pLeft = pExpr->pLeft;
 95473        assert( pLeft );
 95474        if( pLeft->op==TK_INTEGER ){
 95475          codeInteger(pParse, pLeft, 1, target);
 95476          return target;
 95477  #ifndef SQLITE_OMIT_FLOATING_POINT
 95478        }else if( pLeft->op==TK_FLOAT ){
 95479          assert( !ExprHasProperty(pExpr, EP_IntValue) );
 95480          codeReal(v, pLeft->u.zToken, 1, target);
 95481          return target;
 95482  #endif
 95483        }else{
 95484          tempX.op = TK_INTEGER;
 95485          tempX.flags = EP_IntValue|EP_TokenOnly;
 95486          tempX.u.iValue = 0;
 95487          r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
 95488          r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
 95489          sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
 95490          testcase( regFree2==0 );
 95491        }
 95492        break;
 95493      }
 95494      case TK_BITNOT:
 95495      case TK_NOT: {
 95496        assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
 95497        assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
 95498        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
 95499        testcase( regFree1==0 );
 95500        sqlite3VdbeAddOp2(v, op, r1, inReg);
 95501        break;
 95502      }
 95503      case TK_ISNULL:
 95504      case TK_NOTNULL: {
 95505        int addr;
 95506        assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
 95507        assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
 95508        sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
 95509        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
 95510        testcase( regFree1==0 );
 95511        addr = sqlite3VdbeAddOp1(v, op, r1);
 95512        VdbeCoverageIf(v, op==TK_ISNULL);
 95513        VdbeCoverageIf(v, op==TK_NOTNULL);
 95514        sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
 95515        sqlite3VdbeJumpHere(v, addr);
 95516        break;
 95517      }
 95518      case TK_AGG_FUNCTION: {
 95519        AggInfo *pInfo = pExpr->pAggInfo;
 95520        if( pInfo==0 ){
 95521          assert( !ExprHasProperty(pExpr, EP_IntValue) );
 95522          sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
 95523        }else{
 95524          return pInfo->aFunc[pExpr->iAgg].iMem;
 95525        }
 95526        break;
 95527      }
 95528      case TK_FUNCTION: {
 95529        ExprList *pFarg;       /* List of function arguments */
 95530        int nFarg;             /* Number of function arguments */
 95531        FuncDef *pDef;         /* The function definition object */
 95532        const char *zId;       /* The function name */
 95533        u32 constMask = 0;     /* Mask of function arguments that are constant */
 95534        int i;                 /* Loop counter */
 95535        sqlite3 *db = pParse->db;  /* The database connection */
 95536        u8 enc = ENC(db);      /* The text encoding used by this database */
 95537        CollSeq *pColl = 0;    /* A collating sequence */
 95538  
 95539        if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
 95540          /* SQL functions can be expensive. So try to move constant functions
 95541          ** out of the inner loop, even if that means an extra OP_Copy. */
 95542          return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
 95543        }
 95544        assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
 95545        if( ExprHasProperty(pExpr, EP_TokenOnly) ){
 95546          pFarg = 0;
 95547        }else{
 95548          pFarg = pExpr->x.pList;
 95549        }
 95550        nFarg = pFarg ? pFarg->nExpr : 0;
 95551        assert( !ExprHasProperty(pExpr, EP_IntValue) );
 95552        zId = pExpr->u.zToken;
 95553        pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
 95554  #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
 95555        if( pDef==0 && pParse->explain ){
 95556          pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
 95557        }
 95558  #endif
 95559        if( pDef==0 || pDef->xFinalize!=0 ){
 95560          sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
 95561          break;
 95562        }
 95563  
 95564        /* Attempt a direct implementation of the built-in COALESCE() and
 95565        ** IFNULL() functions.  This avoids unnecessary evaluation of
 95566        ** arguments past the first non-NULL argument.
 95567        */
 95568        if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
 95569          int endCoalesce = sqlite3VdbeMakeLabel(v);
 95570          assert( nFarg>=2 );
 95571          sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
 95572          for(i=1; i<nFarg; i++){
 95573            sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
 95574            VdbeCoverage(v);
 95575            sqlite3ExprCacheRemove(pParse, target, 1);
 95576            sqlite3ExprCachePush(pParse);
 95577            sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
 95578            sqlite3ExprCachePop(pParse);
 95579          }
 95580          sqlite3VdbeResolveLabel(v, endCoalesce);
 95581          break;
 95582        }
 95583  
 95584        /* The UNLIKELY() function is a no-op.  The result is the value
 95585        ** of the first argument.
 95586        */
 95587        if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
 95588          assert( nFarg>=1 );
 95589          return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
 95590        }
 95591  
 95592  #ifdef SQLITE_DEBUG
 95593        /* The AFFINITY() function evaluates to a string that describes
 95594        ** the type affinity of the argument.  This is used for testing of
 95595        ** the SQLite type logic.
 95596        */
 95597        if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
 95598          const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
 95599          char aff;
 95600          assert( nFarg==1 );
 95601          aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
 95602          sqlite3VdbeLoadString(v, target, 
 95603                                aff ? azAff[aff-SQLITE_AFF_BLOB] : "none");
 95604          return target;
 95605        }
 95606  #endif
 95607  
 95608        for(i=0; i<nFarg; i++){
 95609          if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
 95610            testcase( i==31 );
 95611            constMask |= MASKBIT32(i);
 95612          }
 95613          if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
 95614            pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
 95615          }
 95616        }
 95617        if( pFarg ){
 95618          if( constMask ){
 95619            r1 = pParse->nMem+1;
 95620            pParse->nMem += nFarg;
 95621          }else{
 95622            r1 = sqlite3GetTempRange(pParse, nFarg);
 95623          }
 95624  
 95625          /* For length() and typeof() functions with a column argument,
 95626          ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
 95627          ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
 95628          ** loading.
 95629          */
 95630          if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
 95631            u8 exprOp;
 95632            assert( nFarg==1 );
 95633            assert( pFarg->a[0].pExpr!=0 );
 95634            exprOp = pFarg->a[0].pExpr->op;
 95635            if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
 95636              assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
 95637              assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
 95638              testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
 95639              pFarg->a[0].pExpr->op2 = 
 95640                    pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
 95641            }
 95642          }
 95643  
 95644          sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
 95645          sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
 95646                                  SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
 95647          sqlite3ExprCachePop(pParse);      /* Ticket 2ea2425d34be */
 95648        }else{
 95649          r1 = 0;
 95650        }
 95651  #ifndef SQLITE_OMIT_VIRTUALTABLE
 95652        /* Possibly overload the function if the first argument is
 95653        ** a virtual table column.
 95654        **
 95655        ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
 95656        ** second argument, not the first, as the argument to test to
 95657        ** see if it is a column in a virtual table.  This is done because
 95658        ** the left operand of infix functions (the operand we want to
 95659        ** control overloading) ends up as the second argument to the
 95660        ** function.  The expression "A glob B" is equivalent to 
 95661        ** "glob(B,A).  We want to use the A in "A glob B" to test
 95662        ** for function overloading.  But we use the B term in "glob(B,A)".
 95663        */
 95664        if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
 95665          pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
 95666        }else if( nFarg>0 ){
 95667          pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
 95668        }
 95669  #endif
 95670        if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
 95671          if( !pColl ) pColl = db->pDfltColl; 
 95672          sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
 95673        }
 95674        sqlite3VdbeAddOp4(v, pParse->iSelfTab ? OP_PureFunc0 : OP_Function0,
 95675                          constMask, r1, target, (char*)pDef, P4_FUNCDEF);
 95676        sqlite3VdbeChangeP5(v, (u8)nFarg);
 95677        if( nFarg && constMask==0 ){
 95678          sqlite3ReleaseTempRange(pParse, r1, nFarg);
 95679        }
 95680        return target;
 95681      }
 95682  #ifndef SQLITE_OMIT_SUBQUERY
 95683      case TK_EXISTS:
 95684      case TK_SELECT: {
 95685        int nCol;
 95686        testcase( op==TK_EXISTS );
 95687        testcase( op==TK_SELECT );
 95688        if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
 95689          sqlite3SubselectError(pParse, nCol, 1);
 95690        }else{
 95691          return sqlite3CodeSubselect(pParse, pExpr, 0, 0);
 95692        }
 95693        break;
 95694      }
 95695      case TK_SELECT_COLUMN: {
 95696        int n;
 95697        if( pExpr->pLeft->iTable==0 ){
 95698          pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
 95699        }
 95700        assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
 95701        if( pExpr->iTable
 95702         && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft)) 
 95703        ){
 95704          sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
 95705                                  pExpr->iTable, n);
 95706        }
 95707        return pExpr->pLeft->iTable + pExpr->iColumn;
 95708      }
 95709      case TK_IN: {
 95710        int destIfFalse = sqlite3VdbeMakeLabel(v);
 95711        int destIfNull = sqlite3VdbeMakeLabel(v);
 95712        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
 95713        sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
 95714        sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
 95715        sqlite3VdbeResolveLabel(v, destIfFalse);
 95716        sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
 95717        sqlite3VdbeResolveLabel(v, destIfNull);
 95718        return target;
 95719      }
 95720  #endif /* SQLITE_OMIT_SUBQUERY */
 95721  
 95722  
 95723      /*
 95724      **    x BETWEEN y AND z
 95725      **
 95726      ** This is equivalent to
 95727      **
 95728      **    x>=y AND x<=z
 95729      **
 95730      ** X is stored in pExpr->pLeft.
 95731      ** Y is stored in pExpr->pList->a[0].pExpr.
 95732      ** Z is stored in pExpr->pList->a[1].pExpr.
 95733      */
 95734      case TK_BETWEEN: {
 95735        exprCodeBetween(pParse, pExpr, target, 0, 0);
 95736        return target;
 95737      }
 95738      case TK_SPAN:
 95739      case TK_COLLATE: 
 95740      case TK_UPLUS: {
 95741        return sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
 95742      }
 95743  
 95744      case TK_TRIGGER: {
 95745        /* If the opcode is TK_TRIGGER, then the expression is a reference
 95746        ** to a column in the new.* or old.* pseudo-tables available to
 95747        ** trigger programs. In this case Expr.iTable is set to 1 for the
 95748        ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
 95749        ** is set to the column of the pseudo-table to read, or to -1 to
 95750        ** read the rowid field.
 95751        **
 95752        ** The expression is implemented using an OP_Param opcode. The p1
 95753        ** parameter is set to 0 for an old.rowid reference, or to (i+1)
 95754        ** to reference another column of the old.* pseudo-table, where 
 95755        ** i is the index of the column. For a new.rowid reference, p1 is
 95756        ** set to (n+1), where n is the number of columns in each pseudo-table.
 95757        ** For a reference to any other column in the new.* pseudo-table, p1
 95758        ** is set to (n+2+i), where n and i are as defined previously. For
 95759        ** example, if the table on which triggers are being fired is
 95760        ** declared as:
 95761        **
 95762        **   CREATE TABLE t1(a, b);
 95763        **
 95764        ** Then p1 is interpreted as follows:
 95765        **
 95766        **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
 95767        **   p1==1   ->    old.a         p1==4   ->    new.a
 95768        **   p1==2   ->    old.b         p1==5   ->    new.b       
 95769        */
 95770        Table *pTab = pExpr->pTab;
 95771        int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
 95772  
 95773        assert( pExpr->iTable==0 || pExpr->iTable==1 );
 95774        assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
 95775        assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
 95776        assert( p1>=0 && p1<(pTab->nCol*2+2) );
 95777  
 95778        sqlite3VdbeAddOp2(v, OP_Param, p1, target);
 95779        VdbeComment((v, "%s.%s -> $%d",
 95780          (pExpr->iTable ? "new" : "old"),
 95781          (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
 95782          target
 95783        ));
 95784  
 95785  #ifndef SQLITE_OMIT_FLOATING_POINT
 95786        /* If the column has REAL affinity, it may currently be stored as an
 95787        ** integer. Use OP_RealAffinity to make sure it is really real.
 95788        **
 95789        ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
 95790        ** floating point when extracting it from the record.  */
 95791        if( pExpr->iColumn>=0 
 95792         && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
 95793        ){
 95794          sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
 95795        }
 95796  #endif
 95797        break;
 95798      }
 95799  
 95800      case TK_VECTOR: {
 95801        sqlite3ErrorMsg(pParse, "row value misused");
 95802        break;
 95803      }
 95804  
 95805      case TK_IF_NULL_ROW: {
 95806        int addrINR;
 95807        addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
 95808        sqlite3ExprCachePush(pParse);
 95809        inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
 95810        sqlite3ExprCachePop(pParse);
 95811        sqlite3VdbeJumpHere(v, addrINR);
 95812        sqlite3VdbeChangeP3(v, addrINR, inReg);
 95813        break;
 95814      }
 95815  
 95816      /*
 95817      ** Form A:
 95818      **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
 95819      **
 95820      ** Form B:
 95821      **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
 95822      **
 95823      ** Form A is can be transformed into the equivalent form B as follows:
 95824      **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
 95825      **        WHEN x=eN THEN rN ELSE y END
 95826      **
 95827      ** X (if it exists) is in pExpr->pLeft.
 95828      ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
 95829      ** odd.  The Y is also optional.  If the number of elements in x.pList
 95830      ** is even, then Y is omitted and the "otherwise" result is NULL.
 95831      ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
 95832      **
 95833      ** The result of the expression is the Ri for the first matching Ei,
 95834      ** or if there is no matching Ei, the ELSE term Y, or if there is
 95835      ** no ELSE term, NULL.
 95836      */
 95837      default: assert( op==TK_CASE ); {
 95838        int endLabel;                     /* GOTO label for end of CASE stmt */
 95839        int nextCase;                     /* GOTO label for next WHEN clause */
 95840        int nExpr;                        /* 2x number of WHEN terms */
 95841        int i;                            /* Loop counter */
 95842        ExprList *pEList;                 /* List of WHEN terms */
 95843        struct ExprList_item *aListelem;  /* Array of WHEN terms */
 95844        Expr opCompare;                   /* The X==Ei expression */
 95845        Expr *pX;                         /* The X expression */
 95846        Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
 95847        VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
 95848  
 95849        assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
 95850        assert(pExpr->x.pList->nExpr > 0);
 95851        pEList = pExpr->x.pList;
 95852        aListelem = pEList->a;
 95853        nExpr = pEList->nExpr;
 95854        endLabel = sqlite3VdbeMakeLabel(v);
 95855        if( (pX = pExpr->pLeft)!=0 ){
 95856          tempX = *pX;
 95857          testcase( pX->op==TK_COLUMN );
 95858          exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
 95859          testcase( regFree1==0 );
 95860          memset(&opCompare, 0, sizeof(opCompare));
 95861          opCompare.op = TK_EQ;
 95862          opCompare.pLeft = &tempX;
 95863          pTest = &opCompare;
 95864          /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
 95865          ** The value in regFree1 might get SCopy-ed into the file result.
 95866          ** So make sure that the regFree1 register is not reused for other
 95867          ** purposes and possibly overwritten.  */
 95868          regFree1 = 0;
 95869        }
 95870        for(i=0; i<nExpr-1; i=i+2){
 95871          sqlite3ExprCachePush(pParse);
 95872          if( pX ){
 95873            assert( pTest!=0 );
 95874            opCompare.pRight = aListelem[i].pExpr;
 95875          }else{
 95876            pTest = aListelem[i].pExpr;
 95877          }
 95878          nextCase = sqlite3VdbeMakeLabel(v);
 95879          testcase( pTest->op==TK_COLUMN );
 95880          sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
 95881          testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
 95882          sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
 95883          sqlite3VdbeGoto(v, endLabel);
 95884          sqlite3ExprCachePop(pParse);
 95885          sqlite3VdbeResolveLabel(v, nextCase);
 95886        }
 95887        if( (nExpr&1)!=0 ){
 95888          sqlite3ExprCachePush(pParse);
 95889          sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
 95890          sqlite3ExprCachePop(pParse);
 95891        }else{
 95892          sqlite3VdbeAddOp2(v, OP_Null, 0, target);
 95893        }
 95894        assert( pParse->db->mallocFailed || pParse->nErr>0 
 95895             || pParse->iCacheLevel==iCacheLevel );
 95896        sqlite3VdbeResolveLabel(v, endLabel);
 95897        break;
 95898      }
 95899  #ifndef SQLITE_OMIT_TRIGGER
 95900      case TK_RAISE: {
 95901        assert( pExpr->affinity==OE_Rollback 
 95902             || pExpr->affinity==OE_Abort
 95903             || pExpr->affinity==OE_Fail
 95904             || pExpr->affinity==OE_Ignore
 95905        );
 95906        if( !pParse->pTriggerTab ){
 95907          sqlite3ErrorMsg(pParse,
 95908                         "RAISE() may only be used within a trigger-program");
 95909          return 0;
 95910        }
 95911        if( pExpr->affinity==OE_Abort ){
 95912          sqlite3MayAbort(pParse);
 95913        }
 95914        assert( !ExprHasProperty(pExpr, EP_IntValue) );
 95915        if( pExpr->affinity==OE_Ignore ){
 95916          sqlite3VdbeAddOp4(
 95917              v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
 95918          VdbeCoverage(v);
 95919        }else{
 95920          sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
 95921                                pExpr->affinity, pExpr->u.zToken, 0, 0);
 95922        }
 95923  
 95924        break;
 95925      }
 95926  #endif
 95927    }
 95928    sqlite3ReleaseTempReg(pParse, regFree1);
 95929    sqlite3ReleaseTempReg(pParse, regFree2);
 95930    return inReg;
 95931  }
 95932  
 95933  /*
 95934  ** Factor out the code of the given expression to initialization time.
 95935  **
 95936  ** If regDest>=0 then the result is always stored in that register and the
 95937  ** result is not reusable.  If regDest<0 then this routine is free to 
 95938  ** store the value whereever it wants.  The register where the expression 
 95939  ** is stored is returned.  When regDest<0, two identical expressions will
 95940  ** code to the same register.
 95941  */
 95942  SQLITE_PRIVATE int sqlite3ExprCodeAtInit(
 95943    Parse *pParse,    /* Parsing context */
 95944    Expr *pExpr,      /* The expression to code when the VDBE initializes */
 95945    int regDest       /* Store the value in this register */
 95946  ){
 95947    ExprList *p;
 95948    assert( ConstFactorOk(pParse) );
 95949    p = pParse->pConstExpr;
 95950    if( regDest<0 && p ){
 95951      struct ExprList_item *pItem;
 95952      int i;
 95953      for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
 95954        if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
 95955          return pItem->u.iConstExprReg;
 95956        }
 95957      }
 95958    }
 95959    pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
 95960    p = sqlite3ExprListAppend(pParse, p, pExpr);
 95961    if( p ){
 95962       struct ExprList_item *pItem = &p->a[p->nExpr-1];
 95963       pItem->reusable = regDest<0;
 95964       if( regDest<0 ) regDest = ++pParse->nMem;
 95965       pItem->u.iConstExprReg = regDest;
 95966    }
 95967    pParse->pConstExpr = p;
 95968    return regDest;
 95969  }
 95970  
 95971  /*
 95972  ** Generate code to evaluate an expression and store the results
 95973  ** into a register.  Return the register number where the results
 95974  ** are stored.
 95975  **
 95976  ** If the register is a temporary register that can be deallocated,
 95977  ** then write its number into *pReg.  If the result register is not
 95978  ** a temporary, then set *pReg to zero.
 95979  **
 95980  ** If pExpr is a constant, then this routine might generate this
 95981  ** code to fill the register in the initialization section of the
 95982  ** VDBE program, in order to factor it out of the evaluation loop.
 95983  */
 95984  SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
 95985    int r2;
 95986    pExpr = sqlite3ExprSkipCollate(pExpr);
 95987    if( ConstFactorOk(pParse)
 95988     && pExpr->op!=TK_REGISTER
 95989     && sqlite3ExprIsConstantNotJoin(pExpr)
 95990    ){
 95991      *pReg  = 0;
 95992      r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
 95993    }else{
 95994      int r1 = sqlite3GetTempReg(pParse);
 95995      r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
 95996      if( r2==r1 ){
 95997        *pReg = r1;
 95998      }else{
 95999        sqlite3ReleaseTempReg(pParse, r1);
 96000        *pReg = 0;
 96001      }
 96002    }
 96003    return r2;
 96004  }
 96005  
 96006  /*
 96007  ** Generate code that will evaluate expression pExpr and store the
 96008  ** results in register target.  The results are guaranteed to appear
 96009  ** in register target.
 96010  */
 96011  SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
 96012    int inReg;
 96013  
 96014    assert( target>0 && target<=pParse->nMem );
 96015    if( pExpr && pExpr->op==TK_REGISTER ){
 96016      sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
 96017    }else{
 96018      inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
 96019      assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
 96020      if( inReg!=target && pParse->pVdbe ){
 96021        sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
 96022      }
 96023    }
 96024  }
 96025  
 96026  /*
 96027  ** Make a transient copy of expression pExpr and then code it using
 96028  ** sqlite3ExprCode().  This routine works just like sqlite3ExprCode()
 96029  ** except that the input expression is guaranteed to be unchanged.
 96030  */
 96031  SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
 96032    sqlite3 *db = pParse->db;
 96033    pExpr = sqlite3ExprDup(db, pExpr, 0);
 96034    if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
 96035    sqlite3ExprDelete(db, pExpr);
 96036  }
 96037  
 96038  /*
 96039  ** Generate code that will evaluate expression pExpr and store the
 96040  ** results in register target.  The results are guaranteed to appear
 96041  ** in register target.  If the expression is constant, then this routine
 96042  ** might choose to code the expression at initialization time.
 96043  */
 96044  SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
 96045    if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
 96046      sqlite3ExprCodeAtInit(pParse, pExpr, target);
 96047    }else{
 96048      sqlite3ExprCode(pParse, pExpr, target);
 96049    }
 96050  }
 96051  
 96052  /*
 96053  ** Generate code that evaluates the given expression and puts the result
 96054  ** in register target.
 96055  **
 96056  ** Also make a copy of the expression results into another "cache" register
 96057  ** and modify the expression so that the next time it is evaluated,
 96058  ** the result is a copy of the cache register.
 96059  **
 96060  ** This routine is used for expressions that are used multiple 
 96061  ** times.  They are evaluated once and the results of the expression
 96062  ** are reused.
 96063  */
 96064  SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
 96065    Vdbe *v = pParse->pVdbe;
 96066    int iMem;
 96067  
 96068    assert( target>0 );
 96069    assert( pExpr->op!=TK_REGISTER );
 96070    sqlite3ExprCode(pParse, pExpr, target);
 96071    iMem = ++pParse->nMem;
 96072    sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
 96073    exprToRegister(pExpr, iMem);
 96074  }
 96075  
 96076  /*
 96077  ** Generate code that pushes the value of every element of the given
 96078  ** expression list into a sequence of registers beginning at target.
 96079  **
 96080  ** Return the number of elements evaluated.  The number returned will
 96081  ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
 96082  ** is defined.
 96083  **
 96084  ** The SQLITE_ECEL_DUP flag prevents the arguments from being
 96085  ** filled using OP_SCopy.  OP_Copy must be used instead.
 96086  **
 96087  ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
 96088  ** factored out into initialization code.
 96089  **
 96090  ** The SQLITE_ECEL_REF flag means that expressions in the list with
 96091  ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
 96092  ** in registers at srcReg, and so the value can be copied from there.
 96093  ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
 96094  ** are simply omitted rather than being copied from srcReg.
 96095  */
 96096  SQLITE_PRIVATE int sqlite3ExprCodeExprList(
 96097    Parse *pParse,     /* Parsing context */
 96098    ExprList *pList,   /* The expression list to be coded */
 96099    int target,        /* Where to write results */
 96100    int srcReg,        /* Source registers if SQLITE_ECEL_REF */
 96101    u8 flags           /* SQLITE_ECEL_* flags */
 96102  ){
 96103    struct ExprList_item *pItem;
 96104    int i, j, n;
 96105    u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
 96106    Vdbe *v = pParse->pVdbe;
 96107    assert( pList!=0 );
 96108    assert( target>0 );
 96109    assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
 96110    n = pList->nExpr;
 96111    if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
 96112    for(pItem=pList->a, i=0; i<n; i++, pItem++){
 96113      Expr *pExpr = pItem->pExpr;
 96114      if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
 96115        if( flags & SQLITE_ECEL_OMITREF ){
 96116          i--;
 96117          n--;
 96118        }else{
 96119          sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
 96120        }
 96121      }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
 96122        sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
 96123      }else{
 96124        int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
 96125        if( inReg!=target+i ){
 96126          VdbeOp *pOp;
 96127          if( copyOp==OP_Copy
 96128           && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
 96129           && pOp->p1+pOp->p3+1==inReg
 96130           && pOp->p2+pOp->p3+1==target+i
 96131          ){
 96132            pOp->p3++;
 96133          }else{
 96134            sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
 96135          }
 96136        }
 96137      }
 96138    }
 96139    return n;
 96140  }
 96141  
 96142  /*
 96143  ** Generate code for a BETWEEN operator.
 96144  **
 96145  **    x BETWEEN y AND z
 96146  **
 96147  ** The above is equivalent to 
 96148  **
 96149  **    x>=y AND x<=z
 96150  **
 96151  ** Code it as such, taking care to do the common subexpression
 96152  ** elimination of x.
 96153  **
 96154  ** The xJumpIf parameter determines details:
 96155  **
 96156  **    NULL:                   Store the boolean result in reg[dest]
 96157  **    sqlite3ExprIfTrue:      Jump to dest if true
 96158  **    sqlite3ExprIfFalse:     Jump to dest if false
 96159  **
 96160  ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
 96161  */
 96162  static void exprCodeBetween(
 96163    Parse *pParse,    /* Parsing and code generating context */
 96164    Expr *pExpr,      /* The BETWEEN expression */
 96165    int dest,         /* Jump destination or storage location */
 96166    void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
 96167    int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
 96168  ){
 96169   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
 96170    Expr compLeft;    /* The  x>=y  term */
 96171    Expr compRight;   /* The  x<=z  term */
 96172    Expr exprX;       /* The  x  subexpression */
 96173    int regFree1 = 0; /* Temporary use register */
 96174  
 96175  
 96176    memset(&compLeft, 0, sizeof(Expr));
 96177    memset(&compRight, 0, sizeof(Expr));
 96178    memset(&exprAnd, 0, sizeof(Expr));
 96179  
 96180    assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
 96181    exprX = *pExpr->pLeft;
 96182    exprAnd.op = TK_AND;
 96183    exprAnd.pLeft = &compLeft;
 96184    exprAnd.pRight = &compRight;
 96185    compLeft.op = TK_GE;
 96186    compLeft.pLeft = &exprX;
 96187    compLeft.pRight = pExpr->x.pList->a[0].pExpr;
 96188    compRight.op = TK_LE;
 96189    compRight.pLeft = &exprX;
 96190    compRight.pRight = pExpr->x.pList->a[1].pExpr;
 96191    exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
 96192    if( xJump ){
 96193      xJump(pParse, &exprAnd, dest, jumpIfNull);
 96194    }else{
 96195      /* Mark the expression is being from the ON or USING clause of a join
 96196      ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
 96197      ** it into the Parse.pConstExpr list.  We should use a new bit for this,
 96198      ** for clarity, but we are out of bits in the Expr.flags field so we
 96199      ** have to reuse the EP_FromJoin bit.  Bummer. */
 96200      exprX.flags |= EP_FromJoin;
 96201      sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
 96202    }
 96203    sqlite3ReleaseTempReg(pParse, regFree1);
 96204  
 96205    /* Ensure adequate test coverage */
 96206    testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1==0 );
 96207    testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1!=0 );
 96208    testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1==0 );
 96209    testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1!=0 );
 96210    testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
 96211    testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
 96212    testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
 96213    testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
 96214    testcase( xJump==0 );
 96215  }
 96216  
 96217  /*
 96218  ** Generate code for a boolean expression such that a jump is made
 96219  ** to the label "dest" if the expression is true but execution
 96220  ** continues straight thru if the expression is false.
 96221  **
 96222  ** If the expression evaluates to NULL (neither true nor false), then
 96223  ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
 96224  **
 96225  ** This code depends on the fact that certain token values (ex: TK_EQ)
 96226  ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
 96227  ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
 96228  ** the make process cause these values to align.  Assert()s in the code
 96229  ** below verify that the numbers are aligned correctly.
 96230  */
 96231  SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
 96232    Vdbe *v = pParse->pVdbe;
 96233    int op = 0;
 96234    int regFree1 = 0;
 96235    int regFree2 = 0;
 96236    int r1, r2;
 96237  
 96238    assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
 96239    if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
 96240    if( NEVER(pExpr==0) ) return;  /* No way this can happen */
 96241    op = pExpr->op;
 96242    switch( op ){
 96243      case TK_AND: {
 96244        int d2 = sqlite3VdbeMakeLabel(v);
 96245        testcase( jumpIfNull==0 );
 96246        sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
 96247        sqlite3ExprCachePush(pParse);
 96248        sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
 96249        sqlite3VdbeResolveLabel(v, d2);
 96250        sqlite3ExprCachePop(pParse);
 96251        break;
 96252      }
 96253      case TK_OR: {
 96254        testcase( jumpIfNull==0 );
 96255        sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
 96256        sqlite3ExprCachePush(pParse);
 96257        sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
 96258        sqlite3ExprCachePop(pParse);
 96259        break;
 96260      }
 96261      case TK_NOT: {
 96262        testcase( jumpIfNull==0 );
 96263        sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
 96264        break;
 96265      }
 96266      case TK_IS:
 96267      case TK_ISNOT:
 96268        testcase( op==TK_IS );
 96269        testcase( op==TK_ISNOT );
 96270        op = (op==TK_IS) ? TK_EQ : TK_NE;
 96271        jumpIfNull = SQLITE_NULLEQ;
 96272        /* Fall thru */
 96273      case TK_LT:
 96274      case TK_LE:
 96275      case TK_GT:
 96276      case TK_GE:
 96277      case TK_NE:
 96278      case TK_EQ: {
 96279        if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
 96280        testcase( jumpIfNull==0 );
 96281        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
 96282        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
 96283        codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
 96284                    r1, r2, dest, jumpIfNull);
 96285        assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
 96286        assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
 96287        assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
 96288        assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
 96289        assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
 96290        VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
 96291        VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
 96292        assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
 96293        VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
 96294        VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
 96295        testcase( regFree1==0 );
 96296        testcase( regFree2==0 );
 96297        break;
 96298      }
 96299      case TK_ISNULL:
 96300      case TK_NOTNULL: {
 96301        assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
 96302        assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
 96303        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
 96304        sqlite3VdbeAddOp2(v, op, r1, dest);
 96305        VdbeCoverageIf(v, op==TK_ISNULL);
 96306        VdbeCoverageIf(v, op==TK_NOTNULL);
 96307        testcase( regFree1==0 );
 96308        break;
 96309      }
 96310      case TK_BETWEEN: {
 96311        testcase( jumpIfNull==0 );
 96312        exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
 96313        break;
 96314      }
 96315  #ifndef SQLITE_OMIT_SUBQUERY
 96316      case TK_IN: {
 96317        int destIfFalse = sqlite3VdbeMakeLabel(v);
 96318        int destIfNull = jumpIfNull ? dest : destIfFalse;
 96319        sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
 96320        sqlite3VdbeGoto(v, dest);
 96321        sqlite3VdbeResolveLabel(v, destIfFalse);
 96322        break;
 96323      }
 96324  #endif
 96325      default: {
 96326      default_expr:
 96327        if( exprAlwaysTrue(pExpr) ){
 96328          sqlite3VdbeGoto(v, dest);
 96329        }else if( exprAlwaysFalse(pExpr) ){
 96330          /* No-op */
 96331        }else{
 96332          r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
 96333          sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
 96334          VdbeCoverage(v);
 96335          testcase( regFree1==0 );
 96336          testcase( jumpIfNull==0 );
 96337        }
 96338        break;
 96339      }
 96340    }
 96341    sqlite3ReleaseTempReg(pParse, regFree1);
 96342    sqlite3ReleaseTempReg(pParse, regFree2);  
 96343  }
 96344  
 96345  /*
 96346  ** Generate code for a boolean expression such that a jump is made
 96347  ** to the label "dest" if the expression is false but execution
 96348  ** continues straight thru if the expression is true.
 96349  **
 96350  ** If the expression evaluates to NULL (neither true nor false) then
 96351  ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
 96352  ** is 0.
 96353  */
 96354  SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
 96355    Vdbe *v = pParse->pVdbe;
 96356    int op = 0;
 96357    int regFree1 = 0;
 96358    int regFree2 = 0;
 96359    int r1, r2;
 96360  
 96361    assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
 96362    if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
 96363    if( pExpr==0 )    return;
 96364  
 96365    /* The value of pExpr->op and op are related as follows:
 96366    **
 96367    **       pExpr->op            op
 96368    **       ---------          ----------
 96369    **       TK_ISNULL          OP_NotNull
 96370    **       TK_NOTNULL         OP_IsNull
 96371    **       TK_NE              OP_Eq
 96372    **       TK_EQ              OP_Ne
 96373    **       TK_GT              OP_Le
 96374    **       TK_LE              OP_Gt
 96375    **       TK_GE              OP_Lt
 96376    **       TK_LT              OP_Ge
 96377    **
 96378    ** For other values of pExpr->op, op is undefined and unused.
 96379    ** The value of TK_ and OP_ constants are arranged such that we
 96380    ** can compute the mapping above using the following expression.
 96381    ** Assert()s verify that the computation is correct.
 96382    */
 96383    op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
 96384  
 96385    /* Verify correct alignment of TK_ and OP_ constants
 96386    */
 96387    assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
 96388    assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
 96389    assert( pExpr->op!=TK_NE || op==OP_Eq );
 96390    assert( pExpr->op!=TK_EQ || op==OP_Ne );
 96391    assert( pExpr->op!=TK_LT || op==OP_Ge );
 96392    assert( pExpr->op!=TK_LE || op==OP_Gt );
 96393    assert( pExpr->op!=TK_GT || op==OP_Le );
 96394    assert( pExpr->op!=TK_GE || op==OP_Lt );
 96395  
 96396    switch( pExpr->op ){
 96397      case TK_AND: {
 96398        testcase( jumpIfNull==0 );
 96399        sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
 96400        sqlite3ExprCachePush(pParse);
 96401        sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
 96402        sqlite3ExprCachePop(pParse);
 96403        break;
 96404      }
 96405      case TK_OR: {
 96406        int d2 = sqlite3VdbeMakeLabel(v);
 96407        testcase( jumpIfNull==0 );
 96408        sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
 96409        sqlite3ExprCachePush(pParse);
 96410        sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
 96411        sqlite3VdbeResolveLabel(v, d2);
 96412        sqlite3ExprCachePop(pParse);
 96413        break;
 96414      }
 96415      case TK_NOT: {
 96416        testcase( jumpIfNull==0 );
 96417        sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
 96418        break;
 96419      }
 96420      case TK_IS:
 96421      case TK_ISNOT:
 96422        testcase( pExpr->op==TK_IS );
 96423        testcase( pExpr->op==TK_ISNOT );
 96424        op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
 96425        jumpIfNull = SQLITE_NULLEQ;
 96426        /* Fall thru */
 96427      case TK_LT:
 96428      case TK_LE:
 96429      case TK_GT:
 96430      case TK_GE:
 96431      case TK_NE:
 96432      case TK_EQ: {
 96433        if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
 96434        testcase( jumpIfNull==0 );
 96435        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
 96436        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
 96437        codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
 96438                    r1, r2, dest, jumpIfNull);
 96439        assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
 96440        assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
 96441        assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
 96442        assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
 96443        assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
 96444        VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
 96445        VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
 96446        assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
 96447        VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
 96448        VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
 96449        testcase( regFree1==0 );
 96450        testcase( regFree2==0 );
 96451        break;
 96452      }
 96453      case TK_ISNULL:
 96454      case TK_NOTNULL: {
 96455        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
 96456        sqlite3VdbeAddOp2(v, op, r1, dest);
 96457        testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
 96458        testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
 96459        testcase( regFree1==0 );
 96460        break;
 96461      }
 96462      case TK_BETWEEN: {
 96463        testcase( jumpIfNull==0 );
 96464        exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
 96465        break;
 96466      }
 96467  #ifndef SQLITE_OMIT_SUBQUERY
 96468      case TK_IN: {
 96469        if( jumpIfNull ){
 96470          sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
 96471        }else{
 96472          int destIfNull = sqlite3VdbeMakeLabel(v);
 96473          sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
 96474          sqlite3VdbeResolveLabel(v, destIfNull);
 96475        }
 96476        break;
 96477      }
 96478  #endif
 96479      default: {
 96480      default_expr: 
 96481        if( exprAlwaysFalse(pExpr) ){
 96482          sqlite3VdbeGoto(v, dest);
 96483        }else if( exprAlwaysTrue(pExpr) ){
 96484          /* no-op */
 96485        }else{
 96486          r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
 96487          sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
 96488          VdbeCoverage(v);
 96489          testcase( regFree1==0 );
 96490          testcase( jumpIfNull==0 );
 96491        }
 96492        break;
 96493      }
 96494    }
 96495    sqlite3ReleaseTempReg(pParse, regFree1);
 96496    sqlite3ReleaseTempReg(pParse, regFree2);
 96497  }
 96498  
 96499  /*
 96500  ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
 96501  ** code generation, and that copy is deleted after code generation. This
 96502  ** ensures that the original pExpr is unchanged.
 96503  */
 96504  SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
 96505    sqlite3 *db = pParse->db;
 96506    Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
 96507    if( db->mallocFailed==0 ){
 96508      sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
 96509    }
 96510    sqlite3ExprDelete(db, pCopy);
 96511  }
 96512  
 96513  /*
 96514  ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
 96515  ** type of expression.
 96516  **
 96517  ** If pExpr is a simple SQL value - an integer, real, string, blob
 96518  ** or NULL value - then the VDBE currently being prepared is configured
 96519  ** to re-prepare each time a new value is bound to variable pVar.
 96520  **
 96521  ** Additionally, if pExpr is a simple SQL value and the value is the
 96522  ** same as that currently bound to variable pVar, non-zero is returned.
 96523  ** Otherwise, if the values are not the same or if pExpr is not a simple
 96524  ** SQL value, zero is returned.
 96525  */
 96526  static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
 96527    int res = 0;
 96528    int iVar;
 96529    sqlite3_value *pL, *pR = 0;
 96530    
 96531    sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
 96532    if( pR ){
 96533      iVar = pVar->iColumn;
 96534      sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
 96535      pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
 96536      if( pL ){
 96537        if( sqlite3_value_type(pL)==SQLITE_TEXT ){
 96538          sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
 96539        }
 96540        res =  0==sqlite3MemCompare(pL, pR, 0);
 96541      }
 96542      sqlite3ValueFree(pR);
 96543      sqlite3ValueFree(pL);
 96544    }
 96545  
 96546    return res;
 96547  }
 96548  
 96549  /*
 96550  ** Do a deep comparison of two expression trees.  Return 0 if the two
 96551  ** expressions are completely identical.  Return 1 if they differ only
 96552  ** by a COLLATE operator at the top level.  Return 2 if there are differences
 96553  ** other than the top-level COLLATE operator.
 96554  **
 96555  ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
 96556  ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
 96557  **
 96558  ** The pA side might be using TK_REGISTER.  If that is the case and pB is
 96559  ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
 96560  **
 96561  ** Sometimes this routine will return 2 even if the two expressions
 96562  ** really are equivalent.  If we cannot prove that the expressions are
 96563  ** identical, we return 2 just to be safe.  So if this routine
 96564  ** returns 2, then you do not really know for certain if the two
 96565  ** expressions are the same.  But if you get a 0 or 1 return, then you
 96566  ** can be sure the expressions are the same.  In the places where
 96567  ** this routine is used, it does not hurt to get an extra 2 - that
 96568  ** just might result in some slightly slower code.  But returning
 96569  ** an incorrect 0 or 1 could lead to a malfunction.
 96570  **
 96571  ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
 96572  ** pParse->pReprepare can be matched against literals in pB.  The 
 96573  ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
 96574  ** If pParse is NULL (the normal case) then any TK_VARIABLE term in 
 96575  ** Argument pParse should normally be NULL. If it is not NULL and pA or
 96576  ** pB causes a return value of 2.
 96577  */
 96578  SQLITE_PRIVATE int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
 96579    u32 combinedFlags;
 96580    if( pA==0 || pB==0 ){
 96581      return pB==pA ? 0 : 2;
 96582    }
 96583    if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
 96584      return 0;
 96585    }
 96586    combinedFlags = pA->flags | pB->flags;
 96587    if( combinedFlags & EP_IntValue ){
 96588      if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
 96589        return 0;
 96590      }
 96591      return 2;
 96592    }
 96593    if( pA->op!=pB->op ){
 96594      if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
 96595        return 1;
 96596      }
 96597      if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
 96598        return 1;
 96599      }
 96600      return 2;
 96601    }
 96602    if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
 96603      if( pA->op==TK_FUNCTION ){
 96604        if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
 96605      }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
 96606        return pA->op==TK_COLLATE ? 1 : 2;
 96607      }
 96608    }
 96609    if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
 96610    if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
 96611      if( combinedFlags & EP_xIsSelect ) return 2;
 96612      if( sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
 96613      if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
 96614      if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
 96615      if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
 96616        if( pA->iColumn!=pB->iColumn ) return 2;
 96617        if( pA->iTable!=pB->iTable 
 96618         && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
 96619      }
 96620    }
 96621    return 0;
 96622  }
 96623  
 96624  /*
 96625  ** Compare two ExprList objects.  Return 0 if they are identical and 
 96626  ** non-zero if they differ in any way.
 96627  **
 96628  ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
 96629  ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
 96630  **
 96631  ** This routine might return non-zero for equivalent ExprLists.  The
 96632  ** only consequence will be disabled optimizations.  But this routine
 96633  ** must never return 0 if the two ExprList objects are different, or
 96634  ** a malfunction will result.
 96635  **
 96636  ** Two NULL pointers are considered to be the same.  But a NULL pointer
 96637  ** always differs from a non-NULL pointer.
 96638  */
 96639  SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
 96640    int i;
 96641    if( pA==0 && pB==0 ) return 0;
 96642    if( pA==0 || pB==0 ) return 1;
 96643    if( pA->nExpr!=pB->nExpr ) return 1;
 96644    for(i=0; i<pA->nExpr; i++){
 96645      Expr *pExprA = pA->a[i].pExpr;
 96646      Expr *pExprB = pB->a[i].pExpr;
 96647      if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
 96648      if( sqlite3ExprCompare(0, pExprA, pExprB, iTab) ) return 1;
 96649    }
 96650    return 0;
 96651  }
 96652  
 96653  /*
 96654  ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
 96655  ** are ignored.
 96656  */
 96657  SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
 96658    return sqlite3ExprCompare(0,
 96659               sqlite3ExprSkipCollate(pA),
 96660               sqlite3ExprSkipCollate(pB),
 96661               iTab);
 96662  }
 96663  
 96664  /*
 96665  ** Return true if we can prove the pE2 will always be true if pE1 is
 96666  ** true.  Return false if we cannot complete the proof or if pE2 might
 96667  ** be false.  Examples:
 96668  **
 96669  **     pE1: x==5       pE2: x==5             Result: true
 96670  **     pE1: x>0        pE2: x==5             Result: false
 96671  **     pE1: x=21       pE2: x=21 OR y=43     Result: true
 96672  **     pE1: x!=123     pE2: x IS NOT NULL    Result: true
 96673  **     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
 96674  **     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
 96675  **     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
 96676  **
 96677  ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
 96678  ** Expr.iTable<0 then assume a table number given by iTab.
 96679  **
 96680  ** If pParse is not NULL, then the values of bound variables in pE1 are 
 96681  ** compared against literal values in pE2 and pParse->pVdbe->expmask is
 96682  ** modified to record which bound variables are referenced.  If pParse 
 96683  ** is NULL, then false will be returned if pE1 contains any bound variables.
 96684  **
 96685  ** When in doubt, return false.  Returning true might give a performance
 96686  ** improvement.  Returning false might cause a performance reduction, but
 96687  ** it will always give the correct answer and is hence always safe.
 96688  */
 96689  SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
 96690    if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
 96691      return 1;
 96692    }
 96693    if( pE2->op==TK_OR
 96694     && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
 96695               || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
 96696    ){
 96697      return 1;
 96698    }
 96699    if( pE2->op==TK_NOTNULL && pE1->op!=TK_ISNULL && pE1->op!=TK_IS ){
 96700      Expr *pX = sqlite3ExprSkipCollate(pE1->pLeft);
 96701      testcase( pX!=pE1->pLeft );
 96702      if( sqlite3ExprCompare(pParse, pX, pE2->pLeft, iTab)==0 ) return 1;
 96703    }
 96704    return 0;
 96705  }
 96706  
 96707  /*
 96708  ** An instance of the following structure is used by the tree walker
 96709  ** to determine if an expression can be evaluated by reference to the
 96710  ** index only, without having to do a search for the corresponding
 96711  ** table entry.  The IdxCover.pIdx field is the index.  IdxCover.iCur
 96712  ** is the cursor for the table.
 96713  */
 96714  struct IdxCover {
 96715    Index *pIdx;     /* The index to be tested for coverage */
 96716    int iCur;        /* Cursor number for the table corresponding to the index */
 96717  };
 96718  
 96719  /*
 96720  ** Check to see if there are references to columns in table 
 96721  ** pWalker->u.pIdxCover->iCur can be satisfied using the index
 96722  ** pWalker->u.pIdxCover->pIdx.
 96723  */
 96724  static int exprIdxCover(Walker *pWalker, Expr *pExpr){
 96725    if( pExpr->op==TK_COLUMN
 96726     && pExpr->iTable==pWalker->u.pIdxCover->iCur
 96727     && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
 96728    ){
 96729      pWalker->eCode = 1;
 96730      return WRC_Abort;
 96731    }
 96732    return WRC_Continue;
 96733  }
 96734  
 96735  /*
 96736  ** Determine if an index pIdx on table with cursor iCur contains will
 96737  ** the expression pExpr.  Return true if the index does cover the
 96738  ** expression and false if the pExpr expression references table columns
 96739  ** that are not found in the index pIdx.
 96740  **
 96741  ** An index covering an expression means that the expression can be
 96742  ** evaluated using only the index and without having to lookup the
 96743  ** corresponding table entry.
 96744  */
 96745  SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
 96746    Expr *pExpr,        /* The index to be tested */
 96747    int iCur,           /* The cursor number for the corresponding table */
 96748    Index *pIdx         /* The index that might be used for coverage */
 96749  ){
 96750    Walker w;
 96751    struct IdxCover xcov;
 96752    memset(&w, 0, sizeof(w));
 96753    xcov.iCur = iCur;
 96754    xcov.pIdx = pIdx;
 96755    w.xExprCallback = exprIdxCover;
 96756    w.u.pIdxCover = &xcov;
 96757    sqlite3WalkExpr(&w, pExpr);
 96758    return !w.eCode;
 96759  }
 96760  
 96761  
 96762  /*
 96763  ** An instance of the following structure is used by the tree walker
 96764  ** to count references to table columns in the arguments of an 
 96765  ** aggregate function, in order to implement the
 96766  ** sqlite3FunctionThisSrc() routine.
 96767  */
 96768  struct SrcCount {
 96769    SrcList *pSrc;   /* One particular FROM clause in a nested query */
 96770    int nThis;       /* Number of references to columns in pSrcList */
 96771    int nOther;      /* Number of references to columns in other FROM clauses */
 96772  };
 96773  
 96774  /*
 96775  ** Count the number of references to columns.
 96776  */
 96777  static int exprSrcCount(Walker *pWalker, Expr *pExpr){
 96778    /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
 96779    ** is always called before sqlite3ExprAnalyzeAggregates() and so the
 96780    ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
 96781    ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
 96782    ** NEVER() will need to be removed. */
 96783    if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
 96784      int i;
 96785      struct SrcCount *p = pWalker->u.pSrcCount;
 96786      SrcList *pSrc = p->pSrc;
 96787      int nSrc = pSrc ? pSrc->nSrc : 0;
 96788      for(i=0; i<nSrc; i++){
 96789        if( pExpr->iTable==pSrc->a[i].iCursor ) break;
 96790      }
 96791      if( i<nSrc ){
 96792        p->nThis++;
 96793      }else{
 96794        p->nOther++;
 96795      }
 96796    }
 96797    return WRC_Continue;
 96798  }
 96799  
 96800  /*
 96801  ** Determine if any of the arguments to the pExpr Function reference
 96802  ** pSrcList.  Return true if they do.  Also return true if the function
 96803  ** has no arguments or has only constant arguments.  Return false if pExpr
 96804  ** references columns but not columns of tables found in pSrcList.
 96805  */
 96806  SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
 96807    Walker w;
 96808    struct SrcCount cnt;
 96809    assert( pExpr->op==TK_AGG_FUNCTION );
 96810    w.xExprCallback = exprSrcCount;
 96811    w.xSelectCallback = 0;
 96812    w.u.pSrcCount = &cnt;
 96813    cnt.pSrc = pSrcList;
 96814    cnt.nThis = 0;
 96815    cnt.nOther = 0;
 96816    sqlite3WalkExprList(&w, pExpr->x.pList);
 96817    return cnt.nThis>0 || cnt.nOther==0;
 96818  }
 96819  
 96820  /*
 96821  ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
 96822  ** the new element.  Return a negative number if malloc fails.
 96823  */
 96824  static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
 96825    int i;
 96826    pInfo->aCol = sqlite3ArrayAllocate(
 96827         db,
 96828         pInfo->aCol,
 96829         sizeof(pInfo->aCol[0]),
 96830         &pInfo->nColumn,
 96831         &i
 96832    );
 96833    return i;
 96834  }    
 96835  
 96836  /*
 96837  ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
 96838  ** the new element.  Return a negative number if malloc fails.
 96839  */
 96840  static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
 96841    int i;
 96842    pInfo->aFunc = sqlite3ArrayAllocate(
 96843         db, 
 96844         pInfo->aFunc,
 96845         sizeof(pInfo->aFunc[0]),
 96846         &pInfo->nFunc,
 96847         &i
 96848    );
 96849    return i;
 96850  }    
 96851  
 96852  /*
 96853  ** This is the xExprCallback for a tree walker.  It is used to
 96854  ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
 96855  ** for additional information.
 96856  */
 96857  static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
 96858    int i;
 96859    NameContext *pNC = pWalker->u.pNC;
 96860    Parse *pParse = pNC->pParse;
 96861    SrcList *pSrcList = pNC->pSrcList;
 96862    AggInfo *pAggInfo = pNC->pAggInfo;
 96863  
 96864    switch( pExpr->op ){
 96865      case TK_AGG_COLUMN:
 96866      case TK_COLUMN: {
 96867        testcase( pExpr->op==TK_AGG_COLUMN );
 96868        testcase( pExpr->op==TK_COLUMN );
 96869        /* Check to see if the column is in one of the tables in the FROM
 96870        ** clause of the aggregate query */
 96871        if( ALWAYS(pSrcList!=0) ){
 96872          struct SrcList_item *pItem = pSrcList->a;
 96873          for(i=0; i<pSrcList->nSrc; i++, pItem++){
 96874            struct AggInfo_col *pCol;
 96875            assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
 96876            if( pExpr->iTable==pItem->iCursor ){
 96877              /* If we reach this point, it means that pExpr refers to a table
 96878              ** that is in the FROM clause of the aggregate query.  
 96879              **
 96880              ** Make an entry for the column in pAggInfo->aCol[] if there
 96881              ** is not an entry there already.
 96882              */
 96883              int k;
 96884              pCol = pAggInfo->aCol;
 96885              for(k=0; k<pAggInfo->nColumn; k++, pCol++){
 96886                if( pCol->iTable==pExpr->iTable &&
 96887                    pCol->iColumn==pExpr->iColumn ){
 96888                  break;
 96889                }
 96890              }
 96891              if( (k>=pAggInfo->nColumn)
 96892               && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
 96893              ){
 96894                pCol = &pAggInfo->aCol[k];
 96895                pCol->pTab = pExpr->pTab;
 96896                pCol->iTable = pExpr->iTable;
 96897                pCol->iColumn = pExpr->iColumn;
 96898                pCol->iMem = ++pParse->nMem;
 96899                pCol->iSorterColumn = -1;
 96900                pCol->pExpr = pExpr;
 96901                if( pAggInfo->pGroupBy ){
 96902                  int j, n;
 96903                  ExprList *pGB = pAggInfo->pGroupBy;
 96904                  struct ExprList_item *pTerm = pGB->a;
 96905                  n = pGB->nExpr;
 96906                  for(j=0; j<n; j++, pTerm++){
 96907                    Expr *pE = pTerm->pExpr;
 96908                    if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
 96909                        pE->iColumn==pExpr->iColumn ){
 96910                      pCol->iSorterColumn = j;
 96911                      break;
 96912                    }
 96913                  }
 96914                }
 96915                if( pCol->iSorterColumn<0 ){
 96916                  pCol->iSorterColumn = pAggInfo->nSortingColumn++;
 96917                }
 96918              }
 96919              /* There is now an entry for pExpr in pAggInfo->aCol[] (either
 96920              ** because it was there before or because we just created it).
 96921              ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
 96922              ** pAggInfo->aCol[] entry.
 96923              */
 96924              ExprSetVVAProperty(pExpr, EP_NoReduce);
 96925              pExpr->pAggInfo = pAggInfo;
 96926              pExpr->op = TK_AGG_COLUMN;
 96927              pExpr->iAgg = (i16)k;
 96928              break;
 96929            } /* endif pExpr->iTable==pItem->iCursor */
 96930          } /* end loop over pSrcList */
 96931        }
 96932        return WRC_Prune;
 96933      }
 96934      case TK_AGG_FUNCTION: {
 96935        if( (pNC->ncFlags & NC_InAggFunc)==0
 96936         && pWalker->walkerDepth==pExpr->op2
 96937        ){
 96938          /* Check to see if pExpr is a duplicate of another aggregate 
 96939          ** function that is already in the pAggInfo structure
 96940          */
 96941          struct AggInfo_func *pItem = pAggInfo->aFunc;
 96942          for(i=0; i<pAggInfo->nFunc; i++, pItem++){
 96943            if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){
 96944              break;
 96945            }
 96946          }
 96947          if( i>=pAggInfo->nFunc ){
 96948            /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
 96949            */
 96950            u8 enc = ENC(pParse->db);
 96951            i = addAggInfoFunc(pParse->db, pAggInfo);
 96952            if( i>=0 ){
 96953              assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
 96954              pItem = &pAggInfo->aFunc[i];
 96955              pItem->pExpr = pExpr;
 96956              pItem->iMem = ++pParse->nMem;
 96957              assert( !ExprHasProperty(pExpr, EP_IntValue) );
 96958              pItem->pFunc = sqlite3FindFunction(pParse->db,
 96959                     pExpr->u.zToken, 
 96960                     pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
 96961              if( pExpr->flags & EP_Distinct ){
 96962                pItem->iDistinct = pParse->nTab++;
 96963              }else{
 96964                pItem->iDistinct = -1;
 96965              }
 96966            }
 96967          }
 96968          /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
 96969          */
 96970          assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
 96971          ExprSetVVAProperty(pExpr, EP_NoReduce);
 96972          pExpr->iAgg = (i16)i;
 96973          pExpr->pAggInfo = pAggInfo;
 96974          return WRC_Prune;
 96975        }else{
 96976          return WRC_Continue;
 96977        }
 96978      }
 96979    }
 96980    return WRC_Continue;
 96981  }
 96982  static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
 96983    UNUSED_PARAMETER(pSelect);
 96984    pWalker->walkerDepth++;
 96985    return WRC_Continue;
 96986  }
 96987  static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
 96988    UNUSED_PARAMETER(pSelect);
 96989    pWalker->walkerDepth--;
 96990  }
 96991  
 96992  /*
 96993  ** Analyze the pExpr expression looking for aggregate functions and
 96994  ** for variables that need to be added to AggInfo object that pNC->pAggInfo
 96995  ** points to.  Additional entries are made on the AggInfo object as
 96996  ** necessary.
 96997  **
 96998  ** This routine should only be called after the expression has been
 96999  ** analyzed by sqlite3ResolveExprNames().
 97000  */
 97001  SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
 97002    Walker w;
 97003    w.xExprCallback = analyzeAggregate;
 97004    w.xSelectCallback = analyzeAggregatesInSelect;
 97005    w.xSelectCallback2 = analyzeAggregatesInSelectEnd;
 97006    w.walkerDepth = 0;
 97007    w.u.pNC = pNC;
 97008    assert( pNC->pSrcList!=0 );
 97009    sqlite3WalkExpr(&w, pExpr);
 97010  }
 97011  
 97012  /*
 97013  ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
 97014  ** expression list.  Return the number of errors.
 97015  **
 97016  ** If an error is found, the analysis is cut short.
 97017  */
 97018  SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
 97019    struct ExprList_item *pItem;
 97020    int i;
 97021    if( pList ){
 97022      for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
 97023        sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
 97024      }
 97025    }
 97026  }
 97027  
 97028  /*
 97029  ** Allocate a single new register for use to hold some intermediate result.
 97030  */
 97031  SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
 97032    if( pParse->nTempReg==0 ){
 97033      return ++pParse->nMem;
 97034    }
 97035    return pParse->aTempReg[--pParse->nTempReg];
 97036  }
 97037  
 97038  /*
 97039  ** Deallocate a register, making available for reuse for some other
 97040  ** purpose.
 97041  **
 97042  ** If a register is currently being used by the column cache, then
 97043  ** the deallocation is deferred until the column cache line that uses
 97044  ** the register becomes stale.
 97045  */
 97046  SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
 97047    if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
 97048      int i;
 97049      struct yColCache *p;
 97050      for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
 97051        if( p->iReg==iReg ){
 97052          p->tempReg = 1;
 97053          return;
 97054        }
 97055      }
 97056      pParse->aTempReg[pParse->nTempReg++] = iReg;
 97057    }
 97058  }
 97059  
 97060  /*
 97061  ** Allocate or deallocate a block of nReg consecutive registers.
 97062  */
 97063  SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
 97064    int i, n;
 97065    if( nReg==1 ) return sqlite3GetTempReg(pParse);
 97066    i = pParse->iRangeReg;
 97067    n = pParse->nRangeReg;
 97068    if( nReg<=n ){
 97069      assert( !usedAsColumnCache(pParse, i, i+n-1) );
 97070      pParse->iRangeReg += nReg;
 97071      pParse->nRangeReg -= nReg;
 97072    }else{
 97073      i = pParse->nMem+1;
 97074      pParse->nMem += nReg;
 97075    }
 97076    return i;
 97077  }
 97078  SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
 97079    if( nReg==1 ){
 97080      sqlite3ReleaseTempReg(pParse, iReg);
 97081      return;
 97082    }
 97083    sqlite3ExprCacheRemove(pParse, iReg, nReg);
 97084    if( nReg>pParse->nRangeReg ){
 97085      pParse->nRangeReg = nReg;
 97086      pParse->iRangeReg = iReg;
 97087    }
 97088  }
 97089  
 97090  /*
 97091  ** Mark all temporary registers as being unavailable for reuse.
 97092  */
 97093  SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
 97094    pParse->nTempReg = 0;
 97095    pParse->nRangeReg = 0;
 97096  }
 97097  
 97098  /*
 97099  ** Validate that no temporary register falls within the range of
 97100  ** iFirst..iLast, inclusive.  This routine is only call from within assert()
 97101  ** statements.
 97102  */
 97103  #ifdef SQLITE_DEBUG
 97104  SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
 97105    int i;
 97106    if( pParse->nRangeReg>0
 97107     && pParse->iRangeReg+pParse->nRangeReg > iFirst
 97108     && pParse->iRangeReg <= iLast
 97109    ){
 97110       return 0;
 97111    }
 97112    for(i=0; i<pParse->nTempReg; i++){
 97113      if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
 97114        return 0;
 97115      }
 97116    }
 97117    return 1;
 97118  }
 97119  #endif /* SQLITE_DEBUG */
 97120  
 97121  /************** End of expr.c ************************************************/
 97122  /************** Begin file alter.c *******************************************/
 97123  /*
 97124  ** 2005 February 15
 97125  **
 97126  ** The author disclaims copyright to this source code.  In place of
 97127  ** a legal notice, here is a blessing:
 97128  **
 97129  **    May you do good and not evil.
 97130  **    May you find forgiveness for yourself and forgive others.
 97131  **    May you share freely, never taking more than you give.
 97132  **
 97133  *************************************************************************
 97134  ** This file contains C code routines that used to generate VDBE code
 97135  ** that implements the ALTER TABLE command.
 97136  */
 97137  /* #include "sqliteInt.h" */
 97138  
 97139  /*
 97140  ** The code in this file only exists if we are not omitting the
 97141  ** ALTER TABLE logic from the build.
 97142  */
 97143  #ifndef SQLITE_OMIT_ALTERTABLE
 97144  
 97145  
 97146  /*
 97147  ** This function is used by SQL generated to implement the 
 97148  ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
 97149  ** CREATE INDEX command. The second is a table name. The table name in 
 97150  ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
 97151  ** argument and the result returned. Examples:
 97152  **
 97153  ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
 97154  **     -> 'CREATE TABLE def(a, b, c)'
 97155  **
 97156  ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
 97157  **     -> 'CREATE INDEX i ON def(a, b, c)'
 97158  */
 97159  static void renameTableFunc(
 97160    sqlite3_context *context,
 97161    int NotUsed,
 97162    sqlite3_value **argv
 97163  ){
 97164    unsigned char const *zSql = sqlite3_value_text(argv[0]);
 97165    unsigned char const *zTableName = sqlite3_value_text(argv[1]);
 97166  
 97167    int token;
 97168    Token tname;
 97169    unsigned char const *zCsr = zSql;
 97170    int len = 0;
 97171    char *zRet;
 97172  
 97173    sqlite3 *db = sqlite3_context_db_handle(context);
 97174  
 97175    UNUSED_PARAMETER(NotUsed);
 97176  
 97177    /* The principle used to locate the table name in the CREATE TABLE 
 97178    ** statement is that the table name is the first non-space token that
 97179    ** is immediately followed by a TK_LP or TK_USING token.
 97180    */
 97181    if( zSql ){
 97182      do {
 97183        if( !*zCsr ){
 97184          /* Ran out of input before finding an opening bracket. Return NULL. */
 97185          return;
 97186        }
 97187  
 97188        /* Store the token that zCsr points to in tname. */
 97189        tname.z = (char*)zCsr;
 97190        tname.n = len;
 97191  
 97192        /* Advance zCsr to the next token. Store that token type in 'token',
 97193        ** and its length in 'len' (to be used next iteration of this loop).
 97194        */
 97195        do {
 97196          zCsr += len;
 97197          len = sqlite3GetToken(zCsr, &token);
 97198        } while( token==TK_SPACE );
 97199        assert( len>0 );
 97200      } while( token!=TK_LP && token!=TK_USING );
 97201  
 97202      zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
 97203         zSql, zTableName, tname.z+tname.n);
 97204      sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
 97205    }
 97206  }
 97207  
 97208  /*
 97209  ** This C function implements an SQL user function that is used by SQL code
 97210  ** generated by the ALTER TABLE ... RENAME command to modify the definition
 97211  ** of any foreign key constraints that use the table being renamed as the 
 97212  ** parent table. It is passed three arguments:
 97213  **
 97214  **   1) The complete text of the CREATE TABLE statement being modified,
 97215  **   2) The old name of the table being renamed, and
 97216  **   3) The new name of the table being renamed.
 97217  **
 97218  ** It returns the new CREATE TABLE statement. For example:
 97219  **
 97220  **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
 97221  **       -> 'CREATE TABLE t1(a REFERENCES t3)'
 97222  */
 97223  #ifndef SQLITE_OMIT_FOREIGN_KEY
 97224  static void renameParentFunc(
 97225    sqlite3_context *context,
 97226    int NotUsed,
 97227    sqlite3_value **argv
 97228  ){
 97229    sqlite3 *db = sqlite3_context_db_handle(context);
 97230    char *zOutput = 0;
 97231    char *zResult;
 97232    unsigned char const *zInput = sqlite3_value_text(argv[0]);
 97233    unsigned char const *zOld = sqlite3_value_text(argv[1]);
 97234    unsigned char const *zNew = sqlite3_value_text(argv[2]);
 97235  
 97236    unsigned const char *z;         /* Pointer to token */
 97237    int n;                          /* Length of token z */
 97238    int token;                      /* Type of token */
 97239  
 97240    UNUSED_PARAMETER(NotUsed);
 97241    if( zInput==0 || zOld==0 ) return;
 97242    for(z=zInput; *z; z=z+n){
 97243      n = sqlite3GetToken(z, &token);
 97244      if( token==TK_REFERENCES ){
 97245        char *zParent;
 97246        do {
 97247          z += n;
 97248          n = sqlite3GetToken(z, &token);
 97249        }while( token==TK_SPACE );
 97250  
 97251        if( token==TK_ILLEGAL ) break;
 97252        zParent = sqlite3DbStrNDup(db, (const char *)z, n);
 97253        if( zParent==0 ) break;
 97254        sqlite3Dequote(zParent);
 97255        if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
 97256          char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", 
 97257              (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
 97258          );
 97259          sqlite3DbFree(db, zOutput);
 97260          zOutput = zOut;
 97261          zInput = &z[n];
 97262        }
 97263        sqlite3DbFree(db, zParent);
 97264      }
 97265    }
 97266  
 97267    zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
 97268    sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
 97269    sqlite3DbFree(db, zOutput);
 97270  }
 97271  #endif
 97272  
 97273  #ifndef SQLITE_OMIT_TRIGGER
 97274  /* This function is used by SQL generated to implement the
 97275  ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
 97276  ** statement. The second is a table name. The table name in the CREATE 
 97277  ** TRIGGER statement is replaced with the third argument and the result 
 97278  ** returned. This is analagous to renameTableFunc() above, except for CREATE
 97279  ** TRIGGER, not CREATE INDEX and CREATE TABLE.
 97280  */
 97281  static void renameTriggerFunc(
 97282    sqlite3_context *context,
 97283    int NotUsed,
 97284    sqlite3_value **argv
 97285  ){
 97286    unsigned char const *zSql = sqlite3_value_text(argv[0]);
 97287    unsigned char const *zTableName = sqlite3_value_text(argv[1]);
 97288  
 97289    int token;
 97290    Token tname;
 97291    int dist = 3;
 97292    unsigned char const *zCsr = zSql;
 97293    int len = 0;
 97294    char *zRet;
 97295    sqlite3 *db = sqlite3_context_db_handle(context);
 97296  
 97297    UNUSED_PARAMETER(NotUsed);
 97298  
 97299    /* The principle used to locate the table name in the CREATE TRIGGER 
 97300    ** statement is that the table name is the first token that is immediately
 97301    ** preceded by either TK_ON or TK_DOT and immediately followed by one
 97302    ** of TK_WHEN, TK_BEGIN or TK_FOR.
 97303    */
 97304    if( zSql ){
 97305      do {
 97306  
 97307        if( !*zCsr ){
 97308          /* Ran out of input before finding the table name. Return NULL. */
 97309          return;
 97310        }
 97311  
 97312        /* Store the token that zCsr points to in tname. */
 97313        tname.z = (char*)zCsr;
 97314        tname.n = len;
 97315  
 97316        /* Advance zCsr to the next token. Store that token type in 'token',
 97317        ** and its length in 'len' (to be used next iteration of this loop).
 97318        */
 97319        do {
 97320          zCsr += len;
 97321          len = sqlite3GetToken(zCsr, &token);
 97322        }while( token==TK_SPACE );
 97323        assert( len>0 );
 97324  
 97325        /* Variable 'dist' stores the number of tokens read since the most
 97326        ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
 97327        ** token is read and 'dist' equals 2, the condition stated above
 97328        ** to be met.
 97329        **
 97330        ** Note that ON cannot be a database, table or column name, so
 97331        ** there is no need to worry about syntax like 
 97332        ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
 97333        */
 97334        dist++;
 97335        if( token==TK_DOT || token==TK_ON ){
 97336          dist = 0;
 97337        }
 97338      } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
 97339  
 97340      /* Variable tname now contains the token that is the old table-name
 97341      ** in the CREATE TRIGGER statement.
 97342      */
 97343      zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
 97344         zSql, zTableName, tname.z+tname.n);
 97345      sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
 97346    }
 97347  }
 97348  #endif   /* !SQLITE_OMIT_TRIGGER */
 97349  
 97350  /*
 97351  ** Register built-in functions used to help implement ALTER TABLE
 97352  */
 97353  SQLITE_PRIVATE void sqlite3AlterFunctions(void){
 97354    static FuncDef aAlterTableFuncs[] = {
 97355      FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
 97356  #ifndef SQLITE_OMIT_TRIGGER
 97357      FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
 97358  #endif
 97359  #ifndef SQLITE_OMIT_FOREIGN_KEY
 97360      FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
 97361  #endif
 97362    };
 97363    sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
 97364  }
 97365  
 97366  /*
 97367  ** This function is used to create the text of expressions of the form:
 97368  **
 97369  **   name=<constant1> OR name=<constant2> OR ...
 97370  **
 97371  ** If argument zWhere is NULL, then a pointer string containing the text 
 97372  ** "name=<constant>" is returned, where <constant> is the quoted version
 97373  ** of the string passed as argument zConstant. The returned buffer is
 97374  ** allocated using sqlite3DbMalloc(). It is the responsibility of the
 97375  ** caller to ensure that it is eventually freed.
 97376  **
 97377  ** If argument zWhere is not NULL, then the string returned is 
 97378  ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
 97379  ** In this case zWhere is passed to sqlite3DbFree() before returning.
 97380  ** 
 97381  */
 97382  static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
 97383    char *zNew;
 97384    if( !zWhere ){
 97385      zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
 97386    }else{
 97387      zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
 97388      sqlite3DbFree(db, zWhere);
 97389    }
 97390    return zNew;
 97391  }
 97392  
 97393  #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
 97394  /*
 97395  ** Generate the text of a WHERE expression which can be used to select all
 97396  ** tables that have foreign key constraints that refer to table pTab (i.e.
 97397  ** constraints for which pTab is the parent table) from the sqlite_master
 97398  ** table.
 97399  */
 97400  static char *whereForeignKeys(Parse *pParse, Table *pTab){
 97401    FKey *p;
 97402    char *zWhere = 0;
 97403    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
 97404      zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
 97405    }
 97406    return zWhere;
 97407  }
 97408  #endif
 97409  
 97410  /*
 97411  ** Generate the text of a WHERE expression which can be used to select all
 97412  ** temporary triggers on table pTab from the sqlite_temp_master table. If
 97413  ** table pTab has no temporary triggers, or is itself stored in the 
 97414  ** temporary database, NULL is returned.
 97415  */
 97416  static char *whereTempTriggers(Parse *pParse, Table *pTab){
 97417    Trigger *pTrig;
 97418    char *zWhere = 0;
 97419    const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
 97420  
 97421    /* If the table is not located in the temp-db (in which case NULL is 
 97422    ** returned, loop through the tables list of triggers. For each trigger
 97423    ** that is not part of the temp-db schema, add a clause to the WHERE 
 97424    ** expression being built up in zWhere.
 97425    */
 97426    if( pTab->pSchema!=pTempSchema ){
 97427      sqlite3 *db = pParse->db;
 97428      for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
 97429        if( pTrig->pSchema==pTempSchema ){
 97430          zWhere = whereOrName(db, zWhere, pTrig->zName);
 97431        }
 97432      }
 97433    }
 97434    if( zWhere ){
 97435      char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
 97436      sqlite3DbFree(pParse->db, zWhere);
 97437      zWhere = zNew;
 97438    }
 97439    return zWhere;
 97440  }
 97441  
 97442  /*
 97443  ** Generate code to drop and reload the internal representation of table
 97444  ** pTab from the database, including triggers and temporary triggers.
 97445  ** Argument zName is the name of the table in the database schema at
 97446  ** the time the generated code is executed. This can be different from
 97447  ** pTab->zName if this function is being called to code part of an 
 97448  ** "ALTER TABLE RENAME TO" statement.
 97449  */
 97450  static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
 97451    Vdbe *v;
 97452    char *zWhere;
 97453    int iDb;                   /* Index of database containing pTab */
 97454  #ifndef SQLITE_OMIT_TRIGGER
 97455    Trigger *pTrig;
 97456  #endif
 97457  
 97458    v = sqlite3GetVdbe(pParse);
 97459    if( NEVER(v==0) ) return;
 97460    assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
 97461    iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
 97462    assert( iDb>=0 );
 97463  
 97464  #ifndef SQLITE_OMIT_TRIGGER
 97465    /* Drop any table triggers from the internal schema. */
 97466    for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
 97467      int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
 97468      assert( iTrigDb==iDb || iTrigDb==1 );
 97469      sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
 97470    }
 97471  #endif
 97472  
 97473    /* Drop the table and index from the internal schema.  */
 97474    sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
 97475  
 97476    /* Reload the table, index and permanent trigger schemas. */
 97477    zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
 97478    if( !zWhere ) return;
 97479    sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
 97480  
 97481  #ifndef SQLITE_OMIT_TRIGGER
 97482    /* Now, if the table is not stored in the temp database, reload any temp 
 97483    ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
 97484    */
 97485    if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
 97486      sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
 97487    }
 97488  #endif
 97489  }
 97490  
 97491  /*
 97492  ** Parameter zName is the name of a table that is about to be altered
 97493  ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
 97494  ** If the table is a system table, this function leaves an error message
 97495  ** in pParse->zErr (system tables may not be altered) and returns non-zero.
 97496  **
 97497  ** Or, if zName is not a system table, zero is returned.
 97498  */
 97499  static int isSystemTable(Parse *pParse, const char *zName){
 97500    if( 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
 97501      sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
 97502      return 1;
 97503    }
 97504    return 0;
 97505  }
 97506  
 97507  /*
 97508  ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
 97509  ** command. 
 97510  */
 97511  SQLITE_PRIVATE void sqlite3AlterRenameTable(
 97512    Parse *pParse,            /* Parser context. */
 97513    SrcList *pSrc,            /* The table to rename. */
 97514    Token *pName              /* The new table name. */
 97515  ){
 97516    int iDb;                  /* Database that contains the table */
 97517    char *zDb;                /* Name of database iDb */
 97518    Table *pTab;              /* Table being renamed */
 97519    char *zName = 0;          /* NULL-terminated version of pName */ 
 97520    sqlite3 *db = pParse->db; /* Database connection */
 97521    int nTabName;             /* Number of UTF-8 characters in zTabName */
 97522    const char *zTabName;     /* Original name of the table */
 97523    Vdbe *v;
 97524  #ifndef SQLITE_OMIT_TRIGGER
 97525    char *zWhere = 0;         /* Where clause to locate temp triggers */
 97526  #endif
 97527    VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
 97528    u32 savedDbFlags;         /* Saved value of db->mDbFlags */
 97529  
 97530    savedDbFlags = db->mDbFlags;  
 97531    if( NEVER(db->mallocFailed) ) goto exit_rename_table;
 97532    assert( pSrc->nSrc==1 );
 97533    assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
 97534  
 97535    pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
 97536    if( !pTab ) goto exit_rename_table;
 97537    iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
 97538    zDb = db->aDb[iDb].zDbSName;
 97539    db->mDbFlags |= DBFLAG_PreferBuiltin;
 97540  
 97541    /* Get a NULL terminated version of the new table name. */
 97542    zName = sqlite3NameFromToken(db, pName);
 97543    if( !zName ) goto exit_rename_table;
 97544  
 97545    /* Check that a table or index named 'zName' does not already exist
 97546    ** in database iDb. If so, this is an error.
 97547    */
 97548    if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
 97549      sqlite3ErrorMsg(pParse, 
 97550          "there is already another table or index with this name: %s", zName);
 97551      goto exit_rename_table;
 97552    }
 97553  
 97554    /* Make sure it is not a system table being altered, or a reserved name
 97555    ** that the table is being renamed to.
 97556    */
 97557    if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
 97558      goto exit_rename_table;
 97559    }
 97560    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
 97561      exit_rename_table;
 97562    }
 97563  
 97564  #ifndef SQLITE_OMIT_VIEW
 97565    if( pTab->pSelect ){
 97566      sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
 97567      goto exit_rename_table;
 97568    }
 97569  #endif
 97570  
 97571  #ifndef SQLITE_OMIT_AUTHORIZATION
 97572    /* Invoke the authorization callback. */
 97573    if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
 97574      goto exit_rename_table;
 97575    }
 97576  #endif
 97577  
 97578  #ifndef SQLITE_OMIT_VIRTUALTABLE
 97579    if( sqlite3ViewGetColumnNames(pParse, pTab) ){
 97580      goto exit_rename_table;
 97581    }
 97582    if( IsVirtual(pTab) ){
 97583      pVTab = sqlite3GetVTable(db, pTab);
 97584      if( pVTab->pVtab->pModule->xRename==0 ){
 97585        pVTab = 0;
 97586      }
 97587    }
 97588  #endif
 97589  
 97590    /* Begin a transaction for database iDb. 
 97591    ** Then modify the schema cookie (since the ALTER TABLE modifies the
 97592    ** schema). Open a statement transaction if the table is a virtual
 97593    ** table.
 97594    */
 97595    v = sqlite3GetVdbe(pParse);
 97596    if( v==0 ){
 97597      goto exit_rename_table;
 97598    }
 97599    sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
 97600    sqlite3ChangeCookie(pParse, iDb);
 97601  
 97602    /* If this is a virtual table, invoke the xRename() function if
 97603    ** one is defined. The xRename() callback will modify the names
 97604    ** of any resources used by the v-table implementation (including other
 97605    ** SQLite tables) that are identified by the name of the virtual table.
 97606    */
 97607  #ifndef SQLITE_OMIT_VIRTUALTABLE
 97608    if( pVTab ){
 97609      int i = ++pParse->nMem;
 97610      sqlite3VdbeLoadString(v, i, zName);
 97611      sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
 97612      sqlite3MayAbort(pParse);
 97613    }
 97614  #endif
 97615  
 97616    /* figure out how many UTF-8 characters are in zName */
 97617    zTabName = pTab->zName;
 97618    nTabName = sqlite3Utf8CharLen(zTabName, -1);
 97619  
 97620  #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
 97621    if( db->flags&SQLITE_ForeignKeys ){
 97622      /* If foreign-key support is enabled, rewrite the CREATE TABLE 
 97623      ** statements corresponding to all child tables of foreign key constraints
 97624      ** for which the renamed table is the parent table.  */
 97625      if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
 97626        sqlite3NestedParse(pParse, 
 97627            "UPDATE \"%w\".%s SET "
 97628                "sql = sqlite_rename_parent(sql, %Q, %Q) "
 97629                "WHERE %s;", zDb, MASTER_NAME, zTabName, zName, zWhere);
 97630        sqlite3DbFree(db, zWhere);
 97631      }
 97632    }
 97633  #endif
 97634  
 97635    /* Modify the sqlite_master table to use the new table name. */
 97636    sqlite3NestedParse(pParse,
 97637        "UPDATE %Q.%s SET "
 97638  #ifdef SQLITE_OMIT_TRIGGER
 97639            "sql = sqlite_rename_table(sql, %Q), "
 97640  #else
 97641            "sql = CASE "
 97642              "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
 97643              "ELSE sqlite_rename_table(sql, %Q) END, "
 97644  #endif
 97645            "tbl_name = %Q, "
 97646            "name = CASE "
 97647              "WHEN type='table' THEN %Q "
 97648              "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
 97649               "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
 97650              "ELSE name END "
 97651        "WHERE tbl_name=%Q COLLATE nocase AND "
 97652            "(type='table' OR type='index' OR type='trigger');", 
 97653        zDb, MASTER_NAME, zName, zName, zName, 
 97654  #ifndef SQLITE_OMIT_TRIGGER
 97655        zName,
 97656  #endif
 97657        zName, nTabName, zTabName
 97658    );
 97659  
 97660  #ifndef SQLITE_OMIT_AUTOINCREMENT
 97661    /* If the sqlite_sequence table exists in this database, then update 
 97662    ** it with the new table name.
 97663    */
 97664    if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
 97665      sqlite3NestedParse(pParse,
 97666          "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
 97667          zDb, zName, pTab->zName);
 97668    }
 97669  #endif
 97670  
 97671  #ifndef SQLITE_OMIT_TRIGGER
 97672    /* If there are TEMP triggers on this table, modify the sqlite_temp_master
 97673    ** table. Don't do this if the table being ALTERed is itself located in
 97674    ** the temp database.
 97675    */
 97676    if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
 97677      sqlite3NestedParse(pParse, 
 97678          "UPDATE sqlite_temp_master SET "
 97679              "sql = sqlite_rename_trigger(sql, %Q), "
 97680              "tbl_name = %Q "
 97681              "WHERE %s;", zName, zName, zWhere);
 97682      sqlite3DbFree(db, zWhere);
 97683    }
 97684  #endif
 97685  
 97686  #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
 97687    if( db->flags&SQLITE_ForeignKeys ){
 97688      FKey *p;
 97689      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
 97690        Table *pFrom = p->pFrom;
 97691        if( pFrom!=pTab ){
 97692          reloadTableSchema(pParse, p->pFrom, pFrom->zName);
 97693        }
 97694      }
 97695    }
 97696  #endif
 97697  
 97698    /* Drop and reload the internal table schema. */
 97699    reloadTableSchema(pParse, pTab, zName);
 97700  
 97701  exit_rename_table:
 97702    sqlite3SrcListDelete(db, pSrc);
 97703    sqlite3DbFree(db, zName);
 97704    db->mDbFlags = savedDbFlags;
 97705  }
 97706  
 97707  /*
 97708  ** This function is called after an "ALTER TABLE ... ADD" statement
 97709  ** has been parsed. Argument pColDef contains the text of the new
 97710  ** column definition.
 97711  **
 97712  ** The Table structure pParse->pNewTable was extended to include
 97713  ** the new column during parsing.
 97714  */
 97715  SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
 97716    Table *pNew;              /* Copy of pParse->pNewTable */
 97717    Table *pTab;              /* Table being altered */
 97718    int iDb;                  /* Database number */
 97719    const char *zDb;          /* Database name */
 97720    const char *zTab;         /* Table name */
 97721    char *zCol;               /* Null-terminated column definition */
 97722    Column *pCol;             /* The new column */
 97723    Expr *pDflt;              /* Default value for the new column */
 97724    sqlite3 *db;              /* The database connection; */
 97725    Vdbe *v = pParse->pVdbe;  /* The prepared statement under construction */
 97726    int r1;                   /* Temporary registers */
 97727  
 97728    db = pParse->db;
 97729    if( pParse->nErr || db->mallocFailed ) return;
 97730    assert( v!=0 );
 97731    pNew = pParse->pNewTable;
 97732    assert( pNew );
 97733  
 97734    assert( sqlite3BtreeHoldsAllMutexes(db) );
 97735    iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
 97736    zDb = db->aDb[iDb].zDbSName;
 97737    zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
 97738    pCol = &pNew->aCol[pNew->nCol-1];
 97739    pDflt = pCol->pDflt;
 97740    pTab = sqlite3FindTable(db, zTab, zDb);
 97741    assert( pTab );
 97742  
 97743  #ifndef SQLITE_OMIT_AUTHORIZATION
 97744    /* Invoke the authorization callback. */
 97745    if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
 97746      return;
 97747    }
 97748  #endif
 97749  
 97750    /* If the default value for the new column was specified with a 
 97751    ** literal NULL, then set pDflt to 0. This simplifies checking
 97752    ** for an SQL NULL default below.
 97753    */
 97754    assert( pDflt==0 || pDflt->op==TK_SPAN );
 97755    if( pDflt && pDflt->pLeft->op==TK_NULL ){
 97756      pDflt = 0;
 97757    }
 97758  
 97759    /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
 97760    ** If there is a NOT NULL constraint, then the default value for the
 97761    ** column must not be NULL.
 97762    */
 97763    if( pCol->colFlags & COLFLAG_PRIMKEY ){
 97764      sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
 97765      return;
 97766    }
 97767    if( pNew->pIndex ){
 97768      sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
 97769      return;
 97770    }
 97771    if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
 97772      sqlite3ErrorMsg(pParse, 
 97773          "Cannot add a REFERENCES column with non-NULL default value");
 97774      return;
 97775    }
 97776    if( pCol->notNull && !pDflt ){
 97777      sqlite3ErrorMsg(pParse, 
 97778          "Cannot add a NOT NULL column with default value NULL");
 97779      return;
 97780    }
 97781  
 97782    /* Ensure the default expression is something that sqlite3ValueFromExpr()
 97783    ** can handle (i.e. not CURRENT_TIME etc.)
 97784    */
 97785    if( pDflt ){
 97786      sqlite3_value *pVal = 0;
 97787      int rc;
 97788      rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
 97789      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
 97790      if( rc!=SQLITE_OK ){
 97791        assert( db->mallocFailed == 1 );
 97792        return;
 97793      }
 97794      if( !pVal ){
 97795        sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
 97796        return;
 97797      }
 97798      sqlite3ValueFree(pVal);
 97799    }
 97800  
 97801    /* Modify the CREATE TABLE statement. */
 97802    zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
 97803    if( zCol ){
 97804      char *zEnd = &zCol[pColDef->n-1];
 97805      u32 savedDbFlags = db->mDbFlags;
 97806      while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
 97807        *zEnd-- = '\0';
 97808      }
 97809      db->mDbFlags |= DBFLAG_PreferBuiltin;
 97810      sqlite3NestedParse(pParse, 
 97811          "UPDATE \"%w\".%s SET "
 97812            "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
 97813          "WHERE type = 'table' AND name = %Q", 
 97814        zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
 97815        zTab
 97816      );
 97817      sqlite3DbFree(db, zCol);
 97818      db->mDbFlags = savedDbFlags;
 97819    }
 97820  
 97821    /* Make sure the schema version is at least 3.  But do not upgrade
 97822    ** from less than 3 to 4, as that will corrupt any preexisting DESC
 97823    ** index.
 97824    */
 97825    r1 = sqlite3GetTempReg(pParse);
 97826    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
 97827    sqlite3VdbeUsesBtree(v, iDb);
 97828    sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
 97829    sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
 97830    VdbeCoverage(v);
 97831    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
 97832    sqlite3ReleaseTempReg(pParse, r1);
 97833  
 97834    /* Reload the schema of the modified table. */
 97835    reloadTableSchema(pParse, pTab, pTab->zName);
 97836  }
 97837  
 97838  /*
 97839  ** This function is called by the parser after the table-name in
 97840  ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
 97841  ** pSrc is the full-name of the table being altered.
 97842  **
 97843  ** This routine makes a (partial) copy of the Table structure
 97844  ** for the table being altered and sets Parse.pNewTable to point
 97845  ** to it. Routines called by the parser as the column definition
 97846  ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
 97847  ** the copy. The copy of the Table structure is deleted by tokenize.c 
 97848  ** after parsing is finished.
 97849  **
 97850  ** Routine sqlite3AlterFinishAddColumn() will be called to complete
 97851  ** coding the "ALTER TABLE ... ADD" statement.
 97852  */
 97853  SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
 97854    Table *pNew;
 97855    Table *pTab;
 97856    Vdbe *v;
 97857    int iDb;
 97858    int i;
 97859    int nAlloc;
 97860    sqlite3 *db = pParse->db;
 97861  
 97862    /* Look up the table being altered. */
 97863    assert( pParse->pNewTable==0 );
 97864    assert( sqlite3BtreeHoldsAllMutexes(db) );
 97865    if( db->mallocFailed ) goto exit_begin_add_column;
 97866    pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
 97867    if( !pTab ) goto exit_begin_add_column;
 97868  
 97869  #ifndef SQLITE_OMIT_VIRTUALTABLE
 97870    if( IsVirtual(pTab) ){
 97871      sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
 97872      goto exit_begin_add_column;
 97873    }
 97874  #endif
 97875  
 97876    /* Make sure this is not an attempt to ALTER a view. */
 97877    if( pTab->pSelect ){
 97878      sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
 97879      goto exit_begin_add_column;
 97880    }
 97881    if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
 97882      goto exit_begin_add_column;
 97883    }
 97884  
 97885    assert( pTab->addColOffset>0 );
 97886    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
 97887  
 97888    /* Put a copy of the Table struct in Parse.pNewTable for the
 97889    ** sqlite3AddColumn() function and friends to modify.  But modify
 97890    ** the name by adding an "sqlite_altertab_" prefix.  By adding this
 97891    ** prefix, we insure that the name will not collide with an existing
 97892    ** table because user table are not allowed to have the "sqlite_"
 97893    ** prefix on their name.
 97894    */
 97895    pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
 97896    if( !pNew ) goto exit_begin_add_column;
 97897    pParse->pNewTable = pNew;
 97898    pNew->nTabRef = 1;
 97899    pNew->nCol = pTab->nCol;
 97900    assert( pNew->nCol>0 );
 97901    nAlloc = (((pNew->nCol-1)/8)*8)+8;
 97902    assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
 97903    pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
 97904    pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
 97905    if( !pNew->aCol || !pNew->zName ){
 97906      assert( db->mallocFailed );
 97907      goto exit_begin_add_column;
 97908    }
 97909    memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
 97910    for(i=0; i<pNew->nCol; i++){
 97911      Column *pCol = &pNew->aCol[i];
 97912      pCol->zName = sqlite3DbStrDup(db, pCol->zName);
 97913      pCol->zColl = 0;
 97914      pCol->pDflt = 0;
 97915    }
 97916    pNew->pSchema = db->aDb[iDb].pSchema;
 97917    pNew->addColOffset = pTab->addColOffset;
 97918    pNew->nTabRef = 1;
 97919  
 97920    /* Begin a transaction and increment the schema cookie.  */
 97921    sqlite3BeginWriteOperation(pParse, 0, iDb);
 97922    v = sqlite3GetVdbe(pParse);
 97923    if( !v ) goto exit_begin_add_column;
 97924    sqlite3ChangeCookie(pParse, iDb);
 97925  
 97926  exit_begin_add_column:
 97927    sqlite3SrcListDelete(db, pSrc);
 97928    return;
 97929  }
 97930  #endif  /* SQLITE_ALTER_TABLE */
 97931  
 97932  /************** End of alter.c ***********************************************/
 97933  /************** Begin file analyze.c *****************************************/
 97934  /*
 97935  ** 2005-07-08
 97936  **
 97937  ** The author disclaims copyright to this source code.  In place of
 97938  ** a legal notice, here is a blessing:
 97939  **
 97940  **    May you do good and not evil.
 97941  **    May you find forgiveness for yourself and forgive others.
 97942  **    May you share freely, never taking more than you give.
 97943  **
 97944  *************************************************************************
 97945  ** This file contains code associated with the ANALYZE command.
 97946  **
 97947  ** The ANALYZE command gather statistics about the content of tables
 97948  ** and indices.  These statistics are made available to the query planner
 97949  ** to help it make better decisions about how to perform queries.
 97950  **
 97951  ** The following system tables are or have been supported:
 97952  **
 97953  **    CREATE TABLE sqlite_stat1(tbl, idx, stat);
 97954  **    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
 97955  **    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
 97956  **    CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
 97957  **
 97958  ** Additional tables might be added in future releases of SQLite.
 97959  ** The sqlite_stat2 table is not created or used unless the SQLite version
 97960  ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
 97961  ** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
 97962  ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
 97963  ** created and used by SQLite versions 3.7.9 and later and with
 97964  ** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3
 97965  ** is a superset of sqlite_stat2.  The sqlite_stat4 is an enhanced
 97966  ** version of sqlite_stat3 and is only available when compiled with
 97967  ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later.  It is
 97968  ** not possible to enable both STAT3 and STAT4 at the same time.  If they
 97969  ** are both enabled, then STAT4 takes precedence.
 97970  **
 97971  ** For most applications, sqlite_stat1 provides all the statistics required
 97972  ** for the query planner to make good choices.
 97973  **
 97974  ** Format of sqlite_stat1:
 97975  **
 97976  ** There is normally one row per index, with the index identified by the
 97977  ** name in the idx column.  The tbl column is the name of the table to
 97978  ** which the index belongs.  In each such row, the stat column will be
 97979  ** a string consisting of a list of integers.  The first integer in this
 97980  ** list is the number of rows in the index.  (This is the same as the
 97981  ** number of rows in the table, except for partial indices.)  The second
 97982  ** integer is the average number of rows in the index that have the same
 97983  ** value in the first column of the index.  The third integer is the average
 97984  ** number of rows in the index that have the same value for the first two
 97985  ** columns.  The N-th integer (for N>1) is the average number of rows in 
 97986  ** the index which have the same value for the first N-1 columns.  For
 97987  ** a K-column index, there will be K+1 integers in the stat column.  If
 97988  ** the index is unique, then the last integer will be 1.
 97989  **
 97990  ** The list of integers in the stat column can optionally be followed
 97991  ** by the keyword "unordered".  The "unordered" keyword, if it is present,
 97992  ** must be separated from the last integer by a single space.  If the
 97993  ** "unordered" keyword is present, then the query planner assumes that
 97994  ** the index is unordered and will not use the index for a range query.
 97995  ** 
 97996  ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
 97997  ** column contains a single integer which is the (estimated) number of
 97998  ** rows in the table identified by sqlite_stat1.tbl.
 97999  **
 98000  ** Format of sqlite_stat2:
 98001  **
 98002  ** The sqlite_stat2 is only created and is only used if SQLite is compiled
 98003  ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
 98004  ** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
 98005  ** about the distribution of keys within an index.  The index is identified by
 98006  ** the "idx" column and the "tbl" column is the name of the table to which
 98007  ** the index belongs.  There are usually 10 rows in the sqlite_stat2
 98008  ** table for each index.
 98009  **
 98010  ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
 98011  ** inclusive are samples of the left-most key value in the index taken at
 98012  ** evenly spaced points along the index.  Let the number of samples be S
 98013  ** (10 in the standard build) and let C be the number of rows in the index.
 98014  ** Then the sampled rows are given by:
 98015  **
 98016  **     rownumber = (i*C*2 + C)/(S*2)
 98017  **
 98018  ** For i between 0 and S-1.  Conceptually, the index space is divided into
 98019  ** S uniform buckets and the samples are the middle row from each bucket.
 98020  **
 98021  ** The format for sqlite_stat2 is recorded here for legacy reference.  This
 98022  ** version of SQLite does not support sqlite_stat2.  It neither reads nor
 98023  ** writes the sqlite_stat2 table.  This version of SQLite only supports
 98024  ** sqlite_stat3.
 98025  **
 98026  ** Format for sqlite_stat3:
 98027  **
 98028  ** The sqlite_stat3 format is a subset of sqlite_stat4.  Hence, the
 98029  ** sqlite_stat4 format will be described first.  Further information
 98030  ** about sqlite_stat3 follows the sqlite_stat4 description.
 98031  **
 98032  ** Format for sqlite_stat4:
 98033  **
 98034  ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
 98035  ** to aid the query planner in choosing good indices based on the values
 98036  ** that indexed columns are compared against in the WHERE clauses of
 98037  ** queries.
 98038  **
 98039  ** The sqlite_stat4 table contains multiple entries for each index.
 98040  ** The idx column names the index and the tbl column is the table of the
 98041  ** index.  If the idx and tbl columns are the same, then the sample is
 98042  ** of the INTEGER PRIMARY KEY.  The sample column is a blob which is the
 98043  ** binary encoding of a key from the index.  The nEq column is a
 98044  ** list of integers.  The first integer is the approximate number
 98045  ** of entries in the index whose left-most column exactly matches
 98046  ** the left-most column of the sample.  The second integer in nEq
 98047  ** is the approximate number of entries in the index where the
 98048  ** first two columns match the first two columns of the sample.
 98049  ** And so forth.  nLt is another list of integers that show the approximate
 98050  ** number of entries that are strictly less than the sample.  The first
 98051  ** integer in nLt contains the number of entries in the index where the
 98052  ** left-most column is less than the left-most column of the sample.
 98053  ** The K-th integer in the nLt entry is the number of index entries 
 98054  ** where the first K columns are less than the first K columns of the
 98055  ** sample.  The nDLt column is like nLt except that it contains the 
 98056  ** number of distinct entries in the index that are less than the
 98057  ** sample.
 98058  **
 98059  ** There can be an arbitrary number of sqlite_stat4 entries per index.
 98060  ** The ANALYZE command will typically generate sqlite_stat4 tables
 98061  ** that contain between 10 and 40 samples which are distributed across
 98062  ** the key space, though not uniformly, and which include samples with
 98063  ** large nEq values.
 98064  **
 98065  ** Format for sqlite_stat3 redux:
 98066  **
 98067  ** The sqlite_stat3 table is like sqlite_stat4 except that it only
 98068  ** looks at the left-most column of the index.  The sqlite_stat3.sample
 98069  ** column contains the actual value of the left-most column instead
 98070  ** of a blob encoding of the complete index key as is found in
 98071  ** sqlite_stat4.sample.  The nEq, nLt, and nDLt entries of sqlite_stat3
 98072  ** all contain just a single integer which is the same as the first
 98073  ** integer in the equivalent columns in sqlite_stat4.
 98074  */
 98075  #ifndef SQLITE_OMIT_ANALYZE
 98076  /* #include "sqliteInt.h" */
 98077  
 98078  #if defined(SQLITE_ENABLE_STAT4)
 98079  # define IsStat4     1
 98080  # define IsStat3     0
 98081  #elif defined(SQLITE_ENABLE_STAT3)
 98082  # define IsStat4     0
 98083  # define IsStat3     1
 98084  #else
 98085  # define IsStat4     0
 98086  # define IsStat3     0
 98087  # undef SQLITE_STAT4_SAMPLES
 98088  # define SQLITE_STAT4_SAMPLES 1
 98089  #endif
 98090  #define IsStat34    (IsStat3+IsStat4)  /* 1 for STAT3 or STAT4. 0 otherwise */
 98091  
 98092  /*
 98093  ** This routine generates code that opens the sqlite_statN tables.
 98094  ** The sqlite_stat1 table is always relevant.  sqlite_stat2 is now
 98095  ** obsolete.  sqlite_stat3 and sqlite_stat4 are only opened when
 98096  ** appropriate compile-time options are provided.
 98097  **
 98098  ** If the sqlite_statN tables do not previously exist, it is created.
 98099  **
 98100  ** Argument zWhere may be a pointer to a buffer containing a table name,
 98101  ** or it may be a NULL pointer. If it is not NULL, then all entries in
 98102  ** the sqlite_statN tables associated with the named table are deleted.
 98103  ** If zWhere==0, then code is generated to delete all stat table entries.
 98104  */
 98105  static void openStatTable(
 98106    Parse *pParse,          /* Parsing context */
 98107    int iDb,                /* The database we are looking in */
 98108    int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
 98109    const char *zWhere,     /* Delete entries for this table or index */
 98110    const char *zWhereType  /* Either "tbl" or "idx" */
 98111  ){
 98112    static const struct {
 98113      const char *zName;
 98114      const char *zCols;
 98115    } aTable[] = {
 98116      { "sqlite_stat1", "tbl,idx,stat" },
 98117  #if defined(SQLITE_ENABLE_STAT4)
 98118      { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
 98119      { "sqlite_stat3", 0 },
 98120  #elif defined(SQLITE_ENABLE_STAT3)
 98121      { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
 98122      { "sqlite_stat4", 0 },
 98123  #else
 98124      { "sqlite_stat3", 0 },
 98125      { "sqlite_stat4", 0 },
 98126  #endif
 98127    };
 98128    int i;
 98129    sqlite3 *db = pParse->db;
 98130    Db *pDb;
 98131    Vdbe *v = sqlite3GetVdbe(pParse);
 98132    int aRoot[ArraySize(aTable)];
 98133    u8 aCreateTbl[ArraySize(aTable)];
 98134  
 98135    if( v==0 ) return;
 98136    assert( sqlite3BtreeHoldsAllMutexes(db) );
 98137    assert( sqlite3VdbeDb(v)==db );
 98138    pDb = &db->aDb[iDb];
 98139  
 98140    /* Create new statistic tables if they do not exist, or clear them
 98141    ** if they do already exist.
 98142    */
 98143    for(i=0; i<ArraySize(aTable); i++){
 98144      const char *zTab = aTable[i].zName;
 98145      Table *pStat;
 98146      if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
 98147        if( aTable[i].zCols ){
 98148          /* The sqlite_statN table does not exist. Create it. Note that a 
 98149          ** side-effect of the CREATE TABLE statement is to leave the rootpage 
 98150          ** of the new table in register pParse->regRoot. This is important 
 98151          ** because the OpenWrite opcode below will be needing it. */
 98152          sqlite3NestedParse(pParse,
 98153              "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
 98154          );
 98155          aRoot[i] = pParse->regRoot;
 98156          aCreateTbl[i] = OPFLAG_P2ISREG;
 98157        }
 98158      }else{
 98159        /* The table already exists. If zWhere is not NULL, delete all entries 
 98160        ** associated with the table zWhere. If zWhere is NULL, delete the
 98161        ** entire contents of the table. */
 98162        aRoot[i] = pStat->tnum;
 98163        aCreateTbl[i] = 0;
 98164        sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
 98165        if( zWhere ){
 98166          sqlite3NestedParse(pParse,
 98167             "DELETE FROM %Q.%s WHERE %s=%Q",
 98168             pDb->zDbSName, zTab, zWhereType, zWhere
 98169          );
 98170        }else{
 98171          /* The sqlite_stat[134] table already exists.  Delete all rows. */
 98172          sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
 98173        }
 98174      }
 98175    }
 98176  
 98177    /* Open the sqlite_stat[134] tables for writing. */
 98178    for(i=0; aTable[i].zCols; i++){
 98179      assert( i<ArraySize(aTable) );
 98180      sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
 98181      sqlite3VdbeChangeP5(v, aCreateTbl[i]);
 98182      VdbeComment((v, aTable[i].zName));
 98183    }
 98184  }
 98185  
 98186  /*
 98187  ** Recommended number of samples for sqlite_stat4
 98188  */
 98189  #ifndef SQLITE_STAT4_SAMPLES
 98190  # define SQLITE_STAT4_SAMPLES 24
 98191  #endif
 98192  
 98193  /*
 98194  ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
 98195  ** share an instance of the following structure to hold their state
 98196  ** information.
 98197  */
 98198  typedef struct Stat4Accum Stat4Accum;
 98199  typedef struct Stat4Sample Stat4Sample;
 98200  struct Stat4Sample {
 98201    tRowcnt *anEq;                  /* sqlite_stat4.nEq */
 98202    tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */
 98203  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 98204    tRowcnt *anLt;                  /* sqlite_stat4.nLt */
 98205    union {
 98206      i64 iRowid;                     /* Rowid in main table of the key */
 98207      u8 *aRowid;                     /* Key for WITHOUT ROWID tables */
 98208    } u;
 98209    u32 nRowid;                     /* Sizeof aRowid[] */
 98210    u8 isPSample;                   /* True if a periodic sample */
 98211    int iCol;                       /* If !isPSample, the reason for inclusion */
 98212    u32 iHash;                      /* Tiebreaker hash */
 98213  #endif
 98214  };                                                    
 98215  struct Stat4Accum {
 98216    tRowcnt nRow;             /* Number of rows in the entire table */
 98217    tRowcnt nPSample;         /* How often to do a periodic sample */
 98218    int nCol;                 /* Number of columns in index + pk/rowid */
 98219    int nKeyCol;              /* Number of index columns w/o the pk/rowid */
 98220    int mxSample;             /* Maximum number of samples to accumulate */
 98221    Stat4Sample current;      /* Current row as a Stat4Sample */
 98222    u32 iPrn;                 /* Pseudo-random number used for sampling */
 98223    Stat4Sample *aBest;       /* Array of nCol best samples */
 98224    int iMin;                 /* Index in a[] of entry with minimum score */
 98225    int nSample;              /* Current number of samples */
 98226    int nMaxEqZero;           /* Max leading 0 in anEq[] for any a[] entry */
 98227    int iGet;                 /* Index of current sample accessed by stat_get() */
 98228    Stat4Sample *a;           /* Array of mxSample Stat4Sample objects */
 98229    sqlite3 *db;              /* Database connection, for malloc() */
 98230  };
 98231  
 98232  /* Reclaim memory used by a Stat4Sample
 98233  */
 98234  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 98235  static void sampleClear(sqlite3 *db, Stat4Sample *p){
 98236    assert( db!=0 );
 98237    if( p->nRowid ){
 98238      sqlite3DbFree(db, p->u.aRowid);
 98239      p->nRowid = 0;
 98240    }
 98241  }
 98242  #endif
 98243  
 98244  /* Initialize the BLOB value of a ROWID
 98245  */
 98246  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 98247  static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
 98248    assert( db!=0 );
 98249    if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
 98250    p->u.aRowid = sqlite3DbMallocRawNN(db, n);
 98251    if( p->u.aRowid ){
 98252      p->nRowid = n;
 98253      memcpy(p->u.aRowid, pData, n);
 98254    }else{
 98255      p->nRowid = 0;
 98256    }
 98257  }
 98258  #endif
 98259  
 98260  /* Initialize the INTEGER value of a ROWID.
 98261  */
 98262  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 98263  static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
 98264    assert( db!=0 );
 98265    if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
 98266    p->nRowid = 0;
 98267    p->u.iRowid = iRowid;
 98268  }
 98269  #endif
 98270  
 98271  
 98272  /*
 98273  ** Copy the contents of object (*pFrom) into (*pTo).
 98274  */
 98275  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 98276  static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
 98277    pTo->isPSample = pFrom->isPSample;
 98278    pTo->iCol = pFrom->iCol;
 98279    pTo->iHash = pFrom->iHash;
 98280    memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
 98281    memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
 98282    memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
 98283    if( pFrom->nRowid ){
 98284      sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
 98285    }else{
 98286      sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
 98287    }
 98288  }
 98289  #endif
 98290  
 98291  /*
 98292  ** Reclaim all memory of a Stat4Accum structure.
 98293  */
 98294  static void stat4Destructor(void *pOld){
 98295    Stat4Accum *p = (Stat4Accum*)pOld;
 98296  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 98297    int i;
 98298    for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
 98299    for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
 98300    sampleClear(p->db, &p->current);
 98301  #endif
 98302    sqlite3DbFree(p->db, p);
 98303  }
 98304  
 98305  /*
 98306  ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
 98307  ** are:
 98308  **     N:    The number of columns in the index including the rowid/pk (note 1)
 98309  **     K:    The number of columns in the index excluding the rowid/pk.
 98310  **     C:    The number of rows in the index (note 2)
 98311  **
 98312  ** Note 1:  In the special case of the covering index that implements a
 98313  ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
 98314  ** total number of columns in the table.
 98315  **
 98316  ** Note 2:  C is only used for STAT3 and STAT4.
 98317  **
 98318  ** For indexes on ordinary rowid tables, N==K+1.  But for indexes on
 98319  ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
 98320  ** PRIMARY KEY of the table.  The covering index that implements the
 98321  ** original WITHOUT ROWID table as N==K as a special case.
 98322  **
 98323  ** This routine allocates the Stat4Accum object in heap memory. The return 
 98324  ** value is a pointer to the Stat4Accum object.  The datatype of the
 98325  ** return value is BLOB, but it is really just a pointer to the Stat4Accum
 98326  ** object.
 98327  */
 98328  static void statInit(
 98329    sqlite3_context *context,
 98330    int argc,
 98331    sqlite3_value **argv
 98332  ){
 98333    Stat4Accum *p;
 98334    int nCol;                       /* Number of columns in index being sampled */
 98335    int nKeyCol;                    /* Number of key columns */
 98336    int nColUp;                     /* nCol rounded up for alignment */
 98337    int n;                          /* Bytes of space to allocate */
 98338    sqlite3 *db;                    /* Database connection */
 98339  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 98340    int mxSample = SQLITE_STAT4_SAMPLES;
 98341  #endif
 98342  
 98343    /* Decode the three function arguments */
 98344    UNUSED_PARAMETER(argc);
 98345    nCol = sqlite3_value_int(argv[0]);
 98346    assert( nCol>0 );
 98347    nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
 98348    nKeyCol = sqlite3_value_int(argv[1]);
 98349    assert( nKeyCol<=nCol );
 98350    assert( nKeyCol>0 );
 98351  
 98352    /* Allocate the space required for the Stat4Accum object */
 98353    n = sizeof(*p) 
 98354      + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anEq */
 98355      + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anDLt */
 98356  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 98357      + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anLt */
 98358      + sizeof(Stat4Sample)*(nCol+mxSample)     /* Stat4Accum.aBest[], a[] */
 98359      + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
 98360  #endif
 98361    ;
 98362    db = sqlite3_context_db_handle(context);
 98363    p = sqlite3DbMallocZero(db, n);
 98364    if( p==0 ){
 98365      sqlite3_result_error_nomem(context);
 98366      return;
 98367    }
 98368  
 98369    p->db = db;
 98370    p->nRow = 0;
 98371    p->nCol = nCol;
 98372    p->nKeyCol = nKeyCol;
 98373    p->current.anDLt = (tRowcnt*)&p[1];
 98374    p->current.anEq = &p->current.anDLt[nColUp];
 98375  
 98376  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 98377    {
 98378      u8 *pSpace;                     /* Allocated space not yet assigned */
 98379      int i;                          /* Used to iterate through p->aSample[] */
 98380  
 98381      p->iGet = -1;
 98382      p->mxSample = mxSample;
 98383      p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
 98384      p->current.anLt = &p->current.anEq[nColUp];
 98385      p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
 98386    
 98387      /* Set up the Stat4Accum.a[] and aBest[] arrays */
 98388      p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
 98389      p->aBest = &p->a[mxSample];
 98390      pSpace = (u8*)(&p->a[mxSample+nCol]);
 98391      for(i=0; i<(mxSample+nCol); i++){
 98392        p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
 98393        p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
 98394        p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
 98395      }
 98396      assert( (pSpace - (u8*)p)==n );
 98397    
 98398      for(i=0; i<nCol; i++){
 98399        p->aBest[i].iCol = i;
 98400      }
 98401    }
 98402  #endif
 98403  
 98404    /* Return a pointer to the allocated object to the caller.  Note that
 98405    ** only the pointer (the 2nd parameter) matters.  The size of the object
 98406    ** (given by the 3rd parameter) is never used and can be any positive
 98407    ** value. */
 98408    sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
 98409  }
 98410  static const FuncDef statInitFuncdef = {
 98411    2+IsStat34,      /* nArg */
 98412    SQLITE_UTF8,     /* funcFlags */
 98413    0,               /* pUserData */
 98414    0,               /* pNext */
 98415    statInit,        /* xSFunc */
 98416    0,               /* xFinalize */
 98417    "stat_init",     /* zName */
 98418    {0}
 98419  };
 98420  
 98421  #ifdef SQLITE_ENABLE_STAT4
 98422  /*
 98423  ** pNew and pOld are both candidate non-periodic samples selected for 
 98424  ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and 
 98425  ** considering only any trailing columns and the sample hash value, this
 98426  ** function returns true if sample pNew is to be preferred over pOld.
 98427  ** In other words, if we assume that the cardinalities of the selected
 98428  ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
 98429  **
 98430  ** This function assumes that for each argument sample, the contents of
 98431  ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid. 
 98432  */
 98433  static int sampleIsBetterPost(
 98434    Stat4Accum *pAccum, 
 98435    Stat4Sample *pNew, 
 98436    Stat4Sample *pOld
 98437  ){
 98438    int nCol = pAccum->nCol;
 98439    int i;
 98440    assert( pNew->iCol==pOld->iCol );
 98441    for(i=pNew->iCol+1; i<nCol; i++){
 98442      if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
 98443      if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
 98444    }
 98445    if( pNew->iHash>pOld->iHash ) return 1;
 98446    return 0;
 98447  }
 98448  #endif
 98449  
 98450  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 98451  /*
 98452  ** Return true if pNew is to be preferred over pOld.
 98453  **
 98454  ** This function assumes that for each argument sample, the contents of
 98455  ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid. 
 98456  */
 98457  static int sampleIsBetter(
 98458    Stat4Accum *pAccum, 
 98459    Stat4Sample *pNew, 
 98460    Stat4Sample *pOld
 98461  ){
 98462    tRowcnt nEqNew = pNew->anEq[pNew->iCol];
 98463    tRowcnt nEqOld = pOld->anEq[pOld->iCol];
 98464  
 98465    assert( pOld->isPSample==0 && pNew->isPSample==0 );
 98466    assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
 98467  
 98468    if( (nEqNew>nEqOld) ) return 1;
 98469  #ifdef SQLITE_ENABLE_STAT4
 98470    if( nEqNew==nEqOld ){
 98471      if( pNew->iCol<pOld->iCol ) return 1;
 98472      return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
 98473    }
 98474    return 0;
 98475  #else
 98476    return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
 98477  #endif
 98478  }
 98479  
 98480  /*
 98481  ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
 98482  ** remove the least desirable sample from p->a[] to make room.
 98483  */
 98484  static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
 98485    Stat4Sample *pSample = 0;
 98486    int i;
 98487  
 98488    assert( IsStat4 || nEqZero==0 );
 98489  
 98490  #ifdef SQLITE_ENABLE_STAT4
 98491    /* Stat4Accum.nMaxEqZero is set to the maximum number of leading 0
 98492    ** values in the anEq[] array of any sample in Stat4Accum.a[]. In
 98493    ** other words, if nMaxEqZero is n, then it is guaranteed that there
 98494    ** are no samples with Stat4Sample.anEq[m]==0 for (m>=n). */
 98495    if( nEqZero>p->nMaxEqZero ){
 98496      p->nMaxEqZero = nEqZero;
 98497    }
 98498    if( pNew->isPSample==0 ){
 98499      Stat4Sample *pUpgrade = 0;
 98500      assert( pNew->anEq[pNew->iCol]>0 );
 98501  
 98502      /* This sample is being added because the prefix that ends in column 
 98503      ** iCol occurs many times in the table. However, if we have already
 98504      ** added a sample that shares this prefix, there is no need to add
 98505      ** this one. Instead, upgrade the priority of the highest priority
 98506      ** existing sample that shares this prefix.  */
 98507      for(i=p->nSample-1; i>=0; i--){
 98508        Stat4Sample *pOld = &p->a[i];
 98509        if( pOld->anEq[pNew->iCol]==0 ){
 98510          if( pOld->isPSample ) return;
 98511          assert( pOld->iCol>pNew->iCol );
 98512          assert( sampleIsBetter(p, pNew, pOld) );
 98513          if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
 98514            pUpgrade = pOld;
 98515          }
 98516        }
 98517      }
 98518      if( pUpgrade ){
 98519        pUpgrade->iCol = pNew->iCol;
 98520        pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
 98521        goto find_new_min;
 98522      }
 98523    }
 98524  #endif
 98525  
 98526    /* If necessary, remove sample iMin to make room for the new sample. */
 98527    if( p->nSample>=p->mxSample ){
 98528      Stat4Sample *pMin = &p->a[p->iMin];
 98529      tRowcnt *anEq = pMin->anEq;
 98530      tRowcnt *anLt = pMin->anLt;
 98531      tRowcnt *anDLt = pMin->anDLt;
 98532      sampleClear(p->db, pMin);
 98533      memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
 98534      pSample = &p->a[p->nSample-1];
 98535      pSample->nRowid = 0;
 98536      pSample->anEq = anEq;
 98537      pSample->anDLt = anDLt;
 98538      pSample->anLt = anLt;
 98539      p->nSample = p->mxSample-1;
 98540    }
 98541  
 98542    /* The "rows less-than" for the rowid column must be greater than that
 98543    ** for the last sample in the p->a[] array. Otherwise, the samples would
 98544    ** be out of order. */
 98545  #ifdef SQLITE_ENABLE_STAT4
 98546    assert( p->nSample==0 
 98547         || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
 98548  #endif
 98549  
 98550    /* Insert the new sample */
 98551    pSample = &p->a[p->nSample];
 98552    sampleCopy(p, pSample, pNew);
 98553    p->nSample++;
 98554  
 98555    /* Zero the first nEqZero entries in the anEq[] array. */
 98556    memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
 98557  
 98558  #ifdef SQLITE_ENABLE_STAT4
 98559   find_new_min:
 98560  #endif
 98561    if( p->nSample>=p->mxSample ){
 98562      int iMin = -1;
 98563      for(i=0; i<p->mxSample; i++){
 98564        if( p->a[i].isPSample ) continue;
 98565        if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
 98566          iMin = i;
 98567        }
 98568      }
 98569      assert( iMin>=0 );
 98570      p->iMin = iMin;
 98571    }
 98572  }
 98573  #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
 98574  
 98575  /*
 98576  ** Field iChng of the index being scanned has changed. So at this point
 98577  ** p->current contains a sample that reflects the previous row of the
 98578  ** index. The value of anEq[iChng] and subsequent anEq[] elements are
 98579  ** correct at this point.
 98580  */
 98581  static void samplePushPrevious(Stat4Accum *p, int iChng){
 98582  #ifdef SQLITE_ENABLE_STAT4
 98583    int i;
 98584  
 98585    /* Check if any samples from the aBest[] array should be pushed
 98586    ** into IndexSample.a[] at this point.  */
 98587    for(i=(p->nCol-2); i>=iChng; i--){
 98588      Stat4Sample *pBest = &p->aBest[i];
 98589      pBest->anEq[i] = p->current.anEq[i];
 98590      if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
 98591        sampleInsert(p, pBest, i);
 98592      }
 98593    }
 98594  
 98595    /* Check that no sample contains an anEq[] entry with an index of
 98596    ** p->nMaxEqZero or greater set to zero. */
 98597    for(i=p->nSample-1; i>=0; i--){
 98598      int j;
 98599      for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );
 98600    }
 98601  
 98602    /* Update the anEq[] fields of any samples already collected. */
 98603    if( iChng<p->nMaxEqZero ){
 98604      for(i=p->nSample-1; i>=0; i--){
 98605        int j;
 98606        for(j=iChng; j<p->nCol; j++){
 98607          if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
 98608        }
 98609      }
 98610      p->nMaxEqZero = iChng;
 98611    }
 98612  #endif
 98613  
 98614  #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
 98615    if( iChng==0 ){
 98616      tRowcnt nLt = p->current.anLt[0];
 98617      tRowcnt nEq = p->current.anEq[0];
 98618  
 98619      /* Check if this is to be a periodic sample. If so, add it. */
 98620      if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
 98621        p->current.isPSample = 1;
 98622        sampleInsert(p, &p->current, 0);
 98623        p->current.isPSample = 0;
 98624      }else 
 98625  
 98626      /* Or if it is a non-periodic sample. Add it in this case too. */
 98627      if( p->nSample<p->mxSample 
 98628       || sampleIsBetter(p, &p->current, &p->a[p->iMin]) 
 98629      ){
 98630        sampleInsert(p, &p->current, 0);
 98631      }
 98632    }
 98633  #endif
 98634  
 98635  #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
 98636    UNUSED_PARAMETER( p );
 98637    UNUSED_PARAMETER( iChng );
 98638  #endif
 98639  }
 98640  
 98641  /*
 98642  ** Implementation of the stat_push SQL function:  stat_push(P,C,R)
 98643  ** Arguments:
 98644  **
 98645  **    P     Pointer to the Stat4Accum object created by stat_init()
 98646  **    C     Index of left-most column to differ from previous row
 98647  **    R     Rowid for the current row.  Might be a key record for
 98648  **          WITHOUT ROWID tables.
 98649  **
 98650  ** This SQL function always returns NULL.  It's purpose it to accumulate
 98651  ** statistical data and/or samples in the Stat4Accum object about the
 98652  ** index being analyzed.  The stat_get() SQL function will later be used to
 98653  ** extract relevant information for constructing the sqlite_statN tables.
 98654  **
 98655  ** The R parameter is only used for STAT3 and STAT4
 98656  */
 98657  static void statPush(
 98658    sqlite3_context *context,
 98659    int argc,
 98660    sqlite3_value **argv
 98661  ){
 98662    int i;
 98663  
 98664    /* The three function arguments */
 98665    Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
 98666    int iChng = sqlite3_value_int(argv[1]);
 98667  
 98668    UNUSED_PARAMETER( argc );
 98669    UNUSED_PARAMETER( context );
 98670    assert( p->nCol>0 );
 98671    assert( iChng<p->nCol );
 98672  
 98673    if( p->nRow==0 ){
 98674      /* This is the first call to this function. Do initialization. */
 98675      for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
 98676    }else{
 98677      /* Second and subsequent calls get processed here */
 98678      samplePushPrevious(p, iChng);
 98679  
 98680      /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
 98681      ** to the current row of the index. */
 98682      for(i=0; i<iChng; i++){
 98683        p->current.anEq[i]++;
 98684      }
 98685      for(i=iChng; i<p->nCol; i++){
 98686        p->current.anDLt[i]++;
 98687  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 98688        p->current.anLt[i] += p->current.anEq[i];
 98689  #endif
 98690        p->current.anEq[i] = 1;
 98691      }
 98692    }
 98693    p->nRow++;
 98694  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 98695    if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
 98696      sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
 98697    }else{
 98698      sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
 98699                                         sqlite3_value_blob(argv[2]));
 98700    }
 98701    p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
 98702  #endif
 98703  
 98704  #ifdef SQLITE_ENABLE_STAT4
 98705    {
 98706      tRowcnt nLt = p->current.anLt[p->nCol-1];
 98707  
 98708      /* Check if this is to be a periodic sample. If so, add it. */
 98709      if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
 98710        p->current.isPSample = 1;
 98711        p->current.iCol = 0;
 98712        sampleInsert(p, &p->current, p->nCol-1);
 98713        p->current.isPSample = 0;
 98714      }
 98715  
 98716      /* Update the aBest[] array. */
 98717      for(i=0; i<(p->nCol-1); i++){
 98718        p->current.iCol = i;
 98719        if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
 98720          sampleCopy(p, &p->aBest[i], &p->current);
 98721        }
 98722      }
 98723    }
 98724  #endif
 98725  }
 98726  static const FuncDef statPushFuncdef = {
 98727    2+IsStat34,      /* nArg */
 98728    SQLITE_UTF8,     /* funcFlags */
 98729    0,               /* pUserData */
 98730    0,               /* pNext */
 98731    statPush,        /* xSFunc */
 98732    0,               /* xFinalize */
 98733    "stat_push",     /* zName */
 98734    {0}
 98735  };
 98736  
 98737  #define STAT_GET_STAT1 0          /* "stat" column of stat1 table */
 98738  #define STAT_GET_ROWID 1          /* "rowid" column of stat[34] entry */
 98739  #define STAT_GET_NEQ   2          /* "neq" column of stat[34] entry */
 98740  #define STAT_GET_NLT   3          /* "nlt" column of stat[34] entry */
 98741  #define STAT_GET_NDLT  4          /* "ndlt" column of stat[34] entry */
 98742  
 98743  /*
 98744  ** Implementation of the stat_get(P,J) SQL function.  This routine is
 98745  ** used to query statistical information that has been gathered into
 98746  ** the Stat4Accum object by prior calls to stat_push().  The P parameter
 98747  ** has type BLOB but it is really just a pointer to the Stat4Accum object.
 98748  ** The content to returned is determined by the parameter J
 98749  ** which is one of the STAT_GET_xxxx values defined above.
 98750  **
 98751  ** The stat_get(P,J) function is not available to generic SQL.  It is
 98752  ** inserted as part of a manually constructed bytecode program.  (See
 98753  ** the callStatGet() routine below.)  It is guaranteed that the P
 98754  ** parameter will always be a poiner to a Stat4Accum object, never a
 98755  ** NULL.
 98756  **
 98757  ** If neither STAT3 nor STAT4 are enabled, then J is always
 98758  ** STAT_GET_STAT1 and is hence omitted and this routine becomes
 98759  ** a one-parameter function, stat_get(P), that always returns the
 98760  ** stat1 table entry information.
 98761  */
 98762  static void statGet(
 98763    sqlite3_context *context,
 98764    int argc,
 98765    sqlite3_value **argv
 98766  ){
 98767    Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
 98768  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 98769    /* STAT3 and STAT4 have a parameter on this routine. */
 98770    int eCall = sqlite3_value_int(argv[1]);
 98771    assert( argc==2 );
 98772    assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ 
 98773         || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
 98774         || eCall==STAT_GET_NDLT 
 98775    );
 98776    if( eCall==STAT_GET_STAT1 )
 98777  #else
 98778    assert( argc==1 );
 98779  #endif
 98780    {
 98781      /* Return the value to store in the "stat" column of the sqlite_stat1
 98782      ** table for this index.
 98783      **
 98784      ** The value is a string composed of a list of integers describing 
 98785      ** the index. The first integer in the list is the total number of 
 98786      ** entries in the index. There is one additional integer in the list 
 98787      ** for each indexed column. This additional integer is an estimate of
 98788      ** the number of rows matched by a stabbing query on the index using
 98789      ** a key with the corresponding number of fields. In other words,
 98790      ** if the index is on columns (a,b) and the sqlite_stat1 value is 
 98791      ** "100 10 2", then SQLite estimates that:
 98792      **
 98793      **   * the index contains 100 rows,
 98794      **   * "WHERE a=?" matches 10 rows, and
 98795      **   * "WHERE a=? AND b=?" matches 2 rows.
 98796      **
 98797      ** If D is the count of distinct values and K is the total number of 
 98798      ** rows, then each estimate is computed as:
 98799      **
 98800      **        I = (K+D-1)/D
 98801      */
 98802      char *z;
 98803      int i;
 98804  
 98805      char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
 98806      if( zRet==0 ){
 98807        sqlite3_result_error_nomem(context);
 98808        return;
 98809      }
 98810  
 98811      sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
 98812      z = zRet + sqlite3Strlen30(zRet);
 98813      for(i=0; i<p->nKeyCol; i++){
 98814        u64 nDistinct = p->current.anDLt[i] + 1;
 98815        u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
 98816        sqlite3_snprintf(24, z, " %llu", iVal);
 98817        z += sqlite3Strlen30(z);
 98818        assert( p->current.anEq[i] );
 98819      }
 98820      assert( z[0]=='\0' && z>zRet );
 98821  
 98822      sqlite3_result_text(context, zRet, -1, sqlite3_free);
 98823    }
 98824  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 98825    else if( eCall==STAT_GET_ROWID ){
 98826      if( p->iGet<0 ){
 98827        samplePushPrevious(p, 0);
 98828        p->iGet = 0;
 98829      }
 98830      if( p->iGet<p->nSample ){
 98831        Stat4Sample *pS = p->a + p->iGet;
 98832        if( pS->nRowid==0 ){
 98833          sqlite3_result_int64(context, pS->u.iRowid);
 98834        }else{
 98835          sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
 98836                              SQLITE_TRANSIENT);
 98837        }
 98838      }
 98839    }else{
 98840      tRowcnt *aCnt = 0;
 98841  
 98842      assert( p->iGet<p->nSample );
 98843      switch( eCall ){
 98844        case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;
 98845        case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;
 98846        default: {
 98847          aCnt = p->a[p->iGet].anDLt; 
 98848          p->iGet++;
 98849          break;
 98850        }
 98851      }
 98852  
 98853      if( IsStat3 ){
 98854        sqlite3_result_int64(context, (i64)aCnt[0]);
 98855      }else{
 98856        char *zRet = sqlite3MallocZero(p->nCol * 25);
 98857        if( zRet==0 ){
 98858          sqlite3_result_error_nomem(context);
 98859        }else{
 98860          int i;
 98861          char *z = zRet;
 98862          for(i=0; i<p->nCol; i++){
 98863            sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
 98864            z += sqlite3Strlen30(z);
 98865          }
 98866          assert( z[0]=='\0' && z>zRet );
 98867          z[-1] = '\0';
 98868          sqlite3_result_text(context, zRet, -1, sqlite3_free);
 98869        }
 98870      }
 98871    }
 98872  #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
 98873  #ifndef SQLITE_DEBUG
 98874    UNUSED_PARAMETER( argc );
 98875  #endif
 98876  }
 98877  static const FuncDef statGetFuncdef = {
 98878    1+IsStat34,      /* nArg */
 98879    SQLITE_UTF8,     /* funcFlags */
 98880    0,               /* pUserData */
 98881    0,               /* pNext */
 98882    statGet,         /* xSFunc */
 98883    0,               /* xFinalize */
 98884    "stat_get",      /* zName */
 98885    {0}
 98886  };
 98887  
 98888  static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
 98889    assert( regOut!=regStat4 && regOut!=regStat4+1 );
 98890  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 98891    sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
 98892  #elif SQLITE_DEBUG
 98893    assert( iParam==STAT_GET_STAT1 );
 98894  #else
 98895    UNUSED_PARAMETER( iParam );
 98896  #endif
 98897    sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
 98898                      (char*)&statGetFuncdef, P4_FUNCDEF);
 98899    sqlite3VdbeChangeP5(v, 1 + IsStat34);
 98900  }
 98901  
 98902  /*
 98903  ** Generate code to do an analysis of all indices associated with
 98904  ** a single table.
 98905  */
 98906  static void analyzeOneTable(
 98907    Parse *pParse,   /* Parser context */
 98908    Table *pTab,     /* Table whose indices are to be analyzed */
 98909    Index *pOnlyIdx, /* If not NULL, only analyze this one index */
 98910    int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
 98911    int iMem,        /* Available memory locations begin here */
 98912    int iTab         /* Next available cursor */
 98913  ){
 98914    sqlite3 *db = pParse->db;    /* Database handle */
 98915    Index *pIdx;                 /* An index to being analyzed */
 98916    int iIdxCur;                 /* Cursor open on index being analyzed */
 98917    int iTabCur;                 /* Table cursor */
 98918    Vdbe *v;                     /* The virtual machine being built up */
 98919    int i;                       /* Loop counter */
 98920    int jZeroRows = -1;          /* Jump from here if number of rows is zero */
 98921    int iDb;                     /* Index of database containing pTab */
 98922    u8 needTableCnt = 1;         /* True to count the table */
 98923    int regNewRowid = iMem++;    /* Rowid for the inserted record */
 98924    int regStat4 = iMem++;       /* Register to hold Stat4Accum object */
 98925    int regChng = iMem++;        /* Index of changed index field */
 98926  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 98927    int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
 98928  #endif
 98929    int regTemp = iMem++;        /* Temporary use register */
 98930    int regTabname = iMem++;     /* Register containing table name */
 98931    int regIdxname = iMem++;     /* Register containing index name */
 98932    int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
 98933    int regPrev = iMem;          /* MUST BE LAST (see below) */
 98934  
 98935    pParse->nMem = MAX(pParse->nMem, iMem);
 98936    v = sqlite3GetVdbe(pParse);
 98937    if( v==0 || NEVER(pTab==0) ){
 98938      return;
 98939    }
 98940    if( pTab->tnum==0 ){
 98941      /* Do not gather statistics on views or virtual tables */
 98942      return;
 98943    }
 98944    if( sqlite3_strlike("sqlite_%", pTab->zName, 0)==0 ){
 98945      /* Do not gather statistics on system tables */
 98946      return;
 98947    }
 98948    assert( sqlite3BtreeHoldsAllMutexes(db) );
 98949    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
 98950    assert( iDb>=0 );
 98951    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 98952  #ifndef SQLITE_OMIT_AUTHORIZATION
 98953    if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
 98954        db->aDb[iDb].zDbSName ) ){
 98955      return;
 98956    }
 98957  #endif
 98958  
 98959    /* Establish a read-lock on the table at the shared-cache level. 
 98960    ** Open a read-only cursor on the table. Also allocate a cursor number
 98961    ** to use for scanning indexes (iIdxCur). No index cursor is opened at
 98962    ** this time though.  */
 98963    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
 98964    iTabCur = iTab++;
 98965    iIdxCur = iTab++;
 98966    pParse->nTab = MAX(pParse->nTab, iTab);
 98967    sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
 98968    sqlite3VdbeLoadString(v, regTabname, pTab->zName);
 98969  
 98970    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
 98971      int nCol;                     /* Number of columns in pIdx. "N" */
 98972      int addrRewind;               /* Address of "OP_Rewind iIdxCur" */
 98973      int addrNextRow;              /* Address of "next_row:" */
 98974      const char *zIdxName;         /* Name of the index */
 98975      int nColTest;                 /* Number of columns to test for changes */
 98976  
 98977      if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
 98978      if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
 98979      if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
 98980        nCol = pIdx->nKeyCol;
 98981        zIdxName = pTab->zName;
 98982        nColTest = nCol - 1;
 98983      }else{
 98984        nCol = pIdx->nColumn;
 98985        zIdxName = pIdx->zName;
 98986        nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
 98987      }
 98988  
 98989      /* Populate the register containing the index name. */
 98990      sqlite3VdbeLoadString(v, regIdxname, zIdxName);
 98991      VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
 98992  
 98993      /*
 98994      ** Pseudo-code for loop that calls stat_push():
 98995      **
 98996      **   Rewind csr
 98997      **   if eof(csr) goto end_of_scan;
 98998      **   regChng = 0
 98999      **   goto chng_addr_0;
 99000      **
 99001      **  next_row:
 99002      **   regChng = 0
 99003      **   if( idx(0) != regPrev(0) ) goto chng_addr_0
 99004      **   regChng = 1
 99005      **   if( idx(1) != regPrev(1) ) goto chng_addr_1
 99006      **   ...
 99007      **   regChng = N
 99008      **   goto chng_addr_N
 99009      **
 99010      **  chng_addr_0:
 99011      **   regPrev(0) = idx(0)
 99012      **  chng_addr_1:
 99013      **   regPrev(1) = idx(1)
 99014      **  ...
 99015      **
 99016      **  endDistinctTest:
 99017      **   regRowid = idx(rowid)
 99018      **   stat_push(P, regChng, regRowid)
 99019      **   Next csr
 99020      **   if !eof(csr) goto next_row;
 99021      **
 99022      **  end_of_scan:
 99023      */
 99024  
 99025      /* Make sure there are enough memory cells allocated to accommodate 
 99026      ** the regPrev array and a trailing rowid (the rowid slot is required
 99027      ** when building a record to insert into the sample column of 
 99028      ** the sqlite_stat4 table.  */
 99029      pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
 99030  
 99031      /* Open a read-only cursor on the index being analyzed. */
 99032      assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
 99033      sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
 99034      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
 99035      VdbeComment((v, "%s", pIdx->zName));
 99036  
 99037      /* Invoke the stat_init() function. The arguments are:
 99038      ** 
 99039      **    (1) the number of columns in the index including the rowid
 99040      **        (or for a WITHOUT ROWID table, the number of PK columns),
 99041      **    (2) the number of columns in the key without the rowid/pk
 99042      **    (3) the number of rows in the index,
 99043      **
 99044      **
 99045      ** The third argument is only used for STAT3 and STAT4
 99046      */
 99047  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 99048      sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
 99049  #endif
 99050      sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
 99051      sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
 99052      sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
 99053                       (char*)&statInitFuncdef, P4_FUNCDEF);
 99054      sqlite3VdbeChangeP5(v, 2+IsStat34);
 99055  
 99056      /* Implementation of the following:
 99057      **
 99058      **   Rewind csr
 99059      **   if eof(csr) goto end_of_scan;
 99060      **   regChng = 0
 99061      **   goto next_push_0;
 99062      **
 99063      */
 99064      addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
 99065      VdbeCoverage(v);
 99066      sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
 99067      addrNextRow = sqlite3VdbeCurrentAddr(v);
 99068  
 99069      if( nColTest>0 ){
 99070        int endDistinctTest = sqlite3VdbeMakeLabel(v);
 99071        int *aGotoChng;               /* Array of jump instruction addresses */
 99072        aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
 99073        if( aGotoChng==0 ) continue;
 99074  
 99075        /*
 99076        **  next_row:
 99077        **   regChng = 0
 99078        **   if( idx(0) != regPrev(0) ) goto chng_addr_0
 99079        **   regChng = 1
 99080        **   if( idx(1) != regPrev(1) ) goto chng_addr_1
 99081        **   ...
 99082        **   regChng = N
 99083        **   goto endDistinctTest
 99084        */
 99085        sqlite3VdbeAddOp0(v, OP_Goto);
 99086        addrNextRow = sqlite3VdbeCurrentAddr(v);
 99087        if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
 99088          /* For a single-column UNIQUE index, once we have found a non-NULL
 99089          ** row, we know that all the rest will be distinct, so skip 
 99090          ** subsequent distinctness tests. */
 99091          sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
 99092          VdbeCoverage(v);
 99093        }
 99094        for(i=0; i<nColTest; i++){
 99095          char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
 99096          sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
 99097          sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
 99098          aGotoChng[i] = 
 99099          sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
 99100          sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
 99101          VdbeCoverage(v);
 99102        }
 99103        sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
 99104        sqlite3VdbeGoto(v, endDistinctTest);
 99105    
 99106    
 99107        /*
 99108        **  chng_addr_0:
 99109        **   regPrev(0) = idx(0)
 99110        **  chng_addr_1:
 99111        **   regPrev(1) = idx(1)
 99112        **  ...
 99113        */
 99114        sqlite3VdbeJumpHere(v, addrNextRow-1);
 99115        for(i=0; i<nColTest; i++){
 99116          sqlite3VdbeJumpHere(v, aGotoChng[i]);
 99117          sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
 99118        }
 99119        sqlite3VdbeResolveLabel(v, endDistinctTest);
 99120        sqlite3DbFree(db, aGotoChng);
 99121      }
 99122    
 99123      /*
 99124      **  chng_addr_N:
 99125      **   regRowid = idx(rowid)            // STAT34 only
 99126      **   stat_push(P, regChng, regRowid)  // 3rd parameter STAT34 only
 99127      **   Next csr
 99128      **   if !eof(csr) goto next_row;
 99129      */
 99130  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 99131      assert( regRowid==(regStat4+2) );
 99132      if( HasRowid(pTab) ){
 99133        sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
 99134      }else{
 99135        Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
 99136        int j, k, regKey;
 99137        regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
 99138        for(j=0; j<pPk->nKeyCol; j++){
 99139          k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
 99140          assert( k>=0 && k<pIdx->nColumn );
 99141          sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
 99142          VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
 99143        }
 99144        sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
 99145        sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
 99146      }
 99147  #endif
 99148      assert( regChng==(regStat4+1) );
 99149      sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
 99150                       (char*)&statPushFuncdef, P4_FUNCDEF);
 99151      sqlite3VdbeChangeP5(v, 2+IsStat34);
 99152      sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
 99153  
 99154      /* Add the entry to the stat1 table. */
 99155      callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
 99156      assert( "BBB"[0]==SQLITE_AFF_TEXT );
 99157      sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
 99158      sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
 99159      sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
 99160      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
 99161  
 99162      /* Add the entries to the stat3 or stat4 table. */
 99163  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 99164      {
 99165        int regEq = regStat1;
 99166        int regLt = regStat1+1;
 99167        int regDLt = regStat1+2;
 99168        int regSample = regStat1+3;
 99169        int regCol = regStat1+4;
 99170        int regSampleRowid = regCol + nCol;
 99171        int addrNext;
 99172        int addrIsNull;
 99173        u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
 99174  
 99175        pParse->nMem = MAX(pParse->nMem, regCol+nCol);
 99176  
 99177        addrNext = sqlite3VdbeCurrentAddr(v);
 99178        callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
 99179        addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
 99180        VdbeCoverage(v);
 99181        callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
 99182        callStatGet(v, regStat4, STAT_GET_NLT, regLt);
 99183        callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
 99184        sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
 99185        /* We know that the regSampleRowid row exists because it was read by
 99186        ** the previous loop.  Thus the not-found jump of seekOp will never
 99187        ** be taken */
 99188        VdbeCoverageNeverTaken(v);
 99189  #ifdef SQLITE_ENABLE_STAT3
 99190        sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
 99191  #else
 99192        for(i=0; i<nCol; i++){
 99193          sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
 99194        }
 99195        sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
 99196  #endif
 99197        sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
 99198        sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
 99199        sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
 99200        sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
 99201        sqlite3VdbeJumpHere(v, addrIsNull);
 99202      }
 99203  #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
 99204  
 99205      /* End of analysis */
 99206      sqlite3VdbeJumpHere(v, addrRewind);
 99207    }
 99208  
 99209  
 99210    /* Create a single sqlite_stat1 entry containing NULL as the index
 99211    ** name and the row count as the content.
 99212    */
 99213    if( pOnlyIdx==0 && needTableCnt ){
 99214      VdbeComment((v, "%s", pTab->zName));
 99215      sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
 99216      jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
 99217      sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
 99218      assert( "BBB"[0]==SQLITE_AFF_TEXT );
 99219      sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
 99220      sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
 99221      sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
 99222      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
 99223      sqlite3VdbeJumpHere(v, jZeroRows);
 99224    }
 99225  }
 99226  
 99227  
 99228  /*
 99229  ** Generate code that will cause the most recent index analysis to
 99230  ** be loaded into internal hash tables where is can be used.
 99231  */
 99232  static void loadAnalysis(Parse *pParse, int iDb){
 99233    Vdbe *v = sqlite3GetVdbe(pParse);
 99234    if( v ){
 99235      sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
 99236    }
 99237  }
 99238  
 99239  /*
 99240  ** Generate code that will do an analysis of an entire database
 99241  */
 99242  static void analyzeDatabase(Parse *pParse, int iDb){
 99243    sqlite3 *db = pParse->db;
 99244    Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
 99245    HashElem *k;
 99246    int iStatCur;
 99247    int iMem;
 99248    int iTab;
 99249  
 99250    sqlite3BeginWriteOperation(pParse, 0, iDb);
 99251    iStatCur = pParse->nTab;
 99252    pParse->nTab += 3;
 99253    openStatTable(pParse, iDb, iStatCur, 0, 0);
 99254    iMem = pParse->nMem+1;
 99255    iTab = pParse->nTab;
 99256    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 99257    for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
 99258      Table *pTab = (Table*)sqliteHashData(k);
 99259      analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
 99260    }
 99261    loadAnalysis(pParse, iDb);
 99262  }
 99263  
 99264  /*
 99265  ** Generate code that will do an analysis of a single table in
 99266  ** a database.  If pOnlyIdx is not NULL then it is a single index
 99267  ** in pTab that should be analyzed.
 99268  */
 99269  static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
 99270    int iDb;
 99271    int iStatCur;
 99272  
 99273    assert( pTab!=0 );
 99274    assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
 99275    iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
 99276    sqlite3BeginWriteOperation(pParse, 0, iDb);
 99277    iStatCur = pParse->nTab;
 99278    pParse->nTab += 3;
 99279    if( pOnlyIdx ){
 99280      openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
 99281    }else{
 99282      openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
 99283    }
 99284    analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
 99285    loadAnalysis(pParse, iDb);
 99286  }
 99287  
 99288  /*
 99289  ** Generate code for the ANALYZE command.  The parser calls this routine
 99290  ** when it recognizes an ANALYZE command.
 99291  **
 99292  **        ANALYZE                            -- 1
 99293  **        ANALYZE  <database>                -- 2
 99294  **        ANALYZE  ?<database>.?<tablename>  -- 3
 99295  **
 99296  ** Form 1 causes all indices in all attached databases to be analyzed.
 99297  ** Form 2 analyzes all indices the single database named.
 99298  ** Form 3 analyzes all indices associated with the named table.
 99299  */
 99300  SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
 99301    sqlite3 *db = pParse->db;
 99302    int iDb;
 99303    int i;
 99304    char *z, *zDb;
 99305    Table *pTab;
 99306    Index *pIdx;
 99307    Token *pTableName;
 99308    Vdbe *v;
 99309  
 99310    /* Read the database schema. If an error occurs, leave an error message
 99311    ** and code in pParse and return NULL. */
 99312    assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
 99313    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
 99314      return;
 99315    }
 99316  
 99317    assert( pName2!=0 || pName1==0 );
 99318    if( pName1==0 ){
 99319      /* Form 1:  Analyze everything */
 99320      for(i=0; i<db->nDb; i++){
 99321        if( i==1 ) continue;  /* Do not analyze the TEMP database */
 99322        analyzeDatabase(pParse, i);
 99323      }
 99324    }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){
 99325      /* Analyze the schema named as the argument */
 99326      analyzeDatabase(pParse, iDb);
 99327    }else{
 99328      /* Form 3: Analyze the table or index named as an argument */
 99329      iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
 99330      if( iDb>=0 ){
 99331        zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
 99332        z = sqlite3NameFromToken(db, pTableName);
 99333        if( z ){
 99334          if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
 99335            analyzeTable(pParse, pIdx->pTable, pIdx);
 99336          }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
 99337            analyzeTable(pParse, pTab, 0);
 99338          }
 99339          sqlite3DbFree(db, z);
 99340        }
 99341      }
 99342    }
 99343    if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){
 99344      sqlite3VdbeAddOp0(v, OP_Expire);
 99345    }
 99346  }
 99347  
 99348  /*
 99349  ** Used to pass information from the analyzer reader through to the
 99350  ** callback routine.
 99351  */
 99352  typedef struct analysisInfo analysisInfo;
 99353  struct analysisInfo {
 99354    sqlite3 *db;
 99355    const char *zDatabase;
 99356  };
 99357  
 99358  /*
 99359  ** The first argument points to a nul-terminated string containing a
 99360  ** list of space separated integers. Read the first nOut of these into
 99361  ** the array aOut[].
 99362  */
 99363  static void decodeIntArray(
 99364    char *zIntArray,       /* String containing int array to decode */
 99365    int nOut,              /* Number of slots in aOut[] */
 99366    tRowcnt *aOut,         /* Store integers here */
 99367    LogEst *aLog,          /* Or, if aOut==0, here */
 99368    Index *pIndex          /* Handle extra flags for this index, if not NULL */
 99369  ){
 99370    char *z = zIntArray;
 99371    int c;
 99372    int i;
 99373    tRowcnt v;
 99374  
 99375  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 99376    if( z==0 ) z = "";
 99377  #else
 99378    assert( z!=0 );
 99379  #endif
 99380    for(i=0; *z && i<nOut; i++){
 99381      v = 0;
 99382      while( (c=z[0])>='0' && c<='9' ){
 99383        v = v*10 + c - '0';
 99384        z++;
 99385      }
 99386  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 99387      if( aOut ) aOut[i] = v;
 99388      if( aLog ) aLog[i] = sqlite3LogEst(v);
 99389  #else
 99390      assert( aOut==0 );
 99391      UNUSED_PARAMETER(aOut);
 99392      assert( aLog!=0 );
 99393      aLog[i] = sqlite3LogEst(v);
 99394  #endif
 99395      if( *z==' ' ) z++;
 99396    }
 99397  #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
 99398    assert( pIndex!=0 ); {
 99399  #else
 99400    if( pIndex ){
 99401  #endif
 99402      pIndex->bUnordered = 0;
 99403      pIndex->noSkipScan = 0;
 99404      while( z[0] ){
 99405        if( sqlite3_strglob("unordered*", z)==0 ){
 99406          pIndex->bUnordered = 1;
 99407        }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
 99408          pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
 99409        }else if( sqlite3_strglob("noskipscan*", z)==0 ){
 99410          pIndex->noSkipScan = 1;
 99411        }
 99412  #ifdef SQLITE_ENABLE_COSTMULT
 99413        else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
 99414          pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
 99415        }
 99416  #endif
 99417        while( z[0]!=0 && z[0]!=' ' ) z++;
 99418        while( z[0]==' ' ) z++;
 99419      }
 99420    }
 99421  }
 99422  
 99423  /*
 99424  ** This callback is invoked once for each index when reading the
 99425  ** sqlite_stat1 table.  
 99426  **
 99427  **     argv[0] = name of the table
 99428  **     argv[1] = name of the index (might be NULL)
 99429  **     argv[2] = results of analysis - on integer for each column
 99430  **
 99431  ** Entries for which argv[1]==NULL simply record the number of rows in
 99432  ** the table.
 99433  */
 99434  static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
 99435    analysisInfo *pInfo = (analysisInfo*)pData;
 99436    Index *pIndex;
 99437    Table *pTable;
 99438    const char *z;
 99439  
 99440    assert( argc==3 );
 99441    UNUSED_PARAMETER2(NotUsed, argc);
 99442  
 99443    if( argv==0 || argv[0]==0 || argv[2]==0 ){
 99444      return 0;
 99445    }
 99446    pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
 99447    if( pTable==0 ){
 99448      return 0;
 99449    }
 99450    if( argv[1]==0 ){
 99451      pIndex = 0;
 99452    }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
 99453      pIndex = sqlite3PrimaryKeyIndex(pTable);
 99454    }else{
 99455      pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
 99456    }
 99457    z = argv[2];
 99458  
 99459    if( pIndex ){
 99460      tRowcnt *aiRowEst = 0;
 99461      int nCol = pIndex->nKeyCol+1;
 99462  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 99463      /* Index.aiRowEst may already be set here if there are duplicate 
 99464      ** sqlite_stat1 entries for this index. In that case just clobber
 99465      ** the old data with the new instead of allocating a new array.  */
 99466      if( pIndex->aiRowEst==0 ){
 99467        pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
 99468        if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
 99469      }
 99470      aiRowEst = pIndex->aiRowEst;
 99471  #endif
 99472      pIndex->bUnordered = 0;
 99473      decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
 99474      pIndex->hasStat1 = 1;
 99475      if( pIndex->pPartIdxWhere==0 ){
 99476        pTable->nRowLogEst = pIndex->aiRowLogEst[0];
 99477        pTable->tabFlags |= TF_HasStat1;
 99478      }
 99479    }else{
 99480      Index fakeIdx;
 99481      fakeIdx.szIdxRow = pTable->szTabRow;
 99482  #ifdef SQLITE_ENABLE_COSTMULT
 99483      fakeIdx.pTable = pTable;
 99484  #endif
 99485      decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
 99486      pTable->szTabRow = fakeIdx.szIdxRow;
 99487      pTable->tabFlags |= TF_HasStat1;
 99488    }
 99489  
 99490    return 0;
 99491  }
 99492  
 99493  /*
 99494  ** If the Index.aSample variable is not NULL, delete the aSample[] array
 99495  ** and its contents.
 99496  */
 99497  SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
 99498  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 99499    if( pIdx->aSample ){
 99500      int j;
 99501      for(j=0; j<pIdx->nSample; j++){
 99502        IndexSample *p = &pIdx->aSample[j];
 99503        sqlite3DbFree(db, p->p);
 99504      }
 99505      sqlite3DbFree(db, pIdx->aSample);
 99506    }
 99507    if( db && db->pnBytesFreed==0 ){
 99508      pIdx->nSample = 0;
 99509      pIdx->aSample = 0;
 99510    }
 99511  #else
 99512    UNUSED_PARAMETER(db);
 99513    UNUSED_PARAMETER(pIdx);
 99514  #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
 99515  }
 99516  
 99517  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 99518  /*
 99519  ** Populate the pIdx->aAvgEq[] array based on the samples currently
 99520  ** stored in pIdx->aSample[]. 
 99521  */
 99522  static void initAvgEq(Index *pIdx){
 99523    if( pIdx ){
 99524      IndexSample *aSample = pIdx->aSample;
 99525      IndexSample *pFinal = &aSample[pIdx->nSample-1];
 99526      int iCol;
 99527      int nCol = 1;
 99528      if( pIdx->nSampleCol>1 ){
 99529        /* If this is stat4 data, then calculate aAvgEq[] values for all
 99530        ** sample columns except the last. The last is always set to 1, as
 99531        ** once the trailing PK fields are considered all index keys are
 99532        ** unique.  */
 99533        nCol = pIdx->nSampleCol-1;
 99534        pIdx->aAvgEq[nCol] = 1;
 99535      }
 99536      for(iCol=0; iCol<nCol; iCol++){
 99537        int nSample = pIdx->nSample;
 99538        int i;                    /* Used to iterate through samples */
 99539        tRowcnt sumEq = 0;        /* Sum of the nEq values */
 99540        tRowcnt avgEq = 0;
 99541        tRowcnt nRow;             /* Number of rows in index */
 99542        i64 nSum100 = 0;          /* Number of terms contributing to sumEq */
 99543        i64 nDist100;             /* Number of distinct values in index */
 99544  
 99545        if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
 99546          nRow = pFinal->anLt[iCol];
 99547          nDist100 = (i64)100 * pFinal->anDLt[iCol];
 99548          nSample--;
 99549        }else{
 99550          nRow = pIdx->aiRowEst[0];
 99551          nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
 99552        }
 99553        pIdx->nRowEst0 = nRow;
 99554  
 99555        /* Set nSum to the number of distinct (iCol+1) field prefixes that
 99556        ** occur in the stat4 table for this index. Set sumEq to the sum of 
 99557        ** the nEq values for column iCol for the same set (adding the value 
 99558        ** only once where there exist duplicate prefixes).  */
 99559        for(i=0; i<nSample; i++){
 99560          if( i==(pIdx->nSample-1)
 99561           || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] 
 99562          ){
 99563            sumEq += aSample[i].anEq[iCol];
 99564            nSum100 += 100;
 99565          }
 99566        }
 99567  
 99568        if( nDist100>nSum100 && sumEq<nRow ){
 99569          avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
 99570        }
 99571        if( avgEq==0 ) avgEq = 1;
 99572        pIdx->aAvgEq[iCol] = avgEq;
 99573      }
 99574    }
 99575  }
 99576  
 99577  /*
 99578  ** Look up an index by name.  Or, if the name of a WITHOUT ROWID table
 99579  ** is supplied instead, find the PRIMARY KEY index for that table.
 99580  */
 99581  static Index *findIndexOrPrimaryKey(
 99582    sqlite3 *db,
 99583    const char *zName,
 99584    const char *zDb
 99585  ){
 99586    Index *pIdx = sqlite3FindIndex(db, zName, zDb);
 99587    if( pIdx==0 ){
 99588      Table *pTab = sqlite3FindTable(db, zName, zDb);
 99589      if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
 99590    }
 99591    return pIdx;
 99592  }
 99593  
 99594  /*
 99595  ** Load the content from either the sqlite_stat4 or sqlite_stat3 table 
 99596  ** into the relevant Index.aSample[] arrays.
 99597  **
 99598  ** Arguments zSql1 and zSql2 must point to SQL statements that return
 99599  ** data equivalent to the following (statements are different for stat3,
 99600  ** see the caller of this function for details):
 99601  **
 99602  **    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
 99603  **    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
 99604  **
 99605  ** where %Q is replaced with the database name before the SQL is executed.
 99606  */
 99607  static int loadStatTbl(
 99608    sqlite3 *db,                  /* Database handle */
 99609    int bStat3,                   /* Assume single column records only */
 99610    const char *zSql1,            /* SQL statement 1 (see above) */
 99611    const char *zSql2,            /* SQL statement 2 (see above) */
 99612    const char *zDb               /* Database name (e.g. "main") */
 99613  ){
 99614    int rc;                       /* Result codes from subroutines */
 99615    sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
 99616    char *zSql;                   /* Text of the SQL statement */
 99617    Index *pPrevIdx = 0;          /* Previous index in the loop */
 99618    IndexSample *pSample;         /* A slot in pIdx->aSample[] */
 99619  
 99620    assert( db->lookaside.bDisable );
 99621    zSql = sqlite3MPrintf(db, zSql1, zDb);
 99622    if( !zSql ){
 99623      return SQLITE_NOMEM_BKPT;
 99624    }
 99625    rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
 99626    sqlite3DbFree(db, zSql);
 99627    if( rc ) return rc;
 99628  
 99629    while( sqlite3_step(pStmt)==SQLITE_ROW ){
 99630      int nIdxCol = 1;              /* Number of columns in stat4 records */
 99631  
 99632      char *zIndex;   /* Index name */
 99633      Index *pIdx;    /* Pointer to the index object */
 99634      int nSample;    /* Number of samples */
 99635      int nByte;      /* Bytes of space required */
 99636      int i;          /* Bytes of space required */
 99637      tRowcnt *pSpace;
 99638  
 99639      zIndex = (char *)sqlite3_column_text(pStmt, 0);
 99640      if( zIndex==0 ) continue;
 99641      nSample = sqlite3_column_int(pStmt, 1);
 99642      pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
 99643      assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
 99644      /* Index.nSample is non-zero at this point if data has already been
 99645      ** loaded from the stat4 table. In this case ignore stat3 data.  */
 99646      if( pIdx==0 || pIdx->nSample ) continue;
 99647      if( bStat3==0 ){
 99648        assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
 99649        if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
 99650          nIdxCol = pIdx->nKeyCol;
 99651        }else{
 99652          nIdxCol = pIdx->nColumn;
 99653        }
 99654      }
 99655      pIdx->nSampleCol = nIdxCol;
 99656      nByte = sizeof(IndexSample) * nSample;
 99657      nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
 99658      nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */
 99659  
 99660      pIdx->aSample = sqlite3DbMallocZero(db, nByte);
 99661      if( pIdx->aSample==0 ){
 99662        sqlite3_finalize(pStmt);
 99663        return SQLITE_NOMEM_BKPT;
 99664      }
 99665      pSpace = (tRowcnt*)&pIdx->aSample[nSample];
 99666      pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
 99667      for(i=0; i<nSample; i++){
 99668        pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
 99669        pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
 99670        pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
 99671      }
 99672      assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
 99673    }
 99674    rc = sqlite3_finalize(pStmt);
 99675    if( rc ) return rc;
 99676  
 99677    zSql = sqlite3MPrintf(db, zSql2, zDb);
 99678    if( !zSql ){
 99679      return SQLITE_NOMEM_BKPT;
 99680    }
 99681    rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
 99682    sqlite3DbFree(db, zSql);
 99683    if( rc ) return rc;
 99684  
 99685    while( sqlite3_step(pStmt)==SQLITE_ROW ){
 99686      char *zIndex;                 /* Index name */
 99687      Index *pIdx;                  /* Pointer to the index object */
 99688      int nCol = 1;                 /* Number of columns in index */
 99689  
 99690      zIndex = (char *)sqlite3_column_text(pStmt, 0);
 99691      if( zIndex==0 ) continue;
 99692      pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
 99693      if( pIdx==0 ) continue;
 99694      /* This next condition is true if data has already been loaded from 
 99695      ** the sqlite_stat4 table. In this case ignore stat3 data.  */
 99696      nCol = pIdx->nSampleCol;
 99697      if( bStat3 && nCol>1 ) continue;
 99698      if( pIdx!=pPrevIdx ){
 99699        initAvgEq(pPrevIdx);
 99700        pPrevIdx = pIdx;
 99701      }
 99702      pSample = &pIdx->aSample[pIdx->nSample];
 99703      decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
 99704      decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
 99705      decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
 99706  
 99707      /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
 99708      ** This is in case the sample record is corrupted. In that case, the
 99709      ** sqlite3VdbeRecordCompare() may read up to two varints past the
 99710      ** end of the allocated buffer before it realizes it is dealing with
 99711      ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
 99712      ** a buffer overread.  */
 99713      pSample->n = sqlite3_column_bytes(pStmt, 4);
 99714      pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
 99715      if( pSample->p==0 ){
 99716        sqlite3_finalize(pStmt);
 99717        return SQLITE_NOMEM_BKPT;
 99718      }
 99719      if( pSample->n ){
 99720        memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
 99721      }
 99722      pIdx->nSample++;
 99723    }
 99724    rc = sqlite3_finalize(pStmt);
 99725    if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
 99726    return rc;
 99727  }
 99728  
 99729  /*
 99730  ** Load content from the sqlite_stat4 and sqlite_stat3 tables into 
 99731  ** the Index.aSample[] arrays of all indices.
 99732  */
 99733  static int loadStat4(sqlite3 *db, const char *zDb){
 99734    int rc = SQLITE_OK;             /* Result codes from subroutines */
 99735  
 99736    assert( db->lookaside.bDisable );
 99737    if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
 99738      rc = loadStatTbl(db, 0,
 99739        "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx", 
 99740        "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
 99741        zDb
 99742      );
 99743    }
 99744  
 99745    if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
 99746      rc = loadStatTbl(db, 1,
 99747        "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx", 
 99748        "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
 99749        zDb
 99750      );
 99751    }
 99752  
 99753    return rc;
 99754  }
 99755  #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
 99756  
 99757  /*
 99758  ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
 99759  ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
 99760  ** arrays. The contents of sqlite_stat3/4 are used to populate the
 99761  ** Index.aSample[] arrays.
 99762  **
 99763  ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
 99764  ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined 
 99765  ** during compilation and the sqlite_stat3/4 table is present, no data is 
 99766  ** read from it.
 99767  **
 99768  ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the 
 99769  ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
 99770  ** returned. However, in this case, data is read from the sqlite_stat1
 99771  ** table (if it is present) before returning.
 99772  **
 99773  ** If an OOM error occurs, this function always sets db->mallocFailed.
 99774  ** This means if the caller does not care about other errors, the return
 99775  ** code may be ignored.
 99776  */
 99777  SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
 99778    analysisInfo sInfo;
 99779    HashElem *i;
 99780    char *zSql;
 99781    int rc = SQLITE_OK;
 99782    Schema *pSchema = db->aDb[iDb].pSchema;
 99783  
 99784    assert( iDb>=0 && iDb<db->nDb );
 99785    assert( db->aDb[iDb].pBt!=0 );
 99786  
 99787    /* Clear any prior statistics */
 99788    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 99789    for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){
 99790      Table *pTab = sqliteHashData(i);
 99791      pTab->tabFlags &= ~TF_HasStat1;
 99792    }
 99793    for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
 99794      Index *pIdx = sqliteHashData(i);
 99795      pIdx->hasStat1 = 0;
 99796  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 99797      sqlite3DeleteIndexSamples(db, pIdx);
 99798      pIdx->aSample = 0;
 99799  #endif
 99800    }
 99801  
 99802    /* Load new statistics out of the sqlite_stat1 table */
 99803    sInfo.db = db;
 99804    sInfo.zDatabase = db->aDb[iDb].zDbSName;
 99805    if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
 99806      zSql = sqlite3MPrintf(db, 
 99807          "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
 99808      if( zSql==0 ){
 99809        rc = SQLITE_NOMEM_BKPT;
 99810      }else{
 99811        rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
 99812        sqlite3DbFree(db, zSql);
 99813      }
 99814    }
 99815  
 99816    /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
 99817    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 99818    for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
 99819      Index *pIdx = sqliteHashData(i);
 99820      if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);
 99821    }
 99822  
 99823    /* Load the statistics from the sqlite_stat4 table. */
 99824  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 99825    if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
 99826      db->lookaside.bDisable++;
 99827      rc = loadStat4(db, sInfo.zDatabase);
 99828      db->lookaside.bDisable--;
 99829    }
 99830    for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
 99831      Index *pIdx = sqliteHashData(i);
 99832      sqlite3_free(pIdx->aiRowEst);
 99833      pIdx->aiRowEst = 0;
 99834    }
 99835  #endif
 99836  
 99837    if( rc==SQLITE_NOMEM ){
 99838      sqlite3OomFault(db);
 99839    }
 99840    return rc;
 99841  }
 99842  
 99843  
 99844  #endif /* SQLITE_OMIT_ANALYZE */
 99845  
 99846  /************** End of analyze.c *********************************************/
 99847  /************** Begin file attach.c ******************************************/
 99848  /*
 99849  ** 2003 April 6
 99850  **
 99851  ** The author disclaims copyright to this source code.  In place of
 99852  ** a legal notice, here is a blessing:
 99853  **
 99854  **    May you do good and not evil.
 99855  **    May you find forgiveness for yourself and forgive others.
 99856  **    May you share freely, never taking more than you give.
 99857  **
 99858  *************************************************************************
 99859  ** This file contains code used to implement the ATTACH and DETACH commands.
 99860  */
 99861  /* #include "sqliteInt.h" */
 99862  
 99863  #ifndef SQLITE_OMIT_ATTACH
 99864  /*
 99865  ** Resolve an expression that was part of an ATTACH or DETACH statement. This
 99866  ** is slightly different from resolving a normal SQL expression, because simple
 99867  ** identifiers are treated as strings, not possible column names or aliases.
 99868  **
 99869  ** i.e. if the parser sees:
 99870  **
 99871  **     ATTACH DATABASE abc AS def
 99872  **
 99873  ** it treats the two expressions as literal strings 'abc' and 'def' instead of
 99874  ** looking for columns of the same name.
 99875  **
 99876  ** This only applies to the root node of pExpr, so the statement:
 99877  **
 99878  **     ATTACH DATABASE abc||def AS 'db2'
 99879  **
 99880  ** will fail because neither abc or def can be resolved.
 99881  */
 99882  static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
 99883  {
 99884    int rc = SQLITE_OK;
 99885    if( pExpr ){
 99886      if( pExpr->op!=TK_ID ){
 99887        rc = sqlite3ResolveExprNames(pName, pExpr);
 99888      }else{
 99889        pExpr->op = TK_STRING;
 99890      }
 99891    }
 99892    return rc;
 99893  }
 99894  
 99895  /*
 99896  ** An SQL user-function registered to do the work of an ATTACH statement. The
 99897  ** three arguments to the function come directly from an attach statement:
 99898  **
 99899  **     ATTACH DATABASE x AS y KEY z
 99900  **
 99901  **     SELECT sqlite_attach(x, y, z)
 99902  **
 99903  ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
 99904  ** third argument.
 99905  */
 99906  static void attachFunc(
 99907    sqlite3_context *context,
 99908    int NotUsed,
 99909    sqlite3_value **argv
 99910  ){
 99911    int i;
 99912    int rc = 0;
 99913    sqlite3 *db = sqlite3_context_db_handle(context);
 99914    const char *zName;
 99915    const char *zFile;
 99916    char *zPath = 0;
 99917    char *zErr = 0;
 99918    unsigned int flags;
 99919    Db *aNew;                 /* New array of Db pointers */
 99920    Db *pNew;                 /* Db object for the newly attached database */
 99921    char *zErrDyn = 0;
 99922    sqlite3_vfs *pVfs;
 99923  
 99924    UNUSED_PARAMETER(NotUsed);
 99925  
 99926    zFile = (const char *)sqlite3_value_text(argv[0]);
 99927    zName = (const char *)sqlite3_value_text(argv[1]);
 99928    if( zFile==0 ) zFile = "";
 99929    if( zName==0 ) zName = "";
 99930  
 99931    /* Check for the following errors:
 99932    **
 99933    **     * Too many attached databases,
 99934    **     * Transaction currently open
 99935    **     * Specified database name already being used.
 99936    */
 99937    if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
 99938      zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
 99939        db->aLimit[SQLITE_LIMIT_ATTACHED]
 99940      );
 99941      goto attach_error;
 99942    }
 99943    for(i=0; i<db->nDb; i++){
 99944      char *z = db->aDb[i].zDbSName;
 99945      assert( z && zName );
 99946      if( sqlite3StrICmp(z, zName)==0 ){
 99947        zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
 99948        goto attach_error;
 99949      }
 99950    }
 99951  
 99952    /* Allocate the new entry in the db->aDb[] array and initialize the schema
 99953    ** hash tables.
 99954    */
 99955    if( db->aDb==db->aDbStatic ){
 99956      aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
 99957      if( aNew==0 ) return;
 99958      memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
 99959    }else{
 99960      aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
 99961      if( aNew==0 ) return;
 99962    }
 99963    db->aDb = aNew;
 99964    pNew = &db->aDb[db->nDb];
 99965    memset(pNew, 0, sizeof(*pNew));
 99966  
 99967    /* Open the database file. If the btree is successfully opened, use
 99968    ** it to obtain the database schema. At this point the schema may
 99969    ** or may not be initialized.
 99970    */
 99971    flags = db->openFlags;
 99972    rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
 99973    if( rc!=SQLITE_OK ){
 99974      if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
 99975      sqlite3_result_error(context, zErr, -1);
 99976      sqlite3_free(zErr);
 99977      return;
 99978    }
 99979    assert( pVfs );
 99980    flags |= SQLITE_OPEN_MAIN_DB;
 99981    rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags);
 99982    sqlite3_free( zPath );
 99983    db->nDb++;
 99984    db->skipBtreeMutex = 0;
 99985    if( rc==SQLITE_CONSTRAINT ){
 99986      rc = SQLITE_ERROR;
 99987      zErrDyn = sqlite3MPrintf(db, "database is already attached");
 99988    }else if( rc==SQLITE_OK ){
 99989      Pager *pPager;
 99990      pNew->pSchema = sqlite3SchemaGet(db, pNew->pBt);
 99991      if( !pNew->pSchema ){
 99992        rc = SQLITE_NOMEM_BKPT;
 99993      }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){
 99994        zErrDyn = sqlite3MPrintf(db, 
 99995          "attached databases must use the same text encoding as main database");
 99996        rc = SQLITE_ERROR;
 99997      }
 99998      sqlite3BtreeEnter(pNew->pBt);
 99999      pPager = sqlite3BtreePager(pNew->pBt);
100000      sqlite3PagerLockingMode(pPager, db->dfltLockMode);
100001      sqlite3BtreeSecureDelete(pNew->pBt,
100002                               sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
100003  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
100004      sqlite3BtreeSetPagerFlags(pNew->pBt,
100005                        PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
100006  #endif
100007      sqlite3BtreeLeave(pNew->pBt);
100008    }
100009    pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
100010    pNew->zDbSName = sqlite3DbStrDup(db, zName);
100011    if( rc==SQLITE_OK && pNew->zDbSName==0 ){
100012      rc = SQLITE_NOMEM_BKPT;
100013    }
100014  
100015  
100016  #ifdef SQLITE_HAS_CODEC
100017    if( rc==SQLITE_OK ){
100018      extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
100019      extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
100020      int nKey;
100021      char *zKey;
100022      int t = sqlite3_value_type(argv[2]);
100023      switch( t ){
100024        case SQLITE_INTEGER:
100025        case SQLITE_FLOAT:
100026          zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
100027          rc = SQLITE_ERROR;
100028          break;
100029          
100030        case SQLITE_TEXT:
100031        case SQLITE_BLOB:
100032          nKey = sqlite3_value_bytes(argv[2]);
100033          zKey = (char *)sqlite3_value_blob(argv[2]);
100034          rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
100035          break;
100036  
100037        case SQLITE_NULL:
100038          /* No key specified.  Use the key from the main database */
100039          sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
100040          if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
100041            rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
100042          }
100043          break;
100044      }
100045    }
100046  #endif
100047  
100048    /* If the file was opened successfully, read the schema for the new database.
100049    ** If this fails, or if opening the file failed, then close the file and 
100050    ** remove the entry from the db->aDb[] array. i.e. put everything back the way
100051    ** we found it.
100052    */
100053    if( rc==SQLITE_OK ){
100054      sqlite3BtreeEnterAll(db);
100055      rc = sqlite3Init(db, &zErrDyn);
100056      sqlite3BtreeLeaveAll(db);
100057    }
100058  #ifdef SQLITE_USER_AUTHENTICATION
100059    if( rc==SQLITE_OK ){
100060      u8 newAuth = 0;
100061      rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
100062      if( newAuth<db->auth.authLevel ){
100063        rc = SQLITE_AUTH_USER;
100064      }
100065    }
100066  #endif
100067    if( rc ){
100068      int iDb = db->nDb - 1;
100069      assert( iDb>=2 );
100070      if( db->aDb[iDb].pBt ){
100071        sqlite3BtreeClose(db->aDb[iDb].pBt);
100072        db->aDb[iDb].pBt = 0;
100073        db->aDb[iDb].pSchema = 0;
100074      }
100075      sqlite3ResetAllSchemasOfConnection(db);
100076      db->nDb = iDb;
100077      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
100078        sqlite3OomFault(db);
100079        sqlite3DbFree(db, zErrDyn);
100080        zErrDyn = sqlite3MPrintf(db, "out of memory");
100081      }else if( zErrDyn==0 ){
100082        zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
100083      }
100084      goto attach_error;
100085    }
100086    
100087    return;
100088  
100089  attach_error:
100090    /* Return an error if we get here */
100091    if( zErrDyn ){
100092      sqlite3_result_error(context, zErrDyn, -1);
100093      sqlite3DbFree(db, zErrDyn);
100094    }
100095    if( rc ) sqlite3_result_error_code(context, rc);
100096  }
100097  
100098  /*
100099  ** An SQL user-function registered to do the work of an DETACH statement. The
100100  ** three arguments to the function come directly from a detach statement:
100101  **
100102  **     DETACH DATABASE x
100103  **
100104  **     SELECT sqlite_detach(x)
100105  */
100106  static void detachFunc(
100107    sqlite3_context *context,
100108    int NotUsed,
100109    sqlite3_value **argv
100110  ){
100111    const char *zName = (const char *)sqlite3_value_text(argv[0]);
100112    sqlite3 *db = sqlite3_context_db_handle(context);
100113    int i;
100114    Db *pDb = 0;
100115    char zErr[128];
100116  
100117    UNUSED_PARAMETER(NotUsed);
100118  
100119    if( zName==0 ) zName = "";
100120    for(i=0; i<db->nDb; i++){
100121      pDb = &db->aDb[i];
100122      if( pDb->pBt==0 ) continue;
100123      if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break;
100124    }
100125  
100126    if( i>=db->nDb ){
100127      sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
100128      goto detach_error;
100129    }
100130    if( i<2 ){
100131      sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
100132      goto detach_error;
100133    }
100134    if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
100135      sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
100136      goto detach_error;
100137    }
100138  
100139    sqlite3BtreeClose(pDb->pBt);
100140    pDb->pBt = 0;
100141    pDb->pSchema = 0;
100142    sqlite3CollapseDatabaseArray(db);
100143    return;
100144  
100145  detach_error:
100146    sqlite3_result_error(context, zErr, -1);
100147  }
100148  
100149  /*
100150  ** This procedure generates VDBE code for a single invocation of either the
100151  ** sqlite_detach() or sqlite_attach() SQL user functions.
100152  */
100153  static void codeAttach(
100154    Parse *pParse,       /* The parser context */
100155    int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
100156    FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
100157    Expr *pAuthArg,      /* Expression to pass to authorization callback */
100158    Expr *pFilename,     /* Name of database file */
100159    Expr *pDbname,       /* Name of the database to use internally */
100160    Expr *pKey           /* Database key for encryption extension */
100161  ){
100162    int rc;
100163    NameContext sName;
100164    Vdbe *v;
100165    sqlite3* db = pParse->db;
100166    int regArgs;
100167  
100168    if( pParse->nErr ) goto attach_end;
100169    memset(&sName, 0, sizeof(NameContext));
100170    sName.pParse = pParse;
100171  
100172    if( 
100173        SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
100174        SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
100175        SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
100176    ){
100177      goto attach_end;
100178    }
100179  
100180  #ifndef SQLITE_OMIT_AUTHORIZATION
100181    if( pAuthArg ){
100182      char *zAuthArg;
100183      if( pAuthArg->op==TK_STRING ){
100184        zAuthArg = pAuthArg->u.zToken;
100185      }else{
100186        zAuthArg = 0;
100187      }
100188      rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
100189      if(rc!=SQLITE_OK ){
100190        goto attach_end;
100191      }
100192    }
100193  #endif /* SQLITE_OMIT_AUTHORIZATION */
100194  
100195  
100196    v = sqlite3GetVdbe(pParse);
100197    regArgs = sqlite3GetTempRange(pParse, 4);
100198    sqlite3ExprCode(pParse, pFilename, regArgs);
100199    sqlite3ExprCode(pParse, pDbname, regArgs+1);
100200    sqlite3ExprCode(pParse, pKey, regArgs+2);
100201  
100202    assert( v || db->mallocFailed );
100203    if( v ){
100204      sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
100205                        (char *)pFunc, P4_FUNCDEF);
100206      assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
100207      sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
100208   
100209      /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
100210      ** statement only). For DETACH, set it to false (expire all existing
100211      ** statements).
100212      */
100213      sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
100214    }
100215    
100216  attach_end:
100217    sqlite3ExprDelete(db, pFilename);
100218    sqlite3ExprDelete(db, pDbname);
100219    sqlite3ExprDelete(db, pKey);
100220  }
100221  
100222  /*
100223  ** Called by the parser to compile a DETACH statement.
100224  **
100225  **     DETACH pDbname
100226  */
100227  SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
100228    static const FuncDef detach_func = {
100229      1,                /* nArg */
100230      SQLITE_UTF8,      /* funcFlags */
100231      0,                /* pUserData */
100232      0,                /* pNext */
100233      detachFunc,       /* xSFunc */
100234      0,                /* xFinalize */
100235      "sqlite_detach",  /* zName */
100236      {0}
100237    };
100238    codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
100239  }
100240  
100241  /*
100242  ** Called by the parser to compile an ATTACH statement.
100243  **
100244  **     ATTACH p AS pDbname KEY pKey
100245  */
100246  SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
100247    static const FuncDef attach_func = {
100248      3,                /* nArg */
100249      SQLITE_UTF8,      /* funcFlags */
100250      0,                /* pUserData */
100251      0,                /* pNext */
100252      attachFunc,       /* xSFunc */
100253      0,                /* xFinalize */
100254      "sqlite_attach",  /* zName */
100255      {0}
100256    };
100257    codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
100258  }
100259  #endif /* SQLITE_OMIT_ATTACH */
100260  
100261  /*
100262  ** Initialize a DbFixer structure.  This routine must be called prior
100263  ** to passing the structure to one of the sqliteFixAAAA() routines below.
100264  */
100265  SQLITE_PRIVATE void sqlite3FixInit(
100266    DbFixer *pFix,      /* The fixer to be initialized */
100267    Parse *pParse,      /* Error messages will be written here */
100268    int iDb,            /* This is the database that must be used */
100269    const char *zType,  /* "view", "trigger", or "index" */
100270    const Token *pName  /* Name of the view, trigger, or index */
100271  ){
100272    sqlite3 *db;
100273  
100274    db = pParse->db;
100275    assert( db->nDb>iDb );
100276    pFix->pParse = pParse;
100277    pFix->zDb = db->aDb[iDb].zDbSName;
100278    pFix->pSchema = db->aDb[iDb].pSchema;
100279    pFix->zType = zType;
100280    pFix->pName = pName;
100281    pFix->bVarOnly = (iDb==1);
100282  }
100283  
100284  /*
100285  ** The following set of routines walk through the parse tree and assign
100286  ** a specific database to all table references where the database name
100287  ** was left unspecified in the original SQL statement.  The pFix structure
100288  ** must have been initialized by a prior call to sqlite3FixInit().
100289  **
100290  ** These routines are used to make sure that an index, trigger, or
100291  ** view in one database does not refer to objects in a different database.
100292  ** (Exception: indices, triggers, and views in the TEMP database are
100293  ** allowed to refer to anything.)  If a reference is explicitly made
100294  ** to an object in a different database, an error message is added to
100295  ** pParse->zErrMsg and these routines return non-zero.  If everything
100296  ** checks out, these routines return 0.
100297  */
100298  SQLITE_PRIVATE int sqlite3FixSrcList(
100299    DbFixer *pFix,       /* Context of the fixation */
100300    SrcList *pList       /* The Source list to check and modify */
100301  ){
100302    int i;
100303    const char *zDb;
100304    struct SrcList_item *pItem;
100305  
100306    if( NEVER(pList==0) ) return 0;
100307    zDb = pFix->zDb;
100308    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
100309      if( pFix->bVarOnly==0 ){
100310        if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
100311          sqlite3ErrorMsg(pFix->pParse,
100312              "%s %T cannot reference objects in database %s",
100313              pFix->zType, pFix->pName, pItem->zDatabase);
100314          return 1;
100315        }
100316        sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
100317        pItem->zDatabase = 0;
100318        pItem->pSchema = pFix->pSchema;
100319      }
100320  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
100321      if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
100322      if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
100323  #endif
100324    }
100325    return 0;
100326  }
100327  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
100328  SQLITE_PRIVATE int sqlite3FixSelect(
100329    DbFixer *pFix,       /* Context of the fixation */
100330    Select *pSelect      /* The SELECT statement to be fixed to one database */
100331  ){
100332    while( pSelect ){
100333      if( sqlite3FixExprList(pFix, pSelect->pEList) ){
100334        return 1;
100335      }
100336      if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
100337        return 1;
100338      }
100339      if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
100340        return 1;
100341      }
100342      if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
100343        return 1;
100344      }
100345      if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
100346        return 1;
100347      }
100348      if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
100349        return 1;
100350      }
100351      if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
100352        return 1;
100353      }
100354      if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
100355        return 1;
100356      }
100357      pSelect = pSelect->pPrior;
100358    }
100359    return 0;
100360  }
100361  SQLITE_PRIVATE int sqlite3FixExpr(
100362    DbFixer *pFix,     /* Context of the fixation */
100363    Expr *pExpr        /* The expression to be fixed to one database */
100364  ){
100365    while( pExpr ){
100366      if( pExpr->op==TK_VARIABLE ){
100367        if( pFix->pParse->db->init.busy ){
100368          pExpr->op = TK_NULL;
100369        }else{
100370          sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
100371          return 1;
100372        }
100373      }
100374      if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
100375      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
100376        if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
100377      }else{
100378        if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
100379      }
100380      if( sqlite3FixExpr(pFix, pExpr->pRight) ){
100381        return 1;
100382      }
100383      pExpr = pExpr->pLeft;
100384    }
100385    return 0;
100386  }
100387  SQLITE_PRIVATE int sqlite3FixExprList(
100388    DbFixer *pFix,     /* Context of the fixation */
100389    ExprList *pList    /* The expression to be fixed to one database */
100390  ){
100391    int i;
100392    struct ExprList_item *pItem;
100393    if( pList==0 ) return 0;
100394    for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
100395      if( sqlite3FixExpr(pFix, pItem->pExpr) ){
100396        return 1;
100397      }
100398    }
100399    return 0;
100400  }
100401  #endif
100402  
100403  #ifndef SQLITE_OMIT_TRIGGER
100404  SQLITE_PRIVATE int sqlite3FixTriggerStep(
100405    DbFixer *pFix,     /* Context of the fixation */
100406    TriggerStep *pStep /* The trigger step be fixed to one database */
100407  ){
100408    while( pStep ){
100409      if( sqlite3FixSelect(pFix, pStep->pSelect) ){
100410        return 1;
100411      }
100412      if( sqlite3FixExpr(pFix, pStep->pWhere) ){
100413        return 1;
100414      }
100415      if( sqlite3FixExprList(pFix, pStep->pExprList) ){
100416        return 1;
100417      }
100418      pStep = pStep->pNext;
100419    }
100420    return 0;
100421  }
100422  #endif
100423  
100424  /************** End of attach.c **********************************************/
100425  /************** Begin file auth.c ********************************************/
100426  /*
100427  ** 2003 January 11
100428  **
100429  ** The author disclaims copyright to this source code.  In place of
100430  ** a legal notice, here is a blessing:
100431  **
100432  **    May you do good and not evil.
100433  **    May you find forgiveness for yourself and forgive others.
100434  **    May you share freely, never taking more than you give.
100435  **
100436  *************************************************************************
100437  ** This file contains code used to implement the sqlite3_set_authorizer()
100438  ** API.  This facility is an optional feature of the library.  Embedded
100439  ** systems that do not need this facility may omit it by recompiling
100440  ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
100441  */
100442  /* #include "sqliteInt.h" */
100443  
100444  /*
100445  ** All of the code in this file may be omitted by defining a single
100446  ** macro.
100447  */
100448  #ifndef SQLITE_OMIT_AUTHORIZATION
100449  
100450  /*
100451  ** Set or clear the access authorization function.
100452  **
100453  ** The access authorization function is be called during the compilation
100454  ** phase to verify that the user has read and/or write access permission on
100455  ** various fields of the database.  The first argument to the auth function
100456  ** is a copy of the 3rd argument to this routine.  The second argument
100457  ** to the auth function is one of these constants:
100458  **
100459  **       SQLITE_CREATE_INDEX
100460  **       SQLITE_CREATE_TABLE
100461  **       SQLITE_CREATE_TEMP_INDEX
100462  **       SQLITE_CREATE_TEMP_TABLE
100463  **       SQLITE_CREATE_TEMP_TRIGGER
100464  **       SQLITE_CREATE_TEMP_VIEW
100465  **       SQLITE_CREATE_TRIGGER
100466  **       SQLITE_CREATE_VIEW
100467  **       SQLITE_DELETE
100468  **       SQLITE_DROP_INDEX
100469  **       SQLITE_DROP_TABLE
100470  **       SQLITE_DROP_TEMP_INDEX
100471  **       SQLITE_DROP_TEMP_TABLE
100472  **       SQLITE_DROP_TEMP_TRIGGER
100473  **       SQLITE_DROP_TEMP_VIEW
100474  **       SQLITE_DROP_TRIGGER
100475  **       SQLITE_DROP_VIEW
100476  **       SQLITE_INSERT
100477  **       SQLITE_PRAGMA
100478  **       SQLITE_READ
100479  **       SQLITE_SELECT
100480  **       SQLITE_TRANSACTION
100481  **       SQLITE_UPDATE
100482  **
100483  ** The third and fourth arguments to the auth function are the name of
100484  ** the table and the column that are being accessed.  The auth function
100485  ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
100486  ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
100487  ** means that the SQL statement will never-run - the sqlite3_exec() call
100488  ** will return with an error.  SQLITE_IGNORE means that the SQL statement
100489  ** should run but attempts to read the specified column will return NULL
100490  ** and attempts to write the column will be ignored.
100491  **
100492  ** Setting the auth function to NULL disables this hook.  The default
100493  ** setting of the auth function is NULL.
100494  */
100495  SQLITE_API int sqlite3_set_authorizer(
100496    sqlite3 *db,
100497    int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
100498    void *pArg
100499  ){
100500  #ifdef SQLITE_ENABLE_API_ARMOR
100501    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
100502  #endif
100503    sqlite3_mutex_enter(db->mutex);
100504    db->xAuth = (sqlite3_xauth)xAuth;
100505    db->pAuthArg = pArg;
100506    sqlite3ExpirePreparedStatements(db);
100507    sqlite3_mutex_leave(db->mutex);
100508    return SQLITE_OK;
100509  }
100510  
100511  /*
100512  ** Write an error message into pParse->zErrMsg that explains that the
100513  ** user-supplied authorization function returned an illegal value.
100514  */
100515  static void sqliteAuthBadReturnCode(Parse *pParse){
100516    sqlite3ErrorMsg(pParse, "authorizer malfunction");
100517    pParse->rc = SQLITE_ERROR;
100518  }
100519  
100520  /*
100521  ** Invoke the authorization callback for permission to read column zCol from
100522  ** table zTab in database zDb. This function assumes that an authorization
100523  ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
100524  **
100525  ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
100526  ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
100527  ** is treated as SQLITE_DENY. In this case an error is left in pParse.
100528  */
100529  SQLITE_PRIVATE int sqlite3AuthReadCol(
100530    Parse *pParse,                  /* The parser context */
100531    const char *zTab,               /* Table name */
100532    const char *zCol,               /* Column name */
100533    int iDb                         /* Index of containing database. */
100534  ){
100535    sqlite3 *db = pParse->db;          /* Database handle */
100536    char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
100537    int rc;                            /* Auth callback return code */
100538  
100539    if( db->init.busy ) return SQLITE_OK;
100540    rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
100541  #ifdef SQLITE_USER_AUTHENTICATION
100542                   ,db->auth.zAuthUser
100543  #endif
100544                  );
100545    if( rc==SQLITE_DENY ){
100546      char *z = sqlite3_mprintf("%s.%s", zTab, zCol);
100547      if( db->nDb>2 || iDb!=0 ) z = sqlite3_mprintf("%s.%z", zDb, z);
100548      sqlite3ErrorMsg(pParse, "access to %z is prohibited", z);
100549      pParse->rc = SQLITE_AUTH;
100550    }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
100551      sqliteAuthBadReturnCode(pParse);
100552    }
100553    return rc;
100554  }
100555  
100556  /*
100557  ** The pExpr should be a TK_COLUMN expression.  The table referred to
100558  ** is in pTabList or else it is the NEW or OLD table of a trigger.  
100559  ** Check to see if it is OK to read this particular column.
100560  **
100561  ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
100562  ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
100563  ** then generate an error.
100564  */
100565  SQLITE_PRIVATE void sqlite3AuthRead(
100566    Parse *pParse,        /* The parser context */
100567    Expr *pExpr,          /* The expression to check authorization on */
100568    Schema *pSchema,      /* The schema of the expression */
100569    SrcList *pTabList     /* All table that pExpr might refer to */
100570  ){
100571    sqlite3 *db = pParse->db;
100572    Table *pTab = 0;      /* The table being read */
100573    const char *zCol;     /* Name of the column of the table */
100574    int iSrc;             /* Index in pTabList->a[] of table being read */
100575    int iDb;              /* The index of the database the expression refers to */
100576    int iCol;             /* Index of column in table */
100577  
100578    if( db->xAuth==0 ) return;
100579    iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
100580    if( iDb<0 ){
100581      /* An attempt to read a column out of a subquery or other
100582      ** temporary table. */
100583      return;
100584    }
100585  
100586    assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
100587    if( pExpr->op==TK_TRIGGER ){
100588      pTab = pParse->pTriggerTab;
100589    }else{
100590      assert( pTabList );
100591      for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
100592        if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
100593          pTab = pTabList->a[iSrc].pTab;
100594          break;
100595        }
100596      }
100597    }
100598    iCol = pExpr->iColumn;
100599    if( NEVER(pTab==0) ) return;
100600  
100601    if( iCol>=0 ){
100602      assert( iCol<pTab->nCol );
100603      zCol = pTab->aCol[iCol].zName;
100604    }else if( pTab->iPKey>=0 ){
100605      assert( pTab->iPKey<pTab->nCol );
100606      zCol = pTab->aCol[pTab->iPKey].zName;
100607    }else{
100608      zCol = "ROWID";
100609    }
100610    assert( iDb>=0 && iDb<db->nDb );
100611    if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
100612      pExpr->op = TK_NULL;
100613    }
100614  }
100615  
100616  /*
100617  ** Do an authorization check using the code and arguments given.  Return
100618  ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
100619  ** is returned, then the error count and error message in pParse are
100620  ** modified appropriately.
100621  */
100622  SQLITE_PRIVATE int sqlite3AuthCheck(
100623    Parse *pParse,
100624    int code,
100625    const char *zArg1,
100626    const char *zArg2,
100627    const char *zArg3
100628  ){
100629    sqlite3 *db = pParse->db;
100630    int rc;
100631  
100632    /* Don't do any authorization checks if the database is initialising
100633    ** or if the parser is being invoked from within sqlite3_declare_vtab.
100634    */
100635    if( db->init.busy || IN_DECLARE_VTAB ){
100636      return SQLITE_OK;
100637    }
100638  
100639    if( db->xAuth==0 ){
100640      return SQLITE_OK;
100641    }
100642  
100643    /* EVIDENCE-OF: R-43249-19882 The third through sixth parameters to the
100644    ** callback are either NULL pointers or zero-terminated strings that
100645    ** contain additional details about the action to be authorized.
100646    **
100647    ** The following testcase() macros show that any of the 3rd through 6th
100648    ** parameters can be either NULL or a string. */
100649    testcase( zArg1==0 );
100650    testcase( zArg2==0 );
100651    testcase( zArg3==0 );
100652    testcase( pParse->zAuthContext==0 );
100653  
100654    rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
100655  #ifdef SQLITE_USER_AUTHENTICATION
100656                   ,db->auth.zAuthUser
100657  #endif
100658                  );
100659    if( rc==SQLITE_DENY ){
100660      sqlite3ErrorMsg(pParse, "not authorized");
100661      pParse->rc = SQLITE_AUTH;
100662    }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
100663      rc = SQLITE_DENY;
100664      sqliteAuthBadReturnCode(pParse);
100665    }
100666    return rc;
100667  }
100668  
100669  /*
100670  ** Push an authorization context.  After this routine is called, the
100671  ** zArg3 argument to authorization callbacks will be zContext until
100672  ** popped.  Or if pParse==0, this routine is a no-op.
100673  */
100674  SQLITE_PRIVATE void sqlite3AuthContextPush(
100675    Parse *pParse,
100676    AuthContext *pContext, 
100677    const char *zContext
100678  ){
100679    assert( pParse );
100680    pContext->pParse = pParse;
100681    pContext->zAuthContext = pParse->zAuthContext;
100682    pParse->zAuthContext = zContext;
100683  }
100684  
100685  /*
100686  ** Pop an authorization context that was previously pushed
100687  ** by sqlite3AuthContextPush
100688  */
100689  SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
100690    if( pContext->pParse ){
100691      pContext->pParse->zAuthContext = pContext->zAuthContext;
100692      pContext->pParse = 0;
100693    }
100694  }
100695  
100696  #endif /* SQLITE_OMIT_AUTHORIZATION */
100697  
100698  /************** End of auth.c ************************************************/
100699  /************** Begin file build.c *******************************************/
100700  /*
100701  ** 2001 September 15
100702  **
100703  ** The author disclaims copyright to this source code.  In place of
100704  ** a legal notice, here is a blessing:
100705  **
100706  **    May you do good and not evil.
100707  **    May you find forgiveness for yourself and forgive others.
100708  **    May you share freely, never taking more than you give.
100709  **
100710  *************************************************************************
100711  ** This file contains C code routines that are called by the SQLite parser
100712  ** when syntax rules are reduced.  The routines in this file handle the
100713  ** following kinds of SQL syntax:
100714  **
100715  **     CREATE TABLE
100716  **     DROP TABLE
100717  **     CREATE INDEX
100718  **     DROP INDEX
100719  **     creating ID lists
100720  **     BEGIN TRANSACTION
100721  **     COMMIT
100722  **     ROLLBACK
100723  */
100724  /* #include "sqliteInt.h" */
100725  
100726  #ifndef SQLITE_OMIT_SHARED_CACHE
100727  /*
100728  ** The TableLock structure is only used by the sqlite3TableLock() and
100729  ** codeTableLocks() functions.
100730  */
100731  struct TableLock {
100732    int iDb;               /* The database containing the table to be locked */
100733    int iTab;              /* The root page of the table to be locked */
100734    u8 isWriteLock;        /* True for write lock.  False for a read lock */
100735    const char *zLockName; /* Name of the table */
100736  };
100737  
100738  /*
100739  ** Record the fact that we want to lock a table at run-time.  
100740  **
100741  ** The table to be locked has root page iTab and is found in database iDb.
100742  ** A read or a write lock can be taken depending on isWritelock.
100743  **
100744  ** This routine just records the fact that the lock is desired.  The
100745  ** code to make the lock occur is generated by a later call to
100746  ** codeTableLocks() which occurs during sqlite3FinishCoding().
100747  */
100748  SQLITE_PRIVATE void sqlite3TableLock(
100749    Parse *pParse,     /* Parsing context */
100750    int iDb,           /* Index of the database containing the table to lock */
100751    int iTab,          /* Root page number of the table to be locked */
100752    u8 isWriteLock,    /* True for a write lock */
100753    const char *zName  /* Name of the table to be locked */
100754  ){
100755    Parse *pToplevel = sqlite3ParseToplevel(pParse);
100756    int i;
100757    int nBytes;
100758    TableLock *p;
100759    assert( iDb>=0 );
100760  
100761    if( iDb==1 ) return;
100762    if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
100763    for(i=0; i<pToplevel->nTableLock; i++){
100764      p = &pToplevel->aTableLock[i];
100765      if( p->iDb==iDb && p->iTab==iTab ){
100766        p->isWriteLock = (p->isWriteLock || isWriteLock);
100767        return;
100768      }
100769    }
100770  
100771    nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
100772    pToplevel->aTableLock =
100773        sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
100774    if( pToplevel->aTableLock ){
100775      p = &pToplevel->aTableLock[pToplevel->nTableLock++];
100776      p->iDb = iDb;
100777      p->iTab = iTab;
100778      p->isWriteLock = isWriteLock;
100779      p->zLockName = zName;
100780    }else{
100781      pToplevel->nTableLock = 0;
100782      sqlite3OomFault(pToplevel->db);
100783    }
100784  }
100785  
100786  /*
100787  ** Code an OP_TableLock instruction for each table locked by the
100788  ** statement (configured by calls to sqlite3TableLock()).
100789  */
100790  static void codeTableLocks(Parse *pParse){
100791    int i;
100792    Vdbe *pVdbe; 
100793  
100794    pVdbe = sqlite3GetVdbe(pParse);
100795    assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
100796  
100797    for(i=0; i<pParse->nTableLock; i++){
100798      TableLock *p = &pParse->aTableLock[i];
100799      int p1 = p->iDb;
100800      sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
100801                        p->zLockName, P4_STATIC);
100802    }
100803  }
100804  #else
100805    #define codeTableLocks(x)
100806  #endif
100807  
100808  /*
100809  ** Return TRUE if the given yDbMask object is empty - if it contains no
100810  ** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
100811  ** macros when SQLITE_MAX_ATTACHED is greater than 30.
100812  */
100813  #if SQLITE_MAX_ATTACHED>30
100814  SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
100815    int i;
100816    for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
100817    return 1;
100818  }
100819  #endif
100820  
100821  /*
100822  ** This routine is called after a single SQL statement has been
100823  ** parsed and a VDBE program to execute that statement has been
100824  ** prepared.  This routine puts the finishing touches on the
100825  ** VDBE program and resets the pParse structure for the next
100826  ** parse.
100827  **
100828  ** Note that if an error occurred, it might be the case that
100829  ** no VDBE code was generated.
100830  */
100831  SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
100832    sqlite3 *db;
100833    Vdbe *v;
100834  
100835    assert( pParse->pToplevel==0 );
100836    db = pParse->db;
100837    if( pParse->nested ) return;
100838    if( db->mallocFailed || pParse->nErr ){
100839      if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
100840      return;
100841    }
100842  
100843    /* Begin by generating some termination code at the end of the
100844    ** vdbe program
100845    */
100846    v = sqlite3GetVdbe(pParse);
100847    assert( !pParse->isMultiWrite 
100848         || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
100849    if( v ){
100850      sqlite3VdbeAddOp0(v, OP_Halt);
100851  
100852  #if SQLITE_USER_AUTHENTICATION
100853      if( pParse->nTableLock>0 && db->init.busy==0 ){
100854        sqlite3UserAuthInit(db);
100855        if( db->auth.authLevel<UAUTH_User ){
100856          sqlite3ErrorMsg(pParse, "user not authenticated");
100857          pParse->rc = SQLITE_AUTH_USER;
100858          return;
100859        }
100860      }
100861  #endif
100862  
100863      /* The cookie mask contains one bit for each database file open.
100864      ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
100865      ** set for each database that is used.  Generate code to start a
100866      ** transaction on each used database and to verify the schema cookie
100867      ** on each used database.
100868      */
100869      if( db->mallocFailed==0 
100870       && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
100871      ){
100872        int iDb, i;
100873        assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
100874        sqlite3VdbeJumpHere(v, 0);
100875        for(iDb=0; iDb<db->nDb; iDb++){
100876          Schema *pSchema;
100877          if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
100878          sqlite3VdbeUsesBtree(v, iDb);
100879          pSchema = db->aDb[iDb].pSchema;
100880          sqlite3VdbeAddOp4Int(v,
100881            OP_Transaction,                    /* Opcode */
100882            iDb,                               /* P1 */
100883            DbMaskTest(pParse->writeMask,iDb), /* P2 */
100884            pSchema->schema_cookie,            /* P3 */
100885            pSchema->iGeneration               /* P4 */
100886          );
100887          if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
100888          VdbeComment((v,
100889                "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
100890        }
100891  #ifndef SQLITE_OMIT_VIRTUALTABLE
100892        for(i=0; i<pParse->nVtabLock; i++){
100893          char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
100894          sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
100895        }
100896        pParse->nVtabLock = 0;
100897  #endif
100898  
100899        /* Once all the cookies have been verified and transactions opened, 
100900        ** obtain the required table-locks. This is a no-op unless the 
100901        ** shared-cache feature is enabled.
100902        */
100903        codeTableLocks(pParse);
100904  
100905        /* Initialize any AUTOINCREMENT data structures required.
100906        */
100907        sqlite3AutoincrementBegin(pParse);
100908  
100909        /* Code constant expressions that where factored out of inner loops */
100910        if( pParse->pConstExpr ){
100911          ExprList *pEL = pParse->pConstExpr;
100912          pParse->okConstFactor = 0;
100913          for(i=0; i<pEL->nExpr; i++){
100914            sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
100915          }
100916        }
100917  
100918        /* Finally, jump back to the beginning of the executable code. */
100919        sqlite3VdbeGoto(v, 1);
100920      }
100921    }
100922  
100923  
100924    /* Get the VDBE program ready for execution
100925    */
100926    if( v && pParse->nErr==0 && !db->mallocFailed ){
100927      assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
100928      /* A minimum of one cursor is required if autoincrement is used
100929      *  See ticket [a696379c1f08866] */
100930      if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
100931      sqlite3VdbeMakeReady(v, pParse);
100932      pParse->rc = SQLITE_DONE;
100933    }else{
100934      pParse->rc = SQLITE_ERROR;
100935    }
100936  }
100937  
100938  /*
100939  ** Run the parser and code generator recursively in order to generate
100940  ** code for the SQL statement given onto the end of the pParse context
100941  ** currently under construction.  When the parser is run recursively
100942  ** this way, the final OP_Halt is not appended and other initialization
100943  ** and finalization steps are omitted because those are handling by the
100944  ** outermost parser.
100945  **
100946  ** Not everything is nestable.  This facility is designed to permit
100947  ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
100948  ** care if you decide to try to use this routine for some other purposes.
100949  */
100950  SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
100951    va_list ap;
100952    char *zSql;
100953    char *zErrMsg = 0;
100954    sqlite3 *db = pParse->db;
100955    char saveBuf[PARSE_TAIL_SZ];
100956  
100957    if( pParse->nErr ) return;
100958    assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
100959    va_start(ap, zFormat);
100960    zSql = sqlite3VMPrintf(db, zFormat, ap);
100961    va_end(ap);
100962    if( zSql==0 ){
100963      return;   /* A malloc must have failed */
100964    }
100965    pParse->nested++;
100966    memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
100967    memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
100968    sqlite3RunParser(pParse, zSql, &zErrMsg);
100969    sqlite3DbFree(db, zErrMsg);
100970    sqlite3DbFree(db, zSql);
100971    memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
100972    pParse->nested--;
100973  }
100974  
100975  #if SQLITE_USER_AUTHENTICATION
100976  /*
100977  ** Return TRUE if zTable is the name of the system table that stores the
100978  ** list of users and their access credentials.
100979  */
100980  SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
100981    return sqlite3_stricmp(zTable, "sqlite_user")==0;
100982  }
100983  #endif
100984  
100985  /*
100986  ** Locate the in-memory structure that describes a particular database
100987  ** table given the name of that table and (optionally) the name of the
100988  ** database containing the table.  Return NULL if not found.
100989  **
100990  ** If zDatabase is 0, all databases are searched for the table and the
100991  ** first matching table is returned.  (No checking for duplicate table
100992  ** names is done.)  The search order is TEMP first, then MAIN, then any
100993  ** auxiliary databases added using the ATTACH command.
100994  **
100995  ** See also sqlite3LocateTable().
100996  */
100997  SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
100998    Table *p = 0;
100999    int i;
101000  
101001    /* All mutexes are required for schema access.  Make sure we hold them. */
101002    assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
101003  #if SQLITE_USER_AUTHENTICATION
101004    /* Only the admin user is allowed to know that the sqlite_user table
101005    ** exists */
101006    if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
101007      return 0;
101008    }
101009  #endif
101010    while(1){
101011      for(i=OMIT_TEMPDB; i<db->nDb; i++){
101012        int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
101013        if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
101014          assert( sqlite3SchemaMutexHeld(db, j, 0) );
101015          p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
101016          if( p ) return p;
101017        }
101018      }
101019      /* Not found.  If the name we were looking for was temp.sqlite_master
101020      ** then change the name to sqlite_temp_master and try again. */
101021      if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break;
101022      if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break;
101023      zName = TEMP_MASTER_NAME;
101024    }
101025    return 0;
101026  }
101027  
101028  /*
101029  ** Locate the in-memory structure that describes a particular database
101030  ** table given the name of that table and (optionally) the name of the
101031  ** database containing the table.  Return NULL if not found.  Also leave an
101032  ** error message in pParse->zErrMsg.
101033  **
101034  ** The difference between this routine and sqlite3FindTable() is that this
101035  ** routine leaves an error message in pParse->zErrMsg where
101036  ** sqlite3FindTable() does not.
101037  */
101038  SQLITE_PRIVATE Table *sqlite3LocateTable(
101039    Parse *pParse,         /* context in which to report errors */
101040    u32 flags,             /* LOCATE_VIEW or LOCATE_NOERR */
101041    const char *zName,     /* Name of the table we are looking for */
101042    const char *zDbase     /* Name of the database.  Might be NULL */
101043  ){
101044    Table *p;
101045  
101046    /* Read the database schema. If an error occurs, leave an error message
101047    ** and code in pParse and return NULL. */
101048    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
101049      return 0;
101050    }
101051  
101052    p = sqlite3FindTable(pParse->db, zName, zDbase);
101053    if( p==0 ){
101054      const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
101055  #ifndef SQLITE_OMIT_VIRTUALTABLE
101056      if( sqlite3FindDbName(pParse->db, zDbase)<1 ){
101057        /* If zName is the not the name of a table in the schema created using
101058        ** CREATE, then check to see if it is the name of an virtual table that
101059        ** can be an eponymous virtual table. */
101060        Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
101061        if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
101062          pMod = sqlite3PragmaVtabRegister(pParse->db, zName);
101063        }
101064        if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
101065          return pMod->pEpoTab;
101066        }
101067      }
101068  #endif
101069      if( (flags & LOCATE_NOERR)==0 ){
101070        if( zDbase ){
101071          sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
101072        }else{
101073          sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
101074        }
101075        pParse->checkSchema = 1;
101076      }
101077    }
101078  
101079    return p;
101080  }
101081  
101082  /*
101083  ** Locate the table identified by *p.
101084  **
101085  ** This is a wrapper around sqlite3LocateTable(). The difference between
101086  ** sqlite3LocateTable() and this function is that this function restricts
101087  ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
101088  ** non-NULL if it is part of a view or trigger program definition. See
101089  ** sqlite3FixSrcList() for details.
101090  */
101091  SQLITE_PRIVATE Table *sqlite3LocateTableItem(
101092    Parse *pParse, 
101093    u32 flags,
101094    struct SrcList_item *p
101095  ){
101096    const char *zDb;
101097    assert( p->pSchema==0 || p->zDatabase==0 );
101098    if( p->pSchema ){
101099      int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
101100      zDb = pParse->db->aDb[iDb].zDbSName;
101101    }else{
101102      zDb = p->zDatabase;
101103    }
101104    return sqlite3LocateTable(pParse, flags, p->zName, zDb);
101105  }
101106  
101107  /*
101108  ** Locate the in-memory structure that describes 
101109  ** a particular index given the name of that index
101110  ** and the name of the database that contains the index.
101111  ** Return NULL if not found.
101112  **
101113  ** If zDatabase is 0, all databases are searched for the
101114  ** table and the first matching index is returned.  (No checking
101115  ** for duplicate index names is done.)  The search order is
101116  ** TEMP first, then MAIN, then any auxiliary databases added
101117  ** using the ATTACH command.
101118  */
101119  SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
101120    Index *p = 0;
101121    int i;
101122    /* All mutexes are required for schema access.  Make sure we hold them. */
101123    assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
101124    for(i=OMIT_TEMPDB; i<db->nDb; i++){
101125      int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
101126      Schema *pSchema = db->aDb[j].pSchema;
101127      assert( pSchema );
101128      if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
101129      assert( sqlite3SchemaMutexHeld(db, j, 0) );
101130      p = sqlite3HashFind(&pSchema->idxHash, zName);
101131      if( p ) break;
101132    }
101133    return p;
101134  }
101135  
101136  /*
101137  ** Reclaim the memory used by an index
101138  */
101139  static void freeIndex(sqlite3 *db, Index *p){
101140  #ifndef SQLITE_OMIT_ANALYZE
101141    sqlite3DeleteIndexSamples(db, p);
101142  #endif
101143    sqlite3ExprDelete(db, p->pPartIdxWhere);
101144    sqlite3ExprListDelete(db, p->aColExpr);
101145    sqlite3DbFree(db, p->zColAff);
101146    if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
101147  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
101148    sqlite3_free(p->aiRowEst);
101149  #endif
101150    sqlite3DbFree(db, p);
101151  }
101152  
101153  /*
101154  ** For the index called zIdxName which is found in the database iDb,
101155  ** unlike that index from its Table then remove the index from
101156  ** the index hash table and free all memory structures associated
101157  ** with the index.
101158  */
101159  SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
101160    Index *pIndex;
101161    Hash *pHash;
101162  
101163    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101164    pHash = &db->aDb[iDb].pSchema->idxHash;
101165    pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
101166    if( ALWAYS(pIndex) ){
101167      if( pIndex->pTable->pIndex==pIndex ){
101168        pIndex->pTable->pIndex = pIndex->pNext;
101169      }else{
101170        Index *p;
101171        /* Justification of ALWAYS();  The index must be on the list of
101172        ** indices. */
101173        p = pIndex->pTable->pIndex;
101174        while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
101175        if( ALWAYS(p && p->pNext==pIndex) ){
101176          p->pNext = pIndex->pNext;
101177        }
101178      }
101179      freeIndex(db, pIndex);
101180    }
101181    db->mDbFlags |= DBFLAG_SchemaChange;
101182  }
101183  
101184  /*
101185  ** Look through the list of open database files in db->aDb[] and if
101186  ** any have been closed, remove them from the list.  Reallocate the
101187  ** db->aDb[] structure to a smaller size, if possible.
101188  **
101189  ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
101190  ** are never candidates for being collapsed.
101191  */
101192  SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
101193    int i, j;
101194    for(i=j=2; i<db->nDb; i++){
101195      struct Db *pDb = &db->aDb[i];
101196      if( pDb->pBt==0 ){
101197        sqlite3DbFree(db, pDb->zDbSName);
101198        pDb->zDbSName = 0;
101199        continue;
101200      }
101201      if( j<i ){
101202        db->aDb[j] = db->aDb[i];
101203      }
101204      j++;
101205    }
101206    db->nDb = j;
101207    if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
101208      memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
101209      sqlite3DbFree(db, db->aDb);
101210      db->aDb = db->aDbStatic;
101211    }
101212  }
101213  
101214  /*
101215  ** Reset the schema for the database at index iDb.  Also reset the
101216  ** TEMP schema.  The reset is deferred if db->nSchemaLock is not zero.
101217  ** Deferred resets may be run by calling with iDb<0.
101218  */
101219  SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
101220    int i;
101221    assert( iDb<db->nDb );
101222  
101223    if( iDb>=0 ){
101224      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101225      DbSetProperty(db, iDb, DB_ResetWanted);
101226      DbSetProperty(db, 1, DB_ResetWanted);
101227    }
101228  
101229    if( db->nSchemaLock==0 ){
101230      for(i=0; i<db->nDb; i++){
101231        if( DbHasProperty(db, i, DB_ResetWanted) ){
101232          sqlite3SchemaClear(db->aDb[i].pSchema);
101233        }
101234      }
101235    }
101236  }
101237  
101238  /*
101239  ** Erase all schema information from all attached databases (including
101240  ** "main" and "temp") for a single database connection.
101241  */
101242  SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
101243    int i;
101244    sqlite3BtreeEnterAll(db);
101245    assert( db->nSchemaLock==0 );
101246    for(i=0; i<db->nDb; i++){
101247      Db *pDb = &db->aDb[i];
101248      if( pDb->pSchema ){
101249        sqlite3SchemaClear(pDb->pSchema);
101250      }
101251    }
101252    db->mDbFlags &= ~DBFLAG_SchemaChange;
101253    sqlite3VtabUnlockList(db);
101254    sqlite3BtreeLeaveAll(db);
101255    sqlite3CollapseDatabaseArray(db);
101256  }
101257  
101258  /*
101259  ** This routine is called when a commit occurs.
101260  */
101261  SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
101262    db->mDbFlags &= ~DBFLAG_SchemaChange;
101263  }
101264  
101265  /*
101266  ** Delete memory allocated for the column names of a table or view (the
101267  ** Table.aCol[] array).
101268  */
101269  SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
101270    int i;
101271    Column *pCol;
101272    assert( pTable!=0 );
101273    if( (pCol = pTable->aCol)!=0 ){
101274      for(i=0; i<pTable->nCol; i++, pCol++){
101275        sqlite3DbFree(db, pCol->zName);
101276        sqlite3ExprDelete(db, pCol->pDflt);
101277        sqlite3DbFree(db, pCol->zColl);
101278      }
101279      sqlite3DbFree(db, pTable->aCol);
101280    }
101281  }
101282  
101283  /*
101284  ** Remove the memory data structures associated with the given
101285  ** Table.  No changes are made to disk by this routine.
101286  **
101287  ** This routine just deletes the data structure.  It does not unlink
101288  ** the table data structure from the hash table.  But it does destroy
101289  ** memory structures of the indices and foreign keys associated with 
101290  ** the table.
101291  **
101292  ** The db parameter is optional.  It is needed if the Table object 
101293  ** contains lookaside memory.  (Table objects in the schema do not use
101294  ** lookaside memory, but some ephemeral Table objects do.)  Or the
101295  ** db parameter can be used with db->pnBytesFreed to measure the memory
101296  ** used by the Table object.
101297  */
101298  static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
101299    Index *pIndex, *pNext;
101300  
101301  #ifdef SQLITE_DEBUG
101302    /* Record the number of outstanding lookaside allocations in schema Tables
101303    ** prior to doing any free() operations.  Since schema Tables do not use
101304    ** lookaside, this number should not change. */
101305    int nLookaside = 0;
101306    if( db && (pTable->tabFlags & TF_Ephemeral)==0 ){
101307      nLookaside = sqlite3LookasideUsed(db, 0);
101308    }
101309  #endif
101310  
101311    /* Delete all indices associated with this table. */
101312    for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
101313      pNext = pIndex->pNext;
101314      assert( pIndex->pSchema==pTable->pSchema
101315           || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
101316      if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
101317        char *zName = pIndex->zName; 
101318        TESTONLY ( Index *pOld = ) sqlite3HashInsert(
101319           &pIndex->pSchema->idxHash, zName, 0
101320        );
101321        assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
101322        assert( pOld==pIndex || pOld==0 );
101323      }
101324      freeIndex(db, pIndex);
101325    }
101326  
101327    /* Delete any foreign keys attached to this table. */
101328    sqlite3FkDelete(db, pTable);
101329  
101330    /* Delete the Table structure itself.
101331    */
101332    sqlite3DeleteColumnNames(db, pTable);
101333    sqlite3DbFree(db, pTable->zName);
101334    sqlite3DbFree(db, pTable->zColAff);
101335    sqlite3SelectDelete(db, pTable->pSelect);
101336    sqlite3ExprListDelete(db, pTable->pCheck);
101337  #ifndef SQLITE_OMIT_VIRTUALTABLE
101338    sqlite3VtabClear(db, pTable);
101339  #endif
101340    sqlite3DbFree(db, pTable);
101341  
101342    /* Verify that no lookaside memory was used by schema tables */
101343    assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
101344  }
101345  SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
101346    /* Do not delete the table until the reference count reaches zero. */
101347    if( !pTable ) return;
101348    if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;
101349    deleteTable(db, pTable);
101350  }
101351  
101352  
101353  /*
101354  ** Unlink the given table from the hash tables and the delete the
101355  ** table structure with all its indices and foreign keys.
101356  */
101357  SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
101358    Table *p;
101359    Db *pDb;
101360  
101361    assert( db!=0 );
101362    assert( iDb>=0 && iDb<db->nDb );
101363    assert( zTabName );
101364    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101365    testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
101366    pDb = &db->aDb[iDb];
101367    p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
101368    sqlite3DeleteTable(db, p);
101369    db->mDbFlags |= DBFLAG_SchemaChange;
101370  }
101371  
101372  /*
101373  ** Given a token, return a string that consists of the text of that
101374  ** token.  Space to hold the returned string
101375  ** is obtained from sqliteMalloc() and must be freed by the calling
101376  ** function.
101377  **
101378  ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
101379  ** surround the body of the token are removed.
101380  **
101381  ** Tokens are often just pointers into the original SQL text and so
101382  ** are not \000 terminated and are not persistent.  The returned string
101383  ** is \000 terminated and is persistent.
101384  */
101385  SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
101386    char *zName;
101387    if( pName ){
101388      zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
101389      sqlite3Dequote(zName);
101390    }else{
101391      zName = 0;
101392    }
101393    return zName;
101394  }
101395  
101396  /*
101397  ** Open the sqlite_master table stored in database number iDb for
101398  ** writing. The table is opened using cursor 0.
101399  */
101400  SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
101401    Vdbe *v = sqlite3GetVdbe(p);
101402    sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);
101403    sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
101404    if( p->nTab==0 ){
101405      p->nTab = 1;
101406    }
101407  }
101408  
101409  /*
101410  ** Parameter zName points to a nul-terminated buffer containing the name
101411  ** of a database ("main", "temp" or the name of an attached db). This
101412  ** function returns the index of the named database in db->aDb[], or
101413  ** -1 if the named db cannot be found.
101414  */
101415  SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
101416    int i = -1;         /* Database number */
101417    if( zName ){
101418      Db *pDb;
101419      for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
101420        if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
101421        /* "main" is always an acceptable alias for the primary database
101422        ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
101423        if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
101424      }
101425    }
101426    return i;
101427  }
101428  
101429  /*
101430  ** The token *pName contains the name of a database (either "main" or
101431  ** "temp" or the name of an attached db). This routine returns the
101432  ** index of the named database in db->aDb[], or -1 if the named db 
101433  ** does not exist.
101434  */
101435  SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
101436    int i;                               /* Database number */
101437    char *zName;                         /* Name we are searching for */
101438    zName = sqlite3NameFromToken(db, pName);
101439    i = sqlite3FindDbName(db, zName);
101440    sqlite3DbFree(db, zName);
101441    return i;
101442  }
101443  
101444  /* The table or view or trigger name is passed to this routine via tokens
101445  ** pName1 and pName2. If the table name was fully qualified, for example:
101446  **
101447  ** CREATE TABLE xxx.yyy (...);
101448  ** 
101449  ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
101450  ** the table name is not fully qualified, i.e.:
101451  **
101452  ** CREATE TABLE yyy(...);
101453  **
101454  ** Then pName1 is set to "yyy" and pName2 is "".
101455  **
101456  ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
101457  ** pName2) that stores the unqualified table name.  The index of the
101458  ** database "xxx" is returned.
101459  */
101460  SQLITE_PRIVATE int sqlite3TwoPartName(
101461    Parse *pParse,      /* Parsing and code generating context */
101462    Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
101463    Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
101464    Token **pUnqual     /* Write the unqualified object name here */
101465  ){
101466    int iDb;                    /* Database holding the object */
101467    sqlite3 *db = pParse->db;
101468  
101469    assert( pName2!=0 );
101470    if( pName2->n>0 ){
101471      if( db->init.busy ) {
101472        sqlite3ErrorMsg(pParse, "corrupt database");
101473        return -1;
101474      }
101475      *pUnqual = pName2;
101476      iDb = sqlite3FindDb(db, pName1);
101477      if( iDb<0 ){
101478        sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
101479        return -1;
101480      }
101481    }else{
101482      assert( db->init.iDb==0 || db->init.busy
101483               || (db->mDbFlags & DBFLAG_Vacuum)!=0);
101484      iDb = db->init.iDb;
101485      *pUnqual = pName1;
101486    }
101487    return iDb;
101488  }
101489  
101490  /*
101491  ** This routine is used to check if the UTF-8 string zName is a legal
101492  ** unqualified name for a new schema object (table, index, view or
101493  ** trigger). All names are legal except those that begin with the string
101494  ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
101495  ** is reserved for internal use.
101496  */
101497  SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
101498    if( !pParse->db->init.busy && pParse->nested==0 
101499            && (pParse->db->flags & SQLITE_WriteSchema)==0
101500            && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
101501      sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
101502      return SQLITE_ERROR;
101503    }
101504    return SQLITE_OK;
101505  }
101506  
101507  /*
101508  ** Return the PRIMARY KEY index of a table
101509  */
101510  SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
101511    Index *p;
101512    for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
101513    return p;
101514  }
101515  
101516  /*
101517  ** Return the column of index pIdx that corresponds to table
101518  ** column iCol.  Return -1 if not found.
101519  */
101520  SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
101521    int i;
101522    for(i=0; i<pIdx->nColumn; i++){
101523      if( iCol==pIdx->aiColumn[i] ) return i;
101524    }
101525    return -1;
101526  }
101527  
101528  /*
101529  ** Begin constructing a new table representation in memory.  This is
101530  ** the first of several action routines that get called in response
101531  ** to a CREATE TABLE statement.  In particular, this routine is called
101532  ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
101533  ** flag is true if the table should be stored in the auxiliary database
101534  ** file instead of in the main database file.  This is normally the case
101535  ** when the "TEMP" or "TEMPORARY" keyword occurs in between
101536  ** CREATE and TABLE.
101537  **
101538  ** The new table record is initialized and put in pParse->pNewTable.
101539  ** As more of the CREATE TABLE statement is parsed, additional action
101540  ** routines will be called to add more information to this record.
101541  ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
101542  ** is called to complete the construction of the new table record.
101543  */
101544  SQLITE_PRIVATE void sqlite3StartTable(
101545    Parse *pParse,   /* Parser context */
101546    Token *pName1,   /* First part of the name of the table or view */
101547    Token *pName2,   /* Second part of the name of the table or view */
101548    int isTemp,      /* True if this is a TEMP table */
101549    int isView,      /* True if this is a VIEW */
101550    int isVirtual,   /* True if this is a VIRTUAL table */
101551    int noErr        /* Do nothing if table already exists */
101552  ){
101553    Table *pTable;
101554    char *zName = 0; /* The name of the new table */
101555    sqlite3 *db = pParse->db;
101556    Vdbe *v;
101557    int iDb;         /* Database number to create the table in */
101558    Token *pName;    /* Unqualified name of the table to create */
101559  
101560    if( db->init.busy && db->init.newTnum==1 ){
101561      /* Special case:  Parsing the sqlite_master or sqlite_temp_master schema */
101562      iDb = db->init.iDb;
101563      zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
101564      pName = pName1;
101565    }else{
101566      /* The common case */
101567      iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
101568      if( iDb<0 ) return;
101569      if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
101570        /* If creating a temp table, the name may not be qualified. Unless 
101571        ** the database name is "temp" anyway.  */
101572        sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
101573        return;
101574      }
101575      if( !OMIT_TEMPDB && isTemp ) iDb = 1;
101576      zName = sqlite3NameFromToken(db, pName);
101577    }
101578    pParse->sNameToken = *pName;
101579    if( zName==0 ) return;
101580    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
101581      goto begin_table_error;
101582    }
101583    if( db->init.iDb==1 ) isTemp = 1;
101584  #ifndef SQLITE_OMIT_AUTHORIZATION
101585    assert( isTemp==0 || isTemp==1 );
101586    assert( isView==0 || isView==1 );
101587    {
101588      static const u8 aCode[] = {
101589         SQLITE_CREATE_TABLE,
101590         SQLITE_CREATE_TEMP_TABLE,
101591         SQLITE_CREATE_VIEW,
101592         SQLITE_CREATE_TEMP_VIEW
101593      };
101594      char *zDb = db->aDb[iDb].zDbSName;
101595      if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
101596        goto begin_table_error;
101597      }
101598      if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
101599                                         zName, 0, zDb) ){
101600        goto begin_table_error;
101601      }
101602    }
101603  #endif
101604  
101605    /* Make sure the new table name does not collide with an existing
101606    ** index or table name in the same database.  Issue an error message if
101607    ** it does. The exception is if the statement being parsed was passed
101608    ** to an sqlite3_declare_vtab() call. In that case only the column names
101609    ** and types will be used, so there is no need to test for namespace
101610    ** collisions.
101611    */
101612    if( !IN_DECLARE_VTAB ){
101613      char *zDb = db->aDb[iDb].zDbSName;
101614      if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
101615        goto begin_table_error;
101616      }
101617      pTable = sqlite3FindTable(db, zName, zDb);
101618      if( pTable ){
101619        if( !noErr ){
101620          sqlite3ErrorMsg(pParse, "table %T already exists", pName);
101621        }else{
101622          assert( !db->init.busy || CORRUPT_DB );
101623          sqlite3CodeVerifySchema(pParse, iDb);
101624        }
101625        goto begin_table_error;
101626      }
101627      if( sqlite3FindIndex(db, zName, zDb)!=0 ){
101628        sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
101629        goto begin_table_error;
101630      }
101631    }
101632  
101633    pTable = sqlite3DbMallocZero(db, sizeof(Table));
101634    if( pTable==0 ){
101635      assert( db->mallocFailed );
101636      pParse->rc = SQLITE_NOMEM_BKPT;
101637      pParse->nErr++;
101638      goto begin_table_error;
101639    }
101640    pTable->zName = zName;
101641    pTable->iPKey = -1;
101642    pTable->pSchema = db->aDb[iDb].pSchema;
101643    pTable->nTabRef = 1;
101644  #ifdef SQLITE_DEFAULT_ROWEST
101645    pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
101646  #else
101647    pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
101648  #endif
101649    assert( pParse->pNewTable==0 );
101650    pParse->pNewTable = pTable;
101651  
101652    /* If this is the magic sqlite_sequence table used by autoincrement,
101653    ** then record a pointer to this table in the main database structure
101654    ** so that INSERT can find the table easily.
101655    */
101656  #ifndef SQLITE_OMIT_AUTOINCREMENT
101657    if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
101658      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101659      pTable->pSchema->pSeqTab = pTable;
101660    }
101661  #endif
101662  
101663    /* Begin generating the code that will insert the table record into
101664    ** the SQLITE_MASTER table.  Note in particular that we must go ahead
101665    ** and allocate the record number for the table entry now.  Before any
101666    ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
101667    ** indices to be created and the table record must come before the 
101668    ** indices.  Hence, the record number for the table must be allocated
101669    ** now.
101670    */
101671    if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
101672      int addr1;
101673      int fileFormat;
101674      int reg1, reg2, reg3;
101675      /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
101676      static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
101677      sqlite3BeginWriteOperation(pParse, 1, iDb);
101678  
101679  #ifndef SQLITE_OMIT_VIRTUALTABLE
101680      if( isVirtual ){
101681        sqlite3VdbeAddOp0(v, OP_VBegin);
101682      }
101683  #endif
101684  
101685      /* If the file format and encoding in the database have not been set, 
101686      ** set them now.
101687      */
101688      reg1 = pParse->regRowid = ++pParse->nMem;
101689      reg2 = pParse->regRoot = ++pParse->nMem;
101690      reg3 = ++pParse->nMem;
101691      sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
101692      sqlite3VdbeUsesBtree(v, iDb);
101693      addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
101694      fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
101695                    1 : SQLITE_MAX_FILE_FORMAT;
101696      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
101697      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
101698      sqlite3VdbeJumpHere(v, addr1);
101699  
101700      /* This just creates a place-holder record in the sqlite_master table.
101701      ** The record created does not contain anything yet.  It will be replaced
101702      ** by the real entry in code generated at sqlite3EndTable().
101703      **
101704      ** The rowid for the new entry is left in register pParse->regRowid.
101705      ** The root page number of the new table is left in reg pParse->regRoot.
101706      ** The rowid and root page number values are needed by the code that
101707      ** sqlite3EndTable will generate.
101708      */
101709  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
101710      if( isView || isVirtual ){
101711        sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
101712      }else
101713  #endif
101714      {
101715        pParse->addrCrTab =
101716           sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
101717      }
101718      sqlite3OpenMasterTable(pParse, iDb);
101719      sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
101720      sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
101721      sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
101722      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
101723      sqlite3VdbeAddOp0(v, OP_Close);
101724    }
101725  
101726    /* Normal (non-error) return. */
101727    return;
101728  
101729    /* If an error occurs, we jump here */
101730  begin_table_error:
101731    sqlite3DbFree(db, zName);
101732    return;
101733  }
101734  
101735  /* Set properties of a table column based on the (magical)
101736  ** name of the column.
101737  */
101738  #if SQLITE_ENABLE_HIDDEN_COLUMNS
101739  SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
101740    if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
101741      pCol->colFlags |= COLFLAG_HIDDEN;
101742    }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
101743      pTab->tabFlags |= TF_OOOHidden;
101744    }
101745  }
101746  #endif
101747  
101748  
101749  /*
101750  ** Add a new column to the table currently being constructed.
101751  **
101752  ** The parser calls this routine once for each column declaration
101753  ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
101754  ** first to get things going.  Then this routine is called for each
101755  ** column.
101756  */
101757  SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
101758    Table *p;
101759    int i;
101760    char *z;
101761    char *zType;
101762    Column *pCol;
101763    sqlite3 *db = pParse->db;
101764    if( (p = pParse->pNewTable)==0 ) return;
101765    if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
101766      sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
101767      return;
101768    }
101769    z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
101770    if( z==0 ) return;
101771    memcpy(z, pName->z, pName->n);
101772    z[pName->n] = 0;
101773    sqlite3Dequote(z);
101774    for(i=0; i<p->nCol; i++){
101775      if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
101776        sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
101777        sqlite3DbFree(db, z);
101778        return;
101779      }
101780    }
101781    if( (p->nCol & 0x7)==0 ){
101782      Column *aNew;
101783      aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
101784      if( aNew==0 ){
101785        sqlite3DbFree(db, z);
101786        return;
101787      }
101788      p->aCol = aNew;
101789    }
101790    pCol = &p->aCol[p->nCol];
101791    memset(pCol, 0, sizeof(p->aCol[0]));
101792    pCol->zName = z;
101793    sqlite3ColumnPropertiesFromName(p, pCol);
101794   
101795    if( pType->n==0 ){
101796      /* If there is no type specified, columns have the default affinity
101797      ** 'BLOB'. */
101798      pCol->affinity = SQLITE_AFF_BLOB;
101799      pCol->szEst = 1;
101800    }else{
101801      zType = z + sqlite3Strlen30(z) + 1;
101802      memcpy(zType, pType->z, pType->n);
101803      zType[pType->n] = 0;
101804      sqlite3Dequote(zType);
101805      pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst);
101806      pCol->colFlags |= COLFLAG_HASTYPE;
101807    }
101808    p->nCol++;
101809    pParse->constraintName.n = 0;
101810  }
101811  
101812  /*
101813  ** This routine is called by the parser while in the middle of
101814  ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
101815  ** been seen on a column.  This routine sets the notNull flag on
101816  ** the column currently under construction.
101817  */
101818  SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
101819    Table *p;
101820    p = pParse->pNewTable;
101821    if( p==0 || NEVER(p->nCol<1) ) return;
101822    p->aCol[p->nCol-1].notNull = (u8)onError;
101823    p->tabFlags |= TF_HasNotNull;
101824  }
101825  
101826  /*
101827  ** Scan the column type name zType (length nType) and return the
101828  ** associated affinity type.
101829  **
101830  ** This routine does a case-independent search of zType for the 
101831  ** substrings in the following table. If one of the substrings is
101832  ** found, the corresponding affinity is returned. If zType contains
101833  ** more than one of the substrings, entries toward the top of 
101834  ** the table take priority. For example, if zType is 'BLOBINT', 
101835  ** SQLITE_AFF_INTEGER is returned.
101836  **
101837  ** Substring     | Affinity
101838  ** --------------------------------
101839  ** 'INT'         | SQLITE_AFF_INTEGER
101840  ** 'CHAR'        | SQLITE_AFF_TEXT
101841  ** 'CLOB'        | SQLITE_AFF_TEXT
101842  ** 'TEXT'        | SQLITE_AFF_TEXT
101843  ** 'BLOB'        | SQLITE_AFF_BLOB
101844  ** 'REAL'        | SQLITE_AFF_REAL
101845  ** 'FLOA'        | SQLITE_AFF_REAL
101846  ** 'DOUB'        | SQLITE_AFF_REAL
101847  **
101848  ** If none of the substrings in the above table are found,
101849  ** SQLITE_AFF_NUMERIC is returned.
101850  */
101851  SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
101852    u32 h = 0;
101853    char aff = SQLITE_AFF_NUMERIC;
101854    const char *zChar = 0;
101855  
101856    assert( zIn!=0 );
101857    while( zIn[0] ){
101858      h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
101859      zIn++;
101860      if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
101861        aff = SQLITE_AFF_TEXT;
101862        zChar = zIn;
101863      }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
101864        aff = SQLITE_AFF_TEXT;
101865      }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
101866        aff = SQLITE_AFF_TEXT;
101867      }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
101868          && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
101869        aff = SQLITE_AFF_BLOB;
101870        if( zIn[0]=='(' ) zChar = zIn;
101871  #ifndef SQLITE_OMIT_FLOATING_POINT
101872      }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
101873          && aff==SQLITE_AFF_NUMERIC ){
101874        aff = SQLITE_AFF_REAL;
101875      }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
101876          && aff==SQLITE_AFF_NUMERIC ){
101877        aff = SQLITE_AFF_REAL;
101878      }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
101879          && aff==SQLITE_AFF_NUMERIC ){
101880        aff = SQLITE_AFF_REAL;
101881  #endif
101882      }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
101883        aff = SQLITE_AFF_INTEGER;
101884        break;
101885      }
101886    }
101887  
101888    /* If pszEst is not NULL, store an estimate of the field size.  The
101889    ** estimate is scaled so that the size of an integer is 1.  */
101890    if( pszEst ){
101891      *pszEst = 1;   /* default size is approx 4 bytes */
101892      if( aff<SQLITE_AFF_NUMERIC ){
101893        if( zChar ){
101894          while( zChar[0] ){
101895            if( sqlite3Isdigit(zChar[0]) ){
101896              int v = 0;
101897              sqlite3GetInt32(zChar, &v);
101898              v = v/4 + 1;
101899              if( v>255 ) v = 255;
101900              *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
101901              break;
101902            }
101903            zChar++;
101904          }
101905        }else{
101906          *pszEst = 5;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
101907        }
101908      }
101909    }
101910    return aff;
101911  }
101912  
101913  /*
101914  ** The expression is the default value for the most recently added column
101915  ** of the table currently under construction.
101916  **
101917  ** Default value expressions must be constant.  Raise an exception if this
101918  ** is not the case.
101919  **
101920  ** This routine is called by the parser while in the middle of
101921  ** parsing a CREATE TABLE statement.
101922  */
101923  SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
101924    Table *p;
101925    Column *pCol;
101926    sqlite3 *db = pParse->db;
101927    p = pParse->pNewTable;
101928    if( p!=0 ){
101929      pCol = &(p->aCol[p->nCol-1]);
101930      if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
101931        sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
101932            pCol->zName);
101933      }else{
101934        /* A copy of pExpr is used instead of the original, as pExpr contains
101935        ** tokens that point to volatile memory. The 'span' of the expression
101936        ** is required by pragma table_info.
101937        */
101938        Expr x;
101939        sqlite3ExprDelete(db, pCol->pDflt);
101940        memset(&x, 0, sizeof(x));
101941        x.op = TK_SPAN;
101942        x.u.zToken = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
101943                                      (int)(pSpan->zEnd - pSpan->zStart));
101944        x.pLeft = pSpan->pExpr;
101945        x.flags = EP_Skip;
101946        pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
101947        sqlite3DbFree(db, x.u.zToken);
101948      }
101949    }
101950    sqlite3ExprDelete(db, pSpan->pExpr);
101951  }
101952  
101953  /*
101954  ** Backwards Compatibility Hack:
101955  ** 
101956  ** Historical versions of SQLite accepted strings as column names in
101957  ** indexes and PRIMARY KEY constraints and in UNIQUE constraints.  Example:
101958  **
101959  **     CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
101960  **     CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
101961  **
101962  ** This is goofy.  But to preserve backwards compatibility we continue to
101963  ** accept it.  This routine does the necessary conversion.  It converts
101964  ** the expression given in its argument from a TK_STRING into a TK_ID
101965  ** if the expression is just a TK_STRING with an optional COLLATE clause.
101966  ** If the epxression is anything other than TK_STRING, the expression is
101967  ** unchanged.
101968  */
101969  static void sqlite3StringToId(Expr *p){
101970    if( p->op==TK_STRING ){
101971      p->op = TK_ID;
101972    }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
101973      p->pLeft->op = TK_ID;
101974    }
101975  }
101976  
101977  /*
101978  ** Designate the PRIMARY KEY for the table.  pList is a list of names 
101979  ** of columns that form the primary key.  If pList is NULL, then the
101980  ** most recently added column of the table is the primary key.
101981  **
101982  ** A table can have at most one primary key.  If the table already has
101983  ** a primary key (and this is the second primary key) then create an
101984  ** error.
101985  **
101986  ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
101987  ** then we will try to use that column as the rowid.  Set the Table.iPKey
101988  ** field of the table under construction to be the index of the
101989  ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
101990  ** no INTEGER PRIMARY KEY.
101991  **
101992  ** If the key is not an INTEGER PRIMARY KEY, then create a unique
101993  ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
101994  */
101995  SQLITE_PRIVATE void sqlite3AddPrimaryKey(
101996    Parse *pParse,    /* Parsing context */
101997    ExprList *pList,  /* List of field names to be indexed */
101998    int onError,      /* What to do with a uniqueness conflict */
101999    int autoInc,      /* True if the AUTOINCREMENT keyword is present */
102000    int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
102001  ){
102002    Table *pTab = pParse->pNewTable;
102003    Column *pCol = 0;
102004    int iCol = -1, i;
102005    int nTerm;
102006    if( pTab==0 ) goto primary_key_exit;
102007    if( pTab->tabFlags & TF_HasPrimaryKey ){
102008      sqlite3ErrorMsg(pParse, 
102009        "table \"%s\" has more than one primary key", pTab->zName);
102010      goto primary_key_exit;
102011    }
102012    pTab->tabFlags |= TF_HasPrimaryKey;
102013    if( pList==0 ){
102014      iCol = pTab->nCol - 1;
102015      pCol = &pTab->aCol[iCol];
102016      pCol->colFlags |= COLFLAG_PRIMKEY;
102017      nTerm = 1;
102018    }else{
102019      nTerm = pList->nExpr;
102020      for(i=0; i<nTerm; i++){
102021        Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
102022        assert( pCExpr!=0 );
102023        sqlite3StringToId(pCExpr);
102024        if( pCExpr->op==TK_ID ){
102025          const char *zCName = pCExpr->u.zToken;
102026          for(iCol=0; iCol<pTab->nCol; iCol++){
102027            if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
102028              pCol = &pTab->aCol[iCol];
102029              pCol->colFlags |= COLFLAG_PRIMKEY;
102030              break;
102031            }
102032          }
102033        }
102034      }
102035    }
102036    if( nTerm==1
102037     && pCol
102038     && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
102039     && sortOrder!=SQLITE_SO_DESC
102040    ){
102041      pTab->iPKey = iCol;
102042      pTab->keyConf = (u8)onError;
102043      assert( autoInc==0 || autoInc==1 );
102044      pTab->tabFlags |= autoInc*TF_Autoincrement;
102045      if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
102046    }else if( autoInc ){
102047  #ifndef SQLITE_OMIT_AUTOINCREMENT
102048      sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
102049         "INTEGER PRIMARY KEY");
102050  #endif
102051    }else{
102052      sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
102053                             0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
102054      pList = 0;
102055    }
102056  
102057  primary_key_exit:
102058    sqlite3ExprListDelete(pParse->db, pList);
102059    return;
102060  }
102061  
102062  /*
102063  ** Add a new CHECK constraint to the table currently under construction.
102064  */
102065  SQLITE_PRIVATE void sqlite3AddCheckConstraint(
102066    Parse *pParse,    /* Parsing context */
102067    Expr *pCheckExpr  /* The check expression */
102068  ){
102069  #ifndef SQLITE_OMIT_CHECK
102070    Table *pTab = pParse->pNewTable;
102071    sqlite3 *db = pParse->db;
102072    if( pTab && !IN_DECLARE_VTAB
102073     && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
102074    ){
102075      pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
102076      if( pParse->constraintName.n ){
102077        sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
102078      }
102079    }else
102080  #endif
102081    {
102082      sqlite3ExprDelete(pParse->db, pCheckExpr);
102083    }
102084  }
102085  
102086  /*
102087  ** Set the collation function of the most recently parsed table column
102088  ** to the CollSeq given.
102089  */
102090  SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
102091    Table *p;
102092    int i;
102093    char *zColl;              /* Dequoted name of collation sequence */
102094    sqlite3 *db;
102095  
102096    if( (p = pParse->pNewTable)==0 ) return;
102097    i = p->nCol-1;
102098    db = pParse->db;
102099    zColl = sqlite3NameFromToken(db, pToken);
102100    if( !zColl ) return;
102101  
102102    if( sqlite3LocateCollSeq(pParse, zColl) ){
102103      Index *pIdx;
102104      sqlite3DbFree(db, p->aCol[i].zColl);
102105      p->aCol[i].zColl = zColl;
102106    
102107      /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
102108      ** then an index may have been created on this column before the
102109      ** collation type was added. Correct this if it is the case.
102110      */
102111      for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
102112        assert( pIdx->nKeyCol==1 );
102113        if( pIdx->aiColumn[0]==i ){
102114          pIdx->azColl[0] = p->aCol[i].zColl;
102115        }
102116      }
102117    }else{
102118      sqlite3DbFree(db, zColl);
102119    }
102120  }
102121  
102122  /*
102123  ** This function returns the collation sequence for database native text
102124  ** encoding identified by the string zName, length nName.
102125  **
102126  ** If the requested collation sequence is not available, or not available
102127  ** in the database native encoding, the collation factory is invoked to
102128  ** request it. If the collation factory does not supply such a sequence,
102129  ** and the sequence is available in another text encoding, then that is
102130  ** returned instead.
102131  **
102132  ** If no versions of the requested collations sequence are available, or
102133  ** another error occurs, NULL is returned and an error message written into
102134  ** pParse.
102135  **
102136  ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
102137  ** invokes the collation factory if the named collation cannot be found
102138  ** and generates an error message.
102139  **
102140  ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
102141  */
102142  SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
102143    sqlite3 *db = pParse->db;
102144    u8 enc = ENC(db);
102145    u8 initbusy = db->init.busy;
102146    CollSeq *pColl;
102147  
102148    pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
102149    if( !initbusy && (!pColl || !pColl->xCmp) ){
102150      pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
102151    }
102152  
102153    return pColl;
102154  }
102155  
102156  
102157  /*
102158  ** Generate code that will increment the schema cookie.
102159  **
102160  ** The schema cookie is used to determine when the schema for the
102161  ** database changes.  After each schema change, the cookie value
102162  ** changes.  When a process first reads the schema it records the
102163  ** cookie.  Thereafter, whenever it goes to access the database,
102164  ** it checks the cookie to make sure the schema has not changed
102165  ** since it was last read.
102166  **
102167  ** This plan is not completely bullet-proof.  It is possible for
102168  ** the schema to change multiple times and for the cookie to be
102169  ** set back to prior value.  But schema changes are infrequent
102170  ** and the probability of hitting the same cookie value is only
102171  ** 1 chance in 2^32.  So we're safe enough.
102172  **
102173  ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
102174  ** the schema-version whenever the schema changes.
102175  */
102176  SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
102177    sqlite3 *db = pParse->db;
102178    Vdbe *v = pParse->pVdbe;
102179    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
102180    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, 
102181                      db->aDb[iDb].pSchema->schema_cookie+1);
102182  }
102183  
102184  /*
102185  ** Measure the number of characters needed to output the given
102186  ** identifier.  The number returned includes any quotes used
102187  ** but does not include the null terminator.
102188  **
102189  ** The estimate is conservative.  It might be larger that what is
102190  ** really needed.
102191  */
102192  static int identLength(const char *z){
102193    int n;
102194    for(n=0; *z; n++, z++){
102195      if( *z=='"' ){ n++; }
102196    }
102197    return n + 2;
102198  }
102199  
102200  /*
102201  ** The first parameter is a pointer to an output buffer. The second 
102202  ** parameter is a pointer to an integer that contains the offset at
102203  ** which to write into the output buffer. This function copies the
102204  ** nul-terminated string pointed to by the third parameter, zSignedIdent,
102205  ** to the specified offset in the buffer and updates *pIdx to refer
102206  ** to the first byte after the last byte written before returning.
102207  ** 
102208  ** If the string zSignedIdent consists entirely of alpha-numeric
102209  ** characters, does not begin with a digit and is not an SQL keyword,
102210  ** then it is copied to the output buffer exactly as it is. Otherwise,
102211  ** it is quoted using double-quotes.
102212  */
102213  static void identPut(char *z, int *pIdx, char *zSignedIdent){
102214    unsigned char *zIdent = (unsigned char*)zSignedIdent;
102215    int i, j, needQuote;
102216    i = *pIdx;
102217  
102218    for(j=0; zIdent[j]; j++){
102219      if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
102220    }
102221    needQuote = sqlite3Isdigit(zIdent[0])
102222              || sqlite3KeywordCode(zIdent, j)!=TK_ID
102223              || zIdent[j]!=0
102224              || j==0;
102225  
102226    if( needQuote ) z[i++] = '"';
102227    for(j=0; zIdent[j]; j++){
102228      z[i++] = zIdent[j];
102229      if( zIdent[j]=='"' ) z[i++] = '"';
102230    }
102231    if( needQuote ) z[i++] = '"';
102232    z[i] = 0;
102233    *pIdx = i;
102234  }
102235  
102236  /*
102237  ** Generate a CREATE TABLE statement appropriate for the given
102238  ** table.  Memory to hold the text of the statement is obtained
102239  ** from sqliteMalloc() and must be freed by the calling function.
102240  */
102241  static char *createTableStmt(sqlite3 *db, Table *p){
102242    int i, k, n;
102243    char *zStmt;
102244    char *zSep, *zSep2, *zEnd;
102245    Column *pCol;
102246    n = 0;
102247    for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
102248      n += identLength(pCol->zName) + 5;
102249    }
102250    n += identLength(p->zName);
102251    if( n<50 ){ 
102252      zSep = "";
102253      zSep2 = ",";
102254      zEnd = ")";
102255    }else{
102256      zSep = "\n  ";
102257      zSep2 = ",\n  ";
102258      zEnd = "\n)";
102259    }
102260    n += 35 + 6*p->nCol;
102261    zStmt = sqlite3DbMallocRaw(0, n);
102262    if( zStmt==0 ){
102263      sqlite3OomFault(db);
102264      return 0;
102265    }
102266    sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
102267    k = sqlite3Strlen30(zStmt);
102268    identPut(zStmt, &k, p->zName);
102269    zStmt[k++] = '(';
102270    for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
102271      static const char * const azType[] = {
102272          /* SQLITE_AFF_BLOB    */ "",
102273          /* SQLITE_AFF_TEXT    */ " TEXT",
102274          /* SQLITE_AFF_NUMERIC */ " NUM",
102275          /* SQLITE_AFF_INTEGER */ " INT",
102276          /* SQLITE_AFF_REAL    */ " REAL"
102277      };
102278      int len;
102279      const char *zType;
102280  
102281      sqlite3_snprintf(n-k, &zStmt[k], zSep);
102282      k += sqlite3Strlen30(&zStmt[k]);
102283      zSep = zSep2;
102284      identPut(zStmt, &k, pCol->zName);
102285      assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
102286      assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
102287      testcase( pCol->affinity==SQLITE_AFF_BLOB );
102288      testcase( pCol->affinity==SQLITE_AFF_TEXT );
102289      testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
102290      testcase( pCol->affinity==SQLITE_AFF_INTEGER );
102291      testcase( pCol->affinity==SQLITE_AFF_REAL );
102292      
102293      zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
102294      len = sqlite3Strlen30(zType);
102295      assert( pCol->affinity==SQLITE_AFF_BLOB 
102296              || pCol->affinity==sqlite3AffinityType(zType, 0) );
102297      memcpy(&zStmt[k], zType, len);
102298      k += len;
102299      assert( k<=n );
102300    }
102301    sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
102302    return zStmt;
102303  }
102304  
102305  /*
102306  ** Resize an Index object to hold N columns total.  Return SQLITE_OK
102307  ** on success and SQLITE_NOMEM on an OOM error.
102308  */
102309  static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
102310    char *zExtra;
102311    int nByte;
102312    if( pIdx->nColumn>=N ) return SQLITE_OK;
102313    assert( pIdx->isResized==0 );
102314    nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
102315    zExtra = sqlite3DbMallocZero(db, nByte);
102316    if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
102317    memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
102318    pIdx->azColl = (const char**)zExtra;
102319    zExtra += sizeof(char*)*N;
102320    memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
102321    pIdx->aiColumn = (i16*)zExtra;
102322    zExtra += sizeof(i16)*N;
102323    memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
102324    pIdx->aSortOrder = (u8*)zExtra;
102325    pIdx->nColumn = N;
102326    pIdx->isResized = 1;
102327    return SQLITE_OK;
102328  }
102329  
102330  /*
102331  ** Estimate the total row width for a table.
102332  */
102333  static void estimateTableWidth(Table *pTab){
102334    unsigned wTable = 0;
102335    const Column *pTabCol;
102336    int i;
102337    for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
102338      wTable += pTabCol->szEst;
102339    }
102340    if( pTab->iPKey<0 ) wTable++;
102341    pTab->szTabRow = sqlite3LogEst(wTable*4);
102342  }
102343  
102344  /*
102345  ** Estimate the average size of a row for an index.
102346  */
102347  static void estimateIndexWidth(Index *pIdx){
102348    unsigned wIndex = 0;
102349    int i;
102350    const Column *aCol = pIdx->pTable->aCol;
102351    for(i=0; i<pIdx->nColumn; i++){
102352      i16 x = pIdx->aiColumn[i];
102353      assert( x<pIdx->pTable->nCol );
102354      wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
102355    }
102356    pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
102357  }
102358  
102359  /* Return true if value x is found any of the first nCol entries of aiCol[]
102360  */
102361  static int hasColumn(const i16 *aiCol, int nCol, int x){
102362    while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
102363    return 0;
102364  }
102365  
102366  /*
102367  ** This routine runs at the end of parsing a CREATE TABLE statement that
102368  ** has a WITHOUT ROWID clause.  The job of this routine is to convert both
102369  ** internal schema data structures and the generated VDBE code so that they
102370  ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
102371  ** Changes include:
102372  **
102373  **     (1)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
102374  **     (2)  Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY 
102375  **          into BTREE_BLOBKEY.
102376  **     (3)  Bypass the creation of the sqlite_master table entry
102377  **          for the PRIMARY KEY as the primary key index is now
102378  **          identified by the sqlite_master table entry of the table itself.
102379  **     (4)  Set the Index.tnum of the PRIMARY KEY Index object in the
102380  **          schema to the rootpage from the main table.
102381  **     (5)  Add all table columns to the PRIMARY KEY Index object
102382  **          so that the PRIMARY KEY is a covering index.  The surplus
102383  **          columns are part of KeyInfo.nAllField and are not used for
102384  **          sorting or lookup or uniqueness checks.
102385  **     (6)  Replace the rowid tail on all automatically generated UNIQUE
102386  **          indices with the PRIMARY KEY columns.
102387  **
102388  ** For virtual tables, only (1) is performed.
102389  */
102390  static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
102391    Index *pIdx;
102392    Index *pPk;
102393    int nPk;
102394    int i, j;
102395    sqlite3 *db = pParse->db;
102396    Vdbe *v = pParse->pVdbe;
102397  
102398    /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
102399    */
102400    if( !db->init.imposterTable ){
102401      for(i=0; i<pTab->nCol; i++){
102402        if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
102403          pTab->aCol[i].notNull = OE_Abort;
102404        }
102405      }
102406    }
102407  
102408    /* The remaining transformations only apply to b-tree tables, not to
102409    ** virtual tables */
102410    if( IN_DECLARE_VTAB ) return;
102411  
102412    /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
102413    ** into BTREE_BLOBKEY.
102414    */
102415    if( pParse->addrCrTab ){
102416      assert( v );
102417      sqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY);
102418    }
102419  
102420    /* Locate the PRIMARY KEY index.  Or, if this table was originally
102421    ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index. 
102422    */
102423    if( pTab->iPKey>=0 ){
102424      ExprList *pList;
102425      Token ipkToken;
102426      sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
102427      pList = sqlite3ExprListAppend(pParse, 0, 
102428                    sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
102429      if( pList==0 ) return;
102430      pList->a[0].sortOrder = pParse->iPkSortOrder;
102431      assert( pParse->pNewTable==pTab );
102432      sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
102433                         SQLITE_IDXTYPE_PRIMARYKEY);
102434      if( db->mallocFailed ) return;
102435      pPk = sqlite3PrimaryKeyIndex(pTab);
102436      pTab->iPKey = -1;
102437    }else{
102438      pPk = sqlite3PrimaryKeyIndex(pTab);
102439  
102440      /*
102441      ** Remove all redundant columns from the PRIMARY KEY.  For example, change
102442      ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)".  Later
102443      ** code assumes the PRIMARY KEY contains no repeated columns.
102444      */
102445      for(i=j=1; i<pPk->nKeyCol; i++){
102446        if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
102447          pPk->nColumn--;
102448        }else{
102449          pPk->aiColumn[j++] = pPk->aiColumn[i];
102450        }
102451      }
102452      pPk->nKeyCol = j;
102453    }
102454    assert( pPk!=0 );
102455    pPk->isCovering = 1;
102456    if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
102457    nPk = pPk->nKeyCol;
102458  
102459    /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
102460    ** table entry. This is only required if currently generating VDBE
102461    ** code for a CREATE TABLE (not when parsing one as part of reading
102462    ** a database schema).  */
102463    if( v && pPk->tnum>0 ){
102464      assert( db->init.busy==0 );
102465      sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
102466    }
102467  
102468    /* The root page of the PRIMARY KEY is the table root page */
102469    pPk->tnum = pTab->tnum;
102470  
102471    /* Update the in-memory representation of all UNIQUE indices by converting
102472    ** the final rowid column into one or more columns of the PRIMARY KEY.
102473    */
102474    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102475      int n;
102476      if( IsPrimaryKeyIndex(pIdx) ) continue;
102477      for(i=n=0; i<nPk; i++){
102478        if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
102479      }
102480      if( n==0 ){
102481        /* This index is a superset of the primary key */
102482        pIdx->nColumn = pIdx->nKeyCol;
102483        continue;
102484      }
102485      if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
102486      for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
102487        if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
102488          pIdx->aiColumn[j] = pPk->aiColumn[i];
102489          pIdx->azColl[j] = pPk->azColl[i];
102490          j++;
102491        }
102492      }
102493      assert( pIdx->nColumn>=pIdx->nKeyCol+n );
102494      assert( pIdx->nColumn>=j );
102495    }
102496  
102497    /* Add all table columns to the PRIMARY KEY index
102498    */
102499    if( nPk<pTab->nCol ){
102500      if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
102501      for(i=0, j=nPk; i<pTab->nCol; i++){
102502        if( !hasColumn(pPk->aiColumn, j, i) ){
102503          assert( j<pPk->nColumn );
102504          pPk->aiColumn[j] = i;
102505          pPk->azColl[j] = sqlite3StrBINARY;
102506          j++;
102507        }
102508      }
102509      assert( pPk->nColumn==j );
102510      assert( pTab->nCol==j );
102511    }else{
102512      pPk->nColumn = pTab->nCol;
102513    }
102514  }
102515  
102516  /*
102517  ** This routine is called to report the final ")" that terminates
102518  ** a CREATE TABLE statement.
102519  **
102520  ** The table structure that other action routines have been building
102521  ** is added to the internal hash tables, assuming no errors have
102522  ** occurred.
102523  **
102524  ** An entry for the table is made in the master table on disk, unless
102525  ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
102526  ** it means we are reading the sqlite_master table because we just
102527  ** connected to the database or because the sqlite_master table has
102528  ** recently changed, so the entry for this table already exists in
102529  ** the sqlite_master table.  We do not want to create it again.
102530  **
102531  ** If the pSelect argument is not NULL, it means that this routine
102532  ** was called to create a table generated from a 
102533  ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
102534  ** the new table will match the result set of the SELECT.
102535  */
102536  SQLITE_PRIVATE void sqlite3EndTable(
102537    Parse *pParse,          /* Parse context */
102538    Token *pCons,           /* The ',' token after the last column defn. */
102539    Token *pEnd,            /* The ')' before options in the CREATE TABLE */
102540    u8 tabOpts,             /* Extra table options. Usually 0. */
102541    Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
102542  ){
102543    Table *p;                 /* The new table */
102544    sqlite3 *db = pParse->db; /* The database connection */
102545    int iDb;                  /* Database in which the table lives */
102546    Index *pIdx;              /* An implied index of the table */
102547  
102548    if( pEnd==0 && pSelect==0 ){
102549      return;
102550    }
102551    assert( !db->mallocFailed );
102552    p = pParse->pNewTable;
102553    if( p==0 ) return;
102554  
102555    assert( !db->init.busy || !pSelect );
102556  
102557    /* If the db->init.busy is 1 it means we are reading the SQL off the
102558    ** "sqlite_master" or "sqlite_temp_master" table on the disk.
102559    ** So do not write to the disk again.  Extract the root page number
102560    ** for the table from the db->init.newTnum field.  (The page number
102561    ** should have been put there by the sqliteOpenCb routine.)
102562    **
102563    ** If the root page number is 1, that means this is the sqlite_master
102564    ** table itself.  So mark it read-only.
102565    */
102566    if( db->init.busy ){
102567      p->tnum = db->init.newTnum;
102568      if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
102569    }
102570  
102571    /* Special processing for WITHOUT ROWID Tables */
102572    if( tabOpts & TF_WithoutRowid ){
102573      if( (p->tabFlags & TF_Autoincrement) ){
102574        sqlite3ErrorMsg(pParse,
102575            "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
102576        return;
102577      }
102578      if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
102579        sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
102580      }else{
102581        p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
102582        convertToWithoutRowidTable(pParse, p);
102583      }
102584    }
102585  
102586    iDb = sqlite3SchemaToIndex(db, p->pSchema);
102587  
102588  #ifndef SQLITE_OMIT_CHECK
102589    /* Resolve names in all CHECK constraint expressions.
102590    */
102591    if( p->pCheck ){
102592      sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
102593    }
102594  #endif /* !defined(SQLITE_OMIT_CHECK) */
102595  
102596    /* Estimate the average row size for the table and for all implied indices */
102597    estimateTableWidth(p);
102598    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
102599      estimateIndexWidth(pIdx);
102600    }
102601  
102602    /* If not initializing, then create a record for the new table
102603    ** in the SQLITE_MASTER table of the database.
102604    **
102605    ** If this is a TEMPORARY table, write the entry into the auxiliary
102606    ** file instead of into the main database file.
102607    */
102608    if( !db->init.busy ){
102609      int n;
102610      Vdbe *v;
102611      char *zType;    /* "view" or "table" */
102612      char *zType2;   /* "VIEW" or "TABLE" */
102613      char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
102614  
102615      v = sqlite3GetVdbe(pParse);
102616      if( NEVER(v==0) ) return;
102617  
102618      sqlite3VdbeAddOp1(v, OP_Close, 0);
102619  
102620      /* 
102621      ** Initialize zType for the new view or table.
102622      */
102623      if( p->pSelect==0 ){
102624        /* A regular table */
102625        zType = "table";
102626        zType2 = "TABLE";
102627  #ifndef SQLITE_OMIT_VIEW
102628      }else{
102629        /* A view */
102630        zType = "view";
102631        zType2 = "VIEW";
102632  #endif
102633      }
102634  
102635      /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
102636      ** statement to populate the new table. The root-page number for the
102637      ** new table is in register pParse->regRoot.
102638      **
102639      ** Once the SELECT has been coded by sqlite3Select(), it is in a
102640      ** suitable state to query for the column names and types to be used
102641      ** by the new table.
102642      **
102643      ** A shared-cache write-lock is not required to write to the new table,
102644      ** as a schema-lock must have already been obtained to create it. Since
102645      ** a schema-lock excludes all other database users, the write-lock would
102646      ** be redundant.
102647      */
102648      if( pSelect ){
102649        SelectDest dest;    /* Where the SELECT should store results */
102650        int regYield;       /* Register holding co-routine entry-point */
102651        int addrTop;        /* Top of the co-routine */
102652        int regRec;         /* A record to be insert into the new table */
102653        int regRowid;       /* Rowid of the next row to insert */
102654        int addrInsLoop;    /* Top of the loop for inserting rows */
102655        Table *pSelTab;     /* A table that describes the SELECT results */
102656  
102657        regYield = ++pParse->nMem;
102658        regRec = ++pParse->nMem;
102659        regRowid = ++pParse->nMem;
102660        assert(pParse->nTab==1);
102661        sqlite3MayAbort(pParse);
102662        sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
102663        sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
102664        pParse->nTab = 2;
102665        addrTop = sqlite3VdbeCurrentAddr(v) + 1;
102666        sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
102667        sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
102668        sqlite3Select(pParse, pSelect, &dest);
102669        sqlite3VdbeEndCoroutine(v, regYield);
102670        sqlite3VdbeJumpHere(v, addrTop - 1);
102671        if( pParse->nErr ) return;
102672        pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
102673        if( pSelTab==0 ) return;
102674        assert( p->aCol==0 );
102675        p->nCol = pSelTab->nCol;
102676        p->aCol = pSelTab->aCol;
102677        pSelTab->nCol = 0;
102678        pSelTab->aCol = 0;
102679        sqlite3DeleteTable(db, pSelTab);
102680        addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
102681        VdbeCoverage(v);
102682        sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
102683        sqlite3TableAffinity(v, p, 0);
102684        sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
102685        sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
102686        sqlite3VdbeGoto(v, addrInsLoop);
102687        sqlite3VdbeJumpHere(v, addrInsLoop);
102688        sqlite3VdbeAddOp1(v, OP_Close, 1);
102689      }
102690  
102691      /* Compute the complete text of the CREATE statement */
102692      if( pSelect ){
102693        zStmt = createTableStmt(db, p);
102694      }else{
102695        Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
102696        n = (int)(pEnd2->z - pParse->sNameToken.z);
102697        if( pEnd2->z[0]!=';' ) n += pEnd2->n;
102698        zStmt = sqlite3MPrintf(db, 
102699            "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
102700        );
102701      }
102702  
102703      /* A slot for the record has already been allocated in the 
102704      ** SQLITE_MASTER table.  We just need to update that slot with all
102705      ** the information we've collected.
102706      */
102707      sqlite3NestedParse(pParse,
102708        "UPDATE %Q.%s "
102709           "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
102710         "WHERE rowid=#%d",
102711        db->aDb[iDb].zDbSName, MASTER_NAME,
102712        zType,
102713        p->zName,
102714        p->zName,
102715        pParse->regRoot,
102716        zStmt,
102717        pParse->regRowid
102718      );
102719      sqlite3DbFree(db, zStmt);
102720      sqlite3ChangeCookie(pParse, iDb);
102721  
102722  #ifndef SQLITE_OMIT_AUTOINCREMENT
102723      /* Check to see if we need to create an sqlite_sequence table for
102724      ** keeping track of autoincrement keys.
102725      */
102726      if( (p->tabFlags & TF_Autoincrement)!=0 ){
102727        Db *pDb = &db->aDb[iDb];
102728        assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
102729        if( pDb->pSchema->pSeqTab==0 ){
102730          sqlite3NestedParse(pParse,
102731            "CREATE TABLE %Q.sqlite_sequence(name,seq)",
102732            pDb->zDbSName
102733          );
102734        }
102735      }
102736  #endif
102737  
102738      /* Reparse everything to update our internal data structures */
102739      sqlite3VdbeAddParseSchemaOp(v, iDb,
102740             sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
102741    }
102742  
102743  
102744    /* Add the table to the in-memory representation of the database.
102745    */
102746    if( db->init.busy ){
102747      Table *pOld;
102748      Schema *pSchema = p->pSchema;
102749      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
102750      pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
102751      if( pOld ){
102752        assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
102753        sqlite3OomFault(db);
102754        return;
102755      }
102756      pParse->pNewTable = 0;
102757      db->mDbFlags |= DBFLAG_SchemaChange;
102758  
102759  #ifndef SQLITE_OMIT_ALTERTABLE
102760      if( !p->pSelect ){
102761        const char *zName = (const char *)pParse->sNameToken.z;
102762        int nName;
102763        assert( !pSelect && pCons && pEnd );
102764        if( pCons->z==0 ){
102765          pCons = pEnd;
102766        }
102767        nName = (int)((const char *)pCons->z - zName);
102768        p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
102769      }
102770  #endif
102771    }
102772  }
102773  
102774  #ifndef SQLITE_OMIT_VIEW
102775  /*
102776  ** The parser calls this routine in order to create a new VIEW
102777  */
102778  SQLITE_PRIVATE void sqlite3CreateView(
102779    Parse *pParse,     /* The parsing context */
102780    Token *pBegin,     /* The CREATE token that begins the statement */
102781    Token *pName1,     /* The token that holds the name of the view */
102782    Token *pName2,     /* The token that holds the name of the view */
102783    ExprList *pCNames, /* Optional list of view column names */
102784    Select *pSelect,   /* A SELECT statement that will become the new view */
102785    int isTemp,        /* TRUE for a TEMPORARY view */
102786    int noErr          /* Suppress error messages if VIEW already exists */
102787  ){
102788    Table *p;
102789    int n;
102790    const char *z;
102791    Token sEnd;
102792    DbFixer sFix;
102793    Token *pName = 0;
102794    int iDb;
102795    sqlite3 *db = pParse->db;
102796  
102797    if( pParse->nVar>0 ){
102798      sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
102799      goto create_view_fail;
102800    }
102801    sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
102802    p = pParse->pNewTable;
102803    if( p==0 || pParse->nErr ) goto create_view_fail;
102804    sqlite3TwoPartName(pParse, pName1, pName2, &pName);
102805    iDb = sqlite3SchemaToIndex(db, p->pSchema);
102806    sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
102807    if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
102808  
102809    /* Make a copy of the entire SELECT statement that defines the view.
102810    ** This will force all the Expr.token.z values to be dynamically
102811    ** allocated rather than point to the input string - which means that
102812    ** they will persist after the current sqlite3_exec() call returns.
102813    */
102814    p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
102815    p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
102816    if( db->mallocFailed ) goto create_view_fail;
102817  
102818    /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
102819    ** the end.
102820    */
102821    sEnd = pParse->sLastToken;
102822    assert( sEnd.z[0]!=0 );
102823    if( sEnd.z[0]!=';' ){
102824      sEnd.z += sEnd.n;
102825    }
102826    sEnd.n = 0;
102827    n = (int)(sEnd.z - pBegin->z);
102828    assert( n>0 );
102829    z = pBegin->z;
102830    while( sqlite3Isspace(z[n-1]) ){ n--; }
102831    sEnd.z = &z[n-1];
102832    sEnd.n = 1;
102833  
102834    /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
102835    sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
102836  
102837  create_view_fail:
102838    sqlite3SelectDelete(db, pSelect);
102839    sqlite3ExprListDelete(db, pCNames);
102840    return;
102841  }
102842  #endif /* SQLITE_OMIT_VIEW */
102843  
102844  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
102845  /*
102846  ** The Table structure pTable is really a VIEW.  Fill in the names of
102847  ** the columns of the view in the pTable structure.  Return the number
102848  ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
102849  */
102850  SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
102851    Table *pSelTab;   /* A fake table from which we get the result set */
102852    Select *pSel;     /* Copy of the SELECT that implements the view */
102853    int nErr = 0;     /* Number of errors encountered */
102854    int n;            /* Temporarily holds the number of cursors assigned */
102855    sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
102856  #ifndef SQLITE_OMIT_VIRTUALTABLE	
102857    int rc;
102858  #endif
102859  #ifndef SQLITE_OMIT_AUTHORIZATION
102860    sqlite3_xauth xAuth;       /* Saved xAuth pointer */
102861  #endif
102862  
102863    assert( pTable );
102864  
102865  #ifndef SQLITE_OMIT_VIRTUALTABLE
102866    db->nSchemaLock++;
102867    rc = sqlite3VtabCallConnect(pParse, pTable);
102868    db->nSchemaLock--;
102869    if( rc ){
102870      return 1;
102871    }
102872    if( IsVirtual(pTable) ) return 0;
102873  #endif
102874  
102875  #ifndef SQLITE_OMIT_VIEW
102876    /* A positive nCol means the columns names for this view are
102877    ** already known.
102878    */
102879    if( pTable->nCol>0 ) return 0;
102880  
102881    /* A negative nCol is a special marker meaning that we are currently
102882    ** trying to compute the column names.  If we enter this routine with
102883    ** a negative nCol, it means two or more views form a loop, like this:
102884    **
102885    **     CREATE VIEW one AS SELECT * FROM two;
102886    **     CREATE VIEW two AS SELECT * FROM one;
102887    **
102888    ** Actually, the error above is now caught prior to reaching this point.
102889    ** But the following test is still important as it does come up
102890    ** in the following:
102891    ** 
102892    **     CREATE TABLE main.ex1(a);
102893    **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
102894    **     SELECT * FROM temp.ex1;
102895    */
102896    if( pTable->nCol<0 ){
102897      sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
102898      return 1;
102899    }
102900    assert( pTable->nCol>=0 );
102901  
102902    /* If we get this far, it means we need to compute the table names.
102903    ** Note that the call to sqlite3ResultSetOfSelect() will expand any
102904    ** "*" elements in the results set of the view and will assign cursors
102905    ** to the elements of the FROM clause.  But we do not want these changes
102906    ** to be permanent.  So the computation is done on a copy of the SELECT
102907    ** statement that defines the view.
102908    */
102909    assert( pTable->pSelect );
102910    pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
102911    if( pSel ){
102912      n = pParse->nTab;
102913      sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
102914      pTable->nCol = -1;
102915      db->lookaside.bDisable++;
102916  #ifndef SQLITE_OMIT_AUTHORIZATION
102917      xAuth = db->xAuth;
102918      db->xAuth = 0;
102919      pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
102920      db->xAuth = xAuth;
102921  #else
102922      pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
102923  #endif
102924      pParse->nTab = n;
102925      if( pTable->pCheck ){
102926        /* CREATE VIEW name(arglist) AS ...
102927        ** The names of the columns in the table are taken from
102928        ** arglist which is stored in pTable->pCheck.  The pCheck field
102929        ** normally holds CHECK constraints on an ordinary table, but for
102930        ** a VIEW it holds the list of column names.
102931        */
102932        sqlite3ColumnsFromExprList(pParse, pTable->pCheck, 
102933                                   &pTable->nCol, &pTable->aCol);
102934        if( db->mallocFailed==0 
102935         && pParse->nErr==0
102936         && pTable->nCol==pSel->pEList->nExpr
102937        ){
102938          sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
102939        }
102940      }else if( pSelTab ){
102941        /* CREATE VIEW name AS...  without an argument list.  Construct
102942        ** the column names from the SELECT statement that defines the view.
102943        */
102944        assert( pTable->aCol==0 );
102945        pTable->nCol = pSelTab->nCol;
102946        pTable->aCol = pSelTab->aCol;
102947        pSelTab->nCol = 0;
102948        pSelTab->aCol = 0;
102949        assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
102950      }else{
102951        pTable->nCol = 0;
102952        nErr++;
102953      }
102954      sqlite3DeleteTable(db, pSelTab);
102955      sqlite3SelectDelete(db, pSel);
102956      db->lookaside.bDisable--;
102957    } else {
102958      nErr++;
102959    }
102960    pTable->pSchema->schemaFlags |= DB_UnresetViews;
102961  #endif /* SQLITE_OMIT_VIEW */
102962    return nErr;  
102963  }
102964  #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
102965  
102966  #ifndef SQLITE_OMIT_VIEW
102967  /*
102968  ** Clear the column names from every VIEW in database idx.
102969  */
102970  static void sqliteViewResetAll(sqlite3 *db, int idx){
102971    HashElem *i;
102972    assert( sqlite3SchemaMutexHeld(db, idx, 0) );
102973    if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
102974    for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
102975      Table *pTab = sqliteHashData(i);
102976      if( pTab->pSelect ){
102977        sqlite3DeleteColumnNames(db, pTab);
102978        pTab->aCol = 0;
102979        pTab->nCol = 0;
102980      }
102981    }
102982    DbClearProperty(db, idx, DB_UnresetViews);
102983  }
102984  #else
102985  # define sqliteViewResetAll(A,B)
102986  #endif /* SQLITE_OMIT_VIEW */
102987  
102988  /*
102989  ** This function is called by the VDBE to adjust the internal schema
102990  ** used by SQLite when the btree layer moves a table root page. The
102991  ** root-page of a table or index in database iDb has changed from iFrom
102992  ** to iTo.
102993  **
102994  ** Ticket #1728:  The symbol table might still contain information
102995  ** on tables and/or indices that are the process of being deleted.
102996  ** If you are unlucky, one of those deleted indices or tables might
102997  ** have the same rootpage number as the real table or index that is
102998  ** being moved.  So we cannot stop searching after the first match 
102999  ** because the first match might be for one of the deleted indices
103000  ** or tables and not the table/index that is actually being moved.
103001  ** We must continue looping until all tables and indices with
103002  ** rootpage==iFrom have been converted to have a rootpage of iTo
103003  ** in order to be certain that we got the right one.
103004  */
103005  #ifndef SQLITE_OMIT_AUTOVACUUM
103006  SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
103007    HashElem *pElem;
103008    Hash *pHash;
103009    Db *pDb;
103010  
103011    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
103012    pDb = &db->aDb[iDb];
103013    pHash = &pDb->pSchema->tblHash;
103014    for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
103015      Table *pTab = sqliteHashData(pElem);
103016      if( pTab->tnum==iFrom ){
103017        pTab->tnum = iTo;
103018      }
103019    }
103020    pHash = &pDb->pSchema->idxHash;
103021    for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
103022      Index *pIdx = sqliteHashData(pElem);
103023      if( pIdx->tnum==iFrom ){
103024        pIdx->tnum = iTo;
103025      }
103026    }
103027  }
103028  #endif
103029  
103030  /*
103031  ** Write code to erase the table with root-page iTable from database iDb.
103032  ** Also write code to modify the sqlite_master table and internal schema
103033  ** if a root-page of another table is moved by the btree-layer whilst
103034  ** erasing iTable (this can happen with an auto-vacuum database).
103035  */ 
103036  static void destroyRootPage(Parse *pParse, int iTable, int iDb){
103037    Vdbe *v = sqlite3GetVdbe(pParse);
103038    int r1 = sqlite3GetTempReg(pParse);
103039    assert( iTable>1 );
103040    sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
103041    sqlite3MayAbort(pParse);
103042  #ifndef SQLITE_OMIT_AUTOVACUUM
103043    /* OP_Destroy stores an in integer r1. If this integer
103044    ** is non-zero, then it is the root page number of a table moved to
103045    ** location iTable. The following code modifies the sqlite_master table to
103046    ** reflect this.
103047    **
103048    ** The "#NNN" in the SQL is a special constant that means whatever value
103049    ** is in register NNN.  See grammar rules associated with the TK_REGISTER
103050    ** token for additional information.
103051    */
103052    sqlite3NestedParse(pParse, 
103053       "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
103054       pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);
103055  #endif
103056    sqlite3ReleaseTempReg(pParse, r1);
103057  }
103058  
103059  /*
103060  ** Write VDBE code to erase table pTab and all associated indices on disk.
103061  ** Code to update the sqlite_master tables and internal schema definitions
103062  ** in case a root-page belonging to another table is moved by the btree layer
103063  ** is also added (this can happen with an auto-vacuum database).
103064  */
103065  static void destroyTable(Parse *pParse, Table *pTab){
103066    /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
103067    ** is not defined), then it is important to call OP_Destroy on the
103068    ** table and index root-pages in order, starting with the numerically 
103069    ** largest root-page number. This guarantees that none of the root-pages
103070    ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
103071    ** following were coded:
103072    **
103073    ** OP_Destroy 4 0
103074    ** ...
103075    ** OP_Destroy 5 0
103076    **
103077    ** and root page 5 happened to be the largest root-page number in the
103078    ** database, then root page 5 would be moved to page 4 by the 
103079    ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
103080    ** a free-list page.
103081    */
103082    int iTab = pTab->tnum;
103083    int iDestroyed = 0;
103084  
103085    while( 1 ){
103086      Index *pIdx;
103087      int iLargest = 0;
103088  
103089      if( iDestroyed==0 || iTab<iDestroyed ){
103090        iLargest = iTab;
103091      }
103092      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
103093        int iIdx = pIdx->tnum;
103094        assert( pIdx->pSchema==pTab->pSchema );
103095        if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
103096          iLargest = iIdx;
103097        }
103098      }
103099      if( iLargest==0 ){
103100        return;
103101      }else{
103102        int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
103103        assert( iDb>=0 && iDb<pParse->db->nDb );
103104        destroyRootPage(pParse, iLargest, iDb);
103105        iDestroyed = iLargest;
103106      }
103107    }
103108  }
103109  
103110  /*
103111  ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
103112  ** after a DROP INDEX or DROP TABLE command.
103113  */
103114  static void sqlite3ClearStatTables(
103115    Parse *pParse,         /* The parsing context */
103116    int iDb,               /* The database number */
103117    const char *zType,     /* "idx" or "tbl" */
103118    const char *zName      /* Name of index or table */
103119  ){
103120    int i;
103121    const char *zDbName = pParse->db->aDb[iDb].zDbSName;
103122    for(i=1; i<=4; i++){
103123      char zTab[24];
103124      sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
103125      if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
103126        sqlite3NestedParse(pParse,
103127          "DELETE FROM %Q.%s WHERE %s=%Q",
103128          zDbName, zTab, zType, zName
103129        );
103130      }
103131    }
103132  }
103133  
103134  /*
103135  ** Generate code to drop a table.
103136  */
103137  SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
103138    Vdbe *v;
103139    sqlite3 *db = pParse->db;
103140    Trigger *pTrigger;
103141    Db *pDb = &db->aDb[iDb];
103142  
103143    v = sqlite3GetVdbe(pParse);
103144    assert( v!=0 );
103145    sqlite3BeginWriteOperation(pParse, 1, iDb);
103146  
103147  #ifndef SQLITE_OMIT_VIRTUALTABLE
103148    if( IsVirtual(pTab) ){
103149      sqlite3VdbeAddOp0(v, OP_VBegin);
103150    }
103151  #endif
103152  
103153    /* Drop all triggers associated with the table being dropped. Code
103154    ** is generated to remove entries from sqlite_master and/or
103155    ** sqlite_temp_master if required.
103156    */
103157    pTrigger = sqlite3TriggerList(pParse, pTab);
103158    while( pTrigger ){
103159      assert( pTrigger->pSchema==pTab->pSchema || 
103160          pTrigger->pSchema==db->aDb[1].pSchema );
103161      sqlite3DropTriggerPtr(pParse, pTrigger);
103162      pTrigger = pTrigger->pNext;
103163    }
103164  
103165  #ifndef SQLITE_OMIT_AUTOINCREMENT
103166    /* Remove any entries of the sqlite_sequence table associated with
103167    ** the table being dropped. This is done before the table is dropped
103168    ** at the btree level, in case the sqlite_sequence table needs to
103169    ** move as a result of the drop (can happen in auto-vacuum mode).
103170    */
103171    if( pTab->tabFlags & TF_Autoincrement ){
103172      sqlite3NestedParse(pParse,
103173        "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
103174        pDb->zDbSName, pTab->zName
103175      );
103176    }
103177  #endif
103178  
103179    /* Drop all SQLITE_MASTER table and index entries that refer to the
103180    ** table. The program name loops through the master table and deletes
103181    ** every row that refers to a table of the same name as the one being
103182    ** dropped. Triggers are handled separately because a trigger can be
103183    ** created in the temp database that refers to a table in another
103184    ** database.
103185    */
103186    sqlite3NestedParse(pParse, 
103187        "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
103188        pDb->zDbSName, MASTER_NAME, pTab->zName);
103189    if( !isView && !IsVirtual(pTab) ){
103190      destroyTable(pParse, pTab);
103191    }
103192  
103193    /* Remove the table entry from SQLite's internal schema and modify
103194    ** the schema cookie.
103195    */
103196    if( IsVirtual(pTab) ){
103197      sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
103198    }
103199    sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
103200    sqlite3ChangeCookie(pParse, iDb);
103201    sqliteViewResetAll(db, iDb);
103202  }
103203  
103204  /*
103205  ** This routine is called to do the work of a DROP TABLE statement.
103206  ** pName is the name of the table to be dropped.
103207  */
103208  SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
103209    Table *pTab;
103210    Vdbe *v;
103211    sqlite3 *db = pParse->db;
103212    int iDb;
103213  
103214    if( db->mallocFailed ){
103215      goto exit_drop_table;
103216    }
103217    assert( pParse->nErr==0 );
103218    assert( pName->nSrc==1 );
103219    if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
103220    if( noErr ) db->suppressErr++;
103221    assert( isView==0 || isView==LOCATE_VIEW );
103222    pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
103223    if( noErr ) db->suppressErr--;
103224  
103225    if( pTab==0 ){
103226      if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
103227      goto exit_drop_table;
103228    }
103229    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
103230    assert( iDb>=0 && iDb<db->nDb );
103231  
103232    /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
103233    ** it is initialized.
103234    */
103235    if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
103236      goto exit_drop_table;
103237    }
103238  #ifndef SQLITE_OMIT_AUTHORIZATION
103239    {
103240      int code;
103241      const char *zTab = SCHEMA_TABLE(iDb);
103242      const char *zDb = db->aDb[iDb].zDbSName;
103243      const char *zArg2 = 0;
103244      if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
103245        goto exit_drop_table;
103246      }
103247      if( isView ){
103248        if( !OMIT_TEMPDB && iDb==1 ){
103249          code = SQLITE_DROP_TEMP_VIEW;
103250        }else{
103251          code = SQLITE_DROP_VIEW;
103252        }
103253  #ifndef SQLITE_OMIT_VIRTUALTABLE
103254      }else if( IsVirtual(pTab) ){
103255        code = SQLITE_DROP_VTABLE;
103256        zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
103257  #endif
103258      }else{
103259        if( !OMIT_TEMPDB && iDb==1 ){
103260          code = SQLITE_DROP_TEMP_TABLE;
103261        }else{
103262          code = SQLITE_DROP_TABLE;
103263        }
103264      }
103265      if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
103266        goto exit_drop_table;
103267      }
103268      if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
103269        goto exit_drop_table;
103270      }
103271    }
103272  #endif
103273    if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
103274      && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
103275      sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
103276      goto exit_drop_table;
103277    }
103278  
103279  #ifndef SQLITE_OMIT_VIEW
103280    /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
103281    ** on a table.
103282    */
103283    if( isView && pTab->pSelect==0 ){
103284      sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
103285      goto exit_drop_table;
103286    }
103287    if( !isView && pTab->pSelect ){
103288      sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
103289      goto exit_drop_table;
103290    }
103291  #endif
103292  
103293    /* Generate code to remove the table from the master table
103294    ** on disk.
103295    */
103296    v = sqlite3GetVdbe(pParse);
103297    if( v ){
103298      sqlite3BeginWriteOperation(pParse, 1, iDb);
103299      sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
103300      sqlite3FkDropTable(pParse, pName, pTab);
103301      sqlite3CodeDropTable(pParse, pTab, iDb, isView);
103302    }
103303  
103304  exit_drop_table:
103305    sqlite3SrcListDelete(db, pName);
103306  }
103307  
103308  /*
103309  ** This routine is called to create a new foreign key on the table
103310  ** currently under construction.  pFromCol determines which columns
103311  ** in the current table point to the foreign key.  If pFromCol==0 then
103312  ** connect the key to the last column inserted.  pTo is the name of
103313  ** the table referred to (a.k.a the "parent" table).  pToCol is a list
103314  ** of tables in the parent pTo table.  flags contains all
103315  ** information about the conflict resolution algorithms specified
103316  ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
103317  **
103318  ** An FKey structure is created and added to the table currently
103319  ** under construction in the pParse->pNewTable field.
103320  **
103321  ** The foreign key is set for IMMEDIATE processing.  A subsequent call
103322  ** to sqlite3DeferForeignKey() might change this to DEFERRED.
103323  */
103324  SQLITE_PRIVATE void sqlite3CreateForeignKey(
103325    Parse *pParse,       /* Parsing context */
103326    ExprList *pFromCol,  /* Columns in this table that point to other table */
103327    Token *pTo,          /* Name of the other table */
103328    ExprList *pToCol,    /* Columns in the other table */
103329    int flags            /* Conflict resolution algorithms. */
103330  ){
103331    sqlite3 *db = pParse->db;
103332  #ifndef SQLITE_OMIT_FOREIGN_KEY
103333    FKey *pFKey = 0;
103334    FKey *pNextTo;
103335    Table *p = pParse->pNewTable;
103336    int nByte;
103337    int i;
103338    int nCol;
103339    char *z;
103340  
103341    assert( pTo!=0 );
103342    if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
103343    if( pFromCol==0 ){
103344      int iCol = p->nCol-1;
103345      if( NEVER(iCol<0) ) goto fk_end;
103346      if( pToCol && pToCol->nExpr!=1 ){
103347        sqlite3ErrorMsg(pParse, "foreign key on %s"
103348           " should reference only one column of table %T",
103349           p->aCol[iCol].zName, pTo);
103350        goto fk_end;
103351      }
103352      nCol = 1;
103353    }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
103354      sqlite3ErrorMsg(pParse,
103355          "number of columns in foreign key does not match the number of "
103356          "columns in the referenced table");
103357      goto fk_end;
103358    }else{
103359      nCol = pFromCol->nExpr;
103360    }
103361    nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
103362    if( pToCol ){
103363      for(i=0; i<pToCol->nExpr; i++){
103364        nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
103365      }
103366    }
103367    pFKey = sqlite3DbMallocZero(db, nByte );
103368    if( pFKey==0 ){
103369      goto fk_end;
103370    }
103371    pFKey->pFrom = p;
103372    pFKey->pNextFrom = p->pFKey;
103373    z = (char*)&pFKey->aCol[nCol];
103374    pFKey->zTo = z;
103375    memcpy(z, pTo->z, pTo->n);
103376    z[pTo->n] = 0;
103377    sqlite3Dequote(z);
103378    z += pTo->n+1;
103379    pFKey->nCol = nCol;
103380    if( pFromCol==0 ){
103381      pFKey->aCol[0].iFrom = p->nCol-1;
103382    }else{
103383      for(i=0; i<nCol; i++){
103384        int j;
103385        for(j=0; j<p->nCol; j++){
103386          if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
103387            pFKey->aCol[i].iFrom = j;
103388            break;
103389          }
103390        }
103391        if( j>=p->nCol ){
103392          sqlite3ErrorMsg(pParse, 
103393            "unknown column \"%s\" in foreign key definition", 
103394            pFromCol->a[i].zName);
103395          goto fk_end;
103396        }
103397      }
103398    }
103399    if( pToCol ){
103400      for(i=0; i<nCol; i++){
103401        int n = sqlite3Strlen30(pToCol->a[i].zName);
103402        pFKey->aCol[i].zCol = z;
103403        memcpy(z, pToCol->a[i].zName, n);
103404        z[n] = 0;
103405        z += n+1;
103406      }
103407    }
103408    pFKey->isDeferred = 0;
103409    pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
103410    pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
103411  
103412    assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
103413    pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
103414        pFKey->zTo, (void *)pFKey
103415    );
103416    if( pNextTo==pFKey ){
103417      sqlite3OomFault(db);
103418      goto fk_end;
103419    }
103420    if( pNextTo ){
103421      assert( pNextTo->pPrevTo==0 );
103422      pFKey->pNextTo = pNextTo;
103423      pNextTo->pPrevTo = pFKey;
103424    }
103425  
103426    /* Link the foreign key to the table as the last step.
103427    */
103428    p->pFKey = pFKey;
103429    pFKey = 0;
103430  
103431  fk_end:
103432    sqlite3DbFree(db, pFKey);
103433  #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
103434    sqlite3ExprListDelete(db, pFromCol);
103435    sqlite3ExprListDelete(db, pToCol);
103436  }
103437  
103438  /*
103439  ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
103440  ** clause is seen as part of a foreign key definition.  The isDeferred
103441  ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
103442  ** The behavior of the most recently created foreign key is adjusted
103443  ** accordingly.
103444  */
103445  SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
103446  #ifndef SQLITE_OMIT_FOREIGN_KEY
103447    Table *pTab;
103448    FKey *pFKey;
103449    if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
103450    assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
103451    pFKey->isDeferred = (u8)isDeferred;
103452  #endif
103453  }
103454  
103455  /*
103456  ** Generate code that will erase and refill index *pIdx.  This is
103457  ** used to initialize a newly created index or to recompute the
103458  ** content of an index in response to a REINDEX command.
103459  **
103460  ** if memRootPage is not negative, it means that the index is newly
103461  ** created.  The register specified by memRootPage contains the
103462  ** root page number of the index.  If memRootPage is negative, then
103463  ** the index already exists and must be cleared before being refilled and
103464  ** the root page number of the index is taken from pIndex->tnum.
103465  */
103466  static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
103467    Table *pTab = pIndex->pTable;  /* The table that is indexed */
103468    int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
103469    int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
103470    int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
103471    int addr1;                     /* Address of top of loop */
103472    int addr2;                     /* Address to jump to for next iteration */
103473    int tnum;                      /* Root page of index */
103474    int iPartIdxLabel;             /* Jump to this label to skip a row */
103475    Vdbe *v;                       /* Generate code into this virtual machine */
103476    KeyInfo *pKey;                 /* KeyInfo for index */
103477    int regRecord;                 /* Register holding assembled index record */
103478    sqlite3 *db = pParse->db;      /* The database connection */
103479    int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
103480  
103481  #ifndef SQLITE_OMIT_AUTHORIZATION
103482    if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
103483        db->aDb[iDb].zDbSName ) ){
103484      return;
103485    }
103486  #endif
103487  
103488    /* Require a write-lock on the table to perform this operation */
103489    sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
103490  
103491    v = sqlite3GetVdbe(pParse);
103492    if( v==0 ) return;
103493    if( memRootPage>=0 ){
103494      tnum = memRootPage;
103495    }else{
103496      tnum = pIndex->tnum;
103497    }
103498    pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
103499    assert( pKey!=0 || db->mallocFailed || pParse->nErr );
103500  
103501    /* Open the sorter cursor if we are to use one. */
103502    iSorter = pParse->nTab++;
103503    sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
103504                      sqlite3KeyInfoRef(pKey), P4_KEYINFO);
103505  
103506    /* Open the table. Loop through all rows of the table, inserting index
103507    ** records into the sorter. */
103508    sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
103509    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
103510    regRecord = sqlite3GetTempReg(pParse);
103511  
103512    sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
103513    sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
103514    sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
103515    sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
103516    sqlite3VdbeJumpHere(v, addr1);
103517    if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
103518    sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
103519                      (char *)pKey, P4_KEYINFO);
103520    sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
103521  
103522    addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
103523    if( IsUniqueIndex(pIndex) ){
103524      int j2 = sqlite3VdbeCurrentAddr(v) + 3;
103525      sqlite3VdbeGoto(v, j2);
103526      addr2 = sqlite3VdbeCurrentAddr(v);
103527      sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
103528                           pIndex->nKeyCol); VdbeCoverage(v);
103529      sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
103530    }else{
103531      addr2 = sqlite3VdbeCurrentAddr(v);
103532    }
103533    sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
103534    sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
103535    sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
103536    sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
103537    sqlite3ReleaseTempReg(pParse, regRecord);
103538    sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
103539    sqlite3VdbeJumpHere(v, addr1);
103540  
103541    sqlite3VdbeAddOp1(v, OP_Close, iTab);
103542    sqlite3VdbeAddOp1(v, OP_Close, iIdx);
103543    sqlite3VdbeAddOp1(v, OP_Close, iSorter);
103544  }
103545  
103546  /*
103547  ** Allocate heap space to hold an Index object with nCol columns.
103548  **
103549  ** Increase the allocation size to provide an extra nExtra bytes
103550  ** of 8-byte aligned space after the Index object and return a
103551  ** pointer to this extra space in *ppExtra.
103552  */
103553  SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
103554    sqlite3 *db,         /* Database connection */
103555    i16 nCol,            /* Total number of columns in the index */
103556    int nExtra,          /* Number of bytes of extra space to alloc */
103557    char **ppExtra       /* Pointer to the "extra" space */
103558  ){
103559    Index *p;            /* Allocated index object */
103560    int nByte;           /* Bytes of space for Index object + arrays */
103561  
103562    nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
103563            ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
103564            ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
103565                   sizeof(i16)*nCol +            /* Index.aiColumn   */
103566                   sizeof(u8)*nCol);             /* Index.aSortOrder */
103567    p = sqlite3DbMallocZero(db, nByte + nExtra);
103568    if( p ){
103569      char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
103570      p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
103571      p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
103572      p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
103573      p->aSortOrder = (u8*)pExtra;
103574      p->nColumn = nCol;
103575      p->nKeyCol = nCol - 1;
103576      *ppExtra = ((char*)p) + nByte;
103577    }
103578    return p;
103579  }
103580  
103581  /*
103582  ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
103583  ** and pTblList is the name of the table that is to be indexed.  Both will 
103584  ** be NULL for a primary key or an index that is created to satisfy a
103585  ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
103586  ** as the table to be indexed.  pParse->pNewTable is a table that is
103587  ** currently being constructed by a CREATE TABLE statement.
103588  **
103589  ** pList is a list of columns to be indexed.  pList will be NULL if this
103590  ** is a primary key or unique-constraint on the most recent column added
103591  ** to the table currently under construction.  
103592  */
103593  SQLITE_PRIVATE void sqlite3CreateIndex(
103594    Parse *pParse,     /* All information about this parse */
103595    Token *pName1,     /* First part of index name. May be NULL */
103596    Token *pName2,     /* Second part of index name. May be NULL */
103597    SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
103598    ExprList *pList,   /* A list of columns to be indexed */
103599    int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
103600    Token *pStart,     /* The CREATE token that begins this statement */
103601    Expr *pPIWhere,    /* WHERE clause for partial indices */
103602    int sortOrder,     /* Sort order of primary key when pList==NULL */
103603    int ifNotExist,    /* Omit error if index already exists */
103604    u8 idxType         /* The index type */
103605  ){
103606    Table *pTab = 0;     /* Table to be indexed */
103607    Index *pIndex = 0;   /* The index to be created */
103608    char *zName = 0;     /* Name of the index */
103609    int nName;           /* Number of characters in zName */
103610    int i, j;
103611    DbFixer sFix;        /* For assigning database names to pTable */
103612    int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
103613    sqlite3 *db = pParse->db;
103614    Db *pDb;             /* The specific table containing the indexed database */
103615    int iDb;             /* Index of the database that is being written */
103616    Token *pName = 0;    /* Unqualified name of the index to create */
103617    struct ExprList_item *pListItem; /* For looping over pList */
103618    int nExtra = 0;                  /* Space allocated for zExtra[] */
103619    int nExtraCol;                   /* Number of extra columns needed */
103620    char *zExtra = 0;                /* Extra space after the Index object */
103621    Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
103622  
103623    if( db->mallocFailed || pParse->nErr>0 ){
103624      goto exit_create_index;
103625    }
103626    if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
103627      goto exit_create_index;
103628    }
103629    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
103630      goto exit_create_index;
103631    }
103632  
103633    /*
103634    ** Find the table that is to be indexed.  Return early if not found.
103635    */
103636    if( pTblName!=0 ){
103637  
103638      /* Use the two-part index name to determine the database 
103639      ** to search for the table. 'Fix' the table name to this db
103640      ** before looking up the table.
103641      */
103642      assert( pName1 && pName2 );
103643      iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
103644      if( iDb<0 ) goto exit_create_index;
103645      assert( pName && pName->z );
103646  
103647  #ifndef SQLITE_OMIT_TEMPDB
103648      /* If the index name was unqualified, check if the table
103649      ** is a temp table. If so, set the database to 1. Do not do this
103650      ** if initialising a database schema.
103651      */
103652      if( !db->init.busy ){
103653        pTab = sqlite3SrcListLookup(pParse, pTblName);
103654        if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
103655          iDb = 1;
103656        }
103657      }
103658  #endif
103659  
103660      sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
103661      if( sqlite3FixSrcList(&sFix, pTblName) ){
103662        /* Because the parser constructs pTblName from a single identifier,
103663        ** sqlite3FixSrcList can never fail. */
103664        assert(0);
103665      }
103666      pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
103667      assert( db->mallocFailed==0 || pTab==0 );
103668      if( pTab==0 ) goto exit_create_index;
103669      if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
103670        sqlite3ErrorMsg(pParse, 
103671             "cannot create a TEMP index on non-TEMP table \"%s\"",
103672             pTab->zName);
103673        goto exit_create_index;
103674      }
103675      if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
103676    }else{
103677      assert( pName==0 );
103678      assert( pStart==0 );
103679      pTab = pParse->pNewTable;
103680      if( !pTab ) goto exit_create_index;
103681      iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
103682    }
103683    pDb = &db->aDb[iDb];
103684  
103685    assert( pTab!=0 );
103686    assert( pParse->nErr==0 );
103687    if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
103688         && db->init.busy==0
103689  #if SQLITE_USER_AUTHENTICATION
103690         && sqlite3UserAuthTable(pTab->zName)==0
103691  #endif
103692         && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
103693      sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
103694      goto exit_create_index;
103695    }
103696  #ifndef SQLITE_OMIT_VIEW
103697    if( pTab->pSelect ){
103698      sqlite3ErrorMsg(pParse, "views may not be indexed");
103699      goto exit_create_index;
103700    }
103701  #endif
103702  #ifndef SQLITE_OMIT_VIRTUALTABLE
103703    if( IsVirtual(pTab) ){
103704      sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
103705      goto exit_create_index;
103706    }
103707  #endif
103708  
103709    /*
103710    ** Find the name of the index.  Make sure there is not already another
103711    ** index or table with the same name.  
103712    **
103713    ** Exception:  If we are reading the names of permanent indices from the
103714    ** sqlite_master table (because some other process changed the schema) and
103715    ** one of the index names collides with the name of a temporary table or
103716    ** index, then we will continue to process this index.
103717    **
103718    ** If pName==0 it means that we are
103719    ** dealing with a primary key or UNIQUE constraint.  We have to invent our
103720    ** own name.
103721    */
103722    if( pName ){
103723      zName = sqlite3NameFromToken(db, pName);
103724      if( zName==0 ) goto exit_create_index;
103725      assert( pName->z!=0 );
103726      if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
103727        goto exit_create_index;
103728      }
103729      if( !db->init.busy ){
103730        if( sqlite3FindTable(db, zName, 0)!=0 ){
103731          sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
103732          goto exit_create_index;
103733        }
103734      }
103735      if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
103736        if( !ifNotExist ){
103737          sqlite3ErrorMsg(pParse, "index %s already exists", zName);
103738        }else{
103739          assert( !db->init.busy );
103740          sqlite3CodeVerifySchema(pParse, iDb);
103741        }
103742        goto exit_create_index;
103743      }
103744    }else{
103745      int n;
103746      Index *pLoop;
103747      for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
103748      zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
103749      if( zName==0 ){
103750        goto exit_create_index;
103751      }
103752  
103753      /* Automatic index names generated from within sqlite3_declare_vtab()
103754      ** must have names that are distinct from normal automatic index names.
103755      ** The following statement converts "sqlite3_autoindex..." into
103756      ** "sqlite3_butoindex..." in order to make the names distinct.
103757      ** The "vtab_err.test" test demonstrates the need of this statement. */
103758      if( IN_DECLARE_VTAB ) zName[7]++;
103759    }
103760  
103761    /* Check for authorization to create an index.
103762    */
103763  #ifndef SQLITE_OMIT_AUTHORIZATION
103764    {
103765      const char *zDb = pDb->zDbSName;
103766      if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
103767        goto exit_create_index;
103768      }
103769      i = SQLITE_CREATE_INDEX;
103770      if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
103771      if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
103772        goto exit_create_index;
103773      }
103774    }
103775  #endif
103776  
103777    /* If pList==0, it means this routine was called to make a primary
103778    ** key out of the last column added to the table under construction.
103779    ** So create a fake list to simulate this.
103780    */
103781    if( pList==0 ){
103782      Token prevCol;
103783      sqlite3TokenInit(&prevCol, pTab->aCol[pTab->nCol-1].zName);
103784      pList = sqlite3ExprListAppend(pParse, 0,
103785                sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
103786      if( pList==0 ) goto exit_create_index;
103787      assert( pList->nExpr==1 );
103788      sqlite3ExprListSetSortOrder(pList, sortOrder);
103789    }else{
103790      sqlite3ExprListCheckLength(pParse, pList, "index");
103791    }
103792  
103793    /* Figure out how many bytes of space are required to store explicitly
103794    ** specified collation sequence names.
103795    */
103796    for(i=0; i<pList->nExpr; i++){
103797      Expr *pExpr = pList->a[i].pExpr;
103798      assert( pExpr!=0 );
103799      if( pExpr->op==TK_COLLATE ){
103800        nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
103801      }
103802    }
103803  
103804    /* 
103805    ** Allocate the index structure. 
103806    */
103807    nName = sqlite3Strlen30(zName);
103808    nExtraCol = pPk ? pPk->nKeyCol : 1;
103809    pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
103810                                        nName + nExtra + 1, &zExtra);
103811    if( db->mallocFailed ){
103812      goto exit_create_index;
103813    }
103814    assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
103815    assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
103816    pIndex->zName = zExtra;
103817    zExtra += nName + 1;
103818    memcpy(pIndex->zName, zName, nName+1);
103819    pIndex->pTable = pTab;
103820    pIndex->onError = (u8)onError;
103821    pIndex->uniqNotNull = onError!=OE_None;
103822    pIndex->idxType = idxType;
103823    pIndex->pSchema = db->aDb[iDb].pSchema;
103824    pIndex->nKeyCol = pList->nExpr;
103825    if( pPIWhere ){
103826      sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
103827      pIndex->pPartIdxWhere = pPIWhere;
103828      pPIWhere = 0;
103829    }
103830    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
103831  
103832    /* Check to see if we should honor DESC requests on index columns
103833    */
103834    if( pDb->pSchema->file_format>=4 ){
103835      sortOrderMask = -1;   /* Honor DESC */
103836    }else{
103837      sortOrderMask = 0;    /* Ignore DESC */
103838    }
103839  
103840    /* Analyze the list of expressions that form the terms of the index and
103841    ** report any errors.  In the common case where the expression is exactly
103842    ** a table column, store that column in aiColumn[].  For general expressions,
103843    ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
103844    **
103845    ** TODO: Issue a warning if two or more columns of the index are identical.
103846    ** TODO: Issue a warning if the table primary key is used as part of the
103847    ** index key.
103848    */
103849    for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
103850      Expr *pCExpr;                  /* The i-th index expression */
103851      int requestedSortOrder;        /* ASC or DESC on the i-th expression */
103852      const char *zColl;             /* Collation sequence name */
103853  
103854      sqlite3StringToId(pListItem->pExpr);
103855      sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
103856      if( pParse->nErr ) goto exit_create_index;
103857      pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
103858      if( pCExpr->op!=TK_COLUMN ){
103859        if( pTab==pParse->pNewTable ){
103860          sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
103861                                  "UNIQUE constraints");
103862          goto exit_create_index;
103863        }
103864        if( pIndex->aColExpr==0 ){
103865          ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
103866          pIndex->aColExpr = pCopy;
103867          if( !db->mallocFailed ){
103868            assert( pCopy!=0 );
103869            pListItem = &pCopy->a[i];
103870          }
103871        }
103872        j = XN_EXPR;
103873        pIndex->aiColumn[i] = XN_EXPR;
103874        pIndex->uniqNotNull = 0;
103875      }else{
103876        j = pCExpr->iColumn;
103877        assert( j<=0x7fff );
103878        if( j<0 ){
103879          j = pTab->iPKey;
103880        }else if( pTab->aCol[j].notNull==0 ){
103881          pIndex->uniqNotNull = 0;
103882        }
103883        pIndex->aiColumn[i] = (i16)j;
103884      }
103885      zColl = 0;
103886      if( pListItem->pExpr->op==TK_COLLATE ){
103887        int nColl;
103888        zColl = pListItem->pExpr->u.zToken;
103889        nColl = sqlite3Strlen30(zColl) + 1;
103890        assert( nExtra>=nColl );
103891        memcpy(zExtra, zColl, nColl);
103892        zColl = zExtra;
103893        zExtra += nColl;
103894        nExtra -= nColl;
103895      }else if( j>=0 ){
103896        zColl = pTab->aCol[j].zColl;
103897      }
103898      if( !zColl ) zColl = sqlite3StrBINARY;
103899      if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
103900        goto exit_create_index;
103901      }
103902      pIndex->azColl[i] = zColl;
103903      requestedSortOrder = pListItem->sortOrder & sortOrderMask;
103904      pIndex->aSortOrder[i] = (u8)requestedSortOrder;
103905    }
103906  
103907    /* Append the table key to the end of the index.  For WITHOUT ROWID
103908    ** tables (when pPk!=0) this will be the declared PRIMARY KEY.  For
103909    ** normal tables (when pPk==0) this will be the rowid.
103910    */
103911    if( pPk ){
103912      for(j=0; j<pPk->nKeyCol; j++){
103913        int x = pPk->aiColumn[j];
103914        assert( x>=0 );
103915        if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
103916          pIndex->nColumn--; 
103917        }else{
103918          pIndex->aiColumn[i] = x;
103919          pIndex->azColl[i] = pPk->azColl[j];
103920          pIndex->aSortOrder[i] = pPk->aSortOrder[j];
103921          i++;
103922        }
103923      }
103924      assert( i==pIndex->nColumn );
103925    }else{
103926      pIndex->aiColumn[i] = XN_ROWID;
103927      pIndex->azColl[i] = sqlite3StrBINARY;
103928    }
103929    sqlite3DefaultRowEst(pIndex);
103930    if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
103931  
103932    /* If this index contains every column of its table, then mark
103933    ** it as a covering index */
103934    assert( HasRowid(pTab) 
103935        || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
103936    if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
103937      pIndex->isCovering = 1;
103938      for(j=0; j<pTab->nCol; j++){
103939        if( j==pTab->iPKey ) continue;
103940        if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
103941        pIndex->isCovering = 0;
103942        break;
103943      }
103944    }
103945  
103946    if( pTab==pParse->pNewTable ){
103947      /* This routine has been called to create an automatic index as a
103948      ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
103949      ** a PRIMARY KEY or UNIQUE clause following the column definitions.
103950      ** i.e. one of:
103951      **
103952      ** CREATE TABLE t(x PRIMARY KEY, y);
103953      ** CREATE TABLE t(x, y, UNIQUE(x, y));
103954      **
103955      ** Either way, check to see if the table already has such an index. If
103956      ** so, don't bother creating this one. This only applies to
103957      ** automatically created indices. Users can do as they wish with
103958      ** explicit indices.
103959      **
103960      ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
103961      ** (and thus suppressing the second one) even if they have different
103962      ** sort orders.
103963      **
103964      ** If there are different collating sequences or if the columns of
103965      ** the constraint occur in different orders, then the constraints are
103966      ** considered distinct and both result in separate indices.
103967      */
103968      Index *pIdx;
103969      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
103970        int k;
103971        assert( IsUniqueIndex(pIdx) );
103972        assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
103973        assert( IsUniqueIndex(pIndex) );
103974  
103975        if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
103976        for(k=0; k<pIdx->nKeyCol; k++){
103977          const char *z1;
103978          const char *z2;
103979          assert( pIdx->aiColumn[k]>=0 );
103980          if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
103981          z1 = pIdx->azColl[k];
103982          z2 = pIndex->azColl[k];
103983          if( sqlite3StrICmp(z1, z2) ) break;
103984        }
103985        if( k==pIdx->nKeyCol ){
103986          if( pIdx->onError!=pIndex->onError ){
103987            /* This constraint creates the same index as a previous
103988            ** constraint specified somewhere in the CREATE TABLE statement.
103989            ** However the ON CONFLICT clauses are different. If both this 
103990            ** constraint and the previous equivalent constraint have explicit
103991            ** ON CONFLICT clauses this is an error. Otherwise, use the
103992            ** explicitly specified behavior for the index.
103993            */
103994            if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
103995              sqlite3ErrorMsg(pParse, 
103996                  "conflicting ON CONFLICT clauses specified", 0);
103997            }
103998            if( pIdx->onError==OE_Default ){
103999              pIdx->onError = pIndex->onError;
104000            }
104001          }
104002          if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
104003          goto exit_create_index;
104004        }
104005      }
104006    }
104007  
104008    /* Link the new Index structure to its table and to the other
104009    ** in-memory database structures. 
104010    */
104011    assert( pParse->nErr==0 );
104012    if( db->init.busy ){
104013      Index *p;
104014      assert( !IN_DECLARE_VTAB );
104015      assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
104016      p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
104017                            pIndex->zName, pIndex);
104018      if( p ){
104019        assert( p==pIndex );  /* Malloc must have failed */
104020        sqlite3OomFault(db);
104021        goto exit_create_index;
104022      }
104023      db->mDbFlags |= DBFLAG_SchemaChange;
104024      if( pTblName!=0 ){
104025        pIndex->tnum = db->init.newTnum;
104026      }
104027    }
104028  
104029    /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
104030    ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
104031    ** emit code to allocate the index rootpage on disk and make an entry for
104032    ** the index in the sqlite_master table and populate the index with
104033    ** content.  But, do not do this if we are simply reading the sqlite_master
104034    ** table to parse the schema, or if this index is the PRIMARY KEY index
104035    ** of a WITHOUT ROWID table.
104036    **
104037    ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
104038    ** or UNIQUE index in a CREATE TABLE statement.  Since the table
104039    ** has just been created, it contains no data and the index initialization
104040    ** step can be skipped.
104041    */
104042    else if( HasRowid(pTab) || pTblName!=0 ){
104043      Vdbe *v;
104044      char *zStmt;
104045      int iMem = ++pParse->nMem;
104046  
104047      v = sqlite3GetVdbe(pParse);
104048      if( v==0 ) goto exit_create_index;
104049  
104050      sqlite3BeginWriteOperation(pParse, 1, iDb);
104051  
104052      /* Create the rootpage for the index using CreateIndex. But before
104053      ** doing so, code a Noop instruction and store its address in 
104054      ** Index.tnum. This is required in case this index is actually a 
104055      ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In 
104056      ** that case the convertToWithoutRowidTable() routine will replace
104057      ** the Noop with a Goto to jump over the VDBE code generated below. */
104058      pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
104059      sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
104060  
104061      /* Gather the complete text of the CREATE INDEX statement into
104062      ** the zStmt variable
104063      */
104064      if( pStart ){
104065        int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
104066        if( pName->z[n-1]==';' ) n--;
104067        /* A named index with an explicit CREATE INDEX statement */
104068        zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
104069          onError==OE_None ? "" : " UNIQUE", n, pName->z);
104070      }else{
104071        /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
104072        /* zStmt = sqlite3MPrintf(""); */
104073        zStmt = 0;
104074      }
104075  
104076      /* Add an entry in sqlite_master for this index
104077      */
104078      sqlite3NestedParse(pParse, 
104079          "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
104080          db->aDb[iDb].zDbSName, MASTER_NAME,
104081          pIndex->zName,
104082          pTab->zName,
104083          iMem,
104084          zStmt
104085      );
104086      sqlite3DbFree(db, zStmt);
104087  
104088      /* Fill the index with data and reparse the schema. Code an OP_Expire
104089      ** to invalidate all pre-compiled statements.
104090      */
104091      if( pTblName ){
104092        sqlite3RefillIndex(pParse, pIndex, iMem);
104093        sqlite3ChangeCookie(pParse, iDb);
104094        sqlite3VdbeAddParseSchemaOp(v, iDb,
104095           sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
104096        sqlite3VdbeAddOp0(v, OP_Expire);
104097      }
104098  
104099      sqlite3VdbeJumpHere(v, pIndex->tnum);
104100    }
104101  
104102    /* When adding an index to the list of indices for a table, make
104103    ** sure all indices labeled OE_Replace come after all those labeled
104104    ** OE_Ignore.  This is necessary for the correct constraint check
104105    ** processing (in sqlite3GenerateConstraintChecks()) as part of
104106    ** UPDATE and INSERT statements.  
104107    */
104108    if( db->init.busy || pTblName==0 ){
104109      if( onError!=OE_Replace || pTab->pIndex==0
104110           || pTab->pIndex->onError==OE_Replace){
104111        pIndex->pNext = pTab->pIndex;
104112        pTab->pIndex = pIndex;
104113      }else{
104114        Index *pOther = pTab->pIndex;
104115        while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
104116          pOther = pOther->pNext;
104117        }
104118        pIndex->pNext = pOther->pNext;
104119        pOther->pNext = pIndex;
104120      }
104121      pIndex = 0;
104122    }
104123  
104124    /* Clean up before exiting */
104125  exit_create_index:
104126    if( pIndex ) freeIndex(db, pIndex);
104127    sqlite3ExprDelete(db, pPIWhere);
104128    sqlite3ExprListDelete(db, pList);
104129    sqlite3SrcListDelete(db, pTblName);
104130    sqlite3DbFree(db, zName);
104131  }
104132  
104133  /*
104134  ** Fill the Index.aiRowEst[] array with default information - information
104135  ** to be used when we have not run the ANALYZE command.
104136  **
104137  ** aiRowEst[0] is supposed to contain the number of elements in the index.
104138  ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
104139  ** number of rows in the table that match any particular value of the
104140  ** first column of the index.  aiRowEst[2] is an estimate of the number
104141  ** of rows that match any particular combination of the first 2 columns
104142  ** of the index.  And so forth.  It must always be the case that
104143  *
104144  **           aiRowEst[N]<=aiRowEst[N-1]
104145  **           aiRowEst[N]>=1
104146  **
104147  ** Apart from that, we have little to go on besides intuition as to
104148  ** how aiRowEst[] should be initialized.  The numbers generated here
104149  ** are based on typical values found in actual indices.
104150  */
104151  SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
104152    /*                10,  9,  8,  7,  6 */
104153    LogEst aVal[] = { 33, 32, 30, 28, 26 };
104154    LogEst *a = pIdx->aiRowLogEst;
104155    int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
104156    int i;
104157  
104158    /* Indexes with default row estimates should not have stat1 data */
104159    assert( !pIdx->hasStat1 );
104160  
104161    /* Set the first entry (number of rows in the index) to the estimated 
104162    ** number of rows in the table, or half the number of rows in the table
104163    ** for a partial index.   But do not let the estimate drop below 10. */
104164    a[0] = pIdx->pTable->nRowLogEst;
104165    if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10;  assert( 10==sqlite3LogEst(2) );
104166    if( a[0]<33 ) a[0] = 33;                  assert( 33==sqlite3LogEst(10) );
104167  
104168    /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
104169    ** 6 and each subsequent value (if any) is 5.  */
104170    memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
104171    for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
104172      a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
104173    }
104174  
104175    assert( 0==sqlite3LogEst(1) );
104176    if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
104177  }
104178  
104179  /*
104180  ** This routine will drop an existing named index.  This routine
104181  ** implements the DROP INDEX statement.
104182  */
104183  SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
104184    Index *pIndex;
104185    Vdbe *v;
104186    sqlite3 *db = pParse->db;
104187    int iDb;
104188  
104189    assert( pParse->nErr==0 );   /* Never called with prior errors */
104190    if( db->mallocFailed ){
104191      goto exit_drop_index;
104192    }
104193    assert( pName->nSrc==1 );
104194    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
104195      goto exit_drop_index;
104196    }
104197    pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
104198    if( pIndex==0 ){
104199      if( !ifExists ){
104200        sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
104201      }else{
104202        sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
104203      }
104204      pParse->checkSchema = 1;
104205      goto exit_drop_index;
104206    }
104207    if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
104208      sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
104209        "or PRIMARY KEY constraint cannot be dropped", 0);
104210      goto exit_drop_index;
104211    }
104212    iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
104213  #ifndef SQLITE_OMIT_AUTHORIZATION
104214    {
104215      int code = SQLITE_DROP_INDEX;
104216      Table *pTab = pIndex->pTable;
104217      const char *zDb = db->aDb[iDb].zDbSName;
104218      const char *zTab = SCHEMA_TABLE(iDb);
104219      if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
104220        goto exit_drop_index;
104221      }
104222      if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
104223      if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
104224        goto exit_drop_index;
104225      }
104226    }
104227  #endif
104228  
104229    /* Generate code to remove the index and from the master table */
104230    v = sqlite3GetVdbe(pParse);
104231    if( v ){
104232      sqlite3BeginWriteOperation(pParse, 1, iDb);
104233      sqlite3NestedParse(pParse,
104234         "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
104235         db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
104236      );
104237      sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
104238      sqlite3ChangeCookie(pParse, iDb);
104239      destroyRootPage(pParse, pIndex->tnum, iDb);
104240      sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
104241    }
104242  
104243  exit_drop_index:
104244    sqlite3SrcListDelete(db, pName);
104245  }
104246  
104247  /*
104248  ** pArray is a pointer to an array of objects. Each object in the
104249  ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
104250  ** to extend the array so that there is space for a new object at the end.
104251  **
104252  ** When this function is called, *pnEntry contains the current size of
104253  ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
104254  ** in total).
104255  **
104256  ** If the realloc() is successful (i.e. if no OOM condition occurs), the
104257  ** space allocated for the new object is zeroed, *pnEntry updated to
104258  ** reflect the new size of the array and a pointer to the new allocation
104259  ** returned. *pIdx is set to the index of the new array entry in this case.
104260  **
104261  ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
104262  ** unchanged and a copy of pArray returned.
104263  */
104264  SQLITE_PRIVATE void *sqlite3ArrayAllocate(
104265    sqlite3 *db,      /* Connection to notify of malloc failures */
104266    void *pArray,     /* Array of objects.  Might be reallocated */
104267    int szEntry,      /* Size of each object in the array */
104268    int *pnEntry,     /* Number of objects currently in use */
104269    int *pIdx         /* Write the index of a new slot here */
104270  ){
104271    char *z;
104272    int n = *pnEntry;
104273    if( (n & (n-1))==0 ){
104274      int sz = (n==0) ? 1 : 2*n;
104275      void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
104276      if( pNew==0 ){
104277        *pIdx = -1;
104278        return pArray;
104279      }
104280      pArray = pNew;
104281    }
104282    z = (char*)pArray;
104283    memset(&z[n * szEntry], 0, szEntry);
104284    *pIdx = n;
104285    ++*pnEntry;
104286    return pArray;
104287  }
104288  
104289  /*
104290  ** Append a new element to the given IdList.  Create a new IdList if
104291  ** need be.
104292  **
104293  ** A new IdList is returned, or NULL if malloc() fails.
104294  */
104295  SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
104296    int i;
104297    if( pList==0 ){
104298      pList = sqlite3DbMallocZero(db, sizeof(IdList) );
104299      if( pList==0 ) return 0;
104300    }
104301    pList->a = sqlite3ArrayAllocate(
104302        db,
104303        pList->a,
104304        sizeof(pList->a[0]),
104305        &pList->nId,
104306        &i
104307    );
104308    if( i<0 ){
104309      sqlite3IdListDelete(db, pList);
104310      return 0;
104311    }
104312    pList->a[i].zName = sqlite3NameFromToken(db, pToken);
104313    return pList;
104314  }
104315  
104316  /*
104317  ** Delete an IdList.
104318  */
104319  SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
104320    int i;
104321    if( pList==0 ) return;
104322    for(i=0; i<pList->nId; i++){
104323      sqlite3DbFree(db, pList->a[i].zName);
104324    }
104325    sqlite3DbFree(db, pList->a);
104326    sqlite3DbFreeNN(db, pList);
104327  }
104328  
104329  /*
104330  ** Return the index in pList of the identifier named zId.  Return -1
104331  ** if not found.
104332  */
104333  SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
104334    int i;
104335    if( pList==0 ) return -1;
104336    for(i=0; i<pList->nId; i++){
104337      if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
104338    }
104339    return -1;
104340  }
104341  
104342  /*
104343  ** Expand the space allocated for the given SrcList object by
104344  ** creating nExtra new slots beginning at iStart.  iStart is zero based.
104345  ** New slots are zeroed.
104346  **
104347  ** For example, suppose a SrcList initially contains two entries: A,B.
104348  ** To append 3 new entries onto the end, do this:
104349  **
104350  **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
104351  **
104352  ** After the call above it would contain:  A, B, nil, nil, nil.
104353  ** If the iStart argument had been 1 instead of 2, then the result
104354  ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
104355  ** the iStart value would be 0.  The result then would
104356  ** be: nil, nil, nil, A, B.
104357  **
104358  ** If a memory allocation fails the SrcList is unchanged.  The
104359  ** db->mallocFailed flag will be set to true.
104360  */
104361  SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
104362    sqlite3 *db,       /* Database connection to notify of OOM errors */
104363    SrcList *pSrc,     /* The SrcList to be enlarged */
104364    int nExtra,        /* Number of new slots to add to pSrc->a[] */
104365    int iStart         /* Index in pSrc->a[] of first new slot */
104366  ){
104367    int i;
104368  
104369    /* Sanity checking on calling parameters */
104370    assert( iStart>=0 );
104371    assert( nExtra>=1 );
104372    assert( pSrc!=0 );
104373    assert( iStart<=pSrc->nSrc );
104374  
104375    /* Allocate additional space if needed */
104376    if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
104377      SrcList *pNew;
104378      int nAlloc = pSrc->nSrc*2+nExtra;
104379      int nGot;
104380      pNew = sqlite3DbRealloc(db, pSrc,
104381                 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
104382      if( pNew==0 ){
104383        assert( db->mallocFailed );
104384        return pSrc;
104385      }
104386      pSrc = pNew;
104387      nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
104388      pSrc->nAlloc = nGot;
104389    }
104390  
104391    /* Move existing slots that come after the newly inserted slots
104392    ** out of the way */
104393    for(i=pSrc->nSrc-1; i>=iStart; i--){
104394      pSrc->a[i+nExtra] = pSrc->a[i];
104395    }
104396    pSrc->nSrc += nExtra;
104397  
104398    /* Zero the newly allocated slots */
104399    memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
104400    for(i=iStart; i<iStart+nExtra; i++){
104401      pSrc->a[i].iCursor = -1;
104402    }
104403  
104404    /* Return a pointer to the enlarged SrcList */
104405    return pSrc;
104406  }
104407  
104408  
104409  /*
104410  ** Append a new table name to the given SrcList.  Create a new SrcList if
104411  ** need be.  A new entry is created in the SrcList even if pTable is NULL.
104412  **
104413  ** A SrcList is returned, or NULL if there is an OOM error.  The returned
104414  ** SrcList might be the same as the SrcList that was input or it might be
104415  ** a new one.  If an OOM error does occurs, then the prior value of pList
104416  ** that is input to this routine is automatically freed.
104417  **
104418  ** If pDatabase is not null, it means that the table has an optional
104419  ** database name prefix.  Like this:  "database.table".  The pDatabase
104420  ** points to the table name and the pTable points to the database name.
104421  ** The SrcList.a[].zName field is filled with the table name which might
104422  ** come from pTable (if pDatabase is NULL) or from pDatabase.  
104423  ** SrcList.a[].zDatabase is filled with the database name from pTable,
104424  ** or with NULL if no database is specified.
104425  **
104426  ** In other words, if call like this:
104427  **
104428  **         sqlite3SrcListAppend(D,A,B,0);
104429  **
104430  ** Then B is a table name and the database name is unspecified.  If called
104431  ** like this:
104432  **
104433  **         sqlite3SrcListAppend(D,A,B,C);
104434  **
104435  ** Then C is the table name and B is the database name.  If C is defined
104436  ** then so is B.  In other words, we never have a case where:
104437  **
104438  **         sqlite3SrcListAppend(D,A,0,C);
104439  **
104440  ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
104441  ** before being added to the SrcList.
104442  */
104443  SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
104444    sqlite3 *db,        /* Connection to notify of malloc failures */
104445    SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
104446    Token *pTable,      /* Table to append */
104447    Token *pDatabase    /* Database of the table */
104448  ){
104449    struct SrcList_item *pItem;
104450    assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
104451    assert( db!=0 );
104452    if( pList==0 ){
104453      pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) );
104454      if( pList==0 ) return 0;
104455      pList->nAlloc = 1;
104456      pList->nSrc = 1;
104457      memset(&pList->a[0], 0, sizeof(pList->a[0]));
104458      pList->a[0].iCursor = -1;
104459    }else{
104460      pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
104461    }
104462    if( db->mallocFailed ){
104463      sqlite3SrcListDelete(db, pList);
104464      return 0;
104465    }
104466    pItem = &pList->a[pList->nSrc-1];
104467    if( pDatabase && pDatabase->z==0 ){
104468      pDatabase = 0;
104469    }
104470    if( pDatabase ){
104471      pItem->zName = sqlite3NameFromToken(db, pDatabase);
104472      pItem->zDatabase = sqlite3NameFromToken(db, pTable);
104473    }else{
104474      pItem->zName = sqlite3NameFromToken(db, pTable);
104475      pItem->zDatabase = 0;
104476    }
104477    return pList;
104478  }
104479  
104480  /*
104481  ** Assign VdbeCursor index numbers to all tables in a SrcList
104482  */
104483  SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
104484    int i;
104485    struct SrcList_item *pItem;
104486    assert(pList || pParse->db->mallocFailed );
104487    if( pList ){
104488      for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
104489        if( pItem->iCursor>=0 ) break;
104490        pItem->iCursor = pParse->nTab++;
104491        if( pItem->pSelect ){
104492          sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
104493        }
104494      }
104495    }
104496  }
104497  
104498  /*
104499  ** Delete an entire SrcList including all its substructure.
104500  */
104501  SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
104502    int i;
104503    struct SrcList_item *pItem;
104504    if( pList==0 ) return;
104505    for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
104506      sqlite3DbFree(db, pItem->zDatabase);
104507      sqlite3DbFree(db, pItem->zName);
104508      sqlite3DbFree(db, pItem->zAlias);
104509      if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
104510      if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
104511      sqlite3DeleteTable(db, pItem->pTab);
104512      sqlite3SelectDelete(db, pItem->pSelect);
104513      sqlite3ExprDelete(db, pItem->pOn);
104514      sqlite3IdListDelete(db, pItem->pUsing);
104515    }
104516    sqlite3DbFreeNN(db, pList);
104517  }
104518  
104519  /*
104520  ** This routine is called by the parser to add a new term to the
104521  ** end of a growing FROM clause.  The "p" parameter is the part of
104522  ** the FROM clause that has already been constructed.  "p" is NULL
104523  ** if this is the first term of the FROM clause.  pTable and pDatabase
104524  ** are the name of the table and database named in the FROM clause term.
104525  ** pDatabase is NULL if the database name qualifier is missing - the
104526  ** usual case.  If the term has an alias, then pAlias points to the
104527  ** alias token.  If the term is a subquery, then pSubquery is the
104528  ** SELECT statement that the subquery encodes.  The pTable and
104529  ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
104530  ** parameters are the content of the ON and USING clauses.
104531  **
104532  ** Return a new SrcList which encodes is the FROM with the new
104533  ** term added.
104534  */
104535  SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
104536    Parse *pParse,          /* Parsing context */
104537    SrcList *p,             /* The left part of the FROM clause already seen */
104538    Token *pTable,          /* Name of the table to add to the FROM clause */
104539    Token *pDatabase,       /* Name of the database containing pTable */
104540    Token *pAlias,          /* The right-hand side of the AS subexpression */
104541    Select *pSubquery,      /* A subquery used in place of a table name */
104542    Expr *pOn,              /* The ON clause of a join */
104543    IdList *pUsing          /* The USING clause of a join */
104544  ){
104545    struct SrcList_item *pItem;
104546    sqlite3 *db = pParse->db;
104547    if( !p && (pOn || pUsing) ){
104548      sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
104549        (pOn ? "ON" : "USING")
104550      );
104551      goto append_from_error;
104552    }
104553    p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
104554    if( p==0 || NEVER(p->nSrc==0) ){
104555      goto append_from_error;
104556    }
104557    pItem = &p->a[p->nSrc-1];
104558    assert( pAlias!=0 );
104559    if( pAlias->n ){
104560      pItem->zAlias = sqlite3NameFromToken(db, pAlias);
104561    }
104562    pItem->pSelect = pSubquery;
104563    pItem->pOn = pOn;
104564    pItem->pUsing = pUsing;
104565    return p;
104566  
104567   append_from_error:
104568    assert( p==0 );
104569    sqlite3ExprDelete(db, pOn);
104570    sqlite3IdListDelete(db, pUsing);
104571    sqlite3SelectDelete(db, pSubquery);
104572    return 0;
104573  }
104574  
104575  /*
104576  ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
104577  ** element of the source-list passed as the second argument.
104578  */
104579  SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
104580    assert( pIndexedBy!=0 );
104581    if( p && pIndexedBy->n>0 ){
104582      struct SrcList_item *pItem;
104583      assert( p->nSrc>0 );
104584      pItem = &p->a[p->nSrc-1];
104585      assert( pItem->fg.notIndexed==0 );
104586      assert( pItem->fg.isIndexedBy==0 );
104587      assert( pItem->fg.isTabFunc==0 );
104588      if( pIndexedBy->n==1 && !pIndexedBy->z ){
104589        /* A "NOT INDEXED" clause was supplied. See parse.y 
104590        ** construct "indexed_opt" for details. */
104591        pItem->fg.notIndexed = 1;
104592      }else{
104593        pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
104594        pItem->fg.isIndexedBy = 1;
104595      }
104596    }
104597  }
104598  
104599  /*
104600  ** Add the list of function arguments to the SrcList entry for a
104601  ** table-valued-function.
104602  */
104603  SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
104604    if( p ){
104605      struct SrcList_item *pItem = &p->a[p->nSrc-1];
104606      assert( pItem->fg.notIndexed==0 );
104607      assert( pItem->fg.isIndexedBy==0 );
104608      assert( pItem->fg.isTabFunc==0 );
104609      pItem->u1.pFuncArg = pList;
104610      pItem->fg.isTabFunc = 1;
104611    }else{
104612      sqlite3ExprListDelete(pParse->db, pList);
104613    }
104614  }
104615  
104616  /*
104617  ** When building up a FROM clause in the parser, the join operator
104618  ** is initially attached to the left operand.  But the code generator
104619  ** expects the join operator to be on the right operand.  This routine
104620  ** Shifts all join operators from left to right for an entire FROM
104621  ** clause.
104622  **
104623  ** Example: Suppose the join is like this:
104624  **
104625  **           A natural cross join B
104626  **
104627  ** The operator is "natural cross join".  The A and B operands are stored
104628  ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
104629  ** operator with A.  This routine shifts that operator over to B.
104630  */
104631  SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
104632    if( p ){
104633      int i;
104634      for(i=p->nSrc-1; i>0; i--){
104635        p->a[i].fg.jointype = p->a[i-1].fg.jointype;
104636      }
104637      p->a[0].fg.jointype = 0;
104638    }
104639  }
104640  
104641  /*
104642  ** Generate VDBE code for a BEGIN statement.
104643  */
104644  SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
104645    sqlite3 *db;
104646    Vdbe *v;
104647    int i;
104648  
104649    assert( pParse!=0 );
104650    db = pParse->db;
104651    assert( db!=0 );
104652    if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
104653      return;
104654    }
104655    v = sqlite3GetVdbe(pParse);
104656    if( !v ) return;
104657    if( type!=TK_DEFERRED ){
104658      for(i=0; i<db->nDb; i++){
104659        sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
104660        sqlite3VdbeUsesBtree(v, i);
104661      }
104662    }
104663    sqlite3VdbeAddOp0(v, OP_AutoCommit);
104664  }
104665  
104666  /*
104667  ** Generate VDBE code for a COMMIT or ROLLBACK statement.
104668  ** Code for ROLLBACK is generated if eType==TK_ROLLBACK.  Otherwise
104669  ** code is generated for a COMMIT.
104670  */
104671  SQLITE_PRIVATE void sqlite3EndTransaction(Parse *pParse, int eType){
104672    Vdbe *v;
104673    int isRollback;
104674  
104675    assert( pParse!=0 );
104676    assert( pParse->db!=0 );
104677    assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
104678    isRollback = eType==TK_ROLLBACK;
104679    if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, 
104680         isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
104681      return;
104682    }
104683    v = sqlite3GetVdbe(pParse);
104684    if( v ){
104685      sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
104686    }
104687  }
104688  
104689  /*
104690  ** This function is called by the parser when it parses a command to create,
104691  ** release or rollback an SQL savepoint. 
104692  */
104693  SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
104694    char *zName = sqlite3NameFromToken(pParse->db, pName);
104695    if( zName ){
104696      Vdbe *v = sqlite3GetVdbe(pParse);
104697  #ifndef SQLITE_OMIT_AUTHORIZATION
104698      static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
104699      assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
104700  #endif
104701      if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
104702        sqlite3DbFree(pParse->db, zName);
104703        return;
104704      }
104705      sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
104706    }
104707  }
104708  
104709  /*
104710  ** Make sure the TEMP database is open and available for use.  Return
104711  ** the number of errors.  Leave any error messages in the pParse structure.
104712  */
104713  SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
104714    sqlite3 *db = pParse->db;
104715    if( db->aDb[1].pBt==0 && !pParse->explain ){
104716      int rc;
104717      Btree *pBt;
104718      static const int flags = 
104719            SQLITE_OPEN_READWRITE |
104720            SQLITE_OPEN_CREATE |
104721            SQLITE_OPEN_EXCLUSIVE |
104722            SQLITE_OPEN_DELETEONCLOSE |
104723            SQLITE_OPEN_TEMP_DB;
104724  
104725      rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
104726      if( rc!=SQLITE_OK ){
104727        sqlite3ErrorMsg(pParse, "unable to open a temporary database "
104728          "file for storing temporary tables");
104729        pParse->rc = rc;
104730        return 1;
104731      }
104732      db->aDb[1].pBt = pBt;
104733      assert( db->aDb[1].pSchema );
104734      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
104735        sqlite3OomFault(db);
104736        return 1;
104737      }
104738    }
104739    return 0;
104740  }
104741  
104742  /*
104743  ** Record the fact that the schema cookie will need to be verified
104744  ** for database iDb.  The code to actually verify the schema cookie
104745  ** will occur at the end of the top-level VDBE and will be generated
104746  ** later, by sqlite3FinishCoding().
104747  */
104748  SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
104749    Parse *pToplevel = sqlite3ParseToplevel(pParse);
104750  
104751    assert( iDb>=0 && iDb<pParse->db->nDb );
104752    assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
104753    assert( iDb<SQLITE_MAX_ATTACHED+2 );
104754    assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
104755    if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
104756      DbMaskSet(pToplevel->cookieMask, iDb);
104757      if( !OMIT_TEMPDB && iDb==1 ){
104758        sqlite3OpenTempDatabase(pToplevel);
104759      }
104760    }
104761  }
104762  
104763  /*
104764  ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 
104765  ** attached database. Otherwise, invoke it for the database named zDb only.
104766  */
104767  SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
104768    sqlite3 *db = pParse->db;
104769    int i;
104770    for(i=0; i<db->nDb; i++){
104771      Db *pDb = &db->aDb[i];
104772      if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
104773        sqlite3CodeVerifySchema(pParse, i);
104774      }
104775    }
104776  }
104777  
104778  /*
104779  ** Generate VDBE code that prepares for doing an operation that
104780  ** might change the database.
104781  **
104782  ** This routine starts a new transaction if we are not already within
104783  ** a transaction.  If we are already within a transaction, then a checkpoint
104784  ** is set if the setStatement parameter is true.  A checkpoint should
104785  ** be set for operations that might fail (due to a constraint) part of
104786  ** the way through and which will need to undo some writes without having to
104787  ** rollback the whole transaction.  For operations where all constraints
104788  ** can be checked before any changes are made to the database, it is never
104789  ** necessary to undo a write and the checkpoint should not be set.
104790  */
104791  SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
104792    Parse *pToplevel = sqlite3ParseToplevel(pParse);
104793    sqlite3CodeVerifySchema(pParse, iDb);
104794    DbMaskSet(pToplevel->writeMask, iDb);
104795    pToplevel->isMultiWrite |= setStatement;
104796  }
104797  
104798  /*
104799  ** Indicate that the statement currently under construction might write
104800  ** more than one entry (example: deleting one row then inserting another,
104801  ** inserting multiple rows in a table, or inserting a row and index entries.)
104802  ** If an abort occurs after some of these writes have completed, then it will
104803  ** be necessary to undo the completed writes.
104804  */
104805  SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
104806    Parse *pToplevel = sqlite3ParseToplevel(pParse);
104807    pToplevel->isMultiWrite = 1;
104808  }
104809  
104810  /* 
104811  ** The code generator calls this routine if is discovers that it is
104812  ** possible to abort a statement prior to completion.  In order to 
104813  ** perform this abort without corrupting the database, we need to make
104814  ** sure that the statement is protected by a statement transaction.
104815  **
104816  ** Technically, we only need to set the mayAbort flag if the
104817  ** isMultiWrite flag was previously set.  There is a time dependency
104818  ** such that the abort must occur after the multiwrite.  This makes
104819  ** some statements involving the REPLACE conflict resolution algorithm
104820  ** go a little faster.  But taking advantage of this time dependency
104821  ** makes it more difficult to prove that the code is correct (in 
104822  ** particular, it prevents us from writing an effective
104823  ** implementation of sqlite3AssertMayAbort()) and so we have chosen
104824  ** to take the safe route and skip the optimization.
104825  */
104826  SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
104827    Parse *pToplevel = sqlite3ParseToplevel(pParse);
104828    pToplevel->mayAbort = 1;
104829  }
104830  
104831  /*
104832  ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
104833  ** error. The onError parameter determines which (if any) of the statement
104834  ** and/or current transaction is rolled back.
104835  */
104836  SQLITE_PRIVATE void sqlite3HaltConstraint(
104837    Parse *pParse,    /* Parsing context */
104838    int errCode,      /* extended error code */
104839    int onError,      /* Constraint type */
104840    char *p4,         /* Error message */
104841    i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
104842    u8 p5Errmsg       /* P5_ErrMsg type */
104843  ){
104844    Vdbe *v = sqlite3GetVdbe(pParse);
104845    assert( (errCode&0xff)==SQLITE_CONSTRAINT );
104846    if( onError==OE_Abort ){
104847      sqlite3MayAbort(pParse);
104848    }
104849    sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
104850    sqlite3VdbeChangeP5(v, p5Errmsg);
104851  }
104852  
104853  /*
104854  ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
104855  */
104856  SQLITE_PRIVATE void sqlite3UniqueConstraint(
104857    Parse *pParse,    /* Parsing context */
104858    int onError,      /* Constraint type */
104859    Index *pIdx       /* The index that triggers the constraint */
104860  ){
104861    char *zErr;
104862    int j;
104863    StrAccum errMsg;
104864    Table *pTab = pIdx->pTable;
104865  
104866    sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
104867    if( pIdx->aColExpr ){
104868      sqlite3XPrintf(&errMsg, "index '%q'", pIdx->zName);
104869    }else{
104870      for(j=0; j<pIdx->nKeyCol; j++){
104871        char *zCol;
104872        assert( pIdx->aiColumn[j]>=0 );
104873        zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
104874        if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
104875        sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
104876        sqlite3StrAccumAppend(&errMsg, ".", 1);
104877        sqlite3StrAccumAppendAll(&errMsg, zCol);
104878      }
104879    }
104880    zErr = sqlite3StrAccumFinish(&errMsg);
104881    sqlite3HaltConstraint(pParse, 
104882      IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY 
104883                              : SQLITE_CONSTRAINT_UNIQUE,
104884      onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
104885  }
104886  
104887  
104888  /*
104889  ** Code an OP_Halt due to non-unique rowid.
104890  */
104891  SQLITE_PRIVATE void sqlite3RowidConstraint(
104892    Parse *pParse,    /* Parsing context */
104893    int onError,      /* Conflict resolution algorithm */
104894    Table *pTab       /* The table with the non-unique rowid */ 
104895  ){
104896    char *zMsg;
104897    int rc;
104898    if( pTab->iPKey>=0 ){
104899      zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
104900                            pTab->aCol[pTab->iPKey].zName);
104901      rc = SQLITE_CONSTRAINT_PRIMARYKEY;
104902    }else{
104903      zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
104904      rc = SQLITE_CONSTRAINT_ROWID;
104905    }
104906    sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
104907                          P5_ConstraintUnique);
104908  }
104909  
104910  /*
104911  ** Check to see if pIndex uses the collating sequence pColl.  Return
104912  ** true if it does and false if it does not.
104913  */
104914  #ifndef SQLITE_OMIT_REINDEX
104915  static int collationMatch(const char *zColl, Index *pIndex){
104916    int i;
104917    assert( zColl!=0 );
104918    for(i=0; i<pIndex->nColumn; i++){
104919      const char *z = pIndex->azColl[i];
104920      assert( z!=0 || pIndex->aiColumn[i]<0 );
104921      if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
104922        return 1;
104923      }
104924    }
104925    return 0;
104926  }
104927  #endif
104928  
104929  /*
104930  ** Recompute all indices of pTab that use the collating sequence pColl.
104931  ** If pColl==0 then recompute all indices of pTab.
104932  */
104933  #ifndef SQLITE_OMIT_REINDEX
104934  static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
104935    Index *pIndex;              /* An index associated with pTab */
104936  
104937    for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
104938      if( zColl==0 || collationMatch(zColl, pIndex) ){
104939        int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
104940        sqlite3BeginWriteOperation(pParse, 0, iDb);
104941        sqlite3RefillIndex(pParse, pIndex, -1);
104942      }
104943    }
104944  }
104945  #endif
104946  
104947  /*
104948  ** Recompute all indices of all tables in all databases where the
104949  ** indices use the collating sequence pColl.  If pColl==0 then recompute
104950  ** all indices everywhere.
104951  */
104952  #ifndef SQLITE_OMIT_REINDEX
104953  static void reindexDatabases(Parse *pParse, char const *zColl){
104954    Db *pDb;                    /* A single database */
104955    int iDb;                    /* The database index number */
104956    sqlite3 *db = pParse->db;   /* The database connection */
104957    HashElem *k;                /* For looping over tables in pDb */
104958    Table *pTab;                /* A table in the database */
104959  
104960    assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
104961    for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
104962      assert( pDb!=0 );
104963      for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
104964        pTab = (Table*)sqliteHashData(k);
104965        reindexTable(pParse, pTab, zColl);
104966      }
104967    }
104968  }
104969  #endif
104970  
104971  /*
104972  ** Generate code for the REINDEX command.
104973  **
104974  **        REINDEX                            -- 1
104975  **        REINDEX  <collation>               -- 2
104976  **        REINDEX  ?<database>.?<tablename>  -- 3
104977  **        REINDEX  ?<database>.?<indexname>  -- 4
104978  **
104979  ** Form 1 causes all indices in all attached databases to be rebuilt.
104980  ** Form 2 rebuilds all indices in all databases that use the named
104981  ** collating function.  Forms 3 and 4 rebuild the named index or all
104982  ** indices associated with the named table.
104983  */
104984  #ifndef SQLITE_OMIT_REINDEX
104985  SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
104986    CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
104987    char *z;                    /* Name of a table or index */
104988    const char *zDb;            /* Name of the database */
104989    Table *pTab;                /* A table in the database */
104990    Index *pIndex;              /* An index associated with pTab */
104991    int iDb;                    /* The database index number */
104992    sqlite3 *db = pParse->db;   /* The database connection */
104993    Token *pObjName;            /* Name of the table or index to be reindexed */
104994  
104995    /* Read the database schema. If an error occurs, leave an error message
104996    ** and code in pParse and return NULL. */
104997    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
104998      return;
104999    }
105000  
105001    if( pName1==0 ){
105002      reindexDatabases(pParse, 0);
105003      return;
105004    }else if( NEVER(pName2==0) || pName2->z==0 ){
105005      char *zColl;
105006      assert( pName1->z );
105007      zColl = sqlite3NameFromToken(pParse->db, pName1);
105008      if( !zColl ) return;
105009      pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
105010      if( pColl ){
105011        reindexDatabases(pParse, zColl);
105012        sqlite3DbFree(db, zColl);
105013        return;
105014      }
105015      sqlite3DbFree(db, zColl);
105016    }
105017    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
105018    if( iDb<0 ) return;
105019    z = sqlite3NameFromToken(db, pObjName);
105020    if( z==0 ) return;
105021    zDb = db->aDb[iDb].zDbSName;
105022    pTab = sqlite3FindTable(db, z, zDb);
105023    if( pTab ){
105024      reindexTable(pParse, pTab, 0);
105025      sqlite3DbFree(db, z);
105026      return;
105027    }
105028    pIndex = sqlite3FindIndex(db, z, zDb);
105029    sqlite3DbFree(db, z);
105030    if( pIndex ){
105031      sqlite3BeginWriteOperation(pParse, 0, iDb);
105032      sqlite3RefillIndex(pParse, pIndex, -1);
105033      return;
105034    }
105035    sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
105036  }
105037  #endif
105038  
105039  /*
105040  ** Return a KeyInfo structure that is appropriate for the given Index.
105041  **
105042  ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
105043  ** when it has finished using it.
105044  */
105045  SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
105046    int i;
105047    int nCol = pIdx->nColumn;
105048    int nKey = pIdx->nKeyCol;
105049    KeyInfo *pKey;
105050    if( pParse->nErr ) return 0;
105051    if( pIdx->uniqNotNull ){
105052      pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
105053    }else{
105054      pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
105055    }
105056    if( pKey ){
105057      assert( sqlite3KeyInfoIsWriteable(pKey) );
105058      for(i=0; i<nCol; i++){
105059        const char *zColl = pIdx->azColl[i];
105060        pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
105061                          sqlite3LocateCollSeq(pParse, zColl);
105062        pKey->aSortOrder[i] = pIdx->aSortOrder[i];
105063      }
105064      if( pParse->nErr ){
105065        sqlite3KeyInfoUnref(pKey);
105066        pKey = 0;
105067      }
105068    }
105069    return pKey;
105070  }
105071  
105072  #ifndef SQLITE_OMIT_CTE
105073  /* 
105074  ** This routine is invoked once per CTE by the parser while parsing a 
105075  ** WITH clause. 
105076  */
105077  SQLITE_PRIVATE With *sqlite3WithAdd(
105078    Parse *pParse,          /* Parsing context */
105079    With *pWith,            /* Existing WITH clause, or NULL */
105080    Token *pName,           /* Name of the common-table */
105081    ExprList *pArglist,     /* Optional column name list for the table */
105082    Select *pQuery          /* Query used to initialize the table */
105083  ){
105084    sqlite3 *db = pParse->db;
105085    With *pNew;
105086    char *zName;
105087  
105088    /* Check that the CTE name is unique within this WITH clause. If
105089    ** not, store an error in the Parse structure. */
105090    zName = sqlite3NameFromToken(pParse->db, pName);
105091    if( zName && pWith ){
105092      int i;
105093      for(i=0; i<pWith->nCte; i++){
105094        if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
105095          sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
105096        }
105097      }
105098    }
105099  
105100    if( pWith ){
105101      int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
105102      pNew = sqlite3DbRealloc(db, pWith, nByte);
105103    }else{
105104      pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
105105    }
105106    assert( (pNew!=0 && zName!=0) || db->mallocFailed );
105107  
105108    if( db->mallocFailed ){
105109      sqlite3ExprListDelete(db, pArglist);
105110      sqlite3SelectDelete(db, pQuery);
105111      sqlite3DbFree(db, zName);
105112      pNew = pWith;
105113    }else{
105114      pNew->a[pNew->nCte].pSelect = pQuery;
105115      pNew->a[pNew->nCte].pCols = pArglist;
105116      pNew->a[pNew->nCte].zName = zName;
105117      pNew->a[pNew->nCte].zCteErr = 0;
105118      pNew->nCte++;
105119    }
105120  
105121    return pNew;
105122  }
105123  
105124  /*
105125  ** Free the contents of the With object passed as the second argument.
105126  */
105127  SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
105128    if( pWith ){
105129      int i;
105130      for(i=0; i<pWith->nCte; i++){
105131        struct Cte *pCte = &pWith->a[i];
105132        sqlite3ExprListDelete(db, pCte->pCols);
105133        sqlite3SelectDelete(db, pCte->pSelect);
105134        sqlite3DbFree(db, pCte->zName);
105135      }
105136      sqlite3DbFree(db, pWith);
105137    }
105138  }
105139  #endif /* !defined(SQLITE_OMIT_CTE) */
105140  
105141  /************** End of build.c ***********************************************/
105142  /************** Begin file callback.c ****************************************/
105143  /*
105144  ** 2005 May 23 
105145  **
105146  ** The author disclaims copyright to this source code.  In place of
105147  ** a legal notice, here is a blessing:
105148  **
105149  **    May you do good and not evil.
105150  **    May you find forgiveness for yourself and forgive others.
105151  **    May you share freely, never taking more than you give.
105152  **
105153  *************************************************************************
105154  **
105155  ** This file contains functions used to access the internal hash tables
105156  ** of user defined functions and collation sequences.
105157  */
105158  
105159  /* #include "sqliteInt.h" */
105160  
105161  /*
105162  ** Invoke the 'collation needed' callback to request a collation sequence
105163  ** in the encoding enc of name zName, length nName.
105164  */
105165  static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
105166    assert( !db->xCollNeeded || !db->xCollNeeded16 );
105167    if( db->xCollNeeded ){
105168      char *zExternal = sqlite3DbStrDup(db, zName);
105169      if( !zExternal ) return;
105170      db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
105171      sqlite3DbFree(db, zExternal);
105172    }
105173  #ifndef SQLITE_OMIT_UTF16
105174    if( db->xCollNeeded16 ){
105175      char const *zExternal;
105176      sqlite3_value *pTmp = sqlite3ValueNew(db);
105177      sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
105178      zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
105179      if( zExternal ){
105180        db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
105181      }
105182      sqlite3ValueFree(pTmp);
105183    }
105184  #endif
105185  }
105186  
105187  /*
105188  ** This routine is called if the collation factory fails to deliver a
105189  ** collation function in the best encoding but there may be other versions
105190  ** of this collation function (for other text encodings) available. Use one
105191  ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
105192  ** possible.
105193  */
105194  static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
105195    CollSeq *pColl2;
105196    char *z = pColl->zName;
105197    int i;
105198    static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
105199    for(i=0; i<3; i++){
105200      pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
105201      if( pColl2->xCmp!=0 ){
105202        memcpy(pColl, pColl2, sizeof(CollSeq));
105203        pColl->xDel = 0;         /* Do not copy the destructor */
105204        return SQLITE_OK;
105205      }
105206    }
105207    return SQLITE_ERROR;
105208  }
105209  
105210  /*
105211  ** This function is responsible for invoking the collation factory callback
105212  ** or substituting a collation sequence of a different encoding when the
105213  ** requested collation sequence is not available in the desired encoding.
105214  ** 
105215  ** If it is not NULL, then pColl must point to the database native encoding 
105216  ** collation sequence with name zName, length nName.
105217  **
105218  ** The return value is either the collation sequence to be used in database
105219  ** db for collation type name zName, length nName, or NULL, if no collation
105220  ** sequence can be found.  If no collation is found, leave an error message.
105221  **
105222  ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
105223  */
105224  SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
105225    Parse *pParse,        /* Parsing context */
105226    u8 enc,               /* The desired encoding for the collating sequence */
105227    CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
105228    const char *zName     /* Collating sequence name */
105229  ){
105230    CollSeq *p;
105231    sqlite3 *db = pParse->db;
105232  
105233    p = pColl;
105234    if( !p ){
105235      p = sqlite3FindCollSeq(db, enc, zName, 0);
105236    }
105237    if( !p || !p->xCmp ){
105238      /* No collation sequence of this type for this encoding is registered.
105239      ** Call the collation factory to see if it can supply us with one.
105240      */
105241      callCollNeeded(db, enc, zName);
105242      p = sqlite3FindCollSeq(db, enc, zName, 0);
105243    }
105244    if( p && !p->xCmp && synthCollSeq(db, p) ){
105245      p = 0;
105246    }
105247    assert( !p || p->xCmp );
105248    if( p==0 ){
105249      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
105250    }
105251    return p;
105252  }
105253  
105254  /*
105255  ** This routine is called on a collation sequence before it is used to
105256  ** check that it is defined. An undefined collation sequence exists when
105257  ** a database is loaded that contains references to collation sequences
105258  ** that have not been defined by sqlite3_create_collation() etc.
105259  **
105260  ** If required, this routine calls the 'collation needed' callback to
105261  ** request a definition of the collating sequence. If this doesn't work, 
105262  ** an equivalent collating sequence that uses a text encoding different
105263  ** from the main database is substituted, if one is available.
105264  */
105265  SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
105266    if( pColl && pColl->xCmp==0 ){
105267      const char *zName = pColl->zName;
105268      sqlite3 *db = pParse->db;
105269      CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
105270      if( !p ){
105271        return SQLITE_ERROR;
105272      }
105273      assert( p==pColl );
105274    }
105275    return SQLITE_OK;
105276  }
105277  
105278  
105279  
105280  /*
105281  ** Locate and return an entry from the db.aCollSeq hash table. If the entry
105282  ** specified by zName and nName is not found and parameter 'create' is
105283  ** true, then create a new entry. Otherwise return NULL.
105284  **
105285  ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
105286  ** array of three CollSeq structures. The first is the collation sequence
105287  ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
105288  **
105289  ** Stored immediately after the three collation sequences is a copy of
105290  ** the collation sequence name. A pointer to this string is stored in
105291  ** each collation sequence structure.
105292  */
105293  static CollSeq *findCollSeqEntry(
105294    sqlite3 *db,          /* Database connection */
105295    const char *zName,    /* Name of the collating sequence */
105296    int create            /* Create a new entry if true */
105297  ){
105298    CollSeq *pColl;
105299    pColl = sqlite3HashFind(&db->aCollSeq, zName);
105300  
105301    if( 0==pColl && create ){
105302      int nName = sqlite3Strlen30(zName) + 1;
105303      pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName);
105304      if( pColl ){
105305        CollSeq *pDel = 0;
105306        pColl[0].zName = (char*)&pColl[3];
105307        pColl[0].enc = SQLITE_UTF8;
105308        pColl[1].zName = (char*)&pColl[3];
105309        pColl[1].enc = SQLITE_UTF16LE;
105310        pColl[2].zName = (char*)&pColl[3];
105311        pColl[2].enc = SQLITE_UTF16BE;
105312        memcpy(pColl[0].zName, zName, nName);
105313        pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
105314  
105315        /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
105316        ** return the pColl pointer to be deleted (because it wasn't added
105317        ** to the hash table).
105318        */
105319        assert( pDel==0 || pDel==pColl );
105320        if( pDel!=0 ){
105321          sqlite3OomFault(db);
105322          sqlite3DbFree(db, pDel);
105323          pColl = 0;
105324        }
105325      }
105326    }
105327    return pColl;
105328  }
105329  
105330  /*
105331  ** Parameter zName points to a UTF-8 encoded string nName bytes long.
105332  ** Return the CollSeq* pointer for the collation sequence named zName
105333  ** for the encoding 'enc' from the database 'db'.
105334  **
105335  ** If the entry specified is not found and 'create' is true, then create a
105336  ** new entry.  Otherwise return NULL.
105337  **
105338  ** A separate function sqlite3LocateCollSeq() is a wrapper around
105339  ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
105340  ** if necessary and generates an error message if the collating sequence
105341  ** cannot be found.
105342  **
105343  ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
105344  */
105345  SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
105346    sqlite3 *db,
105347    u8 enc,
105348    const char *zName,
105349    int create
105350  ){
105351    CollSeq *pColl;
105352    if( zName ){
105353      pColl = findCollSeqEntry(db, zName, create);
105354    }else{
105355      pColl = db->pDfltColl;
105356    }
105357    assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
105358    assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
105359    if( pColl ) pColl += enc-1;
105360    return pColl;
105361  }
105362  
105363  /* During the search for the best function definition, this procedure
105364  ** is called to test how well the function passed as the first argument
105365  ** matches the request for a function with nArg arguments in a system
105366  ** that uses encoding enc. The value returned indicates how well the
105367  ** request is matched. A higher value indicates a better match.
105368  **
105369  ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
105370  ** is also -1.  In other words, we are searching for a function that
105371  ** takes a variable number of arguments.
105372  **
105373  ** If nArg is -2 that means that we are searching for any function 
105374  ** regardless of the number of arguments it uses, so return a positive
105375  ** match score for any
105376  **
105377  ** The returned value is always between 0 and 6, as follows:
105378  **
105379  ** 0: Not a match.
105380  ** 1: UTF8/16 conversion required and function takes any number of arguments.
105381  ** 2: UTF16 byte order change required and function takes any number of args.
105382  ** 3: encoding matches and function takes any number of arguments
105383  ** 4: UTF8/16 conversion required - argument count matches exactly
105384  ** 5: UTF16 byte order conversion required - argument count matches exactly
105385  ** 6: Perfect match:  encoding and argument count match exactly.
105386  **
105387  ** If nArg==(-2) then any function with a non-null xSFunc is
105388  ** a perfect match and any function with xSFunc NULL is
105389  ** a non-match.
105390  */
105391  #define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
105392  static int matchQuality(
105393    FuncDef *p,     /* The function we are evaluating for match quality */
105394    int nArg,       /* Desired number of arguments.  (-1)==any */
105395    u8 enc          /* Desired text encoding */
105396  ){
105397    int match;
105398  
105399    /* nArg of -2 is a special case */
105400    if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
105401  
105402    /* Wrong number of arguments means "no match" */
105403    if( p->nArg!=nArg && p->nArg>=0 ) return 0;
105404  
105405    /* Give a better score to a function with a specific number of arguments
105406    ** than to function that accepts any number of arguments. */
105407    if( p->nArg==nArg ){
105408      match = 4;
105409    }else{
105410      match = 1;
105411    }
105412  
105413    /* Bonus points if the text encoding matches */
105414    if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
105415      match += 2;  /* Exact encoding match */
105416    }else if( (enc & p->funcFlags & 2)!=0 ){
105417      match += 1;  /* Both are UTF16, but with different byte orders */
105418    }
105419  
105420    return match;
105421  }
105422  
105423  /*
105424  ** Search a FuncDefHash for a function with the given name.  Return
105425  ** a pointer to the matching FuncDef if found, or 0 if there is no match.
105426  */
105427  static FuncDef *functionSearch(
105428    int h,               /* Hash of the name */
105429    const char *zFunc    /* Name of function */
105430  ){
105431    FuncDef *p;
105432    for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
105433      if( sqlite3StrICmp(p->zName, zFunc)==0 ){
105434        return p;
105435      }
105436    }
105437    return 0;
105438  }
105439  
105440  /*
105441  ** Insert a new FuncDef into a FuncDefHash hash table.
105442  */
105443  SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
105444    FuncDef *aDef,      /* List of global functions to be inserted */
105445    int nDef            /* Length of the apDef[] list */
105446  ){
105447    int i;
105448    for(i=0; i<nDef; i++){
105449      FuncDef *pOther;
105450      const char *zName = aDef[i].zName;
105451      int nName = sqlite3Strlen30(zName);
105452      int h = (zName[0] + nName) % SQLITE_FUNC_HASH_SZ;
105453      assert( zName[0]>='a' && zName[0]<='z' );
105454      pOther = functionSearch(h, zName);
105455      if( pOther ){
105456        assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
105457        aDef[i].pNext = pOther->pNext;
105458        pOther->pNext = &aDef[i];
105459      }else{
105460        aDef[i].pNext = 0;
105461        aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
105462        sqlite3BuiltinFunctions.a[h] = &aDef[i];
105463      }
105464    }
105465  }
105466    
105467    
105468  
105469  /*
105470  ** Locate a user function given a name, a number of arguments and a flag
105471  ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
105472  ** pointer to the FuncDef structure that defines that function, or return
105473  ** NULL if the function does not exist.
105474  **
105475  ** If the createFlag argument is true, then a new (blank) FuncDef
105476  ** structure is created and liked into the "db" structure if a
105477  ** no matching function previously existed.
105478  **
105479  ** If nArg is -2, then the first valid function found is returned.  A
105480  ** function is valid if xSFunc is non-zero.  The nArg==(-2)
105481  ** case is used to see if zName is a valid function name for some number
105482  ** of arguments.  If nArg is -2, then createFlag must be 0.
105483  **
105484  ** If createFlag is false, then a function with the required name and
105485  ** number of arguments may be returned even if the eTextRep flag does not
105486  ** match that requested.
105487  */
105488  SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
105489    sqlite3 *db,       /* An open database */
105490    const char *zName, /* Name of the function.  zero-terminated */
105491    int nArg,          /* Number of arguments.  -1 means any number */
105492    u8 enc,            /* Preferred text encoding */
105493    u8 createFlag      /* Create new entry if true and does not otherwise exist */
105494  ){
105495    FuncDef *p;         /* Iterator variable */
105496    FuncDef *pBest = 0; /* Best match found so far */
105497    int bestScore = 0;  /* Score of best match */
105498    int h;              /* Hash value */
105499    int nName;          /* Length of the name */
105500  
105501    assert( nArg>=(-2) );
105502    assert( nArg>=(-1) || createFlag==0 );
105503    nName = sqlite3Strlen30(zName);
105504  
105505    /* First search for a match amongst the application-defined functions.
105506    */
105507    p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
105508    while( p ){
105509      int score = matchQuality(p, nArg, enc);
105510      if( score>bestScore ){
105511        pBest = p;
105512        bestScore = score;
105513      }
105514      p = p->pNext;
105515    }
105516  
105517    /* If no match is found, search the built-in functions.
105518    **
105519    ** If the DBFLAG_PreferBuiltin flag is set, then search the built-in
105520    ** functions even if a prior app-defined function was found.  And give
105521    ** priority to built-in functions.
105522    **
105523    ** Except, if createFlag is true, that means that we are trying to
105524    ** install a new function.  Whatever FuncDef structure is returned it will
105525    ** have fields overwritten with new information appropriate for the
105526    ** new function.  But the FuncDefs for built-in functions are read-only.
105527    ** So we must not search for built-ins when creating a new function.
105528    */ 
105529    if( !createFlag && (pBest==0 || (db->mDbFlags & DBFLAG_PreferBuiltin)!=0) ){
105530      bestScore = 0;
105531      h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
105532      p = functionSearch(h, zName);
105533      while( p ){
105534        int score = matchQuality(p, nArg, enc);
105535        if( score>bestScore ){
105536          pBest = p;
105537          bestScore = score;
105538        }
105539        p = p->pNext;
105540      }
105541    }
105542  
105543    /* If the createFlag parameter is true and the search did not reveal an
105544    ** exact match for the name, number of arguments and encoding, then add a
105545    ** new entry to the hash table and return it.
105546    */
105547    if( createFlag && bestScore<FUNC_PERFECT_MATCH && 
105548        (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
105549      FuncDef *pOther;
105550      pBest->zName = (const char*)&pBest[1];
105551      pBest->nArg = (u16)nArg;
105552      pBest->funcFlags = enc;
105553      memcpy((char*)&pBest[1], zName, nName+1);
105554      pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
105555      if( pOther==pBest ){
105556        sqlite3DbFree(db, pBest);
105557        sqlite3OomFault(db);
105558        return 0;
105559      }else{
105560        pBest->pNext = pOther;
105561      }
105562    }
105563  
105564    if( pBest && (pBest->xSFunc || createFlag) ){
105565      return pBest;
105566    }
105567    return 0;
105568  }
105569  
105570  /*
105571  ** Free all resources held by the schema structure. The void* argument points
105572  ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
105573  ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
105574  ** of the schema hash tables).
105575  **
105576  ** The Schema.cache_size variable is not cleared.
105577  */
105578  SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
105579    Hash temp1;
105580    Hash temp2;
105581    HashElem *pElem;
105582    Schema *pSchema = (Schema *)p;
105583  
105584    temp1 = pSchema->tblHash;
105585    temp2 = pSchema->trigHash;
105586    sqlite3HashInit(&pSchema->trigHash);
105587    sqlite3HashClear(&pSchema->idxHash);
105588    for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
105589      sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
105590    }
105591    sqlite3HashClear(&temp2);
105592    sqlite3HashInit(&pSchema->tblHash);
105593    for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
105594      Table *pTab = sqliteHashData(pElem);
105595      sqlite3DeleteTable(0, pTab);
105596    }
105597    sqlite3HashClear(&temp1);
105598    sqlite3HashClear(&pSchema->fkeyHash);
105599    pSchema->pSeqTab = 0;
105600    if( pSchema->schemaFlags & DB_SchemaLoaded ){
105601      pSchema->iGeneration++;
105602    }
105603    pSchema->schemaFlags &= ~(DB_SchemaLoaded|DB_ResetWanted);
105604  }
105605  
105606  /*
105607  ** Find and return the schema associated with a BTree.  Create
105608  ** a new one if necessary.
105609  */
105610  SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
105611    Schema * p;
105612    if( pBt ){
105613      p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
105614    }else{
105615      p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
105616    }
105617    if( !p ){
105618      sqlite3OomFault(db);
105619    }else if ( 0==p->file_format ){
105620      sqlite3HashInit(&p->tblHash);
105621      sqlite3HashInit(&p->idxHash);
105622      sqlite3HashInit(&p->trigHash);
105623      sqlite3HashInit(&p->fkeyHash);
105624      p->enc = SQLITE_UTF8;
105625    }
105626    return p;
105627  }
105628  
105629  /************** End of callback.c ********************************************/
105630  /************** Begin file delete.c ******************************************/
105631  /*
105632  ** 2001 September 15
105633  **
105634  ** The author disclaims copyright to this source code.  In place of
105635  ** a legal notice, here is a blessing:
105636  **
105637  **    May you do good and not evil.
105638  **    May you find forgiveness for yourself and forgive others.
105639  **    May you share freely, never taking more than you give.
105640  **
105641  *************************************************************************
105642  ** This file contains C code routines that are called by the parser
105643  ** in order to generate code for DELETE FROM statements.
105644  */
105645  /* #include "sqliteInt.h" */
105646  
105647  /*
105648  ** While a SrcList can in general represent multiple tables and subqueries
105649  ** (as in the FROM clause of a SELECT statement) in this case it contains
105650  ** the name of a single table, as one might find in an INSERT, DELETE,
105651  ** or UPDATE statement.  Look up that table in the symbol table and
105652  ** return a pointer.  Set an error message and return NULL if the table 
105653  ** name is not found or if any other error occurs.
105654  **
105655  ** The following fields are initialized appropriate in pSrc:
105656  **
105657  **    pSrc->a[0].pTab       Pointer to the Table object
105658  **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
105659  **
105660  */
105661  SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
105662    struct SrcList_item *pItem = pSrc->a;
105663    Table *pTab;
105664    assert( pItem && pSrc->nSrc==1 );
105665    pTab = sqlite3LocateTableItem(pParse, 0, pItem);
105666    sqlite3DeleteTable(pParse->db, pItem->pTab);
105667    pItem->pTab = pTab;
105668    if( pTab ){
105669      pTab->nTabRef++;
105670    }
105671    if( sqlite3IndexedByLookup(pParse, pItem) ){
105672      pTab = 0;
105673    }
105674    return pTab;
105675  }
105676  
105677  /*
105678  ** Check to make sure the given table is writable.  If it is not
105679  ** writable, generate an error message and return 1.  If it is
105680  ** writable return 0;
105681  */
105682  SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
105683    /* A table is not writable under the following circumstances:
105684    **
105685    **   1) It is a virtual table and no implementation of the xUpdate method
105686    **      has been provided, or
105687    **   2) It is a system table (i.e. sqlite_master), this call is not
105688    **      part of a nested parse and writable_schema pragma has not 
105689    **      been specified.
105690    **
105691    ** In either case leave an error message in pParse and return non-zero.
105692    */
105693    if( ( IsVirtual(pTab) 
105694       && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
105695     || ( (pTab->tabFlags & TF_Readonly)!=0
105696       && (pParse->db->flags & SQLITE_WriteSchema)==0
105697       && pParse->nested==0 )
105698    ){
105699      sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
105700      return 1;
105701    }
105702  
105703  #ifndef SQLITE_OMIT_VIEW
105704    if( !viewOk && pTab->pSelect ){
105705      sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
105706      return 1;
105707    }
105708  #endif
105709    return 0;
105710  }
105711  
105712  
105713  #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
105714  /*
105715  ** Evaluate a view and store its result in an ephemeral table.  The
105716  ** pWhere argument is an optional WHERE clause that restricts the
105717  ** set of rows in the view that are to be added to the ephemeral table.
105718  */
105719  SQLITE_PRIVATE void sqlite3MaterializeView(
105720    Parse *pParse,       /* Parsing context */
105721    Table *pView,        /* View definition */
105722    Expr *pWhere,        /* Optional WHERE clause to be added */
105723    int iCur             /* Cursor number for ephemeral table */
105724  ){
105725    SelectDest dest;
105726    Select *pSel;
105727    SrcList *pFrom;
105728    sqlite3 *db = pParse->db;
105729    int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
105730    pWhere = sqlite3ExprDup(db, pWhere, 0);
105731    pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
105732    if( pFrom ){
105733      assert( pFrom->nSrc==1 );
105734      pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
105735      pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
105736      assert( pFrom->a[0].pOn==0 );
105737      assert( pFrom->a[0].pUsing==0 );
105738    }
105739    pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 
105740                            SF_IncludeHidden, 0, 0);
105741    sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
105742    sqlite3Select(pParse, pSel, &dest);
105743    sqlite3SelectDelete(db, pSel);
105744  }
105745  #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
105746  
105747  #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
105748  /*
105749  ** Generate an expression tree to implement the WHERE, ORDER BY,
105750  ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
105751  **
105752  **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
105753  **                            \__________________________/
105754  **                               pLimitWhere (pInClause)
105755  */
105756  SQLITE_PRIVATE Expr *sqlite3LimitWhere(
105757    Parse *pParse,               /* The parser context */
105758    SrcList *pSrc,               /* the FROM clause -- which tables to scan */
105759    Expr *pWhere,                /* The WHERE clause.  May be null */
105760    ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
105761    Expr *pLimit,                /* The LIMIT clause.  May be null */
105762    Expr *pOffset,               /* The OFFSET clause.  May be null */
105763    char *zStmtType              /* Either DELETE or UPDATE.  For err msgs. */
105764  ){
105765    Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
105766    Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
105767    Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
105768    ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
105769    SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
105770    Select *pSelect = NULL;      /* Complete SELECT tree */
105771  
105772    /* Check that there isn't an ORDER BY without a LIMIT clause.
105773    */
105774    if( pOrderBy && (pLimit == 0) ) {
105775      sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
105776      goto limit_where_cleanup;
105777    }
105778  
105779    /* We only need to generate a select expression if there
105780    ** is a limit/offset term to enforce.
105781    */
105782    if( pLimit == 0 ) {
105783      /* if pLimit is null, pOffset will always be null as well. */
105784      assert( pOffset == 0 );
105785      return pWhere;
105786    }
105787  
105788    /* Generate a select expression tree to enforce the limit/offset 
105789    ** term for the DELETE or UPDATE statement.  For example:
105790    **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
105791    ** becomes:
105792    **   DELETE FROM table_a WHERE rowid IN ( 
105793    **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
105794    **   );
105795    */
105796  
105797    pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0);
105798    if( pSelectRowid == 0 ) goto limit_where_cleanup;
105799    pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
105800    if( pEList == 0 ) goto limit_where_cleanup;
105801  
105802    /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
105803    ** and the SELECT subtree. */
105804    pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
105805    if( pSelectSrc == 0 ) {
105806      sqlite3ExprListDelete(pParse->db, pEList);
105807      goto limit_where_cleanup;
105808    }
105809  
105810    /* generate the SELECT expression tree. */
105811    pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
105812                               pOrderBy,0,pLimit,pOffset);
105813    if( pSelect == 0 ) return 0;
105814  
105815    /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
105816    pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0);
105817    pInClause = pWhereRowid ? sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0) : 0;
105818    sqlite3PExprAddSelect(pParse, pInClause, pSelect);
105819    return pInClause;
105820  
105821  limit_where_cleanup:
105822    sqlite3ExprDelete(pParse->db, pWhere);
105823    sqlite3ExprListDelete(pParse->db, pOrderBy);
105824    sqlite3ExprDelete(pParse->db, pLimit);
105825    sqlite3ExprDelete(pParse->db, pOffset);
105826    return 0;
105827  }
105828  #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
105829         /*      && !defined(SQLITE_OMIT_SUBQUERY) */
105830  
105831  /*
105832  ** Generate code for a DELETE FROM statement.
105833  **
105834  **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
105835  **                 \________/       \________________/
105836  **                  pTabList              pWhere
105837  */
105838  SQLITE_PRIVATE void sqlite3DeleteFrom(
105839    Parse *pParse,         /* The parser context */
105840    SrcList *pTabList,     /* The table from which we should delete things */
105841    Expr *pWhere           /* The WHERE clause.  May be null */
105842  ){
105843    Vdbe *v;               /* The virtual database engine */
105844    Table *pTab;           /* The table from which records will be deleted */
105845    int i;                 /* Loop counter */
105846    WhereInfo *pWInfo;     /* Information about the WHERE clause */
105847    Index *pIdx;           /* For looping over indices of the table */
105848    int iTabCur;           /* Cursor number for the table */
105849    int iDataCur = 0;      /* VDBE cursor for the canonical data source */
105850    int iIdxCur = 0;       /* Cursor number of the first index */
105851    int nIdx;              /* Number of indices */
105852    sqlite3 *db;           /* Main database structure */
105853    AuthContext sContext;  /* Authorization context */
105854    NameContext sNC;       /* Name context to resolve expressions in */
105855    int iDb;               /* Database number */
105856    int memCnt = -1;       /* Memory cell used for change counting */
105857    int rcauth;            /* Value returned by authorization callback */
105858    int eOnePass;          /* ONEPASS_OFF or _SINGLE or _MULTI */
105859    int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
105860    u8 *aToOpen = 0;       /* Open cursor iTabCur+j if aToOpen[j] is true */
105861    Index *pPk;            /* The PRIMARY KEY index on the table */
105862    int iPk = 0;           /* First of nPk registers holding PRIMARY KEY value */
105863    i16 nPk = 1;           /* Number of columns in the PRIMARY KEY */
105864    int iKey;              /* Memory cell holding key of row to be deleted */
105865    i16 nKey;              /* Number of memory cells in the row key */
105866    int iEphCur = 0;       /* Ephemeral table holding all primary key values */
105867    int iRowSet = 0;       /* Register for rowset of rows to delete */
105868    int addrBypass = 0;    /* Address of jump over the delete logic */
105869    int addrLoop = 0;      /* Top of the delete loop */
105870    int addrEphOpen = 0;   /* Instruction to open the Ephemeral table */
105871    int bComplex;          /* True if there are triggers or FKs or
105872                           ** subqueries in the WHERE clause */
105873   
105874  #ifndef SQLITE_OMIT_TRIGGER
105875    int isView;                  /* True if attempting to delete from a view */
105876    Trigger *pTrigger;           /* List of table triggers, if required */
105877  #endif
105878  
105879    memset(&sContext, 0, sizeof(sContext));
105880    db = pParse->db;
105881    if( pParse->nErr || db->mallocFailed ){
105882      goto delete_from_cleanup;
105883    }
105884    assert( pTabList->nSrc==1 );
105885  
105886    /* Locate the table which we want to delete.  This table has to be
105887    ** put in an SrcList structure because some of the subroutines we
105888    ** will be calling are designed to work with multiple tables and expect
105889    ** an SrcList* parameter instead of just a Table* parameter.
105890    */
105891    pTab = sqlite3SrcListLookup(pParse, pTabList);
105892    if( pTab==0 )  goto delete_from_cleanup;
105893  
105894    /* Figure out if we have any triggers and if the table being
105895    ** deleted from is a view
105896    */
105897  #ifndef SQLITE_OMIT_TRIGGER
105898    pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
105899    isView = pTab->pSelect!=0;
105900    bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
105901  #else
105902  # define pTrigger 0
105903  # define isView 0
105904  #endif
105905  #ifdef SQLITE_OMIT_VIEW
105906  # undef isView
105907  # define isView 0
105908  #endif
105909  
105910    /* If pTab is really a view, make sure it has been initialized.
105911    */
105912    if( sqlite3ViewGetColumnNames(pParse, pTab) ){
105913      goto delete_from_cleanup;
105914    }
105915  
105916    if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
105917      goto delete_from_cleanup;
105918    }
105919    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
105920    assert( iDb<db->nDb );
105921    rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, 
105922                              db->aDb[iDb].zDbSName);
105923    assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
105924    if( rcauth==SQLITE_DENY ){
105925      goto delete_from_cleanup;
105926    }
105927    assert(!isView || pTrigger);
105928  
105929    /* Assign cursor numbers to the table and all its indices.
105930    */
105931    assert( pTabList->nSrc==1 );
105932    iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
105933    for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
105934      pParse->nTab++;
105935    }
105936  
105937    /* Start the view context
105938    */
105939    if( isView ){
105940      sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
105941    }
105942  
105943    /* Begin generating code.
105944    */
105945    v = sqlite3GetVdbe(pParse);
105946    if( v==0 ){
105947      goto delete_from_cleanup;
105948    }
105949    if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
105950    sqlite3BeginWriteOperation(pParse, 1, iDb);
105951  
105952    /* If we are trying to delete from a view, realize that view into
105953    ** an ephemeral table.
105954    */
105955  #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
105956    if( isView ){
105957      sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
105958      iDataCur = iIdxCur = iTabCur;
105959    }
105960  #endif
105961  
105962    /* Resolve the column names in the WHERE clause.
105963    */
105964    memset(&sNC, 0, sizeof(sNC));
105965    sNC.pParse = pParse;
105966    sNC.pSrcList = pTabList;
105967    if( sqlite3ResolveExprNames(&sNC, pWhere) ){
105968      goto delete_from_cleanup;
105969    }
105970  
105971    /* Initialize the counter of the number of rows deleted, if
105972    ** we are counting rows.
105973    */
105974    if( db->flags & SQLITE_CountRows ){
105975      memCnt = ++pParse->nMem;
105976      sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
105977    }
105978  
105979  #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
105980    /* Special case: A DELETE without a WHERE clause deletes everything.
105981    ** It is easier just to erase the whole table. Prior to version 3.6.5,
105982    ** this optimization caused the row change count (the value returned by 
105983    ** API function sqlite3_count_changes) to be set incorrectly.
105984    **
105985    ** The "rcauth==SQLITE_OK" terms is the
105986    ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
105987    ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but
105988    ** the truncate optimization is disabled and all rows are deleted
105989    ** individually.
105990    */
105991    if( rcauth==SQLITE_OK
105992     && pWhere==0
105993     && !bComplex
105994     && !IsVirtual(pTab)
105995  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
105996     && db->xPreUpdateCallback==0
105997  #endif
105998    ){
105999      assert( !isView );
106000      sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
106001      if( HasRowid(pTab) ){
106002        sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
106003                          pTab->zName, P4_STATIC);
106004      }
106005      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
106006        assert( pIdx->pSchema==pTab->pSchema );
106007        sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
106008      }
106009    }else
106010  #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
106011    {
106012      u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
106013      if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
106014      wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
106015      if( HasRowid(pTab) ){
106016        /* For a rowid table, initialize the RowSet to an empty set */
106017        pPk = 0;
106018        nPk = 1;
106019        iRowSet = ++pParse->nMem;
106020        sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
106021      }else{
106022        /* For a WITHOUT ROWID table, create an ephemeral table used to
106023        ** hold all primary keys for rows to be deleted. */
106024        pPk = sqlite3PrimaryKeyIndex(pTab);
106025        assert( pPk!=0 );
106026        nPk = pPk->nKeyCol;
106027        iPk = pParse->nMem+1;
106028        pParse->nMem += nPk;
106029        iEphCur = pParse->nTab++;
106030        addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
106031        sqlite3VdbeSetP4KeyInfo(pParse, pPk);
106032      }
106033    
106034      /* Construct a query to find the rowid or primary key for every row
106035      ** to be deleted, based on the WHERE clause. Set variable eOnePass
106036      ** to indicate the strategy used to implement this delete:
106037      **
106038      **  ONEPASS_OFF:    Two-pass approach - use a FIFO for rowids/PK values.
106039      **  ONEPASS_SINGLE: One-pass approach - at most one row deleted.
106040      **  ONEPASS_MULTI:  One-pass approach - any number of rows may be deleted.
106041      */
106042      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
106043      if( pWInfo==0 ) goto delete_from_cleanup;
106044      eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
106045      assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
106046      assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
106047    
106048      /* Keep track of the number of rows to be deleted */
106049      if( db->flags & SQLITE_CountRows ){
106050        sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
106051      }
106052    
106053      /* Extract the rowid or primary key for the current row */
106054      if( pPk ){
106055        for(i=0; i<nPk; i++){
106056          assert( pPk->aiColumn[i]>=0 );
106057          sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
106058                                          pPk->aiColumn[i], iPk+i);
106059        }
106060        iKey = iPk;
106061      }else{
106062        iKey = pParse->nMem + 1;
106063        iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
106064        if( iKey>pParse->nMem ) pParse->nMem = iKey;
106065      }
106066    
106067      if( eOnePass!=ONEPASS_OFF ){
106068        /* For ONEPASS, no need to store the rowid/primary-key. There is only
106069        ** one, so just keep it in its register(s) and fall through to the
106070        ** delete code.  */
106071        nKey = nPk; /* OP_Found will use an unpacked key */
106072        aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
106073        if( aToOpen==0 ){
106074          sqlite3WhereEnd(pWInfo);
106075          goto delete_from_cleanup;
106076        }
106077        memset(aToOpen, 1, nIdx+1);
106078        aToOpen[nIdx+1] = 0;
106079        if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
106080        if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
106081        if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
106082      }else{
106083        if( pPk ){
106084          /* Add the PK key for this row to the temporary table */
106085          iKey = ++pParse->nMem;
106086          nKey = 0;   /* Zero tells OP_Found to use a composite key */
106087          sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
106088              sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
106089          sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk);
106090        }else{
106091          /* Add the rowid of the row to be deleted to the RowSet */
106092          nKey = 1;  /* OP_DeferredSeek always uses a single rowid */
106093          sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
106094        }
106095      }
106096    
106097      /* If this DELETE cannot use the ONEPASS strategy, this is the 
106098      ** end of the WHERE loop */
106099      if( eOnePass!=ONEPASS_OFF ){
106100        addrBypass = sqlite3VdbeMakeLabel(v);
106101      }else{
106102        sqlite3WhereEnd(pWInfo);
106103      }
106104    
106105      /* Unless this is a view, open cursors for the table we are 
106106      ** deleting from and all its indices. If this is a view, then the
106107      ** only effect this statement has is to fire the INSTEAD OF 
106108      ** triggers.
106109      */
106110      if( !isView ){
106111        int iAddrOnce = 0;
106112        if( eOnePass==ONEPASS_MULTI ){
106113          iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
106114        }
106115        testcase( IsVirtual(pTab) );
106116        sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
106117                                   iTabCur, aToOpen, &iDataCur, &iIdxCur);
106118        assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
106119        assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
106120        if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
106121      }
106122    
106123      /* Set up a loop over the rowids/primary-keys that were found in the
106124      ** where-clause loop above.
106125      */
106126      if( eOnePass!=ONEPASS_OFF ){
106127        assert( nKey==nPk );  /* OP_Found will use an unpacked key */
106128        if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
106129          assert( pPk!=0 || pTab->pSelect!=0 );
106130          sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
106131          VdbeCoverage(v);
106132        }
106133      }else if( pPk ){
106134        addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
106135        if( IsVirtual(pTab) ){
106136          sqlite3VdbeAddOp3(v, OP_Column, iEphCur, 0, iKey);
106137        }else{
106138          sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey);
106139        }
106140        assert( nKey==0 );  /* OP_Found will use a composite key */
106141      }else{
106142        addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
106143        VdbeCoverage(v);
106144        assert( nKey==1 );
106145      }  
106146    
106147      /* Delete the row */
106148  #ifndef SQLITE_OMIT_VIRTUALTABLE
106149      if( IsVirtual(pTab) ){
106150        const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
106151        sqlite3VtabMakeWritable(pParse, pTab);
106152        sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
106153        sqlite3VdbeChangeP5(v, OE_Abort);
106154        assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
106155        sqlite3MayAbort(pParse);
106156        if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
106157          pParse->isMultiWrite = 0;
106158        }
106159      }else
106160  #endif
106161      {
106162        int count = (pParse->nested==0);    /* True to count changes */
106163        sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
106164            iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
106165      }
106166    
106167      /* End of the loop over all rowids/primary-keys. */
106168      if( eOnePass!=ONEPASS_OFF ){
106169        sqlite3VdbeResolveLabel(v, addrBypass);
106170        sqlite3WhereEnd(pWInfo);
106171      }else if( pPk ){
106172        sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
106173        sqlite3VdbeJumpHere(v, addrLoop);
106174      }else{
106175        sqlite3VdbeGoto(v, addrLoop);
106176        sqlite3VdbeJumpHere(v, addrLoop);
106177      }     
106178    } /* End non-truncate path */
106179  
106180    /* Update the sqlite_sequence table by storing the content of the
106181    ** maximum rowid counter values recorded while inserting into
106182    ** autoincrement tables.
106183    */
106184    if( pParse->nested==0 && pParse->pTriggerTab==0 ){
106185      sqlite3AutoincrementEnd(pParse);
106186    }
106187  
106188    /* Return the number of rows that were deleted. If this routine is 
106189    ** generating code because of a call to sqlite3NestedParse(), do not
106190    ** invoke the callback function.
106191    */
106192    if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
106193      sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
106194      sqlite3VdbeSetNumCols(v, 1);
106195      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
106196    }
106197  
106198  delete_from_cleanup:
106199    sqlite3AuthContextPop(&sContext);
106200    sqlite3SrcListDelete(db, pTabList);
106201    sqlite3ExprDelete(db, pWhere);
106202    sqlite3DbFree(db, aToOpen);
106203    return;
106204  }
106205  /* Make sure "isView" and other macros defined above are undefined. Otherwise
106206  ** they may interfere with compilation of other functions in this file
106207  ** (or in another file, if this file becomes part of the amalgamation).  */
106208  #ifdef isView
106209   #undef isView
106210  #endif
106211  #ifdef pTrigger
106212   #undef pTrigger
106213  #endif
106214  
106215  /*
106216  ** This routine generates VDBE code that causes a single row of a
106217  ** single table to be deleted.  Both the original table entry and
106218  ** all indices are removed.
106219  **
106220  ** Preconditions:
106221  **
106222  **   1.  iDataCur is an open cursor on the btree that is the canonical data
106223  **       store for the table.  (This will be either the table itself,
106224  **       in the case of a rowid table, or the PRIMARY KEY index in the case
106225  **       of a WITHOUT ROWID table.)
106226  **
106227  **   2.  Read/write cursors for all indices of pTab must be open as
106228  **       cursor number iIdxCur+i for the i-th index.
106229  **
106230  **   3.  The primary key for the row to be deleted must be stored in a
106231  **       sequence of nPk memory cells starting at iPk.  If nPk==0 that means
106232  **       that a search record formed from OP_MakeRecord is contained in the
106233  **       single memory location iPk.
106234  **
106235  ** eMode:
106236  **   Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
106237  **   ONEPASS_MULTI.  If eMode is not ONEPASS_OFF, then the cursor
106238  **   iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
106239  **   then this function must seek iDataCur to the entry identified by iPk
106240  **   and nPk before reading from it.
106241  **
106242  **   If eMode is ONEPASS_MULTI, then this call is being made as part
106243  **   of a ONEPASS delete that affects multiple rows. In this case, if 
106244  **   iIdxNoSeek is a valid cursor number (>=0) and is not the same as
106245  **   iDataCur, then its position should be preserved following the delete
106246  **   operation. Or, if iIdxNoSeek is not a valid cursor number, the
106247  **   position of iDataCur should be preserved instead.
106248  **
106249  ** iIdxNoSeek:
106250  **   If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
106251  **   then it identifies an index cursor (from within array of cursors
106252  **   starting at iIdxCur) that already points to the index entry to be deleted.
106253  **   Except, this optimization is disabled if there are BEFORE triggers since
106254  **   the trigger body might have moved the cursor.
106255  */
106256  SQLITE_PRIVATE void sqlite3GenerateRowDelete(
106257    Parse *pParse,     /* Parsing context */
106258    Table *pTab,       /* Table containing the row to be deleted */
106259    Trigger *pTrigger, /* List of triggers to (potentially) fire */
106260    int iDataCur,      /* Cursor from which column data is extracted */
106261    int iIdxCur,       /* First index cursor */
106262    int iPk,           /* First memory cell containing the PRIMARY KEY */
106263    i16 nPk,           /* Number of PRIMARY KEY memory cells */
106264    u8 count,          /* If non-zero, increment the row change counter */
106265    u8 onconf,         /* Default ON CONFLICT policy for triggers */
106266    u8 eMode,          /* ONEPASS_OFF, _SINGLE, or _MULTI.  See above */
106267    int iIdxNoSeek     /* Cursor number of cursor that does not need seeking */
106268  ){
106269    Vdbe *v = pParse->pVdbe;        /* Vdbe */
106270    int iOld = 0;                   /* First register in OLD.* array */
106271    int iLabel;                     /* Label resolved to end of generated code */
106272    u8 opSeek;                      /* Seek opcode */
106273  
106274    /* Vdbe is guaranteed to have been allocated by this stage. */
106275    assert( v );
106276    VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
106277                           iDataCur, iIdxCur, iPk, (int)nPk));
106278  
106279    /* Seek cursor iCur to the row to delete. If this row no longer exists 
106280    ** (this can happen if a trigger program has already deleted it), do
106281    ** not attempt to delete it or fire any DELETE triggers.  */
106282    iLabel = sqlite3VdbeMakeLabel(v);
106283    opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
106284    if( eMode==ONEPASS_OFF ){
106285      sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
106286      VdbeCoverageIf(v, opSeek==OP_NotExists);
106287      VdbeCoverageIf(v, opSeek==OP_NotFound);
106288    }
106289   
106290    /* If there are any triggers to fire, allocate a range of registers to
106291    ** use for the old.* references in the triggers.  */
106292    if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
106293      u32 mask;                     /* Mask of OLD.* columns in use */
106294      int iCol;                     /* Iterator used while populating OLD.* */
106295      int addrStart;                /* Start of BEFORE trigger programs */
106296  
106297      /* TODO: Could use temporary registers here. Also could attempt to
106298      ** avoid copying the contents of the rowid register.  */
106299      mask = sqlite3TriggerColmask(
106300          pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
106301      );
106302      mask |= sqlite3FkOldmask(pParse, pTab);
106303      iOld = pParse->nMem+1;
106304      pParse->nMem += (1 + pTab->nCol);
106305  
106306      /* Populate the OLD.* pseudo-table register array. These values will be 
106307      ** used by any BEFORE and AFTER triggers that exist.  */
106308      sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
106309      for(iCol=0; iCol<pTab->nCol; iCol++){
106310        testcase( mask!=0xffffffff && iCol==31 );
106311        testcase( mask!=0xffffffff && iCol==32 );
106312        if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
106313          sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
106314        }
106315      }
106316  
106317      /* Invoke BEFORE DELETE trigger programs. */
106318      addrStart = sqlite3VdbeCurrentAddr(v);
106319      sqlite3CodeRowTrigger(pParse, pTrigger, 
106320          TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
106321      );
106322  
106323      /* If any BEFORE triggers were coded, then seek the cursor to the 
106324      ** row to be deleted again. It may be that the BEFORE triggers moved
106325      ** the cursor or already deleted the row that the cursor was
106326      ** pointing to.
106327      **
106328      ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
106329      ** may have moved that cursor.
106330      */
106331      if( addrStart<sqlite3VdbeCurrentAddr(v) ){
106332        sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
106333        VdbeCoverageIf(v, opSeek==OP_NotExists);
106334        VdbeCoverageIf(v, opSeek==OP_NotFound);
106335        testcase( iIdxNoSeek>=0 );
106336        iIdxNoSeek = -1;
106337      }
106338  
106339      /* Do FK processing. This call checks that any FK constraints that
106340      ** refer to this table (i.e. constraints attached to other tables) 
106341      ** are not violated by deleting this row.  */
106342      sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
106343    }
106344  
106345    /* Delete the index and table entries. Skip this step if pTab is really
106346    ** a view (in which case the only effect of the DELETE statement is to
106347    ** fire the INSTEAD OF triggers).  
106348    **
106349    ** If variable 'count' is non-zero, then this OP_Delete instruction should
106350    ** invoke the update-hook. The pre-update-hook, on the other hand should
106351    ** be invoked unless table pTab is a system table. The difference is that
106352    ** the update-hook is not invoked for rows removed by REPLACE, but the 
106353    ** pre-update-hook is.
106354    */ 
106355    if( pTab->pSelect==0 ){
106356      u8 p5 = 0;
106357      sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
106358      sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
106359      if( pParse->nested==0 ){
106360        sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);
106361      }
106362      if( eMode!=ONEPASS_OFF ){
106363        sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
106364      }
106365      if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){
106366        sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
106367      }
106368      if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
106369      sqlite3VdbeChangeP5(v, p5);
106370    }
106371  
106372    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
106373    ** handle rows (possibly in other tables) that refer via a foreign key
106374    ** to the row just deleted. */ 
106375    sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
106376  
106377    /* Invoke AFTER DELETE trigger programs. */
106378    sqlite3CodeRowTrigger(pParse, pTrigger, 
106379        TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
106380    );
106381  
106382    /* Jump here if the row had already been deleted before any BEFORE
106383    ** trigger programs were invoked. Or if a trigger program throws a 
106384    ** RAISE(IGNORE) exception.  */
106385    sqlite3VdbeResolveLabel(v, iLabel);
106386    VdbeModuleComment((v, "END: GenRowDel()"));
106387  }
106388  
106389  /*
106390  ** This routine generates VDBE code that causes the deletion of all
106391  ** index entries associated with a single row of a single table, pTab
106392  **
106393  ** Preconditions:
106394  **
106395  **   1.  A read/write cursor "iDataCur" must be open on the canonical storage
106396  **       btree for the table pTab.  (This will be either the table itself
106397  **       for rowid tables or to the primary key index for WITHOUT ROWID
106398  **       tables.)
106399  **
106400  **   2.  Read/write cursors for all indices of pTab must be open as
106401  **       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
106402  **       index is the 0-th index.)
106403  **
106404  **   3.  The "iDataCur" cursor must be already be positioned on the row
106405  **       that is to be deleted.
106406  */
106407  SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
106408    Parse *pParse,     /* Parsing and code generating context */
106409    Table *pTab,       /* Table containing the row to be deleted */
106410    int iDataCur,      /* Cursor of table holding data. */
106411    int iIdxCur,       /* First index cursor */
106412    int *aRegIdx,      /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
106413    int iIdxNoSeek     /* Do not delete from this cursor */
106414  ){
106415    int i;             /* Index loop counter */
106416    int r1 = -1;       /* Register holding an index key */
106417    int iPartIdxLabel; /* Jump destination for skipping partial index entries */
106418    Index *pIdx;       /* Current index */
106419    Index *pPrior = 0; /* Prior index */
106420    Vdbe *v;           /* The prepared statement under construction */
106421    Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */
106422  
106423    v = pParse->pVdbe;
106424    pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
106425    for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
106426      assert( iIdxCur+i!=iDataCur || pPk==pIdx );
106427      if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
106428      if( pIdx==pPk ) continue;
106429      if( iIdxCur+i==iIdxNoSeek ) continue;
106430      VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
106431      r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
106432          &iPartIdxLabel, pPrior, r1);
106433      sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
106434          pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
106435      sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
106436      pPrior = pIdx;
106437    }
106438  }
106439  
106440  /*
106441  ** Generate code that will assemble an index key and stores it in register
106442  ** regOut.  The key with be for index pIdx which is an index on pTab.
106443  ** iCur is the index of a cursor open on the pTab table and pointing to
106444  ** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
106445  ** iCur must be the cursor of the PRIMARY KEY index.
106446  **
106447  ** Return a register number which is the first in a block of
106448  ** registers that holds the elements of the index key.  The
106449  ** block of registers has already been deallocated by the time
106450  ** this routine returns.
106451  **
106452  ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
106453  ** to that label if pIdx is a partial index that should be skipped.
106454  ** The label should be resolved using sqlite3ResolvePartIdxLabel().
106455  ** A partial index should be skipped if its WHERE clause evaluates
106456  ** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
106457  ** will be set to zero which is an empty label that is ignored by
106458  ** sqlite3ResolvePartIdxLabel().
106459  **
106460  ** The pPrior and regPrior parameters are used to implement a cache to
106461  ** avoid unnecessary register loads.  If pPrior is not NULL, then it is
106462  ** a pointer to a different index for which an index key has just been
106463  ** computed into register regPrior.  If the current pIdx index is generating
106464  ** its key into the same sequence of registers and if pPrior and pIdx share
106465  ** a column in common, then the register corresponding to that column already
106466  ** holds the correct value and the loading of that register is skipped.
106467  ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK 
106468  ** on a table with multiple indices, and especially with the ROWID or
106469  ** PRIMARY KEY columns of the index.
106470  */
106471  SQLITE_PRIVATE int sqlite3GenerateIndexKey(
106472    Parse *pParse,       /* Parsing context */
106473    Index *pIdx,         /* The index for which to generate a key */
106474    int iDataCur,        /* Cursor number from which to take column data */
106475    int regOut,          /* Put the new key into this register if not 0 */
106476    int prefixOnly,      /* Compute only a unique prefix of the key */
106477    int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
106478    Index *pPrior,       /* Previously generated index key */
106479    int regPrior         /* Register holding previous generated key */
106480  ){
106481    Vdbe *v = pParse->pVdbe;
106482    int j;
106483    int regBase;
106484    int nCol;
106485  
106486    if( piPartIdxLabel ){
106487      if( pIdx->pPartIdxWhere ){
106488        *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
106489        pParse->iSelfTab = iDataCur + 1;
106490        sqlite3ExprCachePush(pParse);
106491        sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel, 
106492                              SQLITE_JUMPIFNULL);
106493        pParse->iSelfTab = 0;
106494      }else{
106495        *piPartIdxLabel = 0;
106496      }
106497    }
106498    nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
106499    regBase = sqlite3GetTempRange(pParse, nCol);
106500    if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
106501    for(j=0; j<nCol; j++){
106502      if( pPrior
106503       && pPrior->aiColumn[j]==pIdx->aiColumn[j]
106504       && pPrior->aiColumn[j]!=XN_EXPR
106505      ){
106506        /* This column was already computed by the previous index */
106507        continue;
106508      }
106509      sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
106510      /* If the column affinity is REAL but the number is an integer, then it
106511      ** might be stored in the table as an integer (using a compact
106512      ** representation) then converted to REAL by an OP_RealAffinity opcode.
106513      ** But we are getting ready to store this value back into an index, where
106514      ** it should be converted by to INTEGER again.  So omit the OP_RealAffinity
106515      ** opcode if it is present */
106516      sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
106517    }
106518    if( regOut ){
106519      sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
106520      if( pIdx->pTable->pSelect ){
106521        const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx);
106522        sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
106523      }
106524    }
106525    sqlite3ReleaseTempRange(pParse, regBase, nCol);
106526    return regBase;
106527  }
106528  
106529  /*
106530  ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
106531  ** because it was a partial index, then this routine should be called to
106532  ** resolve that label.
106533  */
106534  SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
106535    if( iLabel ){
106536      sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
106537      sqlite3ExprCachePop(pParse);
106538    }
106539  }
106540  
106541  /************** End of delete.c **********************************************/
106542  /************** Begin file func.c ********************************************/
106543  /*
106544  ** 2002 February 23
106545  **
106546  ** The author disclaims copyright to this source code.  In place of
106547  ** a legal notice, here is a blessing:
106548  **
106549  **    May you do good and not evil.
106550  **    May you find forgiveness for yourself and forgive others.
106551  **    May you share freely, never taking more than you give.
106552  **
106553  *************************************************************************
106554  ** This file contains the C-language implementations for many of the SQL
106555  ** functions of SQLite.  (Some function, and in particular the date and
106556  ** time functions, are implemented separately.)
106557  */
106558  /* #include "sqliteInt.h" */
106559  /* #include <stdlib.h> */
106560  /* #include <assert.h> */
106561  /* #include "vdbeInt.h" */
106562  
106563  /*
106564  ** Return the collating function associated with a function.
106565  */
106566  static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
106567    VdbeOp *pOp;
106568    assert( context->pVdbe!=0 );
106569    pOp = &context->pVdbe->aOp[context->iOp-1];
106570    assert( pOp->opcode==OP_CollSeq );
106571    assert( pOp->p4type==P4_COLLSEQ );
106572    return pOp->p4.pColl;
106573  }
106574  
106575  /*
106576  ** Indicate that the accumulator load should be skipped on this
106577  ** iteration of the aggregate loop.
106578  */
106579  static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
106580    context->skipFlag = 1;
106581  }
106582  
106583  /*
106584  ** Implementation of the non-aggregate min() and max() functions
106585  */
106586  static void minmaxFunc(
106587    sqlite3_context *context,
106588    int argc,
106589    sqlite3_value **argv
106590  ){
106591    int i;
106592    int mask;    /* 0 for min() or 0xffffffff for max() */
106593    int iBest;
106594    CollSeq *pColl;
106595  
106596    assert( argc>1 );
106597    mask = sqlite3_user_data(context)==0 ? 0 : -1;
106598    pColl = sqlite3GetFuncCollSeq(context);
106599    assert( pColl );
106600    assert( mask==-1 || mask==0 );
106601    iBest = 0;
106602    if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
106603    for(i=1; i<argc; i++){
106604      if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
106605      if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
106606        testcase( mask==0 );
106607        iBest = i;
106608      }
106609    }
106610    sqlite3_result_value(context, argv[iBest]);
106611  }
106612  
106613  /*
106614  ** Return the type of the argument.
106615  */
106616  static void typeofFunc(
106617    sqlite3_context *context,
106618    int NotUsed,
106619    sqlite3_value **argv
106620  ){
106621    static const char *azType[] = { "integer", "real", "text", "blob", "null" };
106622    int i = sqlite3_value_type(argv[0]) - 1;
106623    UNUSED_PARAMETER(NotUsed);
106624    assert( i>=0 && i<ArraySize(azType) );
106625    assert( SQLITE_INTEGER==1 );
106626    assert( SQLITE_FLOAT==2 );
106627    assert( SQLITE_TEXT==3 );
106628    assert( SQLITE_BLOB==4 );
106629    assert( SQLITE_NULL==5 );
106630    /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns
106631    ** the datatype code for the initial datatype of the sqlite3_value object
106632    ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT,
106633    ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */
106634    sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);
106635  }
106636  
106637  
106638  /*
106639  ** Implementation of the length() function
106640  */
106641  static void lengthFunc(
106642    sqlite3_context *context,
106643    int argc,
106644    sqlite3_value **argv
106645  ){
106646    int len;
106647  
106648    assert( argc==1 );
106649    UNUSED_PARAMETER(argc);
106650    switch( sqlite3_value_type(argv[0]) ){
106651      case SQLITE_BLOB:
106652      case SQLITE_INTEGER:
106653      case SQLITE_FLOAT: {
106654        sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
106655        break;
106656      }
106657      case SQLITE_TEXT: {
106658        const unsigned char *z = sqlite3_value_text(argv[0]);
106659        if( z==0 ) return;
106660        len = 0;
106661        while( *z ){
106662          len++;
106663          SQLITE_SKIP_UTF8(z);
106664        }
106665        sqlite3_result_int(context, len);
106666        break;
106667      }
106668      default: {
106669        sqlite3_result_null(context);
106670        break;
106671      }
106672    }
106673  }
106674  
106675  /*
106676  ** Implementation of the abs() function.
106677  **
106678  ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
106679  ** the numeric argument X. 
106680  */
106681  static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
106682    assert( argc==1 );
106683    UNUSED_PARAMETER(argc);
106684    switch( sqlite3_value_type(argv[0]) ){
106685      case SQLITE_INTEGER: {
106686        i64 iVal = sqlite3_value_int64(argv[0]);
106687        if( iVal<0 ){
106688          if( iVal==SMALLEST_INT64 ){
106689            /* IMP: R-31676-45509 If X is the integer -9223372036854775808
106690            ** then abs(X) throws an integer overflow error since there is no
106691            ** equivalent positive 64-bit two complement value. */
106692            sqlite3_result_error(context, "integer overflow", -1);
106693            return;
106694          }
106695          iVal = -iVal;
106696        } 
106697        sqlite3_result_int64(context, iVal);
106698        break;
106699      }
106700      case SQLITE_NULL: {
106701        /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
106702        sqlite3_result_null(context);
106703        break;
106704      }
106705      default: {
106706        /* Because sqlite3_value_double() returns 0.0 if the argument is not
106707        ** something that can be converted into a number, we have:
106708        ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
106709        ** that cannot be converted to a numeric value.
106710        */
106711        double rVal = sqlite3_value_double(argv[0]);
106712        if( rVal<0 ) rVal = -rVal;
106713        sqlite3_result_double(context, rVal);
106714        break;
106715      }
106716    }
106717  }
106718  
106719  /*
106720  ** Implementation of the instr() function.
106721  **
106722  ** instr(haystack,needle) finds the first occurrence of needle
106723  ** in haystack and returns the number of previous characters plus 1,
106724  ** or 0 if needle does not occur within haystack.
106725  **
106726  ** If both haystack and needle are BLOBs, then the result is one more than
106727  ** the number of bytes in haystack prior to the first occurrence of needle,
106728  ** or 0 if needle never occurs in haystack.
106729  */
106730  static void instrFunc(
106731    sqlite3_context *context,
106732    int argc,
106733    sqlite3_value **argv
106734  ){
106735    const unsigned char *zHaystack;
106736    const unsigned char *zNeedle;
106737    int nHaystack;
106738    int nNeedle;
106739    int typeHaystack, typeNeedle;
106740    int N = 1;
106741    int isText;
106742  
106743    UNUSED_PARAMETER(argc);
106744    typeHaystack = sqlite3_value_type(argv[0]);
106745    typeNeedle = sqlite3_value_type(argv[1]);
106746    if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
106747    nHaystack = sqlite3_value_bytes(argv[0]);
106748    nNeedle = sqlite3_value_bytes(argv[1]);
106749    if( nNeedle>0 ){
106750      if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
106751        zHaystack = sqlite3_value_blob(argv[0]);
106752        zNeedle = sqlite3_value_blob(argv[1]);
106753        isText = 0;
106754      }else{
106755        zHaystack = sqlite3_value_text(argv[0]);
106756        zNeedle = sqlite3_value_text(argv[1]);
106757        isText = 1;
106758      }
106759      if( zNeedle==0 || (nHaystack && zHaystack==0) ) return;
106760      while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
106761        N++;
106762        do{
106763          nHaystack--;
106764          zHaystack++;
106765        }while( isText && (zHaystack[0]&0xc0)==0x80 );
106766      }
106767      if( nNeedle>nHaystack ) N = 0;
106768    }
106769    sqlite3_result_int(context, N);
106770  }
106771  
106772  /*
106773  ** Implementation of the printf() function.
106774  */
106775  static void printfFunc(
106776    sqlite3_context *context,
106777    int argc,
106778    sqlite3_value **argv
106779  ){
106780    PrintfArguments x;
106781    StrAccum str;
106782    const char *zFormat;
106783    int n;
106784    sqlite3 *db = sqlite3_context_db_handle(context);
106785  
106786    if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
106787      x.nArg = argc-1;
106788      x.nUsed = 0;
106789      x.apArg = argv+1;
106790      sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
106791      str.printfFlags = SQLITE_PRINTF_SQLFUNC;
106792      sqlite3XPrintf(&str, zFormat, &x);
106793      n = str.nChar;
106794      sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
106795                          SQLITE_DYNAMIC);
106796    }
106797  }
106798  
106799  /*
106800  ** Implementation of the substr() function.
106801  **
106802  ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
106803  ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
106804  ** of x.  If x is text, then we actually count UTF-8 characters.
106805  ** If x is a blob, then we count bytes.
106806  **
106807  ** If p1 is negative, then we begin abs(p1) from the end of x[].
106808  **
106809  ** If p2 is negative, return the p2 characters preceding p1.
106810  */
106811  static void substrFunc(
106812    sqlite3_context *context,
106813    int argc,
106814    sqlite3_value **argv
106815  ){
106816    const unsigned char *z;
106817    const unsigned char *z2;
106818    int len;
106819    int p0type;
106820    i64 p1, p2;
106821    int negP2 = 0;
106822  
106823    assert( argc==3 || argc==2 );
106824    if( sqlite3_value_type(argv[1])==SQLITE_NULL
106825     || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
106826    ){
106827      return;
106828    }
106829    p0type = sqlite3_value_type(argv[0]);
106830    p1 = sqlite3_value_int(argv[1]);
106831    if( p0type==SQLITE_BLOB ){
106832      len = sqlite3_value_bytes(argv[0]);
106833      z = sqlite3_value_blob(argv[0]);
106834      if( z==0 ) return;
106835      assert( len==sqlite3_value_bytes(argv[0]) );
106836    }else{
106837      z = sqlite3_value_text(argv[0]);
106838      if( z==0 ) return;
106839      len = 0;
106840      if( p1<0 ){
106841        for(z2=z; *z2; len++){
106842          SQLITE_SKIP_UTF8(z2);
106843        }
106844      }
106845    }
106846  #ifdef SQLITE_SUBSTR_COMPATIBILITY
106847    /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
106848    ** as substr(X,1,N) - it returns the first N characters of X.  This
106849    ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
106850    ** from 2009-02-02 for compatibility of applications that exploited the
106851    ** old buggy behavior. */
106852    if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
106853  #endif
106854    if( argc==3 ){
106855      p2 = sqlite3_value_int(argv[2]);
106856      if( p2<0 ){
106857        p2 = -p2;
106858        negP2 = 1;
106859      }
106860    }else{
106861      p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
106862    }
106863    if( p1<0 ){
106864      p1 += len;
106865      if( p1<0 ){
106866        p2 += p1;
106867        if( p2<0 ) p2 = 0;
106868        p1 = 0;
106869      }
106870    }else if( p1>0 ){
106871      p1--;
106872    }else if( p2>0 ){
106873      p2--;
106874    }
106875    if( negP2 ){
106876      p1 -= p2;
106877      if( p1<0 ){
106878        p2 += p1;
106879        p1 = 0;
106880      }
106881    }
106882    assert( p1>=0 && p2>=0 );
106883    if( p0type!=SQLITE_BLOB ){
106884      while( *z && p1 ){
106885        SQLITE_SKIP_UTF8(z);
106886        p1--;
106887      }
106888      for(z2=z; *z2 && p2; p2--){
106889        SQLITE_SKIP_UTF8(z2);
106890      }
106891      sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
106892                            SQLITE_UTF8);
106893    }else{
106894      if( p1+p2>len ){
106895        p2 = len-p1;
106896        if( p2<0 ) p2 = 0;
106897      }
106898      sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
106899    }
106900  }
106901  
106902  /*
106903  ** Implementation of the round() function
106904  */
106905  #ifndef SQLITE_OMIT_FLOATING_POINT
106906  static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
106907    int n = 0;
106908    double r;
106909    char *zBuf;
106910    assert( argc==1 || argc==2 );
106911    if( argc==2 ){
106912      if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
106913      n = sqlite3_value_int(argv[1]);
106914      if( n>30 ) n = 30;
106915      if( n<0 ) n = 0;
106916    }
106917    if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
106918    r = sqlite3_value_double(argv[0]);
106919    /* If Y==0 and X will fit in a 64-bit int,
106920    ** handle the rounding directly,
106921    ** otherwise use printf.
106922    */
106923    if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
106924      r = (double)((sqlite_int64)(r+0.5));
106925    }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
106926      r = -(double)((sqlite_int64)((-r)+0.5));
106927    }else{
106928      zBuf = sqlite3_mprintf("%.*f",n,r);
106929      if( zBuf==0 ){
106930        sqlite3_result_error_nomem(context);
106931        return;
106932      }
106933      sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
106934      sqlite3_free(zBuf);
106935    }
106936    sqlite3_result_double(context, r);
106937  }
106938  #endif
106939  
106940  /*
106941  ** Allocate nByte bytes of space using sqlite3Malloc(). If the
106942  ** allocation fails, call sqlite3_result_error_nomem() to notify
106943  ** the database handle that malloc() has failed and return NULL.
106944  ** If nByte is larger than the maximum string or blob length, then
106945  ** raise an SQLITE_TOOBIG exception and return NULL.
106946  */
106947  static void *contextMalloc(sqlite3_context *context, i64 nByte){
106948    char *z;
106949    sqlite3 *db = sqlite3_context_db_handle(context);
106950    assert( nByte>0 );
106951    testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
106952    testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
106953    if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
106954      sqlite3_result_error_toobig(context);
106955      z = 0;
106956    }else{
106957      z = sqlite3Malloc(nByte);
106958      if( !z ){
106959        sqlite3_result_error_nomem(context);
106960      }
106961    }
106962    return z;
106963  }
106964  
106965  /*
106966  ** Implementation of the upper() and lower() SQL functions.
106967  */
106968  static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
106969    char *z1;
106970    const char *z2;
106971    int i, n;
106972    UNUSED_PARAMETER(argc);
106973    z2 = (char*)sqlite3_value_text(argv[0]);
106974    n = sqlite3_value_bytes(argv[0]);
106975    /* Verify that the call to _bytes() does not invalidate the _text() pointer */
106976    assert( z2==(char*)sqlite3_value_text(argv[0]) );
106977    if( z2 ){
106978      z1 = contextMalloc(context, ((i64)n)+1);
106979      if( z1 ){
106980        for(i=0; i<n; i++){
106981          z1[i] = (char)sqlite3Toupper(z2[i]);
106982        }
106983        sqlite3_result_text(context, z1, n, sqlite3_free);
106984      }
106985    }
106986  }
106987  static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
106988    char *z1;
106989    const char *z2;
106990    int i, n;
106991    UNUSED_PARAMETER(argc);
106992    z2 = (char*)sqlite3_value_text(argv[0]);
106993    n = sqlite3_value_bytes(argv[0]);
106994    /* Verify that the call to _bytes() does not invalidate the _text() pointer */
106995    assert( z2==(char*)sqlite3_value_text(argv[0]) );
106996    if( z2 ){
106997      z1 = contextMalloc(context, ((i64)n)+1);
106998      if( z1 ){
106999        for(i=0; i<n; i++){
107000          z1[i] = sqlite3Tolower(z2[i]);
107001        }
107002        sqlite3_result_text(context, z1, n, sqlite3_free);
107003      }
107004    }
107005  }
107006  
107007  /*
107008  ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
107009  ** as VDBE code so that unused argument values do not have to be computed.
107010  ** However, we still need some kind of function implementation for this
107011  ** routines in the function table.  The noopFunc macro provides this.
107012  ** noopFunc will never be called so it doesn't matter what the implementation
107013  ** is.  We might as well use the "version()" function as a substitute.
107014  */
107015  #define noopFunc versionFunc   /* Substitute function - never called */
107016  
107017  /*
107018  ** Implementation of random().  Return a random integer.  
107019  */
107020  static void randomFunc(
107021    sqlite3_context *context,
107022    int NotUsed,
107023    sqlite3_value **NotUsed2
107024  ){
107025    sqlite_int64 r;
107026    UNUSED_PARAMETER2(NotUsed, NotUsed2);
107027    sqlite3_randomness(sizeof(r), &r);
107028    if( r<0 ){
107029      /* We need to prevent a random number of 0x8000000000000000 
107030      ** (or -9223372036854775808) since when you do abs() of that
107031      ** number of you get the same value back again.  To do this
107032      ** in a way that is testable, mask the sign bit off of negative
107033      ** values, resulting in a positive value.  Then take the 
107034      ** 2s complement of that positive value.  The end result can
107035      ** therefore be no less than -9223372036854775807.
107036      */
107037      r = -(r & LARGEST_INT64);
107038    }
107039    sqlite3_result_int64(context, r);
107040  }
107041  
107042  /*
107043  ** Implementation of randomblob(N).  Return a random blob
107044  ** that is N bytes long.
107045  */
107046  static void randomBlob(
107047    sqlite3_context *context,
107048    int argc,
107049    sqlite3_value **argv
107050  ){
107051    int n;
107052    unsigned char *p;
107053    assert( argc==1 );
107054    UNUSED_PARAMETER(argc);
107055    n = sqlite3_value_int(argv[0]);
107056    if( n<1 ){
107057      n = 1;
107058    }
107059    p = contextMalloc(context, n);
107060    if( p ){
107061      sqlite3_randomness(n, p);
107062      sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
107063    }
107064  }
107065  
107066  /*
107067  ** Implementation of the last_insert_rowid() SQL function.  The return
107068  ** value is the same as the sqlite3_last_insert_rowid() API function.
107069  */
107070  static void last_insert_rowid(
107071    sqlite3_context *context, 
107072    int NotUsed, 
107073    sqlite3_value **NotUsed2
107074  ){
107075    sqlite3 *db = sqlite3_context_db_handle(context);
107076    UNUSED_PARAMETER2(NotUsed, NotUsed2);
107077    /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
107078    ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
107079    ** function. */
107080    sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
107081  }
107082  
107083  /*
107084  ** Implementation of the changes() SQL function.
107085  **
107086  ** IMP: R-62073-11209 The changes() SQL function is a wrapper
107087  ** around the sqlite3_changes() C/C++ function and hence follows the same
107088  ** rules for counting changes.
107089  */
107090  static void changes(
107091    sqlite3_context *context,
107092    int NotUsed,
107093    sqlite3_value **NotUsed2
107094  ){
107095    sqlite3 *db = sqlite3_context_db_handle(context);
107096    UNUSED_PARAMETER2(NotUsed, NotUsed2);
107097    sqlite3_result_int(context, sqlite3_changes(db));
107098  }
107099  
107100  /*
107101  ** Implementation of the total_changes() SQL function.  The return value is
107102  ** the same as the sqlite3_total_changes() API function.
107103  */
107104  static void total_changes(
107105    sqlite3_context *context,
107106    int NotUsed,
107107    sqlite3_value **NotUsed2
107108  ){
107109    sqlite3 *db = sqlite3_context_db_handle(context);
107110    UNUSED_PARAMETER2(NotUsed, NotUsed2);
107111    /* IMP: R-52756-41993 This function is a wrapper around the
107112    ** sqlite3_total_changes() C/C++ interface. */
107113    sqlite3_result_int(context, sqlite3_total_changes(db));
107114  }
107115  
107116  /*
107117  ** A structure defining how to do GLOB-style comparisons.
107118  */
107119  struct compareInfo {
107120    u8 matchAll;          /* "*" or "%" */
107121    u8 matchOne;          /* "?" or "_" */
107122    u8 matchSet;          /* "[" or 0 */
107123    u8 noCase;            /* true to ignore case differences */
107124  };
107125  
107126  /*
107127  ** For LIKE and GLOB matching on EBCDIC machines, assume that every
107128  ** character is exactly one byte in size.  Also, provde the Utf8Read()
107129  ** macro for fast reading of the next character in the common case where
107130  ** the next character is ASCII.
107131  */
107132  #if defined(SQLITE_EBCDIC)
107133  # define sqlite3Utf8Read(A)        (*((*A)++))
107134  # define Utf8Read(A)               (*(A++))
107135  #else
107136  # define Utf8Read(A)               (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
107137  #endif
107138  
107139  static const struct compareInfo globInfo = { '*', '?', '[', 0 };
107140  /* The correct SQL-92 behavior is for the LIKE operator to ignore
107141  ** case.  Thus  'a' LIKE 'A' would be true. */
107142  static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
107143  /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
107144  ** is case sensitive causing 'a' LIKE 'A' to be false */
107145  static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
107146  
107147  /*
107148  ** Possible error returns from patternMatch()
107149  */
107150  #define SQLITE_MATCH             0
107151  #define SQLITE_NOMATCH           1
107152  #define SQLITE_NOWILDCARDMATCH   2
107153  
107154  /*
107155  ** Compare two UTF-8 strings for equality where the first string is
107156  ** a GLOB or LIKE expression.  Return values:
107157  **
107158  **    SQLITE_MATCH:            Match
107159  **    SQLITE_NOMATCH:          No match
107160  **    SQLITE_NOWILDCARDMATCH:  No match in spite of having * or % wildcards.
107161  **
107162  ** Globbing rules:
107163  **
107164  **      '*'       Matches any sequence of zero or more characters.
107165  **
107166  **      '?'       Matches exactly one character.
107167  **
107168  **     [...]      Matches one character from the enclosed list of
107169  **                characters.
107170  **
107171  **     [^...]     Matches one character not in the enclosed list.
107172  **
107173  ** With the [...] and [^...] matching, a ']' character can be included
107174  ** in the list by making it the first character after '[' or '^'.  A
107175  ** range of characters can be specified using '-'.  Example:
107176  ** "[a-z]" matches any single lower-case letter.  To match a '-', make
107177  ** it the last character in the list.
107178  **
107179  ** Like matching rules:
107180  ** 
107181  **      '%'       Matches any sequence of zero or more characters
107182  **
107183  ***     '_'       Matches any one character
107184  **
107185  **      Ec        Where E is the "esc" character and c is any other
107186  **                character, including '%', '_', and esc, match exactly c.
107187  **
107188  ** The comments within this routine usually assume glob matching.
107189  **
107190  ** This routine is usually quick, but can be N**2 in the worst case.
107191  */
107192  static int patternCompare(
107193    const u8 *zPattern,              /* The glob pattern */
107194    const u8 *zString,               /* The string to compare against the glob */
107195    const struct compareInfo *pInfo, /* Information about how to do the compare */
107196    u32 matchOther                   /* The escape char (LIKE) or '[' (GLOB) */
107197  ){
107198    u32 c, c2;                       /* Next pattern and input string chars */
107199    u32 matchOne = pInfo->matchOne;  /* "?" or "_" */
107200    u32 matchAll = pInfo->matchAll;  /* "*" or "%" */
107201    u8 noCase = pInfo->noCase;       /* True if uppercase==lowercase */
107202    const u8 *zEscaped = 0;          /* One past the last escaped input char */
107203    
107204    while( (c = Utf8Read(zPattern))!=0 ){
107205      if( c==matchAll ){  /* Match "*" */
107206        /* Skip over multiple "*" characters in the pattern.  If there
107207        ** are also "?" characters, skip those as well, but consume a
107208        ** single character of the input string for each "?" skipped */
107209        while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
107210          if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
107211            return SQLITE_NOWILDCARDMATCH;
107212          }
107213        }
107214        if( c==0 ){
107215          return SQLITE_MATCH;   /* "*" at the end of the pattern matches */
107216        }else if( c==matchOther ){
107217          if( pInfo->matchSet==0 ){
107218            c = sqlite3Utf8Read(&zPattern);
107219            if( c==0 ) return SQLITE_NOWILDCARDMATCH;
107220          }else{
107221            /* "[...]" immediately follows the "*".  We have to do a slow
107222            ** recursive search in this case, but it is an unusual case. */
107223            assert( matchOther<0x80 );  /* '[' is a single-byte character */
107224            while( *zString ){
107225              int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
107226              if( bMatch!=SQLITE_NOMATCH ) return bMatch;
107227              SQLITE_SKIP_UTF8(zString);
107228            }
107229            return SQLITE_NOWILDCARDMATCH;
107230          }
107231        }
107232  
107233        /* At this point variable c contains the first character of the
107234        ** pattern string past the "*".  Search in the input string for the
107235        ** first matching character and recursively continue the match from
107236        ** that point.
107237        **
107238        ** For a case-insensitive search, set variable cx to be the same as
107239        ** c but in the other case and search the input string for either
107240        ** c or cx.
107241        */
107242        if( c<=0x80 ){
107243          u32 cx;
107244          int bMatch;
107245          if( noCase ){
107246            cx = sqlite3Toupper(c);
107247            c = sqlite3Tolower(c);
107248          }else{
107249            cx = c;
107250          }
107251          while( (c2 = *(zString++))!=0 ){
107252            if( c2!=c && c2!=cx ) continue;
107253            bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
107254            if( bMatch!=SQLITE_NOMATCH ) return bMatch;
107255          }
107256        }else{
107257          int bMatch;
107258          while( (c2 = Utf8Read(zString))!=0 ){
107259            if( c2!=c ) continue;
107260            bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
107261            if( bMatch!=SQLITE_NOMATCH ) return bMatch;
107262          }
107263        }
107264        return SQLITE_NOWILDCARDMATCH;
107265      }
107266      if( c==matchOther ){
107267        if( pInfo->matchSet==0 ){
107268          c = sqlite3Utf8Read(&zPattern);
107269          if( c==0 ) return SQLITE_NOMATCH;
107270          zEscaped = zPattern;
107271        }else{
107272          u32 prior_c = 0;
107273          int seen = 0;
107274          int invert = 0;
107275          c = sqlite3Utf8Read(&zString);
107276          if( c==0 ) return SQLITE_NOMATCH;
107277          c2 = sqlite3Utf8Read(&zPattern);
107278          if( c2=='^' ){
107279            invert = 1;
107280            c2 = sqlite3Utf8Read(&zPattern);
107281          }
107282          if( c2==']' ){
107283            if( c==']' ) seen = 1;
107284            c2 = sqlite3Utf8Read(&zPattern);
107285          }
107286          while( c2 && c2!=']' ){
107287            if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
107288              c2 = sqlite3Utf8Read(&zPattern);
107289              if( c>=prior_c && c<=c2 ) seen = 1;
107290              prior_c = 0;
107291            }else{
107292              if( c==c2 ){
107293                seen = 1;
107294              }
107295              prior_c = c2;
107296            }
107297            c2 = sqlite3Utf8Read(&zPattern);
107298          }
107299          if( c2==0 || (seen ^ invert)==0 ){
107300            return SQLITE_NOMATCH;
107301          }
107302          continue;
107303        }
107304      }
107305      c2 = Utf8Read(zString);
107306      if( c==c2 ) continue;
107307      if( noCase  && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
107308        continue;
107309      }
107310      if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
107311      return SQLITE_NOMATCH;
107312    }
107313    return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;
107314  }
107315  
107316  /*
107317  ** The sqlite3_strglob() interface.  Return 0 on a match (like strcmp()) and
107318  ** non-zero if there is no match.
107319  */
107320  SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
107321    return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');
107322  }
107323  
107324  /*
107325  ** The sqlite3_strlike() interface.  Return 0 on a match and non-zero for
107326  ** a miss - like strcmp().
107327  */
107328  SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
107329    return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);
107330  }
107331  
107332  /*
107333  ** Count the number of times that the LIKE operator (or GLOB which is
107334  ** just a variation of LIKE) gets called.  This is used for testing
107335  ** only.
107336  */
107337  #ifdef SQLITE_TEST
107338  SQLITE_API int sqlite3_like_count = 0;
107339  #endif
107340  
107341  
107342  /*
107343  ** Implementation of the like() SQL function.  This function implements
107344  ** the build-in LIKE operator.  The first argument to the function is the
107345  ** pattern and the second argument is the string.  So, the SQL statements:
107346  **
107347  **       A LIKE B
107348  **
107349  ** is implemented as like(B,A).
107350  **
107351  ** This same function (with a different compareInfo structure) computes
107352  ** the GLOB operator.
107353  */
107354  static void likeFunc(
107355    sqlite3_context *context, 
107356    int argc, 
107357    sqlite3_value **argv
107358  ){
107359    const unsigned char *zA, *zB;
107360    u32 escape;
107361    int nPat;
107362    sqlite3 *db = sqlite3_context_db_handle(context);
107363    struct compareInfo *pInfo = sqlite3_user_data(context);
107364  
107365  #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
107366    if( sqlite3_value_type(argv[0])==SQLITE_BLOB
107367     || sqlite3_value_type(argv[1])==SQLITE_BLOB
107368    ){
107369  #ifdef SQLITE_TEST
107370      sqlite3_like_count++;
107371  #endif
107372      sqlite3_result_int(context, 0);
107373      return;
107374    }
107375  #endif
107376    zB = sqlite3_value_text(argv[0]);
107377    zA = sqlite3_value_text(argv[1]);
107378  
107379    /* Limit the length of the LIKE or GLOB pattern to avoid problems
107380    ** of deep recursion and N*N behavior in patternCompare().
107381    */
107382    nPat = sqlite3_value_bytes(argv[0]);
107383    testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
107384    testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
107385    if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
107386      sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
107387      return;
107388    }
107389    assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
107390  
107391    if( argc==3 ){
107392      /* The escape character string must consist of a single UTF-8 character.
107393      ** Otherwise, return an error.
107394      */
107395      const unsigned char *zEsc = sqlite3_value_text(argv[2]);
107396      if( zEsc==0 ) return;
107397      if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
107398        sqlite3_result_error(context, 
107399            "ESCAPE expression must be a single character", -1);
107400        return;
107401      }
107402      escape = sqlite3Utf8Read(&zEsc);
107403    }else{
107404      escape = pInfo->matchSet;
107405    }
107406    if( zA && zB ){
107407  #ifdef SQLITE_TEST
107408      sqlite3_like_count++;
107409  #endif
107410      sqlite3_result_int(context,
107411                        patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);
107412    }
107413  }
107414  
107415  /*
107416  ** Implementation of the NULLIF(x,y) function.  The result is the first
107417  ** argument if the arguments are different.  The result is NULL if the
107418  ** arguments are equal to each other.
107419  */
107420  static void nullifFunc(
107421    sqlite3_context *context,
107422    int NotUsed,
107423    sqlite3_value **argv
107424  ){
107425    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
107426    UNUSED_PARAMETER(NotUsed);
107427    if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
107428      sqlite3_result_value(context, argv[0]);
107429    }
107430  }
107431  
107432  /*
107433  ** Implementation of the sqlite_version() function.  The result is the version
107434  ** of the SQLite library that is running.
107435  */
107436  static void versionFunc(
107437    sqlite3_context *context,
107438    int NotUsed,
107439    sqlite3_value **NotUsed2
107440  ){
107441    UNUSED_PARAMETER2(NotUsed, NotUsed2);
107442    /* IMP: R-48699-48617 This function is an SQL wrapper around the
107443    ** sqlite3_libversion() C-interface. */
107444    sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
107445  }
107446  
107447  /*
107448  ** Implementation of the sqlite_source_id() function. The result is a string
107449  ** that identifies the particular version of the source code used to build
107450  ** SQLite.
107451  */
107452  static void sourceidFunc(
107453    sqlite3_context *context,
107454    int NotUsed,
107455    sqlite3_value **NotUsed2
107456  ){
107457    UNUSED_PARAMETER2(NotUsed, NotUsed2);
107458    /* IMP: R-24470-31136 This function is an SQL wrapper around the
107459    ** sqlite3_sourceid() C interface. */
107460    sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
107461  }
107462  
107463  /*
107464  ** Implementation of the sqlite_log() function.  This is a wrapper around
107465  ** sqlite3_log().  The return value is NULL.  The function exists purely for
107466  ** its side-effects.
107467  */
107468  static void errlogFunc(
107469    sqlite3_context *context,
107470    int argc,
107471    sqlite3_value **argv
107472  ){
107473    UNUSED_PARAMETER(argc);
107474    UNUSED_PARAMETER(context);
107475    sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
107476  }
107477  
107478  /*
107479  ** Implementation of the sqlite_compileoption_used() function.
107480  ** The result is an integer that identifies if the compiler option
107481  ** was used to build SQLite.
107482  */
107483  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
107484  static void compileoptionusedFunc(
107485    sqlite3_context *context,
107486    int argc,
107487    sqlite3_value **argv
107488  ){
107489    const char *zOptName;
107490    assert( argc==1 );
107491    UNUSED_PARAMETER(argc);
107492    /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
107493    ** function is a wrapper around the sqlite3_compileoption_used() C/C++
107494    ** function.
107495    */
107496    if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
107497      sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
107498    }
107499  }
107500  #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
107501  
107502  /*
107503  ** Implementation of the sqlite_compileoption_get() function. 
107504  ** The result is a string that identifies the compiler options 
107505  ** used to build SQLite.
107506  */
107507  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
107508  static void compileoptiongetFunc(
107509    sqlite3_context *context,
107510    int argc,
107511    sqlite3_value **argv
107512  ){
107513    int n;
107514    assert( argc==1 );
107515    UNUSED_PARAMETER(argc);
107516    /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
107517    ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
107518    */
107519    n = sqlite3_value_int(argv[0]);
107520    sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
107521  }
107522  #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
107523  
107524  /* Array for converting from half-bytes (nybbles) into ASCII hex
107525  ** digits. */
107526  static const char hexdigits[] = {
107527    '0', '1', '2', '3', '4', '5', '6', '7',
107528    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
107529  };
107530  
107531  /*
107532  ** Implementation of the QUOTE() function.  This function takes a single
107533  ** argument.  If the argument is numeric, the return value is the same as
107534  ** the argument.  If the argument is NULL, the return value is the string
107535  ** "NULL".  Otherwise, the argument is enclosed in single quotes with
107536  ** single-quote escapes.
107537  */
107538  static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
107539    assert( argc==1 );
107540    UNUSED_PARAMETER(argc);
107541    switch( sqlite3_value_type(argv[0]) ){
107542      case SQLITE_FLOAT: {
107543        double r1, r2;
107544        char zBuf[50];
107545        r1 = sqlite3_value_double(argv[0]);
107546        sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
107547        sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
107548        if( r1!=r2 ){
107549          sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
107550        }
107551        sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
107552        break;
107553      }
107554      case SQLITE_INTEGER: {
107555        sqlite3_result_value(context, argv[0]);
107556        break;
107557      }
107558      case SQLITE_BLOB: {
107559        char *zText = 0;
107560        char const *zBlob = sqlite3_value_blob(argv[0]);
107561        int nBlob = sqlite3_value_bytes(argv[0]);
107562        assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
107563        zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
107564        if( zText ){
107565          int i;
107566          for(i=0; i<nBlob; i++){
107567            zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
107568            zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
107569          }
107570          zText[(nBlob*2)+2] = '\'';
107571          zText[(nBlob*2)+3] = '\0';
107572          zText[0] = 'X';
107573          zText[1] = '\'';
107574          sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
107575          sqlite3_free(zText);
107576        }
107577        break;
107578      }
107579      case SQLITE_TEXT: {
107580        int i,j;
107581        u64 n;
107582        const unsigned char *zArg = sqlite3_value_text(argv[0]);
107583        char *z;
107584  
107585        if( zArg==0 ) return;
107586        for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
107587        z = contextMalloc(context, ((i64)i)+((i64)n)+3);
107588        if( z ){
107589          z[0] = '\'';
107590          for(i=0, j=1; zArg[i]; i++){
107591            z[j++] = zArg[i];
107592            if( zArg[i]=='\'' ){
107593              z[j++] = '\'';
107594            }
107595          }
107596          z[j++] = '\'';
107597          z[j] = 0;
107598          sqlite3_result_text(context, z, j, sqlite3_free);
107599        }
107600        break;
107601      }
107602      default: {
107603        assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
107604        sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
107605        break;
107606      }
107607    }
107608  }
107609  
107610  /*
107611  ** The unicode() function.  Return the integer unicode code-point value
107612  ** for the first character of the input string. 
107613  */
107614  static void unicodeFunc(
107615    sqlite3_context *context,
107616    int argc,
107617    sqlite3_value **argv
107618  ){
107619    const unsigned char *z = sqlite3_value_text(argv[0]);
107620    (void)argc;
107621    if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
107622  }
107623  
107624  /*
107625  ** The char() function takes zero or more arguments, each of which is
107626  ** an integer.  It constructs a string where each character of the string
107627  ** is the unicode character for the corresponding integer argument.
107628  */
107629  static void charFunc(
107630    sqlite3_context *context,
107631    int argc,
107632    sqlite3_value **argv
107633  ){
107634    unsigned char *z, *zOut;
107635    int i;
107636    zOut = z = sqlite3_malloc64( argc*4+1 );
107637    if( z==0 ){
107638      sqlite3_result_error_nomem(context);
107639      return;
107640    }
107641    for(i=0; i<argc; i++){
107642      sqlite3_int64 x;
107643      unsigned c;
107644      x = sqlite3_value_int64(argv[i]);
107645      if( x<0 || x>0x10ffff ) x = 0xfffd;
107646      c = (unsigned)(x & 0x1fffff);
107647      if( c<0x00080 ){
107648        *zOut++ = (u8)(c&0xFF);
107649      }else if( c<0x00800 ){
107650        *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
107651        *zOut++ = 0x80 + (u8)(c & 0x3F);
107652      }else if( c<0x10000 ){
107653        *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
107654        *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
107655        *zOut++ = 0x80 + (u8)(c & 0x3F);
107656      }else{
107657        *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
107658        *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
107659        *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
107660        *zOut++ = 0x80 + (u8)(c & 0x3F);
107661      }                                                    \
107662    }
107663    sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
107664  }
107665  
107666  /*
107667  ** The hex() function.  Interpret the argument as a blob.  Return
107668  ** a hexadecimal rendering as text.
107669  */
107670  static void hexFunc(
107671    sqlite3_context *context,
107672    int argc,
107673    sqlite3_value **argv
107674  ){
107675    int i, n;
107676    const unsigned char *pBlob;
107677    char *zHex, *z;
107678    assert( argc==1 );
107679    UNUSED_PARAMETER(argc);
107680    pBlob = sqlite3_value_blob(argv[0]);
107681    n = sqlite3_value_bytes(argv[0]);
107682    assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
107683    z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
107684    if( zHex ){
107685      for(i=0; i<n; i++, pBlob++){
107686        unsigned char c = *pBlob;
107687        *(z++) = hexdigits[(c>>4)&0xf];
107688        *(z++) = hexdigits[c&0xf];
107689      }
107690      *z = 0;
107691      sqlite3_result_text(context, zHex, n*2, sqlite3_free);
107692    }
107693  }
107694  
107695  /*
107696  ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
107697  */
107698  static void zeroblobFunc(
107699    sqlite3_context *context,
107700    int argc,
107701    sqlite3_value **argv
107702  ){
107703    i64 n;
107704    int rc;
107705    assert( argc==1 );
107706    UNUSED_PARAMETER(argc);
107707    n = sqlite3_value_int64(argv[0]);
107708    if( n<0 ) n = 0;
107709    rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
107710    if( rc ){
107711      sqlite3_result_error_code(context, rc);
107712    }
107713  }
107714  
107715  /*
107716  ** The replace() function.  Three arguments are all strings: call
107717  ** them A, B, and C. The result is also a string which is derived
107718  ** from A by replacing every occurrence of B with C.  The match
107719  ** must be exact.  Collating sequences are not used.
107720  */
107721  static void replaceFunc(
107722    sqlite3_context *context,
107723    int argc,
107724    sqlite3_value **argv
107725  ){
107726    const unsigned char *zStr;        /* The input string A */
107727    const unsigned char *zPattern;    /* The pattern string B */
107728    const unsigned char *zRep;        /* The replacement string C */
107729    unsigned char *zOut;              /* The output */
107730    int nStr;                /* Size of zStr */
107731    int nPattern;            /* Size of zPattern */
107732    int nRep;                /* Size of zRep */
107733    i64 nOut;                /* Maximum size of zOut */
107734    int loopLimit;           /* Last zStr[] that might match zPattern[] */
107735    int i, j;                /* Loop counters */
107736  
107737    assert( argc==3 );
107738    UNUSED_PARAMETER(argc);
107739    zStr = sqlite3_value_text(argv[0]);
107740    if( zStr==0 ) return;
107741    nStr = sqlite3_value_bytes(argv[0]);
107742    assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
107743    zPattern = sqlite3_value_text(argv[1]);
107744    if( zPattern==0 ){
107745      assert( sqlite3_value_type(argv[1])==SQLITE_NULL
107746              || sqlite3_context_db_handle(context)->mallocFailed );
107747      return;
107748    }
107749    if( zPattern[0]==0 ){
107750      assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
107751      sqlite3_result_value(context, argv[0]);
107752      return;
107753    }
107754    nPattern = sqlite3_value_bytes(argv[1]);
107755    assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
107756    zRep = sqlite3_value_text(argv[2]);
107757    if( zRep==0 ) return;
107758    nRep = sqlite3_value_bytes(argv[2]);
107759    assert( zRep==sqlite3_value_text(argv[2]) );
107760    nOut = nStr + 1;
107761    assert( nOut<SQLITE_MAX_LENGTH );
107762    zOut = contextMalloc(context, (i64)nOut);
107763    if( zOut==0 ){
107764      return;
107765    }
107766    loopLimit = nStr - nPattern;  
107767    for(i=j=0; i<=loopLimit; i++){
107768      if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
107769        zOut[j++] = zStr[i];
107770      }else{
107771        u8 *zOld;
107772        sqlite3 *db = sqlite3_context_db_handle(context);
107773        nOut += nRep - nPattern;
107774        testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
107775        testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
107776        if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
107777          sqlite3_result_error_toobig(context);
107778          sqlite3_free(zOut);
107779          return;
107780        }
107781        zOld = zOut;
107782        zOut = sqlite3_realloc64(zOut, (int)nOut);
107783        if( zOut==0 ){
107784          sqlite3_result_error_nomem(context);
107785          sqlite3_free(zOld);
107786          return;
107787        }
107788        memcpy(&zOut[j], zRep, nRep);
107789        j += nRep;
107790        i += nPattern-1;
107791      }
107792    }
107793    assert( j+nStr-i+1==nOut );
107794    memcpy(&zOut[j], &zStr[i], nStr-i);
107795    j += nStr - i;
107796    assert( j<=nOut );
107797    zOut[j] = 0;
107798    sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
107799  }
107800  
107801  /*
107802  ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
107803  ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
107804  */
107805  static void trimFunc(
107806    sqlite3_context *context,
107807    int argc,
107808    sqlite3_value **argv
107809  ){
107810    const unsigned char *zIn;         /* Input string */
107811    const unsigned char *zCharSet;    /* Set of characters to trim */
107812    int nIn;                          /* Number of bytes in input */
107813    int flags;                        /* 1: trimleft  2: trimright  3: trim */
107814    int i;                            /* Loop counter */
107815    unsigned char *aLen = 0;          /* Length of each character in zCharSet */
107816    unsigned char **azChar = 0;       /* Individual characters in zCharSet */
107817    int nChar;                        /* Number of characters in zCharSet */
107818  
107819    if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
107820      return;
107821    }
107822    zIn = sqlite3_value_text(argv[0]);
107823    if( zIn==0 ) return;
107824    nIn = sqlite3_value_bytes(argv[0]);
107825    assert( zIn==sqlite3_value_text(argv[0]) );
107826    if( argc==1 ){
107827      static const unsigned char lenOne[] = { 1 };
107828      static unsigned char * const azOne[] = { (u8*)" " };
107829      nChar = 1;
107830      aLen = (u8*)lenOne;
107831      azChar = (unsigned char **)azOne;
107832      zCharSet = 0;
107833    }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
107834      return;
107835    }else{
107836      const unsigned char *z;
107837      for(z=zCharSet, nChar=0; *z; nChar++){
107838        SQLITE_SKIP_UTF8(z);
107839      }
107840      if( nChar>0 ){
107841        azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
107842        if( azChar==0 ){
107843          return;
107844        }
107845        aLen = (unsigned char*)&azChar[nChar];
107846        for(z=zCharSet, nChar=0; *z; nChar++){
107847          azChar[nChar] = (unsigned char *)z;
107848          SQLITE_SKIP_UTF8(z);
107849          aLen[nChar] = (u8)(z - azChar[nChar]);
107850        }
107851      }
107852    }
107853    if( nChar>0 ){
107854      flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
107855      if( flags & 1 ){
107856        while( nIn>0 ){
107857          int len = 0;
107858          for(i=0; i<nChar; i++){
107859            len = aLen[i];
107860            if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
107861          }
107862          if( i>=nChar ) break;
107863          zIn += len;
107864          nIn -= len;
107865        }
107866      }
107867      if( flags & 2 ){
107868        while( nIn>0 ){
107869          int len = 0;
107870          for(i=0; i<nChar; i++){
107871            len = aLen[i];
107872            if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
107873          }
107874          if( i>=nChar ) break;
107875          nIn -= len;
107876        }
107877      }
107878      if( zCharSet ){
107879        sqlite3_free(azChar);
107880      }
107881    }
107882    sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
107883  }
107884  
107885  
107886  #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
107887  /*
107888  ** The "unknown" function is automatically substituted in place of
107889  ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
107890  ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
107891  ** When the "sqlite3" command-line shell is built using this functionality,
107892  ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
107893  ** involving application-defined functions to be examined in a generic
107894  ** sqlite3 shell.
107895  */
107896  static void unknownFunc(
107897    sqlite3_context *context,
107898    int argc,
107899    sqlite3_value **argv
107900  ){
107901    /* no-op */
107902  }
107903  #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
107904  
107905  
107906  /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
107907  ** is only available if the SQLITE_SOUNDEX compile-time option is used
107908  ** when SQLite is built.
107909  */
107910  #ifdef SQLITE_SOUNDEX
107911  /*
107912  ** Compute the soundex encoding of a word.
107913  **
107914  ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
107915  ** soundex encoding of the string X. 
107916  */
107917  static void soundexFunc(
107918    sqlite3_context *context,
107919    int argc,
107920    sqlite3_value **argv
107921  ){
107922    char zResult[8];
107923    const u8 *zIn;
107924    int i, j;
107925    static const unsigned char iCode[] = {
107926      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
107927      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
107928      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
107929      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
107930      0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
107931      1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
107932      0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
107933      1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
107934    };
107935    assert( argc==1 );
107936    zIn = (u8*)sqlite3_value_text(argv[0]);
107937    if( zIn==0 ) zIn = (u8*)"";
107938    for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
107939    if( zIn[i] ){
107940      u8 prevcode = iCode[zIn[i]&0x7f];
107941      zResult[0] = sqlite3Toupper(zIn[i]);
107942      for(j=1; j<4 && zIn[i]; i++){
107943        int code = iCode[zIn[i]&0x7f];
107944        if( code>0 ){
107945          if( code!=prevcode ){
107946            prevcode = code;
107947            zResult[j++] = code + '0';
107948          }
107949        }else{
107950          prevcode = 0;
107951        }
107952      }
107953      while( j<4 ){
107954        zResult[j++] = '0';
107955      }
107956      zResult[j] = 0;
107957      sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
107958    }else{
107959      /* IMP: R-64894-50321 The string "?000" is returned if the argument
107960      ** is NULL or contains no ASCII alphabetic characters. */
107961      sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
107962    }
107963  }
107964  #endif /* SQLITE_SOUNDEX */
107965  
107966  #ifndef SQLITE_OMIT_LOAD_EXTENSION
107967  /*
107968  ** A function that loads a shared-library extension then returns NULL.
107969  */
107970  static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
107971    const char *zFile = (const char *)sqlite3_value_text(argv[0]);
107972    const char *zProc;
107973    sqlite3 *db = sqlite3_context_db_handle(context);
107974    char *zErrMsg = 0;
107975  
107976    /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
107977    ** flag is set.  See the sqlite3_enable_load_extension() API.
107978    */
107979    if( (db->flags & SQLITE_LoadExtFunc)==0 ){
107980      sqlite3_result_error(context, "not authorized", -1);
107981      return;
107982    }
107983  
107984    if( argc==2 ){
107985      zProc = (const char *)sqlite3_value_text(argv[1]);
107986    }else{
107987      zProc = 0;
107988    }
107989    if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
107990      sqlite3_result_error(context, zErrMsg, -1);
107991      sqlite3_free(zErrMsg);
107992    }
107993  }
107994  #endif
107995  
107996  
107997  /*
107998  ** An instance of the following structure holds the context of a
107999  ** sum() or avg() aggregate computation.
108000  */
108001  typedef struct SumCtx SumCtx;
108002  struct SumCtx {
108003    double rSum;      /* Floating point sum */
108004    i64 iSum;         /* Integer sum */   
108005    i64 cnt;          /* Number of elements summed */
108006    u8 overflow;      /* True if integer overflow seen */
108007    u8 approx;        /* True if non-integer value was input to the sum */
108008  };
108009  
108010  /*
108011  ** Routines used to compute the sum, average, and total.
108012  **
108013  ** The SUM() function follows the (broken) SQL standard which means
108014  ** that it returns NULL if it sums over no inputs.  TOTAL returns
108015  ** 0.0 in that case.  In addition, TOTAL always returns a float where
108016  ** SUM might return an integer if it never encounters a floating point
108017  ** value.  TOTAL never fails, but SUM might through an exception if
108018  ** it overflows an integer.
108019  */
108020  static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
108021    SumCtx *p;
108022    int type;
108023    assert( argc==1 );
108024    UNUSED_PARAMETER(argc);
108025    p = sqlite3_aggregate_context(context, sizeof(*p));
108026    type = sqlite3_value_numeric_type(argv[0]);
108027    if( p && type!=SQLITE_NULL ){
108028      p->cnt++;
108029      if( type==SQLITE_INTEGER ){
108030        i64 v = sqlite3_value_int64(argv[0]);
108031        p->rSum += v;
108032        if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
108033          p->overflow = 1;
108034        }
108035      }else{
108036        p->rSum += sqlite3_value_double(argv[0]);
108037        p->approx = 1;
108038      }
108039    }
108040  }
108041  static void sumFinalize(sqlite3_context *context){
108042    SumCtx *p;
108043    p = sqlite3_aggregate_context(context, 0);
108044    if( p && p->cnt>0 ){
108045      if( p->overflow ){
108046        sqlite3_result_error(context,"integer overflow",-1);
108047      }else if( p->approx ){
108048        sqlite3_result_double(context, p->rSum);
108049      }else{
108050        sqlite3_result_int64(context, p->iSum);
108051      }
108052    }
108053  }
108054  static void avgFinalize(sqlite3_context *context){
108055    SumCtx *p;
108056    p = sqlite3_aggregate_context(context, 0);
108057    if( p && p->cnt>0 ){
108058      sqlite3_result_double(context, p->rSum/(double)p->cnt);
108059    }
108060  }
108061  static void totalFinalize(sqlite3_context *context){
108062    SumCtx *p;
108063    p = sqlite3_aggregate_context(context, 0);
108064    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
108065    sqlite3_result_double(context, p ? p->rSum : (double)0);
108066  }
108067  
108068  /*
108069  ** The following structure keeps track of state information for the
108070  ** count() aggregate function.
108071  */
108072  typedef struct CountCtx CountCtx;
108073  struct CountCtx {
108074    i64 n;
108075  };
108076  
108077  /*
108078  ** Routines to implement the count() aggregate function.
108079  */
108080  static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
108081    CountCtx *p;
108082    p = sqlite3_aggregate_context(context, sizeof(*p));
108083    if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
108084      p->n++;
108085    }
108086  
108087  #ifndef SQLITE_OMIT_DEPRECATED
108088    /* The sqlite3_aggregate_count() function is deprecated.  But just to make
108089    ** sure it still operates correctly, verify that its count agrees with our 
108090    ** internal count when using count(*) and when the total count can be
108091    ** expressed as a 32-bit integer. */
108092    assert( argc==1 || p==0 || p->n>0x7fffffff
108093            || p->n==sqlite3_aggregate_count(context) );
108094  #endif
108095  }   
108096  static void countFinalize(sqlite3_context *context){
108097    CountCtx *p;
108098    p = sqlite3_aggregate_context(context, 0);
108099    sqlite3_result_int64(context, p ? p->n : 0);
108100  }
108101  
108102  /*
108103  ** Routines to implement min() and max() aggregate functions.
108104  */
108105  static void minmaxStep(
108106    sqlite3_context *context, 
108107    int NotUsed, 
108108    sqlite3_value **argv
108109  ){
108110    Mem *pArg  = (Mem *)argv[0];
108111    Mem *pBest;
108112    UNUSED_PARAMETER(NotUsed);
108113  
108114    pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
108115    if( !pBest ) return;
108116  
108117    if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
108118      if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
108119    }else if( pBest->flags ){
108120      int max;
108121      int cmp;
108122      CollSeq *pColl = sqlite3GetFuncCollSeq(context);
108123      /* This step function is used for both the min() and max() aggregates,
108124      ** the only difference between the two being that the sense of the
108125      ** comparison is inverted. For the max() aggregate, the
108126      ** sqlite3_user_data() function returns (void *)-1. For min() it
108127      ** returns (void *)db, where db is the sqlite3* database pointer.
108128      ** Therefore the next statement sets variable 'max' to 1 for the max()
108129      ** aggregate, or 0 for min().
108130      */
108131      max = sqlite3_user_data(context)!=0;
108132      cmp = sqlite3MemCompare(pBest, pArg, pColl);
108133      if( (max && cmp<0) || (!max && cmp>0) ){
108134        sqlite3VdbeMemCopy(pBest, pArg);
108135      }else{
108136        sqlite3SkipAccumulatorLoad(context);
108137      }
108138    }else{
108139      pBest->db = sqlite3_context_db_handle(context);
108140      sqlite3VdbeMemCopy(pBest, pArg);
108141    }
108142  }
108143  static void minMaxFinalize(sqlite3_context *context){
108144    sqlite3_value *pRes;
108145    pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
108146    if( pRes ){
108147      if( pRes->flags ){
108148        sqlite3_result_value(context, pRes);
108149      }
108150      sqlite3VdbeMemRelease(pRes);
108151    }
108152  }
108153  
108154  /*
108155  ** group_concat(EXPR, ?SEPARATOR?)
108156  */
108157  static void groupConcatStep(
108158    sqlite3_context *context,
108159    int argc,
108160    sqlite3_value **argv
108161  ){
108162    const char *zVal;
108163    StrAccum *pAccum;
108164    const char *zSep;
108165    int nVal, nSep;
108166    assert( argc==1 || argc==2 );
108167    if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
108168    pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
108169  
108170    if( pAccum ){
108171      sqlite3 *db = sqlite3_context_db_handle(context);
108172      int firstTerm = pAccum->mxAlloc==0;
108173      pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
108174      if( !firstTerm ){
108175        if( argc==2 ){
108176          zSep = (char*)sqlite3_value_text(argv[1]);
108177          nSep = sqlite3_value_bytes(argv[1]);
108178        }else{
108179          zSep = ",";
108180          nSep = 1;
108181        }
108182        if( zSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
108183      }
108184      zVal = (char*)sqlite3_value_text(argv[0]);
108185      nVal = sqlite3_value_bytes(argv[0]);
108186      if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
108187    }
108188  }
108189  static void groupConcatFinalize(sqlite3_context *context){
108190    StrAccum *pAccum;
108191    pAccum = sqlite3_aggregate_context(context, 0);
108192    if( pAccum ){
108193      if( pAccum->accError==STRACCUM_TOOBIG ){
108194        sqlite3_result_error_toobig(context);
108195      }else if( pAccum->accError==STRACCUM_NOMEM ){
108196        sqlite3_result_error_nomem(context);
108197      }else{    
108198        sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
108199                            sqlite3_free);
108200      }
108201    }
108202  }
108203  
108204  /*
108205  ** This routine does per-connection function registration.  Most
108206  ** of the built-in functions above are part of the global function set.
108207  ** This routine only deals with those that are not global.
108208  */
108209  SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
108210    int rc = sqlite3_overload_function(db, "MATCH", 2);
108211    assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
108212    if( rc==SQLITE_NOMEM ){
108213      sqlite3OomFault(db);
108214    }
108215  }
108216  
108217  /*
108218  ** Set the LIKEOPT flag on the 2-argument function with the given name.
108219  */
108220  static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
108221    FuncDef *pDef;
108222    pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
108223    if( ALWAYS(pDef) ){
108224      pDef->funcFlags |= flagVal;
108225    }
108226  }
108227  
108228  /*
108229  ** Register the built-in LIKE and GLOB functions.  The caseSensitive
108230  ** parameter determines whether or not the LIKE operator is case
108231  ** sensitive.  GLOB is always case sensitive.
108232  */
108233  SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
108234    struct compareInfo *pInfo;
108235    if( caseSensitive ){
108236      pInfo = (struct compareInfo*)&likeInfoAlt;
108237    }else{
108238      pInfo = (struct compareInfo*)&likeInfoNorm;
108239    }
108240    sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
108241    sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
108242    sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
108243        (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
108244    setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
108245    setLikeOptFlag(db, "like", 
108246        caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
108247  }
108248  
108249  /*
108250  ** pExpr points to an expression which implements a function.  If
108251  ** it is appropriate to apply the LIKE optimization to that function
108252  ** then set aWc[0] through aWc[2] to the wildcard characters and the
108253  ** escape character and then return TRUE.  If the function is not a 
108254  ** LIKE-style function then return FALSE.
108255  **
108256  ** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE
108257  ** operator if c is a string literal that is exactly one byte in length.
108258  ** That one byte is stored in aWc[3].  aWc[3] is set to zero if there is
108259  ** no ESCAPE clause.
108260  **
108261  ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
108262  ** the function (default for LIKE).  If the function makes the distinction
108263  ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
108264  ** false.
108265  */
108266  SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
108267    FuncDef *pDef;
108268    int nExpr;
108269    if( pExpr->op!=TK_FUNCTION || !pExpr->x.pList ){
108270      return 0;
108271    }
108272    assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
108273    nExpr = pExpr->x.pList->nExpr;
108274    pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0);
108275    if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
108276      return 0;
108277    }
108278    if( nExpr<3 ){
108279      aWc[3] = 0;
108280    }else{
108281      Expr *pEscape = pExpr->x.pList->a[2].pExpr;
108282      char *zEscape;
108283      if( pEscape->op!=TK_STRING ) return 0;
108284      zEscape = pEscape->u.zToken;
108285      if( zEscape[0]==0 || zEscape[1]!=0 ) return 0;
108286      aWc[3] = zEscape[0];
108287    }
108288  
108289    /* The memcpy() statement assumes that the wildcard characters are
108290    ** the first three statements in the compareInfo structure.  The
108291    ** asserts() that follow verify that assumption
108292    */
108293    memcpy(aWc, pDef->pUserData, 3);
108294    assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
108295    assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
108296    assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
108297    *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
108298    return 1;
108299  }
108300  
108301  /*
108302  ** All of the FuncDef structures in the aBuiltinFunc[] array above
108303  ** to the global function hash table.  This occurs at start-time (as
108304  ** a consequence of calling sqlite3_initialize()).
108305  **
108306  ** After this routine runs
108307  */
108308  SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
108309    /*
108310    ** The following array holds FuncDef structures for all of the functions
108311    ** defined in this file.
108312    **
108313    ** The array cannot be constant since changes are made to the
108314    ** FuncDef.pHash elements at start-time.  The elements of this array
108315    ** are read-only after initialization is complete.
108316    **
108317    ** For peak efficiency, put the most frequently used function last.
108318    */
108319    static FuncDef aBuiltinFunc[] = {
108320  #ifdef SQLITE_SOUNDEX
108321      FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
108322  #endif
108323  #ifndef SQLITE_OMIT_LOAD_EXTENSION
108324      VFUNCTION(load_extension,    1, 0, 0, loadExt          ),
108325      VFUNCTION(load_extension,    2, 0, 0, loadExt          ),
108326  #endif
108327  #if SQLITE_USER_AUTHENTICATION
108328      FUNCTION(sqlite_crypt,       2, 0, 0, sqlite3CryptFunc ),
108329  #endif
108330  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
108331      DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
108332      DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
108333  #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
108334      FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
108335      FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
108336      FUNCTION2(likely,            1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
108337  #ifdef SQLITE_DEBUG
108338      FUNCTION2(affinity,          1, 0, 0, noopFunc,  SQLITE_FUNC_AFFINITY),
108339  #endif
108340      FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
108341      FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
108342      FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
108343      FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
108344      FUNCTION(trim,               1, 3, 0, trimFunc         ),
108345      FUNCTION(trim,               2, 3, 0, trimFunc         ),
108346      FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
108347      FUNCTION(min,                0, 0, 1, 0                ),
108348      AGGREGATE2(min,              1, 0, 1, minmaxStep,      minMaxFinalize,
108349                                            SQLITE_FUNC_MINMAX ),
108350      FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
108351      FUNCTION(max,                0, 1, 1, 0                ),
108352      AGGREGATE2(max,              1, 1, 1, minmaxStep,      minMaxFinalize,
108353                                            SQLITE_FUNC_MINMAX ),
108354      FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
108355      FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
108356      FUNCTION(instr,              2, 0, 0, instrFunc        ),
108357      FUNCTION(printf,            -1, 0, 0, printfFunc       ),
108358      FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
108359      FUNCTION(char,              -1, 0, 0, charFunc         ),
108360      FUNCTION(abs,                1, 0, 0, absFunc          ),
108361  #ifndef SQLITE_OMIT_FLOATING_POINT
108362      FUNCTION(round,              1, 0, 0, roundFunc        ),
108363      FUNCTION(round,              2, 0, 0, roundFunc        ),
108364  #endif
108365      FUNCTION(upper,              1, 0, 0, upperFunc        ),
108366      FUNCTION(lower,              1, 0, 0, lowerFunc        ),
108367      FUNCTION(hex,                1, 0, 0, hexFunc          ),
108368      FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
108369      VFUNCTION(random,            0, 0, 0, randomFunc       ),
108370      VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
108371      FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
108372      DFUNCTION(sqlite_version,    0, 0, 0, versionFunc      ),
108373      DFUNCTION(sqlite_source_id,  0, 0, 0, sourceidFunc     ),
108374      FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
108375      FUNCTION(quote,              1, 0, 0, quoteFunc        ),
108376      VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
108377      VFUNCTION(changes,           0, 0, 0, changes          ),
108378      VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
108379      FUNCTION(replace,            3, 0, 0, replaceFunc      ),
108380      FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
108381      FUNCTION(substr,             2, 0, 0, substrFunc       ),
108382      FUNCTION(substr,             3, 0, 0, substrFunc       ),
108383      AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
108384      AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
108385      AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
108386      AGGREGATE2(count,            0, 0, 0, countStep,       countFinalize,
108387                 SQLITE_FUNC_COUNT  ),
108388      AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
108389      AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
108390      AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
108391    
108392      LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
108393  #ifdef SQLITE_CASE_SENSITIVE_LIKE
108394      LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
108395      LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
108396  #else
108397      LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
108398      LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
108399  #endif
108400  #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
108401      FUNCTION(unknown,           -1, 0, 0, unknownFunc      ),
108402  #endif
108403      FUNCTION(coalesce,           1, 0, 0, 0                ),
108404      FUNCTION(coalesce,           0, 0, 0, 0                ),
108405      FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
108406    };
108407  #ifndef SQLITE_OMIT_ALTERTABLE
108408    sqlite3AlterFunctions();
108409  #endif
108410  #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
108411    sqlite3AnalyzeFunctions();
108412  #endif
108413    sqlite3RegisterDateTimeFunctions();
108414    sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
108415  
108416  #if 0  /* Enable to print out how the built-in functions are hashed */
108417    {
108418      int i;
108419      FuncDef *p;
108420      for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
108421        printf("FUNC-HASH %02d:", i);
108422        for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
108423          int n = sqlite3Strlen30(p->zName);
108424          int h = p->zName[0] + n;
108425          printf(" %s(%d)", p->zName, h);
108426        }
108427        printf("\n");
108428      }
108429    }
108430  #endif
108431  }
108432  
108433  /************** End of func.c ************************************************/
108434  /************** Begin file fkey.c ********************************************/
108435  /*
108436  **
108437  ** The author disclaims copyright to this source code.  In place of
108438  ** a legal notice, here is a blessing:
108439  **
108440  **    May you do good and not evil.
108441  **    May you find forgiveness for yourself and forgive others.
108442  **    May you share freely, never taking more than you give.
108443  **
108444  *************************************************************************
108445  ** This file contains code used by the compiler to add foreign key
108446  ** support to compiled SQL statements.
108447  */
108448  /* #include "sqliteInt.h" */
108449  
108450  #ifndef SQLITE_OMIT_FOREIGN_KEY
108451  #ifndef SQLITE_OMIT_TRIGGER
108452  
108453  /*
108454  ** Deferred and Immediate FKs
108455  ** --------------------------
108456  **
108457  ** Foreign keys in SQLite come in two flavours: deferred and immediate.
108458  ** If an immediate foreign key constraint is violated,
108459  ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
108460  ** statement transaction rolled back. If a 
108461  ** deferred foreign key constraint is violated, no action is taken 
108462  ** immediately. However if the application attempts to commit the 
108463  ** transaction before fixing the constraint violation, the attempt fails.
108464  **
108465  ** Deferred constraints are implemented using a simple counter associated
108466  ** with the database handle. The counter is set to zero each time a 
108467  ** database transaction is opened. Each time a statement is executed 
108468  ** that causes a foreign key violation, the counter is incremented. Each
108469  ** time a statement is executed that removes an existing violation from
108470  ** the database, the counter is decremented. When the transaction is
108471  ** committed, the commit fails if the current value of the counter is
108472  ** greater than zero. This scheme has two big drawbacks:
108473  **
108474  **   * When a commit fails due to a deferred foreign key constraint, 
108475  **     there is no way to tell which foreign constraint is not satisfied,
108476  **     or which row it is not satisfied for.
108477  **
108478  **   * If the database contains foreign key violations when the 
108479  **     transaction is opened, this may cause the mechanism to malfunction.
108480  **
108481  ** Despite these problems, this approach is adopted as it seems simpler
108482  ** than the alternatives.
108483  **
108484  ** INSERT operations:
108485  **
108486  **   I.1) For each FK for which the table is the child table, search
108487  **        the parent table for a match. If none is found increment the
108488  **        constraint counter.
108489  **
108490  **   I.2) For each FK for which the table is the parent table, 
108491  **        search the child table for rows that correspond to the new
108492  **        row in the parent table. Decrement the counter for each row
108493  **        found (as the constraint is now satisfied).
108494  **
108495  ** DELETE operations:
108496  **
108497  **   D.1) For each FK for which the table is the child table, 
108498  **        search the parent table for a row that corresponds to the 
108499  **        deleted row in the child table. If such a row is not found, 
108500  **        decrement the counter.
108501  **
108502  **   D.2) For each FK for which the table is the parent table, search 
108503  **        the child table for rows that correspond to the deleted row 
108504  **        in the parent table. For each found increment the counter.
108505  **
108506  ** UPDATE operations:
108507  **
108508  **   An UPDATE command requires that all 4 steps above are taken, but only
108509  **   for FK constraints for which the affected columns are actually 
108510  **   modified (values must be compared at runtime).
108511  **
108512  ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
108513  ** This simplifies the implementation a bit.
108514  **
108515  ** For the purposes of immediate FK constraints, the OR REPLACE conflict
108516  ** resolution is considered to delete rows before the new row is inserted.
108517  ** If a delete caused by OR REPLACE violates an FK constraint, an exception
108518  ** is thrown, even if the FK constraint would be satisfied after the new 
108519  ** row is inserted.
108520  **
108521  ** Immediate constraints are usually handled similarly. The only difference 
108522  ** is that the counter used is stored as part of each individual statement
108523  ** object (struct Vdbe). If, after the statement has run, its immediate
108524  ** constraint counter is greater than zero,
108525  ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
108526  ** and the statement transaction is rolled back. An exception is an INSERT
108527  ** statement that inserts a single row only (no triggers). In this case,
108528  ** instead of using a counter, an exception is thrown immediately if the
108529  ** INSERT violates a foreign key constraint. This is necessary as such
108530  ** an INSERT does not open a statement transaction.
108531  **
108532  ** TODO: How should dropping a table be handled? How should renaming a 
108533  ** table be handled?
108534  **
108535  **
108536  ** Query API Notes
108537  ** ---------------
108538  **
108539  ** Before coding an UPDATE or DELETE row operation, the code-generator
108540  ** for those two operations needs to know whether or not the operation
108541  ** requires any FK processing and, if so, which columns of the original
108542  ** row are required by the FK processing VDBE code (i.e. if FKs were
108543  ** implemented using triggers, which of the old.* columns would be 
108544  ** accessed). No information is required by the code-generator before
108545  ** coding an INSERT operation. The functions used by the UPDATE/DELETE
108546  ** generation code to query for this information are:
108547  **
108548  **   sqlite3FkRequired() - Test to see if FK processing is required.
108549  **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
108550  **
108551  **
108552  ** Externally accessible module functions
108553  ** --------------------------------------
108554  **
108555  **   sqlite3FkCheck()    - Check for foreign key violations.
108556  **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
108557  **   sqlite3FkDelete()   - Delete an FKey structure.
108558  */
108559  
108560  /*
108561  ** VDBE Calling Convention
108562  ** -----------------------
108563  **
108564  ** Example:
108565  **
108566  **   For the following INSERT statement:
108567  **
108568  **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
108569  **     INSERT INTO t1 VALUES(1, 2, 3.1);
108570  **
108571  **   Register (x):        2    (type integer)
108572  **   Register (x+1):      1    (type integer)
108573  **   Register (x+2):      NULL (type NULL)
108574  **   Register (x+3):      3.1  (type real)
108575  */
108576  
108577  /*
108578  ** A foreign key constraint requires that the key columns in the parent
108579  ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
108580  ** Given that pParent is the parent table for foreign key constraint pFKey, 
108581  ** search the schema for a unique index on the parent key columns. 
108582  **
108583  ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
108584  ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
108585  ** is set to point to the unique index. 
108586  ** 
108587  ** If the parent key consists of a single column (the foreign key constraint
108588  ** is not a composite foreign key), output variable *paiCol is set to NULL.
108589  ** Otherwise, it is set to point to an allocated array of size N, where
108590  ** N is the number of columns in the parent key. The first element of the
108591  ** array is the index of the child table column that is mapped by the FK
108592  ** constraint to the parent table column stored in the left-most column
108593  ** of index *ppIdx. The second element of the array is the index of the
108594  ** child table column that corresponds to the second left-most column of
108595  ** *ppIdx, and so on.
108596  **
108597  ** If the required index cannot be found, either because:
108598  **
108599  **   1) The named parent key columns do not exist, or
108600  **
108601  **   2) The named parent key columns do exist, but are not subject to a
108602  **      UNIQUE or PRIMARY KEY constraint, or
108603  **
108604  **   3) No parent key columns were provided explicitly as part of the
108605  **      foreign key definition, and the parent table does not have a
108606  **      PRIMARY KEY, or
108607  **
108608  **   4) No parent key columns were provided explicitly as part of the
108609  **      foreign key definition, and the PRIMARY KEY of the parent table 
108610  **      consists of a different number of columns to the child key in 
108611  **      the child table.
108612  **
108613  ** then non-zero is returned, and a "foreign key mismatch" error loaded
108614  ** into pParse. If an OOM error occurs, non-zero is returned and the
108615  ** pParse->db->mallocFailed flag is set.
108616  */
108617  SQLITE_PRIVATE int sqlite3FkLocateIndex(
108618    Parse *pParse,                  /* Parse context to store any error in */
108619    Table *pParent,                 /* Parent table of FK constraint pFKey */
108620    FKey *pFKey,                    /* Foreign key to find index for */
108621    Index **ppIdx,                  /* OUT: Unique index on parent table */
108622    int **paiCol                    /* OUT: Map of index columns in pFKey */
108623  ){
108624    Index *pIdx = 0;                    /* Value to return via *ppIdx */
108625    int *aiCol = 0;                     /* Value to return via *paiCol */
108626    int nCol = pFKey->nCol;             /* Number of columns in parent key */
108627    char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
108628  
108629    /* The caller is responsible for zeroing output parameters. */
108630    assert( ppIdx && *ppIdx==0 );
108631    assert( !paiCol || *paiCol==0 );
108632    assert( pParse );
108633  
108634    /* If this is a non-composite (single column) foreign key, check if it 
108635    ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
108636    ** and *paiCol set to zero and return early. 
108637    **
108638    ** Otherwise, for a composite foreign key (more than one column), allocate
108639    ** space for the aiCol array (returned via output parameter *paiCol).
108640    ** Non-composite foreign keys do not require the aiCol array.
108641    */
108642    if( nCol==1 ){
108643      /* The FK maps to the IPK if any of the following are true:
108644      **
108645      **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
108646      **      mapped to the primary key of table pParent, or
108647      **   2) The FK is explicitly mapped to a column declared as INTEGER
108648      **      PRIMARY KEY.
108649      */
108650      if( pParent->iPKey>=0 ){
108651        if( !zKey ) return 0;
108652        if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
108653      }
108654    }else if( paiCol ){
108655      assert( nCol>1 );
108656      aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
108657      if( !aiCol ) return 1;
108658      *paiCol = aiCol;
108659    }
108660  
108661    for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
108662      if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){ 
108663        /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
108664        ** of columns. If each indexed column corresponds to a foreign key
108665        ** column of pFKey, then this index is a winner.  */
108666  
108667        if( zKey==0 ){
108668          /* If zKey is NULL, then this foreign key is implicitly mapped to 
108669          ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
108670          ** identified by the test.  */
108671          if( IsPrimaryKeyIndex(pIdx) ){
108672            if( aiCol ){
108673              int i;
108674              for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
108675            }
108676            break;
108677          }
108678        }else{
108679          /* If zKey is non-NULL, then this foreign key was declared to
108680          ** map to an explicit list of columns in table pParent. Check if this
108681          ** index matches those columns. Also, check that the index uses
108682          ** the default collation sequences for each column. */
108683          int i, j;
108684          for(i=0; i<nCol; i++){
108685            i16 iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
108686            const char *zDfltColl;            /* Def. collation for column */
108687            char *zIdxCol;                    /* Name of indexed column */
108688  
108689            if( iCol<0 ) break; /* No foreign keys against expression indexes */
108690  
108691            /* If the index uses a collation sequence that is different from
108692            ** the default collation sequence for the column, this index is
108693            ** unusable. Bail out early in this case.  */
108694            zDfltColl = pParent->aCol[iCol].zColl;
108695            if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
108696            if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
108697  
108698            zIdxCol = pParent->aCol[iCol].zName;
108699            for(j=0; j<nCol; j++){
108700              if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
108701                if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
108702                break;
108703              }
108704            }
108705            if( j==nCol ) break;
108706          }
108707          if( i==nCol ) break;      /* pIdx is usable */
108708        }
108709      }
108710    }
108711  
108712    if( !pIdx ){
108713      if( !pParse->disableTriggers ){
108714        sqlite3ErrorMsg(pParse,
108715             "foreign key mismatch - \"%w\" referencing \"%w\"",
108716             pFKey->pFrom->zName, pFKey->zTo);
108717      }
108718      sqlite3DbFree(pParse->db, aiCol);
108719      return 1;
108720    }
108721  
108722    *ppIdx = pIdx;
108723    return 0;
108724  }
108725  
108726  /*
108727  ** This function is called when a row is inserted into or deleted from the 
108728  ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
108729  ** on the child table of pFKey, this function is invoked twice for each row
108730  ** affected - once to "delete" the old row, and then again to "insert" the
108731  ** new row.
108732  **
108733  ** Each time it is called, this function generates VDBE code to locate the
108734  ** row in the parent table that corresponds to the row being inserted into 
108735  ** or deleted from the child table. If the parent row can be found, no 
108736  ** special action is taken. Otherwise, if the parent row can *not* be
108737  ** found in the parent table:
108738  **
108739  **   Operation | FK type   | Action taken
108740  **   --------------------------------------------------------------------------
108741  **   INSERT      immediate   Increment the "immediate constraint counter".
108742  **
108743  **   DELETE      immediate   Decrement the "immediate constraint counter".
108744  **
108745  **   INSERT      deferred    Increment the "deferred constraint counter".
108746  **
108747  **   DELETE      deferred    Decrement the "deferred constraint counter".
108748  **
108749  ** These operations are identified in the comment at the top of this file 
108750  ** (fkey.c) as "I.1" and "D.1".
108751  */
108752  static void fkLookupParent(
108753    Parse *pParse,        /* Parse context */
108754    int iDb,              /* Index of database housing pTab */
108755    Table *pTab,          /* Parent table of FK pFKey */
108756    Index *pIdx,          /* Unique index on parent key columns in pTab */
108757    FKey *pFKey,          /* Foreign key constraint */
108758    int *aiCol,           /* Map from parent key columns to child table columns */
108759    int regData,          /* Address of array containing child table row */
108760    int nIncr,            /* Increment constraint counter by this */
108761    int isIgnore          /* If true, pretend pTab contains all NULL values */
108762  ){
108763    int i;                                    /* Iterator variable */
108764    Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
108765    int iCur = pParse->nTab - 1;              /* Cursor number to use */
108766    int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
108767  
108768    /* If nIncr is less than zero, then check at runtime if there are any
108769    ** outstanding constraints to resolve. If there are not, there is no need
108770    ** to check if deleting this row resolves any outstanding violations.
108771    **
108772    ** Check if any of the key columns in the child table row are NULL. If 
108773    ** any are, then the constraint is considered satisfied. No need to 
108774    ** search for a matching row in the parent table.  */
108775    if( nIncr<0 ){
108776      sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
108777      VdbeCoverage(v);
108778    }
108779    for(i=0; i<pFKey->nCol; i++){
108780      int iReg = aiCol[i] + regData + 1;
108781      sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
108782    }
108783  
108784    if( isIgnore==0 ){
108785      if( pIdx==0 ){
108786        /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
108787        ** column of the parent table (table pTab).  */
108788        int iMustBeInt;               /* Address of MustBeInt instruction */
108789        int regTemp = sqlite3GetTempReg(pParse);
108790    
108791        /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
108792        ** apply the affinity of the parent key). If this fails, then there
108793        ** is no matching parent key. Before using MustBeInt, make a copy of
108794        ** the value. Otherwise, the value inserted into the child key column
108795        ** will have INTEGER affinity applied to it, which may not be correct.  */
108796        sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
108797        iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
108798        VdbeCoverage(v);
108799    
108800        /* If the parent table is the same as the child table, and we are about
108801        ** to increment the constraint-counter (i.e. this is an INSERT operation),
108802        ** then check if the row being inserted matches itself. If so, do not
108803        ** increment the constraint-counter.  */
108804        if( pTab==pFKey->pFrom && nIncr==1 ){
108805          sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
108806          sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
108807        }
108808    
108809        sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
108810        sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
108811        sqlite3VdbeGoto(v, iOk);
108812        sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
108813        sqlite3VdbeJumpHere(v, iMustBeInt);
108814        sqlite3ReleaseTempReg(pParse, regTemp);
108815      }else{
108816        int nCol = pFKey->nCol;
108817        int regTemp = sqlite3GetTempRange(pParse, nCol);
108818        int regRec = sqlite3GetTempReg(pParse);
108819    
108820        sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
108821        sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
108822        for(i=0; i<nCol; i++){
108823          sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
108824        }
108825    
108826        /* If the parent table is the same as the child table, and we are about
108827        ** to increment the constraint-counter (i.e. this is an INSERT operation),
108828        ** then check if the row being inserted matches itself. If so, do not
108829        ** increment the constraint-counter. 
108830        **
108831        ** If any of the parent-key values are NULL, then the row cannot match 
108832        ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
108833        ** of the parent-key values are NULL (at this point it is known that
108834        ** none of the child key values are).
108835        */
108836        if( pTab==pFKey->pFrom && nIncr==1 ){
108837          int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
108838          for(i=0; i<nCol; i++){
108839            int iChild = aiCol[i]+1+regData;
108840            int iParent = pIdx->aiColumn[i]+1+regData;
108841            assert( pIdx->aiColumn[i]>=0 );
108842            assert( aiCol[i]!=pTab->iPKey );
108843            if( pIdx->aiColumn[i]==pTab->iPKey ){
108844              /* The parent key is a composite key that includes the IPK column */
108845              iParent = regData;
108846            }
108847            sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
108848            sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
108849          }
108850          sqlite3VdbeGoto(v, iOk);
108851        }
108852    
108853        sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
108854                          sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
108855        sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
108856    
108857        sqlite3ReleaseTempReg(pParse, regRec);
108858        sqlite3ReleaseTempRange(pParse, regTemp, nCol);
108859      }
108860    }
108861  
108862    if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
108863     && !pParse->pToplevel 
108864     && !pParse->isMultiWrite 
108865    ){
108866      /* Special case: If this is an INSERT statement that will insert exactly
108867      ** one row into the table, raise a constraint immediately instead of
108868      ** incrementing a counter. This is necessary as the VM code is being
108869      ** generated for will not open a statement transaction.  */
108870      assert( nIncr==1 );
108871      sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
108872          OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
108873    }else{
108874      if( nIncr>0 && pFKey->isDeferred==0 ){
108875        sqlite3MayAbort(pParse);
108876      }
108877      sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
108878    }
108879  
108880    sqlite3VdbeResolveLabel(v, iOk);
108881    sqlite3VdbeAddOp1(v, OP_Close, iCur);
108882  }
108883  
108884  
108885  /*
108886  ** Return an Expr object that refers to a memory register corresponding
108887  ** to column iCol of table pTab.
108888  **
108889  ** regBase is the first of an array of register that contains the data
108890  ** for pTab.  regBase itself holds the rowid.  regBase+1 holds the first
108891  ** column.  regBase+2 holds the second column, and so forth.
108892  */
108893  static Expr *exprTableRegister(
108894    Parse *pParse,     /* Parsing and code generating context */
108895    Table *pTab,       /* The table whose content is at r[regBase]... */
108896    int regBase,       /* Contents of table pTab */
108897    i16 iCol           /* Which column of pTab is desired */
108898  ){
108899    Expr *pExpr;
108900    Column *pCol;
108901    const char *zColl;
108902    sqlite3 *db = pParse->db;
108903  
108904    pExpr = sqlite3Expr(db, TK_REGISTER, 0);
108905    if( pExpr ){
108906      if( iCol>=0 && iCol!=pTab->iPKey ){
108907        pCol = &pTab->aCol[iCol];
108908        pExpr->iTable = regBase + iCol + 1;
108909        pExpr->affinity = pCol->affinity;
108910        zColl = pCol->zColl;
108911        if( zColl==0 ) zColl = db->pDfltColl->zName;
108912        pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
108913      }else{
108914        pExpr->iTable = regBase;
108915        pExpr->affinity = SQLITE_AFF_INTEGER;
108916      }
108917    }
108918    return pExpr;
108919  }
108920  
108921  /*
108922  ** Return an Expr object that refers to column iCol of table pTab which
108923  ** has cursor iCur.
108924  */
108925  static Expr *exprTableColumn(
108926    sqlite3 *db,      /* The database connection */
108927    Table *pTab,      /* The table whose column is desired */
108928    int iCursor,      /* The open cursor on the table */
108929    i16 iCol          /* The column that is wanted */
108930  ){
108931    Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
108932    if( pExpr ){
108933      pExpr->pTab = pTab;
108934      pExpr->iTable = iCursor;
108935      pExpr->iColumn = iCol;
108936    }
108937    return pExpr;
108938  }
108939  
108940  /*
108941  ** This function is called to generate code executed when a row is deleted
108942  ** from the parent table of foreign key constraint pFKey and, if pFKey is 
108943  ** deferred, when a row is inserted into the same table. When generating
108944  ** code for an SQL UPDATE operation, this function may be called twice -
108945  ** once to "delete" the old row and once to "insert" the new row.
108946  **
108947  ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
108948  ** the number of FK violations in the db) or +1 when deleting one (as this
108949  ** may increase the number of FK constraint problems).
108950  **
108951  ** The code generated by this function scans through the rows in the child
108952  ** table that correspond to the parent table row being deleted or inserted.
108953  ** For each child row found, one of the following actions is taken:
108954  **
108955  **   Operation | FK type   | Action taken
108956  **   --------------------------------------------------------------------------
108957  **   DELETE      immediate   Increment the "immediate constraint counter".
108958  **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
108959  **                           throw a "FOREIGN KEY constraint failed" exception.
108960  **
108961  **   INSERT      immediate   Decrement the "immediate constraint counter".
108962  **
108963  **   DELETE      deferred    Increment the "deferred constraint counter".
108964  **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
108965  **                           throw a "FOREIGN KEY constraint failed" exception.
108966  **
108967  **   INSERT      deferred    Decrement the "deferred constraint counter".
108968  **
108969  ** These operations are identified in the comment at the top of this file 
108970  ** (fkey.c) as "I.2" and "D.2".
108971  */
108972  static void fkScanChildren(
108973    Parse *pParse,                  /* Parse context */
108974    SrcList *pSrc,                  /* The child table to be scanned */
108975    Table *pTab,                    /* The parent table */
108976    Index *pIdx,                    /* Index on parent covering the foreign key */
108977    FKey *pFKey,                    /* The foreign key linking pSrc to pTab */
108978    int *aiCol,                     /* Map from pIdx cols to child table cols */
108979    int regData,                    /* Parent row data starts here */
108980    int nIncr                       /* Amount to increment deferred counter by */
108981  ){
108982    sqlite3 *db = pParse->db;       /* Database handle */
108983    int i;                          /* Iterator variable */
108984    Expr *pWhere = 0;               /* WHERE clause to scan with */
108985    NameContext sNameContext;       /* Context used to resolve WHERE clause */
108986    WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
108987    int iFkIfZero = 0;              /* Address of OP_FkIfZero */
108988    Vdbe *v = sqlite3GetVdbe(pParse);
108989  
108990    assert( pIdx==0 || pIdx->pTable==pTab );
108991    assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
108992    assert( pIdx!=0 || pFKey->nCol==1 );
108993    assert( pIdx!=0 || HasRowid(pTab) );
108994  
108995    if( nIncr<0 ){
108996      iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
108997      VdbeCoverage(v);
108998    }
108999  
109000    /* Create an Expr object representing an SQL expression like:
109001    **
109002    **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
109003    **
109004    ** The collation sequence used for the comparison should be that of
109005    ** the parent key columns. The affinity of the parent key column should
109006    ** be applied to each child key value before the comparison takes place.
109007    */
109008    for(i=0; i<pFKey->nCol; i++){
109009      Expr *pLeft;                  /* Value from parent table row */
109010      Expr *pRight;                 /* Column ref to child table */
109011      Expr *pEq;                    /* Expression (pLeft = pRight) */
109012      i16 iCol;                     /* Index of column in child table */ 
109013      const char *zCol;             /* Name of column in child table */
109014  
109015      iCol = pIdx ? pIdx->aiColumn[i] : -1;
109016      pLeft = exprTableRegister(pParse, pTab, regData, iCol);
109017      iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
109018      assert( iCol>=0 );
109019      zCol = pFKey->pFrom->aCol[iCol].zName;
109020      pRight = sqlite3Expr(db, TK_ID, zCol);
109021      pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
109022      pWhere = sqlite3ExprAnd(db, pWhere, pEq);
109023    }
109024  
109025    /* If the child table is the same as the parent table, then add terms
109026    ** to the WHERE clause that prevent this entry from being scanned.
109027    ** The added WHERE clause terms are like this:
109028    **
109029    **     $current_rowid!=rowid
109030    **     NOT( $current_a==a AND $current_b==b AND ... )
109031    **
109032    ** The first form is used for rowid tables.  The second form is used
109033    ** for WITHOUT ROWID tables.  In the second form, the primary key is
109034    ** (a,b,...)
109035    */
109036    if( pTab==pFKey->pFrom && nIncr>0 ){
109037      Expr *pNe;                    /* Expression (pLeft != pRight) */
109038      Expr *pLeft;                  /* Value from parent table row */
109039      Expr *pRight;                 /* Column ref to child table */
109040      if( HasRowid(pTab) ){
109041        pLeft = exprTableRegister(pParse, pTab, regData, -1);
109042        pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
109043        pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight);
109044      }else{
109045        Expr *pEq, *pAll = 0;
109046        Index *pPk = sqlite3PrimaryKeyIndex(pTab);
109047        assert( pIdx!=0 );
109048        for(i=0; i<pPk->nKeyCol; i++){
109049          i16 iCol = pIdx->aiColumn[i];
109050          assert( iCol>=0 );
109051          pLeft = exprTableRegister(pParse, pTab, regData, iCol);
109052          pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
109053          pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
109054          pAll = sqlite3ExprAnd(db, pAll, pEq);
109055        }
109056        pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0);
109057      }
109058      pWhere = sqlite3ExprAnd(db, pWhere, pNe);
109059    }
109060  
109061    /* Resolve the references in the WHERE clause. */
109062    memset(&sNameContext, 0, sizeof(NameContext));
109063    sNameContext.pSrcList = pSrc;
109064    sNameContext.pParse = pParse;
109065    sqlite3ResolveExprNames(&sNameContext, pWhere);
109066  
109067    /* Create VDBE to loop through the entries in pSrc that match the WHERE
109068    ** clause. For each row found, increment either the deferred or immediate
109069    ** foreign key constraint counter. */
109070    if( pParse->nErr==0 ){
109071      pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
109072      sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
109073      if( pWInfo ){
109074        sqlite3WhereEnd(pWInfo);
109075      }
109076    }
109077  
109078    /* Clean up the WHERE clause constructed above. */
109079    sqlite3ExprDelete(db, pWhere);
109080    if( iFkIfZero ){
109081      sqlite3VdbeJumpHere(v, iFkIfZero);
109082    }
109083  }
109084  
109085  /*
109086  ** This function returns a linked list of FKey objects (connected by
109087  ** FKey.pNextTo) holding all children of table pTab.  For example,
109088  ** given the following schema:
109089  **
109090  **   CREATE TABLE t1(a PRIMARY KEY);
109091  **   CREATE TABLE t2(b REFERENCES t1(a);
109092  **
109093  ** Calling this function with table "t1" as an argument returns a pointer
109094  ** to the FKey structure representing the foreign key constraint on table
109095  ** "t2". Calling this function with "t2" as the argument would return a
109096  ** NULL pointer (as there are no FK constraints for which t2 is the parent
109097  ** table).
109098  */
109099  SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
109100    return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
109101  }
109102  
109103  /*
109104  ** The second argument is a Trigger structure allocated by the 
109105  ** fkActionTrigger() routine. This function deletes the Trigger structure
109106  ** and all of its sub-components.
109107  **
109108  ** The Trigger structure or any of its sub-components may be allocated from
109109  ** the lookaside buffer belonging to database handle dbMem.
109110  */
109111  static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
109112    if( p ){
109113      TriggerStep *pStep = p->step_list;
109114      sqlite3ExprDelete(dbMem, pStep->pWhere);
109115      sqlite3ExprListDelete(dbMem, pStep->pExprList);
109116      sqlite3SelectDelete(dbMem, pStep->pSelect);
109117      sqlite3ExprDelete(dbMem, p->pWhen);
109118      sqlite3DbFree(dbMem, p);
109119    }
109120  }
109121  
109122  /*
109123  ** This function is called to generate code that runs when table pTab is
109124  ** being dropped from the database. The SrcList passed as the second argument
109125  ** to this function contains a single entry guaranteed to resolve to
109126  ** table pTab.
109127  **
109128  ** Normally, no code is required. However, if either
109129  **
109130  **   (a) The table is the parent table of a FK constraint, or
109131  **   (b) The table is the child table of a deferred FK constraint and it is
109132  **       determined at runtime that there are outstanding deferred FK 
109133  **       constraint violations in the database,
109134  **
109135  ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
109136  ** the table from the database. Triggers are disabled while running this
109137  ** DELETE, but foreign key actions are not.
109138  */
109139  SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
109140    sqlite3 *db = pParse->db;
109141    if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
109142      int iSkip = 0;
109143      Vdbe *v = sqlite3GetVdbe(pParse);
109144  
109145      assert( v );                  /* VDBE has already been allocated */
109146      if( sqlite3FkReferences(pTab)==0 ){
109147        /* Search for a deferred foreign key constraint for which this table
109148        ** is the child table. If one cannot be found, return without 
109149        ** generating any VDBE code. If one can be found, then jump over
109150        ** the entire DELETE if there are no outstanding deferred constraints
109151        ** when this statement is run.  */
109152        FKey *p;
109153        for(p=pTab->pFKey; p; p=p->pNextFrom){
109154          if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
109155        }
109156        if( !p ) return;
109157        iSkip = sqlite3VdbeMakeLabel(v);
109158        sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
109159      }
109160  
109161      pParse->disableTriggers = 1;
109162      sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
109163      pParse->disableTriggers = 0;
109164  
109165      /* If the DELETE has generated immediate foreign key constraint 
109166      ** violations, halt the VDBE and return an error at this point, before
109167      ** any modifications to the schema are made. This is because statement
109168      ** transactions are not able to rollback schema changes.  
109169      **
109170      ** If the SQLITE_DeferFKs flag is set, then this is not required, as
109171      ** the statement transaction will not be rolled back even if FK
109172      ** constraints are violated.
109173      */
109174      if( (db->flags & SQLITE_DeferFKs)==0 ){
109175        sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
109176        VdbeCoverage(v);
109177        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
109178            OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
109179      }
109180  
109181      if( iSkip ){
109182        sqlite3VdbeResolveLabel(v, iSkip);
109183      }
109184    }
109185  }
109186  
109187  
109188  /*
109189  ** The second argument points to an FKey object representing a foreign key
109190  ** for which pTab is the child table. An UPDATE statement against pTab
109191  ** is currently being processed. For each column of the table that is 
109192  ** actually updated, the corresponding element in the aChange[] array
109193  ** is zero or greater (if a column is unmodified the corresponding element
109194  ** is set to -1). If the rowid column is modified by the UPDATE statement
109195  ** the bChngRowid argument is non-zero.
109196  **
109197  ** This function returns true if any of the columns that are part of the
109198  ** child key for FK constraint *p are modified.
109199  */
109200  static int fkChildIsModified(
109201    Table *pTab,                    /* Table being updated */
109202    FKey *p,                        /* Foreign key for which pTab is the child */
109203    int *aChange,                   /* Array indicating modified columns */
109204    int bChngRowid                  /* True if rowid is modified by this update */
109205  ){
109206    int i;
109207    for(i=0; i<p->nCol; i++){
109208      int iChildKey = p->aCol[i].iFrom;
109209      if( aChange[iChildKey]>=0 ) return 1;
109210      if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
109211    }
109212    return 0;
109213  }
109214  
109215  /*
109216  ** The second argument points to an FKey object representing a foreign key
109217  ** for which pTab is the parent table. An UPDATE statement against pTab
109218  ** is currently being processed. For each column of the table that is 
109219  ** actually updated, the corresponding element in the aChange[] array
109220  ** is zero or greater (if a column is unmodified the corresponding element
109221  ** is set to -1). If the rowid column is modified by the UPDATE statement
109222  ** the bChngRowid argument is non-zero.
109223  **
109224  ** This function returns true if any of the columns that are part of the
109225  ** parent key for FK constraint *p are modified.
109226  */
109227  static int fkParentIsModified(
109228    Table *pTab, 
109229    FKey *p, 
109230    int *aChange, 
109231    int bChngRowid
109232  ){
109233    int i;
109234    for(i=0; i<p->nCol; i++){
109235      char *zKey = p->aCol[i].zCol;
109236      int iKey;
109237      for(iKey=0; iKey<pTab->nCol; iKey++){
109238        if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
109239          Column *pCol = &pTab->aCol[iKey];
109240          if( zKey ){
109241            if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
109242          }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
109243            return 1;
109244          }
109245        }
109246      }
109247    }
109248    return 0;
109249  }
109250  
109251  /*
109252  ** Return true if the parser passed as the first argument is being
109253  ** used to code a trigger that is really a "SET NULL" action belonging
109254  ** to trigger pFKey.
109255  */
109256  static int isSetNullAction(Parse *pParse, FKey *pFKey){
109257    Parse *pTop = sqlite3ParseToplevel(pParse);
109258    if( pTop->pTriggerPrg ){
109259      Trigger *p = pTop->pTriggerPrg->pTrigger;
109260      if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
109261       || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
109262      ){
109263        return 1;
109264      }
109265    }
109266    return 0;
109267  }
109268  
109269  /*
109270  ** This function is called when inserting, deleting or updating a row of
109271  ** table pTab to generate VDBE code to perform foreign key constraint 
109272  ** processing for the operation.
109273  **
109274  ** For a DELETE operation, parameter regOld is passed the index of the
109275  ** first register in an array of (pTab->nCol+1) registers containing the
109276  ** rowid of the row being deleted, followed by each of the column values
109277  ** of the row being deleted, from left to right. Parameter regNew is passed
109278  ** zero in this case.
109279  **
109280  ** For an INSERT operation, regOld is passed zero and regNew is passed the
109281  ** first register of an array of (pTab->nCol+1) registers containing the new
109282  ** row data.
109283  **
109284  ** For an UPDATE operation, this function is called twice. Once before
109285  ** the original record is deleted from the table using the calling convention
109286  ** described for DELETE. Then again after the original record is deleted
109287  ** but before the new record is inserted using the INSERT convention. 
109288  */
109289  SQLITE_PRIVATE void sqlite3FkCheck(
109290    Parse *pParse,                  /* Parse context */
109291    Table *pTab,                    /* Row is being deleted from this table */ 
109292    int regOld,                     /* Previous row data is stored here */
109293    int regNew,                     /* New row data is stored here */
109294    int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
109295    int bChngRowid                  /* True if rowid is UPDATEd */
109296  ){
109297    sqlite3 *db = pParse->db;       /* Database handle */
109298    FKey *pFKey;                    /* Used to iterate through FKs */
109299    int iDb;                        /* Index of database containing pTab */
109300    const char *zDb;                /* Name of database containing pTab */
109301    int isIgnoreErrors = pParse->disableTriggers;
109302  
109303    /* Exactly one of regOld and regNew should be non-zero. */
109304    assert( (regOld==0)!=(regNew==0) );
109305  
109306    /* If foreign-keys are disabled, this function is a no-op. */
109307    if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
109308  
109309    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
109310    zDb = db->aDb[iDb].zDbSName;
109311  
109312    /* Loop through all the foreign key constraints for which pTab is the
109313    ** child table (the table that the foreign key definition is part of).  */
109314    for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
109315      Table *pTo;                   /* Parent table of foreign key pFKey */
109316      Index *pIdx = 0;              /* Index on key columns in pTo */
109317      int *aiFree = 0;
109318      int *aiCol;
109319      int iCol;
109320      int i;
109321      int bIgnore = 0;
109322  
109323      if( aChange 
109324       && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
109325       && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0 
109326      ){
109327        continue;
109328      }
109329  
109330      /* Find the parent table of this foreign key. Also find a unique index 
109331      ** on the parent key columns in the parent table. If either of these 
109332      ** schema items cannot be located, set an error in pParse and return 
109333      ** early.  */
109334      if( pParse->disableTriggers ){
109335        pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
109336      }else{
109337        pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
109338      }
109339      if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
109340        assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
109341        if( !isIgnoreErrors || db->mallocFailed ) return;
109342        if( pTo==0 ){
109343          /* If isIgnoreErrors is true, then a table is being dropped. In this
109344          ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
109345          ** before actually dropping it in order to check FK constraints.
109346          ** If the parent table of an FK constraint on the current table is
109347          ** missing, behave as if it is empty. i.e. decrement the relevant
109348          ** FK counter for each row of the current table with non-NULL keys.
109349          */
109350          Vdbe *v = sqlite3GetVdbe(pParse);
109351          int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
109352          for(i=0; i<pFKey->nCol; i++){
109353            int iReg = pFKey->aCol[i].iFrom + regOld + 1;
109354            sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
109355          }
109356          sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
109357        }
109358        continue;
109359      }
109360      assert( pFKey->nCol==1 || (aiFree && pIdx) );
109361  
109362      if( aiFree ){
109363        aiCol = aiFree;
109364      }else{
109365        iCol = pFKey->aCol[0].iFrom;
109366        aiCol = &iCol;
109367      }
109368      for(i=0; i<pFKey->nCol; i++){
109369        if( aiCol[i]==pTab->iPKey ){
109370          aiCol[i] = -1;
109371        }
109372        assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
109373  #ifndef SQLITE_OMIT_AUTHORIZATION
109374        /* Request permission to read the parent key columns. If the 
109375        ** authorization callback returns SQLITE_IGNORE, behave as if any
109376        ** values read from the parent table are NULL. */
109377        if( db->xAuth ){
109378          int rcauth;
109379          char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
109380          rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
109381          bIgnore = (rcauth==SQLITE_IGNORE);
109382        }
109383  #endif
109384      }
109385  
109386      /* Take a shared-cache advisory read-lock on the parent table. Allocate 
109387      ** a cursor to use to search the unique index on the parent key columns 
109388      ** in the parent table.  */
109389      sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
109390      pParse->nTab++;
109391  
109392      if( regOld!=0 ){
109393        /* A row is being removed from the child table. Search for the parent.
109394        ** If the parent does not exist, removing the child row resolves an 
109395        ** outstanding foreign key constraint violation. */
109396        fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
109397      }
109398      if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
109399        /* A row is being added to the child table. If a parent row cannot
109400        ** be found, adding the child row has violated the FK constraint. 
109401        **
109402        ** If this operation is being performed as part of a trigger program
109403        ** that is actually a "SET NULL" action belonging to this very 
109404        ** foreign key, then omit this scan altogether. As all child key
109405        ** values are guaranteed to be NULL, it is not possible for adding
109406        ** this row to cause an FK violation.  */
109407        fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
109408      }
109409  
109410      sqlite3DbFree(db, aiFree);
109411    }
109412  
109413    /* Loop through all the foreign key constraints that refer to this table.
109414    ** (the "child" constraints) */
109415    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
109416      Index *pIdx = 0;              /* Foreign key index for pFKey */
109417      SrcList *pSrc;
109418      int *aiCol = 0;
109419  
109420      if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
109421        continue;
109422      }
109423  
109424      if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs) 
109425       && !pParse->pToplevel && !pParse->isMultiWrite 
109426      ){
109427        assert( regOld==0 && regNew!=0 );
109428        /* Inserting a single row into a parent table cannot cause (or fix)
109429        ** an immediate foreign key violation. So do nothing in this case.  */
109430        continue;
109431      }
109432  
109433      if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
109434        if( !isIgnoreErrors || db->mallocFailed ) return;
109435        continue;
109436      }
109437      assert( aiCol || pFKey->nCol==1 );
109438  
109439      /* Create a SrcList structure containing the child table.  We need the
109440      ** child table as a SrcList for sqlite3WhereBegin() */
109441      pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
109442      if( pSrc ){
109443        struct SrcList_item *pItem = pSrc->a;
109444        pItem->pTab = pFKey->pFrom;
109445        pItem->zName = pFKey->pFrom->zName;
109446        pItem->pTab->nTabRef++;
109447        pItem->iCursor = pParse->nTab++;
109448    
109449        if( regNew!=0 ){
109450          fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
109451        }
109452        if( regOld!=0 ){
109453          int eAction = pFKey->aAction[aChange!=0];
109454          fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
109455          /* If this is a deferred FK constraint, or a CASCADE or SET NULL
109456          ** action applies, then any foreign key violations caused by
109457          ** removing the parent key will be rectified by the action trigger.
109458          ** So do not set the "may-abort" flag in this case.
109459          **
109460          ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
109461          ** may-abort flag will eventually be set on this statement anyway
109462          ** (when this function is called as part of processing the UPDATE
109463          ** within the action trigger).
109464          **
109465          ** Note 2: At first glance it may seem like SQLite could simply omit
109466          ** all OP_FkCounter related scans when either CASCADE or SET NULL
109467          ** applies. The trouble starts if the CASCADE or SET NULL action 
109468          ** trigger causes other triggers or action rules attached to the 
109469          ** child table to fire. In these cases the fk constraint counters
109470          ** might be set incorrectly if any OP_FkCounter related scans are 
109471          ** omitted.  */
109472          if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
109473            sqlite3MayAbort(pParse);
109474          }
109475        }
109476        pItem->zName = 0;
109477        sqlite3SrcListDelete(db, pSrc);
109478      }
109479      sqlite3DbFree(db, aiCol);
109480    }
109481  }
109482  
109483  #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
109484  
109485  /*
109486  ** This function is called before generating code to update or delete a 
109487  ** row contained in table pTab.
109488  */
109489  SQLITE_PRIVATE u32 sqlite3FkOldmask(
109490    Parse *pParse,                  /* Parse context */
109491    Table *pTab                     /* Table being modified */
109492  ){
109493    u32 mask = 0;
109494    if( pParse->db->flags&SQLITE_ForeignKeys ){
109495      FKey *p;
109496      int i;
109497      for(p=pTab->pFKey; p; p=p->pNextFrom){
109498        for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
109499      }
109500      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
109501        Index *pIdx = 0;
109502        sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
109503        if( pIdx ){
109504          for(i=0; i<pIdx->nKeyCol; i++){
109505            assert( pIdx->aiColumn[i]>=0 );
109506            mask |= COLUMN_MASK(pIdx->aiColumn[i]);
109507          }
109508        }
109509      }
109510    }
109511    return mask;
109512  }
109513  
109514  
109515  /*
109516  ** This function is called before generating code to update or delete a 
109517  ** row contained in table pTab. If the operation is a DELETE, then
109518  ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
109519  ** to an array of size N, where N is the number of columns in table pTab.
109520  ** If the i'th column is not modified by the UPDATE, then the corresponding 
109521  ** entry in the aChange[] array is set to -1. If the column is modified,
109522  ** the value is 0 or greater. Parameter chngRowid is set to true if the
109523  ** UPDATE statement modifies the rowid fields of the table.
109524  **
109525  ** If any foreign key processing will be required, this function returns
109526  ** non-zero. If there is no foreign key related processing, this function 
109527  ** returns zero.
109528  **
109529  ** For an UPDATE, this function returns 2 if:
109530  **
109531  **   * There are any FKs for which pTab is the child and the parent table, or
109532  **   * the UPDATE modifies one or more parent keys for which the action is
109533  **     not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL).
109534  **
109535  ** Or, assuming some other foreign key processing is required, 1.
109536  */
109537  SQLITE_PRIVATE int sqlite3FkRequired(
109538    Parse *pParse,                  /* Parse context */
109539    Table *pTab,                    /* Table being modified */
109540    int *aChange,                   /* Non-NULL for UPDATE operations */
109541    int chngRowid                   /* True for UPDATE that affects rowid */
109542  ){
109543    int eRet = 0;
109544    if( pParse->db->flags&SQLITE_ForeignKeys ){
109545      if( !aChange ){
109546        /* A DELETE operation. Foreign key processing is required if the 
109547        ** table in question is either the child or parent table for any 
109548        ** foreign key constraint.  */
109549        eRet = (sqlite3FkReferences(pTab) || pTab->pFKey);
109550      }else{
109551        /* This is an UPDATE. Foreign key processing is only required if the
109552        ** operation modifies one or more child or parent key columns. */
109553        FKey *p;
109554  
109555        /* Check if any child key columns are being modified. */
109556        for(p=pTab->pFKey; p; p=p->pNextFrom){
109557          if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) return 2;
109558          if( fkChildIsModified(pTab, p, aChange, chngRowid) ){
109559            eRet = 1;
109560          }
109561        }
109562  
109563        /* Check if any parent key columns are being modified. */
109564        for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
109565          if( fkParentIsModified(pTab, p, aChange, chngRowid) ){
109566            if( p->aAction[1]!=OE_None ) return 2;
109567            eRet = 1;
109568          }
109569        }
109570      }
109571    }
109572    return eRet;
109573  }
109574  
109575  /*
109576  ** This function is called when an UPDATE or DELETE operation is being 
109577  ** compiled on table pTab, which is the parent table of foreign-key pFKey.
109578  ** If the current operation is an UPDATE, then the pChanges parameter is
109579  ** passed a pointer to the list of columns being modified. If it is a
109580  ** DELETE, pChanges is passed a NULL pointer.
109581  **
109582  ** It returns a pointer to a Trigger structure containing a trigger
109583  ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
109584  ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
109585  ** returned (these actions require no special handling by the triggers
109586  ** sub-system, code for them is created by fkScanChildren()).
109587  **
109588  ** For example, if pFKey is the foreign key and pTab is table "p" in 
109589  ** the following schema:
109590  **
109591  **   CREATE TABLE p(pk PRIMARY KEY);
109592  **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
109593  **
109594  ** then the returned trigger structure is equivalent to:
109595  **
109596  **   CREATE TRIGGER ... DELETE ON p BEGIN
109597  **     DELETE FROM c WHERE ck = old.pk;
109598  **   END;
109599  **
109600  ** The returned pointer is cached as part of the foreign key object. It
109601  ** is eventually freed along with the rest of the foreign key object by 
109602  ** sqlite3FkDelete().
109603  */
109604  static Trigger *fkActionTrigger(
109605    Parse *pParse,                  /* Parse context */
109606    Table *pTab,                    /* Table being updated or deleted from */
109607    FKey *pFKey,                    /* Foreign key to get action for */
109608    ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
109609  ){
109610    sqlite3 *db = pParse->db;       /* Database handle */
109611    int action;                     /* One of OE_None, OE_Cascade etc. */
109612    Trigger *pTrigger;              /* Trigger definition to return */
109613    int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
109614  
109615    action = pFKey->aAction[iAction];
109616    if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
109617      return 0;
109618    }
109619    pTrigger = pFKey->apTrigger[iAction];
109620  
109621    if( action!=OE_None && !pTrigger ){
109622      char const *zFrom;            /* Name of child table */
109623      int nFrom;                    /* Length in bytes of zFrom */
109624      Index *pIdx = 0;              /* Parent key index for this FK */
109625      int *aiCol = 0;               /* child table cols -> parent key cols */
109626      TriggerStep *pStep = 0;        /* First (only) step of trigger program */
109627      Expr *pWhere = 0;             /* WHERE clause of trigger step */
109628      ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
109629      Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
109630      int i;                        /* Iterator variable */
109631      Expr *pWhen = 0;              /* WHEN clause for the trigger */
109632  
109633      if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
109634      assert( aiCol || pFKey->nCol==1 );
109635  
109636      for(i=0; i<pFKey->nCol; i++){
109637        Token tOld = { "old", 3 };  /* Literal "old" token */
109638        Token tNew = { "new", 3 };  /* Literal "new" token */
109639        Token tFromCol;             /* Name of column in child table */
109640        Token tToCol;               /* Name of column in parent table */
109641        int iFromCol;               /* Idx of column in child table */
109642        Expr *pEq;                  /* tFromCol = OLD.tToCol */
109643  
109644        iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
109645        assert( iFromCol>=0 );
109646        assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
109647        assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
109648        sqlite3TokenInit(&tToCol,
109649                     pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
109650        sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
109651  
109652        /* Create the expression "OLD.zToCol = zFromCol". It is important
109653        ** that the "OLD.zToCol" term is on the LHS of the = operator, so
109654        ** that the affinity and collation sequence associated with the
109655        ** parent table are used for the comparison. */
109656        pEq = sqlite3PExpr(pParse, TK_EQ,
109657            sqlite3PExpr(pParse, TK_DOT, 
109658              sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
109659              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
109660            sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
109661        );
109662        pWhere = sqlite3ExprAnd(db, pWhere, pEq);
109663  
109664        /* For ON UPDATE, construct the next term of the WHEN clause.
109665        ** The final WHEN clause will be like this:
109666        **
109667        **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
109668        */
109669        if( pChanges ){
109670          pEq = sqlite3PExpr(pParse, TK_IS,
109671              sqlite3PExpr(pParse, TK_DOT, 
109672                sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
109673                sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
109674              sqlite3PExpr(pParse, TK_DOT, 
109675                sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
109676                sqlite3ExprAlloc(db, TK_ID, &tToCol, 0))
109677              );
109678          pWhen = sqlite3ExprAnd(db, pWhen, pEq);
109679        }
109680    
109681        if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
109682          Expr *pNew;
109683          if( action==OE_Cascade ){
109684            pNew = sqlite3PExpr(pParse, TK_DOT, 
109685              sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
109686              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0));
109687          }else if( action==OE_SetDflt ){
109688            Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
109689            if( pDflt ){
109690              pNew = sqlite3ExprDup(db, pDflt, 0);
109691            }else{
109692              pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
109693            }
109694          }else{
109695            pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
109696          }
109697          pList = sqlite3ExprListAppend(pParse, pList, pNew);
109698          sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
109699        }
109700      }
109701      sqlite3DbFree(db, aiCol);
109702  
109703      zFrom = pFKey->pFrom->zName;
109704      nFrom = sqlite3Strlen30(zFrom);
109705  
109706      if( action==OE_Restrict ){
109707        Token tFrom;
109708        Expr *pRaise; 
109709  
109710        tFrom.z = zFrom;
109711        tFrom.n = nFrom;
109712        pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
109713        if( pRaise ){
109714          pRaise->affinity = OE_Abort;
109715        }
109716        pSelect = sqlite3SelectNew(pParse, 
109717            sqlite3ExprListAppend(pParse, 0, pRaise),
109718            sqlite3SrcListAppend(db, 0, &tFrom, 0),
109719            pWhere,
109720            0, 0, 0, 0, 0, 0
109721        );
109722        pWhere = 0;
109723      }
109724  
109725      /* Disable lookaside memory allocation */
109726      db->lookaside.bDisable++;
109727  
109728      pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
109729          sizeof(Trigger) +         /* struct Trigger */
109730          sizeof(TriggerStep) +     /* Single step in trigger program */
109731          nFrom + 1                 /* Space for pStep->zTarget */
109732      );
109733      if( pTrigger ){
109734        pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
109735        pStep->zTarget = (char *)&pStep[1];
109736        memcpy((char *)pStep->zTarget, zFrom, nFrom);
109737    
109738        pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
109739        pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
109740        pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
109741        if( pWhen ){
109742          pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0);
109743          pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
109744        }
109745      }
109746  
109747      /* Re-enable the lookaside buffer, if it was disabled earlier. */
109748      db->lookaside.bDisable--;
109749  
109750      sqlite3ExprDelete(db, pWhere);
109751      sqlite3ExprDelete(db, pWhen);
109752      sqlite3ExprListDelete(db, pList);
109753      sqlite3SelectDelete(db, pSelect);
109754      if( db->mallocFailed==1 ){
109755        fkTriggerDelete(db, pTrigger);
109756        return 0;
109757      }
109758      assert( pStep!=0 );
109759  
109760      switch( action ){
109761        case OE_Restrict:
109762          pStep->op = TK_SELECT; 
109763          break;
109764        case OE_Cascade: 
109765          if( !pChanges ){ 
109766            pStep->op = TK_DELETE; 
109767            break; 
109768          }
109769        default:
109770          pStep->op = TK_UPDATE;
109771      }
109772      pStep->pTrig = pTrigger;
109773      pTrigger->pSchema = pTab->pSchema;
109774      pTrigger->pTabSchema = pTab->pSchema;
109775      pFKey->apTrigger[iAction] = pTrigger;
109776      pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
109777    }
109778  
109779    return pTrigger;
109780  }
109781  
109782  /*
109783  ** This function is called when deleting or updating a row to implement
109784  ** any required CASCADE, SET NULL or SET DEFAULT actions.
109785  */
109786  SQLITE_PRIVATE void sqlite3FkActions(
109787    Parse *pParse,                  /* Parse context */
109788    Table *pTab,                    /* Table being updated or deleted from */
109789    ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
109790    int regOld,                     /* Address of array containing old row */
109791    int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
109792    int bChngRowid                  /* True if rowid is UPDATEd */
109793  ){
109794    /* If foreign-key support is enabled, iterate through all FKs that 
109795    ** refer to table pTab. If there is an action associated with the FK 
109796    ** for this operation (either update or delete), invoke the associated 
109797    ** trigger sub-program.  */
109798    if( pParse->db->flags&SQLITE_ForeignKeys ){
109799      FKey *pFKey;                  /* Iterator variable */
109800      for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
109801        if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
109802          Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
109803          if( pAct ){
109804            sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
109805          }
109806        }
109807      }
109808    }
109809  }
109810  
109811  #endif /* ifndef SQLITE_OMIT_TRIGGER */
109812  
109813  /*
109814  ** Free all memory associated with foreign key definitions attached to
109815  ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
109816  ** hash table.
109817  */
109818  SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
109819    FKey *pFKey;                    /* Iterator variable */
109820    FKey *pNext;                    /* Copy of pFKey->pNextFrom */
109821  
109822    assert( db==0 || IsVirtual(pTab)
109823           || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
109824    for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
109825  
109826      /* Remove the FK from the fkeyHash hash table. */
109827      if( !db || db->pnBytesFreed==0 ){
109828        if( pFKey->pPrevTo ){
109829          pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
109830        }else{
109831          void *p = (void *)pFKey->pNextTo;
109832          const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
109833          sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
109834        }
109835        if( pFKey->pNextTo ){
109836          pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
109837        }
109838      }
109839  
109840      /* EV: R-30323-21917 Each foreign key constraint in SQLite is
109841      ** classified as either immediate or deferred.
109842      */
109843      assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
109844  
109845      /* Delete any triggers created to implement actions for this FK. */
109846  #ifndef SQLITE_OMIT_TRIGGER
109847      fkTriggerDelete(db, pFKey->apTrigger[0]);
109848      fkTriggerDelete(db, pFKey->apTrigger[1]);
109849  #endif
109850  
109851      pNext = pFKey->pNextFrom;
109852      sqlite3DbFree(db, pFKey);
109853    }
109854  }
109855  #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
109856  
109857  /************** End of fkey.c ************************************************/
109858  /************** Begin file insert.c ******************************************/
109859  /*
109860  ** 2001 September 15
109861  **
109862  ** The author disclaims copyright to this source code.  In place of
109863  ** a legal notice, here is a blessing:
109864  **
109865  **    May you do good and not evil.
109866  **    May you find forgiveness for yourself and forgive others.
109867  **    May you share freely, never taking more than you give.
109868  **
109869  *************************************************************************
109870  ** This file contains C code routines that are called by the parser
109871  ** to handle INSERT statements in SQLite.
109872  */
109873  /* #include "sqliteInt.h" */
109874  
109875  /*
109876  ** Generate code that will 
109877  **
109878  **   (1) acquire a lock for table pTab then
109879  **   (2) open pTab as cursor iCur.
109880  **
109881  ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
109882  ** for that table that is actually opened.
109883  */
109884  SQLITE_PRIVATE void sqlite3OpenTable(
109885    Parse *pParse,  /* Generate code into this VDBE */
109886    int iCur,       /* The cursor number of the table */
109887    int iDb,        /* The database index in sqlite3.aDb[] */
109888    Table *pTab,    /* The table to be opened */
109889    int opcode      /* OP_OpenRead or OP_OpenWrite */
109890  ){
109891    Vdbe *v;
109892    assert( !IsVirtual(pTab) );
109893    v = sqlite3GetVdbe(pParse);
109894    assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
109895    sqlite3TableLock(pParse, iDb, pTab->tnum, 
109896                     (opcode==OP_OpenWrite)?1:0, pTab->zName);
109897    if( HasRowid(pTab) ){
109898      sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
109899      VdbeComment((v, "%s", pTab->zName));
109900    }else{
109901      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
109902      assert( pPk!=0 );
109903      assert( pPk->tnum==pTab->tnum );
109904      sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
109905      sqlite3VdbeSetP4KeyInfo(pParse, pPk);
109906      VdbeComment((v, "%s", pTab->zName));
109907    }
109908  }
109909  
109910  /*
109911  ** Return a pointer to the column affinity string associated with index
109912  ** pIdx. A column affinity string has one character for each column in 
109913  ** the table, according to the affinity of the column:
109914  **
109915  **  Character      Column affinity
109916  **  ------------------------------
109917  **  'A'            BLOB
109918  **  'B'            TEXT
109919  **  'C'            NUMERIC
109920  **  'D'            INTEGER
109921  **  'F'            REAL
109922  **
109923  ** An extra 'D' is appended to the end of the string to cover the
109924  ** rowid that appears as the last column in every index.
109925  **
109926  ** Memory for the buffer containing the column index affinity string
109927  ** is managed along with the rest of the Index structure. It will be
109928  ** released when sqlite3DeleteIndex() is called.
109929  */
109930  SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
109931    if( !pIdx->zColAff ){
109932      /* The first time a column affinity string for a particular index is
109933      ** required, it is allocated and populated here. It is then stored as
109934      ** a member of the Index structure for subsequent use.
109935      **
109936      ** The column affinity string will eventually be deleted by
109937      ** sqliteDeleteIndex() when the Index structure itself is cleaned
109938      ** up.
109939      */
109940      int n;
109941      Table *pTab = pIdx->pTable;
109942      pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
109943      if( !pIdx->zColAff ){
109944        sqlite3OomFault(db);
109945        return 0;
109946      }
109947      for(n=0; n<pIdx->nColumn; n++){
109948        i16 x = pIdx->aiColumn[n];
109949        if( x>=0 ){
109950          pIdx->zColAff[n] = pTab->aCol[x].affinity;
109951        }else if( x==XN_ROWID ){
109952          pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
109953        }else{
109954          char aff;
109955          assert( x==XN_EXPR );
109956          assert( pIdx->aColExpr!=0 );
109957          aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
109958          if( aff==0 ) aff = SQLITE_AFF_BLOB;
109959          pIdx->zColAff[n] = aff;
109960        }
109961      }
109962      pIdx->zColAff[n] = 0;
109963    }
109964   
109965    return pIdx->zColAff;
109966  }
109967  
109968  /*
109969  ** Compute the affinity string for table pTab, if it has not already been
109970  ** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
109971  **
109972  ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
109973  ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
109974  ** for register iReg and following.  Or if affinities exists and iReg==0,
109975  ** then just set the P4 operand of the previous opcode (which should  be
109976  ** an OP_MakeRecord) to the affinity string.
109977  **
109978  ** A column affinity string has one character per column:
109979  **
109980  **  Character      Column affinity
109981  **  ------------------------------
109982  **  'A'            BLOB
109983  **  'B'            TEXT
109984  **  'C'            NUMERIC
109985  **  'D'            INTEGER
109986  **  'E'            REAL
109987  */
109988  SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
109989    int i;
109990    char *zColAff = pTab->zColAff;
109991    if( zColAff==0 ){
109992      sqlite3 *db = sqlite3VdbeDb(v);
109993      zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
109994      if( !zColAff ){
109995        sqlite3OomFault(db);
109996        return;
109997      }
109998  
109999      for(i=0; i<pTab->nCol; i++){
110000        zColAff[i] = pTab->aCol[i].affinity;
110001      }
110002      do{
110003        zColAff[i--] = 0;
110004      }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
110005      pTab->zColAff = zColAff;
110006    }
110007    i = sqlite3Strlen30(zColAff);
110008    if( i ){
110009      if( iReg ){
110010        sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
110011      }else{
110012        sqlite3VdbeChangeP4(v, -1, zColAff, i);
110013      }
110014    }
110015  }
110016  
110017  /*
110018  ** Return non-zero if the table pTab in database iDb or any of its indices
110019  ** have been opened at any point in the VDBE program. This is used to see if 
110020  ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
110021  ** run without using a temporary table for the results of the SELECT. 
110022  */
110023  static int readsTable(Parse *p, int iDb, Table *pTab){
110024    Vdbe *v = sqlite3GetVdbe(p);
110025    int i;
110026    int iEnd = sqlite3VdbeCurrentAddr(v);
110027  #ifndef SQLITE_OMIT_VIRTUALTABLE
110028    VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
110029  #endif
110030  
110031    for(i=1; i<iEnd; i++){
110032      VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
110033      assert( pOp!=0 );
110034      if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
110035        Index *pIndex;
110036        int tnum = pOp->p2;
110037        if( tnum==pTab->tnum ){
110038          return 1;
110039        }
110040        for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
110041          if( tnum==pIndex->tnum ){
110042            return 1;
110043          }
110044        }
110045      }
110046  #ifndef SQLITE_OMIT_VIRTUALTABLE
110047      if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
110048        assert( pOp->p4.pVtab!=0 );
110049        assert( pOp->p4type==P4_VTAB );
110050        return 1;
110051      }
110052  #endif
110053    }
110054    return 0;
110055  }
110056  
110057  #ifndef SQLITE_OMIT_AUTOINCREMENT
110058  /*
110059  ** Locate or create an AutoincInfo structure associated with table pTab
110060  ** which is in database iDb.  Return the register number for the register
110061  ** that holds the maximum rowid.  Return zero if pTab is not an AUTOINCREMENT
110062  ** table.  (Also return zero when doing a VACUUM since we do not want to
110063  ** update the AUTOINCREMENT counters during a VACUUM.)
110064  **
110065  ** There is at most one AutoincInfo structure per table even if the
110066  ** same table is autoincremented multiple times due to inserts within
110067  ** triggers.  A new AutoincInfo structure is created if this is the
110068  ** first use of table pTab.  On 2nd and subsequent uses, the original
110069  ** AutoincInfo structure is used.
110070  **
110071  ** Three memory locations are allocated:
110072  **
110073  **   (1)  Register to hold the name of the pTab table.
110074  **   (2)  Register to hold the maximum ROWID of pTab.
110075  **   (3)  Register to hold the rowid in sqlite_sequence of pTab
110076  **
110077  ** The 2nd register is the one that is returned.  That is all the
110078  ** insert routine needs to know about.
110079  */
110080  static int autoIncBegin(
110081    Parse *pParse,      /* Parsing context */
110082    int iDb,            /* Index of the database holding pTab */
110083    Table *pTab         /* The table we are writing to */
110084  ){
110085    int memId = 0;      /* Register holding maximum rowid */
110086    if( (pTab->tabFlags & TF_Autoincrement)!=0
110087     && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
110088    ){
110089      Parse *pToplevel = sqlite3ParseToplevel(pParse);
110090      AutoincInfo *pInfo;
110091  
110092      pInfo = pToplevel->pAinc;
110093      while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
110094      if( pInfo==0 ){
110095        pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
110096        if( pInfo==0 ) return 0;
110097        pInfo->pNext = pToplevel->pAinc;
110098        pToplevel->pAinc = pInfo;
110099        pInfo->pTab = pTab;
110100        pInfo->iDb = iDb;
110101        pToplevel->nMem++;                  /* Register to hold name of table */
110102        pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
110103        pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
110104      }
110105      memId = pInfo->regCtr;
110106    }
110107    return memId;
110108  }
110109  
110110  /*
110111  ** This routine generates code that will initialize all of the
110112  ** register used by the autoincrement tracker.  
110113  */
110114  SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
110115    AutoincInfo *p;            /* Information about an AUTOINCREMENT */
110116    sqlite3 *db = pParse->db;  /* The database connection */
110117    Db *pDb;                   /* Database only autoinc table */
110118    int memId;                 /* Register holding max rowid */
110119    Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
110120  
110121    /* This routine is never called during trigger-generation.  It is
110122    ** only called from the top-level */
110123    assert( pParse->pTriggerTab==0 );
110124    assert( sqlite3IsToplevel(pParse) );
110125  
110126    assert( v );   /* We failed long ago if this is not so */
110127    for(p = pParse->pAinc; p; p = p->pNext){
110128      static const int iLn = VDBE_OFFSET_LINENO(2);
110129      static const VdbeOpList autoInc[] = {
110130        /* 0  */ {OP_Null,    0,  0, 0},
110131        /* 1  */ {OP_Rewind,  0,  9, 0},
110132        /* 2  */ {OP_Column,  0,  0, 0},
110133        /* 3  */ {OP_Ne,      0,  7, 0},
110134        /* 4  */ {OP_Rowid,   0,  0, 0},
110135        /* 5  */ {OP_Column,  0,  1, 0},
110136        /* 6  */ {OP_Goto,    0,  9, 0},
110137        /* 7  */ {OP_Next,    0,  2, 0},
110138        /* 8  */ {OP_Integer, 0,  0, 0},
110139        /* 9  */ {OP_Close,   0,  0, 0} 
110140      };
110141      VdbeOp *aOp;
110142      pDb = &db->aDb[p->iDb];
110143      memId = p->regCtr;
110144      assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
110145      sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
110146      sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
110147      aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
110148      if( aOp==0 ) break;
110149      aOp[0].p2 = memId;
110150      aOp[0].p3 = memId+1;
110151      aOp[2].p3 = memId;
110152      aOp[3].p1 = memId-1;
110153      aOp[3].p3 = memId;
110154      aOp[3].p5 = SQLITE_JUMPIFNULL;
110155      aOp[4].p2 = memId+1;
110156      aOp[5].p3 = memId;
110157      aOp[8].p2 = memId;
110158    }
110159  }
110160  
110161  /*
110162  ** Update the maximum rowid for an autoincrement calculation.
110163  **
110164  ** This routine should be called when the regRowid register holds a
110165  ** new rowid that is about to be inserted.  If that new rowid is
110166  ** larger than the maximum rowid in the memId memory cell, then the
110167  ** memory cell is updated.
110168  */
110169  static void autoIncStep(Parse *pParse, int memId, int regRowid){
110170    if( memId>0 ){
110171      sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
110172    }
110173  }
110174  
110175  /*
110176  ** This routine generates the code needed to write autoincrement
110177  ** maximum rowid values back into the sqlite_sequence register.
110178  ** Every statement that might do an INSERT into an autoincrement
110179  ** table (either directly or through triggers) needs to call this
110180  ** routine just before the "exit" code.
110181  */
110182  static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
110183    AutoincInfo *p;
110184    Vdbe *v = pParse->pVdbe;
110185    sqlite3 *db = pParse->db;
110186  
110187    assert( v );
110188    for(p = pParse->pAinc; p; p = p->pNext){
110189      static const int iLn = VDBE_OFFSET_LINENO(2);
110190      static const VdbeOpList autoIncEnd[] = {
110191        /* 0 */ {OP_NotNull,     0, 2, 0},
110192        /* 1 */ {OP_NewRowid,    0, 0, 0},
110193        /* 2 */ {OP_MakeRecord,  0, 2, 0},
110194        /* 3 */ {OP_Insert,      0, 0, 0},
110195        /* 4 */ {OP_Close,       0, 0, 0}
110196      };
110197      VdbeOp *aOp;
110198      Db *pDb = &db->aDb[p->iDb];
110199      int iRec;
110200      int memId = p->regCtr;
110201  
110202      iRec = sqlite3GetTempReg(pParse);
110203      assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
110204      sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
110205      aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
110206      if( aOp==0 ) break;
110207      aOp[0].p1 = memId+1;
110208      aOp[1].p2 = memId+1;
110209      aOp[2].p1 = memId-1;
110210      aOp[2].p3 = iRec;
110211      aOp[3].p2 = iRec;
110212      aOp[3].p3 = memId+1;
110213      aOp[3].p5 = OPFLAG_APPEND;
110214      sqlite3ReleaseTempReg(pParse, iRec);
110215    }
110216  }
110217  SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
110218    if( pParse->pAinc ) autoIncrementEnd(pParse);
110219  }
110220  #else
110221  /*
110222  ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
110223  ** above are all no-ops
110224  */
110225  # define autoIncBegin(A,B,C) (0)
110226  # define autoIncStep(A,B,C)
110227  #endif /* SQLITE_OMIT_AUTOINCREMENT */
110228  
110229  
110230  /* Forward declaration */
110231  static int xferOptimization(
110232    Parse *pParse,        /* Parser context */
110233    Table *pDest,         /* The table we are inserting into */
110234    Select *pSelect,      /* A SELECT statement to use as the data source */
110235    int onError,          /* How to handle constraint errors */
110236    int iDbDest           /* The database of pDest */
110237  );
110238  
110239  /*
110240  ** This routine is called to handle SQL of the following forms:
110241  **
110242  **    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
110243  **    insert into TABLE (IDLIST) select
110244  **    insert into TABLE (IDLIST) default values
110245  **
110246  ** The IDLIST following the table name is always optional.  If omitted,
110247  ** then a list of all (non-hidden) columns for the table is substituted.
110248  ** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
110249  ** is omitted.
110250  **
110251  ** For the pSelect parameter holds the values to be inserted for the
110252  ** first two forms shown above.  A VALUES clause is really just short-hand
110253  ** for a SELECT statement that omits the FROM clause and everything else
110254  ** that follows.  If the pSelect parameter is NULL, that means that the
110255  ** DEFAULT VALUES form of the INSERT statement is intended.
110256  **
110257  ** The code generated follows one of four templates.  For a simple
110258  ** insert with data coming from a single-row VALUES clause, the code executes
110259  ** once straight down through.  Pseudo-code follows (we call this
110260  ** the "1st template"):
110261  **
110262  **         open write cursor to <table> and its indices
110263  **         put VALUES clause expressions into registers
110264  **         write the resulting record into <table>
110265  **         cleanup
110266  **
110267  ** The three remaining templates assume the statement is of the form
110268  **
110269  **   INSERT INTO <table> SELECT ...
110270  **
110271  ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
110272  ** in other words if the SELECT pulls all columns from a single table
110273  ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
110274  ** if <table2> and <table1> are distinct tables but have identical
110275  ** schemas, including all the same indices, then a special optimization
110276  ** is invoked that copies raw records from <table2> over to <table1>.
110277  ** See the xferOptimization() function for the implementation of this
110278  ** template.  This is the 2nd template.
110279  **
110280  **         open a write cursor to <table>
110281  **         open read cursor on <table2>
110282  **         transfer all records in <table2> over to <table>
110283  **         close cursors
110284  **         foreach index on <table>
110285  **           open a write cursor on the <table> index
110286  **           open a read cursor on the corresponding <table2> index
110287  **           transfer all records from the read to the write cursors
110288  **           close cursors
110289  **         end foreach
110290  **
110291  ** The 3rd template is for when the second template does not apply
110292  ** and the SELECT clause does not read from <table> at any time.
110293  ** The generated code follows this template:
110294  **
110295  **         X <- A
110296  **         goto B
110297  **      A: setup for the SELECT
110298  **         loop over the rows in the SELECT
110299  **           load values into registers R..R+n
110300  **           yield X
110301  **         end loop
110302  **         cleanup after the SELECT
110303  **         end-coroutine X
110304  **      B: open write cursor to <table> and its indices
110305  **      C: yield X, at EOF goto D
110306  **         insert the select result into <table> from R..R+n
110307  **         goto C
110308  **      D: cleanup
110309  **
110310  ** The 4th template is used if the insert statement takes its
110311  ** values from a SELECT but the data is being inserted into a table
110312  ** that is also read as part of the SELECT.  In the third form,
110313  ** we have to use an intermediate table to store the results of
110314  ** the select.  The template is like this:
110315  **
110316  **         X <- A
110317  **         goto B
110318  **      A: setup for the SELECT
110319  **         loop over the tables in the SELECT
110320  **           load value into register R..R+n
110321  **           yield X
110322  **         end loop
110323  **         cleanup after the SELECT
110324  **         end co-routine R
110325  **      B: open temp table
110326  **      L: yield X, at EOF goto M
110327  **         insert row from R..R+n into temp table
110328  **         goto L
110329  **      M: open write cursor to <table> and its indices
110330  **         rewind temp table
110331  **      C: loop over rows of intermediate table
110332  **           transfer values form intermediate table into <table>
110333  **         end loop
110334  **      D: cleanup
110335  */
110336  SQLITE_PRIVATE void sqlite3Insert(
110337    Parse *pParse,        /* Parser context */
110338    SrcList *pTabList,    /* Name of table into which we are inserting */
110339    Select *pSelect,      /* A SELECT statement to use as the data source */
110340    IdList *pColumn,      /* Column names corresponding to IDLIST. */
110341    int onError           /* How to handle constraint errors */
110342  ){
110343    sqlite3 *db;          /* The main database structure */
110344    Table *pTab;          /* The table to insert into.  aka TABLE */
110345    int i, j;             /* Loop counters */
110346    Vdbe *v;              /* Generate code into this virtual machine */
110347    Index *pIdx;          /* For looping over indices of the table */
110348    int nColumn;          /* Number of columns in the data */
110349    int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
110350    int iDataCur = 0;     /* VDBE cursor that is the main data repository */
110351    int iIdxCur = 0;      /* First index cursor */
110352    int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
110353    int endOfLoop;        /* Label for the end of the insertion loop */
110354    int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
110355    int addrInsTop = 0;   /* Jump to label "D" */
110356    int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
110357    SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
110358    int iDb;              /* Index of database holding TABLE */
110359    u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
110360    u8 appendFlag = 0;    /* True if the insert is likely to be an append */
110361    u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
110362    u8 bIdListInOrder;    /* True if IDLIST is in table order */
110363    ExprList *pList = 0;  /* List of VALUES() to be inserted  */
110364  
110365    /* Register allocations */
110366    int regFromSelect = 0;/* Base register for data coming from SELECT */
110367    int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
110368    int regRowCount = 0;  /* Memory cell used for the row counter */
110369    int regIns;           /* Block of regs holding rowid+data being inserted */
110370    int regRowid;         /* registers holding insert rowid */
110371    int regData;          /* register holding first column to insert */
110372    int *aRegIdx = 0;     /* One register allocated to each index */
110373  
110374  #ifndef SQLITE_OMIT_TRIGGER
110375    int isView;                 /* True if attempting to insert into a view */
110376    Trigger *pTrigger;          /* List of triggers on pTab, if required */
110377    int tmask;                  /* Mask of trigger times */
110378  #endif
110379  
110380    db = pParse->db;
110381    if( pParse->nErr || db->mallocFailed ){
110382      goto insert_cleanup;
110383    }
110384    dest.iSDParm = 0;  /* Suppress a harmless compiler warning */
110385  
110386    /* If the Select object is really just a simple VALUES() list with a
110387    ** single row (the common case) then keep that one row of values
110388    ** and discard the other (unused) parts of the pSelect object
110389    */
110390    if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
110391      pList = pSelect->pEList;
110392      pSelect->pEList = 0;
110393      sqlite3SelectDelete(db, pSelect);
110394      pSelect = 0;
110395    }
110396  
110397    /* Locate the table into which we will be inserting new information.
110398    */
110399    assert( pTabList->nSrc==1 );
110400    pTab = sqlite3SrcListLookup(pParse, pTabList);
110401    if( pTab==0 ){
110402      goto insert_cleanup;
110403    }
110404    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
110405    assert( iDb<db->nDb );
110406    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
110407                         db->aDb[iDb].zDbSName) ){
110408      goto insert_cleanup;
110409    }
110410    withoutRowid = !HasRowid(pTab);
110411  
110412    /* Figure out if we have any triggers and if the table being
110413    ** inserted into is a view
110414    */
110415  #ifndef SQLITE_OMIT_TRIGGER
110416    pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
110417    isView = pTab->pSelect!=0;
110418  #else
110419  # define pTrigger 0
110420  # define tmask 0
110421  # define isView 0
110422  #endif
110423  #ifdef SQLITE_OMIT_VIEW
110424  # undef isView
110425  # define isView 0
110426  #endif
110427    assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
110428  
110429    /* If pTab is really a view, make sure it has been initialized.
110430    ** ViewGetColumnNames() is a no-op if pTab is not a view.
110431    */
110432    if( sqlite3ViewGetColumnNames(pParse, pTab) ){
110433      goto insert_cleanup;
110434    }
110435  
110436    /* Cannot insert into a read-only table.
110437    */
110438    if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
110439      goto insert_cleanup;
110440    }
110441  
110442    /* Allocate a VDBE
110443    */
110444    v = sqlite3GetVdbe(pParse);
110445    if( v==0 ) goto insert_cleanup;
110446    if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
110447    sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
110448  
110449  #ifndef SQLITE_OMIT_XFER_OPT
110450    /* If the statement is of the form
110451    **
110452    **       INSERT INTO <table1> SELECT * FROM <table2>;
110453    **
110454    ** Then special optimizations can be applied that make the transfer
110455    ** very fast and which reduce fragmentation of indices.
110456    **
110457    ** This is the 2nd template.
110458    */
110459    if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
110460      assert( !pTrigger );
110461      assert( pList==0 );
110462      goto insert_end;
110463    }
110464  #endif /* SQLITE_OMIT_XFER_OPT */
110465  
110466    /* If this is an AUTOINCREMENT table, look up the sequence number in the
110467    ** sqlite_sequence table and store it in memory cell regAutoinc.
110468    */
110469    regAutoinc = autoIncBegin(pParse, iDb, pTab);
110470  
110471    /* Allocate registers for holding the rowid of the new row,
110472    ** the content of the new row, and the assembled row record.
110473    */
110474    regRowid = regIns = pParse->nMem+1;
110475    pParse->nMem += pTab->nCol + 1;
110476    if( IsVirtual(pTab) ){
110477      regRowid++;
110478      pParse->nMem++;
110479    }
110480    regData = regRowid+1;
110481  
110482    /* If the INSERT statement included an IDLIST term, then make sure
110483    ** all elements of the IDLIST really are columns of the table and 
110484    ** remember the column indices.
110485    **
110486    ** If the table has an INTEGER PRIMARY KEY column and that column
110487    ** is named in the IDLIST, then record in the ipkColumn variable
110488    ** the index into IDLIST of the primary key column.  ipkColumn is
110489    ** the index of the primary key as it appears in IDLIST, not as
110490    ** is appears in the original table.  (The index of the INTEGER
110491    ** PRIMARY KEY in the original table is pTab->iPKey.)
110492    */
110493    bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
110494    if( pColumn ){
110495      for(i=0; i<pColumn->nId; i++){
110496        pColumn->a[i].idx = -1;
110497      }
110498      for(i=0; i<pColumn->nId; i++){
110499        for(j=0; j<pTab->nCol; j++){
110500          if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
110501            pColumn->a[i].idx = j;
110502            if( i!=j ) bIdListInOrder = 0;
110503            if( j==pTab->iPKey ){
110504              ipkColumn = i;  assert( !withoutRowid );
110505            }
110506            break;
110507          }
110508        }
110509        if( j>=pTab->nCol ){
110510          if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
110511            ipkColumn = i;
110512            bIdListInOrder = 0;
110513          }else{
110514            sqlite3ErrorMsg(pParse, "table %S has no column named %s",
110515                pTabList, 0, pColumn->a[i].zName);
110516            pParse->checkSchema = 1;
110517            goto insert_cleanup;
110518          }
110519        }
110520      }
110521    }
110522  
110523    /* Figure out how many columns of data are supplied.  If the data
110524    ** is coming from a SELECT statement, then generate a co-routine that
110525    ** produces a single row of the SELECT on each invocation.  The
110526    ** co-routine is the common header to the 3rd and 4th templates.
110527    */
110528    if( pSelect ){
110529      /* Data is coming from a SELECT or from a multi-row VALUES clause.
110530      ** Generate a co-routine to run the SELECT. */
110531      int regYield;       /* Register holding co-routine entry-point */
110532      int addrTop;        /* Top of the co-routine */
110533      int rc;             /* Result code */
110534  
110535      regYield = ++pParse->nMem;
110536      addrTop = sqlite3VdbeCurrentAddr(v) + 1;
110537      sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
110538      sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
110539      dest.iSdst = bIdListInOrder ? regData : 0;
110540      dest.nSdst = pTab->nCol;
110541      rc = sqlite3Select(pParse, pSelect, &dest);
110542      regFromSelect = dest.iSdst;
110543      if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
110544      sqlite3VdbeEndCoroutine(v, regYield);
110545      sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
110546      assert( pSelect->pEList );
110547      nColumn = pSelect->pEList->nExpr;
110548  
110549      /* Set useTempTable to TRUE if the result of the SELECT statement
110550      ** should be written into a temporary table (template 4).  Set to
110551      ** FALSE if each output row of the SELECT can be written directly into
110552      ** the destination table (template 3).
110553      **
110554      ** A temp table must be used if the table being updated is also one
110555      ** of the tables being read by the SELECT statement.  Also use a 
110556      ** temp table in the case of row triggers.
110557      */
110558      if( pTrigger || readsTable(pParse, iDb, pTab) ){
110559        useTempTable = 1;
110560      }
110561  
110562      if( useTempTable ){
110563        /* Invoke the coroutine to extract information from the SELECT
110564        ** and add it to a transient table srcTab.  The code generated
110565        ** here is from the 4th template:
110566        **
110567        **      B: open temp table
110568        **      L: yield X, goto M at EOF
110569        **         insert row from R..R+n into temp table
110570        **         goto L
110571        **      M: ...
110572        */
110573        int regRec;          /* Register to hold packed record */
110574        int regTempRowid;    /* Register to hold temp table ROWID */
110575        int addrL;           /* Label "L" */
110576  
110577        srcTab = pParse->nTab++;
110578        regRec = sqlite3GetTempReg(pParse);
110579        regTempRowid = sqlite3GetTempReg(pParse);
110580        sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
110581        addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
110582        sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
110583        sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
110584        sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
110585        sqlite3VdbeGoto(v, addrL);
110586        sqlite3VdbeJumpHere(v, addrL);
110587        sqlite3ReleaseTempReg(pParse, regRec);
110588        sqlite3ReleaseTempReg(pParse, regTempRowid);
110589      }
110590    }else{
110591      /* This is the case if the data for the INSERT is coming from a 
110592      ** single-row VALUES clause
110593      */
110594      NameContext sNC;
110595      memset(&sNC, 0, sizeof(sNC));
110596      sNC.pParse = pParse;
110597      srcTab = -1;
110598      assert( useTempTable==0 );
110599      if( pList ){
110600        nColumn = pList->nExpr;
110601        if( sqlite3ResolveExprListNames(&sNC, pList) ){
110602          goto insert_cleanup;
110603        }
110604      }else{
110605        nColumn = 0;
110606      }
110607    }
110608  
110609    /* If there is no IDLIST term but the table has an integer primary
110610    ** key, the set the ipkColumn variable to the integer primary key 
110611    ** column index in the original table definition.
110612    */
110613    if( pColumn==0 && nColumn>0 ){
110614      ipkColumn = pTab->iPKey;
110615    }
110616  
110617    /* Make sure the number of columns in the source data matches the number
110618    ** of columns to be inserted into the table.
110619    */
110620    for(i=0; i<pTab->nCol; i++){
110621      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
110622    }
110623    if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
110624      sqlite3ErrorMsg(pParse, 
110625         "table %S has %d columns but %d values were supplied",
110626         pTabList, 0, pTab->nCol-nHidden, nColumn);
110627      goto insert_cleanup;
110628    }
110629    if( pColumn!=0 && nColumn!=pColumn->nId ){
110630      sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
110631      goto insert_cleanup;
110632    }
110633      
110634    /* Initialize the count of rows to be inserted
110635    */
110636    if( db->flags & SQLITE_CountRows ){
110637      regRowCount = ++pParse->nMem;
110638      sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
110639    }
110640  
110641    /* If this is not a view, open the table and and all indices */
110642    if( !isView ){
110643      int nIdx;
110644      nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
110645                                        &iDataCur, &iIdxCur);
110646      aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
110647      if( aRegIdx==0 ){
110648        goto insert_cleanup;
110649      }
110650      for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
110651        assert( pIdx );
110652        aRegIdx[i] = ++pParse->nMem;
110653        pParse->nMem += pIdx->nColumn;
110654      }
110655    }
110656  
110657    /* This is the top of the main insertion loop */
110658    if( useTempTable ){
110659      /* This block codes the top of loop only.  The complete loop is the
110660      ** following pseudocode (template 4):
110661      **
110662      **         rewind temp table, if empty goto D
110663      **      C: loop over rows of intermediate table
110664      **           transfer values form intermediate table into <table>
110665      **         end loop
110666      **      D: ...
110667      */
110668      addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
110669      addrCont = sqlite3VdbeCurrentAddr(v);
110670    }else if( pSelect ){
110671      /* This block codes the top of loop only.  The complete loop is the
110672      ** following pseudocode (template 3):
110673      **
110674      **      C: yield X, at EOF goto D
110675      **         insert the select result into <table> from R..R+n
110676      **         goto C
110677      **      D: ...
110678      */
110679      addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
110680      VdbeCoverage(v);
110681    }
110682  
110683    /* Run the BEFORE and INSTEAD OF triggers, if there are any
110684    */
110685    endOfLoop = sqlite3VdbeMakeLabel(v);
110686    if( tmask & TRIGGER_BEFORE ){
110687      int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
110688  
110689      /* build the NEW.* reference row.  Note that if there is an INTEGER
110690      ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
110691      ** translated into a unique ID for the row.  But on a BEFORE trigger,
110692      ** we do not know what the unique ID will be (because the insert has
110693      ** not happened yet) so we substitute a rowid of -1
110694      */
110695      if( ipkColumn<0 ){
110696        sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
110697      }else{
110698        int addr1;
110699        assert( !withoutRowid );
110700        if( useTempTable ){
110701          sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
110702        }else{
110703          assert( pSelect==0 );  /* Otherwise useTempTable is true */
110704          sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
110705        }
110706        addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
110707        sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
110708        sqlite3VdbeJumpHere(v, addr1);
110709        sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
110710      }
110711  
110712      /* Cannot have triggers on a virtual table. If it were possible,
110713      ** this block would have to account for hidden column.
110714      */
110715      assert( !IsVirtual(pTab) );
110716  
110717      /* Create the new column data
110718      */
110719      for(i=j=0; i<pTab->nCol; i++){
110720        if( pColumn ){
110721          for(j=0; j<pColumn->nId; j++){
110722            if( pColumn->a[j].idx==i ) break;
110723          }
110724        }
110725        if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
110726              || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
110727          sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
110728        }else if( useTempTable ){
110729          sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
110730        }else{
110731          assert( pSelect==0 ); /* Otherwise useTempTable is true */
110732          sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
110733        }
110734        if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
110735      }
110736  
110737      /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
110738      ** do not attempt any conversions before assembling the record.
110739      ** If this is a real table, attempt conversions as required by the
110740      ** table column affinities.
110741      */
110742      if( !isView ){
110743        sqlite3TableAffinity(v, pTab, regCols+1);
110744      }
110745  
110746      /* Fire BEFORE or INSTEAD OF triggers */
110747      sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
110748          pTab, regCols-pTab->nCol-1, onError, endOfLoop);
110749  
110750      sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
110751    }
110752  
110753    /* Compute the content of the next row to insert into a range of
110754    ** registers beginning at regIns.
110755    */
110756    if( !isView ){
110757      if( IsVirtual(pTab) ){
110758        /* The row that the VUpdate opcode will delete: none */
110759        sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
110760      }
110761      if( ipkColumn>=0 ){
110762        if( useTempTable ){
110763          sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
110764        }else if( pSelect ){
110765          sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
110766        }else{
110767          VdbeOp *pOp;
110768          sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
110769          pOp = sqlite3VdbeGetOp(v, -1);
110770          if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
110771            appendFlag = 1;
110772            pOp->opcode = OP_NewRowid;
110773            pOp->p1 = iDataCur;
110774            pOp->p2 = regRowid;
110775            pOp->p3 = regAutoinc;
110776          }
110777        }
110778        /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
110779        ** to generate a unique primary key value.
110780        */
110781        if( !appendFlag ){
110782          int addr1;
110783          if( !IsVirtual(pTab) ){
110784            addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
110785            sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
110786            sqlite3VdbeJumpHere(v, addr1);
110787          }else{
110788            addr1 = sqlite3VdbeCurrentAddr(v);
110789            sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
110790          }
110791          sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
110792        }
110793      }else if( IsVirtual(pTab) || withoutRowid ){
110794        sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
110795      }else{
110796        sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
110797        appendFlag = 1;
110798      }
110799      autoIncStep(pParse, regAutoinc, regRowid);
110800  
110801      /* Compute data for all columns of the new entry, beginning
110802      ** with the first column.
110803      */
110804      nHidden = 0;
110805      for(i=0; i<pTab->nCol; i++){
110806        int iRegStore = regRowid+1+i;
110807        if( i==pTab->iPKey ){
110808          /* The value of the INTEGER PRIMARY KEY column is always a NULL.
110809          ** Whenever this column is read, the rowid will be substituted
110810          ** in its place.  Hence, fill this column with a NULL to avoid
110811          ** taking up data space with information that will never be used.
110812          ** As there may be shallow copies of this value, make it a soft-NULL */
110813          sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
110814          continue;
110815        }
110816        if( pColumn==0 ){
110817          if( IsHiddenColumn(&pTab->aCol[i]) ){
110818            j = -1;
110819            nHidden++;
110820          }else{
110821            j = i - nHidden;
110822          }
110823        }else{
110824          for(j=0; j<pColumn->nId; j++){
110825            if( pColumn->a[j].idx==i ) break;
110826          }
110827        }
110828        if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
110829          sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
110830        }else if( useTempTable ){
110831          sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
110832        }else if( pSelect ){
110833          if( regFromSelect!=regData ){
110834            sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
110835          }
110836        }else{
110837          sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
110838        }
110839      }
110840  
110841      /* Generate code to check constraints and generate index keys and
110842      ** do the insertion.
110843      */
110844  #ifndef SQLITE_OMIT_VIRTUALTABLE
110845      if( IsVirtual(pTab) ){
110846        const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
110847        sqlite3VtabMakeWritable(pParse, pTab);
110848        sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
110849        sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
110850        sqlite3MayAbort(pParse);
110851      }else
110852  #endif
110853      {
110854        int isReplace;    /* Set to true if constraints may cause a replace */
110855        int bUseSeek;     /* True to use OPFLAG_SEEKRESULT */
110856        sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
110857            regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0
110858        );
110859        sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
110860  
110861        /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
110862        ** constraints or (b) there are no triggers and this table is not a
110863        ** parent table in a foreign key constraint. It is safe to set the
110864        ** flag in the second case as if any REPLACE constraint is hit, an
110865        ** OP_Delete or OP_IdxDelete instruction will be executed on each 
110866        ** cursor that is disturbed. And these instructions both clear the
110867        ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
110868        ** functionality.  */
110869        bUseSeek = (isReplace==0 || (pTrigger==0 &&
110870            ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0)
110871        ));
110872        sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
110873            regIns, aRegIdx, 0, appendFlag, bUseSeek
110874        );
110875      }
110876    }
110877  
110878    /* Update the count of rows that are inserted
110879    */
110880    if( (db->flags & SQLITE_CountRows)!=0 ){
110881      sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
110882    }
110883  
110884    if( pTrigger ){
110885      /* Code AFTER triggers */
110886      sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
110887          pTab, regData-2-pTab->nCol, onError, endOfLoop);
110888    }
110889  
110890    /* The bottom of the main insertion loop, if the data source
110891    ** is a SELECT statement.
110892    */
110893    sqlite3VdbeResolveLabel(v, endOfLoop);
110894    if( useTempTable ){
110895      sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
110896      sqlite3VdbeJumpHere(v, addrInsTop);
110897      sqlite3VdbeAddOp1(v, OP_Close, srcTab);
110898    }else if( pSelect ){
110899      sqlite3VdbeGoto(v, addrCont);
110900      sqlite3VdbeJumpHere(v, addrInsTop);
110901    }
110902  
110903  insert_end:
110904    /* Update the sqlite_sequence table by storing the content of the
110905    ** maximum rowid counter values recorded while inserting into
110906    ** autoincrement tables.
110907    */
110908    if( pParse->nested==0 && pParse->pTriggerTab==0 ){
110909      sqlite3AutoincrementEnd(pParse);
110910    }
110911  
110912    /*
110913    ** Return the number of rows inserted. If this routine is 
110914    ** generating code because of a call to sqlite3NestedParse(), do not
110915    ** invoke the callback function.
110916    */
110917    if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
110918      sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
110919      sqlite3VdbeSetNumCols(v, 1);
110920      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
110921    }
110922  
110923  insert_cleanup:
110924    sqlite3SrcListDelete(db, pTabList);
110925    sqlite3ExprListDelete(db, pList);
110926    sqlite3SelectDelete(db, pSelect);
110927    sqlite3IdListDelete(db, pColumn);
110928    sqlite3DbFree(db, aRegIdx);
110929  }
110930  
110931  /* Make sure "isView" and other macros defined above are undefined. Otherwise
110932  ** they may interfere with compilation of other functions in this file
110933  ** (or in another file, if this file becomes part of the amalgamation).  */
110934  #ifdef isView
110935   #undef isView
110936  #endif
110937  #ifdef pTrigger
110938   #undef pTrigger
110939  #endif
110940  #ifdef tmask
110941   #undef tmask
110942  #endif
110943  
110944  /*
110945  ** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
110946  */
110947  #define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */
110948  #define CKCNSTRNT_ROWID    0x02    /* CHECK constraint references the ROWID */
110949  
110950  /* This is the Walker callback from checkConstraintUnchanged().  Set
110951  ** bit 0x01 of pWalker->eCode if
110952  ** pWalker->eCode to 0 if this expression node references any of the
110953  ** columns that are being modifed by an UPDATE statement.
110954  */
110955  static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
110956    if( pExpr->op==TK_COLUMN ){
110957      assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
110958      if( pExpr->iColumn>=0 ){
110959        if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
110960          pWalker->eCode |= CKCNSTRNT_COLUMN;
110961        }
110962      }else{
110963        pWalker->eCode |= CKCNSTRNT_ROWID;
110964      }
110965    }
110966    return WRC_Continue;
110967  }
110968  
110969  /*
110970  ** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The
110971  ** only columns that are modified by the UPDATE are those for which
110972  ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
110973  **
110974  ** Return true if CHECK constraint pExpr does not use any of the
110975  ** changing columns (or the rowid if it is changing).  In other words,
110976  ** return true if this CHECK constraint can be skipped when validating
110977  ** the new row in the UPDATE statement.
110978  */
110979  static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
110980    Walker w;
110981    memset(&w, 0, sizeof(w));
110982    w.eCode = 0;
110983    w.xExprCallback = checkConstraintExprNode;
110984    w.u.aiCol = aiChng;
110985    sqlite3WalkExpr(&w, pExpr);
110986    if( !chngRowid ){
110987      testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
110988      w.eCode &= ~CKCNSTRNT_ROWID;
110989    }
110990    testcase( w.eCode==0 );
110991    testcase( w.eCode==CKCNSTRNT_COLUMN );
110992    testcase( w.eCode==CKCNSTRNT_ROWID );
110993    testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
110994    return !w.eCode;
110995  }
110996  
110997  /*
110998  ** Generate code to do constraint checks prior to an INSERT or an UPDATE
110999  ** on table pTab.
111000  **
111001  ** The regNewData parameter is the first register in a range that contains
111002  ** the data to be inserted or the data after the update.  There will be
111003  ** pTab->nCol+1 registers in this range.  The first register (the one
111004  ** that regNewData points to) will contain the new rowid, or NULL in the
111005  ** case of a WITHOUT ROWID table.  The second register in the range will
111006  ** contain the content of the first table column.  The third register will
111007  ** contain the content of the second table column.  And so forth.
111008  **
111009  ** The regOldData parameter is similar to regNewData except that it contains
111010  ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
111011  ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
111012  ** checking regOldData for zero.
111013  **
111014  ** For an UPDATE, the pkChng boolean is true if the true primary key (the
111015  ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
111016  ** might be modified by the UPDATE.  If pkChng is false, then the key of
111017  ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
111018  **
111019  ** For an INSERT, the pkChng boolean indicates whether or not the rowid
111020  ** was explicitly specified as part of the INSERT statement.  If pkChng
111021  ** is zero, it means that the either rowid is computed automatically or
111022  ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
111023  ** pkChng will only be true if the INSERT statement provides an integer
111024  ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
111025  **
111026  ** The code generated by this routine will store new index entries into
111027  ** registers identified by aRegIdx[].  No index entry is created for
111028  ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
111029  ** the same as the order of indices on the linked list of indices
111030  ** at pTab->pIndex.
111031  **
111032  ** The caller must have already opened writeable cursors on the main
111033  ** table and all applicable indices (that is to say, all indices for which
111034  ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
111035  ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
111036  ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
111037  ** for the first index in the pTab->pIndex list.  Cursors for other indices
111038  ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
111039  **
111040  ** This routine also generates code to check constraints.  NOT NULL,
111041  ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
111042  ** then the appropriate action is performed.  There are five possible
111043  ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
111044  **
111045  **  Constraint type  Action       What Happens
111046  **  ---------------  ----------   ----------------------------------------
111047  **  any              ROLLBACK     The current transaction is rolled back and
111048  **                                sqlite3_step() returns immediately with a
111049  **                                return code of SQLITE_CONSTRAINT.
111050  **
111051  **  any              ABORT        Back out changes from the current command
111052  **                                only (do not do a complete rollback) then
111053  **                                cause sqlite3_step() to return immediately
111054  **                                with SQLITE_CONSTRAINT.
111055  **
111056  **  any              FAIL         Sqlite3_step() returns immediately with a
111057  **                                return code of SQLITE_CONSTRAINT.  The
111058  **                                transaction is not rolled back and any
111059  **                                changes to prior rows are retained.
111060  **
111061  **  any              IGNORE       The attempt in insert or update the current
111062  **                                row is skipped, without throwing an error.
111063  **                                Processing continues with the next row.
111064  **                                (There is an immediate jump to ignoreDest.)
111065  **
111066  **  NOT NULL         REPLACE      The NULL value is replace by the default
111067  **                                value for that column.  If the default value
111068  **                                is NULL, the action is the same as ABORT.
111069  **
111070  **  UNIQUE           REPLACE      The other row that conflicts with the row
111071  **                                being inserted is removed.
111072  **
111073  **  CHECK            REPLACE      Illegal.  The results in an exception.
111074  **
111075  ** Which action to take is determined by the overrideError parameter.
111076  ** Or if overrideError==OE_Default, then the pParse->onError parameter
111077  ** is used.  Or if pParse->onError==OE_Default then the onError value
111078  ** for the constraint is used.
111079  */
111080  SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
111081    Parse *pParse,       /* The parser context */
111082    Table *pTab,         /* The table being inserted or updated */
111083    int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
111084    int iDataCur,        /* Canonical data cursor (main table or PK index) */
111085    int iIdxCur,         /* First index cursor */
111086    int regNewData,      /* First register in a range holding values to insert */
111087    int regOldData,      /* Previous content.  0 for INSERTs */
111088    u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
111089    u8 overrideError,    /* Override onError to this if not OE_Default */
111090    int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
111091    int *pbMayReplace,   /* OUT: Set to true if constraint may cause a replace */
111092    int *aiChng          /* column i is unchanged if aiChng[i]<0 */
111093  ){
111094    Vdbe *v;             /* VDBE under constrution */
111095    Index *pIdx;         /* Pointer to one of the indices */
111096    Index *pPk = 0;      /* The PRIMARY KEY index */
111097    sqlite3 *db;         /* Database connection */
111098    int i;               /* loop counter */
111099    int ix;              /* Index loop counter */
111100    int nCol;            /* Number of columns */
111101    int onError;         /* Conflict resolution strategy */
111102    int addr1;           /* Address of jump instruction */
111103    int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
111104    int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
111105    int ipkTop = 0;      /* Top of the rowid change constraint check */
111106    int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
111107    u8 isUpdate;         /* True if this is an UPDATE operation */
111108    u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
111109  
111110    isUpdate = regOldData!=0;
111111    db = pParse->db;
111112    v = sqlite3GetVdbe(pParse);
111113    assert( v!=0 );
111114    assert( pTab->pSelect==0 );  /* This table is not a VIEW */
111115    nCol = pTab->nCol;
111116    
111117    /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
111118    ** normal rowid tables.  nPkField is the number of key fields in the 
111119    ** pPk index or 1 for a rowid table.  In other words, nPkField is the
111120    ** number of fields in the true primary key of the table. */
111121    if( HasRowid(pTab) ){
111122      pPk = 0;
111123      nPkField = 1;
111124    }else{
111125      pPk = sqlite3PrimaryKeyIndex(pTab);
111126      nPkField = pPk->nKeyCol;
111127    }
111128  
111129    /* Record that this module has started */
111130    VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
111131                       iDataCur, iIdxCur, regNewData, regOldData, pkChng));
111132  
111133    /* Test all NOT NULL constraints.
111134    */
111135    for(i=0; i<nCol; i++){
111136      if( i==pTab->iPKey ){
111137        continue;        /* ROWID is never NULL */
111138      }
111139      if( aiChng && aiChng[i]<0 ){
111140        /* Don't bother checking for NOT NULL on columns that do not change */
111141        continue;
111142      }
111143      onError = pTab->aCol[i].notNull;
111144      if( onError==OE_None ) continue;  /* This column is allowed to be NULL */
111145      if( overrideError!=OE_Default ){
111146        onError = overrideError;
111147      }else if( onError==OE_Default ){
111148        onError = OE_Abort;
111149      }
111150      if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
111151        onError = OE_Abort;
111152      }
111153      assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
111154          || onError==OE_Ignore || onError==OE_Replace );
111155      switch( onError ){
111156        case OE_Abort:
111157          sqlite3MayAbort(pParse);
111158          /* Fall through */
111159        case OE_Rollback:
111160        case OE_Fail: {
111161          char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
111162                                      pTab->aCol[i].zName);
111163          sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
111164                            regNewData+1+i);
111165          sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
111166          sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
111167          VdbeCoverage(v);
111168          break;
111169        }
111170        case OE_Ignore: {
111171          sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
111172          VdbeCoverage(v);
111173          break;
111174        }
111175        default: {
111176          assert( onError==OE_Replace );
111177          addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
111178             VdbeCoverage(v);
111179          sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
111180          sqlite3VdbeJumpHere(v, addr1);
111181          break;
111182        }
111183      }
111184    }
111185  
111186    /* Test all CHECK constraints
111187    */
111188  #ifndef SQLITE_OMIT_CHECK
111189    if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
111190      ExprList *pCheck = pTab->pCheck;
111191      pParse->iSelfTab = -(regNewData+1);
111192      onError = overrideError!=OE_Default ? overrideError : OE_Abort;
111193      for(i=0; i<pCheck->nExpr; i++){
111194        int allOk;
111195        Expr *pExpr = pCheck->a[i].pExpr;
111196        if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
111197        allOk = sqlite3VdbeMakeLabel(v);
111198        sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
111199        if( onError==OE_Ignore ){
111200          sqlite3VdbeGoto(v, ignoreDest);
111201        }else{
111202          char *zName = pCheck->a[i].zName;
111203          if( zName==0 ) zName = pTab->zName;
111204          if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
111205          sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
111206                                onError, zName, P4_TRANSIENT,
111207                                P5_ConstraintCheck);
111208        }
111209        sqlite3VdbeResolveLabel(v, allOk);
111210      }
111211      pParse->iSelfTab = 0;
111212    }
111213  #endif /* !defined(SQLITE_OMIT_CHECK) */
111214  
111215    /* If rowid is changing, make sure the new rowid does not previously
111216    ** exist in the table.
111217    */
111218    if( pkChng && pPk==0 ){
111219      int addrRowidOk = sqlite3VdbeMakeLabel(v);
111220  
111221      /* Figure out what action to take in case of a rowid collision */
111222      onError = pTab->keyConf;
111223      if( overrideError!=OE_Default ){
111224        onError = overrideError;
111225      }else if( onError==OE_Default ){
111226        onError = OE_Abort;
111227      }
111228  
111229      if( isUpdate ){
111230        /* pkChng!=0 does not mean that the rowid has changed, only that
111231        ** it might have changed.  Skip the conflict logic below if the rowid
111232        ** is unchanged. */
111233        sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
111234        sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
111235        VdbeCoverage(v);
111236      }
111237  
111238      /* If the response to a rowid conflict is REPLACE but the response
111239      ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
111240      ** to defer the running of the rowid conflict checking until after
111241      ** the UNIQUE constraints have run.
111242      */
111243      if( onError==OE_Replace && overrideError!=OE_Replace ){
111244        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
111245          if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
111246            ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
111247            break;
111248          }
111249        }
111250      }
111251  
111252      /* Check to see if the new rowid already exists in the table.  Skip
111253      ** the following conflict logic if it does not. */
111254      sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
111255      VdbeCoverage(v);
111256  
111257      /* Generate code that deals with a rowid collision */
111258      switch( onError ){
111259        default: {
111260          onError = OE_Abort;
111261          /* Fall thru into the next case */
111262        }
111263        case OE_Rollback:
111264        case OE_Abort:
111265        case OE_Fail: {
111266          sqlite3RowidConstraint(pParse, onError, pTab);
111267          break;
111268        }
111269        case OE_Replace: {
111270          /* If there are DELETE triggers on this table and the
111271          ** recursive-triggers flag is set, call GenerateRowDelete() to
111272          ** remove the conflicting row from the table. This will fire
111273          ** the triggers and remove both the table and index b-tree entries.
111274          **
111275          ** Otherwise, if there are no triggers or the recursive-triggers
111276          ** flag is not set, but the table has one or more indexes, call 
111277          ** GenerateRowIndexDelete(). This removes the index b-tree entries 
111278          ** only. The table b-tree entry will be replaced by the new entry 
111279          ** when it is inserted.  
111280          **
111281          ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
111282          ** also invoke MultiWrite() to indicate that this VDBE may require
111283          ** statement rollback (if the statement is aborted after the delete
111284          ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
111285          ** but being more selective here allows statements like:
111286          **
111287          **   REPLACE INTO t(rowid) VALUES($newrowid)
111288          **
111289          ** to run without a statement journal if there are no indexes on the
111290          ** table.
111291          */
111292          Trigger *pTrigger = 0;
111293          if( db->flags&SQLITE_RecTriggers ){
111294            pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
111295          }
111296          if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
111297            sqlite3MultiWrite(pParse);
111298            sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
111299                                     regNewData, 1, 0, OE_Replace, 1, -1);
111300          }else{
111301  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
111302            if( HasRowid(pTab) ){
111303              /* This OP_Delete opcode fires the pre-update-hook only. It does
111304              ** not modify the b-tree. It is more efficient to let the coming
111305              ** OP_Insert replace the existing entry than it is to delete the
111306              ** existing entry and then insert a new one. */
111307              sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
111308              sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
111309            }
111310  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
111311            if( pTab->pIndex ){
111312              sqlite3MultiWrite(pParse);
111313              sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
111314            }
111315          }
111316          seenReplace = 1;
111317          break;
111318        }
111319        case OE_Ignore: {
111320          /*assert( seenReplace==0 );*/
111321          sqlite3VdbeGoto(v, ignoreDest);
111322          break;
111323        }
111324      }
111325      sqlite3VdbeResolveLabel(v, addrRowidOk);
111326      if( ipkTop ){
111327        ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
111328        sqlite3VdbeJumpHere(v, ipkTop);
111329      }
111330    }
111331  
111332    /* Test all UNIQUE constraints by creating entries for each UNIQUE
111333    ** index and making sure that duplicate entries do not already exist.
111334    ** Compute the revised record entries for indices as we go.
111335    **
111336    ** This loop also handles the case of the PRIMARY KEY index for a
111337    ** WITHOUT ROWID table.
111338    */
111339    for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
111340      int regIdx;          /* Range of registers hold conent for pIdx */
111341      int regR;            /* Range of registers holding conflicting PK */
111342      int iThisCur;        /* Cursor for this UNIQUE index */
111343      int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
111344  
111345      if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
111346      if( bAffinityDone==0 ){
111347        sqlite3TableAffinity(v, pTab, regNewData+1);
111348        bAffinityDone = 1;
111349      }
111350      iThisCur = iIdxCur+ix;
111351      addrUniqueOk = sqlite3VdbeMakeLabel(v);
111352  
111353      /* Skip partial indices for which the WHERE clause is not true */
111354      if( pIdx->pPartIdxWhere ){
111355        sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
111356        pParse->iSelfTab = -(regNewData+1);
111357        sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
111358                              SQLITE_JUMPIFNULL);
111359        pParse->iSelfTab = 0;
111360      }
111361  
111362      /* Create a record for this index entry as it should appear after
111363      ** the insert or update.  Store that record in the aRegIdx[ix] register
111364      */
111365      regIdx = aRegIdx[ix]+1;
111366      for(i=0; i<pIdx->nColumn; i++){
111367        int iField = pIdx->aiColumn[i];
111368        int x;
111369        if( iField==XN_EXPR ){
111370          pParse->iSelfTab = -(regNewData+1);
111371          sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
111372          pParse->iSelfTab = 0;
111373          VdbeComment((v, "%s column %d", pIdx->zName, i));
111374        }else{
111375          if( iField==XN_ROWID || iField==pTab->iPKey ){
111376            x = regNewData;
111377          }else{
111378            x = iField + regNewData + 1;
111379          }
111380          sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
111381          VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
111382        }
111383      }
111384      sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
111385      VdbeComment((v, "for %s", pIdx->zName));
111386  #ifdef SQLITE_ENABLE_NULL_TRIM
111387      if( pIdx->idxType==2 ) sqlite3SetMakeRecordP5(v, pIdx->pTable);
111388  #endif
111389  
111390      /* In an UPDATE operation, if this index is the PRIMARY KEY index 
111391      ** of a WITHOUT ROWID table and there has been no change the
111392      ** primary key, then no collision is possible.  The collision detection
111393      ** logic below can all be skipped. */
111394      if( isUpdate && pPk==pIdx && pkChng==0 ){
111395        sqlite3VdbeResolveLabel(v, addrUniqueOk);
111396        continue;
111397      }
111398  
111399      /* Find out what action to take in case there is a uniqueness conflict */
111400      onError = pIdx->onError;
111401      if( onError==OE_None ){ 
111402        sqlite3VdbeResolveLabel(v, addrUniqueOk);
111403        continue;  /* pIdx is not a UNIQUE index */
111404      }
111405      if( overrideError!=OE_Default ){
111406        onError = overrideError;
111407      }else if( onError==OE_Default ){
111408        onError = OE_Abort;
111409      }
111410  
111411      /* Collision detection may be omitted if all of the following are true:
111412      **   (1) The conflict resolution algorithm is REPLACE
111413      **   (2) The table is a WITHOUT ROWID table
111414      **   (3) There are no secondary indexes on the table
111415      **   (4) No delete triggers need to be fired if there is a conflict
111416      **   (5) No FK constraint counters need to be updated if a conflict occurs.
111417      */ 
111418      if( (ix==0 && pIdx->pNext==0)                   /* Condition 3 */
111419       && pPk==pIdx                                   /* Condition 2 */
111420       && onError==OE_Replace                         /* Condition 1 */
111421       && ( 0==(db->flags&SQLITE_RecTriggers) ||      /* Condition 4 */
111422            0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
111423       && ( 0==(db->flags&SQLITE_ForeignKeys) ||      /* Condition 5 */
111424           (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
111425      ){
111426        sqlite3VdbeResolveLabel(v, addrUniqueOk);
111427        continue;
111428      }
111429  
111430      /* Check to see if the new index entry will be unique */
111431      sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
111432                           regIdx, pIdx->nKeyCol); VdbeCoverage(v);
111433  
111434      /* Generate code to handle collisions */
111435      regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
111436      if( isUpdate || onError==OE_Replace ){
111437        if( HasRowid(pTab) ){
111438          sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
111439          /* Conflict only if the rowid of the existing index entry
111440          ** is different from old-rowid */
111441          if( isUpdate ){
111442            sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
111443            sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
111444            VdbeCoverage(v);
111445          }
111446        }else{
111447          int x;
111448          /* Extract the PRIMARY KEY from the end of the index entry and
111449          ** store it in registers regR..regR+nPk-1 */
111450          if( pIdx!=pPk ){
111451            for(i=0; i<pPk->nKeyCol; i++){
111452              assert( pPk->aiColumn[i]>=0 );
111453              x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
111454              sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
111455              VdbeComment((v, "%s.%s", pTab->zName,
111456                           pTab->aCol[pPk->aiColumn[i]].zName));
111457            }
111458          }
111459          if( isUpdate ){
111460            /* If currently processing the PRIMARY KEY of a WITHOUT ROWID 
111461            ** table, only conflict if the new PRIMARY KEY values are actually
111462            ** different from the old.
111463            **
111464            ** For a UNIQUE index, only conflict if the PRIMARY KEY values
111465            ** of the matched index row are different from the original PRIMARY
111466            ** KEY values of this row before the update.  */
111467            int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
111468            int op = OP_Ne;
111469            int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
111470    
111471            for(i=0; i<pPk->nKeyCol; i++){
111472              char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
111473              x = pPk->aiColumn[i];
111474              assert( x>=0 );
111475              if( i==(pPk->nKeyCol-1) ){
111476                addrJump = addrUniqueOk;
111477                op = OP_Eq;
111478              }
111479              sqlite3VdbeAddOp4(v, op, 
111480                  regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
111481              );
111482              sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
111483              VdbeCoverageIf(v, op==OP_Eq);
111484              VdbeCoverageIf(v, op==OP_Ne);
111485            }
111486          }
111487        }
111488      }
111489  
111490      /* Generate code that executes if the new index entry is not unique */
111491      assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
111492          || onError==OE_Ignore || onError==OE_Replace );
111493      switch( onError ){
111494        case OE_Rollback:
111495        case OE_Abort:
111496        case OE_Fail: {
111497          sqlite3UniqueConstraint(pParse, onError, pIdx);
111498          break;
111499        }
111500        case OE_Ignore: {
111501          sqlite3VdbeGoto(v, ignoreDest);
111502          break;
111503        }
111504        default: {
111505          Trigger *pTrigger = 0;
111506          assert( onError==OE_Replace );
111507          sqlite3MultiWrite(pParse);
111508          if( db->flags&SQLITE_RecTriggers ){
111509            pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
111510          }
111511          sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
111512              regR, nPkField, 0, OE_Replace,
111513              (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
111514          seenReplace = 1;
111515          break;
111516        }
111517      }
111518      sqlite3VdbeResolveLabel(v, addrUniqueOk);
111519      if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
111520    }
111521    if( ipkTop ){
111522      sqlite3VdbeGoto(v, ipkTop+1);
111523      sqlite3VdbeJumpHere(v, ipkBottom);
111524    }
111525    
111526    *pbMayReplace = seenReplace;
111527    VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
111528  }
111529  
111530  #ifdef SQLITE_ENABLE_NULL_TRIM
111531  /*
111532  ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
111533  ** to be the number of columns in table pTab that must not be NULL-trimmed.
111534  **
111535  ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
111536  */
111537  SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
111538    u16 i;
111539  
111540    /* Records with omitted columns are only allowed for schema format
111541    ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
111542    if( pTab->pSchema->file_format<2 ) return;
111543  
111544    for(i=pTab->nCol-1; i>0; i--){
111545      if( pTab->aCol[i].pDflt!=0 ) break;
111546      if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
111547    }
111548    sqlite3VdbeChangeP5(v, i+1);
111549  }
111550  #endif
111551  
111552  /*
111553  ** This routine generates code to finish the INSERT or UPDATE operation
111554  ** that was started by a prior call to sqlite3GenerateConstraintChecks.
111555  ** A consecutive range of registers starting at regNewData contains the
111556  ** rowid and the content to be inserted.
111557  **
111558  ** The arguments to this routine should be the same as the first six
111559  ** arguments to sqlite3GenerateConstraintChecks.
111560  */
111561  SQLITE_PRIVATE void sqlite3CompleteInsertion(
111562    Parse *pParse,      /* The parser context */
111563    Table *pTab,        /* the table into which we are inserting */
111564    int iDataCur,       /* Cursor of the canonical data source */
111565    int iIdxCur,        /* First index cursor */
111566    int regNewData,     /* Range of content */
111567    int *aRegIdx,       /* Register used by each index.  0 for unused indices */
111568    int update_flags,   /* True for UPDATE, False for INSERT */
111569    int appendBias,     /* True if this is likely to be an append */
111570    int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
111571  ){
111572    Vdbe *v;            /* Prepared statements under construction */
111573    Index *pIdx;        /* An index being inserted or updated */
111574    u8 pik_flags;       /* flag values passed to the btree insert */
111575    int regData;        /* Content registers (after the rowid) */
111576    int regRec;         /* Register holding assembled record for the table */
111577    int i;              /* Loop counter */
111578    u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
111579  
111580    assert( update_flags==0
111581         || update_flags==OPFLAG_ISUPDATE
111582         || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
111583    );
111584  
111585    v = sqlite3GetVdbe(pParse);
111586    assert( v!=0 );
111587    assert( pTab->pSelect==0 );  /* This table is not a VIEW */
111588    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
111589      if( aRegIdx[i]==0 ) continue;
111590      bAffinityDone = 1;
111591      if( pIdx->pPartIdxWhere ){
111592        sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
111593        VdbeCoverage(v);
111594      }
111595      pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
111596      if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
111597        assert( pParse->nested==0 );
111598        pik_flags |= OPFLAG_NCHANGE;
111599        pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
111600  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
111601        if( update_flags==0 ){
111602          sqlite3VdbeAddOp4(v, OP_InsertInt, 
111603              iIdxCur+i, aRegIdx[i], 0, (char*)pTab, P4_TABLE
111604          );
111605          sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
111606        }
111607  #endif
111608      }
111609      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
111610                           aRegIdx[i]+1,
111611                           pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
111612      sqlite3VdbeChangeP5(v, pik_flags);
111613    }
111614    if( !HasRowid(pTab) ) return;
111615    regData = regNewData + 1;
111616    regRec = sqlite3GetTempReg(pParse);
111617    sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
111618    sqlite3SetMakeRecordP5(v, pTab);
111619    if( !bAffinityDone ){
111620      sqlite3TableAffinity(v, pTab, 0);
111621      sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
111622    }
111623    if( pParse->nested ){
111624      pik_flags = 0;
111625    }else{
111626      pik_flags = OPFLAG_NCHANGE;
111627      pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
111628    }
111629    if( appendBias ){
111630      pik_flags |= OPFLAG_APPEND;
111631    }
111632    if( useSeekResult ){
111633      pik_flags |= OPFLAG_USESEEKRESULT;
111634    }
111635    sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
111636    if( !pParse->nested ){
111637      sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
111638    }
111639    sqlite3VdbeChangeP5(v, pik_flags);
111640  }
111641  
111642  /*
111643  ** Allocate cursors for the pTab table and all its indices and generate
111644  ** code to open and initialized those cursors.
111645  **
111646  ** The cursor for the object that contains the complete data (normally
111647  ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
111648  ** ROWID table) is returned in *piDataCur.  The first index cursor is
111649  ** returned in *piIdxCur.  The number of indices is returned.
111650  **
111651  ** Use iBase as the first cursor (either the *piDataCur for rowid tables
111652  ** or the first index for WITHOUT ROWID tables) if it is non-negative.
111653  ** If iBase is negative, then allocate the next available cursor.
111654  **
111655  ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
111656  ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
111657  ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
111658  ** pTab->pIndex list.
111659  **
111660  ** If pTab is a virtual table, then this routine is a no-op and the
111661  ** *piDataCur and *piIdxCur values are left uninitialized.
111662  */
111663  SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
111664    Parse *pParse,   /* Parsing context */
111665    Table *pTab,     /* Table to be opened */
111666    int op,          /* OP_OpenRead or OP_OpenWrite */
111667    u8 p5,           /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
111668    int iBase,       /* Use this for the table cursor, if there is one */
111669    u8 *aToOpen,     /* If not NULL: boolean for each table and index */
111670    int *piDataCur,  /* Write the database source cursor number here */
111671    int *piIdxCur    /* Write the first index cursor number here */
111672  ){
111673    int i;
111674    int iDb;
111675    int iDataCur;
111676    Index *pIdx;
111677    Vdbe *v;
111678  
111679    assert( op==OP_OpenRead || op==OP_OpenWrite );
111680    assert( op==OP_OpenWrite || p5==0 );
111681    if( IsVirtual(pTab) ){
111682      /* This routine is a no-op for virtual tables. Leave the output
111683      ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
111684      ** can detect if they are used by mistake in the caller. */
111685      return 0;
111686    }
111687    iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
111688    v = sqlite3GetVdbe(pParse);
111689    assert( v!=0 );
111690    if( iBase<0 ) iBase = pParse->nTab;
111691    iDataCur = iBase++;
111692    if( piDataCur ) *piDataCur = iDataCur;
111693    if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
111694      sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
111695    }else{
111696      sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
111697    }
111698    if( piIdxCur ) *piIdxCur = iBase;
111699    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
111700      int iIdxCur = iBase++;
111701      assert( pIdx->pSchema==pTab->pSchema );
111702      if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
111703        if( piDataCur ) *piDataCur = iIdxCur;
111704        p5 = 0;
111705      }
111706      if( aToOpen==0 || aToOpen[i+1] ){
111707        sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
111708        sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
111709        sqlite3VdbeChangeP5(v, p5);
111710        VdbeComment((v, "%s", pIdx->zName));
111711      }
111712    }
111713    if( iBase>pParse->nTab ) pParse->nTab = iBase;
111714    return i;
111715  }
111716  
111717  
111718  #ifdef SQLITE_TEST
111719  /*
111720  ** The following global variable is incremented whenever the
111721  ** transfer optimization is used.  This is used for testing
111722  ** purposes only - to make sure the transfer optimization really
111723  ** is happening when it is supposed to.
111724  */
111725  SQLITE_API int sqlite3_xferopt_count;
111726  #endif /* SQLITE_TEST */
111727  
111728  
111729  #ifndef SQLITE_OMIT_XFER_OPT
111730  /*
111731  ** Check to see if index pSrc is compatible as a source of data
111732  ** for index pDest in an insert transfer optimization.  The rules
111733  ** for a compatible index:
111734  **
111735  **    *   The index is over the same set of columns
111736  **    *   The same DESC and ASC markings occurs on all columns
111737  **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
111738  **    *   The same collating sequence on each column
111739  **    *   The index has the exact same WHERE clause
111740  */
111741  static int xferCompatibleIndex(Index *pDest, Index *pSrc){
111742    int i;
111743    assert( pDest && pSrc );
111744    assert( pDest->pTable!=pSrc->pTable );
111745    if( pDest->nKeyCol!=pSrc->nKeyCol ){
111746      return 0;   /* Different number of columns */
111747    }
111748    if( pDest->onError!=pSrc->onError ){
111749      return 0;   /* Different conflict resolution strategies */
111750    }
111751    for(i=0; i<pSrc->nKeyCol; i++){
111752      if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
111753        return 0;   /* Different columns indexed */
111754      }
111755      if( pSrc->aiColumn[i]==XN_EXPR ){
111756        assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
111757        if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
111758                               pDest->aColExpr->a[i].pExpr, -1)!=0 ){
111759          return 0;   /* Different expressions in the index */
111760        }
111761      }
111762      if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
111763        return 0;   /* Different sort orders */
111764      }
111765      if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
111766        return 0;   /* Different collating sequences */
111767      }
111768    }
111769    if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
111770      return 0;     /* Different WHERE clauses */
111771    }
111772  
111773    /* If no test above fails then the indices must be compatible */
111774    return 1;
111775  }
111776  
111777  /*
111778  ** Attempt the transfer optimization on INSERTs of the form
111779  **
111780  **     INSERT INTO tab1 SELECT * FROM tab2;
111781  **
111782  ** The xfer optimization transfers raw records from tab2 over to tab1.  
111783  ** Columns are not decoded and reassembled, which greatly improves
111784  ** performance.  Raw index records are transferred in the same way.
111785  **
111786  ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
111787  ** There are lots of rules for determining compatibility - see comments
111788  ** embedded in the code for details.
111789  **
111790  ** This routine returns TRUE if the optimization is guaranteed to be used.
111791  ** Sometimes the xfer optimization will only work if the destination table
111792  ** is empty - a factor that can only be determined at run-time.  In that
111793  ** case, this routine generates code for the xfer optimization but also
111794  ** does a test to see if the destination table is empty and jumps over the
111795  ** xfer optimization code if the test fails.  In that case, this routine
111796  ** returns FALSE so that the caller will know to go ahead and generate
111797  ** an unoptimized transfer.  This routine also returns FALSE if there
111798  ** is no chance that the xfer optimization can be applied.
111799  **
111800  ** This optimization is particularly useful at making VACUUM run faster.
111801  */
111802  static int xferOptimization(
111803    Parse *pParse,        /* Parser context */
111804    Table *pDest,         /* The table we are inserting into */
111805    Select *pSelect,      /* A SELECT statement to use as the data source */
111806    int onError,          /* How to handle constraint errors */
111807    int iDbDest           /* The database of pDest */
111808  ){
111809    sqlite3 *db = pParse->db;
111810    ExprList *pEList;                /* The result set of the SELECT */
111811    Table *pSrc;                     /* The table in the FROM clause of SELECT */
111812    Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
111813    struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
111814    int i;                           /* Loop counter */
111815    int iDbSrc;                      /* The database of pSrc */
111816    int iSrc, iDest;                 /* Cursors from source and destination */
111817    int addr1, addr2;                /* Loop addresses */
111818    int emptyDestTest = 0;           /* Address of test for empty pDest */
111819    int emptySrcTest = 0;            /* Address of test for empty pSrc */
111820    Vdbe *v;                         /* The VDBE we are building */
111821    int regAutoinc;                  /* Memory register used by AUTOINC */
111822    int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
111823    int regData, regRowid;           /* Registers holding data and rowid */
111824  
111825    if( pSelect==0 ){
111826      return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
111827    }
111828    if( pParse->pWith || pSelect->pWith ){
111829      /* Do not attempt to process this query if there are an WITH clauses
111830      ** attached to it. Proceeding may generate a false "no such table: xxx"
111831      ** error if pSelect reads from a CTE named "xxx".  */
111832      return 0;
111833    }
111834    if( sqlite3TriggerList(pParse, pDest) ){
111835      return 0;   /* tab1 must not have triggers */
111836    }
111837  #ifndef SQLITE_OMIT_VIRTUALTABLE
111838    if( IsVirtual(pDest) ){
111839      return 0;   /* tab1 must not be a virtual table */
111840    }
111841  #endif
111842    if( onError==OE_Default ){
111843      if( pDest->iPKey>=0 ) onError = pDest->keyConf;
111844      if( onError==OE_Default ) onError = OE_Abort;
111845    }
111846    assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
111847    if( pSelect->pSrc->nSrc!=1 ){
111848      return 0;   /* FROM clause must have exactly one term */
111849    }
111850    if( pSelect->pSrc->a[0].pSelect ){
111851      return 0;   /* FROM clause cannot contain a subquery */
111852    }
111853    if( pSelect->pWhere ){
111854      return 0;   /* SELECT may not have a WHERE clause */
111855    }
111856    if( pSelect->pOrderBy ){
111857      return 0;   /* SELECT may not have an ORDER BY clause */
111858    }
111859    /* Do not need to test for a HAVING clause.  If HAVING is present but
111860    ** there is no ORDER BY, we will get an error. */
111861    if( pSelect->pGroupBy ){
111862      return 0;   /* SELECT may not have a GROUP BY clause */
111863    }
111864    if( pSelect->pLimit ){
111865      return 0;   /* SELECT may not have a LIMIT clause */
111866    }
111867    assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
111868    if( pSelect->pPrior ){
111869      return 0;   /* SELECT may not be a compound query */
111870    }
111871    if( pSelect->selFlags & SF_Distinct ){
111872      return 0;   /* SELECT may not be DISTINCT */
111873    }
111874    pEList = pSelect->pEList;
111875    assert( pEList!=0 );
111876    if( pEList->nExpr!=1 ){
111877      return 0;   /* The result set must have exactly one column */
111878    }
111879    assert( pEList->a[0].pExpr );
111880    if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
111881      return 0;   /* The result set must be the special operator "*" */
111882    }
111883  
111884    /* At this point we have established that the statement is of the
111885    ** correct syntactic form to participate in this optimization.  Now
111886    ** we have to check the semantics.
111887    */
111888    pItem = pSelect->pSrc->a;
111889    pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
111890    if( pSrc==0 ){
111891      return 0;   /* FROM clause does not contain a real table */
111892    }
111893    if( pSrc==pDest ){
111894      return 0;   /* tab1 and tab2 may not be the same table */
111895    }
111896    if( HasRowid(pDest)!=HasRowid(pSrc) ){
111897      return 0;   /* source and destination must both be WITHOUT ROWID or not */
111898    }
111899  #ifndef SQLITE_OMIT_VIRTUALTABLE
111900    if( IsVirtual(pSrc) ){
111901      return 0;   /* tab2 must not be a virtual table */
111902    }
111903  #endif
111904    if( pSrc->pSelect ){
111905      return 0;   /* tab2 may not be a view */
111906    }
111907    if( pDest->nCol!=pSrc->nCol ){
111908      return 0;   /* Number of columns must be the same in tab1 and tab2 */
111909    }
111910    if( pDest->iPKey!=pSrc->iPKey ){
111911      return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
111912    }
111913    for(i=0; i<pDest->nCol; i++){
111914      Column *pDestCol = &pDest->aCol[i];
111915      Column *pSrcCol = &pSrc->aCol[i];
111916  #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
111917      if( (db->mDbFlags & DBFLAG_Vacuum)==0 
111918       && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN 
111919      ){
111920        return 0;    /* Neither table may have __hidden__ columns */
111921      }
111922  #endif
111923      if( pDestCol->affinity!=pSrcCol->affinity ){
111924        return 0;    /* Affinity must be the same on all columns */
111925      }
111926      if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
111927        return 0;    /* Collating sequence must be the same on all columns */
111928      }
111929      if( pDestCol->notNull && !pSrcCol->notNull ){
111930        return 0;    /* tab2 must be NOT NULL if tab1 is */
111931      }
111932      /* Default values for second and subsequent columns need to match. */
111933      if( i>0 ){
111934        assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
111935        assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
111936        if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0) 
111937         || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
111938                                         pSrcCol->pDflt->u.zToken)!=0)
111939        ){
111940          return 0;    /* Default values must be the same for all columns */
111941        }
111942      }
111943    }
111944    for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
111945      if( IsUniqueIndex(pDestIdx) ){
111946        destHasUniqueIdx = 1;
111947      }
111948      for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
111949        if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
111950      }
111951      if( pSrcIdx==0 ){
111952        return 0;    /* pDestIdx has no corresponding index in pSrc */
111953      }
111954    }
111955  #ifndef SQLITE_OMIT_CHECK
111956    if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
111957      return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
111958    }
111959  #endif
111960  #ifndef SQLITE_OMIT_FOREIGN_KEY
111961    /* Disallow the transfer optimization if the destination table constains
111962    ** any foreign key constraints.  This is more restrictive than necessary.
111963    ** But the main beneficiary of the transfer optimization is the VACUUM 
111964    ** command, and the VACUUM command disables foreign key constraints.  So
111965    ** the extra complication to make this rule less restrictive is probably
111966    ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
111967    */
111968    if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
111969      return 0;
111970    }
111971  #endif
111972    if( (db->flags & SQLITE_CountRows)!=0 ){
111973      return 0;  /* xfer opt does not play well with PRAGMA count_changes */
111974    }
111975  
111976    /* If we get this far, it means that the xfer optimization is at
111977    ** least a possibility, though it might only work if the destination
111978    ** table (tab1) is initially empty.
111979    */
111980  #ifdef SQLITE_TEST
111981    sqlite3_xferopt_count++;
111982  #endif
111983    iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
111984    v = sqlite3GetVdbe(pParse);
111985    sqlite3CodeVerifySchema(pParse, iDbSrc);
111986    iSrc = pParse->nTab++;
111987    iDest = pParse->nTab++;
111988    regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
111989    regData = sqlite3GetTempReg(pParse);
111990    regRowid = sqlite3GetTempReg(pParse);
111991    sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
111992    assert( HasRowid(pDest) || destHasUniqueIdx );
111993    if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
111994        (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
111995     || destHasUniqueIdx                              /* (2) */
111996     || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
111997    )){
111998      /* In some circumstances, we are able to run the xfer optimization
111999      ** only if the destination table is initially empty. Unless the
112000      ** DBFLAG_Vacuum flag is set, this block generates code to make
112001      ** that determination. If DBFLAG_Vacuum is set, then the destination
112002      ** table is always empty.
112003      **
112004      ** Conditions under which the destination must be empty:
112005      **
112006      ** (1) There is no INTEGER PRIMARY KEY but there are indices.
112007      **     (If the destination is not initially empty, the rowid fields
112008      **     of index entries might need to change.)
112009      **
112010      ** (2) The destination has a unique index.  (The xfer optimization 
112011      **     is unable to test uniqueness.)
112012      **
112013      ** (3) onError is something other than OE_Abort and OE_Rollback.
112014      */
112015      addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
112016      emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
112017      sqlite3VdbeJumpHere(v, addr1);
112018    }
112019    if( HasRowid(pSrc) ){
112020      u8 insFlags;
112021      sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
112022      emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
112023      if( pDest->iPKey>=0 ){
112024        addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
112025        addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
112026        VdbeCoverage(v);
112027        sqlite3RowidConstraint(pParse, onError, pDest);
112028        sqlite3VdbeJumpHere(v, addr2);
112029        autoIncStep(pParse, regAutoinc, regRowid);
112030      }else if( pDest->pIndex==0 ){
112031        addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
112032      }else{
112033        addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
112034        assert( (pDest->tabFlags & TF_Autoincrement)==0 );
112035      }
112036      sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
112037      if( db->mDbFlags & DBFLAG_Vacuum ){
112038        sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
112039        insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|
112040                             OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
112041      }else{
112042        insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
112043      }
112044      sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
112045                        (char*)pDest, P4_TABLE);
112046      sqlite3VdbeChangeP5(v, insFlags);
112047      sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
112048      sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
112049      sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
112050    }else{
112051      sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
112052      sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
112053    }
112054    for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
112055      u8 idxInsFlags = 0;
112056      for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
112057        if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
112058      }
112059      assert( pSrcIdx );
112060      sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
112061      sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
112062      VdbeComment((v, "%s", pSrcIdx->zName));
112063      sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
112064      sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
112065      sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
112066      VdbeComment((v, "%s", pDestIdx->zName));
112067      addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
112068      sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
112069      if( db->mDbFlags & DBFLAG_Vacuum ){
112070        /* This INSERT command is part of a VACUUM operation, which guarantees
112071        ** that the destination table is empty. If all indexed columns use
112072        ** collation sequence BINARY, then it can also be assumed that the
112073        ** index will be populated by inserting keys in strictly sorted 
112074        ** order. In this case, instead of seeking within the b-tree as part
112075        ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
112076        ** OP_IdxInsert to seek to the point within the b-tree where each key 
112077        ** should be inserted. This is faster.
112078        **
112079        ** If any of the indexed columns use a collation sequence other than
112080        ** BINARY, this optimization is disabled. This is because the user 
112081        ** might change the definition of a collation sequence and then run
112082        ** a VACUUM command. In that case keys may not be written in strictly
112083        ** sorted order.  */
112084        for(i=0; i<pSrcIdx->nColumn; i++){
112085          const char *zColl = pSrcIdx->azColl[i];
112086          if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
112087        }
112088        if( i==pSrcIdx->nColumn ){
112089          idxInsFlags = OPFLAG_USESEEKRESULT;
112090          sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
112091        }
112092      }
112093      if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
112094        idxInsFlags |= OPFLAG_NCHANGE;
112095      }
112096      sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
112097      sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
112098      sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
112099      sqlite3VdbeJumpHere(v, addr1);
112100      sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
112101      sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
112102    }
112103    if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
112104    sqlite3ReleaseTempReg(pParse, regRowid);
112105    sqlite3ReleaseTempReg(pParse, regData);
112106    if( emptyDestTest ){
112107      sqlite3AutoincrementEnd(pParse);
112108      sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
112109      sqlite3VdbeJumpHere(v, emptyDestTest);
112110      sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
112111      return 0;
112112    }else{
112113      return 1;
112114    }
112115  }
112116  #endif /* SQLITE_OMIT_XFER_OPT */
112117  
112118  /************** End of insert.c **********************************************/
112119  /************** Begin file legacy.c ******************************************/
112120  /*
112121  ** 2001 September 15
112122  **
112123  ** The author disclaims copyright to this source code.  In place of
112124  ** a legal notice, here is a blessing:
112125  **
112126  **    May you do good and not evil.
112127  **    May you find forgiveness for yourself and forgive others.
112128  **    May you share freely, never taking more than you give.
112129  **
112130  *************************************************************************
112131  ** Main file for the SQLite library.  The routines in this file
112132  ** implement the programmer interface to the library.  Routines in
112133  ** other files are for internal use by SQLite and should not be
112134  ** accessed by users of the library.
112135  */
112136  
112137  /* #include "sqliteInt.h" */
112138  
112139  /*
112140  ** Execute SQL code.  Return one of the SQLITE_ success/failure
112141  ** codes.  Also write an error message into memory obtained from
112142  ** malloc() and make *pzErrMsg point to that message.
112143  **
112144  ** If the SQL is a query, then for each row in the query result
112145  ** the xCallback() function is called.  pArg becomes the first
112146  ** argument to xCallback().  If xCallback=NULL then no callback
112147  ** is invoked, even for queries.
112148  */
112149  SQLITE_API int sqlite3_exec(
112150    sqlite3 *db,                /* The database on which the SQL executes */
112151    const char *zSql,           /* The SQL to be executed */
112152    sqlite3_callback xCallback, /* Invoke this callback routine */
112153    void *pArg,                 /* First argument to xCallback() */
112154    char **pzErrMsg             /* Write error messages here */
112155  ){
112156    int rc = SQLITE_OK;         /* Return code */
112157    const char *zLeftover;      /* Tail of unprocessed SQL */
112158    sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
112159    char **azCols = 0;          /* Names of result columns */
112160    int callbackIsInit;         /* True if callback data is initialized */
112161  
112162    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
112163    if( zSql==0 ) zSql = "";
112164  
112165    sqlite3_mutex_enter(db->mutex);
112166    sqlite3Error(db, SQLITE_OK);
112167    while( rc==SQLITE_OK && zSql[0] ){
112168      int nCol;
112169      char **azVals = 0;
112170  
112171      pStmt = 0;
112172      rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
112173      assert( rc==SQLITE_OK || pStmt==0 );
112174      if( rc!=SQLITE_OK ){
112175        continue;
112176      }
112177      if( !pStmt ){
112178        /* this happens for a comment or white-space */
112179        zSql = zLeftover;
112180        continue;
112181      }
112182  
112183      callbackIsInit = 0;
112184      nCol = sqlite3_column_count(pStmt);
112185  
112186      while( 1 ){
112187        int i;
112188        rc = sqlite3_step(pStmt);
112189  
112190        /* Invoke the callback function if required */
112191        if( xCallback && (SQLITE_ROW==rc || 
112192            (SQLITE_DONE==rc && !callbackIsInit
112193                             && db->flags&SQLITE_NullCallback)) ){
112194          if( !callbackIsInit ){
112195            azCols = sqlite3DbMallocRaw(db, (2*nCol+1)*sizeof(const char*));
112196            if( azCols==0 ){
112197              goto exec_out;
112198            }
112199            for(i=0; i<nCol; i++){
112200              azCols[i] = (char *)sqlite3_column_name(pStmt, i);
112201              /* sqlite3VdbeSetColName() installs column names as UTF8
112202              ** strings so there is no way for sqlite3_column_name() to fail. */
112203              assert( azCols[i]!=0 );
112204            }
112205            callbackIsInit = 1;
112206          }
112207          if( rc==SQLITE_ROW ){
112208            azVals = &azCols[nCol];
112209            for(i=0; i<nCol; i++){
112210              azVals[i] = (char *)sqlite3_column_text(pStmt, i);
112211              if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
112212                sqlite3OomFault(db);
112213                goto exec_out;
112214              }
112215            }
112216            azVals[i] = 0;
112217          }
112218          if( xCallback(pArg, nCol, azVals, azCols) ){
112219            /* EVIDENCE-OF: R-38229-40159 If the callback function to
112220            ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
112221            ** return SQLITE_ABORT. */
112222            rc = SQLITE_ABORT;
112223            sqlite3VdbeFinalize((Vdbe *)pStmt);
112224            pStmt = 0;
112225            sqlite3Error(db, SQLITE_ABORT);
112226            goto exec_out;
112227          }
112228        }
112229  
112230        if( rc!=SQLITE_ROW ){
112231          rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
112232          pStmt = 0;
112233          zSql = zLeftover;
112234          while( sqlite3Isspace(zSql[0]) ) zSql++;
112235          break;
112236        }
112237      }
112238  
112239      sqlite3DbFree(db, azCols);
112240      azCols = 0;
112241    }
112242  
112243  exec_out:
112244    if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
112245    sqlite3DbFree(db, azCols);
112246  
112247    rc = sqlite3ApiExit(db, rc);
112248    if( rc!=SQLITE_OK && pzErrMsg ){
112249      *pzErrMsg = sqlite3DbStrDup(0, sqlite3_errmsg(db));
112250      if( *pzErrMsg==0 ){
112251        rc = SQLITE_NOMEM_BKPT;
112252        sqlite3Error(db, SQLITE_NOMEM);
112253      }
112254    }else if( pzErrMsg ){
112255      *pzErrMsg = 0;
112256    }
112257  
112258    assert( (rc&db->errMask)==rc );
112259    sqlite3_mutex_leave(db->mutex);
112260    return rc;
112261  }
112262  
112263  /************** End of legacy.c **********************************************/
112264  /************** Begin file loadext.c *****************************************/
112265  /*
112266  ** 2006 June 7
112267  **
112268  ** The author disclaims copyright to this source code.  In place of
112269  ** a legal notice, here is a blessing:
112270  **
112271  **    May you do good and not evil.
112272  **    May you find forgiveness for yourself and forgive others.
112273  **    May you share freely, never taking more than you give.
112274  **
112275  *************************************************************************
112276  ** This file contains code used to dynamically load extensions into
112277  ** the SQLite library.
112278  */
112279  
112280  #ifndef SQLITE_CORE
112281    #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
112282  #endif
112283  /************** Include sqlite3ext.h in the middle of loadext.c **************/
112284  /************** Begin file sqlite3ext.h **************************************/
112285  /*
112286  ** 2006 June 7
112287  **
112288  ** The author disclaims copyright to this source code.  In place of
112289  ** a legal notice, here is a blessing:
112290  **
112291  **    May you do good and not evil.
112292  **    May you find forgiveness for yourself and forgive others.
112293  **    May you share freely, never taking more than you give.
112294  **
112295  *************************************************************************
112296  ** This header file defines the SQLite interface for use by
112297  ** shared libraries that want to be imported as extensions into
112298  ** an SQLite instance.  Shared libraries that intend to be loaded
112299  ** as extensions by SQLite should #include this file instead of 
112300  ** sqlite3.h.
112301  */
112302  #ifndef SQLITE3EXT_H
112303  #define SQLITE3EXT_H
112304  /* #include "sqlite3.h" */
112305  
112306  /*
112307  ** The following structure holds pointers to all of the SQLite API
112308  ** routines.
112309  **
112310  ** WARNING:  In order to maintain backwards compatibility, add new
112311  ** interfaces to the end of this structure only.  If you insert new
112312  ** interfaces in the middle of this structure, then older different
112313  ** versions of SQLite will not be able to load each other's shared
112314  ** libraries!
112315  */
112316  struct sqlite3_api_routines {
112317    void * (*aggregate_context)(sqlite3_context*,int nBytes);
112318    int  (*aggregate_count)(sqlite3_context*);
112319    int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
112320    int  (*bind_double)(sqlite3_stmt*,int,double);
112321    int  (*bind_int)(sqlite3_stmt*,int,int);
112322    int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
112323    int  (*bind_null)(sqlite3_stmt*,int);
112324    int  (*bind_parameter_count)(sqlite3_stmt*);
112325    int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
112326    const char * (*bind_parameter_name)(sqlite3_stmt*,int);
112327    int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
112328    int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
112329    int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
112330    int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
112331    int  (*busy_timeout)(sqlite3*,int ms);
112332    int  (*changes)(sqlite3*);
112333    int  (*close)(sqlite3*);
112334    int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
112335                             int eTextRep,const char*));
112336    int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
112337                               int eTextRep,const void*));
112338    const void * (*column_blob)(sqlite3_stmt*,int iCol);
112339    int  (*column_bytes)(sqlite3_stmt*,int iCol);
112340    int  (*column_bytes16)(sqlite3_stmt*,int iCol);
112341    int  (*column_count)(sqlite3_stmt*pStmt);
112342    const char * (*column_database_name)(sqlite3_stmt*,int);
112343    const void * (*column_database_name16)(sqlite3_stmt*,int);
112344    const char * (*column_decltype)(sqlite3_stmt*,int i);
112345    const void * (*column_decltype16)(sqlite3_stmt*,int);
112346    double  (*column_double)(sqlite3_stmt*,int iCol);
112347    int  (*column_int)(sqlite3_stmt*,int iCol);
112348    sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
112349    const char * (*column_name)(sqlite3_stmt*,int);
112350    const void * (*column_name16)(sqlite3_stmt*,int);
112351    const char * (*column_origin_name)(sqlite3_stmt*,int);
112352    const void * (*column_origin_name16)(sqlite3_stmt*,int);
112353    const char * (*column_table_name)(sqlite3_stmt*,int);
112354    const void * (*column_table_name16)(sqlite3_stmt*,int);
112355    const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
112356    const void * (*column_text16)(sqlite3_stmt*,int iCol);
112357    int  (*column_type)(sqlite3_stmt*,int iCol);
112358    sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
112359    void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
112360    int  (*complete)(const char*sql);
112361    int  (*complete16)(const void*sql);
112362    int  (*create_collation)(sqlite3*,const char*,int,void*,
112363                             int(*)(void*,int,const void*,int,const void*));
112364    int  (*create_collation16)(sqlite3*,const void*,int,void*,
112365                               int(*)(void*,int,const void*,int,const void*));
112366    int  (*create_function)(sqlite3*,const char*,int,int,void*,
112367                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
112368                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
112369                            void (*xFinal)(sqlite3_context*));
112370    int  (*create_function16)(sqlite3*,const void*,int,int,void*,
112371                              void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
112372                              void (*xStep)(sqlite3_context*,int,sqlite3_value**),
112373                              void (*xFinal)(sqlite3_context*));
112374    int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
112375    int  (*data_count)(sqlite3_stmt*pStmt);
112376    sqlite3 * (*db_handle)(sqlite3_stmt*);
112377    int (*declare_vtab)(sqlite3*,const char*);
112378    int  (*enable_shared_cache)(int);
112379    int  (*errcode)(sqlite3*db);
112380    const char * (*errmsg)(sqlite3*);
112381    const void * (*errmsg16)(sqlite3*);
112382    int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
112383    int  (*expired)(sqlite3_stmt*);
112384    int  (*finalize)(sqlite3_stmt*pStmt);
112385    void  (*free)(void*);
112386    void  (*free_table)(char**result);
112387    int  (*get_autocommit)(sqlite3*);
112388    void * (*get_auxdata)(sqlite3_context*,int);
112389    int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
112390    int  (*global_recover)(void);
112391    void  (*interruptx)(sqlite3*);
112392    sqlite_int64  (*last_insert_rowid)(sqlite3*);
112393    const char * (*libversion)(void);
112394    int  (*libversion_number)(void);
112395    void *(*malloc)(int);
112396    char * (*mprintf)(const char*,...);
112397    int  (*open)(const char*,sqlite3**);
112398    int  (*open16)(const void*,sqlite3**);
112399    int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
112400    int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
112401    void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
112402    void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
112403    void *(*realloc)(void*,int);
112404    int  (*reset)(sqlite3_stmt*pStmt);
112405    void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
112406    void  (*result_double)(sqlite3_context*,double);
112407    void  (*result_error)(sqlite3_context*,const char*,int);
112408    void  (*result_error16)(sqlite3_context*,const void*,int);
112409    void  (*result_int)(sqlite3_context*,int);
112410    void  (*result_int64)(sqlite3_context*,sqlite_int64);
112411    void  (*result_null)(sqlite3_context*);
112412    void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
112413    void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
112414    void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
112415    void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
112416    void  (*result_value)(sqlite3_context*,sqlite3_value*);
112417    void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
112418    int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
112419                           const char*,const char*),void*);
112420    void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
112421    char * (*xsnprintf)(int,char*,const char*,...);
112422    int  (*step)(sqlite3_stmt*);
112423    int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
112424                                  char const**,char const**,int*,int*,int*);
112425    void  (*thread_cleanup)(void);
112426    int  (*total_changes)(sqlite3*);
112427    void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
112428    int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
112429    void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
112430                                           sqlite_int64),void*);
112431    void * (*user_data)(sqlite3_context*);
112432    const void * (*value_blob)(sqlite3_value*);
112433    int  (*value_bytes)(sqlite3_value*);
112434    int  (*value_bytes16)(sqlite3_value*);
112435    double  (*value_double)(sqlite3_value*);
112436    int  (*value_int)(sqlite3_value*);
112437    sqlite_int64  (*value_int64)(sqlite3_value*);
112438    int  (*value_numeric_type)(sqlite3_value*);
112439    const unsigned char * (*value_text)(sqlite3_value*);
112440    const void * (*value_text16)(sqlite3_value*);
112441    const void * (*value_text16be)(sqlite3_value*);
112442    const void * (*value_text16le)(sqlite3_value*);
112443    int  (*value_type)(sqlite3_value*);
112444    char *(*vmprintf)(const char*,va_list);
112445    /* Added ??? */
112446    int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
112447    /* Added by 3.3.13 */
112448    int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
112449    int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
112450    int (*clear_bindings)(sqlite3_stmt*);
112451    /* Added by 3.4.1 */
112452    int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
112453                            void (*xDestroy)(void *));
112454    /* Added by 3.5.0 */
112455    int (*bind_zeroblob)(sqlite3_stmt*,int,int);
112456    int (*blob_bytes)(sqlite3_blob*);
112457    int (*blob_close)(sqlite3_blob*);
112458    int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
112459                     int,sqlite3_blob**);
112460    int (*blob_read)(sqlite3_blob*,void*,int,int);
112461    int (*blob_write)(sqlite3_blob*,const void*,int,int);
112462    int (*create_collation_v2)(sqlite3*,const char*,int,void*,
112463                               int(*)(void*,int,const void*,int,const void*),
112464                               void(*)(void*));
112465    int (*file_control)(sqlite3*,const char*,int,void*);
112466    sqlite3_int64 (*memory_highwater)(int);
112467    sqlite3_int64 (*memory_used)(void);
112468    sqlite3_mutex *(*mutex_alloc)(int);
112469    void (*mutex_enter)(sqlite3_mutex*);
112470    void (*mutex_free)(sqlite3_mutex*);
112471    void (*mutex_leave)(sqlite3_mutex*);
112472    int (*mutex_try)(sqlite3_mutex*);
112473    int (*open_v2)(const char*,sqlite3**,int,const char*);
112474    int (*release_memory)(int);
112475    void (*result_error_nomem)(sqlite3_context*);
112476    void (*result_error_toobig)(sqlite3_context*);
112477    int (*sleep)(int);
112478    void (*soft_heap_limit)(int);
112479    sqlite3_vfs *(*vfs_find)(const char*);
112480    int (*vfs_register)(sqlite3_vfs*,int);
112481    int (*vfs_unregister)(sqlite3_vfs*);
112482    int (*xthreadsafe)(void);
112483    void (*result_zeroblob)(sqlite3_context*,int);
112484    void (*result_error_code)(sqlite3_context*,int);
112485    int (*test_control)(int, ...);
112486    void (*randomness)(int,void*);
112487    sqlite3 *(*context_db_handle)(sqlite3_context*);
112488    int (*extended_result_codes)(sqlite3*,int);
112489    int (*limit)(sqlite3*,int,int);
112490    sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
112491    const char *(*sql)(sqlite3_stmt*);
112492    int (*status)(int,int*,int*,int);
112493    int (*backup_finish)(sqlite3_backup*);
112494    sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
112495    int (*backup_pagecount)(sqlite3_backup*);
112496    int (*backup_remaining)(sqlite3_backup*);
112497    int (*backup_step)(sqlite3_backup*,int);
112498    const char *(*compileoption_get)(int);
112499    int (*compileoption_used)(const char*);
112500    int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
112501                              void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
112502                              void (*xStep)(sqlite3_context*,int,sqlite3_value**),
112503                              void (*xFinal)(sqlite3_context*),
112504                              void(*xDestroy)(void*));
112505    int (*db_config)(sqlite3*,int,...);
112506    sqlite3_mutex *(*db_mutex)(sqlite3*);
112507    int (*db_status)(sqlite3*,int,int*,int*,int);
112508    int (*extended_errcode)(sqlite3*);
112509    void (*log)(int,const char*,...);
112510    sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
112511    const char *(*sourceid)(void);
112512    int (*stmt_status)(sqlite3_stmt*,int,int);
112513    int (*strnicmp)(const char*,const char*,int);
112514    int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
112515    int (*wal_autocheckpoint)(sqlite3*,int);
112516    int (*wal_checkpoint)(sqlite3*,const char*);
112517    void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
112518    int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
112519    int (*vtab_config)(sqlite3*,int op,...);
112520    int (*vtab_on_conflict)(sqlite3*);
112521    /* Version 3.7.16 and later */
112522    int (*close_v2)(sqlite3*);
112523    const char *(*db_filename)(sqlite3*,const char*);
112524    int (*db_readonly)(sqlite3*,const char*);
112525    int (*db_release_memory)(sqlite3*);
112526    const char *(*errstr)(int);
112527    int (*stmt_busy)(sqlite3_stmt*);
112528    int (*stmt_readonly)(sqlite3_stmt*);
112529    int (*stricmp)(const char*,const char*);
112530    int (*uri_boolean)(const char*,const char*,int);
112531    sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
112532    const char *(*uri_parameter)(const char*,const char*);
112533    char *(*xvsnprintf)(int,char*,const char*,va_list);
112534    int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
112535    /* Version 3.8.7 and later */
112536    int (*auto_extension)(void(*)(void));
112537    int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
112538                       void(*)(void*));
112539    int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
112540                        void(*)(void*),unsigned char);
112541    int (*cancel_auto_extension)(void(*)(void));
112542    int (*load_extension)(sqlite3*,const char*,const char*,char**);
112543    void *(*malloc64)(sqlite3_uint64);
112544    sqlite3_uint64 (*msize)(void*);
112545    void *(*realloc64)(void*,sqlite3_uint64);
112546    void (*reset_auto_extension)(void);
112547    void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
112548                          void(*)(void*));
112549    void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
112550                           void(*)(void*), unsigned char);
112551    int (*strglob)(const char*,const char*);
112552    /* Version 3.8.11 and later */
112553    sqlite3_value *(*value_dup)(const sqlite3_value*);
112554    void (*value_free)(sqlite3_value*);
112555    int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
112556    int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
112557    /* Version 3.9.0 and later */
112558    unsigned int (*value_subtype)(sqlite3_value*);
112559    void (*result_subtype)(sqlite3_context*,unsigned int);
112560    /* Version 3.10.0 and later */
112561    int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
112562    int (*strlike)(const char*,const char*,unsigned int);
112563    int (*db_cacheflush)(sqlite3*);
112564    /* Version 3.12.0 and later */
112565    int (*system_errno)(sqlite3*);
112566    /* Version 3.14.0 and later */
112567    int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
112568    char *(*expanded_sql)(sqlite3_stmt*);
112569    /* Version 3.18.0 and later */
112570    void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
112571    /* Version 3.20.0 and later */
112572    int (*prepare_v3)(sqlite3*,const char*,int,unsigned int,
112573                      sqlite3_stmt**,const char**);
112574    int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int,
112575                        sqlite3_stmt**,const void**);
112576    int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));
112577    void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));
112578    void *(*value_pointer)(sqlite3_value*,const char*);
112579  };
112580  
112581  /*
112582  ** This is the function signature used for all extension entry points.  It
112583  ** is also defined in the file "loadext.c".
112584  */
112585  typedef int (*sqlite3_loadext_entry)(
112586    sqlite3 *db,                       /* Handle to the database. */
112587    char **pzErrMsg,                   /* Used to set error string on failure. */
112588    const sqlite3_api_routines *pThunk /* Extension API function pointers. */
112589  );
112590  
112591  /*
112592  ** The following macros redefine the API routines so that they are
112593  ** redirected through the global sqlite3_api structure.
112594  **
112595  ** This header file is also used by the loadext.c source file
112596  ** (part of the main SQLite library - not an extension) so that
112597  ** it can get access to the sqlite3_api_routines structure
112598  ** definition.  But the main library does not want to redefine
112599  ** the API.  So the redefinition macros are only valid if the
112600  ** SQLITE_CORE macros is undefined.
112601  */
112602  #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
112603  #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
112604  #ifndef SQLITE_OMIT_DEPRECATED
112605  #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
112606  #endif
112607  #define sqlite3_bind_blob              sqlite3_api->bind_blob
112608  #define sqlite3_bind_double            sqlite3_api->bind_double
112609  #define sqlite3_bind_int               sqlite3_api->bind_int
112610  #define sqlite3_bind_int64             sqlite3_api->bind_int64
112611  #define sqlite3_bind_null              sqlite3_api->bind_null
112612  #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
112613  #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
112614  #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
112615  #define sqlite3_bind_text              sqlite3_api->bind_text
112616  #define sqlite3_bind_text16            sqlite3_api->bind_text16
112617  #define sqlite3_bind_value             sqlite3_api->bind_value
112618  #define sqlite3_busy_handler           sqlite3_api->busy_handler
112619  #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
112620  #define sqlite3_changes                sqlite3_api->changes
112621  #define sqlite3_close                  sqlite3_api->close
112622  #define sqlite3_collation_needed       sqlite3_api->collation_needed
112623  #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
112624  #define sqlite3_column_blob            sqlite3_api->column_blob
112625  #define sqlite3_column_bytes           sqlite3_api->column_bytes
112626  #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
112627  #define sqlite3_column_count           sqlite3_api->column_count
112628  #define sqlite3_column_database_name   sqlite3_api->column_database_name
112629  #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
112630  #define sqlite3_column_decltype        sqlite3_api->column_decltype
112631  #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
112632  #define sqlite3_column_double          sqlite3_api->column_double
112633  #define sqlite3_column_int             sqlite3_api->column_int
112634  #define sqlite3_column_int64           sqlite3_api->column_int64
112635  #define sqlite3_column_name            sqlite3_api->column_name
112636  #define sqlite3_column_name16          sqlite3_api->column_name16
112637  #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
112638  #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
112639  #define sqlite3_column_table_name      sqlite3_api->column_table_name
112640  #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
112641  #define sqlite3_column_text            sqlite3_api->column_text
112642  #define sqlite3_column_text16          sqlite3_api->column_text16
112643  #define sqlite3_column_type            sqlite3_api->column_type
112644  #define sqlite3_column_value           sqlite3_api->column_value
112645  #define sqlite3_commit_hook            sqlite3_api->commit_hook
112646  #define sqlite3_complete               sqlite3_api->complete
112647  #define sqlite3_complete16             sqlite3_api->complete16
112648  #define sqlite3_create_collation       sqlite3_api->create_collation
112649  #define sqlite3_create_collation16     sqlite3_api->create_collation16
112650  #define sqlite3_create_function        sqlite3_api->create_function
112651  #define sqlite3_create_function16      sqlite3_api->create_function16
112652  #define sqlite3_create_module          sqlite3_api->create_module
112653  #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
112654  #define sqlite3_data_count             sqlite3_api->data_count
112655  #define sqlite3_db_handle              sqlite3_api->db_handle
112656  #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
112657  #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
112658  #define sqlite3_errcode                sqlite3_api->errcode
112659  #define sqlite3_errmsg                 sqlite3_api->errmsg
112660  #define sqlite3_errmsg16               sqlite3_api->errmsg16
112661  #define sqlite3_exec                   sqlite3_api->exec
112662  #ifndef SQLITE_OMIT_DEPRECATED
112663  #define sqlite3_expired                sqlite3_api->expired
112664  #endif
112665  #define sqlite3_finalize               sqlite3_api->finalize
112666  #define sqlite3_free                   sqlite3_api->free
112667  #define sqlite3_free_table             sqlite3_api->free_table
112668  #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
112669  #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
112670  #define sqlite3_get_table              sqlite3_api->get_table
112671  #ifndef SQLITE_OMIT_DEPRECATED
112672  #define sqlite3_global_recover         sqlite3_api->global_recover
112673  #endif
112674  #define sqlite3_interrupt              sqlite3_api->interruptx
112675  #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
112676  #define sqlite3_libversion             sqlite3_api->libversion
112677  #define sqlite3_libversion_number      sqlite3_api->libversion_number
112678  #define sqlite3_malloc                 sqlite3_api->malloc
112679  #define sqlite3_mprintf                sqlite3_api->mprintf
112680  #define sqlite3_open                   sqlite3_api->open
112681  #define sqlite3_open16                 sqlite3_api->open16
112682  #define sqlite3_prepare                sqlite3_api->prepare
112683  #define sqlite3_prepare16              sqlite3_api->prepare16
112684  #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
112685  #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
112686  #define sqlite3_profile                sqlite3_api->profile
112687  #define sqlite3_progress_handler       sqlite3_api->progress_handler
112688  #define sqlite3_realloc                sqlite3_api->realloc
112689  #define sqlite3_reset                  sqlite3_api->reset
112690  #define sqlite3_result_blob            sqlite3_api->result_blob
112691  #define sqlite3_result_double          sqlite3_api->result_double
112692  #define sqlite3_result_error           sqlite3_api->result_error
112693  #define sqlite3_result_error16         sqlite3_api->result_error16
112694  #define sqlite3_result_int             sqlite3_api->result_int
112695  #define sqlite3_result_int64           sqlite3_api->result_int64
112696  #define sqlite3_result_null            sqlite3_api->result_null
112697  #define sqlite3_result_text            sqlite3_api->result_text
112698  #define sqlite3_result_text16          sqlite3_api->result_text16
112699  #define sqlite3_result_text16be        sqlite3_api->result_text16be
112700  #define sqlite3_result_text16le        sqlite3_api->result_text16le
112701  #define sqlite3_result_value           sqlite3_api->result_value
112702  #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
112703  #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
112704  #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
112705  #define sqlite3_snprintf               sqlite3_api->xsnprintf
112706  #define sqlite3_step                   sqlite3_api->step
112707  #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
112708  #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
112709  #define sqlite3_total_changes          sqlite3_api->total_changes
112710  #define sqlite3_trace                  sqlite3_api->trace
112711  #ifndef SQLITE_OMIT_DEPRECATED
112712  #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
112713  #endif
112714  #define sqlite3_update_hook            sqlite3_api->update_hook
112715  #define sqlite3_user_data              sqlite3_api->user_data
112716  #define sqlite3_value_blob             sqlite3_api->value_blob
112717  #define sqlite3_value_bytes            sqlite3_api->value_bytes
112718  #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
112719  #define sqlite3_value_double           sqlite3_api->value_double
112720  #define sqlite3_value_int              sqlite3_api->value_int
112721  #define sqlite3_value_int64            sqlite3_api->value_int64
112722  #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
112723  #define sqlite3_value_text             sqlite3_api->value_text
112724  #define sqlite3_value_text16           sqlite3_api->value_text16
112725  #define sqlite3_value_text16be         sqlite3_api->value_text16be
112726  #define sqlite3_value_text16le         sqlite3_api->value_text16le
112727  #define sqlite3_value_type             sqlite3_api->value_type
112728  #define sqlite3_vmprintf               sqlite3_api->vmprintf
112729  #define sqlite3_vsnprintf              sqlite3_api->xvsnprintf
112730  #define sqlite3_overload_function      sqlite3_api->overload_function
112731  #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
112732  #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
112733  #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
112734  #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
112735  #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
112736  #define sqlite3_blob_close             sqlite3_api->blob_close
112737  #define sqlite3_blob_open              sqlite3_api->blob_open
112738  #define sqlite3_blob_read              sqlite3_api->blob_read
112739  #define sqlite3_blob_write             sqlite3_api->blob_write
112740  #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
112741  #define sqlite3_file_control           sqlite3_api->file_control
112742  #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
112743  #define sqlite3_memory_used            sqlite3_api->memory_used
112744  #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
112745  #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
112746  #define sqlite3_mutex_free             sqlite3_api->mutex_free
112747  #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
112748  #define sqlite3_mutex_try              sqlite3_api->mutex_try
112749  #define sqlite3_open_v2                sqlite3_api->open_v2
112750  #define sqlite3_release_memory         sqlite3_api->release_memory
112751  #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
112752  #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
112753  #define sqlite3_sleep                  sqlite3_api->sleep
112754  #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
112755  #define sqlite3_vfs_find               sqlite3_api->vfs_find
112756  #define sqlite3_vfs_register           sqlite3_api->vfs_register
112757  #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
112758  #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
112759  #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
112760  #define sqlite3_result_error_code      sqlite3_api->result_error_code
112761  #define sqlite3_test_control           sqlite3_api->test_control
112762  #define sqlite3_randomness             sqlite3_api->randomness
112763  #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
112764  #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
112765  #define sqlite3_limit                  sqlite3_api->limit
112766  #define sqlite3_next_stmt              sqlite3_api->next_stmt
112767  #define sqlite3_sql                    sqlite3_api->sql
112768  #define sqlite3_status                 sqlite3_api->status
112769  #define sqlite3_backup_finish          sqlite3_api->backup_finish
112770  #define sqlite3_backup_init            sqlite3_api->backup_init
112771  #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
112772  #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
112773  #define sqlite3_backup_step            sqlite3_api->backup_step
112774  #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
112775  #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
112776  #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
112777  #define sqlite3_db_config              sqlite3_api->db_config
112778  #define sqlite3_db_mutex               sqlite3_api->db_mutex
112779  #define sqlite3_db_status              sqlite3_api->db_status
112780  #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
112781  #define sqlite3_log                    sqlite3_api->log
112782  #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
112783  #define sqlite3_sourceid               sqlite3_api->sourceid
112784  #define sqlite3_stmt_status            sqlite3_api->stmt_status
112785  #define sqlite3_strnicmp               sqlite3_api->strnicmp
112786  #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
112787  #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
112788  #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
112789  #define sqlite3_wal_hook               sqlite3_api->wal_hook
112790  #define sqlite3_blob_reopen            sqlite3_api->blob_reopen
112791  #define sqlite3_vtab_config            sqlite3_api->vtab_config
112792  #define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
112793  /* Version 3.7.16 and later */
112794  #define sqlite3_close_v2               sqlite3_api->close_v2
112795  #define sqlite3_db_filename            sqlite3_api->db_filename
112796  #define sqlite3_db_readonly            sqlite3_api->db_readonly
112797  #define sqlite3_db_release_memory      sqlite3_api->db_release_memory
112798  #define sqlite3_errstr                 sqlite3_api->errstr
112799  #define sqlite3_stmt_busy              sqlite3_api->stmt_busy
112800  #define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
112801  #define sqlite3_stricmp                sqlite3_api->stricmp
112802  #define sqlite3_uri_boolean            sqlite3_api->uri_boolean
112803  #define sqlite3_uri_int64              sqlite3_api->uri_int64
112804  #define sqlite3_uri_parameter          sqlite3_api->uri_parameter
112805  #define sqlite3_uri_vsnprintf          sqlite3_api->xvsnprintf
112806  #define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
112807  /* Version 3.8.7 and later */
112808  #define sqlite3_auto_extension         sqlite3_api->auto_extension
112809  #define sqlite3_bind_blob64            sqlite3_api->bind_blob64
112810  #define sqlite3_bind_text64            sqlite3_api->bind_text64
112811  #define sqlite3_cancel_auto_extension  sqlite3_api->cancel_auto_extension
112812  #define sqlite3_load_extension         sqlite3_api->load_extension
112813  #define sqlite3_malloc64               sqlite3_api->malloc64
112814  #define sqlite3_msize                  sqlite3_api->msize
112815  #define sqlite3_realloc64              sqlite3_api->realloc64
112816  #define sqlite3_reset_auto_extension   sqlite3_api->reset_auto_extension
112817  #define sqlite3_result_blob64          sqlite3_api->result_blob64
112818  #define sqlite3_result_text64          sqlite3_api->result_text64
112819  #define sqlite3_strglob                sqlite3_api->strglob
112820  /* Version 3.8.11 and later */
112821  #define sqlite3_value_dup              sqlite3_api->value_dup
112822  #define sqlite3_value_free             sqlite3_api->value_free
112823  #define sqlite3_result_zeroblob64      sqlite3_api->result_zeroblob64
112824  #define sqlite3_bind_zeroblob64        sqlite3_api->bind_zeroblob64
112825  /* Version 3.9.0 and later */
112826  #define sqlite3_value_subtype          sqlite3_api->value_subtype
112827  #define sqlite3_result_subtype         sqlite3_api->result_subtype
112828  /* Version 3.10.0 and later */
112829  #define sqlite3_status64               sqlite3_api->status64
112830  #define sqlite3_strlike                sqlite3_api->strlike
112831  #define sqlite3_db_cacheflush          sqlite3_api->db_cacheflush
112832  /* Version 3.12.0 and later */
112833  #define sqlite3_system_errno           sqlite3_api->system_errno
112834  /* Version 3.14.0 and later */
112835  #define sqlite3_trace_v2               sqlite3_api->trace_v2
112836  #define sqlite3_expanded_sql           sqlite3_api->expanded_sql
112837  /* Version 3.18.0 and later */
112838  #define sqlite3_set_last_insert_rowid  sqlite3_api->set_last_insert_rowid
112839  /* Version 3.20.0 and later */
112840  #define sqlite3_prepare_v3             sqlite3_api->prepare_v3
112841  #define sqlite3_prepare16_v3           sqlite3_api->prepare16_v3
112842  #define sqlite3_bind_pointer           sqlite3_api->bind_pointer
112843  #define sqlite3_result_pointer         sqlite3_api->result_pointer
112844  #define sqlite3_value_pointer          sqlite3_api->value_pointer
112845  #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
112846  
112847  #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
112848    /* This case when the file really is being compiled as a loadable 
112849    ** extension */
112850  # define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
112851  # define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
112852  # define SQLITE_EXTENSION_INIT3     \
112853      extern const sqlite3_api_routines *sqlite3_api;
112854  #else
112855    /* This case when the file is being statically linked into the 
112856    ** application */
112857  # define SQLITE_EXTENSION_INIT1     /*no-op*/
112858  # define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
112859  # define SQLITE_EXTENSION_INIT3     /*no-op*/
112860  #endif
112861  
112862  #endif /* SQLITE3EXT_H */
112863  
112864  /************** End of sqlite3ext.h ******************************************/
112865  /************** Continuing where we left off in loadext.c ********************/
112866  /* #include "sqliteInt.h" */
112867  
112868  #ifndef SQLITE_OMIT_LOAD_EXTENSION
112869  /*
112870  ** Some API routines are omitted when various features are
112871  ** excluded from a build of SQLite.  Substitute a NULL pointer
112872  ** for any missing APIs.
112873  */
112874  #ifndef SQLITE_ENABLE_COLUMN_METADATA
112875  # define sqlite3_column_database_name   0
112876  # define sqlite3_column_database_name16 0
112877  # define sqlite3_column_table_name      0
112878  # define sqlite3_column_table_name16    0
112879  # define sqlite3_column_origin_name     0
112880  # define sqlite3_column_origin_name16   0
112881  #endif
112882  
112883  #ifdef SQLITE_OMIT_AUTHORIZATION
112884  # define sqlite3_set_authorizer         0
112885  #endif
112886  
112887  #ifdef SQLITE_OMIT_UTF16
112888  # define sqlite3_bind_text16            0
112889  # define sqlite3_collation_needed16     0
112890  # define sqlite3_column_decltype16      0
112891  # define sqlite3_column_name16          0
112892  # define sqlite3_column_text16          0
112893  # define sqlite3_complete16             0
112894  # define sqlite3_create_collation16     0
112895  # define sqlite3_create_function16      0
112896  # define sqlite3_errmsg16               0
112897  # define sqlite3_open16                 0
112898  # define sqlite3_prepare16              0
112899  # define sqlite3_prepare16_v2           0
112900  # define sqlite3_prepare16_v3           0
112901  # define sqlite3_result_error16         0
112902  # define sqlite3_result_text16          0
112903  # define sqlite3_result_text16be        0
112904  # define sqlite3_result_text16le        0
112905  # define sqlite3_value_text16           0
112906  # define sqlite3_value_text16be         0
112907  # define sqlite3_value_text16le         0
112908  # define sqlite3_column_database_name16 0
112909  # define sqlite3_column_table_name16    0
112910  # define sqlite3_column_origin_name16   0
112911  #endif
112912  
112913  #ifdef SQLITE_OMIT_COMPLETE
112914  # define sqlite3_complete 0
112915  # define sqlite3_complete16 0
112916  #endif
112917  
112918  #ifdef SQLITE_OMIT_DECLTYPE
112919  # define sqlite3_column_decltype16      0
112920  # define sqlite3_column_decltype        0
112921  #endif
112922  
112923  #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
112924  # define sqlite3_progress_handler 0
112925  #endif
112926  
112927  #ifdef SQLITE_OMIT_VIRTUALTABLE
112928  # define sqlite3_create_module 0
112929  # define sqlite3_create_module_v2 0
112930  # define sqlite3_declare_vtab 0
112931  # define sqlite3_vtab_config 0
112932  # define sqlite3_vtab_on_conflict 0
112933  #endif
112934  
112935  #ifdef SQLITE_OMIT_SHARED_CACHE
112936  # define sqlite3_enable_shared_cache 0
112937  #endif
112938  
112939  #if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
112940  # define sqlite3_profile       0
112941  # define sqlite3_trace         0
112942  #endif
112943  
112944  #ifdef SQLITE_OMIT_GET_TABLE
112945  # define sqlite3_free_table    0
112946  # define sqlite3_get_table     0
112947  #endif
112948  
112949  #ifdef SQLITE_OMIT_INCRBLOB
112950  #define sqlite3_bind_zeroblob  0
112951  #define sqlite3_blob_bytes     0
112952  #define sqlite3_blob_close     0
112953  #define sqlite3_blob_open      0
112954  #define sqlite3_blob_read      0
112955  #define sqlite3_blob_write     0
112956  #define sqlite3_blob_reopen    0
112957  #endif
112958  
112959  #if defined(SQLITE_OMIT_TRACE)
112960  # define sqlite3_trace_v2      0
112961  #endif
112962  
112963  /*
112964  ** The following structure contains pointers to all SQLite API routines.
112965  ** A pointer to this structure is passed into extensions when they are
112966  ** loaded so that the extension can make calls back into the SQLite
112967  ** library.
112968  **
112969  ** When adding new APIs, add them to the bottom of this structure
112970  ** in order to preserve backwards compatibility.
112971  **
112972  ** Extensions that use newer APIs should first call the
112973  ** sqlite3_libversion_number() to make sure that the API they
112974  ** intend to use is supported by the library.  Extensions should
112975  ** also check to make sure that the pointer to the function is
112976  ** not NULL before calling it.
112977  */
112978  static const sqlite3_api_routines sqlite3Apis = {
112979    sqlite3_aggregate_context,
112980  #ifndef SQLITE_OMIT_DEPRECATED
112981    sqlite3_aggregate_count,
112982  #else
112983    0,
112984  #endif
112985    sqlite3_bind_blob,
112986    sqlite3_bind_double,
112987    sqlite3_bind_int,
112988    sqlite3_bind_int64,
112989    sqlite3_bind_null,
112990    sqlite3_bind_parameter_count,
112991    sqlite3_bind_parameter_index,
112992    sqlite3_bind_parameter_name,
112993    sqlite3_bind_text,
112994    sqlite3_bind_text16,
112995    sqlite3_bind_value,
112996    sqlite3_busy_handler,
112997    sqlite3_busy_timeout,
112998    sqlite3_changes,
112999    sqlite3_close,
113000    sqlite3_collation_needed,
113001    sqlite3_collation_needed16,
113002    sqlite3_column_blob,
113003    sqlite3_column_bytes,
113004    sqlite3_column_bytes16,
113005    sqlite3_column_count,
113006    sqlite3_column_database_name,
113007    sqlite3_column_database_name16,
113008    sqlite3_column_decltype,
113009    sqlite3_column_decltype16,
113010    sqlite3_column_double,
113011    sqlite3_column_int,
113012    sqlite3_column_int64,
113013    sqlite3_column_name,
113014    sqlite3_column_name16,
113015    sqlite3_column_origin_name,
113016    sqlite3_column_origin_name16,
113017    sqlite3_column_table_name,
113018    sqlite3_column_table_name16,
113019    sqlite3_column_text,
113020    sqlite3_column_text16,
113021    sqlite3_column_type,
113022    sqlite3_column_value,
113023    sqlite3_commit_hook,
113024    sqlite3_complete,
113025    sqlite3_complete16,
113026    sqlite3_create_collation,
113027    sqlite3_create_collation16,
113028    sqlite3_create_function,
113029    sqlite3_create_function16,
113030    sqlite3_create_module,
113031    sqlite3_data_count,
113032    sqlite3_db_handle,
113033    sqlite3_declare_vtab,
113034    sqlite3_enable_shared_cache,
113035    sqlite3_errcode,
113036    sqlite3_errmsg,
113037    sqlite3_errmsg16,
113038    sqlite3_exec,
113039  #ifndef SQLITE_OMIT_DEPRECATED
113040    sqlite3_expired,
113041  #else
113042    0,
113043  #endif
113044    sqlite3_finalize,
113045    sqlite3_free,
113046    sqlite3_free_table,
113047    sqlite3_get_autocommit,
113048    sqlite3_get_auxdata,
113049    sqlite3_get_table,
113050    0,     /* Was sqlite3_global_recover(), but that function is deprecated */
113051    sqlite3_interrupt,
113052    sqlite3_last_insert_rowid,
113053    sqlite3_libversion,
113054    sqlite3_libversion_number,
113055    sqlite3_malloc,
113056    sqlite3_mprintf,
113057    sqlite3_open,
113058    sqlite3_open16,
113059    sqlite3_prepare,
113060    sqlite3_prepare16,
113061    sqlite3_profile,
113062    sqlite3_progress_handler,
113063    sqlite3_realloc,
113064    sqlite3_reset,
113065    sqlite3_result_blob,
113066    sqlite3_result_double,
113067    sqlite3_result_error,
113068    sqlite3_result_error16,
113069    sqlite3_result_int,
113070    sqlite3_result_int64,
113071    sqlite3_result_null,
113072    sqlite3_result_text,
113073    sqlite3_result_text16,
113074    sqlite3_result_text16be,
113075    sqlite3_result_text16le,
113076    sqlite3_result_value,
113077    sqlite3_rollback_hook,
113078    sqlite3_set_authorizer,
113079    sqlite3_set_auxdata,
113080    sqlite3_snprintf,
113081    sqlite3_step,
113082    sqlite3_table_column_metadata,
113083  #ifndef SQLITE_OMIT_DEPRECATED
113084    sqlite3_thread_cleanup,
113085  #else
113086    0,
113087  #endif
113088    sqlite3_total_changes,
113089    sqlite3_trace,
113090  #ifndef SQLITE_OMIT_DEPRECATED
113091    sqlite3_transfer_bindings,
113092  #else
113093    0,
113094  #endif
113095    sqlite3_update_hook,
113096    sqlite3_user_data,
113097    sqlite3_value_blob,
113098    sqlite3_value_bytes,
113099    sqlite3_value_bytes16,
113100    sqlite3_value_double,
113101    sqlite3_value_int,
113102    sqlite3_value_int64,
113103    sqlite3_value_numeric_type,
113104    sqlite3_value_text,
113105    sqlite3_value_text16,
113106    sqlite3_value_text16be,
113107    sqlite3_value_text16le,
113108    sqlite3_value_type,
113109    sqlite3_vmprintf,
113110    /*
113111    ** The original API set ends here.  All extensions can call any
113112    ** of the APIs above provided that the pointer is not NULL.  But
113113    ** before calling APIs that follow, extension should check the
113114    ** sqlite3_libversion_number() to make sure they are dealing with
113115    ** a library that is new enough to support that API.
113116    *************************************************************************
113117    */
113118    sqlite3_overload_function,
113119  
113120    /*
113121    ** Added after 3.3.13
113122    */
113123    sqlite3_prepare_v2,
113124    sqlite3_prepare16_v2,
113125    sqlite3_clear_bindings,
113126  
113127    /*
113128    ** Added for 3.4.1
113129    */
113130    sqlite3_create_module_v2,
113131  
113132    /*
113133    ** Added for 3.5.0
113134    */
113135    sqlite3_bind_zeroblob,
113136    sqlite3_blob_bytes,
113137    sqlite3_blob_close,
113138    sqlite3_blob_open,
113139    sqlite3_blob_read,
113140    sqlite3_blob_write,
113141    sqlite3_create_collation_v2,
113142    sqlite3_file_control,
113143    sqlite3_memory_highwater,
113144    sqlite3_memory_used,
113145  #ifdef SQLITE_MUTEX_OMIT
113146    0, 
113147    0, 
113148    0,
113149    0,
113150    0,
113151  #else
113152    sqlite3_mutex_alloc,
113153    sqlite3_mutex_enter,
113154    sqlite3_mutex_free,
113155    sqlite3_mutex_leave,
113156    sqlite3_mutex_try,
113157  #endif
113158    sqlite3_open_v2,
113159    sqlite3_release_memory,
113160    sqlite3_result_error_nomem,
113161    sqlite3_result_error_toobig,
113162    sqlite3_sleep,
113163    sqlite3_soft_heap_limit,
113164    sqlite3_vfs_find,
113165    sqlite3_vfs_register,
113166    sqlite3_vfs_unregister,
113167  
113168    /*
113169    ** Added for 3.5.8
113170    */
113171    sqlite3_threadsafe,
113172    sqlite3_result_zeroblob,
113173    sqlite3_result_error_code,
113174    sqlite3_test_control,
113175    sqlite3_randomness,
113176    sqlite3_context_db_handle,
113177  
113178    /*
113179    ** Added for 3.6.0
113180    */
113181    sqlite3_extended_result_codes,
113182    sqlite3_limit,
113183    sqlite3_next_stmt,
113184    sqlite3_sql,
113185    sqlite3_status,
113186  
113187    /*
113188    ** Added for 3.7.4
113189    */
113190    sqlite3_backup_finish,
113191    sqlite3_backup_init,
113192    sqlite3_backup_pagecount,
113193    sqlite3_backup_remaining,
113194    sqlite3_backup_step,
113195  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
113196    sqlite3_compileoption_get,
113197    sqlite3_compileoption_used,
113198  #else
113199    0,
113200    0,
113201  #endif
113202    sqlite3_create_function_v2,
113203    sqlite3_db_config,
113204    sqlite3_db_mutex,
113205    sqlite3_db_status,
113206    sqlite3_extended_errcode,
113207    sqlite3_log,
113208    sqlite3_soft_heap_limit64,
113209    sqlite3_sourceid,
113210    sqlite3_stmt_status,
113211    sqlite3_strnicmp,
113212  #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
113213    sqlite3_unlock_notify,
113214  #else
113215    0,
113216  #endif
113217  #ifndef SQLITE_OMIT_WAL
113218    sqlite3_wal_autocheckpoint,
113219    sqlite3_wal_checkpoint,
113220    sqlite3_wal_hook,
113221  #else
113222    0,
113223    0,
113224    0,
113225  #endif
113226    sqlite3_blob_reopen,
113227    sqlite3_vtab_config,
113228    sqlite3_vtab_on_conflict,
113229    sqlite3_close_v2,
113230    sqlite3_db_filename,
113231    sqlite3_db_readonly,
113232    sqlite3_db_release_memory,
113233    sqlite3_errstr,
113234    sqlite3_stmt_busy,
113235    sqlite3_stmt_readonly,
113236    sqlite3_stricmp,
113237    sqlite3_uri_boolean,
113238    sqlite3_uri_int64,
113239    sqlite3_uri_parameter,
113240    sqlite3_vsnprintf,
113241    sqlite3_wal_checkpoint_v2,
113242    /* Version 3.8.7 and later */
113243    sqlite3_auto_extension,
113244    sqlite3_bind_blob64,
113245    sqlite3_bind_text64,
113246    sqlite3_cancel_auto_extension,
113247    sqlite3_load_extension,
113248    sqlite3_malloc64,
113249    sqlite3_msize,
113250    sqlite3_realloc64,
113251    sqlite3_reset_auto_extension,
113252    sqlite3_result_blob64,
113253    sqlite3_result_text64,
113254    sqlite3_strglob,
113255    /* Version 3.8.11 and later */
113256    (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
113257    sqlite3_value_free,
113258    sqlite3_result_zeroblob64,
113259    sqlite3_bind_zeroblob64,
113260    /* Version 3.9.0 and later */
113261    sqlite3_value_subtype,
113262    sqlite3_result_subtype,
113263    /* Version 3.10.0 and later */
113264    sqlite3_status64,
113265    sqlite3_strlike,
113266    sqlite3_db_cacheflush,
113267    /* Version 3.12.0 and later */
113268    sqlite3_system_errno,
113269    /* Version 3.14.0 and later */
113270    sqlite3_trace_v2,
113271    sqlite3_expanded_sql,
113272    /* Version 3.18.0 and later */
113273    sqlite3_set_last_insert_rowid,
113274    /* Version 3.20.0 and later */
113275    sqlite3_prepare_v3,
113276    sqlite3_prepare16_v3,
113277    sqlite3_bind_pointer,
113278    sqlite3_result_pointer,
113279    sqlite3_value_pointer
113280  };
113281  
113282  /*
113283  ** Attempt to load an SQLite extension library contained in the file
113284  ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
113285  ** default entry point name (sqlite3_extension_init) is used.  Use
113286  ** of the default name is recommended.
113287  **
113288  ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
113289  **
113290  ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
113291  ** error message text.  The calling function should free this memory
113292  ** by calling sqlite3DbFree(db, ).
113293  */
113294  static int sqlite3LoadExtension(
113295    sqlite3 *db,          /* Load the extension into this database connection */
113296    const char *zFile,    /* Name of the shared library containing extension */
113297    const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
113298    char **pzErrMsg       /* Put error message here if not 0 */
113299  ){
113300    sqlite3_vfs *pVfs = db->pVfs;
113301    void *handle;
113302    sqlite3_loadext_entry xInit;
113303    char *zErrmsg = 0;
113304    const char *zEntry;
113305    char *zAltEntry = 0;
113306    void **aHandle;
113307    u64 nMsg = 300 + sqlite3Strlen30(zFile);
113308    int ii;
113309    int rc;
113310  
113311    /* Shared library endings to try if zFile cannot be loaded as written */
113312    static const char *azEndings[] = {
113313  #if SQLITE_OS_WIN
113314       "dll"   
113315  #elif defined(__APPLE__)
113316       "dylib"
113317  #else
113318       "so"
113319  #endif
113320    };
113321  
113322  
113323    if( pzErrMsg ) *pzErrMsg = 0;
113324  
113325    /* Ticket #1863.  To avoid a creating security problems for older
113326    ** applications that relink against newer versions of SQLite, the
113327    ** ability to run load_extension is turned off by default.  One
113328    ** must call either sqlite3_enable_load_extension(db) or
113329    ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
113330    ** to turn on extension loading.
113331    */
113332    if( (db->flags & SQLITE_LoadExtension)==0 ){
113333      if( pzErrMsg ){
113334        *pzErrMsg = sqlite3_mprintf("not authorized");
113335      }
113336      return SQLITE_ERROR;
113337    }
113338  
113339    zEntry = zProc ? zProc : "sqlite3_extension_init";
113340  
113341    handle = sqlite3OsDlOpen(pVfs, zFile);
113342  #if SQLITE_OS_UNIX || SQLITE_OS_WIN
113343    for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
113344      char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
113345      if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
113346      handle = sqlite3OsDlOpen(pVfs, zAltFile);
113347      sqlite3_free(zAltFile);
113348    }
113349  #endif
113350    if( handle==0 ){
113351      if( pzErrMsg ){
113352        *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
113353        if( zErrmsg ){
113354          sqlite3_snprintf(nMsg, zErrmsg, 
113355              "unable to open shared library [%s]", zFile);
113356          sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
113357        }
113358      }
113359      return SQLITE_ERROR;
113360    }
113361    xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
113362  
113363    /* If no entry point was specified and the default legacy
113364    ** entry point name "sqlite3_extension_init" was not found, then
113365    ** construct an entry point name "sqlite3_X_init" where the X is
113366    ** replaced by the lowercase value of every ASCII alphabetic 
113367    ** character in the filename after the last "/" upto the first ".",
113368    ** and eliding the first three characters if they are "lib".  
113369    ** Examples:
113370    **
113371    **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init
113372    **    C:/lib/mathfuncs.dll              ==>  sqlite3_mathfuncs_init
113373    */
113374    if( xInit==0 && zProc==0 ){
113375      int iFile, iEntry, c;
113376      int ncFile = sqlite3Strlen30(zFile);
113377      zAltEntry = sqlite3_malloc64(ncFile+30);
113378      if( zAltEntry==0 ){
113379        sqlite3OsDlClose(pVfs, handle);
113380        return SQLITE_NOMEM_BKPT;
113381      }
113382      memcpy(zAltEntry, "sqlite3_", 8);
113383      for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
113384      iFile++;
113385      if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
113386      for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
113387        if( sqlite3Isalpha(c) ){
113388          zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
113389        }
113390      }
113391      memcpy(zAltEntry+iEntry, "_init", 6);
113392      zEntry = zAltEntry;
113393      xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
113394    }
113395    if( xInit==0 ){
113396      if( pzErrMsg ){
113397        nMsg += sqlite3Strlen30(zEntry);
113398        *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
113399        if( zErrmsg ){
113400          sqlite3_snprintf(nMsg, zErrmsg,
113401              "no entry point [%s] in shared library [%s]", zEntry, zFile);
113402          sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
113403        }
113404      }
113405      sqlite3OsDlClose(pVfs, handle);
113406      sqlite3_free(zAltEntry);
113407      return SQLITE_ERROR;
113408    }
113409    sqlite3_free(zAltEntry);
113410    rc = xInit(db, &zErrmsg, &sqlite3Apis);
113411    if( rc ){
113412      if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
113413      if( pzErrMsg ){
113414        *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
113415      }
113416      sqlite3_free(zErrmsg);
113417      sqlite3OsDlClose(pVfs, handle);
113418      return SQLITE_ERROR;
113419    }
113420  
113421    /* Append the new shared library handle to the db->aExtension array. */
113422    aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
113423    if( aHandle==0 ){
113424      return SQLITE_NOMEM_BKPT;
113425    }
113426    if( db->nExtension>0 ){
113427      memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
113428    }
113429    sqlite3DbFree(db, db->aExtension);
113430    db->aExtension = aHandle;
113431  
113432    db->aExtension[db->nExtension++] = handle;
113433    return SQLITE_OK;
113434  }
113435  SQLITE_API int sqlite3_load_extension(
113436    sqlite3 *db,          /* Load the extension into this database connection */
113437    const char *zFile,    /* Name of the shared library containing extension */
113438    const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
113439    char **pzErrMsg       /* Put error message here if not 0 */
113440  ){
113441    int rc;
113442    sqlite3_mutex_enter(db->mutex);
113443    rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
113444    rc = sqlite3ApiExit(db, rc);
113445    sqlite3_mutex_leave(db->mutex);
113446    return rc;
113447  }
113448  
113449  /*
113450  ** Call this routine when the database connection is closing in order
113451  ** to clean up loaded extensions
113452  */
113453  SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
113454    int i;
113455    assert( sqlite3_mutex_held(db->mutex) );
113456    for(i=0; i<db->nExtension; i++){
113457      sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
113458    }
113459    sqlite3DbFree(db, db->aExtension);
113460  }
113461  
113462  /*
113463  ** Enable or disable extension loading.  Extension loading is disabled by
113464  ** default so as not to open security holes in older applications.
113465  */
113466  SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
113467    sqlite3_mutex_enter(db->mutex);
113468    if( onoff ){
113469      db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
113470    }else{
113471      db->flags &= ~(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
113472    }
113473    sqlite3_mutex_leave(db->mutex);
113474    return SQLITE_OK;
113475  }
113476  
113477  #endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */
113478  
113479  /*
113480  ** The following object holds the list of automatically loaded
113481  ** extensions.
113482  **
113483  ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
113484  ** mutex must be held while accessing this list.
113485  */
113486  typedef struct sqlite3AutoExtList sqlite3AutoExtList;
113487  static SQLITE_WSD struct sqlite3AutoExtList {
113488    u32 nExt;              /* Number of entries in aExt[] */          
113489    void (**aExt)(void);   /* Pointers to the extension init functions */
113490  } sqlite3Autoext = { 0, 0 };
113491  
113492  /* The "wsdAutoext" macro will resolve to the autoextension
113493  ** state vector.  If writable static data is unsupported on the target,
113494  ** we have to locate the state vector at run-time.  In the more common
113495  ** case where writable static data is supported, wsdStat can refer directly
113496  ** to the "sqlite3Autoext" state vector declared above.
113497  */
113498  #ifdef SQLITE_OMIT_WSD
113499  # define wsdAutoextInit \
113500    sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
113501  # define wsdAutoext x[0]
113502  #else
113503  # define wsdAutoextInit
113504  # define wsdAutoext sqlite3Autoext
113505  #endif
113506  
113507  
113508  /*
113509  ** Register a statically linked extension that is automatically
113510  ** loaded by every new database connection.
113511  */
113512  SQLITE_API int sqlite3_auto_extension(
113513    void (*xInit)(void)
113514  ){
113515    int rc = SQLITE_OK;
113516  #ifndef SQLITE_OMIT_AUTOINIT
113517    rc = sqlite3_initialize();
113518    if( rc ){
113519      return rc;
113520    }else
113521  #endif
113522    {
113523      u32 i;
113524  #if SQLITE_THREADSAFE
113525      sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
113526  #endif
113527      wsdAutoextInit;
113528      sqlite3_mutex_enter(mutex);
113529      for(i=0; i<wsdAutoext.nExt; i++){
113530        if( wsdAutoext.aExt[i]==xInit ) break;
113531      }
113532      if( i==wsdAutoext.nExt ){
113533        u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
113534        void (**aNew)(void);
113535        aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
113536        if( aNew==0 ){
113537          rc = SQLITE_NOMEM_BKPT;
113538        }else{
113539          wsdAutoext.aExt = aNew;
113540          wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
113541          wsdAutoext.nExt++;
113542        }
113543      }
113544      sqlite3_mutex_leave(mutex);
113545      assert( (rc&0xff)==rc );
113546      return rc;
113547    }
113548  }
113549  
113550  /*
113551  ** Cancel a prior call to sqlite3_auto_extension.  Remove xInit from the
113552  ** set of routines that is invoked for each new database connection, if it
113553  ** is currently on the list.  If xInit is not on the list, then this
113554  ** routine is a no-op.
113555  **
113556  ** Return 1 if xInit was found on the list and removed.  Return 0 if xInit
113557  ** was not on the list.
113558  */
113559  SQLITE_API int sqlite3_cancel_auto_extension(
113560    void (*xInit)(void)
113561  ){
113562  #if SQLITE_THREADSAFE
113563    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
113564  #endif
113565    int i;
113566    int n = 0;
113567    wsdAutoextInit;
113568    sqlite3_mutex_enter(mutex);
113569    for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
113570      if( wsdAutoext.aExt[i]==xInit ){
113571        wsdAutoext.nExt--;
113572        wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
113573        n++;
113574        break;
113575      }
113576    }
113577    sqlite3_mutex_leave(mutex);
113578    return n;
113579  }
113580  
113581  /*
113582  ** Reset the automatic extension loading mechanism.
113583  */
113584  SQLITE_API void sqlite3_reset_auto_extension(void){
113585  #ifndef SQLITE_OMIT_AUTOINIT
113586    if( sqlite3_initialize()==SQLITE_OK )
113587  #endif
113588    {
113589  #if SQLITE_THREADSAFE
113590      sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
113591  #endif
113592      wsdAutoextInit;
113593      sqlite3_mutex_enter(mutex);
113594      sqlite3_free(wsdAutoext.aExt);
113595      wsdAutoext.aExt = 0;
113596      wsdAutoext.nExt = 0;
113597      sqlite3_mutex_leave(mutex);
113598    }
113599  }
113600  
113601  /*
113602  ** Load all automatic extensions.
113603  **
113604  ** If anything goes wrong, set an error in the database connection.
113605  */
113606  SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
113607    u32 i;
113608    int go = 1;
113609    int rc;
113610    sqlite3_loadext_entry xInit;
113611  
113612    wsdAutoextInit;
113613    if( wsdAutoext.nExt==0 ){
113614      /* Common case: early out without every having to acquire a mutex */
113615      return;
113616    }
113617    for(i=0; go; i++){
113618      char *zErrmsg;
113619  #if SQLITE_THREADSAFE
113620      sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
113621  #endif
113622  #ifdef SQLITE_OMIT_LOAD_EXTENSION
113623      const sqlite3_api_routines *pThunk = 0;
113624  #else
113625      const sqlite3_api_routines *pThunk = &sqlite3Apis;
113626  #endif
113627      sqlite3_mutex_enter(mutex);
113628      if( i>=wsdAutoext.nExt ){
113629        xInit = 0;
113630        go = 0;
113631      }else{
113632        xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
113633      }
113634      sqlite3_mutex_leave(mutex);
113635      zErrmsg = 0;
113636      if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){
113637        sqlite3ErrorWithMsg(db, rc,
113638              "automatic extension loading failed: %s", zErrmsg);
113639        go = 0;
113640      }
113641      sqlite3_free(zErrmsg);
113642    }
113643  }
113644  
113645  /************** End of loadext.c *********************************************/
113646  /************** Begin file pragma.c ******************************************/
113647  /*
113648  ** 2003 April 6
113649  **
113650  ** The author disclaims copyright to this source code.  In place of
113651  ** a legal notice, here is a blessing:
113652  **
113653  **    May you do good and not evil.
113654  **    May you find forgiveness for yourself and forgive others.
113655  **    May you share freely, never taking more than you give.
113656  **
113657  *************************************************************************
113658  ** This file contains code used to implement the PRAGMA command.
113659  */
113660  /* #include "sqliteInt.h" */
113661  
113662  #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
113663  #  if defined(__APPLE__)
113664  #    define SQLITE_ENABLE_LOCKING_STYLE 1
113665  #  else
113666  #    define SQLITE_ENABLE_LOCKING_STYLE 0
113667  #  endif
113668  #endif
113669  
113670  /***************************************************************************
113671  ** The "pragma.h" include file is an automatically generated file that
113672  ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
113673  ** object.  This ensures that the aPragmaName[] table is arranged in
113674  ** lexicographical order to facility a binary search of the pragma name.
113675  ** Do not edit pragma.h directly.  Edit and rerun the script in at 
113676  ** ../tool/mkpragmatab.tcl. */
113677  /************** Include pragma.h in the middle of pragma.c *******************/
113678  /************** Begin file pragma.h ******************************************/
113679  /* DO NOT EDIT!
113680  ** This file is automatically generated by the script at
113681  ** ../tool/mkpragmatab.tcl.  To update the set of pragmas, edit
113682  ** that script and rerun it.
113683  */
113684  
113685  /* The various pragma types */
113686  #define PragTyp_HEADER_VALUE                   0
113687  #define PragTyp_AUTO_VACUUM                    1
113688  #define PragTyp_FLAG                           2
113689  #define PragTyp_BUSY_TIMEOUT                   3
113690  #define PragTyp_CACHE_SIZE                     4
113691  #define PragTyp_CACHE_SPILL                    5
113692  #define PragTyp_CASE_SENSITIVE_LIKE            6
113693  #define PragTyp_COLLATION_LIST                 7
113694  #define PragTyp_COMPILE_OPTIONS                8
113695  #define PragTyp_DATA_STORE_DIRECTORY           9
113696  #define PragTyp_DATABASE_LIST                 10
113697  #define PragTyp_DEFAULT_CACHE_SIZE            11
113698  #define PragTyp_ENCODING                      12
113699  #define PragTyp_FOREIGN_KEY_CHECK             13
113700  #define PragTyp_FOREIGN_KEY_LIST              14
113701  #define PragTyp_FUNCTION_LIST                 15
113702  #define PragTyp_INCREMENTAL_VACUUM            16
113703  #define PragTyp_INDEX_INFO                    17
113704  #define PragTyp_INDEX_LIST                    18
113705  #define PragTyp_INTEGRITY_CHECK               19
113706  #define PragTyp_JOURNAL_MODE                  20
113707  #define PragTyp_JOURNAL_SIZE_LIMIT            21
113708  #define PragTyp_LOCK_PROXY_FILE               22
113709  #define PragTyp_LOCKING_MODE                  23
113710  #define PragTyp_PAGE_COUNT                    24
113711  #define PragTyp_MMAP_SIZE                     25
113712  #define PragTyp_MODULE_LIST                   26
113713  #define PragTyp_OPTIMIZE                      27
113714  #define PragTyp_PAGE_SIZE                     28
113715  #define PragTyp_PRAGMA_LIST                   29
113716  #define PragTyp_SECURE_DELETE                 30
113717  #define PragTyp_SHRINK_MEMORY                 31
113718  #define PragTyp_SOFT_HEAP_LIMIT               32
113719  #define PragTyp_SYNCHRONOUS                   33
113720  #define PragTyp_TABLE_INFO                    34
113721  #define PragTyp_TEMP_STORE                    35
113722  #define PragTyp_TEMP_STORE_DIRECTORY          36
113723  #define PragTyp_THREADS                       37
113724  #define PragTyp_WAL_AUTOCHECKPOINT            38
113725  #define PragTyp_WAL_CHECKPOINT                39
113726  #define PragTyp_ACTIVATE_EXTENSIONS           40
113727  #define PragTyp_HEXKEY                        41
113728  #define PragTyp_KEY                           42
113729  #define PragTyp_REKEY                         43
113730  #define PragTyp_LOCK_STATUS                   44
113731  #define PragTyp_PARSER_TRACE                  45
113732  #define PragTyp_STATS                         46
113733  
113734  /* Property flags associated with various pragma. */
113735  #define PragFlg_NeedSchema 0x01 /* Force schema load before running */
113736  #define PragFlg_NoColumns  0x02 /* OP_ResultRow called with zero columns */
113737  #define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */
113738  #define PragFlg_ReadOnly   0x08 /* Read-only HEADER_VALUE */
113739  #define PragFlg_Result0    0x10 /* Acts as query when no argument */
113740  #define PragFlg_Result1    0x20 /* Acts as query when has one argument */
113741  #define PragFlg_SchemaOpt  0x40 /* Schema restricts name search if present */
113742  #define PragFlg_SchemaReq  0x80 /* Schema required - "main" is default */
113743  
113744  /* Names of columns for pragmas that return multi-column result
113745  ** or that return single-column results where the name of the
113746  ** result column is different from the name of the pragma
113747  */
113748  static const char *const pragCName[] = {
113749    /*   0 */ "cache_size",  /* Used by: default_cache_size */
113750    /*   1 */ "cid",         /* Used by: table_info */
113751    /*   2 */ "name",       
113752    /*   3 */ "type",       
113753    /*   4 */ "notnull",    
113754    /*   5 */ "dflt_value", 
113755    /*   6 */ "pk",         
113756    /*   7 */ "tbl",         /* Used by: stats */
113757    /*   8 */ "idx",        
113758    /*   9 */ "wdth",       
113759    /*  10 */ "hght",       
113760    /*  11 */ "flgs",       
113761    /*  12 */ "seqno",       /* Used by: index_info */
113762    /*  13 */ "cid",        
113763    /*  14 */ "name",       
113764    /*  15 */ "seqno",       /* Used by: index_xinfo */
113765    /*  16 */ "cid",        
113766    /*  17 */ "name",       
113767    /*  18 */ "desc",       
113768    /*  19 */ "coll",       
113769    /*  20 */ "key",        
113770    /*  21 */ "seq",         /* Used by: index_list */
113771    /*  22 */ "name",       
113772    /*  23 */ "unique",     
113773    /*  24 */ "origin",     
113774    /*  25 */ "partial",    
113775    /*  26 */ "seq",         /* Used by: database_list */
113776    /*  27 */ "name",       
113777    /*  28 */ "file",       
113778    /*  29 */ "name",        /* Used by: function_list */
113779    /*  30 */ "builtin",    
113780    /*  31 */ "name",        /* Used by: module_list pragma_list */
113781    /*  32 */ "seq",         /* Used by: collation_list */
113782    /*  33 */ "name",       
113783    /*  34 */ "id",          /* Used by: foreign_key_list */
113784    /*  35 */ "seq",        
113785    /*  36 */ "table",      
113786    /*  37 */ "from",       
113787    /*  38 */ "to",         
113788    /*  39 */ "on_update",  
113789    /*  40 */ "on_delete",  
113790    /*  41 */ "match",      
113791    /*  42 */ "table",       /* Used by: foreign_key_check */
113792    /*  43 */ "rowid",      
113793    /*  44 */ "parent",     
113794    /*  45 */ "fkid",       
113795    /*  46 */ "busy",        /* Used by: wal_checkpoint */
113796    /*  47 */ "log",        
113797    /*  48 */ "checkpointed",
113798    /*  49 */ "timeout",     /* Used by: busy_timeout */
113799    /*  50 */ "database",    /* Used by: lock_status */
113800    /*  51 */ "status",     
113801  };
113802  
113803  /* Definitions of all built-in pragmas */
113804  typedef struct PragmaName {
113805    const char *const zName; /* Name of pragma */
113806    u8 ePragTyp;             /* PragTyp_XXX value */
113807    u8 mPragFlg;             /* Zero or more PragFlg_XXX values */
113808    u8 iPragCName;           /* Start of column names in pragCName[] */
113809    u8 nPragCName;           /* Num of col names. 0 means use pragma name */
113810    u32 iArg;                /* Extra argument */
113811  } PragmaName;
113812  static const PragmaName aPragmaName[] = {
113813  #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
113814   {/* zName:     */ "activate_extensions",
113815    /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,
113816    /* ePragFlg:  */ 0,
113817    /* ColNames:  */ 0, 0,
113818    /* iArg:      */ 0 },
113819  #endif
113820  #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
113821   {/* zName:     */ "application_id",
113822    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
113823    /* ePragFlg:  */ PragFlg_NoColumns1|PragFlg_Result0,
113824    /* ColNames:  */ 0, 0,
113825    /* iArg:      */ BTREE_APPLICATION_ID },
113826  #endif
113827  #if !defined(SQLITE_OMIT_AUTOVACUUM)
113828   {/* zName:     */ "auto_vacuum",
113829    /* ePragTyp:  */ PragTyp_AUTO_VACUUM,
113830    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
113831    /* ColNames:  */ 0, 0,
113832    /* iArg:      */ 0 },
113833  #endif
113834  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113835  #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
113836   {/* zName:     */ "automatic_index",
113837    /* ePragTyp:  */ PragTyp_FLAG,
113838    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113839    /* ColNames:  */ 0, 0,
113840    /* iArg:      */ SQLITE_AutoIndex },
113841  #endif
113842  #endif
113843   {/* zName:     */ "busy_timeout",
113844    /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
113845    /* ePragFlg:  */ PragFlg_Result0,
113846    /* ColNames:  */ 49, 1,
113847    /* iArg:      */ 0 },
113848  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
113849   {/* zName:     */ "cache_size",
113850    /* ePragTyp:  */ PragTyp_CACHE_SIZE,
113851    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
113852    /* ColNames:  */ 0, 0,
113853    /* iArg:      */ 0 },
113854  #endif
113855  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113856   {/* zName:     */ "cache_spill",
113857    /* ePragTyp:  */ PragTyp_CACHE_SPILL,
113858    /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
113859    /* ColNames:  */ 0, 0,
113860    /* iArg:      */ 0 },
113861  #endif
113862   {/* zName:     */ "case_sensitive_like",
113863    /* ePragTyp:  */ PragTyp_CASE_SENSITIVE_LIKE,
113864    /* ePragFlg:  */ PragFlg_NoColumns,
113865    /* ColNames:  */ 0, 0,
113866    /* iArg:      */ 0 },
113867   {/* zName:     */ "cell_size_check",
113868    /* ePragTyp:  */ PragTyp_FLAG,
113869    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113870    /* ColNames:  */ 0, 0,
113871    /* iArg:      */ SQLITE_CellSizeCk },
113872  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113873   {/* zName:     */ "checkpoint_fullfsync",
113874    /* ePragTyp:  */ PragTyp_FLAG,
113875    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113876    /* ColNames:  */ 0, 0,
113877    /* iArg:      */ SQLITE_CkptFullFSync },
113878  #endif
113879  #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
113880   {/* zName:     */ "collation_list",
113881    /* ePragTyp:  */ PragTyp_COLLATION_LIST,
113882    /* ePragFlg:  */ PragFlg_Result0,
113883    /* ColNames:  */ 32, 2,
113884    /* iArg:      */ 0 },
113885  #endif
113886  #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
113887   {/* zName:     */ "compile_options",
113888    /* ePragTyp:  */ PragTyp_COMPILE_OPTIONS,
113889    /* ePragFlg:  */ PragFlg_Result0,
113890    /* ColNames:  */ 0, 0,
113891    /* iArg:      */ 0 },
113892  #endif
113893  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113894   {/* zName:     */ "count_changes",
113895    /* ePragTyp:  */ PragTyp_FLAG,
113896    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113897    /* ColNames:  */ 0, 0,
113898    /* iArg:      */ SQLITE_CountRows },
113899  #endif
113900  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
113901   {/* zName:     */ "data_store_directory",
113902    /* ePragTyp:  */ PragTyp_DATA_STORE_DIRECTORY,
113903    /* ePragFlg:  */ PragFlg_NoColumns1,
113904    /* ColNames:  */ 0, 0,
113905    /* iArg:      */ 0 },
113906  #endif
113907  #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
113908   {/* zName:     */ "data_version",
113909    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
113910    /* ePragFlg:  */ PragFlg_ReadOnly|PragFlg_Result0,
113911    /* ColNames:  */ 0, 0,
113912    /* iArg:      */ BTREE_DATA_VERSION },
113913  #endif
113914  #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
113915   {/* zName:     */ "database_list",
113916    /* ePragTyp:  */ PragTyp_DATABASE_LIST,
113917    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0,
113918    /* ColNames:  */ 26, 3,
113919    /* iArg:      */ 0 },
113920  #endif
113921  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
113922   {/* zName:     */ "default_cache_size",
113923    /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
113924    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
113925    /* ColNames:  */ 0, 1,
113926    /* iArg:      */ 0 },
113927  #endif
113928  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113929  #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
113930   {/* zName:     */ "defer_foreign_keys",
113931    /* ePragTyp:  */ PragTyp_FLAG,
113932    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113933    /* ColNames:  */ 0, 0,
113934    /* iArg:      */ SQLITE_DeferFKs },
113935  #endif
113936  #endif
113937  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113938   {/* zName:     */ "empty_result_callbacks",
113939    /* ePragTyp:  */ PragTyp_FLAG,
113940    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113941    /* ColNames:  */ 0, 0,
113942    /* iArg:      */ SQLITE_NullCallback },
113943  #endif
113944  #if !defined(SQLITE_OMIT_UTF16)
113945   {/* zName:     */ "encoding",
113946    /* ePragTyp:  */ PragTyp_ENCODING,
113947    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113948    /* ColNames:  */ 0, 0,
113949    /* iArg:      */ 0 },
113950  #endif
113951  #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
113952   {/* zName:     */ "foreign_key_check",
113953    /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
113954    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0,
113955    /* ColNames:  */ 42, 4,
113956    /* iArg:      */ 0 },
113957  #endif
113958  #if !defined(SQLITE_OMIT_FOREIGN_KEY)
113959   {/* zName:     */ "foreign_key_list",
113960    /* ePragTyp:  */ PragTyp_FOREIGN_KEY_LIST,
113961    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
113962    /* ColNames:  */ 34, 8,
113963    /* iArg:      */ 0 },
113964  #endif
113965  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113966  #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
113967   {/* zName:     */ "foreign_keys",
113968    /* ePragTyp:  */ PragTyp_FLAG,
113969    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113970    /* ColNames:  */ 0, 0,
113971    /* iArg:      */ SQLITE_ForeignKeys },
113972  #endif
113973  #endif
113974  #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
113975   {/* zName:     */ "freelist_count",
113976    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
113977    /* ePragFlg:  */ PragFlg_ReadOnly|PragFlg_Result0,
113978    /* ColNames:  */ 0, 0,
113979    /* iArg:      */ BTREE_FREE_PAGE_COUNT },
113980  #endif
113981  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113982   {/* zName:     */ "full_column_names",
113983    /* ePragTyp:  */ PragTyp_FLAG,
113984    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113985    /* ColNames:  */ 0, 0,
113986    /* iArg:      */ SQLITE_FullColNames },
113987   {/* zName:     */ "fullfsync",
113988    /* ePragTyp:  */ PragTyp_FLAG,
113989    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113990    /* ColNames:  */ 0, 0,
113991    /* iArg:      */ SQLITE_FullFSync },
113992  #endif
113993  #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
113994  #if defined(SQLITE_INTROSPECTION_PRAGMAS)
113995   {/* zName:     */ "function_list",
113996    /* ePragTyp:  */ PragTyp_FUNCTION_LIST,
113997    /* ePragFlg:  */ PragFlg_Result0,
113998    /* ColNames:  */ 29, 2,
113999    /* iArg:      */ 0 },
114000  #endif
114001  #endif
114002  #if defined(SQLITE_HAS_CODEC)
114003   {/* zName:     */ "hexkey",
114004    /* ePragTyp:  */ PragTyp_HEXKEY,
114005    /* ePragFlg:  */ 0,
114006    /* ColNames:  */ 0, 0,
114007    /* iArg:      */ 0 },
114008   {/* zName:     */ "hexrekey",
114009    /* ePragTyp:  */ PragTyp_HEXKEY,
114010    /* ePragFlg:  */ 0,
114011    /* ColNames:  */ 0, 0,
114012    /* iArg:      */ 0 },
114013  #endif
114014  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
114015  #if !defined(SQLITE_OMIT_CHECK)
114016   {/* zName:     */ "ignore_check_constraints",
114017    /* ePragTyp:  */ PragTyp_FLAG,
114018    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
114019    /* ColNames:  */ 0, 0,
114020    /* iArg:      */ SQLITE_IgnoreChecks },
114021  #endif
114022  #endif
114023  #if !defined(SQLITE_OMIT_AUTOVACUUM)
114024   {/* zName:     */ "incremental_vacuum",
114025    /* ePragTyp:  */ PragTyp_INCREMENTAL_VACUUM,
114026    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_NoColumns,
114027    /* ColNames:  */ 0, 0,
114028    /* iArg:      */ 0 },
114029  #endif
114030  #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
114031   {/* zName:     */ "index_info",
114032    /* ePragTyp:  */ PragTyp_INDEX_INFO,
114033    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
114034    /* ColNames:  */ 12, 3,
114035    /* iArg:      */ 0 },
114036   {/* zName:     */ "index_list",
114037    /* ePragTyp:  */ PragTyp_INDEX_LIST,
114038    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
114039    /* ColNames:  */ 21, 5,
114040    /* iArg:      */ 0 },
114041   {/* zName:     */ "index_xinfo",
114042    /* ePragTyp:  */ PragTyp_INDEX_INFO,
114043    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
114044    /* ColNames:  */ 15, 6,
114045    /* iArg:      */ 1 },
114046  #endif
114047  #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
114048   {/* zName:     */ "integrity_check",
114049    /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
114050    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
114051    /* ColNames:  */ 0, 0,
114052    /* iArg:      */ 0 },
114053  #endif
114054  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
114055   {/* zName:     */ "journal_mode",
114056    /* ePragTyp:  */ PragTyp_JOURNAL_MODE,
114057    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
114058    /* ColNames:  */ 0, 0,
114059    /* iArg:      */ 0 },
114060   {/* zName:     */ "journal_size_limit",
114061    /* ePragTyp:  */ PragTyp_JOURNAL_SIZE_LIMIT,
114062    /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq,
114063    /* ColNames:  */ 0, 0,
114064    /* iArg:      */ 0 },
114065  #endif
114066  #if defined(SQLITE_HAS_CODEC)
114067   {/* zName:     */ "key",
114068    /* ePragTyp:  */ PragTyp_KEY,
114069    /* ePragFlg:  */ 0,
114070    /* ColNames:  */ 0, 0,
114071    /* iArg:      */ 0 },
114072  #endif
114073  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
114074   {/* zName:     */ "legacy_file_format",
114075    /* ePragTyp:  */ PragTyp_FLAG,
114076    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
114077    /* ColNames:  */ 0, 0,
114078    /* iArg:      */ SQLITE_LegacyFileFmt },
114079  #endif
114080  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
114081   {/* zName:     */ "lock_proxy_file",
114082    /* ePragTyp:  */ PragTyp_LOCK_PROXY_FILE,
114083    /* ePragFlg:  */ PragFlg_NoColumns1,
114084    /* ColNames:  */ 0, 0,
114085    /* iArg:      */ 0 },
114086  #endif
114087  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
114088   {/* zName:     */ "lock_status",
114089    /* ePragTyp:  */ PragTyp_LOCK_STATUS,
114090    /* ePragFlg:  */ PragFlg_Result0,
114091    /* ColNames:  */ 50, 2,
114092    /* iArg:      */ 0 },
114093  #endif
114094  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
114095   {/* zName:     */ "locking_mode",
114096    /* ePragTyp:  */ PragTyp_LOCKING_MODE,
114097    /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq,
114098    /* ColNames:  */ 0, 0,
114099    /* iArg:      */ 0 },
114100   {/* zName:     */ "max_page_count",
114101    /* ePragTyp:  */ PragTyp_PAGE_COUNT,
114102    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
114103    /* ColNames:  */ 0, 0,
114104    /* iArg:      */ 0 },
114105   {/* zName:     */ "mmap_size",
114106    /* ePragTyp:  */ PragTyp_MMAP_SIZE,
114107    /* ePragFlg:  */ 0,
114108    /* ColNames:  */ 0, 0,
114109    /* iArg:      */ 0 },
114110  #endif
114111  #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
114112  #if !defined(SQLITE_OMIT_VIRTUALTABLE)
114113  #if defined(SQLITE_INTROSPECTION_PRAGMAS)
114114   {/* zName:     */ "module_list",
114115    /* ePragTyp:  */ PragTyp_MODULE_LIST,
114116    /* ePragFlg:  */ PragFlg_Result0,
114117    /* ColNames:  */ 31, 1,
114118    /* iArg:      */ 0 },
114119  #endif
114120  #endif
114121  #endif
114122   {/* zName:     */ "optimize",
114123    /* ePragTyp:  */ PragTyp_OPTIMIZE,
114124    /* ePragFlg:  */ PragFlg_Result1|PragFlg_NeedSchema,
114125    /* ColNames:  */ 0, 0,
114126    /* iArg:      */ 0 },
114127  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
114128   {/* zName:     */ "page_count",
114129    /* ePragTyp:  */ PragTyp_PAGE_COUNT,
114130    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
114131    /* ColNames:  */ 0, 0,
114132    /* iArg:      */ 0 },
114133   {/* zName:     */ "page_size",
114134    /* ePragTyp:  */ PragTyp_PAGE_SIZE,
114135    /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
114136    /* ColNames:  */ 0, 0,
114137    /* iArg:      */ 0 },
114138  #endif
114139  #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE)
114140   {/* zName:     */ "parser_trace",
114141    /* ePragTyp:  */ PragTyp_PARSER_TRACE,
114142    /* ePragFlg:  */ 0,
114143    /* ColNames:  */ 0, 0,
114144    /* iArg:      */ 0 },
114145  #endif
114146  #if defined(SQLITE_INTROSPECTION_PRAGMAS)
114147   {/* zName:     */ "pragma_list",
114148    /* ePragTyp:  */ PragTyp_PRAGMA_LIST,
114149    /* ePragFlg:  */ PragFlg_Result0,
114150    /* ColNames:  */ 31, 1,
114151    /* iArg:      */ 0 },
114152  #endif
114153  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
114154   {/* zName:     */ "query_only",
114155    /* ePragTyp:  */ PragTyp_FLAG,
114156    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
114157    /* ColNames:  */ 0, 0,
114158    /* iArg:      */ SQLITE_QueryOnly },
114159  #endif
114160  #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
114161   {/* zName:     */ "quick_check",
114162    /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
114163    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
114164    /* ColNames:  */ 0, 0,
114165    /* iArg:      */ 0 },
114166  #endif
114167  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
114168   {/* zName:     */ "read_uncommitted",
114169    /* ePragTyp:  */ PragTyp_FLAG,
114170    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
114171    /* ColNames:  */ 0, 0,
114172    /* iArg:      */ SQLITE_ReadUncommit },
114173   {/* zName:     */ "recursive_triggers",
114174    /* ePragTyp:  */ PragTyp_FLAG,
114175    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
114176    /* ColNames:  */ 0, 0,
114177    /* iArg:      */ SQLITE_RecTriggers },
114178  #endif
114179  #if defined(SQLITE_HAS_CODEC)
114180   {/* zName:     */ "rekey",
114181    /* ePragTyp:  */ PragTyp_REKEY,
114182    /* ePragFlg:  */ 0,
114183    /* ColNames:  */ 0, 0,
114184    /* iArg:      */ 0 },
114185  #endif
114186  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
114187   {/* zName:     */ "reverse_unordered_selects",
114188    /* ePragTyp:  */ PragTyp_FLAG,
114189    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
114190    /* ColNames:  */ 0, 0,
114191    /* iArg:      */ SQLITE_ReverseOrder },
114192  #endif
114193  #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
114194   {/* zName:     */ "schema_version",
114195    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
114196    /* ePragFlg:  */ PragFlg_NoColumns1|PragFlg_Result0,
114197    /* ColNames:  */ 0, 0,
114198    /* iArg:      */ BTREE_SCHEMA_VERSION },
114199  #endif
114200  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
114201   {/* zName:     */ "secure_delete",
114202    /* ePragTyp:  */ PragTyp_SECURE_DELETE,
114203    /* ePragFlg:  */ PragFlg_Result0,
114204    /* ColNames:  */ 0, 0,
114205    /* iArg:      */ 0 },
114206  #endif
114207  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
114208   {/* zName:     */ "short_column_names",
114209    /* ePragTyp:  */ PragTyp_FLAG,
114210    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
114211    /* ColNames:  */ 0, 0,
114212    /* iArg:      */ SQLITE_ShortColNames },
114213  #endif
114214   {/* zName:     */ "shrink_memory",
114215    /* ePragTyp:  */ PragTyp_SHRINK_MEMORY,
114216    /* ePragFlg:  */ PragFlg_NoColumns,
114217    /* ColNames:  */ 0, 0,
114218    /* iArg:      */ 0 },
114219   {/* zName:     */ "soft_heap_limit",
114220    /* ePragTyp:  */ PragTyp_SOFT_HEAP_LIMIT,
114221    /* ePragFlg:  */ PragFlg_Result0,
114222    /* ColNames:  */ 0, 0,
114223    /* iArg:      */ 0 },
114224  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
114225  #if defined(SQLITE_DEBUG)
114226   {/* zName:     */ "sql_trace",
114227    /* ePragTyp:  */ PragTyp_FLAG,
114228    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
114229    /* ColNames:  */ 0, 0,
114230    /* iArg:      */ SQLITE_SqlTrace },
114231  #endif
114232  #endif
114233  #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && defined(SQLITE_DEBUG)
114234   {/* zName:     */ "stats",
114235    /* ePragTyp:  */ PragTyp_STATS,
114236    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
114237    /* ColNames:  */ 7, 5,
114238    /* iArg:      */ 0 },
114239  #endif
114240  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
114241   {/* zName:     */ "synchronous",
114242    /* ePragTyp:  */ PragTyp_SYNCHRONOUS,
114243    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
114244    /* ColNames:  */ 0, 0,
114245    /* iArg:      */ 0 },
114246  #endif
114247  #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
114248   {/* zName:     */ "table_info",
114249    /* ePragTyp:  */ PragTyp_TABLE_INFO,
114250    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
114251    /* ColNames:  */ 1, 6,
114252    /* iArg:      */ 0 },
114253  #endif
114254  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
114255   {/* zName:     */ "temp_store",
114256    /* ePragTyp:  */ PragTyp_TEMP_STORE,
114257    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
114258    /* ColNames:  */ 0, 0,
114259    /* iArg:      */ 0 },
114260   {/* zName:     */ "temp_store_directory",
114261    /* ePragTyp:  */ PragTyp_TEMP_STORE_DIRECTORY,
114262    /* ePragFlg:  */ PragFlg_NoColumns1,
114263    /* ColNames:  */ 0, 0,
114264    /* iArg:      */ 0 },
114265  #endif
114266   {/* zName:     */ "threads",
114267    /* ePragTyp:  */ PragTyp_THREADS,
114268    /* ePragFlg:  */ PragFlg_Result0,
114269    /* ColNames:  */ 0, 0,
114270    /* iArg:      */ 0 },
114271  #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
114272   {/* zName:     */ "user_version",
114273    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
114274    /* ePragFlg:  */ PragFlg_NoColumns1|PragFlg_Result0,
114275    /* ColNames:  */ 0, 0,
114276    /* iArg:      */ BTREE_USER_VERSION },
114277  #endif
114278  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
114279  #if defined(SQLITE_DEBUG)
114280   {/* zName:     */ "vdbe_addoptrace",
114281    /* ePragTyp:  */ PragTyp_FLAG,
114282    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
114283    /* ColNames:  */ 0, 0,
114284    /* iArg:      */ SQLITE_VdbeAddopTrace },
114285   {/* zName:     */ "vdbe_debug",
114286    /* ePragTyp:  */ PragTyp_FLAG,
114287    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
114288    /* ColNames:  */ 0, 0,
114289    /* iArg:      */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
114290   {/* zName:     */ "vdbe_eqp",
114291    /* ePragTyp:  */ PragTyp_FLAG,
114292    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
114293    /* ColNames:  */ 0, 0,
114294    /* iArg:      */ SQLITE_VdbeEQP },
114295   {/* zName:     */ "vdbe_listing",
114296    /* ePragTyp:  */ PragTyp_FLAG,
114297    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
114298    /* ColNames:  */ 0, 0,
114299    /* iArg:      */ SQLITE_VdbeListing },
114300   {/* zName:     */ "vdbe_trace",
114301    /* ePragTyp:  */ PragTyp_FLAG,
114302    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
114303    /* ColNames:  */ 0, 0,
114304    /* iArg:      */ SQLITE_VdbeTrace },
114305  #endif
114306  #endif
114307  #if !defined(SQLITE_OMIT_WAL)
114308   {/* zName:     */ "wal_autocheckpoint",
114309    /* ePragTyp:  */ PragTyp_WAL_AUTOCHECKPOINT,
114310    /* ePragFlg:  */ 0,
114311    /* ColNames:  */ 0, 0,
114312    /* iArg:      */ 0 },
114313   {/* zName:     */ "wal_checkpoint",
114314    /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
114315    /* ePragFlg:  */ PragFlg_NeedSchema,
114316    /* ColNames:  */ 46, 3,
114317    /* iArg:      */ 0 },
114318  #endif
114319  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
114320   {/* zName:     */ "writable_schema",
114321    /* ePragTyp:  */ PragTyp_FLAG,
114322    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
114323    /* ColNames:  */ 0, 0,
114324    /* iArg:      */ SQLITE_WriteSchema },
114325  #endif
114326  };
114327  /* Number of pragmas: 60 on by default, 77 total. */
114328  
114329  /************** End of pragma.h **********************************************/
114330  /************** Continuing where we left off in pragma.c *********************/
114331  
114332  /*
114333  ** Interpret the given string as a safety level.  Return 0 for OFF,
114334  ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA.  Return 1 for an empty or 
114335  ** unrecognized string argument.  The FULL and EXTRA option is disallowed
114336  ** if the omitFull parameter it 1.
114337  **
114338  ** Note that the values returned are one less that the values that
114339  ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
114340  ** to support legacy SQL code.  The safety level used to be boolean
114341  ** and older scripts may have used numbers 0 for OFF and 1 for ON.
114342  */
114343  static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
114344                               /* 123456789 123456789 123 */
114345    static const char zText[] = "onoffalseyestruextrafull";
114346    static const u8 iOffset[] = {0, 1, 2,  4,    9,  12,  15,   20};
114347    static const u8 iLength[] = {2, 2, 3,  5,    3,   4,   5,    4};
114348    static const u8 iValue[] =  {1, 0, 0,  0,    1,   1,   3,    2};
114349                              /* on no off false yes true extra full */
114350    int i, n;
114351    if( sqlite3Isdigit(*z) ){
114352      return (u8)sqlite3Atoi(z);
114353    }
114354    n = sqlite3Strlen30(z);
114355    for(i=0; i<ArraySize(iLength); i++){
114356      if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
114357       && (!omitFull || iValue[i]<=1)
114358      ){
114359        return iValue[i];
114360      }
114361    }
114362    return dflt;
114363  }
114364  
114365  /*
114366  ** Interpret the given string as a boolean value.
114367  */
114368  SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
114369    return getSafetyLevel(z,1,dflt)!=0;
114370  }
114371  
114372  /* The sqlite3GetBoolean() function is used by other modules but the
114373  ** remainder of this file is specific to PRAGMA processing.  So omit
114374  ** the rest of the file if PRAGMAs are omitted from the build.
114375  */
114376  #if !defined(SQLITE_OMIT_PRAGMA)
114377  
114378  /*
114379  ** Interpret the given string as a locking mode value.
114380  */
114381  static int getLockingMode(const char *z){
114382    if( z ){
114383      if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
114384      if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
114385    }
114386    return PAGER_LOCKINGMODE_QUERY;
114387  }
114388  
114389  #ifndef SQLITE_OMIT_AUTOVACUUM
114390  /*
114391  ** Interpret the given string as an auto-vacuum mode value.
114392  **
114393  ** The following strings, "none", "full" and "incremental" are 
114394  ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
114395  */
114396  static int getAutoVacuum(const char *z){
114397    int i;
114398    if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
114399    if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
114400    if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
114401    i = sqlite3Atoi(z);
114402    return (u8)((i>=0&&i<=2)?i:0);
114403  }
114404  #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
114405  
114406  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
114407  /*
114408  ** Interpret the given string as a temp db location. Return 1 for file
114409  ** backed temporary databases, 2 for the Red-Black tree in memory database
114410  ** and 0 to use the compile-time default.
114411  */
114412  static int getTempStore(const char *z){
114413    if( z[0]>='0' && z[0]<='2' ){
114414      return z[0] - '0';
114415    }else if( sqlite3StrICmp(z, "file")==0 ){
114416      return 1;
114417    }else if( sqlite3StrICmp(z, "memory")==0 ){
114418      return 2;
114419    }else{
114420      return 0;
114421    }
114422  }
114423  #endif /* SQLITE_PAGER_PRAGMAS */
114424  
114425  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
114426  /*
114427  ** Invalidate temp storage, either when the temp storage is changed
114428  ** from default, or when 'file' and the temp_store_directory has changed
114429  */
114430  static int invalidateTempStorage(Parse *pParse){
114431    sqlite3 *db = pParse->db;
114432    if( db->aDb[1].pBt!=0 ){
114433      if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
114434        sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
114435          "from within a transaction");
114436        return SQLITE_ERROR;
114437      }
114438      sqlite3BtreeClose(db->aDb[1].pBt);
114439      db->aDb[1].pBt = 0;
114440      sqlite3ResetAllSchemasOfConnection(db);
114441    }
114442    return SQLITE_OK;
114443  }
114444  #endif /* SQLITE_PAGER_PRAGMAS */
114445  
114446  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
114447  /*
114448  ** If the TEMP database is open, close it and mark the database schema
114449  ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
114450  ** or DEFAULT_TEMP_STORE pragmas.
114451  */
114452  static int changeTempStorage(Parse *pParse, const char *zStorageType){
114453    int ts = getTempStore(zStorageType);
114454    sqlite3 *db = pParse->db;
114455    if( db->temp_store==ts ) return SQLITE_OK;
114456    if( invalidateTempStorage( pParse ) != SQLITE_OK ){
114457      return SQLITE_ERROR;
114458    }
114459    db->temp_store = (u8)ts;
114460    return SQLITE_OK;
114461  }
114462  #endif /* SQLITE_PAGER_PRAGMAS */
114463  
114464  /*
114465  ** Set result column names for a pragma.
114466  */
114467  static void setPragmaResultColumnNames(
114468    Vdbe *v,                     /* The query under construction */
114469    const PragmaName *pPragma    /* The pragma */
114470  ){
114471    u8 n = pPragma->nPragCName;
114472    sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);
114473    if( n==0 ){
114474      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
114475    }else{
114476      int i, j;
114477      for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
114478        sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);
114479      }
114480    }
114481  }
114482  
114483  /*
114484  ** Generate code to return a single integer value.
114485  */
114486  static void returnSingleInt(Vdbe *v, i64 value){
114487    sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
114488    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
114489  }
114490  
114491  /*
114492  ** Generate code to return a single text value.
114493  */
114494  static void returnSingleText(
114495    Vdbe *v,                /* Prepared statement under construction */
114496    const char *zValue      /* Value to be returned */
114497  ){
114498    if( zValue ){
114499      sqlite3VdbeLoadString(v, 1, (const char*)zValue);
114500      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
114501    }
114502  }
114503  
114504  
114505  /*
114506  ** Set the safety_level and pager flags for pager iDb.  Or if iDb<0
114507  ** set these values for all pagers.
114508  */
114509  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
114510  static void setAllPagerFlags(sqlite3 *db){
114511    if( db->autoCommit ){
114512      Db *pDb = db->aDb;
114513      int n = db->nDb;
114514      assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
114515      assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
114516      assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
114517      assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
114518               ==  PAGER_FLAGS_MASK );
114519      assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
114520      while( (n--) > 0 ){
114521        if( pDb->pBt ){
114522          sqlite3BtreeSetPagerFlags(pDb->pBt,
114523                   pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
114524        }
114525        pDb++;
114526      }
114527    }
114528  }
114529  #else
114530  # define setAllPagerFlags(X)  /* no-op */
114531  #endif
114532  
114533  
114534  /*
114535  ** Return a human-readable name for a constraint resolution action.
114536  */
114537  #ifndef SQLITE_OMIT_FOREIGN_KEY
114538  static const char *actionName(u8 action){
114539    const char *zName;
114540    switch( action ){
114541      case OE_SetNull:  zName = "SET NULL";        break;
114542      case OE_SetDflt:  zName = "SET DEFAULT";     break;
114543      case OE_Cascade:  zName = "CASCADE";         break;
114544      case OE_Restrict: zName = "RESTRICT";        break;
114545      default:          zName = "NO ACTION";  
114546                        assert( action==OE_None ); break;
114547    }
114548    return zName;
114549  }
114550  #endif
114551  
114552  
114553  /*
114554  ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
114555  ** defined in pager.h. This function returns the associated lowercase
114556  ** journal-mode name.
114557  */
114558  SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
114559    static char * const azModeName[] = {
114560      "delete", "persist", "off", "truncate", "memory"
114561  #ifndef SQLITE_OMIT_WAL
114562       , "wal"
114563  #endif
114564    };
114565    assert( PAGER_JOURNALMODE_DELETE==0 );
114566    assert( PAGER_JOURNALMODE_PERSIST==1 );
114567    assert( PAGER_JOURNALMODE_OFF==2 );
114568    assert( PAGER_JOURNALMODE_TRUNCATE==3 );
114569    assert( PAGER_JOURNALMODE_MEMORY==4 );
114570    assert( PAGER_JOURNALMODE_WAL==5 );
114571    assert( eMode>=0 && eMode<=ArraySize(azModeName) );
114572  
114573    if( eMode==ArraySize(azModeName) ) return 0;
114574    return azModeName[eMode];
114575  }
114576  
114577  /*
114578  ** Locate a pragma in the aPragmaName[] array.
114579  */
114580  static const PragmaName *pragmaLocate(const char *zName){
114581    int upr, lwr, mid = 0, rc;
114582    lwr = 0;
114583    upr = ArraySize(aPragmaName)-1;
114584    while( lwr<=upr ){
114585      mid = (lwr+upr)/2;
114586      rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);
114587      if( rc==0 ) break;
114588      if( rc<0 ){
114589        upr = mid - 1;
114590      }else{
114591        lwr = mid + 1;
114592      }
114593    }
114594    return lwr>upr ? 0 : &aPragmaName[mid];
114595  }
114596  
114597  /*
114598  ** Helper subroutine for PRAGMA integrity_check:
114599  **
114600  ** Generate code to output a single-column result row with a value of the
114601  ** string held in register 3.  Decrement the result count in register 1
114602  ** and halt if the maximum number of result rows have been issued.
114603  */
114604  static int integrityCheckResultRow(Vdbe *v){
114605    int addr;
114606    sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
114607    addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
114608    VdbeCoverage(v);
114609    sqlite3VdbeAddOp0(v, OP_Halt);
114610    return addr;
114611  }
114612  
114613  /*
114614  ** Process a pragma statement.  
114615  **
114616  ** Pragmas are of this form:
114617  **
114618  **      PRAGMA [schema.]id [= value]
114619  **
114620  ** The identifier might also be a string.  The value is a string, and
114621  ** identifier, or a number.  If minusFlag is true, then the value is
114622  ** a number that was preceded by a minus sign.
114623  **
114624  ** If the left side is "database.id" then pId1 is the database name
114625  ** and pId2 is the id.  If the left side is just "id" then pId1 is the
114626  ** id and pId2 is any empty string.
114627  */
114628  SQLITE_PRIVATE void sqlite3Pragma(
114629    Parse *pParse, 
114630    Token *pId1,        /* First part of [schema.]id field */
114631    Token *pId2,        /* Second part of [schema.]id field, or NULL */
114632    Token *pValue,      /* Token for <value>, or NULL */
114633    int minusFlag       /* True if a '-' sign preceded <value> */
114634  ){
114635    char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
114636    char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
114637    const char *zDb = 0;   /* The database name */
114638    Token *pId;            /* Pointer to <id> token */
114639    char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
114640    int iDb;               /* Database index for <database> */
114641    int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
114642    sqlite3 *db = pParse->db;    /* The database connection */
114643    Db *pDb;                     /* The specific database being pragmaed */
114644    Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
114645    const PragmaName *pPragma;   /* The pragma */
114646  
114647    if( v==0 ) return;
114648    sqlite3VdbeRunOnlyOnce(v);
114649    pParse->nMem = 2;
114650  
114651    /* Interpret the [schema.] part of the pragma statement. iDb is the
114652    ** index of the database this pragma is being applied to in db.aDb[]. */
114653    iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
114654    if( iDb<0 ) return;
114655    pDb = &db->aDb[iDb];
114656  
114657    /* If the temp database has been explicitly named as part of the 
114658    ** pragma, make sure it is open. 
114659    */
114660    if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
114661      return;
114662    }
114663  
114664    zLeft = sqlite3NameFromToken(db, pId);
114665    if( !zLeft ) return;
114666    if( minusFlag ){
114667      zRight = sqlite3MPrintf(db, "-%T", pValue);
114668    }else{
114669      zRight = sqlite3NameFromToken(db, pValue);
114670    }
114671  
114672    assert( pId2 );
114673    zDb = pId2->n>0 ? pDb->zDbSName : 0;
114674    if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
114675      goto pragma_out;
114676    }
114677  
114678    /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
114679    ** connection.  If it returns SQLITE_OK, then assume that the VFS
114680    ** handled the pragma and generate a no-op prepared statement.
114681    **
114682    ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
114683    ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
114684    ** object corresponding to the database file to which the pragma
114685    ** statement refers.
114686    **
114687    ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
114688    ** file control is an array of pointers to strings (char**) in which the
114689    ** second element of the array is the name of the pragma and the third
114690    ** element is the argument to the pragma or NULL if the pragma has no
114691    ** argument.
114692    */
114693    aFcntl[0] = 0;
114694    aFcntl[1] = zLeft;
114695    aFcntl[2] = zRight;
114696    aFcntl[3] = 0;
114697    db->busyHandler.nBusy = 0;
114698    rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
114699    if( rc==SQLITE_OK ){
114700      sqlite3VdbeSetNumCols(v, 1);
114701      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
114702      returnSingleText(v, aFcntl[0]);
114703      sqlite3_free(aFcntl[0]);
114704      goto pragma_out;
114705    }
114706    if( rc!=SQLITE_NOTFOUND ){
114707      if( aFcntl[0] ){
114708        sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
114709        sqlite3_free(aFcntl[0]);
114710      }
114711      pParse->nErr++;
114712      pParse->rc = rc;
114713      goto pragma_out;
114714    }
114715  
114716    /* Locate the pragma in the lookup table */
114717    pPragma = pragmaLocate(zLeft);
114718    if( pPragma==0 ) goto pragma_out;
114719  
114720    /* Make sure the database schema is loaded if the pragma requires that */
114721    if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
114722      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
114723    }
114724  
114725    /* Register the result column names for pragmas that return results */
114726    if( (pPragma->mPragFlg & PragFlg_NoColumns)==0 
114727     && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
114728    ){
114729      setPragmaResultColumnNames(v, pPragma);
114730    }
114731  
114732    /* Jump to the appropriate pragma handler */
114733    switch( pPragma->ePragTyp ){
114734    
114735  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
114736    /*
114737    **  PRAGMA [schema.]default_cache_size
114738    **  PRAGMA [schema.]default_cache_size=N
114739    **
114740    ** The first form reports the current persistent setting for the
114741    ** page cache size.  The value returned is the maximum number of
114742    ** pages in the page cache.  The second form sets both the current
114743    ** page cache size value and the persistent page cache size value
114744    ** stored in the database file.
114745    **
114746    ** Older versions of SQLite would set the default cache size to a
114747    ** negative number to indicate synchronous=OFF.  These days, synchronous
114748    ** is always on by default regardless of the sign of the default cache
114749    ** size.  But continue to take the absolute value of the default cache
114750    ** size of historical compatibility.
114751    */
114752    case PragTyp_DEFAULT_CACHE_SIZE: {
114753      static const int iLn = VDBE_OFFSET_LINENO(2);
114754      static const VdbeOpList getCacheSize[] = {
114755        { OP_Transaction, 0, 0,        0},                         /* 0 */
114756        { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
114757        { OP_IfPos,       1, 8,        0},
114758        { OP_Integer,     0, 2,        0},
114759        { OP_Subtract,    1, 2,        1},
114760        { OP_IfPos,       1, 8,        0},
114761        { OP_Integer,     0, 1,        0},                         /* 6 */
114762        { OP_Noop,        0, 0,        0},
114763        { OP_ResultRow,   1, 1,        0},
114764      };
114765      VdbeOp *aOp;
114766      sqlite3VdbeUsesBtree(v, iDb);
114767      if( !zRight ){
114768        pParse->nMem += 2;
114769        sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
114770        aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
114771        if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
114772        aOp[0].p1 = iDb;
114773        aOp[1].p1 = iDb;
114774        aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
114775      }else{
114776        int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
114777        sqlite3BeginWriteOperation(pParse, 0, iDb);
114778        sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
114779        assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
114780        pDb->pSchema->cache_size = size;
114781        sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
114782      }
114783      break;
114784    }
114785  #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
114786  
114787  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
114788    /*
114789    **  PRAGMA [schema.]page_size
114790    **  PRAGMA [schema.]page_size=N
114791    **
114792    ** The first form reports the current setting for the
114793    ** database page size in bytes.  The second form sets the
114794    ** database page size value.  The value can only be set if
114795    ** the database has not yet been created.
114796    */
114797    case PragTyp_PAGE_SIZE: {
114798      Btree *pBt = pDb->pBt;
114799      assert( pBt!=0 );
114800      if( !zRight ){
114801        int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
114802        returnSingleInt(v, size);
114803      }else{
114804        /* Malloc may fail when setting the page-size, as there is an internal
114805        ** buffer that the pager module resizes using sqlite3_realloc().
114806        */
114807        db->nextPagesize = sqlite3Atoi(zRight);
114808        if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
114809          sqlite3OomFault(db);
114810        }
114811      }
114812      break;
114813    }
114814  
114815    /*
114816    **  PRAGMA [schema.]secure_delete
114817    **  PRAGMA [schema.]secure_delete=ON/OFF/FAST
114818    **
114819    ** The first form reports the current setting for the
114820    ** secure_delete flag.  The second form changes the secure_delete
114821    ** flag setting and reports the new value.
114822    */
114823    case PragTyp_SECURE_DELETE: {
114824      Btree *pBt = pDb->pBt;
114825      int b = -1;
114826      assert( pBt!=0 );
114827      if( zRight ){
114828        if( sqlite3_stricmp(zRight, "fast")==0 ){
114829          b = 2;
114830        }else{
114831          b = sqlite3GetBoolean(zRight, 0);
114832        }
114833      }
114834      if( pId2->n==0 && b>=0 ){
114835        int ii;
114836        for(ii=0; ii<db->nDb; ii++){
114837          sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
114838        }
114839      }
114840      b = sqlite3BtreeSecureDelete(pBt, b);
114841      returnSingleInt(v, b);
114842      break;
114843    }
114844  
114845    /*
114846    **  PRAGMA [schema.]max_page_count
114847    **  PRAGMA [schema.]max_page_count=N
114848    **
114849    ** The first form reports the current setting for the
114850    ** maximum number of pages in the database file.  The 
114851    ** second form attempts to change this setting.  Both
114852    ** forms return the current setting.
114853    **
114854    ** The absolute value of N is used.  This is undocumented and might
114855    ** change.  The only purpose is to provide an easy way to test
114856    ** the sqlite3AbsInt32() function.
114857    **
114858    **  PRAGMA [schema.]page_count
114859    **
114860    ** Return the number of pages in the specified database.
114861    */
114862    case PragTyp_PAGE_COUNT: {
114863      int iReg;
114864      sqlite3CodeVerifySchema(pParse, iDb);
114865      iReg = ++pParse->nMem;
114866      if( sqlite3Tolower(zLeft[0])=='p' ){
114867        sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
114868      }else{
114869        sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, 
114870                          sqlite3AbsInt32(sqlite3Atoi(zRight)));
114871      }
114872      sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
114873      break;
114874    }
114875  
114876    /*
114877    **  PRAGMA [schema.]locking_mode
114878    **  PRAGMA [schema.]locking_mode = (normal|exclusive)
114879    */
114880    case PragTyp_LOCKING_MODE: {
114881      const char *zRet = "normal";
114882      int eMode = getLockingMode(zRight);
114883  
114884      if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
114885        /* Simple "PRAGMA locking_mode;" statement. This is a query for
114886        ** the current default locking mode (which may be different to
114887        ** the locking-mode of the main database).
114888        */
114889        eMode = db->dfltLockMode;
114890      }else{
114891        Pager *pPager;
114892        if( pId2->n==0 ){
114893          /* This indicates that no database name was specified as part
114894          ** of the PRAGMA command. In this case the locking-mode must be
114895          ** set on all attached databases, as well as the main db file.
114896          **
114897          ** Also, the sqlite3.dfltLockMode variable is set so that
114898          ** any subsequently attached databases also use the specified
114899          ** locking mode.
114900          */
114901          int ii;
114902          assert(pDb==&db->aDb[0]);
114903          for(ii=2; ii<db->nDb; ii++){
114904            pPager = sqlite3BtreePager(db->aDb[ii].pBt);
114905            sqlite3PagerLockingMode(pPager, eMode);
114906          }
114907          db->dfltLockMode = (u8)eMode;
114908        }
114909        pPager = sqlite3BtreePager(pDb->pBt);
114910        eMode = sqlite3PagerLockingMode(pPager, eMode);
114911      }
114912  
114913      assert( eMode==PAGER_LOCKINGMODE_NORMAL
114914              || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
114915      if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
114916        zRet = "exclusive";
114917      }
114918      returnSingleText(v, zRet);
114919      break;
114920    }
114921  
114922    /*
114923    **  PRAGMA [schema.]journal_mode
114924    **  PRAGMA [schema.]journal_mode =
114925    **                      (delete|persist|off|truncate|memory|wal|off)
114926    */
114927    case PragTyp_JOURNAL_MODE: {
114928      int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
114929      int ii;           /* Loop counter */
114930  
114931      if( zRight==0 ){
114932        /* If there is no "=MODE" part of the pragma, do a query for the
114933        ** current mode */
114934        eMode = PAGER_JOURNALMODE_QUERY;
114935      }else{
114936        const char *zMode;
114937        int n = sqlite3Strlen30(zRight);
114938        for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
114939          if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
114940        }
114941        if( !zMode ){
114942          /* If the "=MODE" part does not match any known journal mode,
114943          ** then do a query */
114944          eMode = PAGER_JOURNALMODE_QUERY;
114945        }
114946      }
114947      if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
114948        /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
114949        iDb = 0;
114950        pId2->n = 1;
114951      }
114952      for(ii=db->nDb-1; ii>=0; ii--){
114953        if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
114954          sqlite3VdbeUsesBtree(v, ii);
114955          sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
114956        }
114957      }
114958      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
114959      break;
114960    }
114961  
114962    /*
114963    **  PRAGMA [schema.]journal_size_limit
114964    **  PRAGMA [schema.]journal_size_limit=N
114965    **
114966    ** Get or set the size limit on rollback journal files.
114967    */
114968    case PragTyp_JOURNAL_SIZE_LIMIT: {
114969      Pager *pPager = sqlite3BtreePager(pDb->pBt);
114970      i64 iLimit = -2;
114971      if( zRight ){
114972        sqlite3DecOrHexToI64(zRight, &iLimit);
114973        if( iLimit<-1 ) iLimit = -1;
114974      }
114975      iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
114976      returnSingleInt(v, iLimit);
114977      break;
114978    }
114979  
114980  #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
114981  
114982    /*
114983    **  PRAGMA [schema.]auto_vacuum
114984    **  PRAGMA [schema.]auto_vacuum=N
114985    **
114986    ** Get or set the value of the database 'auto-vacuum' parameter.
114987    ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
114988    */
114989  #ifndef SQLITE_OMIT_AUTOVACUUM
114990    case PragTyp_AUTO_VACUUM: {
114991      Btree *pBt = pDb->pBt;
114992      assert( pBt!=0 );
114993      if( !zRight ){
114994        returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
114995      }else{
114996        int eAuto = getAutoVacuum(zRight);
114997        assert( eAuto>=0 && eAuto<=2 );
114998        db->nextAutovac = (u8)eAuto;
114999        /* Call SetAutoVacuum() to set initialize the internal auto and
115000        ** incr-vacuum flags. This is required in case this connection
115001        ** creates the database file. It is important that it is created
115002        ** as an auto-vacuum capable db.
115003        */
115004        rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
115005        if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
115006          /* When setting the auto_vacuum mode to either "full" or 
115007          ** "incremental", write the value of meta[6] in the database
115008          ** file. Before writing to meta[6], check that meta[3] indicates
115009          ** that this really is an auto-vacuum capable database.
115010          */
115011          static const int iLn = VDBE_OFFSET_LINENO(2);
115012          static const VdbeOpList setMeta6[] = {
115013            { OP_Transaction,    0,         1,                 0},    /* 0 */
115014            { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
115015            { OP_If,             1,         0,                 0},    /* 2 */
115016            { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
115017            { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 0},    /* 4 */
115018          };
115019          VdbeOp *aOp;
115020          int iAddr = sqlite3VdbeCurrentAddr(v);
115021          sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
115022          aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
115023          if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
115024          aOp[0].p1 = iDb;
115025          aOp[1].p1 = iDb;
115026          aOp[2].p2 = iAddr+4;
115027          aOp[4].p1 = iDb;
115028          aOp[4].p3 = eAuto - 1;
115029          sqlite3VdbeUsesBtree(v, iDb);
115030        }
115031      }
115032      break;
115033    }
115034  #endif
115035  
115036    /*
115037    **  PRAGMA [schema.]incremental_vacuum(N)
115038    **
115039    ** Do N steps of incremental vacuuming on a database.
115040    */
115041  #ifndef SQLITE_OMIT_AUTOVACUUM
115042    case PragTyp_INCREMENTAL_VACUUM: {
115043      int iLimit, addr;
115044      if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
115045        iLimit = 0x7fffffff;
115046      }
115047      sqlite3BeginWriteOperation(pParse, 0, iDb);
115048      sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
115049      addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
115050      sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
115051      sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
115052      sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
115053      sqlite3VdbeJumpHere(v, addr);
115054      break;
115055    }
115056  #endif
115057  
115058  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
115059    /*
115060    **  PRAGMA [schema.]cache_size
115061    **  PRAGMA [schema.]cache_size=N
115062    **
115063    ** The first form reports the current local setting for the
115064    ** page cache size. The second form sets the local
115065    ** page cache size value.  If N is positive then that is the
115066    ** number of pages in the cache.  If N is negative, then the
115067    ** number of pages is adjusted so that the cache uses -N kibibytes
115068    ** of memory.
115069    */
115070    case PragTyp_CACHE_SIZE: {
115071      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
115072      if( !zRight ){
115073        returnSingleInt(v, pDb->pSchema->cache_size);
115074      }else{
115075        int size = sqlite3Atoi(zRight);
115076        pDb->pSchema->cache_size = size;
115077        sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
115078      }
115079      break;
115080    }
115081  
115082    /*
115083    **  PRAGMA [schema.]cache_spill
115084    **  PRAGMA cache_spill=BOOLEAN
115085    **  PRAGMA [schema.]cache_spill=N
115086    **
115087    ** The first form reports the current local setting for the
115088    ** page cache spill size. The second form turns cache spill on
115089    ** or off.  When turnning cache spill on, the size is set to the
115090    ** current cache_size.  The third form sets a spill size that
115091    ** may be different form the cache size.
115092    ** If N is positive then that is the
115093    ** number of pages in the cache.  If N is negative, then the
115094    ** number of pages is adjusted so that the cache uses -N kibibytes
115095    ** of memory.
115096    **
115097    ** If the number of cache_spill pages is less then the number of
115098    ** cache_size pages, no spilling occurs until the page count exceeds
115099    ** the number of cache_size pages.
115100    **
115101    ** The cache_spill=BOOLEAN setting applies to all attached schemas,
115102    ** not just the schema specified.
115103    */
115104    case PragTyp_CACHE_SPILL: {
115105      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
115106      if( !zRight ){
115107        returnSingleInt(v,
115108           (db->flags & SQLITE_CacheSpill)==0 ? 0 : 
115109              sqlite3BtreeSetSpillSize(pDb->pBt,0));
115110      }else{
115111        int size = 1;
115112        if( sqlite3GetInt32(zRight, &size) ){
115113          sqlite3BtreeSetSpillSize(pDb->pBt, size);
115114        }
115115        if( sqlite3GetBoolean(zRight, size!=0) ){
115116          db->flags |= SQLITE_CacheSpill;
115117        }else{
115118          db->flags &= ~SQLITE_CacheSpill;
115119        }
115120        setAllPagerFlags(db);
115121      }
115122      break;
115123    }
115124  
115125    /*
115126    **  PRAGMA [schema.]mmap_size(N)
115127    **
115128    ** Used to set mapping size limit. The mapping size limit is
115129    ** used to limit the aggregate size of all memory mapped regions of the
115130    ** database file. If this parameter is set to zero, then memory mapping
115131    ** is not used at all.  If N is negative, then the default memory map
115132    ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
115133    ** The parameter N is measured in bytes.
115134    **
115135    ** This value is advisory.  The underlying VFS is free to memory map
115136    ** as little or as much as it wants.  Except, if N is set to 0 then the
115137    ** upper layers will never invoke the xFetch interfaces to the VFS.
115138    */
115139    case PragTyp_MMAP_SIZE: {
115140      sqlite3_int64 sz;
115141  #if SQLITE_MAX_MMAP_SIZE>0
115142      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
115143      if( zRight ){
115144        int ii;
115145        sqlite3DecOrHexToI64(zRight, &sz);
115146        if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
115147        if( pId2->n==0 ) db->szMmap = sz;
115148        for(ii=db->nDb-1; ii>=0; ii--){
115149          if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
115150            sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
115151          }
115152        }
115153      }
115154      sz = -1;
115155      rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
115156  #else
115157      sz = 0;
115158      rc = SQLITE_OK;
115159  #endif
115160      if( rc==SQLITE_OK ){
115161        returnSingleInt(v, sz);
115162      }else if( rc!=SQLITE_NOTFOUND ){
115163        pParse->nErr++;
115164        pParse->rc = rc;
115165      }
115166      break;
115167    }
115168  
115169    /*
115170    **   PRAGMA temp_store
115171    **   PRAGMA temp_store = "default"|"memory"|"file"
115172    **
115173    ** Return or set the local value of the temp_store flag.  Changing
115174    ** the local value does not make changes to the disk file and the default
115175    ** value will be restored the next time the database is opened.
115176    **
115177    ** Note that it is possible for the library compile-time options to
115178    ** override this setting
115179    */
115180    case PragTyp_TEMP_STORE: {
115181      if( !zRight ){
115182        returnSingleInt(v, db->temp_store);
115183      }else{
115184        changeTempStorage(pParse, zRight);
115185      }
115186      break;
115187    }
115188  
115189    /*
115190    **   PRAGMA temp_store_directory
115191    **   PRAGMA temp_store_directory = ""|"directory_name"
115192    **
115193    ** Return or set the local value of the temp_store_directory flag.  Changing
115194    ** the value sets a specific directory to be used for temporary files.
115195    ** Setting to a null string reverts to the default temporary directory search.
115196    ** If temporary directory is changed, then invalidateTempStorage.
115197    **
115198    */
115199    case PragTyp_TEMP_STORE_DIRECTORY: {
115200      if( !zRight ){
115201        returnSingleText(v, sqlite3_temp_directory);
115202      }else{
115203  #ifndef SQLITE_OMIT_WSD
115204        if( zRight[0] ){
115205          int res;
115206          rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
115207          if( rc!=SQLITE_OK || res==0 ){
115208            sqlite3ErrorMsg(pParse, "not a writable directory");
115209            goto pragma_out;
115210          }
115211        }
115212        if( SQLITE_TEMP_STORE==0
115213         || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
115214         || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
115215        ){
115216          invalidateTempStorage(pParse);
115217        }
115218        sqlite3_free(sqlite3_temp_directory);
115219        if( zRight[0] ){
115220          sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
115221        }else{
115222          sqlite3_temp_directory = 0;
115223        }
115224  #endif /* SQLITE_OMIT_WSD */
115225      }
115226      break;
115227    }
115228  
115229  #if SQLITE_OS_WIN
115230    /*
115231    **   PRAGMA data_store_directory
115232    **   PRAGMA data_store_directory = ""|"directory_name"
115233    **
115234    ** Return or set the local value of the data_store_directory flag.  Changing
115235    ** the value sets a specific directory to be used for database files that
115236    ** were specified with a relative pathname.  Setting to a null string reverts
115237    ** to the default database directory, which for database files specified with
115238    ** a relative path will probably be based on the current directory for the
115239    ** process.  Database file specified with an absolute path are not impacted
115240    ** by this setting, regardless of its value.
115241    **
115242    */
115243    case PragTyp_DATA_STORE_DIRECTORY: {
115244      if( !zRight ){
115245        returnSingleText(v, sqlite3_data_directory);
115246      }else{
115247  #ifndef SQLITE_OMIT_WSD
115248        if( zRight[0] ){
115249          int res;
115250          rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
115251          if( rc!=SQLITE_OK || res==0 ){
115252            sqlite3ErrorMsg(pParse, "not a writable directory");
115253            goto pragma_out;
115254          }
115255        }
115256        sqlite3_free(sqlite3_data_directory);
115257        if( zRight[0] ){
115258          sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
115259        }else{
115260          sqlite3_data_directory = 0;
115261        }
115262  #endif /* SQLITE_OMIT_WSD */
115263      }
115264      break;
115265    }
115266  #endif
115267  
115268  #if SQLITE_ENABLE_LOCKING_STYLE
115269    /*
115270    **   PRAGMA [schema.]lock_proxy_file
115271    **   PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
115272    **
115273    ** Return or set the value of the lock_proxy_file flag.  Changing
115274    ** the value sets a specific file to be used for database access locks.
115275    **
115276    */
115277    case PragTyp_LOCK_PROXY_FILE: {
115278      if( !zRight ){
115279        Pager *pPager = sqlite3BtreePager(pDb->pBt);
115280        char *proxy_file_path = NULL;
115281        sqlite3_file *pFile = sqlite3PagerFile(pPager);
115282        sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, 
115283                             &proxy_file_path);
115284        returnSingleText(v, proxy_file_path);
115285      }else{
115286        Pager *pPager = sqlite3BtreePager(pDb->pBt);
115287        sqlite3_file *pFile = sqlite3PagerFile(pPager);
115288        int res;
115289        if( zRight[0] ){
115290          res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
115291                                       zRight);
115292        } else {
115293          res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
115294                                       NULL);
115295        }
115296        if( res!=SQLITE_OK ){
115297          sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
115298          goto pragma_out;
115299        }
115300      }
115301      break;
115302    }
115303  #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
115304      
115305    /*
115306    **   PRAGMA [schema.]synchronous
115307    **   PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
115308    **
115309    ** Return or set the local value of the synchronous flag.  Changing
115310    ** the local value does not make changes to the disk file and the
115311    ** default value will be restored the next time the database is
115312    ** opened.
115313    */
115314    case PragTyp_SYNCHRONOUS: {
115315      if( !zRight ){
115316        returnSingleInt(v, pDb->safety_level-1);
115317      }else{
115318        if( !db->autoCommit ){
115319          sqlite3ErrorMsg(pParse, 
115320              "Safety level may not be changed inside a transaction");
115321        }else if( iDb!=1 ){
115322          int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
115323          if( iLevel==0 ) iLevel = 1;
115324          pDb->safety_level = iLevel;
115325          pDb->bSyncSet = 1;
115326          setAllPagerFlags(db);
115327        }
115328      }
115329      break;
115330    }
115331  #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
115332  
115333  #ifndef SQLITE_OMIT_FLAG_PRAGMAS
115334    case PragTyp_FLAG: {
115335      if( zRight==0 ){
115336        setPragmaResultColumnNames(v, pPragma);
115337        returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
115338      }else{
115339        int mask = pPragma->iArg;    /* Mask of bits to set or clear. */
115340        if( db->autoCommit==0 ){
115341          /* Foreign key support may not be enabled or disabled while not
115342          ** in auto-commit mode.  */
115343          mask &= ~(SQLITE_ForeignKeys);
115344        }
115345  #if SQLITE_USER_AUTHENTICATION
115346        if( db->auth.authLevel==UAUTH_User ){
115347          /* Do not allow non-admin users to modify the schema arbitrarily */
115348          mask &= ~(SQLITE_WriteSchema);
115349        }
115350  #endif
115351  
115352        if( sqlite3GetBoolean(zRight, 0) ){
115353          db->flags |= mask;
115354        }else{
115355          db->flags &= ~mask;
115356          if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
115357        }
115358  
115359        /* Many of the flag-pragmas modify the code generated by the SQL 
115360        ** compiler (eg. count_changes). So add an opcode to expire all
115361        ** compiled SQL statements after modifying a pragma value.
115362        */
115363        sqlite3VdbeAddOp0(v, OP_Expire);
115364        setAllPagerFlags(db);
115365      }
115366      break;
115367    }
115368  #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
115369  
115370  #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
115371    /*
115372    **   PRAGMA table_info(<table>)
115373    **
115374    ** Return a single row for each column of the named table. The columns of
115375    ** the returned data set are:
115376    **
115377    ** cid:        Column id (numbered from left to right, starting at 0)
115378    ** name:       Column name
115379    ** type:       Column declaration type.
115380    ** notnull:    True if 'NOT NULL' is part of column declaration
115381    ** dflt_value: The default value for the column, if any.
115382    */
115383    case PragTyp_TABLE_INFO: if( zRight ){
115384      Table *pTab;
115385      pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
115386      if( pTab ){
115387        int i, k;
115388        int nHidden = 0;
115389        Column *pCol;
115390        Index *pPk = sqlite3PrimaryKeyIndex(pTab);
115391        pParse->nMem = 6;
115392        sqlite3CodeVerifySchema(pParse, iDb);
115393        sqlite3ViewGetColumnNames(pParse, pTab);
115394        for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
115395          if( IsHiddenColumn(pCol) ){
115396            nHidden++;
115397            continue;
115398          }
115399          if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
115400            k = 0;
115401          }else if( pPk==0 ){
115402            k = 1;
115403          }else{
115404            for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
115405          }
115406          assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
115407          sqlite3VdbeMultiLoad(v, 1, "issisi",
115408                 i-nHidden,
115409                 pCol->zName,
115410                 sqlite3ColumnType(pCol,""),
115411                 pCol->notNull ? 1 : 0,
115412                 pCol->pDflt ? pCol->pDflt->u.zToken : 0,
115413                 k);
115414        }
115415      }
115416    }
115417    break;
115418  
115419  #ifdef SQLITE_DEBUG
115420    case PragTyp_STATS: {
115421      Index *pIdx;
115422      HashElem *i;
115423      pParse->nMem = 5;
115424      sqlite3CodeVerifySchema(pParse, iDb);
115425      for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
115426        Table *pTab = sqliteHashData(i);
115427        sqlite3VdbeMultiLoad(v, 1, "ssiii",
115428             pTab->zName,
115429             0,
115430             pTab->szTabRow,
115431             pTab->nRowLogEst,
115432             pTab->tabFlags);
115433        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
115434          sqlite3VdbeMultiLoad(v, 2, "siiiX",
115435             pIdx->zName,
115436             pIdx->szIdxRow,
115437             pIdx->aiRowLogEst[0],
115438             pIdx->hasStat1);
115439          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
115440        }
115441      }
115442    }
115443    break;
115444  #endif
115445  
115446    case PragTyp_INDEX_INFO: if( zRight ){
115447      Index *pIdx;
115448      Table *pTab;
115449      pIdx = sqlite3FindIndex(db, zRight, zDb);
115450      if( pIdx ){
115451        int i;
115452        int mx;
115453        if( pPragma->iArg ){
115454          /* PRAGMA index_xinfo (newer version with more rows and columns) */
115455          mx = pIdx->nColumn;
115456          pParse->nMem = 6;
115457        }else{
115458          /* PRAGMA index_info (legacy version) */
115459          mx = pIdx->nKeyCol;
115460          pParse->nMem = 3;
115461        }
115462        pTab = pIdx->pTable;
115463        sqlite3CodeVerifySchema(pParse, iDb);
115464        assert( pParse->nMem<=pPragma->nPragCName );
115465        for(i=0; i<mx; i++){
115466          i16 cnum = pIdx->aiColumn[i];
115467          sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
115468                               cnum<0 ? 0 : pTab->aCol[cnum].zName);
115469          if( pPragma->iArg ){
115470            sqlite3VdbeMultiLoad(v, 4, "isiX",
115471              pIdx->aSortOrder[i],
115472              pIdx->azColl[i],
115473              i<pIdx->nKeyCol);
115474          }
115475          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
115476        }
115477      }
115478    }
115479    break;
115480  
115481    case PragTyp_INDEX_LIST: if( zRight ){
115482      Index *pIdx;
115483      Table *pTab;
115484      int i;
115485      pTab = sqlite3FindTable(db, zRight, zDb);
115486      if( pTab ){
115487        pParse->nMem = 5;
115488        sqlite3CodeVerifySchema(pParse, iDb);
115489        for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
115490          const char *azOrigin[] = { "c", "u", "pk" };
115491          sqlite3VdbeMultiLoad(v, 1, "isisi",
115492             i,
115493             pIdx->zName,
115494             IsUniqueIndex(pIdx),
115495             azOrigin[pIdx->idxType],
115496             pIdx->pPartIdxWhere!=0);
115497        }
115498      }
115499    }
115500    break;
115501  
115502    case PragTyp_DATABASE_LIST: {
115503      int i;
115504      pParse->nMem = 3;
115505      for(i=0; i<db->nDb; i++){
115506        if( db->aDb[i].pBt==0 ) continue;
115507        assert( db->aDb[i].zDbSName!=0 );
115508        sqlite3VdbeMultiLoad(v, 1, "iss",
115509           i,
115510           db->aDb[i].zDbSName,
115511           sqlite3BtreeGetFilename(db->aDb[i].pBt));
115512      }
115513    }
115514    break;
115515  
115516    case PragTyp_COLLATION_LIST: {
115517      int i = 0;
115518      HashElem *p;
115519      pParse->nMem = 2;
115520      for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
115521        CollSeq *pColl = (CollSeq *)sqliteHashData(p);
115522        sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
115523      }
115524    }
115525    break;
115526  
115527  #ifdef SQLITE_INTROSPECTION_PRAGMAS
115528    case PragTyp_FUNCTION_LIST: {
115529      int i;
115530      HashElem *j;
115531      FuncDef *p;
115532      pParse->nMem = 2;
115533      for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
115534        for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
115535          sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 1);
115536        }
115537      }
115538      for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
115539        p = (FuncDef*)sqliteHashData(j);
115540        sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 0);
115541      }
115542    }
115543    break;
115544  
115545  #ifndef SQLITE_OMIT_VIRTUALTABLE
115546    case PragTyp_MODULE_LIST: {
115547      HashElem *j;
115548      pParse->nMem = 1;
115549      for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
115550        Module *pMod = (Module*)sqliteHashData(j);
115551        sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
115552      }
115553    }
115554    break;
115555  #endif /* SQLITE_OMIT_VIRTUALTABLE */
115556  
115557    case PragTyp_PRAGMA_LIST: {
115558      int i;
115559      for(i=0; i<ArraySize(aPragmaName); i++){
115560        sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
115561      }
115562    }
115563    break;
115564  #endif /* SQLITE_INTROSPECTION_PRAGMAS */
115565  
115566  #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
115567  
115568  #ifndef SQLITE_OMIT_FOREIGN_KEY
115569    case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
115570      FKey *pFK;
115571      Table *pTab;
115572      pTab = sqlite3FindTable(db, zRight, zDb);
115573      if( pTab ){
115574        pFK = pTab->pFKey;
115575        if( pFK ){
115576          int i = 0; 
115577          pParse->nMem = 8;
115578          sqlite3CodeVerifySchema(pParse, iDb);
115579          while(pFK){
115580            int j;
115581            for(j=0; j<pFK->nCol; j++){
115582              sqlite3VdbeMultiLoad(v, 1, "iissssss",
115583                     i,
115584                     j,
115585                     pFK->zTo,
115586                     pTab->aCol[pFK->aCol[j].iFrom].zName,
115587                     pFK->aCol[j].zCol,
115588                     actionName(pFK->aAction[1]),  /* ON UPDATE */
115589                     actionName(pFK->aAction[0]),  /* ON DELETE */
115590                     "NONE");
115591            }
115592            ++i;
115593            pFK = pFK->pNextFrom;
115594          }
115595        }
115596      }
115597    }
115598    break;
115599  #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
115600  
115601  #ifndef SQLITE_OMIT_FOREIGN_KEY
115602  #ifndef SQLITE_OMIT_TRIGGER
115603    case PragTyp_FOREIGN_KEY_CHECK: {
115604      FKey *pFK;             /* A foreign key constraint */
115605      Table *pTab;           /* Child table contain "REFERENCES" keyword */
115606      Table *pParent;        /* Parent table that child points to */
115607      Index *pIdx;           /* Index in the parent table */
115608      int i;                 /* Loop counter:  Foreign key number for pTab */
115609      int j;                 /* Loop counter:  Field of the foreign key */
115610      HashElem *k;           /* Loop counter:  Next table in schema */
115611      int x;                 /* result variable */
115612      int regResult;         /* 3 registers to hold a result row */
115613      int regKey;            /* Register to hold key for checking the FK */
115614      int regRow;            /* Registers to hold a row from pTab */
115615      int addrTop;           /* Top of a loop checking foreign keys */
115616      int addrOk;            /* Jump here if the key is OK */
115617      int *aiCols;           /* child to parent column mapping */
115618  
115619      regResult = pParse->nMem+1;
115620      pParse->nMem += 4;
115621      regKey = ++pParse->nMem;
115622      regRow = ++pParse->nMem;
115623      sqlite3CodeVerifySchema(pParse, iDb);
115624      k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
115625      while( k ){
115626        if( zRight ){
115627          pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
115628          k = 0;
115629        }else{
115630          pTab = (Table*)sqliteHashData(k);
115631          k = sqliteHashNext(k);
115632        }
115633        if( pTab==0 || pTab->pFKey==0 ) continue;
115634        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
115635        if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
115636        sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
115637        sqlite3VdbeLoadString(v, regResult, pTab->zName);
115638        for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
115639          pParent = sqlite3FindTable(db, pFK->zTo, zDb);
115640          if( pParent==0 ) continue;
115641          pIdx = 0;
115642          sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
115643          x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
115644          if( x==0 ){
115645            if( pIdx==0 ){
115646              sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
115647            }else{
115648              sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
115649              sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
115650            }
115651          }else{
115652            k = 0;
115653            break;
115654          }
115655        }
115656        assert( pParse->nErr>0 || pFK==0 );
115657        if( pFK ) break;
115658        if( pParse->nTab<i ) pParse->nTab = i;
115659        addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
115660        for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
115661          pParent = sqlite3FindTable(db, pFK->zTo, zDb);
115662          pIdx = 0;
115663          aiCols = 0;
115664          if( pParent ){
115665            x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
115666            assert( x==0 );
115667          }
115668          addrOk = sqlite3VdbeMakeLabel(v);
115669  
115670          /* Generate code to read the child key values into registers
115671          ** regRow..regRow+n. If any of the child key values are NULL, this 
115672          ** row cannot cause an FK violation. Jump directly to addrOk in 
115673          ** this case. */
115674          for(j=0; j<pFK->nCol; j++){
115675            int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
115676            sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
115677            sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
115678          }
115679  
115680          /* Generate code to query the parent index for a matching parent
115681          ** key. If a match is found, jump to addrOk. */
115682          if( pIdx ){
115683            sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
115684                sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
115685            sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
115686            VdbeCoverage(v);
115687          }else if( pParent ){
115688            int jmp = sqlite3VdbeCurrentAddr(v)+2;
115689            sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
115690            sqlite3VdbeGoto(v, addrOk);
115691            assert( pFK->nCol==1 );
115692          }
115693  
115694          /* Generate code to report an FK violation to the caller. */
115695          if( HasRowid(pTab) ){
115696            sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
115697          }else{
115698            sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
115699          }
115700          sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
115701          sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
115702          sqlite3VdbeResolveLabel(v, addrOk);
115703          sqlite3DbFree(db, aiCols);
115704        }
115705        sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
115706        sqlite3VdbeJumpHere(v, addrTop);
115707      }
115708    }
115709    break;
115710  #endif /* !defined(SQLITE_OMIT_TRIGGER) */
115711  #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
115712  
115713  #ifndef NDEBUG
115714    case PragTyp_PARSER_TRACE: {
115715      if( zRight ){
115716        if( sqlite3GetBoolean(zRight, 0) ){
115717          sqlite3ParserTrace(stdout, "parser: ");
115718        }else{
115719          sqlite3ParserTrace(0, 0);
115720        }
115721      }
115722    }
115723    break;
115724  #endif
115725  
115726    /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
115727    ** used will be case sensitive or not depending on the RHS.
115728    */
115729    case PragTyp_CASE_SENSITIVE_LIKE: {
115730      if( zRight ){
115731        sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
115732      }
115733    }
115734    break;
115735  
115736  #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
115737  # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
115738  #endif
115739  
115740  #ifndef SQLITE_OMIT_INTEGRITY_CHECK
115741    /*    PRAGMA integrity_check
115742    **    PRAGMA integrity_check(N)
115743    **    PRAGMA quick_check
115744    **    PRAGMA quick_check(N)
115745    **
115746    ** Verify the integrity of the database.
115747    **
115748    ** The "quick_check" is reduced version of 
115749    ** integrity_check designed to detect most database corruption
115750    ** without the overhead of cross-checking indexes.  Quick_check
115751    ** is linear time wherease integrity_check is O(NlogN).
115752    */
115753    case PragTyp_INTEGRITY_CHECK: {
115754      int i, j, addr, mxErr;
115755  
115756      int isQuick = (sqlite3Tolower(zLeft[0])=='q');
115757  
115758      /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
115759      ** then iDb is set to the index of the database identified by <db>.
115760      ** In this case, the integrity of database iDb only is verified by
115761      ** the VDBE created below.
115762      **
115763      ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
115764      ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
115765      ** to -1 here, to indicate that the VDBE should verify the integrity
115766      ** of all attached databases.  */
115767      assert( iDb>=0 );
115768      assert( iDb==0 || pId2->z );
115769      if( pId2->z==0 ) iDb = -1;
115770  
115771      /* Initialize the VDBE program */
115772      pParse->nMem = 6;
115773  
115774      /* Set the maximum error count */
115775      mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
115776      if( zRight ){
115777        sqlite3GetInt32(zRight, &mxErr);
115778        if( mxErr<=0 ){
115779          mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
115780        }
115781      }
115782      sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
115783  
115784      /* Do an integrity check on each database file */
115785      for(i=0; i<db->nDb; i++){
115786        HashElem *x;     /* For looping over tables in the schema */
115787        Hash *pTbls;     /* Set of all tables in the schema */
115788        int *aRoot;      /* Array of root page numbers of all btrees */
115789        int cnt = 0;     /* Number of entries in aRoot[] */
115790        int mxIdx = 0;   /* Maximum number of indexes for any table */
115791  
115792        if( OMIT_TEMPDB && i==1 ) continue;
115793        if( iDb>=0 && i!=iDb ) continue;
115794  
115795        sqlite3CodeVerifySchema(pParse, i);
115796  
115797        /* Do an integrity check of the B-Tree
115798        **
115799        ** Begin by finding the root pages numbers
115800        ** for all tables and indices in the database.
115801        */
115802        assert( sqlite3SchemaMutexHeld(db, i, 0) );
115803        pTbls = &db->aDb[i].pSchema->tblHash;
115804        for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
115805          Table *pTab = sqliteHashData(x);  /* Current table */
115806          Index *pIdx;                      /* An index on pTab */
115807          int nIdx;                         /* Number of indexes on pTab */
115808          if( HasRowid(pTab) ) cnt++;
115809          for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
115810          if( nIdx>mxIdx ) mxIdx = nIdx;
115811        }
115812        aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
115813        if( aRoot==0 ) break;
115814        for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
115815          Table *pTab = sqliteHashData(x);
115816          Index *pIdx;
115817          if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
115818          for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
115819            aRoot[++cnt] = pIdx->tnum;
115820          }
115821        }
115822        aRoot[0] = cnt;
115823  
115824        /* Make sure sufficient number of registers have been allocated */
115825        pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
115826        sqlite3ClearTempRegCache(pParse);
115827  
115828        /* Do the b-tree integrity checks */
115829        sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
115830        sqlite3VdbeChangeP5(v, (u8)i);
115831        addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
115832        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
115833           sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
115834           P4_DYNAMIC);
115835        sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
115836        integrityCheckResultRow(v);
115837        sqlite3VdbeJumpHere(v, addr);
115838  
115839        /* Make sure all the indices are constructed correctly.
115840        */
115841        for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
115842          Table *pTab = sqliteHashData(x);
115843          Index *pIdx, *pPk;
115844          Index *pPrior = 0;
115845          int loopTop;
115846          int iDataCur, iIdxCur;
115847          int r1 = -1;
115848  
115849          if( pTab->tnum<1 ) continue;  /* Skip VIEWs or VIRTUAL TABLEs */
115850          pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
115851          sqlite3ExprCacheClear(pParse);
115852          sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
115853                                     1, 0, &iDataCur, &iIdxCur);
115854          /* reg[7] counts the number of entries in the table.
115855          ** reg[8+i] counts the number of entries in the i-th index 
115856          */
115857          sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
115858          for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
115859            sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
115860          }
115861          assert( pParse->nMem>=8+j );
115862          assert( sqlite3NoTempsInRange(pParse,1,7+j) );
115863          sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
115864          loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
115865          /* Verify that all NOT NULL columns really are NOT NULL */
115866          for(j=0; j<pTab->nCol; j++){
115867            char *zErr;
115868            int jmp2;
115869            if( j==pTab->iPKey ) continue;
115870            if( pTab->aCol[j].notNull==0 ) continue;
115871            sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
115872            sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
115873            jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
115874            zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
115875                                pTab->aCol[j].zName);
115876            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
115877            integrityCheckResultRow(v);
115878            sqlite3VdbeJumpHere(v, jmp2);
115879          }
115880          /* Verify CHECK constraints */
115881          if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
115882            ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
115883            if( db->mallocFailed==0 ){
115884              int addrCkFault = sqlite3VdbeMakeLabel(v);
115885              int addrCkOk = sqlite3VdbeMakeLabel(v);
115886              char *zErr;
115887              int k;
115888              pParse->iSelfTab = iDataCur + 1;
115889              sqlite3ExprCachePush(pParse);
115890              for(k=pCheck->nExpr-1; k>0; k--){
115891                sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
115892              }
115893              sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk, 
115894                  SQLITE_JUMPIFNULL);
115895              sqlite3VdbeResolveLabel(v, addrCkFault);
115896              pParse->iSelfTab = 0;
115897              zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
115898                  pTab->zName);
115899              sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
115900              integrityCheckResultRow(v);
115901              sqlite3VdbeResolveLabel(v, addrCkOk);
115902              sqlite3ExprCachePop(pParse);
115903            }
115904            sqlite3ExprListDelete(db, pCheck);
115905          }
115906          if( !isQuick ){ /* Omit the remaining tests for quick_check */
115907            /* Sanity check on record header decoding */
115908            sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nCol-1, 3);
115909            sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
115910            /* Validate index entries for the current row */
115911            for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
115912              int jmp2, jmp3, jmp4, jmp5;
115913              int ckUniq = sqlite3VdbeMakeLabel(v);
115914              if( pPk==pIdx ) continue;
115915              r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
115916                                           pPrior, r1);
115917              pPrior = pIdx;
115918              sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */
115919              /* Verify that an index entry exists for the current table row */
115920              jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
115921                                          pIdx->nColumn); VdbeCoverage(v);
115922              sqlite3VdbeLoadString(v, 3, "row ");
115923              sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
115924              sqlite3VdbeLoadString(v, 4, " missing from index ");
115925              sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
115926              jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
115927              sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
115928              jmp4 = integrityCheckResultRow(v);
115929              sqlite3VdbeJumpHere(v, jmp2);
115930              /* For UNIQUE indexes, verify that only one entry exists with the
115931              ** current key.  The entry is unique if (1) any column is NULL
115932              ** or (2) the next entry has a different key */
115933              if( IsUniqueIndex(pIdx) ){
115934                int uniqOk = sqlite3VdbeMakeLabel(v);
115935                int jmp6;
115936                int kk;
115937                for(kk=0; kk<pIdx->nKeyCol; kk++){
115938                  int iCol = pIdx->aiColumn[kk];
115939                  assert( iCol!=XN_ROWID && iCol<pTab->nCol );
115940                  if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
115941                  sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
115942                  VdbeCoverage(v);
115943                }
115944                jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
115945                sqlite3VdbeGoto(v, uniqOk);
115946                sqlite3VdbeJumpHere(v, jmp6);
115947                sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
115948                                     pIdx->nKeyCol); VdbeCoverage(v);
115949                sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
115950                sqlite3VdbeGoto(v, jmp5);
115951                sqlite3VdbeResolveLabel(v, uniqOk);
115952              }
115953              sqlite3VdbeJumpHere(v, jmp4);
115954              sqlite3ResolvePartIdxLabel(pParse, jmp3);
115955            }
115956          }
115957          sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
115958          sqlite3VdbeJumpHere(v, loopTop-1);
115959  #ifndef SQLITE_OMIT_BTREECOUNT
115960          if( !isQuick ){
115961            sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
115962            for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
115963              if( pPk==pIdx ) continue;
115964              sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
115965              addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
115966              sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
115967              sqlite3VdbeLoadString(v, 4, pIdx->zName);
115968              sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
115969              integrityCheckResultRow(v);
115970              sqlite3VdbeJumpHere(v, addr);
115971            }
115972          }
115973  #endif /* SQLITE_OMIT_BTREECOUNT */
115974        } 
115975      }
115976      {
115977        static const int iLn = VDBE_OFFSET_LINENO(2);
115978        static const VdbeOpList endCode[] = {
115979          { OP_AddImm,      1, 0,        0},    /* 0 */
115980          { OP_IfNotZero,   1, 4,        0},    /* 1 */
115981          { OP_String8,     0, 3,        0},    /* 2 */
115982          { OP_ResultRow,   3, 1,        0},    /* 3 */
115983          { OP_Halt,        0, 0,        0},    /* 4 */
115984          { OP_String8,     0, 3,        0},    /* 5 */
115985          { OP_Goto,        0, 3,        0},    /* 6 */
115986        };
115987        VdbeOp *aOp;
115988  
115989        aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
115990        if( aOp ){
115991          aOp[0].p2 = 1-mxErr;
115992          aOp[2].p4type = P4_STATIC;
115993          aOp[2].p4.z = "ok";
115994          aOp[5].p4type = P4_STATIC;
115995          aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);
115996        }
115997        sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
115998      }
115999    }
116000    break;
116001  #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
116002  
116003  #ifndef SQLITE_OMIT_UTF16
116004    /*
116005    **   PRAGMA encoding
116006    **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
116007    **
116008    ** In its first form, this pragma returns the encoding of the main
116009    ** database. If the database is not initialized, it is initialized now.
116010    **
116011    ** The second form of this pragma is a no-op if the main database file
116012    ** has not already been initialized. In this case it sets the default
116013    ** encoding that will be used for the main database file if a new file
116014    ** is created. If an existing main database file is opened, then the
116015    ** default text encoding for the existing database is used.
116016    ** 
116017    ** In all cases new databases created using the ATTACH command are
116018    ** created to use the same default text encoding as the main database. If
116019    ** the main database has not been initialized and/or created when ATTACH
116020    ** is executed, this is done before the ATTACH operation.
116021    **
116022    ** In the second form this pragma sets the text encoding to be used in
116023    ** new database files created using this database handle. It is only
116024    ** useful if invoked immediately after the main database i
116025    */
116026    case PragTyp_ENCODING: {
116027      static const struct EncName {
116028        char *zName;
116029        u8 enc;
116030      } encnames[] = {
116031        { "UTF8",     SQLITE_UTF8        },
116032        { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
116033        { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
116034        { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
116035        { "UTF16le",  SQLITE_UTF16LE     },
116036        { "UTF16be",  SQLITE_UTF16BE     },
116037        { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
116038        { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
116039        { 0, 0 }
116040      };
116041      const struct EncName *pEnc;
116042      if( !zRight ){    /* "PRAGMA encoding" */
116043        if( sqlite3ReadSchema(pParse) ) goto pragma_out;
116044        assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
116045        assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
116046        assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
116047        returnSingleText(v, encnames[ENC(pParse->db)].zName);
116048      }else{                        /* "PRAGMA encoding = XXX" */
116049        /* Only change the value of sqlite.enc if the database handle is not
116050        ** initialized. If the main database exists, the new sqlite.enc value
116051        ** will be overwritten when the schema is next loaded. If it does not
116052        ** already exists, it will be created to use the new encoding value.
116053        */
116054        if( 
116055          !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
116056          DbHasProperty(db, 0, DB_Empty) 
116057        ){
116058          for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
116059            if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
116060              SCHEMA_ENC(db) = ENC(db) =
116061                  pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
116062              break;
116063            }
116064          }
116065          if( !pEnc->zName ){
116066            sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
116067          }
116068        }
116069      }
116070    }
116071    break;
116072  #endif /* SQLITE_OMIT_UTF16 */
116073  
116074  #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
116075    /*
116076    **   PRAGMA [schema.]schema_version
116077    **   PRAGMA [schema.]schema_version = <integer>
116078    **
116079    **   PRAGMA [schema.]user_version
116080    **   PRAGMA [schema.]user_version = <integer>
116081    **
116082    **   PRAGMA [schema.]freelist_count
116083    **
116084    **   PRAGMA [schema.]data_version
116085    **
116086    **   PRAGMA [schema.]application_id
116087    **   PRAGMA [schema.]application_id = <integer>
116088    **
116089    ** The pragma's schema_version and user_version are used to set or get
116090    ** the value of the schema-version and user-version, respectively. Both
116091    ** the schema-version and the user-version are 32-bit signed integers
116092    ** stored in the database header.
116093    **
116094    ** The schema-cookie is usually only manipulated internally by SQLite. It
116095    ** is incremented by SQLite whenever the database schema is modified (by
116096    ** creating or dropping a table or index). The schema version is used by
116097    ** SQLite each time a query is executed to ensure that the internal cache
116098    ** of the schema used when compiling the SQL query matches the schema of
116099    ** the database against which the compiled query is actually executed.
116100    ** Subverting this mechanism by using "PRAGMA schema_version" to modify
116101    ** the schema-version is potentially dangerous and may lead to program
116102    ** crashes or database corruption. Use with caution!
116103    **
116104    ** The user-version is not used internally by SQLite. It may be used by
116105    ** applications for any purpose.
116106    */
116107    case PragTyp_HEADER_VALUE: {
116108      int iCookie = pPragma->iArg;  /* Which cookie to read or write */
116109      sqlite3VdbeUsesBtree(v, iDb);
116110      if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
116111        /* Write the specified cookie value */
116112        static const VdbeOpList setCookie[] = {
116113          { OP_Transaction,    0,  1,  0},    /* 0 */
116114          { OP_SetCookie,      0,  0,  0},    /* 1 */
116115        };
116116        VdbeOp *aOp;
116117        sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
116118        aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
116119        if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
116120        aOp[0].p1 = iDb;
116121        aOp[1].p1 = iDb;
116122        aOp[1].p2 = iCookie;
116123        aOp[1].p3 = sqlite3Atoi(zRight);
116124      }else{
116125        /* Read the specified cookie value */
116126        static const VdbeOpList readCookie[] = {
116127          { OP_Transaction,     0,  0,  0},    /* 0 */
116128          { OP_ReadCookie,      0,  1,  0},    /* 1 */
116129          { OP_ResultRow,       1,  1,  0}
116130        };
116131        VdbeOp *aOp;
116132        sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
116133        aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
116134        if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
116135        aOp[0].p1 = iDb;
116136        aOp[1].p1 = iDb;
116137        aOp[1].p3 = iCookie;
116138        sqlite3VdbeReusable(v);
116139      }
116140    }
116141    break;
116142  #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
116143  
116144  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
116145    /*
116146    **   PRAGMA compile_options
116147    **
116148    ** Return the names of all compile-time options used in this build,
116149    ** one option per row.
116150    */
116151    case PragTyp_COMPILE_OPTIONS: {
116152      int i = 0;
116153      const char *zOpt;
116154      pParse->nMem = 1;
116155      while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
116156        sqlite3VdbeLoadString(v, 1, zOpt);
116157        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
116158      }
116159      sqlite3VdbeReusable(v);
116160    }
116161    break;
116162  #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
116163  
116164  #ifndef SQLITE_OMIT_WAL
116165    /*
116166    **   PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
116167    **
116168    ** Checkpoint the database.
116169    */
116170    case PragTyp_WAL_CHECKPOINT: {
116171      int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
116172      int eMode = SQLITE_CHECKPOINT_PASSIVE;
116173      if( zRight ){
116174        if( sqlite3StrICmp(zRight, "full")==0 ){
116175          eMode = SQLITE_CHECKPOINT_FULL;
116176        }else if( sqlite3StrICmp(zRight, "restart")==0 ){
116177          eMode = SQLITE_CHECKPOINT_RESTART;
116178        }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
116179          eMode = SQLITE_CHECKPOINT_TRUNCATE;
116180        }
116181      }
116182      pParse->nMem = 3;
116183      sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
116184      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
116185    }
116186    break;
116187  
116188    /*
116189    **   PRAGMA wal_autocheckpoint
116190    **   PRAGMA wal_autocheckpoint = N
116191    **
116192    ** Configure a database connection to automatically checkpoint a database
116193    ** after accumulating N frames in the log. Or query for the current value
116194    ** of N.
116195    */
116196    case PragTyp_WAL_AUTOCHECKPOINT: {
116197      if( zRight ){
116198        sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
116199      }
116200      returnSingleInt(v, 
116201         db->xWalCallback==sqlite3WalDefaultHook ? 
116202             SQLITE_PTR_TO_INT(db->pWalArg) : 0);
116203    }
116204    break;
116205  #endif
116206  
116207    /*
116208    **  PRAGMA shrink_memory
116209    **
116210    ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
116211    ** connection on which it is invoked to free up as much memory as it
116212    ** can, by calling sqlite3_db_release_memory().
116213    */
116214    case PragTyp_SHRINK_MEMORY: {
116215      sqlite3_db_release_memory(db);
116216      break;
116217    }
116218  
116219    /*
116220    **  PRAGMA optimize
116221    **  PRAGMA optimize(MASK)
116222    **  PRAGMA schema.optimize
116223    **  PRAGMA schema.optimize(MASK)
116224    **
116225    ** Attempt to optimize the database.  All schemas are optimized in the first
116226    ** two forms, and only the specified schema is optimized in the latter two.
116227    **
116228    ** The details of optimizations performed by this pragma are expected
116229    ** to change and improve over time.  Applications should anticipate that
116230    ** this pragma will perform new optimizations in future releases.
116231    **
116232    ** The optional argument is a bitmask of optimizations to perform:
116233    **
116234    **    0x0001    Debugging mode.  Do not actually perform any optimizations
116235    **              but instead return one line of text for each optimization
116236    **              that would have been done.  Off by default.
116237    **
116238    **    0x0002    Run ANALYZE on tables that might benefit.  On by default.
116239    **              See below for additional information.
116240    **
116241    **    0x0004    (Not yet implemented) Record usage and performance 
116242    **              information from the current session in the
116243    **              database file so that it will be available to "optimize"
116244    **              pragmas run by future database connections.
116245    **
116246    **    0x0008    (Not yet implemented) Create indexes that might have
116247    **              been helpful to recent queries
116248    **
116249    ** The default MASK is and always shall be 0xfffe.  0xfffe means perform all
116250    ** of the optimizations listed above except Debug Mode, including new
116251    ** optimizations that have not yet been invented.  If new optimizations are
116252    ** ever added that should be off by default, those off-by-default 
116253    ** optimizations will have bitmasks of 0x10000 or larger.
116254    **
116255    ** DETERMINATION OF WHEN TO RUN ANALYZE
116256    **
116257    ** In the current implementation, a table is analyzed if only if all of
116258    ** the following are true:
116259    **
116260    ** (1) MASK bit 0x02 is set.
116261    **
116262    ** (2) The query planner used sqlite_stat1-style statistics for one or
116263    **     more indexes of the table at some point during the lifetime of
116264    **     the current connection.
116265    **
116266    ** (3) One or more indexes of the table are currently unanalyzed OR
116267    **     the number of rows in the table has increased by 25 times or more
116268    **     since the last time ANALYZE was run.
116269    **
116270    ** The rules for when tables are analyzed are likely to change in
116271    ** future releases.
116272    */
116273    case PragTyp_OPTIMIZE: {
116274      int iDbLast;           /* Loop termination point for the schema loop */
116275      int iTabCur;           /* Cursor for a table whose size needs checking */
116276      HashElem *k;           /* Loop over tables of a schema */
116277      Schema *pSchema;       /* The current schema */
116278      Table *pTab;           /* A table in the schema */
116279      Index *pIdx;           /* An index of the table */
116280      LogEst szThreshold;    /* Size threshold above which reanalysis is needd */
116281      char *zSubSql;         /* SQL statement for the OP_SqlExec opcode */
116282      u32 opMask;            /* Mask of operations to perform */
116283  
116284      if( zRight ){
116285        opMask = (u32)sqlite3Atoi(zRight);
116286        if( (opMask & 0x02)==0 ) break;
116287      }else{
116288        opMask = 0xfffe;
116289      }
116290      iTabCur = pParse->nTab++;
116291      for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
116292        if( iDb==1 ) continue;
116293        sqlite3CodeVerifySchema(pParse, iDb);
116294        pSchema = db->aDb[iDb].pSchema;
116295        for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
116296          pTab = (Table*)sqliteHashData(k);
116297  
116298          /* If table pTab has not been used in a way that would benefit from
116299          ** having analysis statistics during the current session, then skip it.
116300          ** This also has the effect of skipping virtual tables and views */
116301          if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
116302  
116303          /* Reanalyze if the table is 25 times larger than the last analysis */
116304          szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
116305          for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
116306            if( !pIdx->hasStat1 ){
116307              szThreshold = 0; /* Always analyze if any index lacks statistics */
116308              break;
116309            }
116310          }
116311          if( szThreshold ){
116312            sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
116313            sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur, 
116314                           sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
116315            VdbeCoverage(v);
116316          }
116317          zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
116318                                   db->aDb[iDb].zDbSName, pTab->zName);
116319          if( opMask & 0x01 ){
116320            int r1 = sqlite3GetTempReg(pParse);
116321            sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
116322            sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
116323          }else{
116324            sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
116325          }
116326        }
116327      }
116328      sqlite3VdbeAddOp0(v, OP_Expire);
116329      break;
116330    }
116331  
116332    /*
116333    **   PRAGMA busy_timeout
116334    **   PRAGMA busy_timeout = N
116335    **
116336    ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
116337    ** if one is set.  If no busy handler or a different busy handler is set
116338    ** then 0 is returned.  Setting the busy_timeout to 0 or negative
116339    ** disables the timeout.
116340    */
116341    /*case PragTyp_BUSY_TIMEOUT*/ default: {
116342      assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
116343      if( zRight ){
116344        sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
116345      }
116346      returnSingleInt(v, db->busyTimeout);
116347      break;
116348    }
116349  
116350    /*
116351    **   PRAGMA soft_heap_limit
116352    **   PRAGMA soft_heap_limit = N
116353    **
116354    ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
116355    ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
116356    ** specified and is a non-negative integer.
116357    ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
116358    ** returns the same integer that would be returned by the
116359    ** sqlite3_soft_heap_limit64(-1) C-language function.
116360    */
116361    case PragTyp_SOFT_HEAP_LIMIT: {
116362      sqlite3_int64 N;
116363      if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
116364        sqlite3_soft_heap_limit64(N);
116365      }
116366      returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
116367      break;
116368    }
116369  
116370    /*
116371    **   PRAGMA threads
116372    **   PRAGMA threads = N
116373    **
116374    ** Configure the maximum number of worker threads.  Return the new
116375    ** maximum, which might be less than requested.
116376    */
116377    case PragTyp_THREADS: {
116378      sqlite3_int64 N;
116379      if( zRight
116380       && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
116381       && N>=0
116382      ){
116383        sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
116384      }
116385      returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
116386      break;
116387    }
116388  
116389  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
116390    /*
116391    ** Report the current state of file logs for all databases
116392    */
116393    case PragTyp_LOCK_STATUS: {
116394      static const char *const azLockName[] = {
116395        "unlocked", "shared", "reserved", "pending", "exclusive"
116396      };
116397      int i;
116398      pParse->nMem = 2;
116399      for(i=0; i<db->nDb; i++){
116400        Btree *pBt;
116401        const char *zState = "unknown";
116402        int j;
116403        if( db->aDb[i].zDbSName==0 ) continue;
116404        pBt = db->aDb[i].pBt;
116405        if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
116406          zState = "closed";
116407        }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0, 
116408                                       SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
116409           zState = azLockName[j];
116410        }
116411        sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
116412      }
116413      break;
116414    }
116415  #endif
116416  
116417  #ifdef SQLITE_HAS_CODEC
116418    case PragTyp_KEY: {
116419      if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
116420      break;
116421    }
116422    case PragTyp_REKEY: {
116423      if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
116424      break;
116425    }
116426    case PragTyp_HEXKEY: {
116427      if( zRight ){
116428        u8 iByte;
116429        int i;
116430        char zKey[40];
116431        for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
116432          iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
116433          if( (i&1)!=0 ) zKey[i/2] = iByte;
116434        }
116435        if( (zLeft[3] & 0xf)==0xb ){
116436          sqlite3_key_v2(db, zDb, zKey, i/2);
116437        }else{
116438          sqlite3_rekey_v2(db, zDb, zKey, i/2);
116439        }
116440      }
116441      break;
116442    }
116443  #endif
116444  #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
116445    case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
116446  #ifdef SQLITE_HAS_CODEC
116447      if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
116448        sqlite3_activate_see(&zRight[4]);
116449      }
116450  #endif
116451  #ifdef SQLITE_ENABLE_CEROD
116452      if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
116453        sqlite3_activate_cerod(&zRight[6]);
116454      }
116455  #endif
116456    }
116457    break;
116458  #endif
116459  
116460    } /* End of the PRAGMA switch */
116461  
116462    /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
116463    ** purpose is to execute assert() statements to verify that if the
116464    ** PragFlg_NoColumns1 flag is set and the caller specified an argument
116465    ** to the PRAGMA, the implementation has not added any OP_ResultRow 
116466    ** instructions to the VM.  */
116467    if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
116468      sqlite3VdbeVerifyNoResultRow(v);
116469    }
116470  
116471  pragma_out:
116472    sqlite3DbFree(db, zLeft);
116473    sqlite3DbFree(db, zRight);
116474  }
116475  #ifndef SQLITE_OMIT_VIRTUALTABLE
116476  /*****************************************************************************
116477  ** Implementation of an eponymous virtual table that runs a pragma.
116478  **
116479  */
116480  typedef struct PragmaVtab PragmaVtab;
116481  typedef struct PragmaVtabCursor PragmaVtabCursor;
116482  struct PragmaVtab {
116483    sqlite3_vtab base;        /* Base class.  Must be first */
116484    sqlite3 *db;              /* The database connection to which it belongs */
116485    const PragmaName *pName;  /* Name of the pragma */
116486    u8 nHidden;               /* Number of hidden columns */
116487    u8 iHidden;               /* Index of the first hidden column */
116488  };
116489  struct PragmaVtabCursor {
116490    sqlite3_vtab_cursor base; /* Base class.  Must be first */
116491    sqlite3_stmt *pPragma;    /* The pragma statement to run */
116492    sqlite_int64 iRowid;      /* Current rowid */
116493    char *azArg[2];           /* Value of the argument and schema */
116494  };
116495  
116496  /* 
116497  ** Pragma virtual table module xConnect method.
116498  */
116499  static int pragmaVtabConnect(
116500    sqlite3 *db,
116501    void *pAux,
116502    int argc, const char *const*argv,
116503    sqlite3_vtab **ppVtab,
116504    char **pzErr
116505  ){
116506    const PragmaName *pPragma = (const PragmaName*)pAux;
116507    PragmaVtab *pTab = 0;
116508    int rc;
116509    int i, j;
116510    char cSep = '(';
116511    StrAccum acc;
116512    char zBuf[200];
116513  
116514    UNUSED_PARAMETER(argc);
116515    UNUSED_PARAMETER(argv);
116516    sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
116517    sqlite3StrAccumAppendAll(&acc, "CREATE TABLE x");
116518    for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
116519      sqlite3XPrintf(&acc, "%c\"%s\"", cSep, pragCName[j]);
116520      cSep = ',';
116521    }
116522    if( i==0 ){
116523      sqlite3XPrintf(&acc, "(\"%s\"", pPragma->zName);
116524      cSep = ',';
116525      i++;
116526    }
116527    j = 0;
116528    if( pPragma->mPragFlg & PragFlg_Result1 ){
116529      sqlite3StrAccumAppendAll(&acc, ",arg HIDDEN");
116530      j++;
116531    }
116532    if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
116533      sqlite3StrAccumAppendAll(&acc, ",schema HIDDEN");
116534      j++;
116535    }
116536    sqlite3StrAccumAppend(&acc, ")", 1);
116537    sqlite3StrAccumFinish(&acc);
116538    assert( strlen(zBuf) < sizeof(zBuf)-1 );
116539    rc = sqlite3_declare_vtab(db, zBuf);
116540    if( rc==SQLITE_OK ){
116541      pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
116542      if( pTab==0 ){
116543        rc = SQLITE_NOMEM;
116544      }else{
116545        memset(pTab, 0, sizeof(PragmaVtab));
116546        pTab->pName = pPragma;
116547        pTab->db = db;
116548        pTab->iHidden = i;
116549        pTab->nHidden = j;
116550      }
116551    }else{
116552      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
116553    }
116554  
116555    *ppVtab = (sqlite3_vtab*)pTab;
116556    return rc;
116557  }
116558  
116559  /* 
116560  ** Pragma virtual table module xDisconnect method.
116561  */
116562  static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
116563    PragmaVtab *pTab = (PragmaVtab*)pVtab;
116564    sqlite3_free(pTab);
116565    return SQLITE_OK;
116566  }
116567  
116568  /* Figure out the best index to use to search a pragma virtual table.
116569  **
116570  ** There are not really any index choices.  But we want to encourage the
116571  ** query planner to give == constraints on as many hidden parameters as
116572  ** possible, and especially on the first hidden parameter.  So return a
116573  ** high cost if hidden parameters are unconstrained.
116574  */
116575  static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
116576    PragmaVtab *pTab = (PragmaVtab*)tab;
116577    const struct sqlite3_index_constraint *pConstraint;
116578    int i, j;
116579    int seen[2];
116580  
116581    pIdxInfo->estimatedCost = (double)1;
116582    if( pTab->nHidden==0 ){ return SQLITE_OK; }
116583    pConstraint = pIdxInfo->aConstraint;
116584    seen[0] = 0;
116585    seen[1] = 0;
116586    for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
116587      if( pConstraint->usable==0 ) continue;
116588      if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
116589      if( pConstraint->iColumn < pTab->iHidden ) continue;
116590      j = pConstraint->iColumn - pTab->iHidden;
116591      assert( j < 2 );
116592      seen[j] = i+1;
116593    }
116594    if( seen[0]==0 ){
116595      pIdxInfo->estimatedCost = (double)2147483647;
116596      pIdxInfo->estimatedRows = 2147483647;
116597      return SQLITE_OK;
116598    }
116599    j = seen[0]-1;
116600    pIdxInfo->aConstraintUsage[j].argvIndex = 1;
116601    pIdxInfo->aConstraintUsage[j].omit = 1;
116602    if( seen[1]==0 ) return SQLITE_OK;
116603    pIdxInfo->estimatedCost = (double)20;
116604    pIdxInfo->estimatedRows = 20;
116605    j = seen[1]-1;
116606    pIdxInfo->aConstraintUsage[j].argvIndex = 2;
116607    pIdxInfo->aConstraintUsage[j].omit = 1;
116608    return SQLITE_OK;
116609  }
116610  
116611  /* Create a new cursor for the pragma virtual table */
116612  static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
116613    PragmaVtabCursor *pCsr;
116614    pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
116615    if( pCsr==0 ) return SQLITE_NOMEM;
116616    memset(pCsr, 0, sizeof(PragmaVtabCursor));
116617    pCsr->base.pVtab = pVtab;
116618    *ppCursor = &pCsr->base;
116619    return SQLITE_OK;
116620  }
116621  
116622  /* Clear all content from pragma virtual table cursor. */
116623  static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
116624    int i;
116625    sqlite3_finalize(pCsr->pPragma);
116626    pCsr->pPragma = 0;
116627    for(i=0; i<ArraySize(pCsr->azArg); i++){
116628      sqlite3_free(pCsr->azArg[i]);
116629      pCsr->azArg[i] = 0;
116630    }
116631  }
116632  
116633  /* Close a pragma virtual table cursor */
116634  static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
116635    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
116636    pragmaVtabCursorClear(pCsr);
116637    sqlite3_free(pCsr);
116638    return SQLITE_OK;
116639  }
116640  
116641  /* Advance the pragma virtual table cursor to the next row */
116642  static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
116643    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
116644    int rc = SQLITE_OK;
116645  
116646    /* Increment the xRowid value */
116647    pCsr->iRowid++;
116648    assert( pCsr->pPragma );
116649    if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
116650      rc = sqlite3_finalize(pCsr->pPragma);
116651      pCsr->pPragma = 0;
116652      pragmaVtabCursorClear(pCsr);
116653    }
116654    return rc;
116655  }
116656  
116657  /* 
116658  ** Pragma virtual table module xFilter method.
116659  */
116660  static int pragmaVtabFilter(
116661    sqlite3_vtab_cursor *pVtabCursor, 
116662    int idxNum, const char *idxStr,
116663    int argc, sqlite3_value **argv
116664  ){
116665    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
116666    PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
116667    int rc;
116668    int i, j;
116669    StrAccum acc;
116670    char *zSql;
116671  
116672    UNUSED_PARAMETER(idxNum);
116673    UNUSED_PARAMETER(idxStr);
116674    pragmaVtabCursorClear(pCsr);
116675    j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
116676    for(i=0; i<argc; i++, j++){
116677      const char *zText = (const char*)sqlite3_value_text(argv[i]);
116678      assert( j<ArraySize(pCsr->azArg) );
116679      assert( pCsr->azArg[j]==0 );
116680      if( zText ){
116681        pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
116682        if( pCsr->azArg[j]==0 ){
116683          return SQLITE_NOMEM;
116684        }
116685      }
116686    }
116687    sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
116688    sqlite3StrAccumAppendAll(&acc, "PRAGMA ");
116689    if( pCsr->azArg[1] ){
116690      sqlite3XPrintf(&acc, "%Q.", pCsr->azArg[1]);
116691    }
116692    sqlite3StrAccumAppendAll(&acc, pTab->pName->zName);
116693    if( pCsr->azArg[0] ){
116694      sqlite3XPrintf(&acc, "=%Q", pCsr->azArg[0]);
116695    }
116696    zSql = sqlite3StrAccumFinish(&acc);
116697    if( zSql==0 ) return SQLITE_NOMEM;
116698    rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
116699    sqlite3_free(zSql);
116700    if( rc!=SQLITE_OK ){
116701      pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
116702      return rc;
116703    }
116704    return pragmaVtabNext(pVtabCursor);
116705  }
116706  
116707  /*
116708  ** Pragma virtual table module xEof method.
116709  */
116710  static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
116711    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
116712    return (pCsr->pPragma==0);
116713  }
116714  
116715  /* The xColumn method simply returns the corresponding column from
116716  ** the PRAGMA.  
116717  */
116718  static int pragmaVtabColumn(
116719    sqlite3_vtab_cursor *pVtabCursor, 
116720    sqlite3_context *ctx, 
116721    int i
116722  ){
116723    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
116724    PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
116725    if( i<pTab->iHidden ){
116726      sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
116727    }else{
116728      sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
116729    }
116730    return SQLITE_OK;
116731  }
116732  
116733  /* 
116734  ** Pragma virtual table module xRowid method.
116735  */
116736  static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
116737    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
116738    *p = pCsr->iRowid;
116739    return SQLITE_OK;
116740  }
116741  
116742  /* The pragma virtual table object */
116743  static const sqlite3_module pragmaVtabModule = {
116744    0,                           /* iVersion */
116745    0,                           /* xCreate - create a table */
116746    pragmaVtabConnect,           /* xConnect - connect to an existing table */
116747    pragmaVtabBestIndex,         /* xBestIndex - Determine search strategy */
116748    pragmaVtabDisconnect,        /* xDisconnect - Disconnect from a table */
116749    0,                           /* xDestroy - Drop a table */
116750    pragmaVtabOpen,              /* xOpen - open a cursor */
116751    pragmaVtabClose,             /* xClose - close a cursor */
116752    pragmaVtabFilter,            /* xFilter - configure scan constraints */
116753    pragmaVtabNext,              /* xNext - advance a cursor */
116754    pragmaVtabEof,               /* xEof */
116755    pragmaVtabColumn,            /* xColumn - read data */
116756    pragmaVtabRowid,             /* xRowid - read data */
116757    0,                           /* xUpdate - write data */
116758    0,                           /* xBegin - begin transaction */
116759    0,                           /* xSync - sync transaction */
116760    0,                           /* xCommit - commit transaction */
116761    0,                           /* xRollback - rollback transaction */
116762    0,                           /* xFindFunction - function overloading */
116763    0,                           /* xRename - rename the table */
116764    0,                           /* xSavepoint */
116765    0,                           /* xRelease */
116766    0                            /* xRollbackTo */
116767  };
116768  
116769  /*
116770  ** Check to see if zTabName is really the name of a pragma.  If it is,
116771  ** then register an eponymous virtual table for that pragma and return
116772  ** a pointer to the Module object for the new virtual table.
116773  */
116774  SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
116775    const PragmaName *pName;
116776    assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
116777    pName = pragmaLocate(zName+7);
116778    if( pName==0 ) return 0;
116779    if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
116780    assert( sqlite3HashFind(&db->aModule, zName)==0 );
116781    return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
116782  }
116783  
116784  #endif /* SQLITE_OMIT_VIRTUALTABLE */
116785  
116786  #endif /* SQLITE_OMIT_PRAGMA */
116787  
116788  /************** End of pragma.c **********************************************/
116789  /************** Begin file prepare.c *****************************************/
116790  /*
116791  ** 2005 May 25
116792  **
116793  ** The author disclaims copyright to this source code.  In place of
116794  ** a legal notice, here is a blessing:
116795  **
116796  **    May you do good and not evil.
116797  **    May you find forgiveness for yourself and forgive others.
116798  **    May you share freely, never taking more than you give.
116799  **
116800  *************************************************************************
116801  ** This file contains the implementation of the sqlite3_prepare()
116802  ** interface, and routines that contribute to loading the database schema
116803  ** from disk.
116804  */
116805  /* #include "sqliteInt.h" */
116806  
116807  /*
116808  ** Fill the InitData structure with an error message that indicates
116809  ** that the database is corrupt.
116810  */
116811  static void corruptSchema(
116812    InitData *pData,     /* Initialization context */
116813    const char *zObj,    /* Object being parsed at the point of error */
116814    const char *zExtra   /* Error information */
116815  ){
116816    sqlite3 *db = pData->db;
116817    if( !db->mallocFailed && (db->flags & SQLITE_WriteSchema)==0 ){
116818      char *z;
116819      if( zObj==0 ) zObj = "?";
116820      z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
116821      if( zExtra ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
116822      sqlite3DbFree(db, *pData->pzErrMsg);
116823      *pData->pzErrMsg = z;
116824    }
116825    pData->rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_CORRUPT_BKPT;
116826  }
116827  
116828  /*
116829  ** This is the callback routine for the code that initializes the
116830  ** database.  See sqlite3Init() below for additional information.
116831  ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
116832  **
116833  ** Each callback contains the following information:
116834  **
116835  **     argv[0] = name of thing being created
116836  **     argv[1] = root page number for table or index. 0 for trigger or view.
116837  **     argv[2] = SQL text for the CREATE statement.
116838  **
116839  */
116840  SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
116841    InitData *pData = (InitData*)pInit;
116842    sqlite3 *db = pData->db;
116843    int iDb = pData->iDb;
116844  
116845    assert( argc==3 );
116846    UNUSED_PARAMETER2(NotUsed, argc);
116847    assert( sqlite3_mutex_held(db->mutex) );
116848    DbClearProperty(db, iDb, DB_Empty);
116849    if( db->mallocFailed ){
116850      corruptSchema(pData, argv[0], 0);
116851      return 1;
116852    }
116853  
116854    assert( iDb>=0 && iDb<db->nDb );
116855    if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
116856    if( argv[1]==0 ){
116857      corruptSchema(pData, argv[0], 0);
116858    }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
116859      /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
116860      ** But because db->init.busy is set to 1, no VDBE code is generated
116861      ** or executed.  All the parser does is build the internal data
116862      ** structures that describe the table, index, or view.
116863      */
116864      int rc;
116865      u8 saved_iDb = db->init.iDb;
116866      sqlite3_stmt *pStmt;
116867      TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
116868  
116869      assert( db->init.busy );
116870      db->init.iDb = iDb;
116871      db->init.newTnum = sqlite3Atoi(argv[1]);
116872      db->init.orphanTrigger = 0;
116873      TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
116874      rc = db->errCode;
116875      assert( (rc&0xFF)==(rcp&0xFF) );
116876      db->init.iDb = saved_iDb;
116877      assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 );
116878      if( SQLITE_OK!=rc ){
116879        if( db->init.orphanTrigger ){
116880          assert( iDb==1 );
116881        }else{
116882          pData->rc = rc;
116883          if( rc==SQLITE_NOMEM ){
116884            sqlite3OomFault(db);
116885          }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
116886            corruptSchema(pData, argv[0], sqlite3_errmsg(db));
116887          }
116888        }
116889      }
116890      sqlite3_finalize(pStmt);
116891    }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
116892      corruptSchema(pData, argv[0], 0);
116893    }else{
116894      /* If the SQL column is blank it means this is an index that
116895      ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
116896      ** constraint for a CREATE TABLE.  The index should have already
116897      ** been created when we processed the CREATE TABLE.  All we have
116898      ** to do here is record the root page number for that index.
116899      */
116900      Index *pIndex;
116901      pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zDbSName);
116902      if( pIndex==0 ){
116903        /* This can occur if there exists an index on a TEMP table which
116904        ** has the same name as another index on a permanent index.  Since
116905        ** the permanent table is hidden by the TEMP table, we can also
116906        ** safely ignore the index on the permanent table.
116907        */
116908        /* Do Nothing */;
116909      }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
116910        corruptSchema(pData, argv[0], "invalid rootpage");
116911      }
116912    }
116913    return 0;
116914  }
116915  
116916  /*
116917  ** Attempt to read the database schema and initialize internal
116918  ** data structures for a single database file.  The index of the
116919  ** database file is given by iDb.  iDb==0 is used for the main
116920  ** database.  iDb==1 should never be used.  iDb>=2 is used for
116921  ** auxiliary databases.  Return one of the SQLITE_ error codes to
116922  ** indicate success or failure.
116923  */
116924  static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
116925    int rc;
116926    int i;
116927  #ifndef SQLITE_OMIT_DEPRECATED
116928    int size;
116929  #endif
116930    Db *pDb;
116931    char const *azArg[4];
116932    int meta[5];
116933    InitData initData;
116934    const char *zMasterName;
116935    int openedTransaction = 0;
116936  
116937    assert( iDb>=0 && iDb<db->nDb );
116938    assert( db->aDb[iDb].pSchema );
116939    assert( sqlite3_mutex_held(db->mutex) );
116940    assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
116941  
116942    db->init.busy = 1;
116943  
116944    /* Construct the in-memory representation schema tables (sqlite_master or
116945    ** sqlite_temp_master) by invoking the parser directly.  The appropriate
116946    ** table name will be inserted automatically by the parser so we can just
116947    ** use the abbreviation "x" here.  The parser will also automatically tag
116948    ** the schema table as read-only. */
116949    azArg[0] = zMasterName = SCHEMA_TABLE(iDb);
116950    azArg[1] = "1";
116951    azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text,"
116952                              "rootpage int,sql text)";
116953    azArg[3] = 0;
116954    initData.db = db;
116955    initData.iDb = iDb;
116956    initData.rc = SQLITE_OK;
116957    initData.pzErrMsg = pzErrMsg;
116958    sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
116959    if( initData.rc ){
116960      rc = initData.rc;
116961      goto error_out;
116962    }
116963  
116964    /* Create a cursor to hold the database open
116965    */
116966    pDb = &db->aDb[iDb];
116967    if( pDb->pBt==0 ){
116968      assert( iDb==1 );
116969      DbSetProperty(db, 1, DB_SchemaLoaded);
116970      rc = SQLITE_OK;
116971      goto error_out;
116972    }
116973  
116974    /* If there is not already a read-only (or read-write) transaction opened
116975    ** on the b-tree database, open one now. If a transaction is opened, it 
116976    ** will be closed before this function returns.  */
116977    sqlite3BtreeEnter(pDb->pBt);
116978    if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
116979      rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
116980      if( rc!=SQLITE_OK ){
116981        sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
116982        goto initone_error_out;
116983      }
116984      openedTransaction = 1;
116985    }
116986  
116987    /* Get the database meta information.
116988    **
116989    ** Meta values are as follows:
116990    **    meta[0]   Schema cookie.  Changes with each schema change.
116991    **    meta[1]   File format of schema layer.
116992    **    meta[2]   Size of the page cache.
116993    **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
116994    **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
116995    **    meta[5]   User version
116996    **    meta[6]   Incremental vacuum mode
116997    **    meta[7]   unused
116998    **    meta[8]   unused
116999    **    meta[9]   unused
117000    **
117001    ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
117002    ** the possible values of meta[4].
117003    */
117004    for(i=0; i<ArraySize(meta); i++){
117005      sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
117006    }
117007    pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
117008  
117009    /* If opening a non-empty database, check the text encoding. For the
117010    ** main database, set sqlite3.enc to the encoding of the main database.
117011    ** For an attached db, it is an error if the encoding is not the same
117012    ** as sqlite3.enc.
117013    */
117014    if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
117015      if( iDb==0 ){
117016  #ifndef SQLITE_OMIT_UTF16
117017        u8 encoding;
117018        /* If opening the main database, set ENC(db). */
117019        encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
117020        if( encoding==0 ) encoding = SQLITE_UTF8;
117021        ENC(db) = encoding;
117022  #else
117023        ENC(db) = SQLITE_UTF8;
117024  #endif
117025      }else{
117026        /* If opening an attached database, the encoding much match ENC(db) */
117027        if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
117028          sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
117029              " text encoding as main database");
117030          rc = SQLITE_ERROR;
117031          goto initone_error_out;
117032        }
117033      }
117034    }else{
117035      DbSetProperty(db, iDb, DB_Empty);
117036    }
117037    pDb->pSchema->enc = ENC(db);
117038  
117039    if( pDb->pSchema->cache_size==0 ){
117040  #ifndef SQLITE_OMIT_DEPRECATED
117041      size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
117042      if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
117043      pDb->pSchema->cache_size = size;
117044  #else
117045      pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
117046  #endif
117047      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
117048    }
117049  
117050    /*
117051    ** file_format==1    Version 3.0.0.
117052    ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
117053    ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
117054    ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
117055    */
117056    pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
117057    if( pDb->pSchema->file_format==0 ){
117058      pDb->pSchema->file_format = 1;
117059    }
117060    if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
117061      sqlite3SetString(pzErrMsg, db, "unsupported file format");
117062      rc = SQLITE_ERROR;
117063      goto initone_error_out;
117064    }
117065  
117066    /* Ticket #2804:  When we open a database in the newer file format,
117067    ** clear the legacy_file_format pragma flag so that a VACUUM will
117068    ** not downgrade the database and thus invalidate any descending
117069    ** indices that the user might have created.
117070    */
117071    if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
117072      db->flags &= ~SQLITE_LegacyFileFmt;
117073    }
117074  
117075    /* Read the schema information out of the schema tables
117076    */
117077    assert( db->init.busy );
117078    {
117079      char *zSql;
117080      zSql = sqlite3MPrintf(db, 
117081          "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
117082          db->aDb[iDb].zDbSName, zMasterName);
117083  #ifndef SQLITE_OMIT_AUTHORIZATION
117084      {
117085        sqlite3_xauth xAuth;
117086        xAuth = db->xAuth;
117087        db->xAuth = 0;
117088  #endif
117089        rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
117090  #ifndef SQLITE_OMIT_AUTHORIZATION
117091        db->xAuth = xAuth;
117092      }
117093  #endif
117094      if( rc==SQLITE_OK ) rc = initData.rc;
117095      sqlite3DbFree(db, zSql);
117096  #ifndef SQLITE_OMIT_ANALYZE
117097      if( rc==SQLITE_OK ){
117098        sqlite3AnalysisLoad(db, iDb);
117099      }
117100  #endif
117101    }
117102    if( db->mallocFailed ){
117103      rc = SQLITE_NOMEM_BKPT;
117104      sqlite3ResetAllSchemasOfConnection(db);
117105    }
117106    if( rc==SQLITE_OK || (db->flags&SQLITE_WriteSchema)){
117107      /* Black magic: If the SQLITE_WriteSchema flag is set, then consider
117108      ** the schema loaded, even if errors occurred. In this situation the 
117109      ** current sqlite3_prepare() operation will fail, but the following one
117110      ** will attempt to compile the supplied statement against whatever subset
117111      ** of the schema was loaded before the error occurred. The primary
117112      ** purpose of this is to allow access to the sqlite_master table
117113      ** even when its contents have been corrupted.
117114      */
117115      DbSetProperty(db, iDb, DB_SchemaLoaded);
117116      rc = SQLITE_OK;
117117    }
117118  
117119    /* Jump here for an error that occurs after successfully allocating
117120    ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
117121    ** before that point, jump to error_out.
117122    */
117123  initone_error_out:
117124    if( openedTransaction ){
117125      sqlite3BtreeCommit(pDb->pBt);
117126    }
117127    sqlite3BtreeLeave(pDb->pBt);
117128  
117129  error_out:
117130    if( rc ){
117131      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
117132        sqlite3OomFault(db);
117133      }
117134      sqlite3ResetOneSchema(db, iDb);
117135    }
117136    db->init.busy = 0;
117137    return rc;
117138  }
117139  
117140  /*
117141  ** Initialize all database files - the main database file, the file
117142  ** used to store temporary tables, and any additional database files
117143  ** created using ATTACH statements.  Return a success code.  If an
117144  ** error occurs, write an error message into *pzErrMsg.
117145  **
117146  ** After a database is initialized, the DB_SchemaLoaded bit is set
117147  ** bit is set in the flags field of the Db structure. If the database
117148  ** file was of zero-length, then the DB_Empty flag is also set.
117149  */
117150  SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
117151    int i, rc;
117152    int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange);
117153    
117154    assert( sqlite3_mutex_held(db->mutex) );
117155    assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
117156    assert( db->init.busy==0 );
117157    ENC(db) = SCHEMA_ENC(db);
117158    assert( db->nDb>0 );
117159    /* Do the main schema first */
117160    if( !DbHasProperty(db, 0, DB_SchemaLoaded) ){
117161      rc = sqlite3InitOne(db, 0, pzErrMsg);
117162      if( rc ) return rc;
117163    }
117164    /* All other schemas after the main schema. The "temp" schema must be last */
117165    for(i=db->nDb-1; i>0; i--){
117166      if( !DbHasProperty(db, i, DB_SchemaLoaded) ){
117167        rc = sqlite3InitOne(db, i, pzErrMsg);
117168        if( rc ) return rc;
117169      }
117170    }
117171    if( commit_internal ){
117172      sqlite3CommitInternalChanges(db);
117173    }
117174    return SQLITE_OK;
117175  }
117176  
117177  /*
117178  ** This routine is a no-op if the database schema is already initialized.
117179  ** Otherwise, the schema is loaded. An error code is returned.
117180  */
117181  SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
117182    int rc = SQLITE_OK;
117183    sqlite3 *db = pParse->db;
117184    assert( sqlite3_mutex_held(db->mutex) );
117185    if( !db->init.busy ){
117186      rc = sqlite3Init(db, &pParse->zErrMsg);
117187    }
117188    if( rc!=SQLITE_OK ){
117189      pParse->rc = rc;
117190      pParse->nErr++;
117191    }
117192    return rc;
117193  }
117194  
117195  
117196  /*
117197  ** Check schema cookies in all databases.  If any cookie is out
117198  ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
117199  ** make no changes to pParse->rc.
117200  */
117201  static void schemaIsValid(Parse *pParse){
117202    sqlite3 *db = pParse->db;
117203    int iDb;
117204    int rc;
117205    int cookie;
117206  
117207    assert( pParse->checkSchema );
117208    assert( sqlite3_mutex_held(db->mutex) );
117209    for(iDb=0; iDb<db->nDb; iDb++){
117210      int openedTransaction = 0;         /* True if a transaction is opened */
117211      Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
117212      if( pBt==0 ) continue;
117213  
117214      /* If there is not already a read-only (or read-write) transaction opened
117215      ** on the b-tree database, open one now. If a transaction is opened, it 
117216      ** will be closed immediately after reading the meta-value. */
117217      if( !sqlite3BtreeIsInReadTrans(pBt) ){
117218        rc = sqlite3BtreeBeginTrans(pBt, 0);
117219        if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
117220          sqlite3OomFault(db);
117221        }
117222        if( rc!=SQLITE_OK ) return;
117223        openedTransaction = 1;
117224      }
117225  
117226      /* Read the schema cookie from the database. If it does not match the 
117227      ** value stored as part of the in-memory schema representation,
117228      ** set Parse.rc to SQLITE_SCHEMA. */
117229      sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
117230      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
117231      if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
117232        sqlite3ResetOneSchema(db, iDb);
117233        pParse->rc = SQLITE_SCHEMA;
117234      }
117235  
117236      /* Close the transaction, if one was opened. */
117237      if( openedTransaction ){
117238        sqlite3BtreeCommit(pBt);
117239      }
117240    }
117241  }
117242  
117243  /*
117244  ** Convert a schema pointer into the iDb index that indicates
117245  ** which database file in db->aDb[] the schema refers to.
117246  **
117247  ** If the same database is attached more than once, the first
117248  ** attached database is returned.
117249  */
117250  SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
117251    int i = -1000000;
117252  
117253    /* If pSchema is NULL, then return -1000000. This happens when code in 
117254    ** expr.c is trying to resolve a reference to a transient table (i.e. one
117255    ** created by a sub-select). In this case the return value of this 
117256    ** function should never be used.
117257    **
117258    ** We return -1000000 instead of the more usual -1 simply because using
117259    ** -1000000 as the incorrect index into db->aDb[] is much 
117260    ** more likely to cause a segfault than -1 (of course there are assert()
117261    ** statements too, but it never hurts to play the odds).
117262    */
117263    assert( sqlite3_mutex_held(db->mutex) );
117264    if( pSchema ){
117265      for(i=0; ALWAYS(i<db->nDb); i++){
117266        if( db->aDb[i].pSchema==pSchema ){
117267          break;
117268        }
117269      }
117270      assert( i>=0 && i<db->nDb );
117271    }
117272    return i;
117273  }
117274  
117275  /*
117276  ** Free all memory allocations in the pParse object
117277  */
117278  SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
117279    sqlite3 *db = pParse->db;
117280    sqlite3DbFree(db, pParse->aLabel);
117281    sqlite3ExprListDelete(db, pParse->pConstExpr);
117282    if( db ){
117283      assert( db->lookaside.bDisable >= pParse->disableLookaside );
117284      db->lookaside.bDisable -= pParse->disableLookaside;
117285    }
117286    pParse->disableLookaside = 0;
117287  }
117288  
117289  /*
117290  ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
117291  */
117292  static int sqlite3Prepare(
117293    sqlite3 *db,              /* Database handle. */
117294    const char *zSql,         /* UTF-8 encoded SQL statement. */
117295    int nBytes,               /* Length of zSql in bytes. */
117296    u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
117297    Vdbe *pReprepare,         /* VM being reprepared */
117298    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
117299    const char **pzTail       /* OUT: End of parsed string */
117300  ){
117301    char *zErrMsg = 0;        /* Error message */
117302    int rc = SQLITE_OK;       /* Result code */
117303    int i;                    /* Loop counter */
117304    Parse sParse;             /* Parsing context */
117305  
117306    memset(&sParse, 0, PARSE_HDR_SZ);
117307    memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
117308    sParse.pReprepare = pReprepare;
117309    assert( ppStmt && *ppStmt==0 );
117310    /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
117311    assert( sqlite3_mutex_held(db->mutex) );
117312  
117313    /* For a long-term use prepared statement avoid the use of
117314    ** lookaside memory.
117315    */
117316    if( prepFlags & SQLITE_PREPARE_PERSISTENT ){
117317      sParse.disableLookaside++;
117318      db->lookaside.bDisable++;
117319    }
117320  
117321    /* Check to verify that it is possible to get a read lock on all
117322    ** database schemas.  The inability to get a read lock indicates that
117323    ** some other database connection is holding a write-lock, which in
117324    ** turn means that the other connection has made uncommitted changes
117325    ** to the schema.
117326    **
117327    ** Were we to proceed and prepare the statement against the uncommitted
117328    ** schema changes and if those schema changes are subsequently rolled
117329    ** back and different changes are made in their place, then when this
117330    ** prepared statement goes to run the schema cookie would fail to detect
117331    ** the schema change.  Disaster would follow.
117332    **
117333    ** This thread is currently holding mutexes on all Btrees (because
117334    ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
117335    ** is not possible for another thread to start a new schema change
117336    ** while this routine is running.  Hence, we do not need to hold 
117337    ** locks on the schema, we just need to make sure nobody else is 
117338    ** holding them.
117339    **
117340    ** Note that setting READ_UNCOMMITTED overrides most lock detection,
117341    ** but it does *not* override schema lock detection, so this all still
117342    ** works even if READ_UNCOMMITTED is set.
117343    */
117344    for(i=0; i<db->nDb; i++) {
117345      Btree *pBt = db->aDb[i].pBt;
117346      if( pBt ){
117347        assert( sqlite3BtreeHoldsMutex(pBt) );
117348        rc = sqlite3BtreeSchemaLocked(pBt);
117349        if( rc ){
117350          const char *zDb = db->aDb[i].zDbSName;
117351          sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
117352          testcase( db->flags & SQLITE_ReadUncommit );
117353          goto end_prepare;
117354        }
117355      }
117356    }
117357  
117358    sqlite3VtabUnlockList(db);
117359  
117360    sParse.db = db;
117361    if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
117362      char *zSqlCopy;
117363      int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
117364      testcase( nBytes==mxLen );
117365      testcase( nBytes==mxLen+1 );
117366      if( nBytes>mxLen ){
117367        sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
117368        rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
117369        goto end_prepare;
117370      }
117371      zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
117372      if( zSqlCopy ){
117373        sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
117374        sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
117375        sqlite3DbFree(db, zSqlCopy);
117376      }else{
117377        sParse.zTail = &zSql[nBytes];
117378      }
117379    }else{
117380      sqlite3RunParser(&sParse, zSql, &zErrMsg);
117381    }
117382    assert( 0==sParse.nQueryLoop );
117383  
117384    if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
117385    if( sParse.checkSchema ){
117386      schemaIsValid(&sParse);
117387    }
117388    if( db->mallocFailed ){
117389      sParse.rc = SQLITE_NOMEM_BKPT;
117390    }
117391    if( pzTail ){
117392      *pzTail = sParse.zTail;
117393    }
117394    rc = sParse.rc;
117395  
117396  #ifndef SQLITE_OMIT_EXPLAIN
117397    if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
117398      static const char * const azColName[] = {
117399         "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
117400         "selectid", "order", "from", "detail"
117401      };
117402      int iFirst, mx;
117403      if( sParse.explain==2 ){
117404        sqlite3VdbeSetNumCols(sParse.pVdbe, 4);
117405        iFirst = 8;
117406        mx = 12;
117407      }else{
117408        sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
117409        iFirst = 0;
117410        mx = 8;
117411      }
117412      for(i=iFirst; i<mx; i++){
117413        sqlite3VdbeSetColName(sParse.pVdbe, i-iFirst, COLNAME_NAME,
117414                              azColName[i], SQLITE_STATIC);
117415      }
117416    }
117417  #endif
117418  
117419    if( db->init.busy==0 ){
117420      sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);
117421    }
117422    if( sParse.pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
117423      sqlite3VdbeFinalize(sParse.pVdbe);
117424      assert(!(*ppStmt));
117425    }else{
117426      *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
117427    }
117428  
117429    if( zErrMsg ){
117430      sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
117431      sqlite3DbFree(db, zErrMsg);
117432    }else{
117433      sqlite3Error(db, rc);
117434    }
117435  
117436    /* Delete any TriggerPrg structures allocated while parsing this statement. */
117437    while( sParse.pTriggerPrg ){
117438      TriggerPrg *pT = sParse.pTriggerPrg;
117439      sParse.pTriggerPrg = pT->pNext;
117440      sqlite3DbFree(db, pT);
117441    }
117442  
117443  end_prepare:
117444  
117445    sqlite3ParserReset(&sParse);
117446    rc = sqlite3ApiExit(db, rc);
117447    assert( (rc&db->errMask)==rc );
117448    return rc;
117449  }
117450  static int sqlite3LockAndPrepare(
117451    sqlite3 *db,              /* Database handle. */
117452    const char *zSql,         /* UTF-8 encoded SQL statement. */
117453    int nBytes,               /* Length of zSql in bytes. */
117454    u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
117455    Vdbe *pOld,               /* VM being reprepared */
117456    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
117457    const char **pzTail       /* OUT: End of parsed string */
117458  ){
117459    int rc;
117460  
117461  #ifdef SQLITE_ENABLE_API_ARMOR
117462    if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
117463  #endif
117464    *ppStmt = 0;
117465    if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
117466      return SQLITE_MISUSE_BKPT;
117467    }
117468    sqlite3_mutex_enter(db->mutex);
117469    sqlite3BtreeEnterAll(db);
117470    rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
117471    if( rc==SQLITE_SCHEMA ){
117472      sqlite3ResetOneSchema(db, -1);
117473      sqlite3_finalize(*ppStmt);
117474      rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
117475    }
117476    sqlite3BtreeLeaveAll(db);
117477    sqlite3_mutex_leave(db->mutex);
117478    assert( rc==SQLITE_OK || *ppStmt==0 );
117479    return rc;
117480  }
117481  
117482  /*
117483  ** Rerun the compilation of a statement after a schema change.
117484  **
117485  ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
117486  ** if the statement cannot be recompiled because another connection has
117487  ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
117488  ** occurs, return SQLITE_SCHEMA.
117489  */
117490  SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
117491    int rc;
117492    sqlite3_stmt *pNew;
117493    const char *zSql;
117494    sqlite3 *db;
117495    u8 prepFlags;
117496  
117497    assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
117498    zSql = sqlite3_sql((sqlite3_stmt *)p);
117499    assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
117500    db = sqlite3VdbeDb(p);
117501    assert( sqlite3_mutex_held(db->mutex) );
117502    prepFlags = sqlite3VdbePrepareFlags(p);
117503    rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0);
117504    if( rc ){
117505      if( rc==SQLITE_NOMEM ){
117506        sqlite3OomFault(db);
117507      }
117508      assert( pNew==0 );
117509      return rc;
117510    }else{
117511      assert( pNew!=0 );
117512    }
117513    sqlite3VdbeSwap((Vdbe*)pNew, p);
117514    sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
117515    sqlite3VdbeResetStepResult((Vdbe*)pNew);
117516    sqlite3VdbeFinalize((Vdbe*)pNew);
117517    return SQLITE_OK;
117518  }
117519  
117520  
117521  /*
117522  ** Two versions of the official API.  Legacy and new use.  In the legacy
117523  ** version, the original SQL text is not saved in the prepared statement
117524  ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
117525  ** sqlite3_step().  In the new version, the original SQL text is retained
117526  ** and the statement is automatically recompiled if an schema change
117527  ** occurs.
117528  */
117529  SQLITE_API int sqlite3_prepare(
117530    sqlite3 *db,              /* Database handle. */
117531    const char *zSql,         /* UTF-8 encoded SQL statement. */
117532    int nBytes,               /* Length of zSql in bytes. */
117533    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
117534    const char **pzTail       /* OUT: End of parsed string */
117535  ){
117536    int rc;
117537    rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
117538    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
117539    return rc;
117540  }
117541  SQLITE_API int sqlite3_prepare_v2(
117542    sqlite3 *db,              /* Database handle. */
117543    const char *zSql,         /* UTF-8 encoded SQL statement. */
117544    int nBytes,               /* Length of zSql in bytes. */
117545    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
117546    const char **pzTail       /* OUT: End of parsed string */
117547  ){
117548    int rc;
117549    /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works
117550    ** exactly the same as sqlite3_prepare_v3() with a zero prepFlags
117551    ** parameter.
117552    **
117553    ** Proof in that the 5th parameter to sqlite3LockAndPrepare is 0 */
117554    rc = sqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0,
117555                               ppStmt,pzTail);
117556    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
117557    return rc;
117558  }
117559  SQLITE_API int sqlite3_prepare_v3(
117560    sqlite3 *db,              /* Database handle. */
117561    const char *zSql,         /* UTF-8 encoded SQL statement. */
117562    int nBytes,               /* Length of zSql in bytes. */
117563    unsigned int prepFlags,   /* Zero or more SQLITE_PREPARE_* flags */
117564    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
117565    const char **pzTail       /* OUT: End of parsed string */
117566  ){
117567    int rc;
117568    /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from
117569    ** sqlite3_prepare_v2() only in having the extra prepFlags parameter,
117570    ** which is a bit array consisting of zero or more of the
117571    ** SQLITE_PREPARE_* flags.
117572    **
117573    ** Proof by comparison to the implementation of sqlite3_prepare_v2()
117574    ** directly above. */
117575    rc = sqlite3LockAndPrepare(db,zSql,nBytes,
117576                   SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
117577                   0,ppStmt,pzTail);
117578    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
117579    return rc;
117580  }
117581  
117582  
117583  #ifndef SQLITE_OMIT_UTF16
117584  /*
117585  ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
117586  */
117587  static int sqlite3Prepare16(
117588    sqlite3 *db,              /* Database handle. */ 
117589    const void *zSql,         /* UTF-16 encoded SQL statement. */
117590    int nBytes,               /* Length of zSql in bytes. */
117591    u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
117592    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
117593    const void **pzTail       /* OUT: End of parsed string */
117594  ){
117595    /* This function currently works by first transforming the UTF-16
117596    ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
117597    ** tricky bit is figuring out the pointer to return in *pzTail.
117598    */
117599    char *zSql8;
117600    const char *zTail8 = 0;
117601    int rc = SQLITE_OK;
117602  
117603  #ifdef SQLITE_ENABLE_API_ARMOR
117604    if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
117605  #endif
117606    *ppStmt = 0;
117607    if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
117608      return SQLITE_MISUSE_BKPT;
117609    }
117610    if( nBytes>=0 ){
117611      int sz;
117612      const char *z = (const char*)zSql;
117613      for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
117614      nBytes = sz;
117615    }
117616    sqlite3_mutex_enter(db->mutex);
117617    zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
117618    if( zSql8 ){
117619      rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8);
117620    }
117621  
117622    if( zTail8 && pzTail ){
117623      /* If sqlite3_prepare returns a tail pointer, we calculate the
117624      ** equivalent pointer into the UTF-16 string by counting the unicode
117625      ** characters between zSql8 and zTail8, and then returning a pointer
117626      ** the same number of characters into the UTF-16 string.
117627      */
117628      int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
117629      *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
117630    }
117631    sqlite3DbFree(db, zSql8); 
117632    rc = sqlite3ApiExit(db, rc);
117633    sqlite3_mutex_leave(db->mutex);
117634    return rc;
117635  }
117636  
117637  /*
117638  ** Two versions of the official API.  Legacy and new use.  In the legacy
117639  ** version, the original SQL text is not saved in the prepared statement
117640  ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
117641  ** sqlite3_step().  In the new version, the original SQL text is retained
117642  ** and the statement is automatically recompiled if an schema change
117643  ** occurs.
117644  */
117645  SQLITE_API int sqlite3_prepare16(
117646    sqlite3 *db,              /* Database handle. */ 
117647    const void *zSql,         /* UTF-16 encoded SQL statement. */
117648    int nBytes,               /* Length of zSql in bytes. */
117649    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
117650    const void **pzTail       /* OUT: End of parsed string */
117651  ){
117652    int rc;
117653    rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
117654    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
117655    return rc;
117656  }
117657  SQLITE_API int sqlite3_prepare16_v2(
117658    sqlite3 *db,              /* Database handle. */ 
117659    const void *zSql,         /* UTF-16 encoded SQL statement. */
117660    int nBytes,               /* Length of zSql in bytes. */
117661    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
117662    const void **pzTail       /* OUT: End of parsed string */
117663  ){
117664    int rc;
117665    rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
117666    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
117667    return rc;
117668  }
117669  SQLITE_API int sqlite3_prepare16_v3(
117670    sqlite3 *db,              /* Database handle. */ 
117671    const void *zSql,         /* UTF-16 encoded SQL statement. */
117672    int nBytes,               /* Length of zSql in bytes. */
117673    unsigned int prepFlags,   /* Zero or more SQLITE_PREPARE_* flags */
117674    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
117675    const void **pzTail       /* OUT: End of parsed string */
117676  ){
117677    int rc;
117678    rc = sqlite3Prepare16(db,zSql,nBytes,
117679           SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
117680           ppStmt,pzTail);
117681    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
117682    return rc;
117683  }
117684  
117685  #endif /* SQLITE_OMIT_UTF16 */
117686  
117687  /************** End of prepare.c *********************************************/
117688  /************** Begin file select.c ******************************************/
117689  /*
117690  ** 2001 September 15
117691  **
117692  ** The author disclaims copyright to this source code.  In place of
117693  ** a legal notice, here is a blessing:
117694  **
117695  **    May you do good and not evil.
117696  **    May you find forgiveness for yourself and forgive others.
117697  **    May you share freely, never taking more than you give.
117698  **
117699  *************************************************************************
117700  ** This file contains C code routines that are called by the parser
117701  ** to handle SELECT statements in SQLite.
117702  */
117703  /* #include "sqliteInt.h" */
117704  
117705  /*
117706  ** Trace output macros
117707  */
117708  #if SELECTTRACE_ENABLED
117709  /***/ int sqlite3SelectTrace = 0;
117710  # define SELECTTRACE(K,P,S,X)  \
117711    if(sqlite3SelectTrace&(K))   \
117712      sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
117713          (S)->zSelName,(S)),\
117714      sqlite3DebugPrintf X
117715  #else
117716  # define SELECTTRACE(K,P,S,X)
117717  #endif
117718  
117719  
117720  /*
117721  ** An instance of the following object is used to record information about
117722  ** how to process the DISTINCT keyword, to simplify passing that information
117723  ** into the selectInnerLoop() routine.
117724  */
117725  typedef struct DistinctCtx DistinctCtx;
117726  struct DistinctCtx {
117727    u8 isTnct;      /* True if the DISTINCT keyword is present */
117728    u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
117729    int tabTnct;    /* Ephemeral table used for DISTINCT processing */
117730    int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
117731  };
117732  
117733  /*
117734  ** An instance of the following object is used to record information about
117735  ** the ORDER BY (or GROUP BY) clause of query is being coded.
117736  */
117737  typedef struct SortCtx SortCtx;
117738  struct SortCtx {
117739    ExprList *pOrderBy;   /* The ORDER BY (or GROUP BY clause) */
117740    int nOBSat;           /* Number of ORDER BY terms satisfied by indices */
117741    int iECursor;         /* Cursor number for the sorter */
117742    int regReturn;        /* Register holding block-output return address */
117743    int labelBkOut;       /* Start label for the block-output subroutine */
117744    int addrSortIndex;    /* Address of the OP_SorterOpen or OP_OpenEphemeral */
117745    int labelDone;        /* Jump here when done, ex: LIMIT reached */
117746    u8 sortFlags;         /* Zero or more SORTFLAG_* bits */
117747    u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */
117748  };
117749  #define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */
117750  
117751  /*
117752  ** Delete all the content of a Select structure.  Deallocate the structure
117753  ** itself only if bFree is true.
117754  */
117755  static void clearSelect(sqlite3 *db, Select *p, int bFree){
117756    while( p ){
117757      Select *pPrior = p->pPrior;
117758      sqlite3ExprListDelete(db, p->pEList);
117759      sqlite3SrcListDelete(db, p->pSrc);
117760      sqlite3ExprDelete(db, p->pWhere);
117761      sqlite3ExprListDelete(db, p->pGroupBy);
117762      sqlite3ExprDelete(db, p->pHaving);
117763      sqlite3ExprListDelete(db, p->pOrderBy);
117764      sqlite3ExprDelete(db, p->pLimit);
117765      sqlite3ExprDelete(db, p->pOffset);
117766      if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
117767      if( bFree ) sqlite3DbFreeNN(db, p);
117768      p = pPrior;
117769      bFree = 1;
117770    }
117771  }
117772  
117773  /*
117774  ** Initialize a SelectDest structure.
117775  */
117776  SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
117777    pDest->eDest = (u8)eDest;
117778    pDest->iSDParm = iParm;
117779    pDest->zAffSdst = 0;
117780    pDest->iSdst = 0;
117781    pDest->nSdst = 0;
117782  }
117783  
117784  
117785  /*
117786  ** Allocate a new Select structure and return a pointer to that
117787  ** structure.
117788  */
117789  SQLITE_PRIVATE Select *sqlite3SelectNew(
117790    Parse *pParse,        /* Parsing context */
117791    ExprList *pEList,     /* which columns to include in the result */
117792    SrcList *pSrc,        /* the FROM clause -- which tables to scan */
117793    Expr *pWhere,         /* the WHERE clause */
117794    ExprList *pGroupBy,   /* the GROUP BY clause */
117795    Expr *pHaving,        /* the HAVING clause */
117796    ExprList *pOrderBy,   /* the ORDER BY clause */
117797    u32 selFlags,         /* Flag parameters, such as SF_Distinct */
117798    Expr *pLimit,         /* LIMIT value.  NULL means not used */
117799    Expr *pOffset         /* OFFSET value.  NULL means no offset */
117800  ){
117801    Select *pNew;
117802    Select standin;
117803    pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
117804    if( pNew==0 ){
117805      assert( pParse->db->mallocFailed );
117806      pNew = &standin;
117807    }
117808    if( pEList==0 ){
117809      pEList = sqlite3ExprListAppend(pParse, 0,
117810                                     sqlite3Expr(pParse->db,TK_ASTERISK,0));
117811    }
117812    pNew->pEList = pEList;
117813    pNew->op = TK_SELECT;
117814    pNew->selFlags = selFlags;
117815    pNew->iLimit = 0;
117816    pNew->iOffset = 0;
117817  #if SELECTTRACE_ENABLED
117818    pNew->zSelName[0] = 0;
117819  #endif
117820    pNew->addrOpenEphm[0] = -1;
117821    pNew->addrOpenEphm[1] = -1;
117822    pNew->nSelectRow = 0;
117823    if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
117824    pNew->pSrc = pSrc;
117825    pNew->pWhere = pWhere;
117826    pNew->pGroupBy = pGroupBy;
117827    pNew->pHaving = pHaving;
117828    pNew->pOrderBy = pOrderBy;
117829    pNew->pPrior = 0;
117830    pNew->pNext = 0;
117831    pNew->pLimit = pLimit;
117832    pNew->pOffset = pOffset;
117833    pNew->pWith = 0;
117834    assert( pOffset==0 || pLimit!=0 || pParse->nErr>0
117835                       || pParse->db->mallocFailed!=0 );
117836    if( pParse->db->mallocFailed ) {
117837      clearSelect(pParse->db, pNew, pNew!=&standin);
117838      pNew = 0;
117839    }else{
117840      assert( pNew->pSrc!=0 || pParse->nErr>0 );
117841    }
117842    assert( pNew!=&standin );
117843    return pNew;
117844  }
117845  
117846  #if SELECTTRACE_ENABLED
117847  /*
117848  ** Set the name of a Select object
117849  */
117850  SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
117851    if( p && zName ){
117852      sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
117853    }
117854  }
117855  #endif
117856  
117857  
117858  /*
117859  ** Delete the given Select structure and all of its substructures.
117860  */
117861  SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
117862    if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);
117863  }
117864  
117865  /*
117866  ** Return a pointer to the right-most SELECT statement in a compound.
117867  */
117868  static Select *findRightmost(Select *p){
117869    while( p->pNext ) p = p->pNext;
117870    return p;
117871  }
117872  
117873  /*
117874  ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
117875  ** type of join.  Return an integer constant that expresses that type
117876  ** in terms of the following bit values:
117877  **
117878  **     JT_INNER
117879  **     JT_CROSS
117880  **     JT_OUTER
117881  **     JT_NATURAL
117882  **     JT_LEFT
117883  **     JT_RIGHT
117884  **
117885  ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
117886  **
117887  ** If an illegal or unsupported join type is seen, then still return
117888  ** a join type, but put an error in the pParse structure.
117889  */
117890  SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
117891    int jointype = 0;
117892    Token *apAll[3];
117893    Token *p;
117894                               /*   0123456789 123456789 123456789 123 */
117895    static const char zKeyText[] = "naturaleftouterightfullinnercross";
117896    static const struct {
117897      u8 i;        /* Beginning of keyword text in zKeyText[] */
117898      u8 nChar;    /* Length of the keyword in characters */
117899      u8 code;     /* Join type mask */
117900    } aKeyword[] = {
117901      /* natural */ { 0,  7, JT_NATURAL                },
117902      /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
117903      /* outer   */ { 10, 5, JT_OUTER                  },
117904      /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
117905      /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
117906      /* inner   */ { 23, 5, JT_INNER                  },
117907      /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
117908    };
117909    int i, j;
117910    apAll[0] = pA;
117911    apAll[1] = pB;
117912    apAll[2] = pC;
117913    for(i=0; i<3 && apAll[i]; i++){
117914      p = apAll[i];
117915      for(j=0; j<ArraySize(aKeyword); j++){
117916        if( p->n==aKeyword[j].nChar 
117917            && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
117918          jointype |= aKeyword[j].code;
117919          break;
117920        }
117921      }
117922      testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
117923      if( j>=ArraySize(aKeyword) ){
117924        jointype |= JT_ERROR;
117925        break;
117926      }
117927    }
117928    if(
117929       (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
117930       (jointype & JT_ERROR)!=0
117931    ){
117932      const char *zSp = " ";
117933      assert( pB!=0 );
117934      if( pC==0 ){ zSp++; }
117935      sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
117936         "%T %T%s%T", pA, pB, zSp, pC);
117937      jointype = JT_INNER;
117938    }else if( (jointype & JT_OUTER)!=0 
117939           && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
117940      sqlite3ErrorMsg(pParse, 
117941        "RIGHT and FULL OUTER JOINs are not currently supported");
117942      jointype = JT_INNER;
117943    }
117944    return jointype;
117945  }
117946  
117947  /*
117948  ** Return the index of a column in a table.  Return -1 if the column
117949  ** is not contained in the table.
117950  */
117951  static int columnIndex(Table *pTab, const char *zCol){
117952    int i;
117953    for(i=0; i<pTab->nCol; i++){
117954      if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
117955    }
117956    return -1;
117957  }
117958  
117959  /*
117960  ** Search the first N tables in pSrc, from left to right, looking for a
117961  ** table that has a column named zCol.  
117962  **
117963  ** When found, set *piTab and *piCol to the table index and column index
117964  ** of the matching column and return TRUE.
117965  **
117966  ** If not found, return FALSE.
117967  */
117968  static int tableAndColumnIndex(
117969    SrcList *pSrc,       /* Array of tables to search */
117970    int N,               /* Number of tables in pSrc->a[] to search */
117971    const char *zCol,    /* Name of the column we are looking for */
117972    int *piTab,          /* Write index of pSrc->a[] here */
117973    int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
117974  ){
117975    int i;               /* For looping over tables in pSrc */
117976    int iCol;            /* Index of column matching zCol */
117977  
117978    assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
117979    for(i=0; i<N; i++){
117980      iCol = columnIndex(pSrc->a[i].pTab, zCol);
117981      if( iCol>=0 ){
117982        if( piTab ){
117983          *piTab = i;
117984          *piCol = iCol;
117985        }
117986        return 1;
117987      }
117988    }
117989    return 0;
117990  }
117991  
117992  /*
117993  ** This function is used to add terms implied by JOIN syntax to the
117994  ** WHERE clause expression of a SELECT statement. The new term, which
117995  ** is ANDed with the existing WHERE clause, is of the form:
117996  **
117997  **    (tab1.col1 = tab2.col2)
117998  **
117999  ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
118000  ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
118001  ** column iColRight of tab2.
118002  */
118003  static void addWhereTerm(
118004    Parse *pParse,                  /* Parsing context */
118005    SrcList *pSrc,                  /* List of tables in FROM clause */
118006    int iLeft,                      /* Index of first table to join in pSrc */
118007    int iColLeft,                   /* Index of column in first table */
118008    int iRight,                     /* Index of second table in pSrc */
118009    int iColRight,                  /* Index of column in second table */
118010    int isOuterJoin,                /* True if this is an OUTER join */
118011    Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
118012  ){
118013    sqlite3 *db = pParse->db;
118014    Expr *pE1;
118015    Expr *pE2;
118016    Expr *pEq;
118017  
118018    assert( iLeft<iRight );
118019    assert( pSrc->nSrc>iRight );
118020    assert( pSrc->a[iLeft].pTab );
118021    assert( pSrc->a[iRight].pTab );
118022  
118023    pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
118024    pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
118025  
118026    pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
118027    if( pEq && isOuterJoin ){
118028      ExprSetProperty(pEq, EP_FromJoin);
118029      assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
118030      ExprSetVVAProperty(pEq, EP_NoReduce);
118031      pEq->iRightJoinTable = (i16)pE2->iTable;
118032    }
118033    *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
118034  }
118035  
118036  /*
118037  ** Set the EP_FromJoin property on all terms of the given expression.
118038  ** And set the Expr.iRightJoinTable to iTable for every term in the
118039  ** expression.
118040  **
118041  ** The EP_FromJoin property is used on terms of an expression to tell
118042  ** the LEFT OUTER JOIN processing logic that this term is part of the
118043  ** join restriction specified in the ON or USING clause and not a part
118044  ** of the more general WHERE clause.  These terms are moved over to the
118045  ** WHERE clause during join processing but we need to remember that they
118046  ** originated in the ON or USING clause.
118047  **
118048  ** The Expr.iRightJoinTable tells the WHERE clause processing that the
118049  ** expression depends on table iRightJoinTable even if that table is not
118050  ** explicitly mentioned in the expression.  That information is needed
118051  ** for cases like this:
118052  **
118053  **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
118054  **
118055  ** The where clause needs to defer the handling of the t1.x=5
118056  ** term until after the t2 loop of the join.  In that way, a
118057  ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
118058  ** defer the handling of t1.x=5, it will be processed immediately
118059  ** after the t1 loop and rows with t1.x!=5 will never appear in
118060  ** the output, which is incorrect.
118061  */
118062  static void setJoinExpr(Expr *p, int iTable){
118063    while( p ){
118064      ExprSetProperty(p, EP_FromJoin);
118065      assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
118066      ExprSetVVAProperty(p, EP_NoReduce);
118067      p->iRightJoinTable = (i16)iTable;
118068      if( p->op==TK_FUNCTION && p->x.pList ){
118069        int i;
118070        for(i=0; i<p->x.pList->nExpr; i++){
118071          setJoinExpr(p->x.pList->a[i].pExpr, iTable);
118072        }
118073      }
118074      setJoinExpr(p->pLeft, iTable);
118075      p = p->pRight;
118076    } 
118077  }
118078  
118079  /*
118080  ** This routine processes the join information for a SELECT statement.
118081  ** ON and USING clauses are converted into extra terms of the WHERE clause.
118082  ** NATURAL joins also create extra WHERE clause terms.
118083  **
118084  ** The terms of a FROM clause are contained in the Select.pSrc structure.
118085  ** The left most table is the first entry in Select.pSrc.  The right-most
118086  ** table is the last entry.  The join operator is held in the entry to
118087  ** the left.  Thus entry 0 contains the join operator for the join between
118088  ** entries 0 and 1.  Any ON or USING clauses associated with the join are
118089  ** also attached to the left entry.
118090  **
118091  ** This routine returns the number of errors encountered.
118092  */
118093  static int sqliteProcessJoin(Parse *pParse, Select *p){
118094    SrcList *pSrc;                  /* All tables in the FROM clause */
118095    int i, j;                       /* Loop counters */
118096    struct SrcList_item *pLeft;     /* Left table being joined */
118097    struct SrcList_item *pRight;    /* Right table being joined */
118098  
118099    pSrc = p->pSrc;
118100    pLeft = &pSrc->a[0];
118101    pRight = &pLeft[1];
118102    for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
118103      Table *pRightTab = pRight->pTab;
118104      int isOuter;
118105  
118106      if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;
118107      isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
118108  
118109      /* When the NATURAL keyword is present, add WHERE clause terms for
118110      ** every column that the two tables have in common.
118111      */
118112      if( pRight->fg.jointype & JT_NATURAL ){
118113        if( pRight->pOn || pRight->pUsing ){
118114          sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
118115             "an ON or USING clause", 0);
118116          return 1;
118117        }
118118        for(j=0; j<pRightTab->nCol; j++){
118119          char *zName;   /* Name of column in the right table */
118120          int iLeft;     /* Matching left table */
118121          int iLeftCol;  /* Matching column in the left table */
118122  
118123          zName = pRightTab->aCol[j].zName;
118124          if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
118125            addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
118126                         isOuter, &p->pWhere);
118127          }
118128        }
118129      }
118130  
118131      /* Disallow both ON and USING clauses in the same join
118132      */
118133      if( pRight->pOn && pRight->pUsing ){
118134        sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
118135          "clauses in the same join");
118136        return 1;
118137      }
118138  
118139      /* Add the ON clause to the end of the WHERE clause, connected by
118140      ** an AND operator.
118141      */
118142      if( pRight->pOn ){
118143        if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
118144        p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
118145        pRight->pOn = 0;
118146      }
118147  
118148      /* Create extra terms on the WHERE clause for each column named
118149      ** in the USING clause.  Example: If the two tables to be joined are 
118150      ** A and B and the USING clause names X, Y, and Z, then add this
118151      ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
118152      ** Report an error if any column mentioned in the USING clause is
118153      ** not contained in both tables to be joined.
118154      */
118155      if( pRight->pUsing ){
118156        IdList *pList = pRight->pUsing;
118157        for(j=0; j<pList->nId; j++){
118158          char *zName;     /* Name of the term in the USING clause */
118159          int iLeft;       /* Table on the left with matching column name */
118160          int iLeftCol;    /* Column number of matching column on the left */
118161          int iRightCol;   /* Column number of matching column on the right */
118162  
118163          zName = pList->a[j].zName;
118164          iRightCol = columnIndex(pRightTab, zName);
118165          if( iRightCol<0
118166           || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
118167          ){
118168            sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
118169              "not present in both tables", zName);
118170            return 1;
118171          }
118172          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
118173                       isOuter, &p->pWhere);
118174        }
118175      }
118176    }
118177    return 0;
118178  }
118179  
118180  /* Forward reference */
118181  static KeyInfo *keyInfoFromExprList(
118182    Parse *pParse,       /* Parsing context */
118183    ExprList *pList,     /* Form the KeyInfo object from this ExprList */
118184    int iStart,          /* Begin with this column of pList */
118185    int nExtra           /* Add this many extra columns to the end */
118186  );
118187  
118188  /*
118189  ** Generate code that will push the record in registers regData
118190  ** through regData+nData-1 onto the sorter.
118191  */
118192  static void pushOntoSorter(
118193    Parse *pParse,         /* Parser context */
118194    SortCtx *pSort,        /* Information about the ORDER BY clause */
118195    Select *pSelect,       /* The whole SELECT statement */
118196    int regData,           /* First register holding data to be sorted */
118197    int regOrigData,       /* First register holding data before packing */
118198    int nData,             /* Number of elements in the data array */
118199    int nPrefixReg         /* No. of reg prior to regData available for use */
118200  ){
118201    Vdbe *v = pParse->pVdbe;                         /* Stmt under construction */
118202    int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
118203    int nExpr = pSort->pOrderBy->nExpr;              /* No. of ORDER BY terms */
118204    int nBase = nExpr + bSeq + nData;                /* Fields in sorter record */
118205    int regBase;                                     /* Regs for sorter record */
118206    int regRecord = ++pParse->nMem;                  /* Assembled sorter record */
118207    int nOBSat = pSort->nOBSat;                      /* ORDER BY terms to skip */
118208    int op;                            /* Opcode to add sorter record to sorter */
118209    int iLimit;                        /* LIMIT counter */
118210  
118211    assert( bSeq==0 || bSeq==1 );
118212    assert( nData==1 || regData==regOrigData || regOrigData==0 );
118213    if( nPrefixReg ){
118214      assert( nPrefixReg==nExpr+bSeq );
118215      regBase = regData - nExpr - bSeq;
118216    }else{
118217      regBase = pParse->nMem + 1;
118218      pParse->nMem += nBase;
118219    }
118220    assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
118221    iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
118222    pSort->labelDone = sqlite3VdbeMakeLabel(v);
118223    sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
118224                            SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
118225    if( bSeq ){
118226      sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
118227    }
118228    if( nPrefixReg==0 && nData>0 ){
118229      sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
118230    }
118231    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
118232    if( nOBSat>0 ){
118233      int regPrevKey;   /* The first nOBSat columns of the previous row */
118234      int addrFirst;    /* Address of the OP_IfNot opcode */
118235      int addrJmp;      /* Address of the OP_Jump opcode */
118236      VdbeOp *pOp;      /* Opcode that opens the sorter */
118237      int nKey;         /* Number of sorting key columns, including OP_Sequence */
118238      KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
118239  
118240      regPrevKey = pParse->nMem+1;
118241      pParse->nMem += pSort->nOBSat;
118242      nKey = nExpr - pSort->nOBSat + bSeq;
118243      if( bSeq ){
118244        addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); 
118245      }else{
118246        addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
118247      }
118248      VdbeCoverage(v);
118249      sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
118250      pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
118251      if( pParse->db->mallocFailed ) return;
118252      pOp->p2 = nKey + nData;
118253      pKI = pOp->p4.pKeyInfo;
118254      memset(pKI->aSortOrder, 0, pKI->nKeyField); /* Makes OP_Jump testable */
118255      sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
118256      testcase( pKI->nAllField > pKI->nKeyField+2 );
118257      pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
118258                                             pKI->nAllField-pKI->nKeyField-1);
118259      addrJmp = sqlite3VdbeCurrentAddr(v);
118260      sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
118261      pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
118262      pSort->regReturn = ++pParse->nMem;
118263      sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
118264      sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
118265      if( iLimit ){
118266        sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
118267        VdbeCoverage(v);
118268      }
118269      sqlite3VdbeJumpHere(v, addrFirst);
118270      sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
118271      sqlite3VdbeJumpHere(v, addrJmp);
118272    }
118273    if( pSort->sortFlags & SORTFLAG_UseSorter ){
118274      op = OP_SorterInsert;
118275    }else{
118276      op = OP_IdxInsert;
118277    }
118278    sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
118279                         regBase+nOBSat, nBase-nOBSat);
118280    if( iLimit ){
118281      int addr;
118282      int r1 = 0;
118283      /* Fill the sorter until it contains LIMIT+OFFSET entries.  (The iLimit
118284      ** register is initialized with value of LIMIT+OFFSET.)  After the sorter
118285      ** fills up, delete the least entry in the sorter after each insert.
118286      ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */
118287      addr = sqlite3VdbeAddOp1(v, OP_IfNotZero, iLimit); VdbeCoverage(v);
118288      sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
118289      if( pSort->bOrderedInnerLoop ){
118290        r1 = ++pParse->nMem;
118291        sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1);
118292        VdbeComment((v, "seq"));
118293      }
118294      sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
118295      if( pSort->bOrderedInnerLoop ){
118296        /* If the inner loop is driven by an index such that values from
118297        ** the same iteration of the inner loop are in sorted order, then
118298        ** immediately jump to the next iteration of an inner loop if the
118299        ** entry from the current iteration does not fit into the top
118300        ** LIMIT+OFFSET entries of the sorter. */
118301        int iBrk = sqlite3VdbeCurrentAddr(v) + 2;
118302        sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1);
118303        sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
118304        VdbeCoverage(v);
118305      }
118306      sqlite3VdbeJumpHere(v, addr);
118307    }
118308  }
118309  
118310  /*
118311  ** Add code to implement the OFFSET
118312  */
118313  static void codeOffset(
118314    Vdbe *v,          /* Generate code into this VM */
118315    int iOffset,      /* Register holding the offset counter */
118316    int iContinue     /* Jump here to skip the current record */
118317  ){
118318    if( iOffset>0 ){
118319      sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
118320      VdbeComment((v, "OFFSET"));
118321    }
118322  }
118323  
118324  /*
118325  ** Add code that will check to make sure the N registers starting at iMem
118326  ** form a distinct entry.  iTab is a sorting index that holds previously
118327  ** seen combinations of the N values.  A new entry is made in iTab
118328  ** if the current N values are new.
118329  **
118330  ** A jump to addrRepeat is made and the N+1 values are popped from the
118331  ** stack if the top N elements are not distinct.
118332  */
118333  static void codeDistinct(
118334    Parse *pParse,     /* Parsing and code generating context */
118335    int iTab,          /* A sorting index used to test for distinctness */
118336    int addrRepeat,    /* Jump to here if not distinct */
118337    int N,             /* Number of elements */
118338    int iMem           /* First element */
118339  ){
118340    Vdbe *v;
118341    int r1;
118342  
118343    v = pParse->pVdbe;
118344    r1 = sqlite3GetTempReg(pParse);
118345    sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
118346    sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
118347    sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
118348    sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
118349    sqlite3ReleaseTempReg(pParse, r1);
118350  }
118351  
118352  /*
118353  ** This routine generates the code for the inside of the inner loop
118354  ** of a SELECT.
118355  **
118356  ** If srcTab is negative, then the p->pEList expressions
118357  ** are evaluated in order to get the data for this row.  If srcTab is
118358  ** zero or more, then data is pulled from srcTab and p->pEList is used only 
118359  ** to get the number of columns and the collation sequence for each column.
118360  */
118361  static void selectInnerLoop(
118362    Parse *pParse,          /* The parser context */
118363    Select *p,              /* The complete select statement being coded */
118364    int srcTab,             /* Pull data from this table if non-negative */
118365    SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */
118366    DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
118367    SelectDest *pDest,      /* How to dispose of the results */
118368    int iContinue,          /* Jump here to continue with next row */
118369    int iBreak              /* Jump here to break out of the inner loop */
118370  ){
118371    Vdbe *v = pParse->pVdbe;
118372    int i;
118373    int hasDistinct;            /* True if the DISTINCT keyword is present */
118374    int eDest = pDest->eDest;   /* How to dispose of results */
118375    int iParm = pDest->iSDParm; /* First argument to disposal method */
118376    int nResultCol;             /* Number of result columns */
118377    int nPrefixReg = 0;         /* Number of extra registers before regResult */
118378  
118379    /* Usually, regResult is the first cell in an array of memory cells
118380    ** containing the current result row. In this case regOrig is set to the
118381    ** same value. However, if the results are being sent to the sorter, the
118382    ** values for any expressions that are also part of the sort-key are omitted
118383    ** from this array. In this case regOrig is set to zero.  */
118384    int regResult;              /* Start of memory holding current results */
118385    int regOrig;                /* Start of memory holding full result (or 0) */
118386  
118387    assert( v );
118388    assert( p->pEList!=0 );
118389    hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
118390    if( pSort && pSort->pOrderBy==0 ) pSort = 0;
118391    if( pSort==0 && !hasDistinct ){
118392      assert( iContinue!=0 );
118393      codeOffset(v, p->iOffset, iContinue);
118394    }
118395  
118396    /* Pull the requested columns.
118397    */
118398    nResultCol = p->pEList->nExpr;
118399  
118400    if( pDest->iSdst==0 ){
118401      if( pSort ){
118402        nPrefixReg = pSort->pOrderBy->nExpr;
118403        if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
118404        pParse->nMem += nPrefixReg;
118405      }
118406      pDest->iSdst = pParse->nMem+1;
118407      pParse->nMem += nResultCol;
118408    }else if( pDest->iSdst+nResultCol > pParse->nMem ){
118409      /* This is an error condition that can result, for example, when a SELECT
118410      ** on the right-hand side of an INSERT contains more result columns than
118411      ** there are columns in the table on the left.  The error will be caught
118412      ** and reported later.  But we need to make sure enough memory is allocated
118413      ** to avoid other spurious errors in the meantime. */
118414      pParse->nMem += nResultCol;
118415    }
118416    pDest->nSdst = nResultCol;
118417    regOrig = regResult = pDest->iSdst;
118418    if( srcTab>=0 ){
118419      for(i=0; i<nResultCol; i++){
118420        sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
118421        VdbeComment((v, "%s", p->pEList->a[i].zName));
118422      }
118423    }else if( eDest!=SRT_Exists ){
118424      /* If the destination is an EXISTS(...) expression, the actual
118425      ** values returned by the SELECT are not required.
118426      */
118427      u8 ecelFlags;
118428      if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
118429        ecelFlags = SQLITE_ECEL_DUP;
118430      }else{
118431        ecelFlags = 0;
118432      }
118433      if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
118434        /* For each expression in p->pEList that is a copy of an expression in
118435        ** the ORDER BY clause (pSort->pOrderBy), set the associated 
118436        ** iOrderByCol value to one more than the index of the ORDER BY 
118437        ** expression within the sort-key that pushOntoSorter() will generate.
118438        ** This allows the p->pEList field to be omitted from the sorted record,
118439        ** saving space and CPU cycles.  */
118440        ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
118441        for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
118442          int j;
118443          if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
118444            p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
118445          }
118446        }
118447        regOrig = 0;
118448        assert( eDest==SRT_Set || eDest==SRT_Mem 
118449             || eDest==SRT_Coroutine || eDest==SRT_Output );
118450      }
118451      nResultCol = sqlite3ExprCodeExprList(pParse,p->pEList,regResult,
118452                                           0,ecelFlags);
118453    }
118454  
118455    /* If the DISTINCT keyword was present on the SELECT statement
118456    ** and this row has been seen before, then do not make this row
118457    ** part of the result.
118458    */
118459    if( hasDistinct ){
118460      switch( pDistinct->eTnctType ){
118461        case WHERE_DISTINCT_ORDERED: {
118462          VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
118463          int iJump;              /* Jump destination */
118464          int regPrev;            /* Previous row content */
118465  
118466          /* Allocate space for the previous row */
118467          regPrev = pParse->nMem+1;
118468          pParse->nMem += nResultCol;
118469  
118470          /* Change the OP_OpenEphemeral coded earlier to an OP_Null
118471          ** sets the MEM_Cleared bit on the first register of the
118472          ** previous value.  This will cause the OP_Ne below to always
118473          ** fail on the first iteration of the loop even if the first
118474          ** row is all NULLs.
118475          */
118476          sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
118477          pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
118478          pOp->opcode = OP_Null;
118479          pOp->p1 = 1;
118480          pOp->p2 = regPrev;
118481  
118482          iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
118483          for(i=0; i<nResultCol; i++){
118484            CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
118485            if( i<nResultCol-1 ){
118486              sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
118487              VdbeCoverage(v);
118488            }else{
118489              sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
118490              VdbeCoverage(v);
118491             }
118492            sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
118493            sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
118494          }
118495          assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
118496          sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
118497          break;
118498        }
118499  
118500        case WHERE_DISTINCT_UNIQUE: {
118501          sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
118502          break;
118503        }
118504  
118505        default: {
118506          assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
118507          codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
118508                       regResult);
118509          break;
118510        }
118511      }
118512      if( pSort==0 ){
118513        codeOffset(v, p->iOffset, iContinue);
118514      }
118515    }
118516  
118517    switch( eDest ){
118518      /* In this mode, write each query result to the key of the temporary
118519      ** table iParm.
118520      */
118521  #ifndef SQLITE_OMIT_COMPOUND_SELECT
118522      case SRT_Union: {
118523        int r1;
118524        r1 = sqlite3GetTempReg(pParse);
118525        sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
118526        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
118527        sqlite3ReleaseTempReg(pParse, r1);
118528        break;
118529      }
118530  
118531      /* Construct a record from the query result, but instead of
118532      ** saving that record, use it as a key to delete elements from
118533      ** the temporary table iParm.
118534      */
118535      case SRT_Except: {
118536        sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
118537        break;
118538      }
118539  #endif /* SQLITE_OMIT_COMPOUND_SELECT */
118540  
118541      /* Store the result as data using a unique key.
118542      */
118543      case SRT_Fifo:
118544      case SRT_DistFifo:
118545      case SRT_Table:
118546      case SRT_EphemTab: {
118547        int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
118548        testcase( eDest==SRT_Table );
118549        testcase( eDest==SRT_EphemTab );
118550        testcase( eDest==SRT_Fifo );
118551        testcase( eDest==SRT_DistFifo );
118552        sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
118553  #ifndef SQLITE_OMIT_CTE
118554        if( eDest==SRT_DistFifo ){
118555          /* If the destination is DistFifo, then cursor (iParm+1) is open
118556          ** on an ephemeral index. If the current row is already present
118557          ** in the index, do not write it to the output. If not, add the
118558          ** current row to the index and proceed with writing it to the
118559          ** output table as well.  */
118560          int addr = sqlite3VdbeCurrentAddr(v) + 4;
118561          sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
118562          VdbeCoverage(v);
118563          sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
118564          assert( pSort==0 );
118565        }
118566  #endif
118567        if( pSort ){
118568          pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
118569        }else{
118570          int r2 = sqlite3GetTempReg(pParse);
118571          sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
118572          sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
118573          sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
118574          sqlite3ReleaseTempReg(pParse, r2);
118575        }
118576        sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
118577        break;
118578      }
118579  
118580  #ifndef SQLITE_OMIT_SUBQUERY
118581      /* If we are creating a set for an "expr IN (SELECT ...)" construct,
118582      ** then there should be a single item on the stack.  Write this
118583      ** item into the set table with bogus data.
118584      */
118585      case SRT_Set: {
118586        if( pSort ){
118587          /* At first glance you would think we could optimize out the
118588          ** ORDER BY in this case since the order of entries in the set
118589          ** does not matter.  But there might be a LIMIT clause, in which
118590          ** case the order does matter */
118591          pushOntoSorter(
118592              pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
118593        }else{
118594          int r1 = sqlite3GetTempReg(pParse);
118595          assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
118596          sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol, 
118597              r1, pDest->zAffSdst, nResultCol);
118598          sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
118599          sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
118600          sqlite3ReleaseTempReg(pParse, r1);
118601        }
118602        break;
118603      }
118604  
118605      /* If any row exist in the result set, record that fact and abort.
118606      */
118607      case SRT_Exists: {
118608        sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
118609        /* The LIMIT clause will terminate the loop for us */
118610        break;
118611      }
118612  
118613      /* If this is a scalar select that is part of an expression, then
118614      ** store the results in the appropriate memory cell or array of 
118615      ** memory cells and break out of the scan loop.
118616      */
118617      case SRT_Mem: {
118618        if( pSort ){
118619          assert( nResultCol<=pDest->nSdst );
118620          pushOntoSorter(
118621              pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
118622        }else{
118623          assert( nResultCol==pDest->nSdst );
118624          assert( regResult==iParm );
118625          /* The LIMIT clause will jump out of the loop for us */
118626        }
118627        break;
118628      }
118629  #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
118630  
118631      case SRT_Coroutine:       /* Send data to a co-routine */
118632      case SRT_Output: {        /* Return the results */
118633        testcase( eDest==SRT_Coroutine );
118634        testcase( eDest==SRT_Output );
118635        if( pSort ){
118636          pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
118637                         nPrefixReg);
118638        }else if( eDest==SRT_Coroutine ){
118639          sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
118640        }else{
118641          sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
118642          sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
118643        }
118644        break;
118645      }
118646  
118647  #ifndef SQLITE_OMIT_CTE
118648      /* Write the results into a priority queue that is order according to
118649      ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
118650      ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
118651      ** pSO->nExpr columns, then make sure all keys are unique by adding a
118652      ** final OP_Sequence column.  The last column is the record as a blob.
118653      */
118654      case SRT_DistQueue:
118655      case SRT_Queue: {
118656        int nKey;
118657        int r1, r2, r3;
118658        int addrTest = 0;
118659        ExprList *pSO;
118660        pSO = pDest->pOrderBy;
118661        assert( pSO );
118662        nKey = pSO->nExpr;
118663        r1 = sqlite3GetTempReg(pParse);
118664        r2 = sqlite3GetTempRange(pParse, nKey+2);
118665        r3 = r2+nKey+1;
118666        if( eDest==SRT_DistQueue ){
118667          /* If the destination is DistQueue, then cursor (iParm+1) is open
118668          ** on a second ephemeral index that holds all values every previously
118669          ** added to the queue. */
118670          addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, 
118671                                          regResult, nResultCol);
118672          VdbeCoverage(v);
118673        }
118674        sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
118675        if( eDest==SRT_DistQueue ){
118676          sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
118677          sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
118678        }
118679        for(i=0; i<nKey; i++){
118680          sqlite3VdbeAddOp2(v, OP_SCopy,
118681                            regResult + pSO->a[i].u.x.iOrderByCol - 1,
118682                            r2+i);
118683        }
118684        sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
118685        sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
118686        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
118687        if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
118688        sqlite3ReleaseTempReg(pParse, r1);
118689        sqlite3ReleaseTempRange(pParse, r2, nKey+2);
118690        break;
118691      }
118692  #endif /* SQLITE_OMIT_CTE */
118693  
118694  
118695  
118696  #if !defined(SQLITE_OMIT_TRIGGER)
118697      /* Discard the results.  This is used for SELECT statements inside
118698      ** the body of a TRIGGER.  The purpose of such selects is to call
118699      ** user-defined functions that have side effects.  We do not care
118700      ** about the actual results of the select.
118701      */
118702      default: {
118703        assert( eDest==SRT_Discard );
118704        break;
118705      }
118706  #endif
118707    }
118708  
118709    /* Jump to the end of the loop if the LIMIT is reached.  Except, if
118710    ** there is a sorter, in which case the sorter has already limited
118711    ** the output for us.
118712    */
118713    if( pSort==0 && p->iLimit ){
118714      sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
118715    }
118716  }
118717  
118718  /*
118719  ** Allocate a KeyInfo object sufficient for an index of N key columns and
118720  ** X extra columns.
118721  */
118722  SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
118723    int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
118724    KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
118725    if( p ){
118726      p->aSortOrder = (u8*)&p->aColl[N+X];
118727      p->nKeyField = (u16)N;
118728      p->nAllField = (u16)(N+X);
118729      p->enc = ENC(db);
118730      p->db = db;
118731      p->nRef = 1;
118732      memset(&p[1], 0, nExtra);
118733    }else{
118734      sqlite3OomFault(db);
118735    }
118736    return p;
118737  }
118738  
118739  /*
118740  ** Deallocate a KeyInfo object
118741  */
118742  SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
118743    if( p ){
118744      assert( p->nRef>0 );
118745      p->nRef--;
118746      if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p);
118747    }
118748  }
118749  
118750  /*
118751  ** Make a new pointer to a KeyInfo object
118752  */
118753  SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
118754    if( p ){
118755      assert( p->nRef>0 );
118756      p->nRef++;
118757    }
118758    return p;
118759  }
118760  
118761  #ifdef SQLITE_DEBUG
118762  /*
118763  ** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
118764  ** can only be changed if this is just a single reference to the object.
118765  **
118766  ** This routine is used only inside of assert() statements.
118767  */
118768  SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
118769  #endif /* SQLITE_DEBUG */
118770  
118771  /*
118772  ** Given an expression list, generate a KeyInfo structure that records
118773  ** the collating sequence for each expression in that expression list.
118774  **
118775  ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
118776  ** KeyInfo structure is appropriate for initializing a virtual index to
118777  ** implement that clause.  If the ExprList is the result set of a SELECT
118778  ** then the KeyInfo structure is appropriate for initializing a virtual
118779  ** index to implement a DISTINCT test.
118780  **
118781  ** Space to hold the KeyInfo structure is obtained from malloc.  The calling
118782  ** function is responsible for seeing that this structure is eventually
118783  ** freed.
118784  */
118785  static KeyInfo *keyInfoFromExprList(
118786    Parse *pParse,       /* Parsing context */
118787    ExprList *pList,     /* Form the KeyInfo object from this ExprList */
118788    int iStart,          /* Begin with this column of pList */
118789    int nExtra           /* Add this many extra columns to the end */
118790  ){
118791    int nExpr;
118792    KeyInfo *pInfo;
118793    struct ExprList_item *pItem;
118794    sqlite3 *db = pParse->db;
118795    int i;
118796  
118797    nExpr = pList->nExpr;
118798    pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
118799    if( pInfo ){
118800      assert( sqlite3KeyInfoIsWriteable(pInfo) );
118801      for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
118802        pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
118803        pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
118804      }
118805    }
118806    return pInfo;
118807  }
118808  
118809  /*
118810  ** Name of the connection operator, used for error messages.
118811  */
118812  static const char *selectOpName(int id){
118813    char *z;
118814    switch( id ){
118815      case TK_ALL:       z = "UNION ALL";   break;
118816      case TK_INTERSECT: z = "INTERSECT";   break;
118817      case TK_EXCEPT:    z = "EXCEPT";      break;
118818      default:           z = "UNION";       break;
118819    }
118820    return z;
118821  }
118822  
118823  #ifndef SQLITE_OMIT_EXPLAIN
118824  /*
118825  ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
118826  ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
118827  ** where the caption is of the form:
118828  **
118829  **   "USE TEMP B-TREE FOR xxx"
118830  **
118831  ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
118832  ** is determined by the zUsage argument.
118833  */
118834  static void explainTempTable(Parse *pParse, const char *zUsage){
118835    if( pParse->explain==2 ){
118836      Vdbe *v = pParse->pVdbe;
118837      char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
118838      sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
118839    }
118840  }
118841  
118842  /*
118843  ** Assign expression b to lvalue a. A second, no-op, version of this macro
118844  ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
118845  ** in sqlite3Select() to assign values to structure member variables that
118846  ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
118847  ** code with #ifndef directives.
118848  */
118849  # define explainSetInteger(a, b) a = b
118850  
118851  #else
118852  /* No-op versions of the explainXXX() functions and macros. */
118853  # define explainTempTable(y,z)
118854  # define explainSetInteger(y,z)
118855  #endif
118856  
118857  #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
118858  /*
118859  ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
118860  ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
118861  ** where the caption is of one of the two forms:
118862  **
118863  **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
118864  **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
118865  **
118866  ** where iSub1 and iSub2 are the integers passed as the corresponding
118867  ** function parameters, and op is the text representation of the parameter
118868  ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
118869  ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 
118870  ** false, or the second form if it is true.
118871  */
118872  static void explainComposite(
118873    Parse *pParse,                  /* Parse context */
118874    int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
118875    int iSub1,                      /* Subquery id 1 */
118876    int iSub2,                      /* Subquery id 2 */
118877    int bUseTmp                     /* True if a temp table was used */
118878  ){
118879    assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
118880    if( pParse->explain==2 ){
118881      Vdbe *v = pParse->pVdbe;
118882      char *zMsg = sqlite3MPrintf(
118883          pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
118884          bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
118885      );
118886      sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
118887    }
118888  }
118889  #else
118890  /* No-op versions of the explainXXX() functions and macros. */
118891  # define explainComposite(v,w,x,y,z)
118892  #endif
118893  
118894  /*
118895  ** If the inner loop was generated using a non-null pOrderBy argument,
118896  ** then the results were placed in a sorter.  After the loop is terminated
118897  ** we need to run the sorter and output the results.  The following
118898  ** routine generates the code needed to do that.
118899  */
118900  static void generateSortTail(
118901    Parse *pParse,    /* Parsing context */
118902    Select *p,        /* The SELECT statement */
118903    SortCtx *pSort,   /* Information on the ORDER BY clause */
118904    int nColumn,      /* Number of columns of data */
118905    SelectDest *pDest /* Write the sorted results here */
118906  ){
118907    Vdbe *v = pParse->pVdbe;                     /* The prepared statement */
118908    int addrBreak = pSort->labelDone;            /* Jump here to exit loop */
118909    int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
118910    int addr;
118911    int addrOnce = 0;
118912    int iTab;
118913    ExprList *pOrderBy = pSort->pOrderBy;
118914    int eDest = pDest->eDest;
118915    int iParm = pDest->iSDParm;
118916    int regRow;
118917    int regRowid;
118918    int iCol;
118919    int nKey;
118920    int iSortTab;                   /* Sorter cursor to read from */
118921    int nSortData;                  /* Trailing values to read from sorter */
118922    int i;
118923    int bSeq;                       /* True if sorter record includes seq. no. */
118924    struct ExprList_item *aOutEx = p->pEList->a;
118925  
118926    assert( addrBreak<0 );
118927    if( pSort->labelBkOut ){
118928      sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
118929      sqlite3VdbeGoto(v, addrBreak);
118930      sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
118931    }
118932    iTab = pSort->iECursor;
118933    if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
118934      regRowid = 0;
118935      regRow = pDest->iSdst;
118936      nSortData = nColumn;
118937    }else{
118938      regRowid = sqlite3GetTempReg(pParse);
118939      regRow = sqlite3GetTempRange(pParse, nColumn);
118940      nSortData = nColumn;
118941    }
118942    nKey = pOrderBy->nExpr - pSort->nOBSat;
118943    if( pSort->sortFlags & SORTFLAG_UseSorter ){
118944      int regSortOut = ++pParse->nMem;
118945      iSortTab = pParse->nTab++;
118946      if( pSort->labelBkOut ){
118947        addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
118948      }
118949      sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
118950      if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
118951      addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
118952      VdbeCoverage(v);
118953      codeOffset(v, p->iOffset, addrContinue);
118954      sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
118955      bSeq = 0;
118956    }else{
118957      addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
118958      codeOffset(v, p->iOffset, addrContinue);
118959      iSortTab = iTab;
118960      bSeq = 1;
118961    }
118962    for(i=0, iCol=nKey+bSeq; i<nSortData; i++){
118963      int iRead;
118964      if( aOutEx[i].u.x.iOrderByCol ){
118965        iRead = aOutEx[i].u.x.iOrderByCol-1;
118966      }else{
118967        iRead = iCol++;
118968      }
118969      sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
118970      VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
118971    }
118972    switch( eDest ){
118973      case SRT_Table:
118974      case SRT_EphemTab: {
118975        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
118976        sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
118977        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
118978        break;
118979      }
118980  #ifndef SQLITE_OMIT_SUBQUERY
118981      case SRT_Set: {
118982        assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
118983        sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
118984                          pDest->zAffSdst, nColumn);
118985        sqlite3ExprCacheAffinityChange(pParse, regRow, nColumn);
118986        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
118987        break;
118988      }
118989      case SRT_Mem: {
118990        /* The LIMIT clause will terminate the loop for us */
118991        break;
118992      }
118993  #endif
118994      default: {
118995        assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
118996        testcase( eDest==SRT_Output );
118997        testcase( eDest==SRT_Coroutine );
118998        if( eDest==SRT_Output ){
118999          sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
119000          sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
119001        }else{
119002          sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
119003        }
119004        break;
119005      }
119006    }
119007    if( regRowid ){
119008      if( eDest==SRT_Set ){
119009        sqlite3ReleaseTempRange(pParse, regRow, nColumn);
119010      }else{
119011        sqlite3ReleaseTempReg(pParse, regRow);
119012      }
119013      sqlite3ReleaseTempReg(pParse, regRowid);
119014    }
119015    /* The bottom of the loop
119016    */
119017    sqlite3VdbeResolveLabel(v, addrContinue);
119018    if( pSort->sortFlags & SORTFLAG_UseSorter ){
119019      sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
119020    }else{
119021      sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
119022    }
119023    if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
119024    sqlite3VdbeResolveLabel(v, addrBreak);
119025  }
119026  
119027  /*
119028  ** Return a pointer to a string containing the 'declaration type' of the
119029  ** expression pExpr. The string may be treated as static by the caller.
119030  **
119031  ** Also try to estimate the size of the returned value and return that
119032  ** result in *pEstWidth.
119033  **
119034  ** The declaration type is the exact datatype definition extracted from the
119035  ** original CREATE TABLE statement if the expression is a column. The
119036  ** declaration type for a ROWID field is INTEGER. Exactly when an expression
119037  ** is considered a column can be complex in the presence of subqueries. The
119038  ** result-set expression in all of the following SELECT statements is 
119039  ** considered a column by this function.
119040  **
119041  **   SELECT col FROM tbl;
119042  **   SELECT (SELECT col FROM tbl;
119043  **   SELECT (SELECT col FROM tbl);
119044  **   SELECT abc FROM (SELECT col AS abc FROM tbl);
119045  ** 
119046  ** The declaration type for any expression other than a column is NULL.
119047  **
119048  ** This routine has either 3 or 6 parameters depending on whether or not
119049  ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
119050  */
119051  #ifdef SQLITE_ENABLE_COLUMN_METADATA
119052  # define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)
119053  #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
119054  # define columnType(A,B,C,D,E) columnTypeImpl(A,B)
119055  #endif
119056  static const char *columnTypeImpl(
119057    NameContext *pNC, 
119058  #ifndef SQLITE_ENABLE_COLUMN_METADATA
119059    Expr *pExpr
119060  #else
119061    Expr *pExpr,
119062    const char **pzOrigDb,
119063    const char **pzOrigTab,
119064    const char **pzOrigCol
119065  #endif
119066  ){
119067    char const *zType = 0;
119068    int j;
119069  #ifdef SQLITE_ENABLE_COLUMN_METADATA
119070    char const *zOrigDb = 0;
119071    char const *zOrigTab = 0;
119072    char const *zOrigCol = 0;
119073  #endif
119074  
119075    assert( pExpr!=0 );
119076    assert( pNC->pSrcList!=0 );
119077    switch( pExpr->op ){
119078      case TK_AGG_COLUMN:
119079      case TK_COLUMN: {
119080        /* The expression is a column. Locate the table the column is being
119081        ** extracted from in NameContext.pSrcList. This table may be real
119082        ** database table or a subquery.
119083        */
119084        Table *pTab = 0;            /* Table structure column is extracted from */
119085        Select *pS = 0;             /* Select the column is extracted from */
119086        int iCol = pExpr->iColumn;  /* Index of column in pTab */
119087        testcase( pExpr->op==TK_AGG_COLUMN );
119088        testcase( pExpr->op==TK_COLUMN );
119089        while( pNC && !pTab ){
119090          SrcList *pTabList = pNC->pSrcList;
119091          for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
119092          if( j<pTabList->nSrc ){
119093            pTab = pTabList->a[j].pTab;
119094            pS = pTabList->a[j].pSelect;
119095          }else{
119096            pNC = pNC->pNext;
119097          }
119098        }
119099  
119100        if( pTab==0 ){
119101          /* At one time, code such as "SELECT new.x" within a trigger would
119102          ** cause this condition to run.  Since then, we have restructured how
119103          ** trigger code is generated and so this condition is no longer 
119104          ** possible. However, it can still be true for statements like
119105          ** the following:
119106          **
119107          **   CREATE TABLE t1(col INTEGER);
119108          **   SELECT (SELECT t1.col) FROM FROM t1;
119109          **
119110          ** when columnType() is called on the expression "t1.col" in the 
119111          ** sub-select. In this case, set the column type to NULL, even
119112          ** though it should really be "INTEGER".
119113          **
119114          ** This is not a problem, as the column type of "t1.col" is never
119115          ** used. When columnType() is called on the expression 
119116          ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
119117          ** branch below.  */
119118          break;
119119        }
119120  
119121        assert( pTab && pExpr->pTab==pTab );
119122        if( pS ){
119123          /* The "table" is actually a sub-select or a view in the FROM clause
119124          ** of the SELECT statement. Return the declaration type and origin
119125          ** data for the result-set column of the sub-select.
119126          */
119127          if( iCol>=0 && iCol<pS->pEList->nExpr ){
119128            /* If iCol is less than zero, then the expression requests the
119129            ** rowid of the sub-select or view. This expression is legal (see 
119130            ** test case misc2.2.2) - it always evaluates to NULL.
119131            */
119132            NameContext sNC;
119133            Expr *p = pS->pEList->a[iCol].pExpr;
119134            sNC.pSrcList = pS->pSrc;
119135            sNC.pNext = pNC;
119136            sNC.pParse = pNC->pParse;
119137            zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol); 
119138          }
119139        }else{
119140          /* A real table or a CTE table */
119141          assert( !pS );
119142  #ifdef SQLITE_ENABLE_COLUMN_METADATA
119143          if( iCol<0 ) iCol = pTab->iPKey;
119144          assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
119145          if( iCol<0 ){
119146            zType = "INTEGER";
119147            zOrigCol = "rowid";
119148          }else{
119149            zOrigCol = pTab->aCol[iCol].zName;
119150            zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
119151          }
119152          zOrigTab = pTab->zName;
119153          if( pNC->pParse && pTab->pSchema ){
119154            int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
119155            zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
119156          }
119157  #else
119158          assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
119159          if( iCol<0 ){
119160            zType = "INTEGER";
119161          }else{
119162            zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
119163          }
119164  #endif
119165        }
119166        break;
119167      }
119168  #ifndef SQLITE_OMIT_SUBQUERY
119169      case TK_SELECT: {
119170        /* The expression is a sub-select. Return the declaration type and
119171        ** origin info for the single column in the result set of the SELECT
119172        ** statement.
119173        */
119174        NameContext sNC;
119175        Select *pS = pExpr->x.pSelect;
119176        Expr *p = pS->pEList->a[0].pExpr;
119177        assert( ExprHasProperty(pExpr, EP_xIsSelect) );
119178        sNC.pSrcList = pS->pSrc;
119179        sNC.pNext = pNC;
119180        sNC.pParse = pNC->pParse;
119181        zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 
119182        break;
119183      }
119184  #endif
119185    }
119186  
119187  #ifdef SQLITE_ENABLE_COLUMN_METADATA  
119188    if( pzOrigDb ){
119189      assert( pzOrigTab && pzOrigCol );
119190      *pzOrigDb = zOrigDb;
119191      *pzOrigTab = zOrigTab;
119192      *pzOrigCol = zOrigCol;
119193    }
119194  #endif
119195    return zType;
119196  }
119197  
119198  /*
119199  ** Generate code that will tell the VDBE the declaration types of columns
119200  ** in the result set.
119201  */
119202  static void generateColumnTypes(
119203    Parse *pParse,      /* Parser context */
119204    SrcList *pTabList,  /* List of tables */
119205    ExprList *pEList    /* Expressions defining the result set */
119206  ){
119207  #ifndef SQLITE_OMIT_DECLTYPE
119208    Vdbe *v = pParse->pVdbe;
119209    int i;
119210    NameContext sNC;
119211    sNC.pSrcList = pTabList;
119212    sNC.pParse = pParse;
119213    sNC.pNext = 0;
119214    for(i=0; i<pEList->nExpr; i++){
119215      Expr *p = pEList->a[i].pExpr;
119216      const char *zType;
119217  #ifdef SQLITE_ENABLE_COLUMN_METADATA
119218      const char *zOrigDb = 0;
119219      const char *zOrigTab = 0;
119220      const char *zOrigCol = 0;
119221      zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
119222  
119223      /* The vdbe must make its own copy of the column-type and other 
119224      ** column specific strings, in case the schema is reset before this
119225      ** virtual machine is deleted.
119226      */
119227      sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
119228      sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
119229      sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
119230  #else
119231      zType = columnType(&sNC, p, 0, 0, 0);
119232  #endif
119233      sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
119234    }
119235  #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
119236  }
119237  
119238  
119239  /*
119240  ** Compute the column names for a SELECT statement.
119241  **
119242  ** The only guarantee that SQLite makes about column names is that if the
119243  ** column has an AS clause assigning it a name, that will be the name used.
119244  ** That is the only documented guarantee.  However, countless applications
119245  ** developed over the years have made baseless assumptions about column names
119246  ** and will break if those assumptions changes.  Hence, use extreme caution
119247  ** when modifying this routine to avoid breaking legacy.
119248  **
119249  ** See Also: sqlite3ColumnsFromExprList()
119250  **
119251  ** The PRAGMA short_column_names and PRAGMA full_column_names settings are
119252  ** deprecated.  The default setting is short=ON, full=OFF.  99.9% of all
119253  ** applications should operate this way.  Nevertheless, we need to support the
119254  ** other modes for legacy:
119255  **
119256  **    short=OFF, full=OFF:      Column name is the text of the expression has it
119257  **                              originally appears in the SELECT statement.  In
119258  **                              other words, the zSpan of the result expression.
119259  **
119260  **    short=ON, full=OFF:       (This is the default setting).  If the result
119261  **                              refers directly to a table column, then the
119262  **                              result column name is just the table column
119263  **                              name: COLUMN.  Otherwise use zSpan.
119264  **
119265  **    full=ON, short=ANY:       If the result refers directly to a table column,
119266  **                              then the result column name with the table name
119267  **                              prefix, ex: TABLE.COLUMN.  Otherwise use zSpan.
119268  */
119269  static void generateColumnNames(
119270    Parse *pParse,      /* Parser context */
119271    Select *pSelect     /* Generate column names for this SELECT statement */
119272  ){
119273    Vdbe *v = pParse->pVdbe;
119274    int i;
119275    Table *pTab;
119276    SrcList *pTabList;
119277    ExprList *pEList;
119278    sqlite3 *db = pParse->db;
119279    int fullName;    /* TABLE.COLUMN if no AS clause and is a direct table ref */
119280    int srcName;     /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
119281  
119282  #ifndef SQLITE_OMIT_EXPLAIN
119283    /* If this is an EXPLAIN, skip this step */
119284    if( pParse->explain ){
119285      return;
119286    }
119287  #endif
119288  
119289    if( pParse->colNamesSet || db->mallocFailed ) return;
119290    /* Column names are determined by the left-most term of a compound select */
119291    while( pSelect->pPrior ) pSelect = pSelect->pPrior;
119292    pTabList = pSelect->pSrc;
119293    pEList = pSelect->pEList;
119294    assert( v!=0 );
119295    assert( pTabList!=0 );
119296    pParse->colNamesSet = 1;
119297    fullName = (db->flags & SQLITE_FullColNames)!=0;
119298    srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
119299    sqlite3VdbeSetNumCols(v, pEList->nExpr);
119300    for(i=0; i<pEList->nExpr; i++){
119301      Expr *p = pEList->a[i].pExpr;
119302  
119303      assert( p!=0 );
119304      assert( p->op!=TK_AGG_COLUMN );  /* Agg processing has not run yet */
119305      assert( p->op!=TK_COLUMN || p->pTab!=0 ); /* Covering idx not yet coded */
119306      if( pEList->a[i].zName ){
119307        /* An AS clause always takes first priority */
119308        char *zName = pEList->a[i].zName;
119309        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
119310      }else if( srcName && p->op==TK_COLUMN ){
119311        char *zCol;
119312        int iCol = p->iColumn;
119313        pTab = p->pTab;
119314        assert( pTab!=0 );
119315        if( iCol<0 ) iCol = pTab->iPKey;
119316        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
119317        if( iCol<0 ){
119318          zCol = "rowid";
119319        }else{
119320          zCol = pTab->aCol[iCol].zName;
119321        }
119322        if( fullName ){
119323          char *zName = 0;
119324          zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
119325          sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
119326        }else{
119327          sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
119328        }
119329      }else{
119330        const char *z = pEList->a[i].zSpan;
119331        z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
119332        sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
119333      }
119334    }
119335    generateColumnTypes(pParse, pTabList, pEList);
119336  }
119337  
119338  /*
119339  ** Given an expression list (which is really the list of expressions
119340  ** that form the result set of a SELECT statement) compute appropriate
119341  ** column names for a table that would hold the expression list.
119342  **
119343  ** All column names will be unique.
119344  **
119345  ** Only the column names are computed.  Column.zType, Column.zColl,
119346  ** and other fields of Column are zeroed.
119347  **
119348  ** Return SQLITE_OK on success.  If a memory allocation error occurs,
119349  ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
119350  **
119351  ** The only guarantee that SQLite makes about column names is that if the
119352  ** column has an AS clause assigning it a name, that will be the name used.
119353  ** That is the only documented guarantee.  However, countless applications
119354  ** developed over the years have made baseless assumptions about column names
119355  ** and will break if those assumptions changes.  Hence, use extreme caution
119356  ** when modifying this routine to avoid breaking legacy.
119357  **
119358  ** See Also: generateColumnNames()
119359  */
119360  SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
119361    Parse *pParse,          /* Parsing context */
119362    ExprList *pEList,       /* Expr list from which to derive column names */
119363    i16 *pnCol,             /* Write the number of columns here */
119364    Column **paCol          /* Write the new column list here */
119365  ){
119366    sqlite3 *db = pParse->db;   /* Database connection */
119367    int i, j;                   /* Loop counters */
119368    u32 cnt;                    /* Index added to make the name unique */
119369    Column *aCol, *pCol;        /* For looping over result columns */
119370    int nCol;                   /* Number of columns in the result set */
119371    char *zName;                /* Column name */
119372    int nName;                  /* Size of name in zName[] */
119373    Hash ht;                    /* Hash table of column names */
119374  
119375    sqlite3HashInit(&ht);
119376    if( pEList ){
119377      nCol = pEList->nExpr;
119378      aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
119379      testcase( aCol==0 );
119380      if( nCol>32767 ) nCol = 32767;
119381    }else{
119382      nCol = 0;
119383      aCol = 0;
119384    }
119385    assert( nCol==(i16)nCol );
119386    *pnCol = nCol;
119387    *paCol = aCol;
119388  
119389    for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
119390      /* Get an appropriate name for the column
119391      */
119392      if( (zName = pEList->a[i].zName)!=0 ){
119393        /* If the column contains an "AS <name>" phrase, use <name> as the name */
119394      }else{
119395        Expr *pColExpr = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
119396        while( pColExpr->op==TK_DOT ){
119397          pColExpr = pColExpr->pRight;
119398          assert( pColExpr!=0 );
119399        }
119400        if( (pColExpr->op==TK_COLUMN || pColExpr->op==TK_AGG_COLUMN)
119401         && pColExpr->pTab!=0 
119402        ){
119403          /* For columns use the column name name */
119404          int iCol = pColExpr->iColumn;
119405          Table *pTab = pColExpr->pTab;
119406          if( iCol<0 ) iCol = pTab->iPKey;
119407          zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
119408        }else if( pColExpr->op==TK_ID ){
119409          assert( !ExprHasProperty(pColExpr, EP_IntValue) );
119410          zName = pColExpr->u.zToken;
119411        }else{
119412          /* Use the original text of the column expression as its name */
119413          zName = pEList->a[i].zSpan;
119414        }
119415      }
119416      if( zName ){
119417        zName = sqlite3DbStrDup(db, zName);
119418      }else{
119419        zName = sqlite3MPrintf(db,"column%d",i+1);
119420      }
119421  
119422      /* Make sure the column name is unique.  If the name is not unique,
119423      ** append an integer to the name so that it becomes unique.
119424      */
119425      cnt = 0;
119426      while( zName && sqlite3HashFind(&ht, zName)!=0 ){
119427        nName = sqlite3Strlen30(zName);
119428        if( nName>0 ){
119429          for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
119430          if( zName[j]==':' ) nName = j;
119431        }
119432        zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
119433        if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
119434      }
119435      pCol->zName = zName;
119436      sqlite3ColumnPropertiesFromName(0, pCol);
119437      if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
119438        sqlite3OomFault(db);
119439      }
119440    }
119441    sqlite3HashClear(&ht);
119442    if( db->mallocFailed ){
119443      for(j=0; j<i; j++){
119444        sqlite3DbFree(db, aCol[j].zName);
119445      }
119446      sqlite3DbFree(db, aCol);
119447      *paCol = 0;
119448      *pnCol = 0;
119449      return SQLITE_NOMEM_BKPT;
119450    }
119451    return SQLITE_OK;
119452  }
119453  
119454  /*
119455  ** Add type and collation information to a column list based on
119456  ** a SELECT statement.
119457  ** 
119458  ** The column list presumably came from selectColumnNamesFromExprList().
119459  ** The column list has only names, not types or collations.  This
119460  ** routine goes through and adds the types and collations.
119461  **
119462  ** This routine requires that all identifiers in the SELECT
119463  ** statement be resolved.
119464  */
119465  SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
119466    Parse *pParse,        /* Parsing contexts */
119467    Table *pTab,          /* Add column type information to this table */
119468    Select *pSelect       /* SELECT used to determine types and collations */
119469  ){
119470    sqlite3 *db = pParse->db;
119471    NameContext sNC;
119472    Column *pCol;
119473    CollSeq *pColl;
119474    int i;
119475    Expr *p;
119476    struct ExprList_item *a;
119477  
119478    assert( pSelect!=0 );
119479    assert( (pSelect->selFlags & SF_Resolved)!=0 );
119480    assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
119481    if( db->mallocFailed ) return;
119482    memset(&sNC, 0, sizeof(sNC));
119483    sNC.pSrcList = pSelect->pSrc;
119484    a = pSelect->pEList->a;
119485    for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
119486      const char *zType;
119487      int n, m;
119488      p = a[i].pExpr;
119489      zType = columnType(&sNC, p, 0, 0, 0);
119490      /* pCol->szEst = ... // Column size est for SELECT tables never used */
119491      pCol->affinity = sqlite3ExprAffinity(p);
119492      if( zType ){
119493        m = sqlite3Strlen30(zType);
119494        n = sqlite3Strlen30(pCol->zName);
119495        pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
119496        if( pCol->zName ){
119497          memcpy(&pCol->zName[n+1], zType, m+1);
119498          pCol->colFlags |= COLFLAG_HASTYPE;
119499        }
119500      }
119501      if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
119502      pColl = sqlite3ExprCollSeq(pParse, p);
119503      if( pColl && pCol->zColl==0 ){
119504        pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
119505      }
119506    }
119507    pTab->szTabRow = 1; /* Any non-zero value works */
119508  }
119509  
119510  /*
119511  ** Given a SELECT statement, generate a Table structure that describes
119512  ** the result set of that SELECT.
119513  */
119514  SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
119515    Table *pTab;
119516    sqlite3 *db = pParse->db;
119517    int savedFlags;
119518  
119519    savedFlags = db->flags;
119520    db->flags &= ~SQLITE_FullColNames;
119521    db->flags |= SQLITE_ShortColNames;
119522    sqlite3SelectPrep(pParse, pSelect, 0);
119523    if( pParse->nErr ) return 0;
119524    while( pSelect->pPrior ) pSelect = pSelect->pPrior;
119525    db->flags = savedFlags;
119526    pTab = sqlite3DbMallocZero(db, sizeof(Table) );
119527    if( pTab==0 ){
119528      return 0;
119529    }
119530    /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
119531    ** is disabled */
119532    assert( db->lookaside.bDisable );
119533    pTab->nTabRef = 1;
119534    pTab->zName = 0;
119535    pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
119536    sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
119537    sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
119538    pTab->iPKey = -1;
119539    if( db->mallocFailed ){
119540      sqlite3DeleteTable(db, pTab);
119541      return 0;
119542    }
119543    return pTab;
119544  }
119545  
119546  /*
119547  ** Get a VDBE for the given parser context.  Create a new one if necessary.
119548  ** If an error occurs, return NULL and leave a message in pParse.
119549  */
119550  SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
119551    if( pParse->pVdbe ){
119552      return pParse->pVdbe;
119553    }
119554    if( pParse->pToplevel==0
119555     && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
119556    ){
119557      pParse->okConstFactor = 1;
119558    }
119559    return sqlite3VdbeCreate(pParse);
119560  }
119561  
119562  
119563  /*
119564  ** Compute the iLimit and iOffset fields of the SELECT based on the
119565  ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
119566  ** that appear in the original SQL statement after the LIMIT and OFFSET
119567  ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
119568  ** are the integer memory register numbers for counters used to compute 
119569  ** the limit and offset.  If there is no limit and/or offset, then 
119570  ** iLimit and iOffset are negative.
119571  **
119572  ** This routine changes the values of iLimit and iOffset only if
119573  ** a limit or offset is defined by pLimit and pOffset.  iLimit and
119574  ** iOffset should have been preset to appropriate default values (zero)
119575  ** prior to calling this routine.
119576  **
119577  ** The iOffset register (if it exists) is initialized to the value
119578  ** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
119579  ** iOffset+1 is initialized to LIMIT+OFFSET.
119580  **
119581  ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
119582  ** redefined.  The UNION ALL operator uses this property to force
119583  ** the reuse of the same limit and offset registers across multiple
119584  ** SELECT statements.
119585  */
119586  static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
119587    Vdbe *v = 0;
119588    int iLimit = 0;
119589    int iOffset;
119590    int n;
119591    if( p->iLimit ) return;
119592  
119593    /* 
119594    ** "LIMIT -1" always shows all rows.  There is some
119595    ** controversy about what the correct behavior should be.
119596    ** The current implementation interprets "LIMIT 0" to mean
119597    ** no rows.
119598    */
119599    sqlite3ExprCacheClear(pParse);
119600    assert( p->pOffset==0 || p->pLimit!=0 );
119601    if( p->pLimit ){
119602      p->iLimit = iLimit = ++pParse->nMem;
119603      v = sqlite3GetVdbe(pParse);
119604      assert( v!=0 );
119605      if( sqlite3ExprIsInteger(p->pLimit, &n) ){
119606        sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
119607        VdbeComment((v, "LIMIT counter"));
119608        if( n==0 ){
119609          sqlite3VdbeGoto(v, iBreak);
119610        }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
119611          p->nSelectRow = sqlite3LogEst((u64)n);
119612          p->selFlags |= SF_FixedLimit;
119613        }
119614      }else{
119615        sqlite3ExprCode(pParse, p->pLimit, iLimit);
119616        sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
119617        VdbeComment((v, "LIMIT counter"));
119618        sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
119619      }
119620      if( p->pOffset ){
119621        p->iOffset = iOffset = ++pParse->nMem;
119622        pParse->nMem++;   /* Allocate an extra register for limit+offset */
119623        sqlite3ExprCode(pParse, p->pOffset, iOffset);
119624        sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
119625        VdbeComment((v, "OFFSET counter"));
119626        sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
119627        VdbeComment((v, "LIMIT+OFFSET"));
119628      }
119629    }
119630  }
119631  
119632  #ifndef SQLITE_OMIT_COMPOUND_SELECT
119633  /*
119634  ** Return the appropriate collating sequence for the iCol-th column of
119635  ** the result set for the compound-select statement "p".  Return NULL if
119636  ** the column has no default collating sequence.
119637  **
119638  ** The collating sequence for the compound select is taken from the
119639  ** left-most term of the select that has a collating sequence.
119640  */
119641  static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
119642    CollSeq *pRet;
119643    if( p->pPrior ){
119644      pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
119645    }else{
119646      pRet = 0;
119647    }
119648    assert( iCol>=0 );
119649    /* iCol must be less than p->pEList->nExpr.  Otherwise an error would
119650    ** have been thrown during name resolution and we would not have gotten
119651    ** this far */
119652    if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
119653      pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
119654    }
119655    return pRet;
119656  }
119657  
119658  /*
119659  ** The select statement passed as the second parameter is a compound SELECT
119660  ** with an ORDER BY clause. This function allocates and returns a KeyInfo
119661  ** structure suitable for implementing the ORDER BY.
119662  **
119663  ** Space to hold the KeyInfo structure is obtained from malloc. The calling
119664  ** function is responsible for ensuring that this structure is eventually
119665  ** freed.
119666  */
119667  static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
119668    ExprList *pOrderBy = p->pOrderBy;
119669    int nOrderBy = p->pOrderBy->nExpr;
119670    sqlite3 *db = pParse->db;
119671    KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
119672    if( pRet ){
119673      int i;
119674      for(i=0; i<nOrderBy; i++){
119675        struct ExprList_item *pItem = &pOrderBy->a[i];
119676        Expr *pTerm = pItem->pExpr;
119677        CollSeq *pColl;
119678  
119679        if( pTerm->flags & EP_Collate ){
119680          pColl = sqlite3ExprCollSeq(pParse, pTerm);
119681        }else{
119682          pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
119683          if( pColl==0 ) pColl = db->pDfltColl;
119684          pOrderBy->a[i].pExpr =
119685            sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
119686        }
119687        assert( sqlite3KeyInfoIsWriteable(pRet) );
119688        pRet->aColl[i] = pColl;
119689        pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
119690      }
119691    }
119692  
119693    return pRet;
119694  }
119695  
119696  #ifndef SQLITE_OMIT_CTE
119697  /*
119698  ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
119699  ** query of the form:
119700  **
119701  **   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
119702  **                         \___________/             \_______________/
119703  **                           p->pPrior                      p
119704  **
119705  **
119706  ** There is exactly one reference to the recursive-table in the FROM clause
119707  ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
119708  **
119709  ** The setup-query runs once to generate an initial set of rows that go
119710  ** into a Queue table.  Rows are extracted from the Queue table one by
119711  ** one.  Each row extracted from Queue is output to pDest.  Then the single
119712  ** extracted row (now in the iCurrent table) becomes the content of the
119713  ** recursive-table for a recursive-query run.  The output of the recursive-query
119714  ** is added back into the Queue table.  Then another row is extracted from Queue
119715  ** and the iteration continues until the Queue table is empty.
119716  **
119717  ** If the compound query operator is UNION then no duplicate rows are ever
119718  ** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
119719  ** that have ever been inserted into Queue and causes duplicates to be
119720  ** discarded.  If the operator is UNION ALL, then duplicates are allowed.
119721  ** 
119722  ** If the query has an ORDER BY, then entries in the Queue table are kept in
119723  ** ORDER BY order and the first entry is extracted for each cycle.  Without
119724  ** an ORDER BY, the Queue table is just a FIFO.
119725  **
119726  ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
119727  ** have been output to pDest.  A LIMIT of zero means to output no rows and a
119728  ** negative LIMIT means to output all rows.  If there is also an OFFSET clause
119729  ** with a positive value, then the first OFFSET outputs are discarded rather
119730  ** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
119731  ** rows have been skipped.
119732  */
119733  static void generateWithRecursiveQuery(
119734    Parse *pParse,        /* Parsing context */
119735    Select *p,            /* The recursive SELECT to be coded */
119736    SelectDest *pDest     /* What to do with query results */
119737  ){
119738    SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
119739    int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
119740    Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
119741    Select *pSetup = p->pPrior;   /* The setup query */
119742    int addrTop;                  /* Top of the loop */
119743    int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
119744    int iCurrent = 0;             /* The Current table */
119745    int regCurrent;               /* Register holding Current table */
119746    int iQueue;                   /* The Queue table */
119747    int iDistinct = 0;            /* To ensure unique results if UNION */
119748    int eDest = SRT_Fifo;         /* How to write to Queue */
119749    SelectDest destQueue;         /* SelectDest targetting the Queue table */
119750    int i;                        /* Loop counter */
119751    int rc;                       /* Result code */
119752    ExprList *pOrderBy;           /* The ORDER BY clause */
119753    Expr *pLimit, *pOffset;       /* Saved LIMIT and OFFSET */
119754    int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
119755  
119756    /* Obtain authorization to do a recursive query */
119757    if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
119758  
119759    /* Process the LIMIT and OFFSET clauses, if they exist */
119760    addrBreak = sqlite3VdbeMakeLabel(v);
119761    p->nSelectRow = 320;  /* 4 billion rows */
119762    computeLimitRegisters(pParse, p, addrBreak);
119763    pLimit = p->pLimit;
119764    pOffset = p->pOffset;
119765    regLimit = p->iLimit;
119766    regOffset = p->iOffset;
119767    p->pLimit = p->pOffset = 0;
119768    p->iLimit = p->iOffset = 0;
119769    pOrderBy = p->pOrderBy;
119770  
119771    /* Locate the cursor number of the Current table */
119772    for(i=0; ALWAYS(i<pSrc->nSrc); i++){
119773      if( pSrc->a[i].fg.isRecursive ){
119774        iCurrent = pSrc->a[i].iCursor;
119775        break;
119776      }
119777    }
119778  
119779    /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
119780    ** the Distinct table must be exactly one greater than Queue in order
119781    ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
119782    iQueue = pParse->nTab++;
119783    if( p->op==TK_UNION ){
119784      eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
119785      iDistinct = pParse->nTab++;
119786    }else{
119787      eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
119788    }
119789    sqlite3SelectDestInit(&destQueue, eDest, iQueue);
119790  
119791    /* Allocate cursors for Current, Queue, and Distinct. */
119792    regCurrent = ++pParse->nMem;
119793    sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
119794    if( pOrderBy ){
119795      KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
119796      sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
119797                        (char*)pKeyInfo, P4_KEYINFO);
119798      destQueue.pOrderBy = pOrderBy;
119799    }else{
119800      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
119801    }
119802    VdbeComment((v, "Queue table"));
119803    if( iDistinct ){
119804      p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
119805      p->selFlags |= SF_UsesEphemeral;
119806    }
119807  
119808    /* Detach the ORDER BY clause from the compound SELECT */
119809    p->pOrderBy = 0;
119810  
119811    /* Store the results of the setup-query in Queue. */
119812    pSetup->pNext = 0;
119813    rc = sqlite3Select(pParse, pSetup, &destQueue);
119814    pSetup->pNext = p;
119815    if( rc ) goto end_of_recursive_query;
119816  
119817    /* Find the next row in the Queue and output that row */
119818    addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
119819  
119820    /* Transfer the next row in Queue over to Current */
119821    sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
119822    if( pOrderBy ){
119823      sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
119824    }else{
119825      sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
119826    }
119827    sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
119828  
119829    /* Output the single row in Current */
119830    addrCont = sqlite3VdbeMakeLabel(v);
119831    codeOffset(v, regOffset, addrCont);
119832    selectInnerLoop(pParse, p, iCurrent,
119833        0, 0, pDest, addrCont, addrBreak);
119834    if( regLimit ){
119835      sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
119836      VdbeCoverage(v);
119837    }
119838    sqlite3VdbeResolveLabel(v, addrCont);
119839  
119840    /* Execute the recursive SELECT taking the single row in Current as
119841    ** the value for the recursive-table. Store the results in the Queue.
119842    */
119843    if( p->selFlags & SF_Aggregate ){
119844      sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
119845    }else{
119846      p->pPrior = 0;
119847      sqlite3Select(pParse, p, &destQueue);
119848      assert( p->pPrior==0 );
119849      p->pPrior = pSetup;
119850    }
119851  
119852    /* Keep running the loop until the Queue is empty */
119853    sqlite3VdbeGoto(v, addrTop);
119854    sqlite3VdbeResolveLabel(v, addrBreak);
119855  
119856  end_of_recursive_query:
119857    sqlite3ExprListDelete(pParse->db, p->pOrderBy);
119858    p->pOrderBy = pOrderBy;
119859    p->pLimit = pLimit;
119860    p->pOffset = pOffset;
119861    return;
119862  }
119863  #endif /* SQLITE_OMIT_CTE */
119864  
119865  /* Forward references */
119866  static int multiSelectOrderBy(
119867    Parse *pParse,        /* Parsing context */
119868    Select *p,            /* The right-most of SELECTs to be coded */
119869    SelectDest *pDest     /* What to do with query results */
119870  );
119871  
119872  /*
119873  ** Handle the special case of a compound-select that originates from a
119874  ** VALUES clause.  By handling this as a special case, we avoid deep
119875  ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
119876  ** on a VALUES clause.
119877  **
119878  ** Because the Select object originates from a VALUES clause:
119879  **   (1) It has no LIMIT or OFFSET
119880  **   (2) All terms are UNION ALL
119881  **   (3) There is no ORDER BY clause
119882  */
119883  static int multiSelectValues(
119884    Parse *pParse,        /* Parsing context */
119885    Select *p,            /* The right-most of SELECTs to be coded */
119886    SelectDest *pDest     /* What to do with query results */
119887  ){
119888    Select *pPrior;
119889    int nRow = 1;
119890    int rc = 0;
119891    assert( p->selFlags & SF_MultiValue );
119892    do{
119893      assert( p->selFlags & SF_Values );
119894      assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
119895      assert( p->pLimit==0 );
119896      assert( p->pOffset==0 );
119897      assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
119898      if( p->pPrior==0 ) break;
119899      assert( p->pPrior->pNext==p );
119900      p = p->pPrior;
119901      nRow++;
119902    }while(1);
119903    while( p ){
119904      pPrior = p->pPrior;
119905      p->pPrior = 0;
119906      rc = sqlite3Select(pParse, p, pDest);
119907      p->pPrior = pPrior;
119908      if( rc ) break;
119909      p->nSelectRow = nRow;
119910      p = p->pNext;
119911    }
119912    return rc;
119913  }
119914  
119915  /*
119916  ** This routine is called to process a compound query form from
119917  ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
119918  ** INTERSECT
119919  **
119920  ** "p" points to the right-most of the two queries.  the query on the
119921  ** left is p->pPrior.  The left query could also be a compound query
119922  ** in which case this routine will be called recursively. 
119923  **
119924  ** The results of the total query are to be written into a destination
119925  ** of type eDest with parameter iParm.
119926  **
119927  ** Example 1:  Consider a three-way compound SQL statement.
119928  **
119929  **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
119930  **
119931  ** This statement is parsed up as follows:
119932  **
119933  **     SELECT c FROM t3
119934  **      |
119935  **      `----->  SELECT b FROM t2
119936  **                |
119937  **                `------>  SELECT a FROM t1
119938  **
119939  ** The arrows in the diagram above represent the Select.pPrior pointer.
119940  ** So if this routine is called with p equal to the t3 query, then
119941  ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
119942  **
119943  ** Notice that because of the way SQLite parses compound SELECTs, the
119944  ** individual selects always group from left to right.
119945  */
119946  static int multiSelect(
119947    Parse *pParse,        /* Parsing context */
119948    Select *p,            /* The right-most of SELECTs to be coded */
119949    SelectDest *pDest     /* What to do with query results */
119950  ){
119951    int rc = SQLITE_OK;   /* Success code from a subroutine */
119952    Select *pPrior;       /* Another SELECT immediately to our left */
119953    Vdbe *v;              /* Generate code to this VDBE */
119954    SelectDest dest;      /* Alternative data destination */
119955    Select *pDelete = 0;  /* Chain of simple selects to delete */
119956    sqlite3 *db;          /* Database connection */
119957  #ifndef SQLITE_OMIT_EXPLAIN
119958    int iSub1 = 0;        /* EQP id of left-hand query */
119959    int iSub2 = 0;        /* EQP id of right-hand query */
119960  #endif
119961  
119962    /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
119963    ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
119964    */
119965    assert( p && p->pPrior );  /* Calling function guarantees this much */
119966    assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
119967    db = pParse->db;
119968    pPrior = p->pPrior;
119969    dest = *pDest;
119970    if( pPrior->pOrderBy || pPrior->pLimit ){
119971      sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
119972        pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op));
119973      rc = 1;
119974      goto multi_select_end;
119975    }
119976  
119977    v = sqlite3GetVdbe(pParse);
119978    assert( v!=0 );  /* The VDBE already created by calling function */
119979  
119980    /* Create the destination temporary table if necessary
119981    */
119982    if( dest.eDest==SRT_EphemTab ){
119983      assert( p->pEList );
119984      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
119985      dest.eDest = SRT_Table;
119986    }
119987  
119988    /* Special handling for a compound-select that originates as a VALUES clause.
119989    */
119990    if( p->selFlags & SF_MultiValue ){
119991      rc = multiSelectValues(pParse, p, &dest);
119992      goto multi_select_end;
119993    }
119994  
119995    /* Make sure all SELECTs in the statement have the same number of elements
119996    ** in their result sets.
119997    */
119998    assert( p->pEList && pPrior->pEList );
119999    assert( p->pEList->nExpr==pPrior->pEList->nExpr );
120000  
120001  #ifndef SQLITE_OMIT_CTE
120002    if( p->selFlags & SF_Recursive ){
120003      generateWithRecursiveQuery(pParse, p, &dest);
120004    }else
120005  #endif
120006  
120007    /* Compound SELECTs that have an ORDER BY clause are handled separately.
120008    */
120009    if( p->pOrderBy ){
120010      return multiSelectOrderBy(pParse, p, pDest);
120011    }else
120012  
120013    /* Generate code for the left and right SELECT statements.
120014    */
120015    switch( p->op ){
120016      case TK_ALL: {
120017        int addr = 0;
120018        int nLimit;
120019        assert( !pPrior->pLimit );
120020        pPrior->iLimit = p->iLimit;
120021        pPrior->iOffset = p->iOffset;
120022        pPrior->pLimit = p->pLimit;
120023        pPrior->pOffset = p->pOffset;
120024        explainSetInteger(iSub1, pParse->iNextSelectId);
120025        rc = sqlite3Select(pParse, pPrior, &dest);
120026        p->pLimit = 0;
120027        p->pOffset = 0;
120028        if( rc ){
120029          goto multi_select_end;
120030        }
120031        p->pPrior = 0;
120032        p->iLimit = pPrior->iLimit;
120033        p->iOffset = pPrior->iOffset;
120034        if( p->iLimit ){
120035          addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
120036          VdbeComment((v, "Jump ahead if LIMIT reached"));
120037          if( p->iOffset ){
120038            sqlite3VdbeAddOp3(v, OP_OffsetLimit,
120039                              p->iLimit, p->iOffset+1, p->iOffset);
120040          }
120041        }
120042        explainSetInteger(iSub2, pParse->iNextSelectId);
120043        rc = sqlite3Select(pParse, p, &dest);
120044        testcase( rc!=SQLITE_OK );
120045        pDelete = p->pPrior;
120046        p->pPrior = pPrior;
120047        p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
120048        if( pPrior->pLimit
120049         && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
120050         && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) 
120051        ){
120052          p->nSelectRow = sqlite3LogEst((u64)nLimit);
120053        }
120054        if( addr ){
120055          sqlite3VdbeJumpHere(v, addr);
120056        }
120057        break;
120058      }
120059      case TK_EXCEPT:
120060      case TK_UNION: {
120061        int unionTab;    /* Cursor number of the temporary table holding result */
120062        u8 op = 0;       /* One of the SRT_ operations to apply to self */
120063        int priorOp;     /* The SRT_ operation to apply to prior selects */
120064        Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
120065        int addr;
120066        SelectDest uniondest;
120067  
120068        testcase( p->op==TK_EXCEPT );
120069        testcase( p->op==TK_UNION );
120070        priorOp = SRT_Union;
120071        if( dest.eDest==priorOp ){
120072          /* We can reuse a temporary table generated by a SELECT to our
120073          ** right.
120074          */
120075          assert( p->pLimit==0 );      /* Not allowed on leftward elements */
120076          assert( p->pOffset==0 );     /* Not allowed on leftward elements */
120077          unionTab = dest.iSDParm;
120078        }else{
120079          /* We will need to create our own temporary table to hold the
120080          ** intermediate results.
120081          */
120082          unionTab = pParse->nTab++;
120083          assert( p->pOrderBy==0 );
120084          addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
120085          assert( p->addrOpenEphm[0] == -1 );
120086          p->addrOpenEphm[0] = addr;
120087          findRightmost(p)->selFlags |= SF_UsesEphemeral;
120088          assert( p->pEList );
120089        }
120090  
120091        /* Code the SELECT statements to our left
120092        */
120093        assert( !pPrior->pOrderBy );
120094        sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
120095        explainSetInteger(iSub1, pParse->iNextSelectId);
120096        rc = sqlite3Select(pParse, pPrior, &uniondest);
120097        if( rc ){
120098          goto multi_select_end;
120099        }
120100  
120101        /* Code the current SELECT statement
120102        */
120103        if( p->op==TK_EXCEPT ){
120104          op = SRT_Except;
120105        }else{
120106          assert( p->op==TK_UNION );
120107          op = SRT_Union;
120108        }
120109        p->pPrior = 0;
120110        pLimit = p->pLimit;
120111        p->pLimit = 0;
120112        pOffset = p->pOffset;
120113        p->pOffset = 0;
120114        uniondest.eDest = op;
120115        explainSetInteger(iSub2, pParse->iNextSelectId);
120116        rc = sqlite3Select(pParse, p, &uniondest);
120117        testcase( rc!=SQLITE_OK );
120118        /* Query flattening in sqlite3Select() might refill p->pOrderBy.
120119        ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
120120        sqlite3ExprListDelete(db, p->pOrderBy);
120121        pDelete = p->pPrior;
120122        p->pPrior = pPrior;
120123        p->pOrderBy = 0;
120124        if( p->op==TK_UNION ){
120125          p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
120126        }
120127        sqlite3ExprDelete(db, p->pLimit);
120128        p->pLimit = pLimit;
120129        p->pOffset = pOffset;
120130        p->iLimit = 0;
120131        p->iOffset = 0;
120132  
120133        /* Convert the data in the temporary table into whatever form
120134        ** it is that we currently need.
120135        */
120136        assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
120137        if( dest.eDest!=priorOp ){
120138          int iCont, iBreak, iStart;
120139          assert( p->pEList );
120140          iBreak = sqlite3VdbeMakeLabel(v);
120141          iCont = sqlite3VdbeMakeLabel(v);
120142          computeLimitRegisters(pParse, p, iBreak);
120143          sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
120144          iStart = sqlite3VdbeCurrentAddr(v);
120145          selectInnerLoop(pParse, p, unionTab,
120146                          0, 0, &dest, iCont, iBreak);
120147          sqlite3VdbeResolveLabel(v, iCont);
120148          sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
120149          sqlite3VdbeResolveLabel(v, iBreak);
120150          sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
120151        }
120152        break;
120153      }
120154      default: assert( p->op==TK_INTERSECT ); {
120155        int tab1, tab2;
120156        int iCont, iBreak, iStart;
120157        Expr *pLimit, *pOffset;
120158        int addr;
120159        SelectDest intersectdest;
120160        int r1;
120161  
120162        /* INTERSECT is different from the others since it requires
120163        ** two temporary tables.  Hence it has its own case.  Begin
120164        ** by allocating the tables we will need.
120165        */
120166        tab1 = pParse->nTab++;
120167        tab2 = pParse->nTab++;
120168        assert( p->pOrderBy==0 );
120169  
120170        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
120171        assert( p->addrOpenEphm[0] == -1 );
120172        p->addrOpenEphm[0] = addr;
120173        findRightmost(p)->selFlags |= SF_UsesEphemeral;
120174        assert( p->pEList );
120175  
120176        /* Code the SELECTs to our left into temporary table "tab1".
120177        */
120178        sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
120179        explainSetInteger(iSub1, pParse->iNextSelectId);
120180        rc = sqlite3Select(pParse, pPrior, &intersectdest);
120181        if( rc ){
120182          goto multi_select_end;
120183        }
120184  
120185        /* Code the current SELECT into temporary table "tab2"
120186        */
120187        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
120188        assert( p->addrOpenEphm[1] == -1 );
120189        p->addrOpenEphm[1] = addr;
120190        p->pPrior = 0;
120191        pLimit = p->pLimit;
120192        p->pLimit = 0;
120193        pOffset = p->pOffset;
120194        p->pOffset = 0;
120195        intersectdest.iSDParm = tab2;
120196        explainSetInteger(iSub2, pParse->iNextSelectId);
120197        rc = sqlite3Select(pParse, p, &intersectdest);
120198        testcase( rc!=SQLITE_OK );
120199        pDelete = p->pPrior;
120200        p->pPrior = pPrior;
120201        if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
120202        sqlite3ExprDelete(db, p->pLimit);
120203        p->pLimit = pLimit;
120204        p->pOffset = pOffset;
120205  
120206        /* Generate code to take the intersection of the two temporary
120207        ** tables.
120208        */
120209        assert( p->pEList );
120210        iBreak = sqlite3VdbeMakeLabel(v);
120211        iCont = sqlite3VdbeMakeLabel(v);
120212        computeLimitRegisters(pParse, p, iBreak);
120213        sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
120214        r1 = sqlite3GetTempReg(pParse);
120215        iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
120216        sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
120217        sqlite3ReleaseTempReg(pParse, r1);
120218        selectInnerLoop(pParse, p, tab1,
120219                        0, 0, &dest, iCont, iBreak);
120220        sqlite3VdbeResolveLabel(v, iCont);
120221        sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
120222        sqlite3VdbeResolveLabel(v, iBreak);
120223        sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
120224        sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
120225        break;
120226      }
120227    }
120228  
120229    explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
120230  
120231    /* Compute collating sequences used by 
120232    ** temporary tables needed to implement the compound select.
120233    ** Attach the KeyInfo structure to all temporary tables.
120234    **
120235    ** This section is run by the right-most SELECT statement only.
120236    ** SELECT statements to the left always skip this part.  The right-most
120237    ** SELECT might also skip this part if it has no ORDER BY clause and
120238    ** no temp tables are required.
120239    */
120240    if( p->selFlags & SF_UsesEphemeral ){
120241      int i;                        /* Loop counter */
120242      KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
120243      Select *pLoop;                /* For looping through SELECT statements */
120244      CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
120245      int nCol;                     /* Number of columns in result set */
120246  
120247      assert( p->pNext==0 );
120248      nCol = p->pEList->nExpr;
120249      pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
120250      if( !pKeyInfo ){
120251        rc = SQLITE_NOMEM_BKPT;
120252        goto multi_select_end;
120253      }
120254      for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
120255        *apColl = multiSelectCollSeq(pParse, p, i);
120256        if( 0==*apColl ){
120257          *apColl = db->pDfltColl;
120258        }
120259      }
120260  
120261      for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
120262        for(i=0; i<2; i++){
120263          int addr = pLoop->addrOpenEphm[i];
120264          if( addr<0 ){
120265            /* If [0] is unused then [1] is also unused.  So we can
120266            ** always safely abort as soon as the first unused slot is found */
120267            assert( pLoop->addrOpenEphm[1]<0 );
120268            break;
120269          }
120270          sqlite3VdbeChangeP2(v, addr, nCol);
120271          sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
120272                              P4_KEYINFO);
120273          pLoop->addrOpenEphm[i] = -1;
120274        }
120275      }
120276      sqlite3KeyInfoUnref(pKeyInfo);
120277    }
120278  
120279  multi_select_end:
120280    pDest->iSdst = dest.iSdst;
120281    pDest->nSdst = dest.nSdst;
120282    sqlite3SelectDelete(db, pDelete);
120283    return rc;
120284  }
120285  #endif /* SQLITE_OMIT_COMPOUND_SELECT */
120286  
120287  /*
120288  ** Error message for when two or more terms of a compound select have different
120289  ** size result sets.
120290  */
120291  SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
120292    if( p->selFlags & SF_Values ){
120293      sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
120294    }else{
120295      sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
120296        " do not have the same number of result columns", selectOpName(p->op));
120297    }
120298  }
120299  
120300  /*
120301  ** Code an output subroutine for a coroutine implementation of a
120302  ** SELECT statment.
120303  **
120304  ** The data to be output is contained in pIn->iSdst.  There are
120305  ** pIn->nSdst columns to be output.  pDest is where the output should
120306  ** be sent.
120307  **
120308  ** regReturn is the number of the register holding the subroutine
120309  ** return address.
120310  **
120311  ** If regPrev>0 then it is the first register in a vector that
120312  ** records the previous output.  mem[regPrev] is a flag that is false
120313  ** if there has been no previous output.  If regPrev>0 then code is
120314  ** generated to suppress duplicates.  pKeyInfo is used for comparing
120315  ** keys.
120316  **
120317  ** If the LIMIT found in p->iLimit is reached, jump immediately to
120318  ** iBreak.
120319  */
120320  static int generateOutputSubroutine(
120321    Parse *pParse,          /* Parsing context */
120322    Select *p,              /* The SELECT statement */
120323    SelectDest *pIn,        /* Coroutine supplying data */
120324    SelectDest *pDest,      /* Where to send the data */
120325    int regReturn,          /* The return address register */
120326    int regPrev,            /* Previous result register.  No uniqueness if 0 */
120327    KeyInfo *pKeyInfo,      /* For comparing with previous entry */
120328    int iBreak              /* Jump here if we hit the LIMIT */
120329  ){
120330    Vdbe *v = pParse->pVdbe;
120331    int iContinue;
120332    int addr;
120333  
120334    addr = sqlite3VdbeCurrentAddr(v);
120335    iContinue = sqlite3VdbeMakeLabel(v);
120336  
120337    /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
120338    */
120339    if( regPrev ){
120340      int addr1, addr2;
120341      addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
120342      addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
120343                                (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
120344      sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
120345      sqlite3VdbeJumpHere(v, addr1);
120346      sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
120347      sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
120348    }
120349    if( pParse->db->mallocFailed ) return 0;
120350  
120351    /* Suppress the first OFFSET entries if there is an OFFSET clause
120352    */
120353    codeOffset(v, p->iOffset, iContinue);
120354  
120355    assert( pDest->eDest!=SRT_Exists );
120356    assert( pDest->eDest!=SRT_Table );
120357    switch( pDest->eDest ){
120358      /* Store the result as data using a unique key.
120359      */
120360      case SRT_EphemTab: {
120361        int r1 = sqlite3GetTempReg(pParse);
120362        int r2 = sqlite3GetTempReg(pParse);
120363        sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
120364        sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
120365        sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
120366        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
120367        sqlite3ReleaseTempReg(pParse, r2);
120368        sqlite3ReleaseTempReg(pParse, r1);
120369        break;
120370      }
120371  
120372  #ifndef SQLITE_OMIT_SUBQUERY
120373      /* If we are creating a set for an "expr IN (SELECT ...)".
120374      */
120375      case SRT_Set: {
120376        int r1;
120377        testcase( pIn->nSdst>1 );
120378        r1 = sqlite3GetTempReg(pParse);
120379        sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, 
120380            r1, pDest->zAffSdst, pIn->nSdst);
120381        sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
120382        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
120383                             pIn->iSdst, pIn->nSdst);
120384        sqlite3ReleaseTempReg(pParse, r1);
120385        break;
120386      }
120387  
120388      /* If this is a scalar select that is part of an expression, then
120389      ** store the results in the appropriate memory cell and break out
120390      ** of the scan loop.
120391      */
120392      case SRT_Mem: {
120393        assert( pIn->nSdst==1 || pParse->nErr>0 );  testcase( pIn->nSdst!=1 );
120394        sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
120395        /* The LIMIT clause will jump out of the loop for us */
120396        break;
120397      }
120398  #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
120399  
120400      /* The results are stored in a sequence of registers
120401      ** starting at pDest->iSdst.  Then the co-routine yields.
120402      */
120403      case SRT_Coroutine: {
120404        if( pDest->iSdst==0 ){
120405          pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
120406          pDest->nSdst = pIn->nSdst;
120407        }
120408        sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
120409        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
120410        break;
120411      }
120412  
120413      /* If none of the above, then the result destination must be
120414      ** SRT_Output.  This routine is never called with any other
120415      ** destination other than the ones handled above or SRT_Output.
120416      **
120417      ** For SRT_Output, results are stored in a sequence of registers.  
120418      ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
120419      ** return the next row of result.
120420      */
120421      default: {
120422        assert( pDest->eDest==SRT_Output );
120423        sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
120424        sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
120425        break;
120426      }
120427    }
120428  
120429    /* Jump to the end of the loop if the LIMIT is reached.
120430    */
120431    if( p->iLimit ){
120432      sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
120433    }
120434  
120435    /* Generate the subroutine return
120436    */
120437    sqlite3VdbeResolveLabel(v, iContinue);
120438    sqlite3VdbeAddOp1(v, OP_Return, regReturn);
120439  
120440    return addr;
120441  }
120442  
120443  /*
120444  ** Alternative compound select code generator for cases when there
120445  ** is an ORDER BY clause.
120446  **
120447  ** We assume a query of the following form:
120448  **
120449  **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
120450  **
120451  ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
120452  ** is to code both <selectA> and <selectB> with the ORDER BY clause as
120453  ** co-routines.  Then run the co-routines in parallel and merge the results
120454  ** into the output.  In addition to the two coroutines (called selectA and
120455  ** selectB) there are 7 subroutines:
120456  **
120457  **    outA:    Move the output of the selectA coroutine into the output
120458  **             of the compound query.
120459  **
120460  **    outB:    Move the output of the selectB coroutine into the output
120461  **             of the compound query.  (Only generated for UNION and
120462  **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
120463  **             appears only in B.)
120464  **
120465  **    AltB:    Called when there is data from both coroutines and A<B.
120466  **
120467  **    AeqB:    Called when there is data from both coroutines and A==B.
120468  **
120469  **    AgtB:    Called when there is data from both coroutines and A>B.
120470  **
120471  **    EofA:    Called when data is exhausted from selectA.
120472  **
120473  **    EofB:    Called when data is exhausted from selectB.
120474  **
120475  ** The implementation of the latter five subroutines depend on which 
120476  ** <operator> is used:
120477  **
120478  **
120479  **             UNION ALL         UNION            EXCEPT          INTERSECT
120480  **          -------------  -----------------  --------------  -----------------
120481  **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
120482  **
120483  **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
120484  **
120485  **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
120486  **
120487  **   EofA:   outB, nextB      outB, nextB          halt             halt
120488  **
120489  **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
120490  **
120491  ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
120492  ** causes an immediate jump to EofA and an EOF on B following nextB causes
120493  ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
120494  ** following nextX causes a jump to the end of the select processing.
120495  **
120496  ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
120497  ** within the output subroutine.  The regPrev register set holds the previously
120498  ** output value.  A comparison is made against this value and the output
120499  ** is skipped if the next results would be the same as the previous.
120500  **
120501  ** The implementation plan is to implement the two coroutines and seven
120502  ** subroutines first, then put the control logic at the bottom.  Like this:
120503  **
120504  **          goto Init
120505  **     coA: coroutine for left query (A)
120506  **     coB: coroutine for right query (B)
120507  **    outA: output one row of A
120508  **    outB: output one row of B (UNION and UNION ALL only)
120509  **    EofA: ...
120510  **    EofB: ...
120511  **    AltB: ...
120512  **    AeqB: ...
120513  **    AgtB: ...
120514  **    Init: initialize coroutine registers
120515  **          yield coA
120516  **          if eof(A) goto EofA
120517  **          yield coB
120518  **          if eof(B) goto EofB
120519  **    Cmpr: Compare A, B
120520  **          Jump AltB, AeqB, AgtB
120521  **     End: ...
120522  **
120523  ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
120524  ** actually called using Gosub and they do not Return.  EofA and EofB loop
120525  ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
120526  ** and AgtB jump to either L2 or to one of EofA or EofB.
120527  */
120528  #ifndef SQLITE_OMIT_COMPOUND_SELECT
120529  static int multiSelectOrderBy(
120530    Parse *pParse,        /* Parsing context */
120531    Select *p,            /* The right-most of SELECTs to be coded */
120532    SelectDest *pDest     /* What to do with query results */
120533  ){
120534    int i, j;             /* Loop counters */
120535    Select *pPrior;       /* Another SELECT immediately to our left */
120536    Vdbe *v;              /* Generate code to this VDBE */
120537    SelectDest destA;     /* Destination for coroutine A */
120538    SelectDest destB;     /* Destination for coroutine B */
120539    int regAddrA;         /* Address register for select-A coroutine */
120540    int regAddrB;         /* Address register for select-B coroutine */
120541    int addrSelectA;      /* Address of the select-A coroutine */
120542    int addrSelectB;      /* Address of the select-B coroutine */
120543    int regOutA;          /* Address register for the output-A subroutine */
120544    int regOutB;          /* Address register for the output-B subroutine */
120545    int addrOutA;         /* Address of the output-A subroutine */
120546    int addrOutB = 0;     /* Address of the output-B subroutine */
120547    int addrEofA;         /* Address of the select-A-exhausted subroutine */
120548    int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
120549    int addrEofB;         /* Address of the select-B-exhausted subroutine */
120550    int addrAltB;         /* Address of the A<B subroutine */
120551    int addrAeqB;         /* Address of the A==B subroutine */
120552    int addrAgtB;         /* Address of the A>B subroutine */
120553    int regLimitA;        /* Limit register for select-A */
120554    int regLimitB;        /* Limit register for select-A */
120555    int regPrev;          /* A range of registers to hold previous output */
120556    int savedLimit;       /* Saved value of p->iLimit */
120557    int savedOffset;      /* Saved value of p->iOffset */
120558    int labelCmpr;        /* Label for the start of the merge algorithm */
120559    int labelEnd;         /* Label for the end of the overall SELECT stmt */
120560    int addr1;            /* Jump instructions that get retargetted */
120561    int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
120562    KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
120563    KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
120564    sqlite3 *db;          /* Database connection */
120565    ExprList *pOrderBy;   /* The ORDER BY clause */
120566    int nOrderBy;         /* Number of terms in the ORDER BY clause */
120567    int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
120568  #ifndef SQLITE_OMIT_EXPLAIN
120569    int iSub1;            /* EQP id of left-hand query */
120570    int iSub2;            /* EQP id of right-hand query */
120571  #endif
120572  
120573    assert( p->pOrderBy!=0 );
120574    assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
120575    db = pParse->db;
120576    v = pParse->pVdbe;
120577    assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
120578    labelEnd = sqlite3VdbeMakeLabel(v);
120579    labelCmpr = sqlite3VdbeMakeLabel(v);
120580  
120581  
120582    /* Patch up the ORDER BY clause
120583    */
120584    op = p->op;  
120585    pPrior = p->pPrior;
120586    assert( pPrior->pOrderBy==0 );
120587    pOrderBy = p->pOrderBy;
120588    assert( pOrderBy );
120589    nOrderBy = pOrderBy->nExpr;
120590  
120591    /* For operators other than UNION ALL we have to make sure that
120592    ** the ORDER BY clause covers every term of the result set.  Add
120593    ** terms to the ORDER BY clause as necessary.
120594    */
120595    if( op!=TK_ALL ){
120596      for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
120597        struct ExprList_item *pItem;
120598        for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
120599          assert( pItem->u.x.iOrderByCol>0 );
120600          if( pItem->u.x.iOrderByCol==i ) break;
120601        }
120602        if( j==nOrderBy ){
120603          Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
120604          if( pNew==0 ) return SQLITE_NOMEM_BKPT;
120605          pNew->flags |= EP_IntValue;
120606          pNew->u.iValue = i;
120607          p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
120608          if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
120609        }
120610      }
120611    }
120612  
120613    /* Compute the comparison permutation and keyinfo that is used with
120614    ** the permutation used to determine if the next
120615    ** row of results comes from selectA or selectB.  Also add explicit
120616    ** collations to the ORDER BY clause terms so that when the subqueries
120617    ** to the right and the left are evaluated, they use the correct
120618    ** collation.
120619    */
120620    aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
120621    if( aPermute ){
120622      struct ExprList_item *pItem;
120623      aPermute[0] = nOrderBy;
120624      for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
120625        assert( pItem->u.x.iOrderByCol>0 );
120626        assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
120627        aPermute[i] = pItem->u.x.iOrderByCol - 1;
120628      }
120629      pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
120630    }else{
120631      pKeyMerge = 0;
120632    }
120633  
120634    /* Reattach the ORDER BY clause to the query.
120635    */
120636    p->pOrderBy = pOrderBy;
120637    pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
120638  
120639    /* Allocate a range of temporary registers and the KeyInfo needed
120640    ** for the logic that removes duplicate result rows when the
120641    ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
120642    */
120643    if( op==TK_ALL ){
120644      regPrev = 0;
120645    }else{
120646      int nExpr = p->pEList->nExpr;
120647      assert( nOrderBy>=nExpr || db->mallocFailed );
120648      regPrev = pParse->nMem+1;
120649      pParse->nMem += nExpr+1;
120650      sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
120651      pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
120652      if( pKeyDup ){
120653        assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
120654        for(i=0; i<nExpr; i++){
120655          pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
120656          pKeyDup->aSortOrder[i] = 0;
120657        }
120658      }
120659    }
120660   
120661    /* Separate the left and the right query from one another
120662    */
120663    p->pPrior = 0;
120664    pPrior->pNext = 0;
120665    sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
120666    if( pPrior->pPrior==0 ){
120667      sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
120668    }
120669  
120670    /* Compute the limit registers */
120671    computeLimitRegisters(pParse, p, labelEnd);
120672    if( p->iLimit && op==TK_ALL ){
120673      regLimitA = ++pParse->nMem;
120674      regLimitB = ++pParse->nMem;
120675      sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
120676                                    regLimitA);
120677      sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
120678    }else{
120679      regLimitA = regLimitB = 0;
120680    }
120681    sqlite3ExprDelete(db, p->pLimit);
120682    p->pLimit = 0;
120683    sqlite3ExprDelete(db, p->pOffset);
120684    p->pOffset = 0;
120685  
120686    regAddrA = ++pParse->nMem;
120687    regAddrB = ++pParse->nMem;
120688    regOutA = ++pParse->nMem;
120689    regOutB = ++pParse->nMem;
120690    sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
120691    sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
120692  
120693    /* Generate a coroutine to evaluate the SELECT statement to the
120694    ** left of the compound operator - the "A" select.
120695    */
120696    addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
120697    addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
120698    VdbeComment((v, "left SELECT"));
120699    pPrior->iLimit = regLimitA;
120700    explainSetInteger(iSub1, pParse->iNextSelectId);
120701    sqlite3Select(pParse, pPrior, &destA);
120702    sqlite3VdbeEndCoroutine(v, regAddrA);
120703    sqlite3VdbeJumpHere(v, addr1);
120704  
120705    /* Generate a coroutine to evaluate the SELECT statement on 
120706    ** the right - the "B" select
120707    */
120708    addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
120709    addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
120710    VdbeComment((v, "right SELECT"));
120711    savedLimit = p->iLimit;
120712    savedOffset = p->iOffset;
120713    p->iLimit = regLimitB;
120714    p->iOffset = 0;  
120715    explainSetInteger(iSub2, pParse->iNextSelectId);
120716    sqlite3Select(pParse, p, &destB);
120717    p->iLimit = savedLimit;
120718    p->iOffset = savedOffset;
120719    sqlite3VdbeEndCoroutine(v, regAddrB);
120720  
120721    /* Generate a subroutine that outputs the current row of the A
120722    ** select as the next output row of the compound select.
120723    */
120724    VdbeNoopComment((v, "Output routine for A"));
120725    addrOutA = generateOutputSubroutine(pParse,
120726                   p, &destA, pDest, regOutA,
120727                   regPrev, pKeyDup, labelEnd);
120728    
120729    /* Generate a subroutine that outputs the current row of the B
120730    ** select as the next output row of the compound select.
120731    */
120732    if( op==TK_ALL || op==TK_UNION ){
120733      VdbeNoopComment((v, "Output routine for B"));
120734      addrOutB = generateOutputSubroutine(pParse,
120735                   p, &destB, pDest, regOutB,
120736                   regPrev, pKeyDup, labelEnd);
120737    }
120738    sqlite3KeyInfoUnref(pKeyDup);
120739  
120740    /* Generate a subroutine to run when the results from select A
120741    ** are exhausted and only data in select B remains.
120742    */
120743    if( op==TK_EXCEPT || op==TK_INTERSECT ){
120744      addrEofA_noB = addrEofA = labelEnd;
120745    }else{  
120746      VdbeNoopComment((v, "eof-A subroutine"));
120747      addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
120748      addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
120749                                       VdbeCoverage(v);
120750      sqlite3VdbeGoto(v, addrEofA);
120751      p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
120752    }
120753  
120754    /* Generate a subroutine to run when the results from select B
120755    ** are exhausted and only data in select A remains.
120756    */
120757    if( op==TK_INTERSECT ){
120758      addrEofB = addrEofA;
120759      if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
120760    }else{  
120761      VdbeNoopComment((v, "eof-B subroutine"));
120762      addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
120763      sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
120764      sqlite3VdbeGoto(v, addrEofB);
120765    }
120766  
120767    /* Generate code to handle the case of A<B
120768    */
120769    VdbeNoopComment((v, "A-lt-B subroutine"));
120770    addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
120771    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
120772    sqlite3VdbeGoto(v, labelCmpr);
120773  
120774    /* Generate code to handle the case of A==B
120775    */
120776    if( op==TK_ALL ){
120777      addrAeqB = addrAltB;
120778    }else if( op==TK_INTERSECT ){
120779      addrAeqB = addrAltB;
120780      addrAltB++;
120781    }else{
120782      VdbeNoopComment((v, "A-eq-B subroutine"));
120783      addrAeqB =
120784      sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
120785      sqlite3VdbeGoto(v, labelCmpr);
120786    }
120787  
120788    /* Generate code to handle the case of A>B
120789    */
120790    VdbeNoopComment((v, "A-gt-B subroutine"));
120791    addrAgtB = sqlite3VdbeCurrentAddr(v);
120792    if( op==TK_ALL || op==TK_UNION ){
120793      sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
120794    }
120795    sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
120796    sqlite3VdbeGoto(v, labelCmpr);
120797  
120798    /* This code runs once to initialize everything.
120799    */
120800    sqlite3VdbeJumpHere(v, addr1);
120801    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
120802    sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
120803  
120804    /* Implement the main merge loop
120805    */
120806    sqlite3VdbeResolveLabel(v, labelCmpr);
120807    sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
120808    sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
120809                           (char*)pKeyMerge, P4_KEYINFO);
120810    sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
120811    sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
120812  
120813    /* Jump to the this point in order to terminate the query.
120814    */
120815    sqlite3VdbeResolveLabel(v, labelEnd);
120816  
120817    /* Reassembly the compound query so that it will be freed correctly
120818    ** by the calling function */
120819    if( p->pPrior ){
120820      sqlite3SelectDelete(db, p->pPrior);
120821    }
120822    p->pPrior = pPrior;
120823    pPrior->pNext = p;
120824  
120825    /*** TBD:  Insert subroutine calls to close cursors on incomplete
120826    **** subqueries ****/
120827    explainComposite(pParse, p->op, iSub1, iSub2, 0);
120828    return pParse->nErr!=0;
120829  }
120830  #endif
120831  
120832  #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
120833  
120834  /* An instance of the SubstContext object describes an substitution edit
120835  ** to be performed on a parse tree.
120836  **
120837  ** All references to columns in table iTable are to be replaced by corresponding
120838  ** expressions in pEList.
120839  */
120840  typedef struct SubstContext {
120841    Parse *pParse;            /* The parsing context */
120842    int iTable;               /* Replace references to this table */
120843    int iNewTable;            /* New table number */
120844    int isLeftJoin;           /* Add TK_IF_NULL_ROW opcodes on each replacement */
120845    ExprList *pEList;         /* Replacement expressions */
120846  } SubstContext;
120847  
120848  /* Forward Declarations */
120849  static void substExprList(SubstContext*, ExprList*);
120850  static void substSelect(SubstContext*, Select*, int);
120851  
120852  /*
120853  ** Scan through the expression pExpr.  Replace every reference to
120854  ** a column in table number iTable with a copy of the iColumn-th
120855  ** entry in pEList.  (But leave references to the ROWID column 
120856  ** unchanged.)
120857  **
120858  ** This routine is part of the flattening procedure.  A subquery
120859  ** whose result set is defined by pEList appears as entry in the
120860  ** FROM clause of a SELECT such that the VDBE cursor assigned to that
120861  ** FORM clause entry is iTable.  This routine makes the necessary 
120862  ** changes to pExpr so that it refers directly to the source table
120863  ** of the subquery rather the result set of the subquery.
120864  */
120865  static Expr *substExpr(
120866    SubstContext *pSubst,  /* Description of the substitution */
120867    Expr *pExpr            /* Expr in which substitution occurs */
120868  ){
120869    if( pExpr==0 ) return 0;
120870    if( ExprHasProperty(pExpr, EP_FromJoin)
120871     && pExpr->iRightJoinTable==pSubst->iTable
120872    ){
120873      pExpr->iRightJoinTable = pSubst->iNewTable;
120874    }
120875    if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){
120876      if( pExpr->iColumn<0 ){
120877        pExpr->op = TK_NULL;
120878      }else{
120879        Expr *pNew;
120880        Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr;
120881        Expr ifNullRow;
120882        assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr );
120883        assert( pExpr->pLeft==0 && pExpr->pRight==0 );
120884        if( sqlite3ExprIsVector(pCopy) ){
120885          sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
120886        }else{
120887          sqlite3 *db = pSubst->pParse->db;
120888          if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){
120889            memset(&ifNullRow, 0, sizeof(ifNullRow));
120890            ifNullRow.op = TK_IF_NULL_ROW;
120891            ifNullRow.pLeft = pCopy;
120892            ifNullRow.iTable = pSubst->iNewTable;
120893            pCopy = &ifNullRow;
120894          }
120895          pNew = sqlite3ExprDup(db, pCopy, 0);
120896          if( pNew && pSubst->isLeftJoin ){
120897            ExprSetProperty(pNew, EP_CanBeNull);
120898          }
120899          if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){
120900            pNew->iRightJoinTable = pExpr->iRightJoinTable;
120901            ExprSetProperty(pNew, EP_FromJoin);
120902          }
120903          sqlite3ExprDelete(db, pExpr);
120904          pExpr = pNew;
120905        }
120906      }
120907    }else{
120908      if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
120909        pExpr->iTable = pSubst->iNewTable;
120910      }
120911      pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
120912      pExpr->pRight = substExpr(pSubst, pExpr->pRight);
120913      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
120914        substSelect(pSubst, pExpr->x.pSelect, 1);
120915      }else{
120916        substExprList(pSubst, pExpr->x.pList);
120917      }
120918    }
120919    return pExpr;
120920  }
120921  static void substExprList(
120922    SubstContext *pSubst, /* Description of the substitution */
120923    ExprList *pList       /* List to scan and in which to make substitutes */
120924  ){
120925    int i;
120926    if( pList==0 ) return;
120927    for(i=0; i<pList->nExpr; i++){
120928      pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
120929    }
120930  }
120931  static void substSelect(
120932    SubstContext *pSubst, /* Description of the substitution */
120933    Select *p,            /* SELECT statement in which to make substitutions */
120934    int doPrior           /* Do substitutes on p->pPrior too */
120935  ){
120936    SrcList *pSrc;
120937    struct SrcList_item *pItem;
120938    int i;
120939    if( !p ) return;
120940    do{
120941      substExprList(pSubst, p->pEList);
120942      substExprList(pSubst, p->pGroupBy);
120943      substExprList(pSubst, p->pOrderBy);
120944      p->pHaving = substExpr(pSubst, p->pHaving);
120945      p->pWhere = substExpr(pSubst, p->pWhere);
120946      pSrc = p->pSrc;
120947      assert( pSrc!=0 );
120948      for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
120949        substSelect(pSubst, pItem->pSelect, 1);
120950        if( pItem->fg.isTabFunc ){
120951          substExprList(pSubst, pItem->u1.pFuncArg);
120952        }
120953      }
120954    }while( doPrior && (p = p->pPrior)!=0 );
120955  }
120956  #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
120957  
120958  #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
120959  /*
120960  ** This routine attempts to flatten subqueries as a performance optimization.
120961  ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
120962  **
120963  ** To understand the concept of flattening, consider the following
120964  ** query:
120965  **
120966  **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
120967  **
120968  ** The default way of implementing this query is to execute the
120969  ** subquery first and store the results in a temporary table, then
120970  ** run the outer query on that temporary table.  This requires two
120971  ** passes over the data.  Furthermore, because the temporary table
120972  ** has no indices, the WHERE clause on the outer query cannot be
120973  ** optimized.
120974  **
120975  ** This routine attempts to rewrite queries such as the above into
120976  ** a single flat select, like this:
120977  **
120978  **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
120979  **
120980  ** The code generated for this simplification gives the same result
120981  ** but only has to scan the data once.  And because indices might 
120982  ** exist on the table t1, a complete scan of the data might be
120983  ** avoided.
120984  **
120985  ** Flattening is subject to the following constraints:
120986  **
120987  **  (**)  We no longer attempt to flatten aggregate subqueries. Was:
120988  **        The subquery and the outer query cannot both be aggregates.
120989  **
120990  **  (**)  We no longer attempt to flatten aggregate subqueries. Was:
120991  **        (2) If the subquery is an aggregate then
120992  **        (2a) the outer query must not be a join and
120993  **        (2b) the outer query must not use subqueries
120994  **             other than the one FROM-clause subquery that is a candidate
120995  **             for flattening.  (This is due to ticket [2f7170d73bf9abf80]
120996  **             from 2015-02-09.)
120997  **
120998  **   (3)  If the subquery is the right operand of a LEFT JOIN then
120999  **        (3a) the subquery may not be a join and
121000  **        (3b) the FROM clause of the subquery may not contain a virtual
121001  **             table and
121002  **        (3c) the outer query may not be an aggregate.
121003  **
121004  **   (4)  The subquery can not be DISTINCT.
121005  **
121006  **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
121007  **        sub-queries that were excluded from this optimization. Restriction 
121008  **        (4) has since been expanded to exclude all DISTINCT subqueries.
121009  **
121010  **  (**)  We no longer attempt to flatten aggregate subqueries.  Was:
121011  **        If the subquery is aggregate, the outer query may not be DISTINCT.
121012  **
121013  **   (7)  The subquery must have a FROM clause.  TODO:  For subqueries without
121014  **        A FROM clause, consider adding a FROM clause with the special
121015  **        table sqlite_once that consists of a single row containing a
121016  **        single NULL.
121017  **
121018  **   (8)  If the subquery uses LIMIT then the outer query may not be a join.
121019  **
121020  **   (9)  If the subquery uses LIMIT then the outer query may not be aggregate.
121021  **
121022  **  (**)  Restriction (10) was removed from the code on 2005-02-05 but we
121023  **        accidently carried the comment forward until 2014-09-15.  Original
121024  **        constraint: "If the subquery is aggregate then the outer query 
121025  **        may not use LIMIT."
121026  **
121027  **  (11)  The subquery and the outer query may not both have ORDER BY clauses.
121028  **
121029  **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
121030  **        a separate restriction deriving from ticket #350.
121031  **
121032  **  (13)  The subquery and outer query may not both use LIMIT.
121033  **
121034  **  (14)  The subquery may not use OFFSET.
121035  **
121036  **  (15)  If the outer query is part of a compound select, then the
121037  **        subquery may not use LIMIT.
121038  **        (See ticket #2339 and ticket [02a8e81d44]).
121039  **
121040  **  (16)  If the outer query is aggregate, then the subquery may not
121041  **        use ORDER BY.  (Ticket #2942)  This used to not matter
121042  **        until we introduced the group_concat() function.  
121043  **
121044  **  (17)  If the subquery is a compound select, then
121045  **        (17a) all compound operators must be a UNION ALL, and
121046  **        (17b) no terms within the subquery compound may be aggregate
121047  **              or DISTINCT, and
121048  **        (17c) every term within the subquery compound must have a FROM clause
121049  **        (17d) the outer query may not be
121050  **              (17d1) aggregate, or
121051  **              (17d2) DISTINCT, or
121052  **              (17d3) a join.
121053  **
121054  **        The parent and sub-query may contain WHERE clauses. Subject to
121055  **        rules (11), (13) and (14), they may also contain ORDER BY,
121056  **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
121057  **        operator other than UNION ALL because all the other compound
121058  **        operators have an implied DISTINCT which is disallowed by
121059  **        restriction (4).
121060  **
121061  **        Also, each component of the sub-query must return the same number
121062  **        of result columns. This is actually a requirement for any compound
121063  **        SELECT statement, but all the code here does is make sure that no
121064  **        such (illegal) sub-query is flattened. The caller will detect the
121065  **        syntax error and return a detailed message.
121066  **
121067  **  (18)  If the sub-query is a compound select, then all terms of the
121068  **        ORDER BY clause of the parent must be simple references to 
121069  **        columns of the sub-query.
121070  **
121071  **  (19)  If the subquery uses LIMIT then the outer query may not
121072  **        have a WHERE clause.
121073  **
121074  **  (**)  Subsumed into (17d3).  Was: If the sub-query is a compound select,
121075  **        then it must not use an ORDER BY clause - Ticket #3773.  Because
121076  **        of (17d3), then only way to have a compound subquery is if it is
121077  **        the only term in the FROM clause of the outer query.  But if the
121078  **        only term in the FROM clause has an ORDER BY, then it will be
121079  **        implemented as a co-routine and the flattener will never be called.
121080  **
121081  **  (21)  If the subquery uses LIMIT then the outer query may not be
121082  **        DISTINCT.  (See ticket [752e1646fc]).
121083  **
121084  **  (22)  The subquery may not be a recursive CTE.
121085  **
121086  **  (**)  Subsumed into restriction (17d3).  Was: If the outer query is
121087  **        a recursive CTE, then the sub-query may not be a compound query.
121088  **        This restriction is because transforming the
121089  **        parent to a compound query confuses the code that handles
121090  **        recursive queries in multiSelect().
121091  **
121092  **  (**)  We no longer attempt to flatten aggregate subqueries.  Was:
121093  **        The subquery may not be an aggregate that uses the built-in min() or 
121094  **        or max() functions.  (Without this restriction, a query like:
121095  **        "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
121096  **        return the value X for which Y was maximal.)
121097  **
121098  **
121099  ** In this routine, the "p" parameter is a pointer to the outer query.
121100  ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
121101  ** uses aggregates.
121102  **
121103  ** If flattening is not attempted, this routine is a no-op and returns 0.
121104  ** If flattening is attempted this routine returns 1.
121105  **
121106  ** All of the expression analysis must occur on both the outer query and
121107  ** the subquery before this routine runs.
121108  */
121109  static int flattenSubquery(
121110    Parse *pParse,       /* Parsing context */
121111    Select *p,           /* The parent or outer SELECT statement */
121112    int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
121113    int isAgg            /* True if outer SELECT uses aggregate functions */
121114  ){
121115    const char *zSavedAuthContext = pParse->zAuthContext;
121116    Select *pParent;    /* Current UNION ALL term of the other query */
121117    Select *pSub;       /* The inner query or "subquery" */
121118    Select *pSub1;      /* Pointer to the rightmost select in sub-query */
121119    SrcList *pSrc;      /* The FROM clause of the outer query */
121120    SrcList *pSubSrc;   /* The FROM clause of the subquery */
121121    int iParent;        /* VDBE cursor number of the pSub result set temp table */
121122    int iNewParent = -1;/* Replacement table for iParent */
121123    int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */    
121124    int i;              /* Loop counter */
121125    Expr *pWhere;                    /* The WHERE clause */
121126    struct SrcList_item *pSubitem;   /* The subquery */
121127    sqlite3 *db = pParse->db;
121128  
121129    /* Check to see if flattening is permitted.  Return 0 if not.
121130    */
121131    assert( p!=0 );
121132    assert( p->pPrior==0 );
121133    if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
121134    pSrc = p->pSrc;
121135    assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
121136    pSubitem = &pSrc->a[iFrom];
121137    iParent = pSubitem->iCursor;
121138    pSub = pSubitem->pSelect;
121139    assert( pSub!=0 );
121140  
121141    pSubSrc = pSub->pSrc;
121142    assert( pSubSrc );
121143    /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
121144    ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
121145    ** because they could be computed at compile-time.  But when LIMIT and OFFSET
121146    ** became arbitrary expressions, we were forced to add restrictions (13)
121147    ** and (14). */
121148    if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
121149    if( pSub->pOffset ) return 0;                          /* Restriction (14) */
121150    if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
121151      return 0;                                            /* Restriction (15) */
121152    }
121153    if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
121154    if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (4)  */
121155    if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
121156       return 0;         /* Restrictions (8)(9) */
121157    }
121158    if( p->pOrderBy && pSub->pOrderBy ){
121159       return 0;                                           /* Restriction (11) */
121160    }
121161    if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
121162    if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
121163    if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
121164       return 0;         /* Restriction (21) */
121165    }
121166    if( pSub->selFlags & (SF_Recursive) ){
121167      return 0; /* Restrictions (22) */
121168    }
121169  
121170    /*
121171    ** If the subquery is the right operand of a LEFT JOIN, then the
121172    ** subquery may not be a join itself (3a). Example of why this is not
121173    ** allowed:
121174    **
121175    **         t1 LEFT OUTER JOIN (t2 JOIN t3)
121176    **
121177    ** If we flatten the above, we would get
121178    **
121179    **         (t1 LEFT OUTER JOIN t2) JOIN t3
121180    **
121181    ** which is not at all the same thing.
121182    **
121183    ** If the subquery is the right operand of a LEFT JOIN, then the outer
121184    ** query cannot be an aggregate. (3c)  This is an artifact of the way
121185    ** aggregates are processed - there is no mechanism to determine if
121186    ** the LEFT JOIN table should be all-NULL.
121187    **
121188    ** See also tickets #306, #350, and #3300.
121189    */
121190    if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
121191      isLeftJoin = 1;
121192      if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){
121193        /*  (3a)             (3c)     (3b) */
121194        return 0;
121195      }
121196    }
121197  #ifdef SQLITE_EXTRA_IFNULLROW
121198    else if( iFrom>0 && !isAgg ){
121199      /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
121200      ** every reference to any result column from subquery in a join, even
121201      ** though they are not necessary.  This will stress-test the OP_IfNullRow 
121202      ** opcode. */
121203      isLeftJoin = -1;
121204    }
121205  #endif
121206  
121207    /* Restriction (17): If the sub-query is a compound SELECT, then it must
121208    ** use only the UNION ALL operator. And none of the simple select queries
121209    ** that make up the compound SELECT are allowed to be aggregate or distinct
121210    ** queries.
121211    */
121212    if( pSub->pPrior ){
121213      if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
121214        return 0; /* (17d1), (17d2), or (17d3) */
121215      }
121216      for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
121217        testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
121218        testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
121219        assert( pSub->pSrc!=0 );
121220        assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
121221        if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0    /* (17b) */
121222         || (pSub1->pPrior && pSub1->op!=TK_ALL)                 /* (17a) */
121223         || pSub1->pSrc->nSrc<1                                  /* (17c) */
121224        ){
121225          return 0;
121226        }
121227        testcase( pSub1->pSrc->nSrc>1 );
121228      }
121229  
121230      /* Restriction (18). */
121231      if( p->pOrderBy ){
121232        int ii;
121233        for(ii=0; ii<p->pOrderBy->nExpr; ii++){
121234          if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
121235        }
121236      }
121237    }
121238  
121239    /* Ex-restriction (23):
121240    ** The only way that the recursive part of a CTE can contain a compound
121241    ** subquery is for the subquery to be one term of a join.  But if the
121242    ** subquery is a join, then the flattening has already been stopped by
121243    ** restriction (17d3)
121244    */
121245    assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 );
121246  
121247    /* Ex-restriction (20):
121248    ** A compound subquery must be the only term in the FROM clause of the
121249    ** outer query by restriction (17d3).  But if that term also has an
121250    ** ORDER BY clause, then the subquery will be implemented by co-routine
121251    ** and so the flattener will never be invoked.  Hence, it is not possible
121252    ** for the subquery to be a compound and have an ORDER BY clause.
121253    */
121254    assert( pSub->pPrior==0 || pSub->pOrderBy==0 );
121255  
121256    /***** If we reach this point, flattening is permitted. *****/
121257    SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
121258                     pSub->zSelName, pSub, iFrom));
121259  
121260    /* Authorize the subquery */
121261    pParse->zAuthContext = pSubitem->zName;
121262    TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
121263    testcase( i==SQLITE_DENY );
121264    pParse->zAuthContext = zSavedAuthContext;
121265  
121266    /* If the sub-query is a compound SELECT statement, then (by restrictions
121267    ** 17 and 18 above) it must be a UNION ALL and the parent query must 
121268    ** be of the form:
121269    **
121270    **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
121271    **
121272    ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
121273    ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
121274    ** OFFSET clauses and joins them to the left-hand-side of the original
121275    ** using UNION ALL operators. In this case N is the number of simple
121276    ** select statements in the compound sub-query.
121277    **
121278    ** Example:
121279    **
121280    **     SELECT a+1 FROM (
121281    **        SELECT x FROM tab
121282    **        UNION ALL
121283    **        SELECT y FROM tab
121284    **        UNION ALL
121285    **        SELECT abs(z*2) FROM tab2
121286    **     ) WHERE a!=5 ORDER BY 1
121287    **
121288    ** Transformed into:
121289    **
121290    **     SELECT x+1 FROM tab WHERE x+1!=5
121291    **     UNION ALL
121292    **     SELECT y+1 FROM tab WHERE y+1!=5
121293    **     UNION ALL
121294    **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
121295    **     ORDER BY 1
121296    **
121297    ** We call this the "compound-subquery flattening".
121298    */
121299    for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
121300      Select *pNew;
121301      ExprList *pOrderBy = p->pOrderBy;
121302      Expr *pLimit = p->pLimit;
121303      Expr *pOffset = p->pOffset;
121304      Select *pPrior = p->pPrior;
121305      p->pOrderBy = 0;
121306      p->pSrc = 0;
121307      p->pPrior = 0;
121308      p->pLimit = 0;
121309      p->pOffset = 0;
121310      pNew = sqlite3SelectDup(db, p, 0);
121311      sqlite3SelectSetName(pNew, pSub->zSelName);
121312      p->pOffset = pOffset;
121313      p->pLimit = pLimit;
121314      p->pOrderBy = pOrderBy;
121315      p->pSrc = pSrc;
121316      p->op = TK_ALL;
121317      if( pNew==0 ){
121318        p->pPrior = pPrior;
121319      }else{
121320        pNew->pPrior = pPrior;
121321        if( pPrior ) pPrior->pNext = pNew;
121322        pNew->pNext = p;
121323        p->pPrior = pNew;
121324        SELECTTRACE(2,pParse,p,
121325           ("compound-subquery flattener creates %s.%p as peer\n",
121326           pNew->zSelName, pNew));
121327      }
121328      if( db->mallocFailed ) return 1;
121329    }
121330  
121331    /* Begin flattening the iFrom-th entry of the FROM clause 
121332    ** in the outer query.
121333    */
121334    pSub = pSub1 = pSubitem->pSelect;
121335  
121336    /* Delete the transient table structure associated with the
121337    ** subquery
121338    */
121339    sqlite3DbFree(db, pSubitem->zDatabase);
121340    sqlite3DbFree(db, pSubitem->zName);
121341    sqlite3DbFree(db, pSubitem->zAlias);
121342    pSubitem->zDatabase = 0;
121343    pSubitem->zName = 0;
121344    pSubitem->zAlias = 0;
121345    pSubitem->pSelect = 0;
121346  
121347    /* Defer deleting the Table object associated with the
121348    ** subquery until code generation is
121349    ** complete, since there may still exist Expr.pTab entries that
121350    ** refer to the subquery even after flattening.  Ticket #3346.
121351    **
121352    ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
121353    */
121354    if( ALWAYS(pSubitem->pTab!=0) ){
121355      Table *pTabToDel = pSubitem->pTab;
121356      if( pTabToDel->nTabRef==1 ){
121357        Parse *pToplevel = sqlite3ParseToplevel(pParse);
121358        pTabToDel->pNextZombie = pToplevel->pZombieTab;
121359        pToplevel->pZombieTab = pTabToDel;
121360      }else{
121361        pTabToDel->nTabRef--;
121362      }
121363      pSubitem->pTab = 0;
121364    }
121365  
121366    /* The following loop runs once for each term in a compound-subquery
121367    ** flattening (as described above).  If we are doing a different kind
121368    ** of flattening - a flattening other than a compound-subquery flattening -
121369    ** then this loop only runs once.
121370    **
121371    ** This loop moves all of the FROM elements of the subquery into the
121372    ** the FROM clause of the outer query.  Before doing this, remember
121373    ** the cursor number for the original outer query FROM element in
121374    ** iParent.  The iParent cursor will never be used.  Subsequent code
121375    ** will scan expressions looking for iParent references and replace
121376    ** those references with expressions that resolve to the subquery FROM
121377    ** elements we are now copying in.
121378    */
121379    for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
121380      int nSubSrc;
121381      u8 jointype = 0;
121382      pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
121383      nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
121384      pSrc = pParent->pSrc;     /* FROM clause of the outer query */
121385  
121386      if( pSrc ){
121387        assert( pParent==p );  /* First time through the loop */
121388        jointype = pSubitem->fg.jointype;
121389      }else{
121390        assert( pParent!=p );  /* 2nd and subsequent times through the loop */
121391        pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
121392        if( pSrc==0 ){
121393          assert( db->mallocFailed );
121394          break;
121395        }
121396      }
121397  
121398      /* The subquery uses a single slot of the FROM clause of the outer
121399      ** query.  If the subquery has more than one element in its FROM clause,
121400      ** then expand the outer query to make space for it to hold all elements
121401      ** of the subquery.
121402      **
121403      ** Example:
121404      **
121405      **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
121406      **
121407      ** The outer query has 3 slots in its FROM clause.  One slot of the
121408      ** outer query (the middle slot) is used by the subquery.  The next
121409      ** block of code will expand the outer query FROM clause to 4 slots.
121410      ** The middle slot is expanded to two slots in order to make space
121411      ** for the two elements in the FROM clause of the subquery.
121412      */
121413      if( nSubSrc>1 ){
121414        pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
121415        if( db->mallocFailed ){
121416          break;
121417        }
121418      }
121419  
121420      /* Transfer the FROM clause terms from the subquery into the
121421      ** outer query.
121422      */
121423      for(i=0; i<nSubSrc; i++){
121424        sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
121425        assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
121426        pSrc->a[i+iFrom] = pSubSrc->a[i];
121427        iNewParent = pSubSrc->a[i].iCursor;
121428        memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
121429      }
121430      pSrc->a[iFrom].fg.jointype = jointype;
121431    
121432      /* Now begin substituting subquery result set expressions for 
121433      ** references to the iParent in the outer query.
121434      ** 
121435      ** Example:
121436      **
121437      **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
121438      **   \                     \_____________ subquery __________/          /
121439      **    \_____________________ outer query ______________________________/
121440      **
121441      ** We look at every expression in the outer query and every place we see
121442      ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
121443      */
121444      if( pSub->pOrderBy ){
121445        /* At this point, any non-zero iOrderByCol values indicate that the
121446        ** ORDER BY column expression is identical to the iOrderByCol'th
121447        ** expression returned by SELECT statement pSub. Since these values
121448        ** do not necessarily correspond to columns in SELECT statement pParent,
121449        ** zero them before transfering the ORDER BY clause.
121450        **
121451        ** Not doing this may cause an error if a subsequent call to this
121452        ** function attempts to flatten a compound sub-query into pParent
121453        ** (the only way this can happen is if the compound sub-query is
121454        ** currently part of pSub->pSrc). See ticket [d11a6e908f].  */
121455        ExprList *pOrderBy = pSub->pOrderBy;
121456        for(i=0; i<pOrderBy->nExpr; i++){
121457          pOrderBy->a[i].u.x.iOrderByCol = 0;
121458        }
121459        assert( pParent->pOrderBy==0 );
121460        assert( pSub->pPrior==0 );
121461        pParent->pOrderBy = pOrderBy;
121462        pSub->pOrderBy = 0;
121463      }
121464      pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
121465      if( isLeftJoin>0 ){
121466        setJoinExpr(pWhere, iNewParent);
121467      }
121468      pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere);
121469      if( db->mallocFailed==0 ){
121470        SubstContext x;
121471        x.pParse = pParse;
121472        x.iTable = iParent;
121473        x.iNewTable = iNewParent;
121474        x.isLeftJoin = isLeftJoin;
121475        x.pEList = pSub->pEList;
121476        substSelect(&x, pParent, 0);
121477      }
121478    
121479      /* The flattened query is distinct if either the inner or the
121480      ** outer query is distinct. 
121481      */
121482      pParent->selFlags |= pSub->selFlags & SF_Distinct;
121483    
121484      /*
121485      ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
121486      **
121487      ** One is tempted to try to add a and b to combine the limits.  But this
121488      ** does not work if either limit is negative.
121489      */
121490      if( pSub->pLimit ){
121491        pParent->pLimit = pSub->pLimit;
121492        pSub->pLimit = 0;
121493      }
121494    }
121495  
121496    /* Finially, delete what is left of the subquery and return
121497    ** success.
121498    */
121499    sqlite3SelectDelete(db, pSub1);
121500  
121501  #if SELECTTRACE_ENABLED
121502    if( sqlite3SelectTrace & 0x100 ){
121503      SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
121504      sqlite3TreeViewSelect(0, p, 0);
121505    }
121506  #endif
121507  
121508    return 1;
121509  }
121510  #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
121511  
121512  
121513  
121514  #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
121515  /*
121516  ** Make copies of relevant WHERE clause terms of the outer query into
121517  ** the WHERE clause of subquery.  Example:
121518  **
121519  **    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
121520  **
121521  ** Transformed into:
121522  **
121523  **    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
121524  **     WHERE x=5 AND y=10;
121525  **
121526  ** The hope is that the terms added to the inner query will make it more
121527  ** efficient.
121528  **
121529  ** Do not attempt this optimization if:
121530  **
121531  **   (1) (** This restriction was removed on 2017-09-29.  We used to
121532  **           disallow this optimization for aggregate subqueries, but now
121533  **           it is allowed by putting the extra terms on the HAVING clause.
121534  **           The added HAVING clause is pointless if the subquery lacks
121535  **           a GROUP BY clause.  But such a HAVING clause is also harmless
121536  **           so there does not appear to be any reason to add extra logic
121537  **           to suppress it. **)
121538  **
121539  **   (2) The inner query is the recursive part of a common table expression.
121540  **
121541  **   (3) The inner query has a LIMIT clause (since the changes to the WHERE
121542  **       close would change the meaning of the LIMIT).
121543  **
121544  **   (4) The inner query is the right operand of a LEFT JOIN.  (The caller
121545  **       enforces this restriction since this routine does not have enough
121546  **       information to know.)
121547  **
121548  **   (5) The WHERE clause expression originates in the ON or USING clause
121549  **       of a LEFT JOIN.
121550  **
121551  ** Return 0 if no changes are made and non-zero if one or more WHERE clause
121552  ** terms are duplicated into the subquery.
121553  */
121554  static int pushDownWhereTerms(
121555    Parse *pParse,        /* Parse context (for malloc() and error reporting) */
121556    Select *pSubq,        /* The subquery whose WHERE clause is to be augmented */
121557    Expr *pWhere,         /* The WHERE clause of the outer query */
121558    int iCursor           /* Cursor number of the subquery */
121559  ){
121560    Expr *pNew;
121561    int nChng = 0;
121562    if( pWhere==0 ) return 0;
121563    if( pSubq->selFlags & SF_Recursive ) return 0;  /* restriction (2) */
121564  
121565  #ifdef SQLITE_DEBUG
121566    /* Only the first term of a compound can have a WITH clause.  But make
121567    ** sure no other terms are marked SF_Recursive in case something changes
121568    ** in the future.
121569    */
121570    {
121571      Select *pX;  
121572      for(pX=pSubq; pX; pX=pX->pPrior){
121573        assert( (pX->selFlags & (SF_Recursive))==0 );
121574      }
121575    }
121576  #endif
121577  
121578    if( pSubq->pLimit!=0 ){
121579      return 0; /* restriction (3) */
121580    }
121581    while( pWhere->op==TK_AND ){
121582      nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, iCursor);
121583      pWhere = pWhere->pLeft;
121584    }
121585    if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction (5) */
121586    if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
121587      nChng++;
121588      while( pSubq ){
121589        SubstContext x;
121590        pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
121591        x.pParse = pParse;
121592        x.iTable = iCursor;
121593        x.iNewTable = iCursor;
121594        x.isLeftJoin = 0;
121595        x.pEList = pSubq->pEList;
121596        pNew = substExpr(&x, pNew);
121597        if( pSubq->selFlags & SF_Aggregate ){
121598          pSubq->pHaving = sqlite3ExprAnd(pParse->db, pSubq->pHaving, pNew);
121599        }else{
121600          pSubq->pWhere = sqlite3ExprAnd(pParse->db, pSubq->pWhere, pNew);
121601        }
121602        pSubq = pSubq->pPrior;
121603      }
121604    }
121605    return nChng;
121606  }
121607  #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
121608  
121609  /*
121610  ** Based on the contents of the AggInfo structure indicated by the first
121611  ** argument, this function checks if the following are true:
121612  **
121613  **    * the query contains just a single aggregate function,
121614  **    * the aggregate function is either min() or max(), and
121615  **    * the argument to the aggregate function is a column value.
121616  **
121617  ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
121618  ** is returned as appropriate. Also, *ppMinMax is set to point to the 
121619  ** list of arguments passed to the aggregate before returning.
121620  **
121621  ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
121622  ** WHERE_ORDERBY_NORMAL is returned.
121623  */
121624  static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
121625    int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
121626  
121627    *ppMinMax = 0;
121628    if( pAggInfo->nFunc==1 ){
121629      Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
121630      ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
121631  
121632      assert( pExpr->op==TK_AGG_FUNCTION );
121633      if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
121634        const char *zFunc = pExpr->u.zToken;
121635        if( sqlite3StrICmp(zFunc, "min")==0 ){
121636          eRet = WHERE_ORDERBY_MIN;
121637          *ppMinMax = pEList;
121638        }else if( sqlite3StrICmp(zFunc, "max")==0 ){
121639          eRet = WHERE_ORDERBY_MAX;
121640          *ppMinMax = pEList;
121641        }
121642      }
121643    }
121644  
121645    assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
121646    return eRet;
121647  }
121648  
121649  /*
121650  ** The select statement passed as the first argument is an aggregate query.
121651  ** The second argument is the associated aggregate-info object. This 
121652  ** function tests if the SELECT is of the form:
121653  **
121654  **   SELECT count(*) FROM <tbl>
121655  **
121656  ** where table is a database table, not a sub-select or view. If the query
121657  ** does match this pattern, then a pointer to the Table object representing
121658  ** <tbl> is returned. Otherwise, 0 is returned.
121659  */
121660  static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
121661    Table *pTab;
121662    Expr *pExpr;
121663  
121664    assert( !p->pGroupBy );
121665  
121666    if( p->pWhere || p->pEList->nExpr!=1 
121667     || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
121668    ){
121669      return 0;
121670    }
121671    pTab = p->pSrc->a[0].pTab;
121672    pExpr = p->pEList->a[0].pExpr;
121673    assert( pTab && !pTab->pSelect && pExpr );
121674  
121675    if( IsVirtual(pTab) ) return 0;
121676    if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
121677    if( NEVER(pAggInfo->nFunc==0) ) return 0;
121678    if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
121679    if( pExpr->flags&EP_Distinct ) return 0;
121680  
121681    return pTab;
121682  }
121683  
121684  /*
121685  ** If the source-list item passed as an argument was augmented with an
121686  ** INDEXED BY clause, then try to locate the specified index. If there
121687  ** was such a clause and the named index cannot be found, return 
121688  ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
121689  ** pFrom->pIndex and return SQLITE_OK.
121690  */
121691  SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
121692    if( pFrom->pTab && pFrom->fg.isIndexedBy ){
121693      Table *pTab = pFrom->pTab;
121694      char *zIndexedBy = pFrom->u1.zIndexedBy;
121695      Index *pIdx;
121696      for(pIdx=pTab->pIndex; 
121697          pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy); 
121698          pIdx=pIdx->pNext
121699      );
121700      if( !pIdx ){
121701        sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
121702        pParse->checkSchema = 1;
121703        return SQLITE_ERROR;
121704      }
121705      pFrom->pIBIndex = pIdx;
121706    }
121707    return SQLITE_OK;
121708  }
121709  /*
121710  ** Detect compound SELECT statements that use an ORDER BY clause with 
121711  ** an alternative collating sequence.
121712  **
121713  **    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
121714  **
121715  ** These are rewritten as a subquery:
121716  **
121717  **    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
121718  **     ORDER BY ... COLLATE ...
121719  **
121720  ** This transformation is necessary because the multiSelectOrderBy() routine
121721  ** above that generates the code for a compound SELECT with an ORDER BY clause
121722  ** uses a merge algorithm that requires the same collating sequence on the
121723  ** result columns as on the ORDER BY clause.  See ticket
121724  ** http://www.sqlite.org/src/info/6709574d2a
121725  **
121726  ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
121727  ** The UNION ALL operator works fine with multiSelectOrderBy() even when
121728  ** there are COLLATE terms in the ORDER BY.
121729  */
121730  static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
121731    int i;
121732    Select *pNew;
121733    Select *pX;
121734    sqlite3 *db;
121735    struct ExprList_item *a;
121736    SrcList *pNewSrc;
121737    Parse *pParse;
121738    Token dummy;
121739  
121740    if( p->pPrior==0 ) return WRC_Continue;
121741    if( p->pOrderBy==0 ) return WRC_Continue;
121742    for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
121743    if( pX==0 ) return WRC_Continue;
121744    a = p->pOrderBy->a;
121745    for(i=p->pOrderBy->nExpr-1; i>=0; i--){
121746      if( a[i].pExpr->flags & EP_Collate ) break;
121747    }
121748    if( i<0 ) return WRC_Continue;
121749  
121750    /* If we reach this point, that means the transformation is required. */
121751  
121752    pParse = pWalker->pParse;
121753    db = pParse->db;
121754    pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
121755    if( pNew==0 ) return WRC_Abort;
121756    memset(&dummy, 0, sizeof(dummy));
121757    pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
121758    if( pNewSrc==0 ) return WRC_Abort;
121759    *pNew = *p;
121760    p->pSrc = pNewSrc;
121761    p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
121762    p->op = TK_SELECT;
121763    p->pWhere = 0;
121764    pNew->pGroupBy = 0;
121765    pNew->pHaving = 0;
121766    pNew->pOrderBy = 0;
121767    p->pPrior = 0;
121768    p->pNext = 0;
121769    p->pWith = 0;
121770    p->selFlags &= ~SF_Compound;
121771    assert( (p->selFlags & SF_Converted)==0 );
121772    p->selFlags |= SF_Converted;
121773    assert( pNew->pPrior!=0 );
121774    pNew->pPrior->pNext = pNew;
121775    pNew->pLimit = 0;
121776    pNew->pOffset = 0;
121777    return WRC_Continue;
121778  }
121779  
121780  /*
121781  ** Check to see if the FROM clause term pFrom has table-valued function
121782  ** arguments.  If it does, leave an error message in pParse and return
121783  ** non-zero, since pFrom is not allowed to be a table-valued function.
121784  */
121785  static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
121786    if( pFrom->fg.isTabFunc ){
121787      sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
121788      return 1;
121789    }
121790    return 0;
121791  }
121792  
121793  #ifndef SQLITE_OMIT_CTE
121794  /*
121795  ** Argument pWith (which may be NULL) points to a linked list of nested 
121796  ** WITH contexts, from inner to outermost. If the table identified by 
121797  ** FROM clause element pItem is really a common-table-expression (CTE) 
121798  ** then return a pointer to the CTE definition for that table. Otherwise
121799  ** return NULL.
121800  **
121801  ** If a non-NULL value is returned, set *ppContext to point to the With
121802  ** object that the returned CTE belongs to.
121803  */
121804  static struct Cte *searchWith(
121805    With *pWith,                    /* Current innermost WITH clause */
121806    struct SrcList_item *pItem,     /* FROM clause element to resolve */
121807    With **ppContext                /* OUT: WITH clause return value belongs to */
121808  ){
121809    const char *zName;
121810    if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
121811      With *p;
121812      for(p=pWith; p; p=p->pOuter){
121813        int i;
121814        for(i=0; i<p->nCte; i++){
121815          if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
121816            *ppContext = p;
121817            return &p->a[i];
121818          }
121819        }
121820      }
121821    }
121822    return 0;
121823  }
121824  
121825  /* The code generator maintains a stack of active WITH clauses
121826  ** with the inner-most WITH clause being at the top of the stack.
121827  **
121828  ** This routine pushes the WITH clause passed as the second argument
121829  ** onto the top of the stack. If argument bFree is true, then this
121830  ** WITH clause will never be popped from the stack. In this case it
121831  ** should be freed along with the Parse object. In other cases, when
121832  ** bFree==0, the With object will be freed along with the SELECT 
121833  ** statement with which it is associated.
121834  */
121835  SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
121836    assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
121837    if( pWith ){
121838      assert( pParse->pWith!=pWith );
121839      pWith->pOuter = pParse->pWith;
121840      pParse->pWith = pWith;
121841      if( bFree ) pParse->pWithToFree = pWith;
121842    }
121843  }
121844  
121845  /*
121846  ** This function checks if argument pFrom refers to a CTE declared by 
121847  ** a WITH clause on the stack currently maintained by the parser. And,
121848  ** if currently processing a CTE expression, if it is a recursive
121849  ** reference to the current CTE.
121850  **
121851  ** If pFrom falls into either of the two categories above, pFrom->pTab
121852  ** and other fields are populated accordingly. The caller should check
121853  ** (pFrom->pTab!=0) to determine whether or not a successful match
121854  ** was found.
121855  **
121856  ** Whether or not a match is found, SQLITE_OK is returned if no error
121857  ** occurs. If an error does occur, an error message is stored in the
121858  ** parser and some error code other than SQLITE_OK returned.
121859  */
121860  static int withExpand(
121861    Walker *pWalker, 
121862    struct SrcList_item *pFrom
121863  ){
121864    Parse *pParse = pWalker->pParse;
121865    sqlite3 *db = pParse->db;
121866    struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
121867    With *pWith;                    /* WITH clause that pCte belongs to */
121868  
121869    assert( pFrom->pTab==0 );
121870  
121871    pCte = searchWith(pParse->pWith, pFrom, &pWith);
121872    if( pCte ){
121873      Table *pTab;
121874      ExprList *pEList;
121875      Select *pSel;
121876      Select *pLeft;                /* Left-most SELECT statement */
121877      int bMayRecursive;            /* True if compound joined by UNION [ALL] */
121878      With *pSavedWith;             /* Initial value of pParse->pWith */
121879  
121880      /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
121881      ** recursive reference to CTE pCte. Leave an error in pParse and return
121882      ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
121883      ** In this case, proceed.  */
121884      if( pCte->zCteErr ){
121885        sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
121886        return SQLITE_ERROR;
121887      }
121888      if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
121889  
121890      assert( pFrom->pTab==0 );
121891      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
121892      if( pTab==0 ) return WRC_Abort;
121893      pTab->nTabRef = 1;
121894      pTab->zName = sqlite3DbStrDup(db, pCte->zName);
121895      pTab->iPKey = -1;
121896      pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
121897      pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
121898      pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
121899      if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
121900      assert( pFrom->pSelect );
121901  
121902      /* Check if this is a recursive CTE. */
121903      pSel = pFrom->pSelect;
121904      bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
121905      if( bMayRecursive ){
121906        int i;
121907        SrcList *pSrc = pFrom->pSelect->pSrc;
121908        for(i=0; i<pSrc->nSrc; i++){
121909          struct SrcList_item *pItem = &pSrc->a[i];
121910          if( pItem->zDatabase==0 
121911           && pItem->zName!=0 
121912           && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
121913            ){
121914            pItem->pTab = pTab;
121915            pItem->fg.isRecursive = 1;
121916            pTab->nTabRef++;
121917            pSel->selFlags |= SF_Recursive;
121918          }
121919        }
121920      }
121921  
121922      /* Only one recursive reference is permitted. */ 
121923      if( pTab->nTabRef>2 ){
121924        sqlite3ErrorMsg(
121925            pParse, "multiple references to recursive table: %s", pCte->zName
121926        );
121927        return SQLITE_ERROR;
121928      }
121929      assert( pTab->nTabRef==1 || 
121930              ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));
121931  
121932      pCte->zCteErr = "circular reference: %s";
121933      pSavedWith = pParse->pWith;
121934      pParse->pWith = pWith;
121935      if( bMayRecursive ){
121936        Select *pPrior = pSel->pPrior;
121937        assert( pPrior->pWith==0 );
121938        pPrior->pWith = pSel->pWith;
121939        sqlite3WalkSelect(pWalker, pPrior);
121940        pPrior->pWith = 0;
121941      }else{
121942        sqlite3WalkSelect(pWalker, pSel);
121943      }
121944      pParse->pWith = pWith;
121945  
121946      for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
121947      pEList = pLeft->pEList;
121948      if( pCte->pCols ){
121949        if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
121950          sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
121951              pCte->zName, pEList->nExpr, pCte->pCols->nExpr
121952          );
121953          pParse->pWith = pSavedWith;
121954          return SQLITE_ERROR;
121955        }
121956        pEList = pCte->pCols;
121957      }
121958  
121959      sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
121960      if( bMayRecursive ){
121961        if( pSel->selFlags & SF_Recursive ){
121962          pCte->zCteErr = "multiple recursive references: %s";
121963        }else{
121964          pCte->zCteErr = "recursive reference in a subquery: %s";
121965        }
121966        sqlite3WalkSelect(pWalker, pSel);
121967      }
121968      pCte->zCteErr = 0;
121969      pParse->pWith = pSavedWith;
121970    }
121971  
121972    return SQLITE_OK;
121973  }
121974  #endif
121975  
121976  #ifndef SQLITE_OMIT_CTE
121977  /*
121978  ** If the SELECT passed as the second argument has an associated WITH 
121979  ** clause, pop it from the stack stored as part of the Parse object.
121980  **
121981  ** This function is used as the xSelectCallback2() callback by
121982  ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
121983  ** names and other FROM clause elements. 
121984  */
121985  static void selectPopWith(Walker *pWalker, Select *p){
121986    Parse *pParse = pWalker->pParse;
121987    if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
121988      With *pWith = findRightmost(p)->pWith;
121989      if( pWith!=0 ){
121990        assert( pParse->pWith==pWith );
121991        pParse->pWith = pWith->pOuter;
121992      }
121993    }
121994  }
121995  #else
121996  #define selectPopWith 0
121997  #endif
121998  
121999  /*
122000  ** This routine is a Walker callback for "expanding" a SELECT statement.
122001  ** "Expanding" means to do the following:
122002  **
122003  **    (1)  Make sure VDBE cursor numbers have been assigned to every
122004  **         element of the FROM clause.
122005  **
122006  **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
122007  **         defines FROM clause.  When views appear in the FROM clause,
122008  **         fill pTabList->a[].pSelect with a copy of the SELECT statement
122009  **         that implements the view.  A copy is made of the view's SELECT
122010  **         statement so that we can freely modify or delete that statement
122011  **         without worrying about messing up the persistent representation
122012  **         of the view.
122013  **
122014  **    (3)  Add terms to the WHERE clause to accommodate the NATURAL keyword
122015  **         on joins and the ON and USING clause of joins.
122016  **
122017  **    (4)  Scan the list of columns in the result set (pEList) looking
122018  **         for instances of the "*" operator or the TABLE.* operator.
122019  **         If found, expand each "*" to be every column in every table
122020  **         and TABLE.* to be every column in TABLE.
122021  **
122022  */
122023  static int selectExpander(Walker *pWalker, Select *p){
122024    Parse *pParse = pWalker->pParse;
122025    int i, j, k;
122026    SrcList *pTabList;
122027    ExprList *pEList;
122028    struct SrcList_item *pFrom;
122029    sqlite3 *db = pParse->db;
122030    Expr *pE, *pRight, *pExpr;
122031    u16 selFlags = p->selFlags;
122032  
122033    p->selFlags |= SF_Expanded;
122034    if( db->mallocFailed  ){
122035      return WRC_Abort;
122036    }
122037    if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
122038      return WRC_Prune;
122039    }
122040    pTabList = p->pSrc;
122041    pEList = p->pEList;
122042    if( OK_IF_ALWAYS_TRUE(p->pWith) ){
122043      sqlite3WithPush(pParse, p->pWith, 0);
122044    }
122045  
122046    /* Make sure cursor numbers have been assigned to all entries in
122047    ** the FROM clause of the SELECT statement.
122048    */
122049    sqlite3SrcListAssignCursors(pParse, pTabList);
122050  
122051    /* Look up every table named in the FROM clause of the select.  If
122052    ** an entry of the FROM clause is a subquery instead of a table or view,
122053    ** then create a transient table structure to describe the subquery.
122054    */
122055    for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
122056      Table *pTab;
122057      assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
122058      if( pFrom->fg.isRecursive ) continue;
122059      assert( pFrom->pTab==0 );
122060  #ifndef SQLITE_OMIT_CTE
122061      if( withExpand(pWalker, pFrom) ) return WRC_Abort;
122062      if( pFrom->pTab ) {} else
122063  #endif
122064      if( pFrom->zName==0 ){
122065  #ifndef SQLITE_OMIT_SUBQUERY
122066        Select *pSel = pFrom->pSelect;
122067        /* A sub-query in the FROM clause of a SELECT */
122068        assert( pSel!=0 );
122069        assert( pFrom->pTab==0 );
122070        if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
122071        pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
122072        if( pTab==0 ) return WRC_Abort;
122073        pTab->nTabRef = 1;
122074        if( pFrom->zAlias ){
122075          pTab->zName = sqlite3DbStrDup(db, pFrom->zAlias);
122076        }else{
122077          pTab->zName = sqlite3MPrintf(db, "subquery_%p", (void*)pTab);
122078        }
122079        while( pSel->pPrior ){ pSel = pSel->pPrior; }
122080        sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
122081        pTab->iPKey = -1;
122082        pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
122083        pTab->tabFlags |= TF_Ephemeral;
122084  #endif
122085      }else{
122086        /* An ordinary table or view name in the FROM clause */
122087        assert( pFrom->pTab==0 );
122088        pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
122089        if( pTab==0 ) return WRC_Abort;
122090        if( pTab->nTabRef>=0xffff ){
122091          sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
122092             pTab->zName);
122093          pFrom->pTab = 0;
122094          return WRC_Abort;
122095        }
122096        pTab->nTabRef++;
122097        if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
122098          return WRC_Abort;
122099        }
122100  #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
122101        if( IsVirtual(pTab) || pTab->pSelect ){
122102          i16 nCol;
122103          if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
122104          assert( pFrom->pSelect==0 );
122105          pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
122106          sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
122107          nCol = pTab->nCol;
122108          pTab->nCol = -1;
122109          sqlite3WalkSelect(pWalker, pFrom->pSelect);
122110          pTab->nCol = nCol;
122111        }
122112  #endif
122113      }
122114  
122115      /* Locate the index named by the INDEXED BY clause, if any. */
122116      if( sqlite3IndexedByLookup(pParse, pFrom) ){
122117        return WRC_Abort;
122118      }
122119    }
122120  
122121    /* Process NATURAL keywords, and ON and USING clauses of joins.
122122    */
122123    if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
122124      return WRC_Abort;
122125    }
122126  
122127    /* For every "*" that occurs in the column list, insert the names of
122128    ** all columns in all tables.  And for every TABLE.* insert the names
122129    ** of all columns in TABLE.  The parser inserted a special expression
122130    ** with the TK_ASTERISK operator for each "*" that it found in the column
122131    ** list.  The following code just has to locate the TK_ASTERISK
122132    ** expressions and expand each one to the list of all columns in
122133    ** all tables.
122134    **
122135    ** The first loop just checks to see if there are any "*" operators
122136    ** that need expanding.
122137    */
122138    for(k=0; k<pEList->nExpr; k++){
122139      pE = pEList->a[k].pExpr;
122140      if( pE->op==TK_ASTERISK ) break;
122141      assert( pE->op!=TK_DOT || pE->pRight!=0 );
122142      assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
122143      if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
122144    }
122145    if( k<pEList->nExpr ){
122146      /*
122147      ** If we get here it means the result set contains one or more "*"
122148      ** operators that need to be expanded.  Loop through each expression
122149      ** in the result set and expand them one by one.
122150      */
122151      struct ExprList_item *a = pEList->a;
122152      ExprList *pNew = 0;
122153      int flags = pParse->db->flags;
122154      int longNames = (flags & SQLITE_FullColNames)!=0
122155                        && (flags & SQLITE_ShortColNames)==0;
122156  
122157      for(k=0; k<pEList->nExpr; k++){
122158        pE = a[k].pExpr;
122159        pRight = pE->pRight;
122160        assert( pE->op!=TK_DOT || pRight!=0 );
122161        if( pE->op!=TK_ASTERISK
122162         && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
122163        ){
122164          /* This particular expression does not need to be expanded.
122165          */
122166          pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
122167          if( pNew ){
122168            pNew->a[pNew->nExpr-1].zName = a[k].zName;
122169            pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
122170            a[k].zName = 0;
122171            a[k].zSpan = 0;
122172          }
122173          a[k].pExpr = 0;
122174        }else{
122175          /* This expression is a "*" or a "TABLE.*" and needs to be
122176          ** expanded. */
122177          int tableSeen = 0;      /* Set to 1 when TABLE matches */
122178          char *zTName = 0;       /* text of name of TABLE */
122179          if( pE->op==TK_DOT ){
122180            assert( pE->pLeft!=0 );
122181            assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
122182            zTName = pE->pLeft->u.zToken;
122183          }
122184          for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
122185            Table *pTab = pFrom->pTab;
122186            Select *pSub = pFrom->pSelect;
122187            char *zTabName = pFrom->zAlias;
122188            const char *zSchemaName = 0;
122189            int iDb;
122190            if( zTabName==0 ){
122191              zTabName = pTab->zName;
122192            }
122193            if( db->mallocFailed ) break;
122194            if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
122195              pSub = 0;
122196              if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
122197                continue;
122198              }
122199              iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
122200              zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
122201            }
122202            for(j=0; j<pTab->nCol; j++){
122203              char *zName = pTab->aCol[j].zName;
122204              char *zColname;  /* The computed column name */
122205              char *zToFree;   /* Malloced string that needs to be freed */
122206              Token sColname;  /* Computed column name as a token */
122207  
122208              assert( zName );
122209              if( zTName && pSub
122210               && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
122211              ){
122212                continue;
122213              }
122214  
122215              /* If a column is marked as 'hidden', omit it from the expanded
122216              ** result-set list unless the SELECT has the SF_IncludeHidden
122217              ** bit set.
122218              */
122219              if( (p->selFlags & SF_IncludeHidden)==0
122220               && IsHiddenColumn(&pTab->aCol[j]) 
122221              ){
122222                continue;
122223              }
122224              tableSeen = 1;
122225  
122226              if( i>0 && zTName==0 ){
122227                if( (pFrom->fg.jointype & JT_NATURAL)!=0
122228                  && tableAndColumnIndex(pTabList, i, zName, 0, 0)
122229                ){
122230                  /* In a NATURAL join, omit the join columns from the 
122231                  ** table to the right of the join */
122232                  continue;
122233                }
122234                if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
122235                  /* In a join with a USING clause, omit columns in the
122236                  ** using clause from the table on the right. */
122237                  continue;
122238                }
122239              }
122240              pRight = sqlite3Expr(db, TK_ID, zName);
122241              zColname = zName;
122242              zToFree = 0;
122243              if( longNames || pTabList->nSrc>1 ){
122244                Expr *pLeft;
122245                pLeft = sqlite3Expr(db, TK_ID, zTabName);
122246                pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
122247                if( zSchemaName ){
122248                  pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
122249                  pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
122250                }
122251                if( longNames ){
122252                  zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
122253                  zToFree = zColname;
122254                }
122255              }else{
122256                pExpr = pRight;
122257              }
122258              pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
122259              sqlite3TokenInit(&sColname, zColname);
122260              sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
122261              if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
122262                struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
122263                if( pSub ){
122264                  pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
122265                  testcase( pX->zSpan==0 );
122266                }else{
122267                  pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
122268                                             zSchemaName, zTabName, zColname);
122269                  testcase( pX->zSpan==0 );
122270                }
122271                pX->bSpanIsTab = 1;
122272              }
122273              sqlite3DbFree(db, zToFree);
122274            }
122275          }
122276          if( !tableSeen ){
122277            if( zTName ){
122278              sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
122279            }else{
122280              sqlite3ErrorMsg(pParse, "no tables specified");
122281            }
122282          }
122283        }
122284      }
122285      sqlite3ExprListDelete(db, pEList);
122286      p->pEList = pNew;
122287    }
122288    if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
122289      sqlite3ErrorMsg(pParse, "too many columns in result set");
122290      return WRC_Abort;
122291    }
122292    return WRC_Continue;
122293  }
122294  
122295  /*
122296  ** No-op routine for the parse-tree walker.
122297  **
122298  ** When this routine is the Walker.xExprCallback then expression trees
122299  ** are walked without any actions being taken at each node.  Presumably,
122300  ** when this routine is used for Walker.xExprCallback then 
122301  ** Walker.xSelectCallback is set to do something useful for every 
122302  ** subquery in the parser tree.
122303  */
122304  SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
122305    UNUSED_PARAMETER2(NotUsed, NotUsed2);
122306    return WRC_Continue;
122307  }
122308  
122309  /*
122310  ** No-op routine for the parse-tree walker for SELECT statements.
122311  ** subquery in the parser tree.
122312  */
122313  SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
122314    UNUSED_PARAMETER2(NotUsed, NotUsed2);
122315    return WRC_Continue;
122316  }
122317  
122318  #if SQLITE_DEBUG
122319  /*
122320  ** Always assert.  This xSelectCallback2 implementation proves that the
122321  ** xSelectCallback2 is never invoked.
122322  */
122323  SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
122324    UNUSED_PARAMETER2(NotUsed, NotUsed2);
122325    assert( 0 );
122326  }
122327  #endif
122328  /*
122329  ** This routine "expands" a SELECT statement and all of its subqueries.
122330  ** For additional information on what it means to "expand" a SELECT
122331  ** statement, see the comment on the selectExpand worker callback above.
122332  **
122333  ** Expanding a SELECT statement is the first step in processing a
122334  ** SELECT statement.  The SELECT statement must be expanded before
122335  ** name resolution is performed.
122336  **
122337  ** If anything goes wrong, an error message is written into pParse.
122338  ** The calling function can detect the problem by looking at pParse->nErr
122339  ** and/or pParse->db->mallocFailed.
122340  */
122341  static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
122342    Walker w;
122343    w.xExprCallback = sqlite3ExprWalkNoop;
122344    w.pParse = pParse;
122345    if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
122346      w.xSelectCallback = convertCompoundSelectToSubquery;
122347      w.xSelectCallback2 = 0;
122348      sqlite3WalkSelect(&w, pSelect);
122349    }
122350    w.xSelectCallback = selectExpander;
122351    w.xSelectCallback2 = selectPopWith;
122352    sqlite3WalkSelect(&w, pSelect);
122353  }
122354  
122355  
122356  #ifndef SQLITE_OMIT_SUBQUERY
122357  /*
122358  ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
122359  ** interface.
122360  **
122361  ** For each FROM-clause subquery, add Column.zType and Column.zColl
122362  ** information to the Table structure that represents the result set
122363  ** of that subquery.
122364  **
122365  ** The Table structure that represents the result set was constructed
122366  ** by selectExpander() but the type and collation information was omitted
122367  ** at that point because identifiers had not yet been resolved.  This
122368  ** routine is called after identifier resolution.
122369  */
122370  static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
122371    Parse *pParse;
122372    int i;
122373    SrcList *pTabList;
122374    struct SrcList_item *pFrom;
122375  
122376    assert( p->selFlags & SF_Resolved );
122377    assert( (p->selFlags & SF_HasTypeInfo)==0 );
122378    p->selFlags |= SF_HasTypeInfo;
122379    pParse = pWalker->pParse;
122380    pTabList = p->pSrc;
122381    for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
122382      Table *pTab = pFrom->pTab;
122383      assert( pTab!=0 );
122384      if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
122385        /* A sub-query in the FROM clause of a SELECT */
122386        Select *pSel = pFrom->pSelect;
122387        if( pSel ){
122388          while( pSel->pPrior ) pSel = pSel->pPrior;
122389          sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
122390        }
122391      }
122392    }
122393  }
122394  #endif
122395  
122396  
122397  /*
122398  ** This routine adds datatype and collating sequence information to
122399  ** the Table structures of all FROM-clause subqueries in a
122400  ** SELECT statement.
122401  **
122402  ** Use this routine after name resolution.
122403  */
122404  static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
122405  #ifndef SQLITE_OMIT_SUBQUERY
122406    Walker w;
122407    w.xSelectCallback = sqlite3SelectWalkNoop;
122408    w.xSelectCallback2 = selectAddSubqueryTypeInfo;
122409    w.xExprCallback = sqlite3ExprWalkNoop;
122410    w.pParse = pParse;
122411    sqlite3WalkSelect(&w, pSelect);
122412  #endif
122413  }
122414  
122415  
122416  /*
122417  ** This routine sets up a SELECT statement for processing.  The
122418  ** following is accomplished:
122419  **
122420  **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
122421  **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
122422  **     *  ON and USING clauses are shifted into WHERE statements
122423  **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
122424  **     *  Identifiers in expression are matched to tables.
122425  **
122426  ** This routine acts recursively on all subqueries within the SELECT.
122427  */
122428  SQLITE_PRIVATE void sqlite3SelectPrep(
122429    Parse *pParse,         /* The parser context */
122430    Select *p,             /* The SELECT statement being coded. */
122431    NameContext *pOuterNC  /* Name context for container */
122432  ){
122433    assert( p!=0 || pParse->db->mallocFailed );
122434    if( pParse->db->mallocFailed ) return;
122435    if( p->selFlags & SF_HasTypeInfo ) return;
122436    sqlite3SelectExpand(pParse, p);
122437    if( pParse->nErr || pParse->db->mallocFailed ) return;
122438    sqlite3ResolveSelectNames(pParse, p, pOuterNC);
122439    if( pParse->nErr || pParse->db->mallocFailed ) return;
122440    sqlite3SelectAddTypeInfo(pParse, p);
122441  }
122442  
122443  /*
122444  ** Reset the aggregate accumulator.
122445  **
122446  ** The aggregate accumulator is a set of memory cells that hold
122447  ** intermediate results while calculating an aggregate.  This
122448  ** routine generates code that stores NULLs in all of those memory
122449  ** cells.
122450  */
122451  static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
122452    Vdbe *v = pParse->pVdbe;
122453    int i;
122454    struct AggInfo_func *pFunc;
122455    int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
122456    if( nReg==0 ) return;
122457  #ifdef SQLITE_DEBUG
122458    /* Verify that all AggInfo registers are within the range specified by
122459    ** AggInfo.mnReg..AggInfo.mxReg */
122460    assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
122461    for(i=0; i<pAggInfo->nColumn; i++){
122462      assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
122463           && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
122464    }
122465    for(i=0; i<pAggInfo->nFunc; i++){
122466      assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
122467           && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
122468    }
122469  #endif
122470    sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
122471    for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
122472      if( pFunc->iDistinct>=0 ){
122473        Expr *pE = pFunc->pExpr;
122474        assert( !ExprHasProperty(pE, EP_xIsSelect) );
122475        if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
122476          sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
122477             "argument");
122478          pFunc->iDistinct = -1;
122479        }else{
122480          KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
122481          sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
122482                            (char*)pKeyInfo, P4_KEYINFO);
122483        }
122484      }
122485    }
122486  }
122487  
122488  /*
122489  ** Invoke the OP_AggFinalize opcode for every aggregate function
122490  ** in the AggInfo structure.
122491  */
122492  static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
122493    Vdbe *v = pParse->pVdbe;
122494    int i;
122495    struct AggInfo_func *pF;
122496    for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
122497      ExprList *pList = pF->pExpr->x.pList;
122498      assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
122499      sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
122500      sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
122501    }
122502  }
122503  
122504  /*
122505  ** Update the accumulator memory cells for an aggregate based on
122506  ** the current cursor position.
122507  */
122508  static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
122509    Vdbe *v = pParse->pVdbe;
122510    int i;
122511    int regHit = 0;
122512    int addrHitTest = 0;
122513    struct AggInfo_func *pF;
122514    struct AggInfo_col *pC;
122515  
122516    pAggInfo->directMode = 1;
122517    for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
122518      int nArg;
122519      int addrNext = 0;
122520      int regAgg;
122521      ExprList *pList = pF->pExpr->x.pList;
122522      assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
122523      if( pList ){
122524        nArg = pList->nExpr;
122525        regAgg = sqlite3GetTempRange(pParse, nArg);
122526        sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
122527      }else{
122528        nArg = 0;
122529        regAgg = 0;
122530      }
122531      if( pF->iDistinct>=0 ){
122532        addrNext = sqlite3VdbeMakeLabel(v);
122533        testcase( nArg==0 );  /* Error condition */
122534        testcase( nArg>1 );   /* Also an error */
122535        codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
122536      }
122537      if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
122538        CollSeq *pColl = 0;
122539        struct ExprList_item *pItem;
122540        int j;
122541        assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
122542        for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
122543          pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
122544        }
122545        if( !pColl ){
122546          pColl = pParse->db->pDfltColl;
122547        }
122548        if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
122549        sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
122550      }
122551      sqlite3VdbeAddOp3(v, OP_AggStep0, 0, regAgg, pF->iMem);
122552      sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
122553      sqlite3VdbeChangeP5(v, (u8)nArg);
122554      sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
122555      sqlite3ReleaseTempRange(pParse, regAgg, nArg);
122556      if( addrNext ){
122557        sqlite3VdbeResolveLabel(v, addrNext);
122558        sqlite3ExprCacheClear(pParse);
122559      }
122560    }
122561  
122562    /* Before populating the accumulator registers, clear the column cache.
122563    ** Otherwise, if any of the required column values are already present 
122564    ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
122565    ** to pC->iMem. But by the time the value is used, the original register
122566    ** may have been used, invalidating the underlying buffer holding the
122567    ** text or blob value. See ticket [883034dcb5].
122568    **
122569    ** Another solution would be to change the OP_SCopy used to copy cached
122570    ** values to an OP_Copy.
122571    */
122572    if( regHit ){
122573      addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
122574    }
122575    sqlite3ExprCacheClear(pParse);
122576    for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
122577      sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
122578    }
122579    pAggInfo->directMode = 0;
122580    sqlite3ExprCacheClear(pParse);
122581    if( addrHitTest ){
122582      sqlite3VdbeJumpHere(v, addrHitTest);
122583    }
122584  }
122585  
122586  /*
122587  ** Add a single OP_Explain instruction to the VDBE to explain a simple
122588  ** count(*) query ("SELECT count(*) FROM pTab").
122589  */
122590  #ifndef SQLITE_OMIT_EXPLAIN
122591  static void explainSimpleCount(
122592    Parse *pParse,                  /* Parse context */
122593    Table *pTab,                    /* Table being queried */
122594    Index *pIdx                     /* Index used to optimize scan, or NULL */
122595  ){
122596    if( pParse->explain==2 ){
122597      int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
122598      char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
122599          pTab->zName,
122600          bCover ? " USING COVERING INDEX " : "",
122601          bCover ? pIdx->zName : ""
122602      );
122603      sqlite3VdbeAddOp4(
122604          pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
122605      );
122606    }
122607  }
122608  #else
122609  # define explainSimpleCount(a,b,c)
122610  #endif
122611  
122612  /*
122613  ** Context object for havingToWhereExprCb().
122614  */
122615  struct HavingToWhereCtx {
122616    Expr **ppWhere;
122617    ExprList *pGroupBy;
122618  };
122619  
122620  /*
122621  ** sqlite3WalkExpr() callback used by havingToWhere().
122622  **
122623  ** If the node passed to the callback is a TK_AND node, return 
122624  ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
122625  **
122626  ** Otherwise, return WRC_Prune. In this case, also check if the 
122627  ** sub-expression matches the criteria for being moved to the WHERE
122628  ** clause. If so, add it to the WHERE clause and replace the sub-expression
122629  ** within the HAVING expression with a constant "1".
122630  */
122631  static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
122632    if( pExpr->op!=TK_AND ){
122633      struct HavingToWhereCtx *p = pWalker->u.pHavingCtx;
122634      if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, p->pGroupBy) ){
122635        sqlite3 *db = pWalker->pParse->db;
122636        Expr *pNew = sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[1], 0);
122637        if( pNew ){
122638          Expr *pWhere = *(p->ppWhere);
122639          SWAP(Expr, *pNew, *pExpr);
122640          pNew = sqlite3ExprAnd(db, pWhere, pNew);
122641          *(p->ppWhere) = pNew;
122642        }
122643      }
122644      return WRC_Prune;
122645    }
122646    return WRC_Continue;
122647  }
122648  
122649  /*
122650  ** Transfer eligible terms from the HAVING clause of a query, which is
122651  ** processed after grouping, to the WHERE clause, which is processed before
122652  ** grouping. For example, the query:
122653  **
122654  **   SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
122655  **
122656  ** can be rewritten as:
122657  **
122658  **   SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
122659  **
122660  ** A term of the HAVING expression is eligible for transfer if it consists
122661  ** entirely of constants and expressions that are also GROUP BY terms that
122662  ** use the "BINARY" collation sequence.
122663  */
122664  static void havingToWhere(
122665    Parse *pParse,
122666    ExprList *pGroupBy,
122667    Expr *pHaving, 
122668    Expr **ppWhere
122669  ){
122670    struct HavingToWhereCtx sCtx;
122671    Walker sWalker;
122672  
122673    sCtx.ppWhere = ppWhere;
122674    sCtx.pGroupBy = pGroupBy;
122675  
122676    memset(&sWalker, 0, sizeof(sWalker));
122677    sWalker.pParse = pParse;
122678    sWalker.xExprCallback = havingToWhereExprCb;
122679    sWalker.u.pHavingCtx = &sCtx;
122680    sqlite3WalkExpr(&sWalker, pHaving);
122681  }
122682  
122683  /*
122684  ** Check to see if the pThis entry of pTabList is a self-join of a prior view.
122685  ** If it is, then return the SrcList_item for the prior view.  If it is not,
122686  ** then return 0.
122687  */
122688  static struct SrcList_item *isSelfJoinView(
122689    SrcList *pTabList,           /* Search for self-joins in this FROM clause */
122690    struct SrcList_item *pThis   /* Search for prior reference to this subquery */
122691  ){
122692    struct SrcList_item *pItem;
122693    for(pItem = pTabList->a; pItem<pThis; pItem++){
122694      if( pItem->pSelect==0 ) continue;
122695      if( pItem->fg.viaCoroutine ) continue;
122696      if( pItem->zName==0 ) continue;
122697      if( sqlite3_stricmp(pItem->zDatabase, pThis->zDatabase)!=0 ) continue;
122698      if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
122699      if( sqlite3ExprCompare(0, 
122700            pThis->pSelect->pWhere, pItem->pSelect->pWhere, -1) 
122701      ){
122702        /* The view was modified by some other optimization such as
122703        ** pushDownWhereTerms() */
122704        continue;
122705      }
122706      return pItem;
122707    }
122708    return 0;
122709  }
122710  
122711  #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
122712  /*
122713  ** Attempt to transform a query of the form
122714  **
122715  **    SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
122716  **
122717  ** Into this:
122718  **
122719  **    SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
122720  **
122721  ** The transformation only works if all of the following are true:
122722  **
122723  **   *  The subquery is a UNION ALL of two or more terms
122724  **   *  There is no WHERE or GROUP BY or HAVING clauses on the subqueries
122725  **   *  The outer query is a simple count(*)
122726  **
122727  ** Return TRUE if the optimization is undertaken.
122728  */
122729  static int countOfViewOptimization(Parse *pParse, Select *p){
122730    Select *pSub, *pPrior;
122731    Expr *pExpr;
122732    Expr *pCount;
122733    sqlite3 *db;
122734    if( (p->selFlags & SF_Aggregate)==0 ) return 0;   /* This is an aggregate */
122735    if( p->pEList->nExpr!=1 ) return 0;               /* Single result column */
122736    pExpr = p->pEList->a[0].pExpr;
122737    if( pExpr->op!=TK_AGG_FUNCTION ) return 0;        /* Result is an aggregate */
122738    if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0;  /* Is count() */
122739    if( pExpr->x.pList!=0 ) return 0;                 /* Must be count(*) */
122740    if( p->pSrc->nSrc!=1 ) return 0;                  /* One table in FROM  */
122741    pSub = p->pSrc->a[0].pSelect;
122742    if( pSub==0 ) return 0;                           /* The FROM is a subquery */
122743    if( pSub->pPrior==0 ) return 0;                   /* Must be a compound ry */
122744    do{
122745      if( pSub->op!=TK_ALL && pSub->pPrior ) return 0;  /* Must be UNION ALL */
122746      if( pSub->pWhere ) return 0;                      /* No WHERE clause */
122747      if( pSub->selFlags & SF_Aggregate ) return 0;     /* Not an aggregate */
122748      pSub = pSub->pPrior;                              /* Repeat over compound */
122749    }while( pSub );
122750  
122751    /* If we reach this point then it is OK to perform the transformation */
122752  
122753    db = pParse->db;
122754    pCount = pExpr;
122755    pExpr = 0;
122756    pSub = p->pSrc->a[0].pSelect;
122757    p->pSrc->a[0].pSelect = 0;
122758    sqlite3SrcListDelete(db, p->pSrc);
122759    p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
122760    while( pSub ){
122761      Expr *pTerm;
122762      pPrior = pSub->pPrior;
122763      pSub->pPrior = 0;
122764      pSub->pNext = 0;
122765      pSub->selFlags |= SF_Aggregate;
122766      pSub->selFlags &= ~SF_Compound;
122767      pSub->nSelectRow = 0;
122768      sqlite3ExprListDelete(db, pSub->pEList);
122769      pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
122770      pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
122771      pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
122772      sqlite3PExprAddSelect(pParse, pTerm, pSub);
122773      if( pExpr==0 ){
122774        pExpr = pTerm;
122775      }else{
122776        pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
122777      }
122778      pSub = pPrior;
122779    }
122780    p->pEList->a[0].pExpr = pExpr;
122781    p->selFlags &= ~SF_Aggregate;
122782  
122783  #if SELECTTRACE_ENABLED
122784    if( sqlite3SelectTrace & 0x400 ){
122785      SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n"));
122786      sqlite3TreeViewSelect(0, p, 0);
122787    }
122788  #endif
122789    return 1;
122790  }
122791  #endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */
122792  
122793  /*
122794  ** Generate code for the SELECT statement given in the p argument.  
122795  **
122796  ** The results are returned according to the SelectDest structure.
122797  ** See comments in sqliteInt.h for further information.
122798  **
122799  ** This routine returns the number of errors.  If any errors are
122800  ** encountered, then an appropriate error message is left in
122801  ** pParse->zErrMsg.
122802  **
122803  ** This routine does NOT free the Select structure passed in.  The
122804  ** calling function needs to do that.
122805  */
122806  SQLITE_PRIVATE int sqlite3Select(
122807    Parse *pParse,         /* The parser context */
122808    Select *p,             /* The SELECT statement being coded. */
122809    SelectDest *pDest      /* What to do with the query results */
122810  ){
122811    int i, j;              /* Loop counters */
122812    WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
122813    Vdbe *v;               /* The virtual machine under construction */
122814    int isAgg;             /* True for select lists like "count(*)" */
122815    ExprList *pEList = 0;  /* List of columns to extract. */
122816    SrcList *pTabList;     /* List of tables to select from */
122817    Expr *pWhere;          /* The WHERE clause.  May be NULL */
122818    ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
122819    Expr *pHaving;         /* The HAVING clause.  May be NULL */
122820    int rc = 1;            /* Value to return from this function */
122821    DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
122822    SortCtx sSort;         /* Info on how to code the ORDER BY clause */
122823    AggInfo sAggInfo;      /* Information used by aggregate queries */
122824    int iEnd;              /* Address of the end of the query */
122825    sqlite3 *db;           /* The database connection */
122826  
122827  #ifndef SQLITE_OMIT_EXPLAIN
122828    int iRestoreSelectId = pParse->iSelectId;
122829    pParse->iSelectId = pParse->iNextSelectId++;
122830  #endif
122831  
122832    db = pParse->db;
122833    if( p==0 || db->mallocFailed || pParse->nErr ){
122834      return 1;
122835    }
122836    if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
122837    memset(&sAggInfo, 0, sizeof(sAggInfo));
122838  #if SELECTTRACE_ENABLED
122839    pParse->nSelectIndent++;
122840    SELECTTRACE(1,pParse,p, ("begin processing:\n"));
122841    if( sqlite3SelectTrace & 0x100 ){
122842      sqlite3TreeViewSelect(0, p, 0);
122843    }
122844  #endif
122845  
122846    assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
122847    assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
122848    assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
122849    assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
122850    if( IgnorableOrderby(pDest) ){
122851      assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
122852             pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
122853             pDest->eDest==SRT_Queue  || pDest->eDest==SRT_DistFifo ||
122854             pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
122855      /* If ORDER BY makes no difference in the output then neither does
122856      ** DISTINCT so it can be removed too. */
122857      sqlite3ExprListDelete(db, p->pOrderBy);
122858      p->pOrderBy = 0;
122859      p->selFlags &= ~SF_Distinct;
122860    }
122861    sqlite3SelectPrep(pParse, p, 0);
122862    memset(&sSort, 0, sizeof(sSort));
122863    sSort.pOrderBy = p->pOrderBy;
122864    pTabList = p->pSrc;
122865    if( pParse->nErr || db->mallocFailed ){
122866      goto select_end;
122867    }
122868    assert( p->pEList!=0 );
122869    isAgg = (p->selFlags & SF_Aggregate)!=0;
122870  #if SELECTTRACE_ENABLED
122871    if( sqlite3SelectTrace & 0x100 ){
122872      SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
122873      sqlite3TreeViewSelect(0, p, 0);
122874    }
122875  #endif
122876  
122877    /* Get a pointer the VDBE under construction, allocating a new VDBE if one
122878    ** does not already exist */
122879    v = sqlite3GetVdbe(pParse);
122880    if( v==0 ) goto select_end;
122881    if( pDest->eDest==SRT_Output ){
122882      generateColumnNames(pParse, p);
122883    }
122884  
122885    /* Try to flatten subqueries in the FROM clause up into the main query
122886    */
122887  #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
122888    for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
122889      struct SrcList_item *pItem = &pTabList->a[i];
122890      Select *pSub = pItem->pSelect;
122891      Table *pTab = pItem->pTab;
122892      if( pSub==0 ) continue;
122893  
122894      /* Catch mismatch in the declared columns of a view and the number of
122895      ** columns in the SELECT on the RHS */
122896      if( pTab->nCol!=pSub->pEList->nExpr ){
122897        sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
122898                        pTab->nCol, pTab->zName, pSub->pEList->nExpr);
122899        goto select_end;
122900      }
122901  
122902      /* Do not try to flatten an aggregate subquery.
122903      **
122904      ** Flattening an aggregate subquery is only possible if the outer query
122905      ** is not a join.  But if the outer query is not a join, then the subquery
122906      ** will be implemented as a co-routine and there is no advantage to
122907      ** flattening in that case.
122908      */
122909      if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
122910      assert( pSub->pGroupBy==0 );
122911  
122912      /* If the subquery contains an ORDER BY clause and if
122913      ** it will be implemented as a co-routine, then do not flatten.  This
122914      ** restriction allows SQL constructs like this:
122915      **
122916      **  SELECT expensive_function(x)
122917      **    FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
122918      **
122919      ** The expensive_function() is only computed on the 10 rows that
122920      ** are output, rather than every row of the table.
122921      */
122922      if( pSub->pOrderBy!=0
122923       && i==0
122924       && (pTabList->nSrc==1
122925           || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)
122926      ){
122927        continue;
122928      }
122929  
122930      if( flattenSubquery(pParse, p, i, isAgg) ){
122931        /* This subquery can be absorbed into its parent. */
122932        i = -1;
122933      }
122934      pTabList = p->pSrc;
122935      if( db->mallocFailed ) goto select_end;
122936      if( !IgnorableOrderby(pDest) ){
122937        sSort.pOrderBy = p->pOrderBy;
122938      }
122939    }
122940  #endif
122941  
122942  #ifndef SQLITE_OMIT_COMPOUND_SELECT
122943    /* Handle compound SELECT statements using the separate multiSelect()
122944    ** procedure.
122945    */
122946    if( p->pPrior ){
122947      rc = multiSelect(pParse, p, pDest);
122948      explainSetInteger(pParse->iSelectId, iRestoreSelectId);
122949  #if SELECTTRACE_ENABLED
122950      SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
122951      pParse->nSelectIndent--;
122952  #endif
122953      return rc;
122954    }
122955  #endif
122956  
122957    /* For each term in the FROM clause, do two things:
122958    ** (1) Authorized unreferenced tables
122959    ** (2) Generate code for all sub-queries
122960    */
122961    for(i=0; i<pTabList->nSrc; i++){
122962      struct SrcList_item *pItem = &pTabList->a[i];
122963      SelectDest dest;
122964      Select *pSub;
122965  #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
122966      const char *zSavedAuthContext;
122967  #endif
122968  
122969      /* Issue SQLITE_READ authorizations with a fake column name for any
122970      ** tables that are referenced but from which no values are extracted.
122971      ** Examples of where these kinds of null SQLITE_READ authorizations
122972      ** would occur:
122973      **
122974      **     SELECT count(*) FROM t1;   -- SQLITE_READ t1.""
122975      **     SELECT t1.* FROM t1, t2;   -- SQLITE_READ t2.""
122976      **
122977      ** The fake column name is an empty string.  It is possible for a table to
122978      ** have a column named by the empty string, in which case there is no way to
122979      ** distinguish between an unreferenced table and an actual reference to the
122980      ** "" column. The original design was for the fake column name to be a NULL,
122981      ** which would be unambiguous.  But legacy authorization callbacks might
122982      ** assume the column name is non-NULL and segfault.  The use of an empty
122983      ** string for the fake column name seems safer.
122984      */
122985      if( pItem->colUsed==0 ){
122986        sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
122987      }
122988  
122989  #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
122990      /* Generate code for all sub-queries in the FROM clause
122991      */
122992      pSub = pItem->pSelect;
122993      if( pSub==0 ) continue;
122994  
122995      /* Sometimes the code for a subquery will be generated more than
122996      ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
122997      ** for example.  In that case, do not regenerate the code to manifest
122998      ** a view or the co-routine to implement a view.  The first instance
122999      ** is sufficient, though the subroutine to manifest the view does need
123000      ** to be invoked again. */
123001      if( pItem->addrFillSub ){
123002        if( pItem->fg.viaCoroutine==0 ){
123003          /* The subroutine that manifests the view might be a one-time routine,
123004          ** or it might need to be rerun on each iteration because it
123005          ** encodes a correlated subquery. */
123006          testcase( sqlite3VdbeGetOp(v, pItem->addrFillSub)->opcode==OP_Once );
123007          sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
123008        }
123009        continue;
123010      }
123011  
123012      /* Increment Parse.nHeight by the height of the largest expression
123013      ** tree referred to by this, the parent select. The child select
123014      ** may contain expression trees of at most
123015      ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
123016      ** more conservative than necessary, but much easier than enforcing
123017      ** an exact limit.
123018      */
123019      pParse->nHeight += sqlite3SelectExprHeight(p);
123020  
123021      /* Make copies of constant WHERE-clause terms in the outer query down
123022      ** inside the subquery.  This can help the subquery to run more efficiently.
123023      */
123024      if( (pItem->fg.jointype & JT_OUTER)==0
123025       && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor)
123026      ){
123027  #if SELECTTRACE_ENABLED
123028        if( sqlite3SelectTrace & 0x100 ){
123029          SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
123030          sqlite3TreeViewSelect(0, p, 0);
123031        }
123032  #endif
123033      }
123034  
123035      zSavedAuthContext = pParse->zAuthContext;
123036      pParse->zAuthContext = pItem->zName;
123037  
123038      /* Generate code to implement the subquery
123039      **
123040      ** The subquery is implemented as a co-routine if the subquery is
123041      ** guaranteed to be the outer loop (so that it does not need to be
123042      ** computed more than once)
123043      **
123044      ** TODO: Are there other reasons beside (1) to use a co-routine
123045      ** implementation?
123046      */
123047      if( i==0
123048       && (pTabList->nSrc==1
123049              || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)  /* (1) */
123050      ){
123051        /* Implement a co-routine that will return a single row of the result
123052        ** set on each invocation.
123053        */
123054        int addrTop = sqlite3VdbeCurrentAddr(v)+1;
123055       
123056        pItem->regReturn = ++pParse->nMem;
123057        sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
123058        VdbeComment((v, "%s", pItem->pTab->zName));
123059        pItem->addrFillSub = addrTop;
123060        sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
123061        explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
123062        sqlite3Select(pParse, pSub, &dest);
123063        pItem->pTab->nRowLogEst = pSub->nSelectRow;
123064        pItem->fg.viaCoroutine = 1;
123065        pItem->regResult = dest.iSdst;
123066        sqlite3VdbeEndCoroutine(v, pItem->regReturn);
123067        sqlite3VdbeJumpHere(v, addrTop-1);
123068        sqlite3ClearTempRegCache(pParse);
123069      }else{
123070        /* Generate a subroutine that will fill an ephemeral table with
123071        ** the content of this subquery.  pItem->addrFillSub will point
123072        ** to the address of the generated subroutine.  pItem->regReturn
123073        ** is a register allocated to hold the subroutine return address
123074        */
123075        int topAddr;
123076        int onceAddr = 0;
123077        int retAddr;
123078        struct SrcList_item *pPrior;
123079  
123080        assert( pItem->addrFillSub==0 );
123081        pItem->regReturn = ++pParse->nMem;
123082        topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
123083        pItem->addrFillSub = topAddr+1;
123084        if( pItem->fg.isCorrelated==0 ){
123085          /* If the subquery is not correlated and if we are not inside of
123086          ** a trigger, then we only need to compute the value of the subquery
123087          ** once. */
123088          onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
123089          VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
123090        }else{
123091          VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
123092        }
123093        pPrior = isSelfJoinView(pTabList, pItem);
123094        if( pPrior ){
123095          sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
123096          explainSetInteger(pItem->iSelectId, pPrior->iSelectId);
123097          assert( pPrior->pSelect!=0 );
123098          pSub->nSelectRow = pPrior->pSelect->nSelectRow;
123099        }else{
123100          sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
123101          explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
123102          sqlite3Select(pParse, pSub, &dest);
123103        }
123104        pItem->pTab->nRowLogEst = pSub->nSelectRow;
123105        if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
123106        retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
123107        VdbeComment((v, "end %s", pItem->pTab->zName));
123108        sqlite3VdbeChangeP1(v, topAddr, retAddr);
123109        sqlite3ClearTempRegCache(pParse);
123110      }
123111      if( db->mallocFailed ) goto select_end;
123112      pParse->nHeight -= sqlite3SelectExprHeight(p);
123113      pParse->zAuthContext = zSavedAuthContext;
123114  #endif
123115    }
123116  
123117    /* Various elements of the SELECT copied into local variables for
123118    ** convenience */
123119    pEList = p->pEList;
123120    pWhere = p->pWhere;
123121    pGroupBy = p->pGroupBy;
123122    pHaving = p->pHaving;
123123    sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
123124  
123125  #if SELECTTRACE_ENABLED
123126    if( sqlite3SelectTrace & 0x400 ){
123127      SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
123128      sqlite3TreeViewSelect(0, p, 0);
123129    }
123130  #endif
123131  
123132  #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
123133    if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
123134     && countOfViewOptimization(pParse, p)
123135    ){
123136      if( db->mallocFailed ) goto select_end;
123137      pEList = p->pEList;
123138      pTabList = p->pSrc;
123139    }
123140  #endif
123141  
123142    /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 
123143    ** if the select-list is the same as the ORDER BY list, then this query
123144    ** can be rewritten as a GROUP BY. In other words, this:
123145    **
123146    **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
123147    **
123148    ** is transformed to:
123149    **
123150    **     SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
123151    **
123152    ** The second form is preferred as a single index (or temp-table) may be 
123153    ** used for both the ORDER BY and DISTINCT processing. As originally 
123154    ** written the query must use a temp-table for at least one of the ORDER 
123155    ** BY and DISTINCT, and an index or separate temp-table for the other.
123156    */
123157    if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 
123158     && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
123159    ){
123160      p->selFlags &= ~SF_Distinct;
123161      pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
123162      /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
123163      ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
123164      ** original setting of the SF_Distinct flag, not the current setting */
123165      assert( sDistinct.isTnct );
123166  
123167  #if SELECTTRACE_ENABLED
123168      if( sqlite3SelectTrace & 0x400 ){
123169        SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
123170        sqlite3TreeViewSelect(0, p, 0);
123171      }
123172  #endif
123173    }
123174  
123175    /* If there is an ORDER BY clause, then create an ephemeral index to
123176    ** do the sorting.  But this sorting ephemeral index might end up
123177    ** being unused if the data can be extracted in pre-sorted order.
123178    ** If that is the case, then the OP_OpenEphemeral instruction will be
123179    ** changed to an OP_Noop once we figure out that the sorting index is
123180    ** not needed.  The sSort.addrSortIndex variable is used to facilitate
123181    ** that change.
123182    */
123183    if( sSort.pOrderBy ){
123184      KeyInfo *pKeyInfo;
123185      pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
123186      sSort.iECursor = pParse->nTab++;
123187      sSort.addrSortIndex =
123188        sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
123189            sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
123190            (char*)pKeyInfo, P4_KEYINFO
123191        );
123192    }else{
123193      sSort.addrSortIndex = -1;
123194    }
123195  
123196    /* If the output is destined for a temporary table, open that table.
123197    */
123198    if( pDest->eDest==SRT_EphemTab ){
123199      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
123200    }
123201  
123202    /* Set the limiter.
123203    */
123204    iEnd = sqlite3VdbeMakeLabel(v);
123205    if( (p->selFlags & SF_FixedLimit)==0 ){
123206      p->nSelectRow = 320;  /* 4 billion rows */
123207    }
123208    computeLimitRegisters(pParse, p, iEnd);
123209    if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
123210      sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
123211      sSort.sortFlags |= SORTFLAG_UseSorter;
123212    }
123213  
123214    /* Open an ephemeral index to use for the distinct set.
123215    */
123216    if( p->selFlags & SF_Distinct ){
123217      sDistinct.tabTnct = pParse->nTab++;
123218      sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
123219                               sDistinct.tabTnct, 0, 0,
123220                               (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
123221                               P4_KEYINFO);
123222      sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
123223      sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
123224    }else{
123225      sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
123226    }
123227  
123228    if( !isAgg && pGroupBy==0 ){
123229      /* No aggregate functions and no GROUP BY clause */
123230      u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
123231      assert( WHERE_USE_LIMIT==SF_FixedLimit );
123232      wctrlFlags |= p->selFlags & SF_FixedLimit;
123233  
123234      /* Begin the database scan. */
123235      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
123236                                 p->pEList, wctrlFlags, p->nSelectRow);
123237      if( pWInfo==0 ) goto select_end;
123238      if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
123239        p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
123240      }
123241      if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
123242        sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
123243      }
123244      if( sSort.pOrderBy ){
123245        sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
123246        sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo);
123247        if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
123248          sSort.pOrderBy = 0;
123249        }
123250      }
123251  
123252      /* If sorting index that was created by a prior OP_OpenEphemeral 
123253      ** instruction ended up not being needed, then change the OP_OpenEphemeral
123254      ** into an OP_Noop.
123255      */
123256      if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
123257        sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
123258      }
123259  
123260      /* Use the standard inner loop. */
123261      assert( p->pEList==pEList );
123262      selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
123263                      sqlite3WhereContinueLabel(pWInfo),
123264                      sqlite3WhereBreakLabel(pWInfo));
123265  
123266      /* End the database scan loop.
123267      */
123268      sqlite3WhereEnd(pWInfo);
123269    }else{
123270      /* This case when there exist aggregate functions or a GROUP BY clause
123271      ** or both */
123272      NameContext sNC;    /* Name context for processing aggregate information */
123273      int iAMem;          /* First Mem address for storing current GROUP BY */
123274      int iBMem;          /* First Mem address for previous GROUP BY */
123275      int iUseFlag;       /* Mem address holding flag indicating that at least
123276                          ** one row of the input to the aggregator has been
123277                          ** processed */
123278      int iAbortFlag;     /* Mem address which causes query abort if positive */
123279      int groupBySort;    /* Rows come from source in GROUP BY order */
123280      int addrEnd;        /* End of processing for this SELECT */
123281      int sortPTab = 0;   /* Pseudotable used to decode sorting results */
123282      int sortOut = 0;    /* Output register from the sorter */
123283      int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
123284  
123285      /* Remove any and all aliases between the result set and the
123286      ** GROUP BY clause.
123287      */
123288      if( pGroupBy ){
123289        int k;                        /* Loop counter */
123290        struct ExprList_item *pItem;  /* For looping over expression in a list */
123291  
123292        for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
123293          pItem->u.x.iAlias = 0;
123294        }
123295        for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
123296          pItem->u.x.iAlias = 0;
123297        }
123298        assert( 66==sqlite3LogEst(100) );
123299        if( p->nSelectRow>66 ) p->nSelectRow = 66;
123300      }else{
123301        assert( 0==sqlite3LogEst(1) );
123302        p->nSelectRow = 0;
123303      }
123304  
123305      /* If there is both a GROUP BY and an ORDER BY clause and they are
123306      ** identical, then it may be possible to disable the ORDER BY clause 
123307      ** on the grounds that the GROUP BY will cause elements to come out 
123308      ** in the correct order. It also may not - the GROUP BY might use a
123309      ** database index that causes rows to be grouped together as required
123310      ** but not actually sorted. Either way, record the fact that the
123311      ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
123312      ** variable.  */
123313      if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
123314        orderByGrp = 1;
123315      }
123316   
123317      /* Create a label to jump to when we want to abort the query */
123318      addrEnd = sqlite3VdbeMakeLabel(v);
123319  
123320      /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
123321      ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
123322      ** SELECT statement.
123323      */
123324      memset(&sNC, 0, sizeof(sNC));
123325      sNC.pParse = pParse;
123326      sNC.pSrcList = pTabList;
123327      sNC.pAggInfo = &sAggInfo;
123328      sAggInfo.mnReg = pParse->nMem+1;
123329      sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
123330      sAggInfo.pGroupBy = pGroupBy;
123331      sqlite3ExprAnalyzeAggList(&sNC, pEList);
123332      sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
123333      if( pHaving ){
123334        if( pGroupBy ){
123335          assert( pWhere==p->pWhere );
123336          havingToWhere(pParse, pGroupBy, pHaving, &p->pWhere);
123337          pWhere = p->pWhere;
123338        }
123339        sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
123340      }
123341      sAggInfo.nAccumulator = sAggInfo.nColumn;
123342      for(i=0; i<sAggInfo.nFunc; i++){
123343        assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
123344        sNC.ncFlags |= NC_InAggFunc;
123345        sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
123346        sNC.ncFlags &= ~NC_InAggFunc;
123347      }
123348      sAggInfo.mxReg = pParse->nMem;
123349      if( db->mallocFailed ) goto select_end;
123350  
123351      /* Processing for aggregates with GROUP BY is very different and
123352      ** much more complex than aggregates without a GROUP BY.
123353      */
123354      if( pGroupBy ){
123355        KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
123356        int addr1;          /* A-vs-B comparision jump */
123357        int addrOutputRow;  /* Start of subroutine that outputs a result row */
123358        int regOutputRow;   /* Return address register for output subroutine */
123359        int addrSetAbort;   /* Set the abort flag and return */
123360        int addrTopOfLoop;  /* Top of the input loop */
123361        int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
123362        int addrReset;      /* Subroutine for resetting the accumulator */
123363        int regReset;       /* Return address register for reset subroutine */
123364  
123365        /* If there is a GROUP BY clause we might need a sorting index to
123366        ** implement it.  Allocate that sorting index now.  If it turns out
123367        ** that we do not need it after all, the OP_SorterOpen instruction
123368        ** will be converted into a Noop.  
123369        */
123370        sAggInfo.sortingIdx = pParse->nTab++;
123371        pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
123372        addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 
123373            sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
123374            0, (char*)pKeyInfo, P4_KEYINFO);
123375  
123376        /* Initialize memory locations used by GROUP BY aggregate processing
123377        */
123378        iUseFlag = ++pParse->nMem;
123379        iAbortFlag = ++pParse->nMem;
123380        regOutputRow = ++pParse->nMem;
123381        addrOutputRow = sqlite3VdbeMakeLabel(v);
123382        regReset = ++pParse->nMem;
123383        addrReset = sqlite3VdbeMakeLabel(v);
123384        iAMem = pParse->nMem + 1;
123385        pParse->nMem += pGroupBy->nExpr;
123386        iBMem = pParse->nMem + 1;
123387        pParse->nMem += pGroupBy->nExpr;
123388        sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
123389        VdbeComment((v, "clear abort flag"));
123390        sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
123391        VdbeComment((v, "indicate accumulator empty"));
123392        sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
123393  
123394        /* Begin a loop that will extract all source rows in GROUP BY order.
123395        ** This might involve two separate loops with an OP_Sort in between, or
123396        ** it might be a single loop that uses an index to extract information
123397        ** in the right order to begin with.
123398        */
123399        sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
123400        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
123401            WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
123402        );
123403        if( pWInfo==0 ) goto select_end;
123404        if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
123405          /* The optimizer is able to deliver rows in group by order so
123406          ** we do not have to sort.  The OP_OpenEphemeral table will be
123407          ** cancelled later because we still need to use the pKeyInfo
123408          */
123409          groupBySort = 0;
123410        }else{
123411          /* Rows are coming out in undetermined order.  We have to push
123412          ** each row into a sorting index, terminate the first loop,
123413          ** then loop over the sorting index in order to get the output
123414          ** in sorted order
123415          */
123416          int regBase;
123417          int regRecord;
123418          int nCol;
123419          int nGroupBy;
123420  
123421          explainTempTable(pParse, 
123422              (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
123423                      "DISTINCT" : "GROUP BY");
123424  
123425          groupBySort = 1;
123426          nGroupBy = pGroupBy->nExpr;
123427          nCol = nGroupBy;
123428          j = nGroupBy;
123429          for(i=0; i<sAggInfo.nColumn; i++){
123430            if( sAggInfo.aCol[i].iSorterColumn>=j ){
123431              nCol++;
123432              j++;
123433            }
123434          }
123435          regBase = sqlite3GetTempRange(pParse, nCol);
123436          sqlite3ExprCacheClear(pParse);
123437          sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
123438          j = nGroupBy;
123439          for(i=0; i<sAggInfo.nColumn; i++){
123440            struct AggInfo_col *pCol = &sAggInfo.aCol[i];
123441            if( pCol->iSorterColumn>=j ){
123442              int r1 = j + regBase;
123443              sqlite3ExprCodeGetColumnToReg(pParse, 
123444                                 pCol->pTab, pCol->iColumn, pCol->iTable, r1);
123445              j++;
123446            }
123447          }
123448          regRecord = sqlite3GetTempReg(pParse);
123449          sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
123450          sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
123451          sqlite3ReleaseTempReg(pParse, regRecord);
123452          sqlite3ReleaseTempRange(pParse, regBase, nCol);
123453          sqlite3WhereEnd(pWInfo);
123454          sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
123455          sortOut = sqlite3GetTempReg(pParse);
123456          sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
123457          sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
123458          VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
123459          sAggInfo.useSortingIdx = 1;
123460          sqlite3ExprCacheClear(pParse);
123461  
123462        }
123463  
123464        /* If the index or temporary table used by the GROUP BY sort
123465        ** will naturally deliver rows in the order required by the ORDER BY
123466        ** clause, cancel the ephemeral table open coded earlier.
123467        **
123468        ** This is an optimization - the correct answer should result regardless.
123469        ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to 
123470        ** disable this optimization for testing purposes.  */
123471        if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder) 
123472         && (groupBySort || sqlite3WhereIsSorted(pWInfo))
123473        ){
123474          sSort.pOrderBy = 0;
123475          sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
123476        }
123477  
123478        /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
123479        ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
123480        ** Then compare the current GROUP BY terms against the GROUP BY terms
123481        ** from the previous row currently stored in a0, a1, a2...
123482        */
123483        addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
123484        sqlite3ExprCacheClear(pParse);
123485        if( groupBySort ){
123486          sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
123487                            sortOut, sortPTab);
123488        }
123489        for(j=0; j<pGroupBy->nExpr; j++){
123490          if( groupBySort ){
123491            sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
123492          }else{
123493            sAggInfo.directMode = 1;
123494            sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
123495          }
123496        }
123497        sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
123498                            (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
123499        addr1 = sqlite3VdbeCurrentAddr(v);
123500        sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
123501  
123502        /* Generate code that runs whenever the GROUP BY changes.
123503        ** Changes in the GROUP BY are detected by the previous code
123504        ** block.  If there were no changes, this block is skipped.
123505        **
123506        ** This code copies current group by terms in b0,b1,b2,...
123507        ** over to a0,a1,a2.  It then calls the output subroutine
123508        ** and resets the aggregate accumulator registers in preparation
123509        ** for the next GROUP BY batch.
123510        */
123511        sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
123512        sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
123513        VdbeComment((v, "output one row"));
123514        sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
123515        VdbeComment((v, "check abort flag"));
123516        sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
123517        VdbeComment((v, "reset accumulator"));
123518  
123519        /* Update the aggregate accumulators based on the content of
123520        ** the current row
123521        */
123522        sqlite3VdbeJumpHere(v, addr1);
123523        updateAccumulator(pParse, &sAggInfo);
123524        sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
123525        VdbeComment((v, "indicate data in accumulator"));
123526  
123527        /* End of the loop
123528        */
123529        if( groupBySort ){
123530          sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
123531          VdbeCoverage(v);
123532        }else{
123533          sqlite3WhereEnd(pWInfo);
123534          sqlite3VdbeChangeToNoop(v, addrSortingIdx);
123535        }
123536  
123537        /* Output the final row of result
123538        */
123539        sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
123540        VdbeComment((v, "output final row"));
123541  
123542        /* Jump over the subroutines
123543        */
123544        sqlite3VdbeGoto(v, addrEnd);
123545  
123546        /* Generate a subroutine that outputs a single row of the result
123547        ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
123548        ** is less than or equal to zero, the subroutine is a no-op.  If
123549        ** the processing calls for the query to abort, this subroutine
123550        ** increments the iAbortFlag memory location before returning in
123551        ** order to signal the caller to abort.
123552        */
123553        addrSetAbort = sqlite3VdbeCurrentAddr(v);
123554        sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
123555        VdbeComment((v, "set abort flag"));
123556        sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
123557        sqlite3VdbeResolveLabel(v, addrOutputRow);
123558        addrOutputRow = sqlite3VdbeCurrentAddr(v);
123559        sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
123560        VdbeCoverage(v);
123561        VdbeComment((v, "Groupby result generator entry point"));
123562        sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
123563        finalizeAggFunctions(pParse, &sAggInfo);
123564        sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
123565        selectInnerLoop(pParse, p, -1, &sSort,
123566                        &sDistinct, pDest,
123567                        addrOutputRow+1, addrSetAbort);
123568        sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
123569        VdbeComment((v, "end groupby result generator"));
123570  
123571        /* Generate a subroutine that will reset the group-by accumulator
123572        */
123573        sqlite3VdbeResolveLabel(v, addrReset);
123574        resetAccumulator(pParse, &sAggInfo);
123575        sqlite3VdbeAddOp1(v, OP_Return, regReset);
123576       
123577      } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
123578      else {
123579        ExprList *pDel = 0;
123580  #ifndef SQLITE_OMIT_BTREECOUNT
123581        Table *pTab;
123582        if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
123583          /* If isSimpleCount() returns a pointer to a Table structure, then
123584          ** the SQL statement is of the form:
123585          **
123586          **   SELECT count(*) FROM <tbl>
123587          **
123588          ** where the Table structure returned represents table <tbl>.
123589          **
123590          ** This statement is so common that it is optimized specially. The
123591          ** OP_Count instruction is executed either on the intkey table that
123592          ** contains the data for table <tbl> or on one of its indexes. It
123593          ** is better to execute the op on an index, as indexes are almost
123594          ** always spread across less pages than their corresponding tables.
123595          */
123596          const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
123597          const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
123598          Index *pIdx;                         /* Iterator variable */
123599          KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
123600          Index *pBest = 0;                    /* Best index found so far */
123601          int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
123602  
123603          sqlite3CodeVerifySchema(pParse, iDb);
123604          sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
123605  
123606          /* Search for the index that has the lowest scan cost.
123607          **
123608          ** (2011-04-15) Do not do a full scan of an unordered index.
123609          **
123610          ** (2013-10-03) Do not count the entries in a partial index.
123611          **
123612          ** In practice the KeyInfo structure will not be used. It is only 
123613          ** passed to keep OP_OpenRead happy.
123614          */
123615          if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
123616          for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
123617            if( pIdx->bUnordered==0
123618             && pIdx->szIdxRow<pTab->szTabRow
123619             && pIdx->pPartIdxWhere==0
123620             && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
123621            ){
123622              pBest = pIdx;
123623            }
123624          }
123625          if( pBest ){
123626            iRoot = pBest->tnum;
123627            pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
123628          }
123629  
123630          /* Open a read-only cursor, execute the OP_Count, close the cursor. */
123631          sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
123632          if( pKeyInfo ){
123633            sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
123634          }
123635          sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
123636          sqlite3VdbeAddOp1(v, OP_Close, iCsr);
123637          explainSimpleCount(pParse, pTab, pBest);
123638        }else
123639  #endif /* SQLITE_OMIT_BTREECOUNT */
123640        {
123641          /* Check if the query is of one of the following forms:
123642          **
123643          **   SELECT min(x) FROM ...
123644          **   SELECT max(x) FROM ...
123645          **
123646          ** If it is, then ask the code in where.c to attempt to sort results
123647          ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
123648          ** If where.c is able to produce results sorted in this order, then
123649          ** add vdbe code to break out of the processing loop after the 
123650          ** first iteration (since the first iteration of the loop is 
123651          ** guaranteed to operate on the row with the minimum or maximum 
123652          ** value of x, the only row required).
123653          **
123654          ** A special flag must be passed to sqlite3WhereBegin() to slightly
123655          ** modify behavior as follows:
123656          **
123657          **   + If the query is a "SELECT min(x)", then the loop coded by
123658          **     where.c should not iterate over any values with a NULL value
123659          **     for x.
123660          **
123661          **   + The optimizer code in where.c (the thing that decides which
123662          **     index or indices to use) should place a different priority on 
123663          **     satisfying the 'ORDER BY' clause than it does in other cases.
123664          **     Refer to code and comments in where.c for details.
123665          */
123666          ExprList *pMinMax = 0;
123667          u8 flag = WHERE_ORDERBY_NORMAL;
123668          
123669          assert( p->pGroupBy==0 );
123670          assert( flag==0 );
123671          if( p->pHaving==0 ){
123672            flag = minMaxQuery(&sAggInfo, &pMinMax);
123673          }
123674          assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
123675  
123676          if( flag ){
123677            pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
123678            pDel = pMinMax;
123679            assert( db->mallocFailed || pMinMax!=0 );
123680            if( !db->mallocFailed ){
123681              pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
123682              pMinMax->a[0].pExpr->op = TK_COLUMN;
123683            }
123684          }
123685    
123686          /* This case runs if the aggregate has no GROUP BY clause.  The
123687          ** processing is much simpler since there is only a single row
123688          ** of output.
123689          */
123690          resetAccumulator(pParse, &sAggInfo);
123691          pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax, 0,flag,0);
123692          if( pWInfo==0 ){
123693            sqlite3ExprListDelete(db, pDel);
123694            goto select_end;
123695          }
123696          updateAccumulator(pParse, &sAggInfo);
123697          assert( pMinMax==0 || pMinMax->nExpr==1 );
123698          if( sqlite3WhereIsOrdered(pWInfo)>0 ){
123699            sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
123700            VdbeComment((v, "%s() by index",
123701                  (flag==WHERE_ORDERBY_MIN?"min":"max")));
123702          }
123703          sqlite3WhereEnd(pWInfo);
123704          finalizeAggFunctions(pParse, &sAggInfo);
123705        }
123706  
123707        sSort.pOrderBy = 0;
123708        sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
123709        selectInnerLoop(pParse, p, -1, 0, 0, 
123710                        pDest, addrEnd, addrEnd);
123711        sqlite3ExprListDelete(db, pDel);
123712      }
123713      sqlite3VdbeResolveLabel(v, addrEnd);
123714      
123715    } /* endif aggregate query */
123716  
123717    if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
123718      explainTempTable(pParse, "DISTINCT");
123719    }
123720  
123721    /* If there is an ORDER BY clause, then we need to sort the results
123722    ** and send them to the callback one by one.
123723    */
123724    if( sSort.pOrderBy ){
123725      explainTempTable(pParse,
123726                       sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
123727      generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
123728    }
123729  
123730    /* Jump here to skip this query
123731    */
123732    sqlite3VdbeResolveLabel(v, iEnd);
123733  
123734    /* The SELECT has been coded. If there is an error in the Parse structure,
123735    ** set the return code to 1. Otherwise 0. */
123736    rc = (pParse->nErr>0);
123737  
123738    /* Control jumps to here if an error is encountered above, or upon
123739    ** successful coding of the SELECT.
123740    */
123741  select_end:
123742    explainSetInteger(pParse->iSelectId, iRestoreSelectId);
123743  
123744    sqlite3DbFree(db, sAggInfo.aCol);
123745    sqlite3DbFree(db, sAggInfo.aFunc);
123746  #if SELECTTRACE_ENABLED
123747    SELECTTRACE(1,pParse,p,("end processing\n"));
123748    pParse->nSelectIndent--;
123749  #endif
123750    return rc;
123751  }
123752  
123753  /************** End of select.c **********************************************/
123754  /************** Begin file table.c *******************************************/
123755  /*
123756  ** 2001 September 15
123757  **
123758  ** The author disclaims copyright to this source code.  In place of
123759  ** a legal notice, here is a blessing:
123760  **
123761  **    May you do good and not evil.
123762  **    May you find forgiveness for yourself and forgive others.
123763  **    May you share freely, never taking more than you give.
123764  **
123765  *************************************************************************
123766  ** This file contains the sqlite3_get_table() and sqlite3_free_table()
123767  ** interface routines.  These are just wrappers around the main
123768  ** interface routine of sqlite3_exec().
123769  **
123770  ** These routines are in a separate files so that they will not be linked
123771  ** if they are not used.
123772  */
123773  /* #include "sqliteInt.h" */
123774  
123775  #ifndef SQLITE_OMIT_GET_TABLE
123776  
123777  /*
123778  ** This structure is used to pass data from sqlite3_get_table() through
123779  ** to the callback function is uses to build the result.
123780  */
123781  typedef struct TabResult {
123782    char **azResult;   /* Accumulated output */
123783    char *zErrMsg;     /* Error message text, if an error occurs */
123784    u32 nAlloc;        /* Slots allocated for azResult[] */
123785    u32 nRow;          /* Number of rows in the result */
123786    u32 nColumn;       /* Number of columns in the result */
123787    u32 nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
123788    int rc;            /* Return code from sqlite3_exec() */
123789  } TabResult;
123790  
123791  /*
123792  ** This routine is called once for each row in the result table.  Its job
123793  ** is to fill in the TabResult structure appropriately, allocating new
123794  ** memory as necessary.
123795  */
123796  static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
123797    TabResult *p = (TabResult*)pArg;  /* Result accumulator */
123798    int need;                         /* Slots needed in p->azResult[] */
123799    int i;                            /* Loop counter */
123800    char *z;                          /* A single column of result */
123801  
123802    /* Make sure there is enough space in p->azResult to hold everything
123803    ** we need to remember from this invocation of the callback.
123804    */
123805    if( p->nRow==0 && argv!=0 ){
123806      need = nCol*2;
123807    }else{
123808      need = nCol;
123809    }
123810    if( p->nData + need > p->nAlloc ){
123811      char **azNew;
123812      p->nAlloc = p->nAlloc*2 + need;
123813      azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
123814      if( azNew==0 ) goto malloc_failed;
123815      p->azResult = azNew;
123816    }
123817  
123818    /* If this is the first row, then generate an extra row containing
123819    ** the names of all columns.
123820    */
123821    if( p->nRow==0 ){
123822      p->nColumn = nCol;
123823      for(i=0; i<nCol; i++){
123824        z = sqlite3_mprintf("%s", colv[i]);
123825        if( z==0 ) goto malloc_failed;
123826        p->azResult[p->nData++] = z;
123827      }
123828    }else if( (int)p->nColumn!=nCol ){
123829      sqlite3_free(p->zErrMsg);
123830      p->zErrMsg = sqlite3_mprintf(
123831         "sqlite3_get_table() called with two or more incompatible queries"
123832      );
123833      p->rc = SQLITE_ERROR;
123834      return 1;
123835    }
123836  
123837    /* Copy over the row data
123838    */
123839    if( argv!=0 ){
123840      for(i=0; i<nCol; i++){
123841        if( argv[i]==0 ){
123842          z = 0;
123843        }else{
123844          int n = sqlite3Strlen30(argv[i])+1;
123845          z = sqlite3_malloc64( n );
123846          if( z==0 ) goto malloc_failed;
123847          memcpy(z, argv[i], n);
123848        }
123849        p->azResult[p->nData++] = z;
123850      }
123851      p->nRow++;
123852    }
123853    return 0;
123854  
123855  malloc_failed:
123856    p->rc = SQLITE_NOMEM_BKPT;
123857    return 1;
123858  }
123859  
123860  /*
123861  ** Query the database.  But instead of invoking a callback for each row,
123862  ** malloc() for space to hold the result and return the entire results
123863  ** at the conclusion of the call.
123864  **
123865  ** The result that is written to ***pazResult is held in memory obtained
123866  ** from malloc().  But the caller cannot free this memory directly.  
123867  ** Instead, the entire table should be passed to sqlite3_free_table() when
123868  ** the calling procedure is finished using it.
123869  */
123870  SQLITE_API int sqlite3_get_table(
123871    sqlite3 *db,                /* The database on which the SQL executes */
123872    const char *zSql,           /* The SQL to be executed */
123873    char ***pazResult,          /* Write the result table here */
123874    int *pnRow,                 /* Write the number of rows in the result here */
123875    int *pnColumn,              /* Write the number of columns of result here */
123876    char **pzErrMsg             /* Write error messages here */
123877  ){
123878    int rc;
123879    TabResult res;
123880  
123881  #ifdef SQLITE_ENABLE_API_ARMOR
123882    if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
123883  #endif
123884    *pazResult = 0;
123885    if( pnColumn ) *pnColumn = 0;
123886    if( pnRow ) *pnRow = 0;
123887    if( pzErrMsg ) *pzErrMsg = 0;
123888    res.zErrMsg = 0;
123889    res.nRow = 0;
123890    res.nColumn = 0;
123891    res.nData = 1;
123892    res.nAlloc = 20;
123893    res.rc = SQLITE_OK;
123894    res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
123895    if( res.azResult==0 ){
123896       db->errCode = SQLITE_NOMEM;
123897       return SQLITE_NOMEM_BKPT;
123898    }
123899    res.azResult[0] = 0;
123900    rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
123901    assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
123902    res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
123903    if( (rc&0xff)==SQLITE_ABORT ){
123904      sqlite3_free_table(&res.azResult[1]);
123905      if( res.zErrMsg ){
123906        if( pzErrMsg ){
123907          sqlite3_free(*pzErrMsg);
123908          *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
123909        }
123910        sqlite3_free(res.zErrMsg);
123911      }
123912      db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
123913      return res.rc;
123914    }
123915    sqlite3_free(res.zErrMsg);
123916    if( rc!=SQLITE_OK ){
123917      sqlite3_free_table(&res.azResult[1]);
123918      return rc;
123919    }
123920    if( res.nAlloc>res.nData ){
123921      char **azNew;
123922      azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
123923      if( azNew==0 ){
123924        sqlite3_free_table(&res.azResult[1]);
123925        db->errCode = SQLITE_NOMEM;
123926        return SQLITE_NOMEM_BKPT;
123927      }
123928      res.azResult = azNew;
123929    }
123930    *pazResult = &res.azResult[1];
123931    if( pnColumn ) *pnColumn = res.nColumn;
123932    if( pnRow ) *pnRow = res.nRow;
123933    return rc;
123934  }
123935  
123936  /*
123937  ** This routine frees the space the sqlite3_get_table() malloced.
123938  */
123939  SQLITE_API void sqlite3_free_table(
123940    char **azResult            /* Result returned from sqlite3_get_table() */
123941  ){
123942    if( azResult ){
123943      int i, n;
123944      azResult--;
123945      assert( azResult!=0 );
123946      n = SQLITE_PTR_TO_INT(azResult[0]);
123947      for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
123948      sqlite3_free(azResult);
123949    }
123950  }
123951  
123952  #endif /* SQLITE_OMIT_GET_TABLE */
123953  
123954  /************** End of table.c ***********************************************/
123955  /************** Begin file trigger.c *****************************************/
123956  /*
123957  **
123958  ** The author disclaims copyright to this source code.  In place of
123959  ** a legal notice, here is a blessing:
123960  **
123961  **    May you do good and not evil.
123962  **    May you find forgiveness for yourself and forgive others.
123963  **    May you share freely, never taking more than you give.
123964  **
123965  *************************************************************************
123966  ** This file contains the implementation for TRIGGERs
123967  */
123968  /* #include "sqliteInt.h" */
123969  
123970  #ifndef SQLITE_OMIT_TRIGGER
123971  /*
123972  ** Delete a linked list of TriggerStep structures.
123973  */
123974  SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
123975    while( pTriggerStep ){
123976      TriggerStep * pTmp = pTriggerStep;
123977      pTriggerStep = pTriggerStep->pNext;
123978  
123979      sqlite3ExprDelete(db, pTmp->pWhere);
123980      sqlite3ExprListDelete(db, pTmp->pExprList);
123981      sqlite3SelectDelete(db, pTmp->pSelect);
123982      sqlite3IdListDelete(db, pTmp->pIdList);
123983  
123984      sqlite3DbFree(db, pTmp);
123985    }
123986  }
123987  
123988  /*
123989  ** Given table pTab, return a list of all the triggers attached to 
123990  ** the table. The list is connected by Trigger.pNext pointers.
123991  **
123992  ** All of the triggers on pTab that are in the same database as pTab
123993  ** are already attached to pTab->pTrigger.  But there might be additional
123994  ** triggers on pTab in the TEMP schema.  This routine prepends all
123995  ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
123996  ** and returns the combined list.
123997  **
123998  ** To state it another way:  This routine returns a list of all triggers
123999  ** that fire off of pTab.  The list will include any TEMP triggers on
124000  ** pTab as well as the triggers lised in pTab->pTrigger.
124001  */
124002  SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
124003    Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
124004    Trigger *pList = 0;                  /* List of triggers to return */
124005  
124006    if( pParse->disableTriggers ){
124007      return 0;
124008    }
124009  
124010    if( pTmpSchema!=pTab->pSchema ){
124011      HashElem *p;
124012      assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
124013      for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
124014        Trigger *pTrig = (Trigger *)sqliteHashData(p);
124015        if( pTrig->pTabSchema==pTab->pSchema
124016         && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
124017        ){
124018          pTrig->pNext = (pList ? pList : pTab->pTrigger);
124019          pList = pTrig;
124020        }
124021      }
124022    }
124023  
124024    return (pList ? pList : pTab->pTrigger);
124025  }
124026  
124027  /*
124028  ** This is called by the parser when it sees a CREATE TRIGGER statement
124029  ** up to the point of the BEGIN before the trigger actions.  A Trigger
124030  ** structure is generated based on the information available and stored
124031  ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
124032  ** sqlite3FinishTrigger() function is called to complete the trigger
124033  ** construction process.
124034  */
124035  SQLITE_PRIVATE void sqlite3BeginTrigger(
124036    Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
124037    Token *pName1,      /* The name of the trigger */
124038    Token *pName2,      /* The name of the trigger */
124039    int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
124040    int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
124041    IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
124042    SrcList *pTableName,/* The name of the table/view the trigger applies to */
124043    Expr *pWhen,        /* WHEN clause */
124044    int isTemp,         /* True if the TEMPORARY keyword is present */
124045    int noErr           /* Suppress errors if the trigger already exists */
124046  ){
124047    Trigger *pTrigger = 0;  /* The new trigger */
124048    Table *pTab;            /* Table that the trigger fires off of */
124049    char *zName = 0;        /* Name of the trigger */
124050    sqlite3 *db = pParse->db;  /* The database connection */
124051    int iDb;                /* The database to store the trigger in */
124052    Token *pName;           /* The unqualified db name */
124053    DbFixer sFix;           /* State vector for the DB fixer */
124054  
124055    assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
124056    assert( pName2!=0 );
124057    assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
124058    assert( op>0 && op<0xff );
124059    if( isTemp ){
124060      /* If TEMP was specified, then the trigger name may not be qualified. */
124061      if( pName2->n>0 ){
124062        sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
124063        goto trigger_cleanup;
124064      }
124065      iDb = 1;
124066      pName = pName1;
124067    }else{
124068      /* Figure out the db that the trigger will be created in */
124069      iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
124070      if( iDb<0 ){
124071        goto trigger_cleanup;
124072      }
124073    }
124074    if( !pTableName || db->mallocFailed ){
124075      goto trigger_cleanup;
124076    }
124077  
124078    /* A long-standing parser bug is that this syntax was allowed:
124079    **
124080    **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
124081    **                                                 ^^^^^^^^
124082    **
124083    ** To maintain backwards compatibility, ignore the database
124084    ** name on pTableName if we are reparsing out of SQLITE_MASTER.
124085    */
124086    if( db->init.busy && iDb!=1 ){
124087      sqlite3DbFree(db, pTableName->a[0].zDatabase);
124088      pTableName->a[0].zDatabase = 0;
124089    }
124090  
124091    /* If the trigger name was unqualified, and the table is a temp table,
124092    ** then set iDb to 1 to create the trigger in the temporary database.
124093    ** If sqlite3SrcListLookup() returns 0, indicating the table does not
124094    ** exist, the error is caught by the block below.
124095    */
124096    pTab = sqlite3SrcListLookup(pParse, pTableName);
124097    if( db->init.busy==0 && pName2->n==0 && pTab
124098          && pTab->pSchema==db->aDb[1].pSchema ){
124099      iDb = 1;
124100    }
124101  
124102    /* Ensure the table name matches database name and that the table exists */
124103    if( db->mallocFailed ) goto trigger_cleanup;
124104    assert( pTableName->nSrc==1 );
124105    sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
124106    if( sqlite3FixSrcList(&sFix, pTableName) ){
124107      goto trigger_cleanup;
124108    }
124109    pTab = sqlite3SrcListLookup(pParse, pTableName);
124110    if( !pTab ){
124111      /* The table does not exist. */
124112      if( db->init.iDb==1 ){
124113        /* Ticket #3810.
124114        ** Normally, whenever a table is dropped, all associated triggers are
124115        ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
124116        ** and the table is dropped by a different database connection, the
124117        ** trigger is not visible to the database connection that does the
124118        ** drop so the trigger cannot be dropped.  This results in an
124119        ** "orphaned trigger" - a trigger whose associated table is missing.
124120        */
124121        db->init.orphanTrigger = 1;
124122      }
124123      goto trigger_cleanup;
124124    }
124125    if( IsVirtual(pTab) ){
124126      sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
124127      goto trigger_cleanup;
124128    }
124129  
124130    /* Check that the trigger name is not reserved and that no trigger of the
124131    ** specified name exists */
124132    zName = sqlite3NameFromToken(db, pName);
124133    if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
124134      goto trigger_cleanup;
124135    }
124136    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
124137    if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
124138      if( !noErr ){
124139        sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
124140      }else{
124141        assert( !db->init.busy );
124142        sqlite3CodeVerifySchema(pParse, iDb);
124143      }
124144      goto trigger_cleanup;
124145    }
124146  
124147    /* Do not create a trigger on a system table */
124148    if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
124149      sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
124150      goto trigger_cleanup;
124151    }
124152  
124153    /* INSTEAD of triggers are only for views and views only support INSTEAD
124154    ** of triggers.
124155    */
124156    if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
124157      sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
124158          (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
124159      goto trigger_cleanup;
124160    }
124161    if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
124162      sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
124163          " trigger on table: %S", pTableName, 0);
124164      goto trigger_cleanup;
124165    }
124166  
124167  #ifndef SQLITE_OMIT_AUTHORIZATION
124168    {
124169      int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
124170      int code = SQLITE_CREATE_TRIGGER;
124171      const char *zDb = db->aDb[iTabDb].zDbSName;
124172      const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
124173      if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
124174      if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
124175        goto trigger_cleanup;
124176      }
124177      if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
124178        goto trigger_cleanup;
124179      }
124180    }
124181  #endif
124182  
124183    /* INSTEAD OF triggers can only appear on views and BEFORE triggers
124184    ** cannot appear on views.  So we might as well translate every
124185    ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
124186    ** elsewhere.
124187    */
124188    if (tr_tm == TK_INSTEAD){
124189      tr_tm = TK_BEFORE;
124190    }
124191  
124192    /* Build the Trigger object */
124193    pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
124194    if( pTrigger==0 ) goto trigger_cleanup;
124195    pTrigger->zName = zName;
124196    zName = 0;
124197    pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
124198    pTrigger->pSchema = db->aDb[iDb].pSchema;
124199    pTrigger->pTabSchema = pTab->pSchema;
124200    pTrigger->op = (u8)op;
124201    pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
124202    pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
124203    pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
124204    assert( pParse->pNewTrigger==0 );
124205    pParse->pNewTrigger = pTrigger;
124206  
124207  trigger_cleanup:
124208    sqlite3DbFree(db, zName);
124209    sqlite3SrcListDelete(db, pTableName);
124210    sqlite3IdListDelete(db, pColumns);
124211    sqlite3ExprDelete(db, pWhen);
124212    if( !pParse->pNewTrigger ){
124213      sqlite3DeleteTrigger(db, pTrigger);
124214    }else{
124215      assert( pParse->pNewTrigger==pTrigger );
124216    }
124217  }
124218  
124219  /*
124220  ** This routine is called after all of the trigger actions have been parsed
124221  ** in order to complete the process of building the trigger.
124222  */
124223  SQLITE_PRIVATE void sqlite3FinishTrigger(
124224    Parse *pParse,          /* Parser context */
124225    TriggerStep *pStepList, /* The triggered program */
124226    Token *pAll             /* Token that describes the complete CREATE TRIGGER */
124227  ){
124228    Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
124229    char *zName;                            /* Name of trigger */
124230    sqlite3 *db = pParse->db;               /* The database */
124231    DbFixer sFix;                           /* Fixer object */
124232    int iDb;                                /* Database containing the trigger */
124233    Token nameToken;                        /* Trigger name for error reporting */
124234  
124235    pParse->pNewTrigger = 0;
124236    if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
124237    zName = pTrig->zName;
124238    iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
124239    pTrig->step_list = pStepList;
124240    while( pStepList ){
124241      pStepList->pTrig = pTrig;
124242      pStepList = pStepList->pNext;
124243    }
124244    sqlite3TokenInit(&nameToken, pTrig->zName);
124245    sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
124246    if( sqlite3FixTriggerStep(&sFix, pTrig->step_list) 
124247     || sqlite3FixExpr(&sFix, pTrig->pWhen) 
124248    ){
124249      goto triggerfinish_cleanup;
124250    }
124251  
124252    /* if we are not initializing,
124253    ** build the sqlite_master entry
124254    */
124255    if( !db->init.busy ){
124256      Vdbe *v;
124257      char *z;
124258  
124259      /* Make an entry in the sqlite_master table */
124260      v = sqlite3GetVdbe(pParse);
124261      if( v==0 ) goto triggerfinish_cleanup;
124262      sqlite3BeginWriteOperation(pParse, 0, iDb);
124263      z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
124264      testcase( z==0 );
124265      sqlite3NestedParse(pParse,
124266         "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
124267         db->aDb[iDb].zDbSName, MASTER_NAME, zName,
124268         pTrig->table, z);
124269      sqlite3DbFree(db, z);
124270      sqlite3ChangeCookie(pParse, iDb);
124271      sqlite3VdbeAddParseSchemaOp(v, iDb,
124272          sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
124273    }
124274  
124275    if( db->init.busy ){
124276      Trigger *pLink = pTrig;
124277      Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
124278      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
124279      pTrig = sqlite3HashInsert(pHash, zName, pTrig);
124280      if( pTrig ){
124281        sqlite3OomFault(db);
124282      }else if( pLink->pSchema==pLink->pTabSchema ){
124283        Table *pTab;
124284        pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
124285        assert( pTab!=0 );
124286        pLink->pNext = pTab->pTrigger;
124287        pTab->pTrigger = pLink;
124288      }
124289    }
124290  
124291  triggerfinish_cleanup:
124292    sqlite3DeleteTrigger(db, pTrig);
124293    assert( !pParse->pNewTrigger );
124294    sqlite3DeleteTriggerStep(db, pStepList);
124295  }
124296  
124297  /*
124298  ** Turn a SELECT statement (that the pSelect parameter points to) into
124299  ** a trigger step.  Return a pointer to a TriggerStep structure.
124300  **
124301  ** The parser calls this routine when it finds a SELECT statement in
124302  ** body of a TRIGGER.  
124303  */
124304  SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
124305    TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
124306    if( pTriggerStep==0 ) {
124307      sqlite3SelectDelete(db, pSelect);
124308      return 0;
124309    }
124310    pTriggerStep->op = TK_SELECT;
124311    pTriggerStep->pSelect = pSelect;
124312    pTriggerStep->orconf = OE_Default;
124313    return pTriggerStep;
124314  }
124315  
124316  /*
124317  ** Allocate space to hold a new trigger step.  The allocated space
124318  ** holds both the TriggerStep object and the TriggerStep.target.z string.
124319  **
124320  ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
124321  */
124322  static TriggerStep *triggerStepAllocate(
124323    sqlite3 *db,                /* Database connection */
124324    u8 op,                      /* Trigger opcode */
124325    Token *pName                /* The target name */
124326  ){
124327    TriggerStep *pTriggerStep;
124328  
124329    pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
124330    if( pTriggerStep ){
124331      char *z = (char*)&pTriggerStep[1];
124332      memcpy(z, pName->z, pName->n);
124333      sqlite3Dequote(z);
124334      pTriggerStep->zTarget = z;
124335      pTriggerStep->op = op;
124336    }
124337    return pTriggerStep;
124338  }
124339  
124340  /*
124341  ** Build a trigger step out of an INSERT statement.  Return a pointer
124342  ** to the new trigger step.
124343  **
124344  ** The parser calls this routine when it sees an INSERT inside the
124345  ** body of a trigger.
124346  */
124347  SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
124348    sqlite3 *db,        /* The database connection */
124349    Token *pTableName,  /* Name of the table into which we insert */
124350    IdList *pColumn,    /* List of columns in pTableName to insert into */
124351    Select *pSelect,    /* A SELECT statement that supplies values */
124352    u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
124353  ){
124354    TriggerStep *pTriggerStep;
124355  
124356    assert(pSelect != 0 || db->mallocFailed);
124357  
124358    pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
124359    if( pTriggerStep ){
124360      pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
124361      pTriggerStep->pIdList = pColumn;
124362      pTriggerStep->orconf = orconf;
124363    }else{
124364      sqlite3IdListDelete(db, pColumn);
124365    }
124366    sqlite3SelectDelete(db, pSelect);
124367  
124368    return pTriggerStep;
124369  }
124370  
124371  /*
124372  ** Construct a trigger step that implements an UPDATE statement and return
124373  ** a pointer to that trigger step.  The parser calls this routine when it
124374  ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
124375  */
124376  SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
124377    sqlite3 *db,         /* The database connection */
124378    Token *pTableName,   /* Name of the table to be updated */
124379    ExprList *pEList,    /* The SET clause: list of column and new values */
124380    Expr *pWhere,        /* The WHERE clause */
124381    u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
124382  ){
124383    TriggerStep *pTriggerStep;
124384  
124385    pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
124386    if( pTriggerStep ){
124387      pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
124388      pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
124389      pTriggerStep->orconf = orconf;
124390    }
124391    sqlite3ExprListDelete(db, pEList);
124392    sqlite3ExprDelete(db, pWhere);
124393    return pTriggerStep;
124394  }
124395  
124396  /*
124397  ** Construct a trigger step that implements a DELETE statement and return
124398  ** a pointer to that trigger step.  The parser calls this routine when it
124399  ** sees a DELETE statement inside the body of a CREATE TRIGGER.
124400  */
124401  SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
124402    sqlite3 *db,            /* Database connection */
124403    Token *pTableName,      /* The table from which rows are deleted */
124404    Expr *pWhere            /* The WHERE clause */
124405  ){
124406    TriggerStep *pTriggerStep;
124407  
124408    pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
124409    if( pTriggerStep ){
124410      pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
124411      pTriggerStep->orconf = OE_Default;
124412    }
124413    sqlite3ExprDelete(db, pWhere);
124414    return pTriggerStep;
124415  }
124416  
124417  /* 
124418  ** Recursively delete a Trigger structure
124419  */
124420  SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
124421    if( pTrigger==0 ) return;
124422    sqlite3DeleteTriggerStep(db, pTrigger->step_list);
124423    sqlite3DbFree(db, pTrigger->zName);
124424    sqlite3DbFree(db, pTrigger->table);
124425    sqlite3ExprDelete(db, pTrigger->pWhen);
124426    sqlite3IdListDelete(db, pTrigger->pColumns);
124427    sqlite3DbFree(db, pTrigger);
124428  }
124429  
124430  /*
124431  ** This function is called to drop a trigger from the database schema. 
124432  **
124433  ** This may be called directly from the parser and therefore identifies
124434  ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
124435  ** same job as this routine except it takes a pointer to the trigger
124436  ** instead of the trigger name.
124437  **/
124438  SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
124439    Trigger *pTrigger = 0;
124440    int i;
124441    const char *zDb;
124442    const char *zName;
124443    sqlite3 *db = pParse->db;
124444  
124445    if( db->mallocFailed ) goto drop_trigger_cleanup;
124446    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
124447      goto drop_trigger_cleanup;
124448    }
124449  
124450    assert( pName->nSrc==1 );
124451    zDb = pName->a[0].zDatabase;
124452    zName = pName->a[0].zName;
124453    assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
124454    for(i=OMIT_TEMPDB; i<db->nDb; i++){
124455      int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
124456      if( zDb && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue;
124457      assert( sqlite3SchemaMutexHeld(db, j, 0) );
124458      pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
124459      if( pTrigger ) break;
124460    }
124461    if( !pTrigger ){
124462      if( !noErr ){
124463        sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
124464      }else{
124465        sqlite3CodeVerifyNamedSchema(pParse, zDb);
124466      }
124467      pParse->checkSchema = 1;
124468      goto drop_trigger_cleanup;
124469    }
124470    sqlite3DropTriggerPtr(pParse, pTrigger);
124471  
124472  drop_trigger_cleanup:
124473    sqlite3SrcListDelete(db, pName);
124474  }
124475  
124476  /*
124477  ** Return a pointer to the Table structure for the table that a trigger
124478  ** is set on.
124479  */
124480  static Table *tableOfTrigger(Trigger *pTrigger){
124481    return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
124482  }
124483  
124484  
124485  /*
124486  ** Drop a trigger given a pointer to that trigger. 
124487  */
124488  SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
124489    Table   *pTable;
124490    Vdbe *v;
124491    sqlite3 *db = pParse->db;
124492    int iDb;
124493  
124494    iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
124495    assert( iDb>=0 && iDb<db->nDb );
124496    pTable = tableOfTrigger(pTrigger);
124497    assert( pTable );
124498    assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
124499  #ifndef SQLITE_OMIT_AUTHORIZATION
124500    {
124501      int code = SQLITE_DROP_TRIGGER;
124502      const char *zDb = db->aDb[iDb].zDbSName;
124503      const char *zTab = SCHEMA_TABLE(iDb);
124504      if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
124505      if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
124506        sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
124507        return;
124508      }
124509    }
124510  #endif
124511  
124512    /* Generate code to destroy the database record of the trigger.
124513    */
124514    assert( pTable!=0 );
124515    if( (v = sqlite3GetVdbe(pParse))!=0 ){
124516      sqlite3NestedParse(pParse,
124517         "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
124518         db->aDb[iDb].zDbSName, MASTER_NAME, pTrigger->zName
124519      );
124520      sqlite3ChangeCookie(pParse, iDb);
124521      sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
124522    }
124523  }
124524  
124525  /*
124526  ** Remove a trigger from the hash tables of the sqlite* pointer.
124527  */
124528  SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
124529    Trigger *pTrigger;
124530    Hash *pHash;
124531  
124532    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
124533    pHash = &(db->aDb[iDb].pSchema->trigHash);
124534    pTrigger = sqlite3HashInsert(pHash, zName, 0);
124535    if( ALWAYS(pTrigger) ){
124536      if( pTrigger->pSchema==pTrigger->pTabSchema ){
124537        Table *pTab = tableOfTrigger(pTrigger);
124538        Trigger **pp;
124539        for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
124540        *pp = (*pp)->pNext;
124541      }
124542      sqlite3DeleteTrigger(db, pTrigger);
124543      db->mDbFlags |= DBFLAG_SchemaChange;
124544    }
124545  }
124546  
124547  /*
124548  ** pEList is the SET clause of an UPDATE statement.  Each entry
124549  ** in pEList is of the format <id>=<expr>.  If any of the entries
124550  ** in pEList have an <id> which matches an identifier in pIdList,
124551  ** then return TRUE.  If pIdList==NULL, then it is considered a
124552  ** wildcard that matches anything.  Likewise if pEList==NULL then
124553  ** it matches anything so always return true.  Return false only
124554  ** if there is no match.
124555  */
124556  static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
124557    int e;
124558    if( pIdList==0 || NEVER(pEList==0) ) return 1;
124559    for(e=0; e<pEList->nExpr; e++){
124560      if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
124561    }
124562    return 0; 
124563  }
124564  
124565  /*
124566  ** Return a list of all triggers on table pTab if there exists at least
124567  ** one trigger that must be fired when an operation of type 'op' is 
124568  ** performed on the table, and, if that operation is an UPDATE, if at
124569  ** least one of the columns in pChanges is being modified.
124570  */
124571  SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
124572    Parse *pParse,          /* Parse context */
124573    Table *pTab,            /* The table the contains the triggers */
124574    int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
124575    ExprList *pChanges,     /* Columns that change in an UPDATE statement */
124576    int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
124577  ){
124578    int mask = 0;
124579    Trigger *pList = 0;
124580    Trigger *p;
124581  
124582    if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
124583      pList = sqlite3TriggerList(pParse, pTab);
124584    }
124585    assert( pList==0 || IsVirtual(pTab)==0 );
124586    for(p=pList; p; p=p->pNext){
124587      if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
124588        mask |= p->tr_tm;
124589      }
124590    }
124591    if( pMask ){
124592      *pMask = mask;
124593    }
124594    return (mask ? pList : 0);
124595  }
124596  
124597  /*
124598  ** Convert the pStep->zTarget string into a SrcList and return a pointer
124599  ** to that SrcList.
124600  **
124601  ** This routine adds a specific database name, if needed, to the target when
124602  ** forming the SrcList.  This prevents a trigger in one database from
124603  ** referring to a target in another database.  An exception is when the
124604  ** trigger is in TEMP in which case it can refer to any other database it
124605  ** wants.
124606  */
124607  static SrcList *targetSrcList(
124608    Parse *pParse,       /* The parsing context */
124609    TriggerStep *pStep   /* The trigger containing the target token */
124610  ){
124611    sqlite3 *db = pParse->db;
124612    int iDb;             /* Index of the database to use */
124613    SrcList *pSrc;       /* SrcList to be returned */
124614  
124615    pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
124616    if( pSrc ){
124617      assert( pSrc->nSrc>0 );
124618      pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
124619      iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
124620      if( iDb==0 || iDb>=2 ){
124621        const char *zDb;
124622        assert( iDb<db->nDb );
124623        zDb = db->aDb[iDb].zDbSName;
124624        pSrc->a[pSrc->nSrc-1].zDatabase =  sqlite3DbStrDup(db, zDb);
124625      }
124626    }
124627    return pSrc;
124628  }
124629  
124630  /*
124631  ** Generate VDBE code for the statements inside the body of a single 
124632  ** trigger.
124633  */
124634  static int codeTriggerProgram(
124635    Parse *pParse,            /* The parser context */
124636    TriggerStep *pStepList,   /* List of statements inside the trigger body */
124637    int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
124638  ){
124639    TriggerStep *pStep;
124640    Vdbe *v = pParse->pVdbe;
124641    sqlite3 *db = pParse->db;
124642  
124643    assert( pParse->pTriggerTab && pParse->pToplevel );
124644    assert( pStepList );
124645    assert( v!=0 );
124646    for(pStep=pStepList; pStep; pStep=pStep->pNext){
124647      /* Figure out the ON CONFLICT policy that will be used for this step
124648      ** of the trigger program. If the statement that caused this trigger
124649      ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
124650      ** the ON CONFLICT policy that was specified as part of the trigger
124651      ** step statement. Example:
124652      **
124653      **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
124654      **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
124655      **   END;
124656      **
124657      **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
124658      **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
124659      */
124660      pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
124661      assert( pParse->okConstFactor==0 );
124662  
124663      switch( pStep->op ){
124664        case TK_UPDATE: {
124665          sqlite3Update(pParse, 
124666            targetSrcList(pParse, pStep),
124667            sqlite3ExprListDup(db, pStep->pExprList, 0), 
124668            sqlite3ExprDup(db, pStep->pWhere, 0), 
124669            pParse->eOrconf
124670          );
124671          break;
124672        }
124673        case TK_INSERT: {
124674          sqlite3Insert(pParse, 
124675            targetSrcList(pParse, pStep),
124676            sqlite3SelectDup(db, pStep->pSelect, 0), 
124677            sqlite3IdListDup(db, pStep->pIdList), 
124678            pParse->eOrconf
124679          );
124680          break;
124681        }
124682        case TK_DELETE: {
124683          sqlite3DeleteFrom(pParse, 
124684            targetSrcList(pParse, pStep),
124685            sqlite3ExprDup(db, pStep->pWhere, 0)
124686          );
124687          break;
124688        }
124689        default: assert( pStep->op==TK_SELECT ); {
124690          SelectDest sDest;
124691          Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
124692          sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
124693          sqlite3Select(pParse, pSelect, &sDest);
124694          sqlite3SelectDelete(db, pSelect);
124695          break;
124696        }
124697      } 
124698      if( pStep->op!=TK_SELECT ){
124699        sqlite3VdbeAddOp0(v, OP_ResetCount);
124700      }
124701    }
124702  
124703    return 0;
124704  }
124705  
124706  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
124707  /*
124708  ** This function is used to add VdbeComment() annotations to a VDBE
124709  ** program. It is not used in production code, only for debugging.
124710  */
124711  static const char *onErrorText(int onError){
124712    switch( onError ){
124713      case OE_Abort:    return "abort";
124714      case OE_Rollback: return "rollback";
124715      case OE_Fail:     return "fail";
124716      case OE_Replace:  return "replace";
124717      case OE_Ignore:   return "ignore";
124718      case OE_Default:  return "default";
124719    }
124720    return "n/a";
124721  }
124722  #endif
124723  
124724  /*
124725  ** Parse context structure pFrom has just been used to create a sub-vdbe
124726  ** (trigger program). If an error has occurred, transfer error information
124727  ** from pFrom to pTo.
124728  */
124729  static void transferParseError(Parse *pTo, Parse *pFrom){
124730    assert( pFrom->zErrMsg==0 || pFrom->nErr );
124731    assert( pTo->zErrMsg==0 || pTo->nErr );
124732    if( pTo->nErr==0 ){
124733      pTo->zErrMsg = pFrom->zErrMsg;
124734      pTo->nErr = pFrom->nErr;
124735      pTo->rc = pFrom->rc;
124736    }else{
124737      sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
124738    }
124739  }
124740  
124741  /*
124742  ** Create and populate a new TriggerPrg object with a sub-program 
124743  ** implementing trigger pTrigger with ON CONFLICT policy orconf.
124744  */
124745  static TriggerPrg *codeRowTrigger(
124746    Parse *pParse,       /* Current parse context */
124747    Trigger *pTrigger,   /* Trigger to code */
124748    Table *pTab,         /* The table pTrigger is attached to */
124749    int orconf           /* ON CONFLICT policy to code trigger program with */
124750  ){
124751    Parse *pTop = sqlite3ParseToplevel(pParse);
124752    sqlite3 *db = pParse->db;   /* Database handle */
124753    TriggerPrg *pPrg;           /* Value to return */
124754    Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
124755    Vdbe *v;                    /* Temporary VM */
124756    NameContext sNC;            /* Name context for sub-vdbe */
124757    SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
124758    Parse *pSubParse;           /* Parse context for sub-vdbe */
124759    int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
124760  
124761    assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
124762    assert( pTop->pVdbe );
124763  
124764    /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
124765    ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
124766    ** list of the top-level Parse object sooner rather than later.  */
124767    pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
124768    if( !pPrg ) return 0;
124769    pPrg->pNext = pTop->pTriggerPrg;
124770    pTop->pTriggerPrg = pPrg;
124771    pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
124772    if( !pProgram ) return 0;
124773    sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
124774    pPrg->pTrigger = pTrigger;
124775    pPrg->orconf = orconf;
124776    pPrg->aColmask[0] = 0xffffffff;
124777    pPrg->aColmask[1] = 0xffffffff;
124778  
124779    /* Allocate and populate a new Parse context to use for coding the 
124780    ** trigger sub-program.  */
124781    pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
124782    if( !pSubParse ) return 0;
124783    memset(&sNC, 0, sizeof(sNC));
124784    sNC.pParse = pSubParse;
124785    pSubParse->db = db;
124786    pSubParse->pTriggerTab = pTab;
124787    pSubParse->pToplevel = pTop;
124788    pSubParse->zAuthContext = pTrigger->zName;
124789    pSubParse->eTriggerOp = pTrigger->op;
124790    pSubParse->nQueryLoop = pParse->nQueryLoop;
124791  
124792    v = sqlite3GetVdbe(pSubParse);
124793    if( v ){
124794      VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
124795        pTrigger->zName, onErrorText(orconf),
124796        (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
124797          (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
124798          (pTrigger->op==TK_INSERT ? "INSERT" : ""),
124799          (pTrigger->op==TK_DELETE ? "DELETE" : ""),
124800        pTab->zName
124801      ));
124802  #ifndef SQLITE_OMIT_TRACE
124803      sqlite3VdbeChangeP4(v, -1, 
124804        sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
124805      );
124806  #endif
124807  
124808      /* If one was specified, code the WHEN clause. If it evaluates to false
124809      ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
124810      ** OP_Halt inserted at the end of the program.  */
124811      if( pTrigger->pWhen ){
124812        pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
124813        if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
124814         && db->mallocFailed==0 
124815        ){
124816          iEndTrigger = sqlite3VdbeMakeLabel(v);
124817          sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
124818        }
124819        sqlite3ExprDelete(db, pWhen);
124820      }
124821  
124822      /* Code the trigger program into the sub-vdbe. */
124823      codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
124824  
124825      /* Insert an OP_Halt at the end of the sub-program. */
124826      if( iEndTrigger ){
124827        sqlite3VdbeResolveLabel(v, iEndTrigger);
124828      }
124829      sqlite3VdbeAddOp0(v, OP_Halt);
124830      VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
124831  
124832      transferParseError(pParse, pSubParse);
124833      if( db->mallocFailed==0 ){
124834        pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
124835      }
124836      pProgram->nMem = pSubParse->nMem;
124837      pProgram->nCsr = pSubParse->nTab;
124838      pProgram->token = (void *)pTrigger;
124839      pPrg->aColmask[0] = pSubParse->oldmask;
124840      pPrg->aColmask[1] = pSubParse->newmask;
124841      sqlite3VdbeDelete(v);
124842    }
124843  
124844    assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
124845    assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
124846    sqlite3ParserReset(pSubParse);
124847    sqlite3StackFree(db, pSubParse);
124848  
124849    return pPrg;
124850  }
124851      
124852  /*
124853  ** Return a pointer to a TriggerPrg object containing the sub-program for
124854  ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
124855  ** TriggerPrg object exists, a new object is allocated and populated before
124856  ** being returned.
124857  */
124858  static TriggerPrg *getRowTrigger(
124859    Parse *pParse,       /* Current parse context */
124860    Trigger *pTrigger,   /* Trigger to code */
124861    Table *pTab,         /* The table trigger pTrigger is attached to */
124862    int orconf           /* ON CONFLICT algorithm. */
124863  ){
124864    Parse *pRoot = sqlite3ParseToplevel(pParse);
124865    TriggerPrg *pPrg;
124866  
124867    assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
124868  
124869    /* It may be that this trigger has already been coded (or is in the
124870    ** process of being coded). If this is the case, then an entry with
124871    ** a matching TriggerPrg.pTrigger field will be present somewhere
124872    ** in the Parse.pTriggerPrg list. Search for such an entry.  */
124873    for(pPrg=pRoot->pTriggerPrg; 
124874        pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
124875        pPrg=pPrg->pNext
124876    );
124877  
124878    /* If an existing TriggerPrg could not be located, create a new one. */
124879    if( !pPrg ){
124880      pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
124881    }
124882  
124883    return pPrg;
124884  }
124885  
124886  /*
124887  ** Generate code for the trigger program associated with trigger p on 
124888  ** table pTab. The reg, orconf and ignoreJump parameters passed to this
124889  ** function are the same as those described in the header function for
124890  ** sqlite3CodeRowTrigger()
124891  */
124892  SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
124893    Parse *pParse,       /* Parse context */
124894    Trigger *p,          /* Trigger to code */
124895    Table *pTab,         /* The table to code triggers from */
124896    int reg,             /* Reg array containing OLD.* and NEW.* values */
124897    int orconf,          /* ON CONFLICT policy */
124898    int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
124899  ){
124900    Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
124901    TriggerPrg *pPrg;
124902    pPrg = getRowTrigger(pParse, p, pTab, orconf);
124903    assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
124904  
124905    /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
124906    ** is a pointer to the sub-vdbe containing the trigger program.  */
124907    if( pPrg ){
124908      int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
124909  
124910      sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
124911                        (const char *)pPrg->pProgram, P4_SUBPROGRAM);
124912      VdbeComment(
124913          (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
124914  
124915      /* Set the P5 operand of the OP_Program instruction to non-zero if
124916      ** recursive invocation of this trigger program is disallowed. Recursive
124917      ** invocation is disallowed if (a) the sub-program is really a trigger,
124918      ** not a foreign key action, and (b) the flag to enable recursive triggers
124919      ** is clear.  */
124920      sqlite3VdbeChangeP5(v, (u8)bRecursive);
124921    }
124922  }
124923  
124924  /*
124925  ** This is called to code the required FOR EACH ROW triggers for an operation
124926  ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
124927  ** is given by the op parameter. The tr_tm parameter determines whether the
124928  ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
124929  ** parameter pChanges is passed the list of columns being modified.
124930  **
124931  ** If there are no triggers that fire at the specified time for the specified
124932  ** operation on pTab, this function is a no-op.
124933  **
124934  ** The reg argument is the address of the first in an array of registers 
124935  ** that contain the values substituted for the new.* and old.* references
124936  ** in the trigger program. If N is the number of columns in table pTab
124937  ** (a copy of pTab->nCol), then registers are populated as follows:
124938  **
124939  **   Register       Contains
124940  **   ------------------------------------------------------
124941  **   reg+0          OLD.rowid
124942  **   reg+1          OLD.* value of left-most column of pTab
124943  **   ...            ...
124944  **   reg+N          OLD.* value of right-most column of pTab
124945  **   reg+N+1        NEW.rowid
124946  **   reg+N+2        OLD.* value of left-most column of pTab
124947  **   ...            ...
124948  **   reg+N+N+1      NEW.* value of right-most column of pTab
124949  **
124950  ** For ON DELETE triggers, the registers containing the NEW.* values will
124951  ** never be accessed by the trigger program, so they are not allocated or 
124952  ** populated by the caller (there is no data to populate them with anyway). 
124953  ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
124954  ** are never accessed, and so are not allocated by the caller. So, for an
124955  ** ON INSERT trigger, the value passed to this function as parameter reg
124956  ** is not a readable register, although registers (reg+N) through 
124957  ** (reg+N+N+1) are.
124958  **
124959  ** Parameter orconf is the default conflict resolution algorithm for the
124960  ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
124961  ** is the instruction that control should jump to if a trigger program
124962  ** raises an IGNORE exception.
124963  */
124964  SQLITE_PRIVATE void sqlite3CodeRowTrigger(
124965    Parse *pParse,       /* Parse context */
124966    Trigger *pTrigger,   /* List of triggers on table pTab */
124967    int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
124968    ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
124969    int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
124970    Table *pTab,         /* The table to code triggers from */
124971    int reg,             /* The first in an array of registers (see above) */
124972    int orconf,          /* ON CONFLICT policy */
124973    int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
124974  ){
124975    Trigger *p;          /* Used to iterate through pTrigger list */
124976  
124977    assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
124978    assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
124979    assert( (op==TK_UPDATE)==(pChanges!=0) );
124980  
124981    for(p=pTrigger; p; p=p->pNext){
124982  
124983      /* Sanity checking:  The schema for the trigger and for the table are
124984      ** always defined.  The trigger must be in the same schema as the table
124985      ** or else it must be a TEMP trigger. */
124986      assert( p->pSchema!=0 );
124987      assert( p->pTabSchema!=0 );
124988      assert( p->pSchema==p->pTabSchema 
124989           || p->pSchema==pParse->db->aDb[1].pSchema );
124990  
124991      /* Determine whether we should code this trigger */
124992      if( p->op==op 
124993       && p->tr_tm==tr_tm 
124994       && checkColumnOverlap(p->pColumns, pChanges)
124995      ){
124996        sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
124997      }
124998    }
124999  }
125000  
125001  /*
125002  ** Triggers may access values stored in the old.* or new.* pseudo-table. 
125003  ** This function returns a 32-bit bitmask indicating which columns of the 
125004  ** old.* or new.* tables actually are used by triggers. This information 
125005  ** may be used by the caller, for example, to avoid having to load the entire
125006  ** old.* record into memory when executing an UPDATE or DELETE command.
125007  **
125008  ** Bit 0 of the returned mask is set if the left-most column of the
125009  ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
125010  ** the second leftmost column value is required, and so on. If there
125011  ** are more than 32 columns in the table, and at least one of the columns
125012  ** with an index greater than 32 may be accessed, 0xffffffff is returned.
125013  **
125014  ** It is not possible to determine if the old.rowid or new.rowid column is 
125015  ** accessed by triggers. The caller must always assume that it is.
125016  **
125017  ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
125018  ** applies to the old.* table. If 1, the new.* table.
125019  **
125020  ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
125021  ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
125022  ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
125023  ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
125024  ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
125025  */
125026  SQLITE_PRIVATE u32 sqlite3TriggerColmask(
125027    Parse *pParse,       /* Parse context */
125028    Trigger *pTrigger,   /* List of triggers on table pTab */
125029    ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
125030    int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
125031    int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
125032    Table *pTab,         /* The table to code triggers from */
125033    int orconf           /* Default ON CONFLICT policy for trigger steps */
125034  ){
125035    const int op = pChanges ? TK_UPDATE : TK_DELETE;
125036    u32 mask = 0;
125037    Trigger *p;
125038  
125039    assert( isNew==1 || isNew==0 );
125040    for(p=pTrigger; p; p=p->pNext){
125041      if( p->op==op && (tr_tm&p->tr_tm)
125042       && checkColumnOverlap(p->pColumns,pChanges)
125043      ){
125044        TriggerPrg *pPrg;
125045        pPrg = getRowTrigger(pParse, p, pTab, orconf);
125046        if( pPrg ){
125047          mask |= pPrg->aColmask[isNew];
125048        }
125049      }
125050    }
125051  
125052    return mask;
125053  }
125054  
125055  #endif /* !defined(SQLITE_OMIT_TRIGGER) */
125056  
125057  /************** End of trigger.c *********************************************/
125058  /************** Begin file update.c ******************************************/
125059  /*
125060  ** 2001 September 15
125061  **
125062  ** The author disclaims copyright to this source code.  In place of
125063  ** a legal notice, here is a blessing:
125064  **
125065  **    May you do good and not evil.
125066  **    May you find forgiveness for yourself and forgive others.
125067  **    May you share freely, never taking more than you give.
125068  **
125069  *************************************************************************
125070  ** This file contains C code routines that are called by the parser
125071  ** to handle UPDATE statements.
125072  */
125073  /* #include "sqliteInt.h" */
125074  
125075  #ifndef SQLITE_OMIT_VIRTUALTABLE
125076  /* Forward declaration */
125077  static void updateVirtualTable(
125078    Parse *pParse,       /* The parsing context */
125079    SrcList *pSrc,       /* The virtual table to be modified */
125080    Table *pTab,         /* The virtual table */
125081    ExprList *pChanges,  /* The columns to change in the UPDATE statement */
125082    Expr *pRowidExpr,    /* Expression used to recompute the rowid */
125083    int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
125084    Expr *pWhere,        /* WHERE clause of the UPDATE statement */
125085    int onError          /* ON CONFLICT strategy */
125086  );
125087  #endif /* SQLITE_OMIT_VIRTUALTABLE */
125088  
125089  /*
125090  ** The most recently coded instruction was an OP_Column to retrieve the
125091  ** i-th column of table pTab. This routine sets the P4 parameter of the 
125092  ** OP_Column to the default value, if any.
125093  **
125094  ** The default value of a column is specified by a DEFAULT clause in the 
125095  ** column definition. This was either supplied by the user when the table
125096  ** was created, or added later to the table definition by an ALTER TABLE
125097  ** command. If the latter, then the row-records in the table btree on disk
125098  ** may not contain a value for the column and the default value, taken
125099  ** from the P4 parameter of the OP_Column instruction, is returned instead.
125100  ** If the former, then all row-records are guaranteed to include a value
125101  ** for the column and the P4 value is not required.
125102  **
125103  ** Column definitions created by an ALTER TABLE command may only have 
125104  ** literal default values specified: a number, null or a string. (If a more
125105  ** complicated default expression value was provided, it is evaluated 
125106  ** when the ALTER TABLE is executed and one of the literal values written
125107  ** into the sqlite_master table.)
125108  **
125109  ** Therefore, the P4 parameter is only required if the default value for
125110  ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
125111  ** function is capable of transforming these types of expressions into
125112  ** sqlite3_value objects.
125113  **
125114  ** If parameter iReg is not negative, code an OP_RealAffinity instruction
125115  ** on register iReg. This is used when an equivalent integer value is 
125116  ** stored in place of an 8-byte floating point value in order to save 
125117  ** space.
125118  */
125119  SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
125120    assert( pTab!=0 );
125121    if( !pTab->pSelect ){
125122      sqlite3_value *pValue = 0;
125123      u8 enc = ENC(sqlite3VdbeDb(v));
125124      Column *pCol = &pTab->aCol[i];
125125      VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
125126      assert( i<pTab->nCol );
125127      sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
125128                           pCol->affinity, &pValue);
125129      if( pValue ){
125130        sqlite3VdbeAppendP4(v, pValue, P4_MEM);
125131      }
125132    }
125133  #ifndef SQLITE_OMIT_FLOATING_POINT
125134    if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
125135      sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
125136    }
125137  #endif
125138  }
125139  
125140  /*
125141  ** Process an UPDATE statement.
125142  **
125143  **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
125144  **          \_______/ \________/     \______/       \________________/
125145  *            onError   pTabList      pChanges             pWhere
125146  */
125147  SQLITE_PRIVATE void sqlite3Update(
125148    Parse *pParse,         /* The parser context */
125149    SrcList *pTabList,     /* The table in which we should change things */
125150    ExprList *pChanges,    /* Things to be changed */
125151    Expr *pWhere,          /* The WHERE clause.  May be null */
125152    int onError            /* How to handle constraint errors */
125153  ){
125154    int i, j;              /* Loop counters */
125155    Table *pTab;           /* The table to be updated */
125156    int addrTop = 0;       /* VDBE instruction address of the start of the loop */
125157    WhereInfo *pWInfo;     /* Information about the WHERE clause */
125158    Vdbe *v;               /* The virtual database engine */
125159    Index *pIdx;           /* For looping over indices */
125160    Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
125161    int nIdx;              /* Number of indices that need updating */
125162    int iBaseCur;          /* Base cursor number */
125163    int iDataCur;          /* Cursor for the canonical data btree */
125164    int iIdxCur;           /* Cursor for the first index */
125165    sqlite3 *db;           /* The database structure */
125166    int *aRegIdx = 0;      /* First register in array assigned to each index */
125167    int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
125168                           ** an expression for the i-th column of the table.
125169                           ** aXRef[i]==-1 if the i-th column is not changed. */
125170    u8 *aToOpen;           /* 1 for tables and indices to be opened */
125171    u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */
125172    u8 chngRowid;          /* Rowid changed in a normal table */
125173    u8 chngKey;            /* Either chngPk or chngRowid */
125174    Expr *pRowidExpr = 0;  /* Expression defining the new record number */
125175    AuthContext sContext;  /* The authorization context */
125176    NameContext sNC;       /* The name-context to resolve expressions in */
125177    int iDb;               /* Database containing the table being updated */
125178    int eOnePass;          /* ONEPASS_XXX value from where.c */
125179    int hasFK;             /* True if foreign key processing is required */
125180    int labelBreak;        /* Jump here to break out of UPDATE loop */
125181    int labelContinue;     /* Jump here to continue next step of UPDATE loop */
125182    int flags;             /* Flags for sqlite3WhereBegin() */
125183  
125184  #ifndef SQLITE_OMIT_TRIGGER
125185    int isView;            /* True when updating a view (INSTEAD OF trigger) */
125186    Trigger *pTrigger;     /* List of triggers on pTab, if required */
125187    int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
125188  #endif
125189    int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
125190    int iEph = 0;          /* Ephemeral table holding all primary key values */
125191    int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */
125192    int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
125193    int addrOpen = 0;      /* Address of OP_OpenEphemeral */
125194    int iPk = 0;           /* First of nPk cells holding PRIMARY KEY value */
125195    i16 nPk = 0;           /* Number of components of the PRIMARY KEY */
125196    int bReplace = 0;      /* True if REPLACE conflict resolution might happen */
125197  
125198    /* Register Allocations */
125199    int regRowCount = 0;   /* A count of rows changed */
125200    int regOldRowid = 0;   /* The old rowid */
125201    int regNewRowid = 0;   /* The new rowid */
125202    int regNew = 0;        /* Content of the NEW.* table in triggers */
125203    int regOld = 0;        /* Content of OLD.* table in triggers */
125204    int regRowSet = 0;     /* Rowset of rows to be updated */
125205    int regKey = 0;        /* composite PRIMARY KEY value */
125206  
125207    memset(&sContext, 0, sizeof(sContext));
125208    db = pParse->db;
125209    if( pParse->nErr || db->mallocFailed ){
125210      goto update_cleanup;
125211    }
125212    assert( pTabList->nSrc==1 );
125213  
125214    /* Locate the table which we want to update. 
125215    */
125216    pTab = sqlite3SrcListLookup(pParse, pTabList);
125217    if( pTab==0 ) goto update_cleanup;
125218    iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
125219  
125220    /* Figure out if we have any triggers and if the table being
125221    ** updated is a view.
125222    */
125223  #ifndef SQLITE_OMIT_TRIGGER
125224    pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
125225    isView = pTab->pSelect!=0;
125226    assert( pTrigger || tmask==0 );
125227  #else
125228  # define pTrigger 0
125229  # define isView 0
125230  # define tmask 0
125231  #endif
125232  #ifdef SQLITE_OMIT_VIEW
125233  # undef isView
125234  # define isView 0
125235  #endif
125236  
125237    if( sqlite3ViewGetColumnNames(pParse, pTab) ){
125238      goto update_cleanup;
125239    }
125240    if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
125241      goto update_cleanup;
125242    }
125243  
125244    /* Allocate a cursors for the main database table and for all indices.
125245    ** The index cursors might not be used, but if they are used they
125246    ** need to occur right after the database cursor.  So go ahead and
125247    ** allocate enough space, just in case.
125248    */
125249    pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
125250    iIdxCur = iDataCur+1;
125251    pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
125252    for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
125253      if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
125254        iDataCur = pParse->nTab;
125255        pTabList->a[0].iCursor = iDataCur;
125256      }
125257      pParse->nTab++;
125258    }
125259  
125260    /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].  
125261    ** Initialize aXRef[] and aToOpen[] to their default values.
125262    */
125263    aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
125264    if( aXRef==0 ) goto update_cleanup;
125265    aRegIdx = aXRef+pTab->nCol;
125266    aToOpen = (u8*)(aRegIdx+nIdx);
125267    memset(aToOpen, 1, nIdx+1);
125268    aToOpen[nIdx+1] = 0;
125269    for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
125270  
125271    /* Initialize the name-context */
125272    memset(&sNC, 0, sizeof(sNC));
125273    sNC.pParse = pParse;
125274    sNC.pSrcList = pTabList;
125275  
125276    /* Resolve the column names in all the expressions of the
125277    ** of the UPDATE statement.  Also find the column index
125278    ** for each column to be updated in the pChanges array.  For each
125279    ** column to be updated, make sure we have authorization to change
125280    ** that column.
125281    */
125282    chngRowid = chngPk = 0;
125283    for(i=0; i<pChanges->nExpr; i++){
125284      if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
125285        goto update_cleanup;
125286      }
125287      for(j=0; j<pTab->nCol; j++){
125288        if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
125289          if( j==pTab->iPKey ){
125290            chngRowid = 1;
125291            pRowidExpr = pChanges->a[i].pExpr;
125292          }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
125293            chngPk = 1;
125294          }
125295          aXRef[j] = i;
125296          break;
125297        }
125298      }
125299      if( j>=pTab->nCol ){
125300        if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
125301          j = -1;
125302          chngRowid = 1;
125303          pRowidExpr = pChanges->a[i].pExpr;
125304        }else{
125305          sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
125306          pParse->checkSchema = 1;
125307          goto update_cleanup;
125308        }
125309      }
125310  #ifndef SQLITE_OMIT_AUTHORIZATION
125311      {
125312        int rc;
125313        rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
125314                              j<0 ? "ROWID" : pTab->aCol[j].zName,
125315                              db->aDb[iDb].zDbSName);
125316        if( rc==SQLITE_DENY ){
125317          goto update_cleanup;
125318        }else if( rc==SQLITE_IGNORE ){
125319          aXRef[j] = -1;
125320        }
125321      }
125322  #endif
125323    }
125324    assert( (chngRowid & chngPk)==0 );
125325    assert( chngRowid==0 || chngRowid==1 );
125326    assert( chngPk==0 || chngPk==1 );
125327    chngKey = chngRowid + chngPk;
125328  
125329    /* The SET expressions are not actually used inside the WHERE loop.  
125330    ** So reset the colUsed mask. Unless this is a virtual table. In that
125331    ** case, set all bits of the colUsed mask (to ensure that the virtual
125332    ** table implementation makes all columns available).
125333    */
125334    pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
125335  
125336    hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
125337  
125338    /* There is one entry in the aRegIdx[] array for each index on the table
125339    ** being updated.  Fill in aRegIdx[] with a register number that will hold
125340    ** the key for accessing each index.
125341    **
125342    ** FIXME:  Be smarter about omitting indexes that use expressions.
125343    */
125344    for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
125345      int reg;
125346      if( chngKey || hasFK>1 || pIdx->pPartIdxWhere || pIdx==pPk ){
125347        reg = ++pParse->nMem;
125348        pParse->nMem += pIdx->nColumn;
125349      }else{
125350        reg = 0;
125351        for(i=0; i<pIdx->nKeyCol; i++){
125352          i16 iIdxCol = pIdx->aiColumn[i];
125353          if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
125354            reg = ++pParse->nMem;
125355            pParse->nMem += pIdx->nColumn;
125356            if( (onError==OE_Replace)
125357             || (onError==OE_Default && pIdx->onError==OE_Replace) 
125358            ){
125359              bReplace = 1;
125360            }
125361            break;
125362          }
125363        }
125364      }
125365      if( reg==0 ) aToOpen[j+1] = 0;
125366      aRegIdx[j] = reg;
125367    }
125368    if( bReplace ){
125369      /* If REPLACE conflict resolution might be invoked, open cursors on all 
125370      ** indexes in case they are needed to delete records.  */
125371      memset(aToOpen, 1, nIdx+1);
125372    }
125373  
125374    /* Begin generating code. */
125375    v = sqlite3GetVdbe(pParse);
125376    if( v==0 ) goto update_cleanup;
125377    if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
125378    sqlite3BeginWriteOperation(pParse, 1, iDb);
125379  
125380    /* Allocate required registers. */
125381    if( !IsVirtual(pTab) ){
125382      regRowSet = ++pParse->nMem;
125383      regOldRowid = regNewRowid = ++pParse->nMem;
125384      if( chngPk || pTrigger || hasFK ){
125385        regOld = pParse->nMem + 1;
125386        pParse->nMem += pTab->nCol;
125387      }
125388      if( chngKey || pTrigger || hasFK ){
125389        regNewRowid = ++pParse->nMem;
125390      }
125391      regNew = pParse->nMem + 1;
125392      pParse->nMem += pTab->nCol;
125393    }
125394  
125395    /* Start the view context. */
125396    if( isView ){
125397      sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
125398    }
125399  
125400    /* If we are trying to update a view, realize that view into
125401    ** an ephemeral table.
125402    */
125403  #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
125404    if( isView ){
125405      sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
125406    }
125407  #endif
125408  
125409    /* Resolve the column names in all the expressions in the
125410    ** WHERE clause.
125411    */
125412    if( sqlite3ResolveExprNames(&sNC, pWhere) ){
125413      goto update_cleanup;
125414    }
125415  
125416  #ifndef SQLITE_OMIT_VIRTUALTABLE
125417    /* Virtual tables must be handled separately */
125418    if( IsVirtual(pTab) ){
125419      updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
125420                         pWhere, onError);
125421      goto update_cleanup;
125422    }
125423  #endif
125424  
125425    /* Initialize the count of updated rows */
125426    if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
125427      regRowCount = ++pParse->nMem;
125428      sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
125429    }
125430  
125431    if( HasRowid(pTab) ){
125432      sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
125433    }else{
125434      assert( pPk!=0 );
125435      nPk = pPk->nKeyCol;
125436      iPk = pParse->nMem+1;
125437      pParse->nMem += nPk;
125438      regKey = ++pParse->nMem;
125439      iEph = pParse->nTab++;
125440  
125441      sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
125442      addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
125443      sqlite3VdbeSetP4KeyInfo(pParse, pPk);
125444    }
125445  
125446    /* Begin the database scan. 
125447    **
125448    ** Do not consider a single-pass strategy for a multi-row update if
125449    ** there are any triggers or foreign keys to process, or rows may
125450    ** be deleted as a result of REPLACE conflict handling. Any of these
125451    ** things might disturb a cursor being used to scan through the table
125452    ** or index, causing a single-pass approach to malfunction.  */
125453    flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE;
125454    if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
125455      flags |= WHERE_ONEPASS_MULTIROW;
125456    }
125457    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags, iIdxCur);
125458    if( pWInfo==0 ) goto update_cleanup;
125459  
125460    /* A one-pass strategy that might update more than one row may not
125461    ** be used if any column of the index used for the scan is being
125462    ** updated. Otherwise, if there is an index on "b", statements like
125463    ** the following could create an infinite loop:
125464    **
125465    **   UPDATE t1 SET b=b+1 WHERE b>?
125466    **
125467    ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
125468    ** strategy that uses an index for which one or more columns are being
125469    ** updated.  */
125470    eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
125471    if( eOnePass==ONEPASS_MULTI ){
125472      int iCur = aiCurOnePass[1];
125473      if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
125474        eOnePass = ONEPASS_OFF;
125475      }
125476      assert( iCur!=iDataCur || !HasRowid(pTab) );
125477    }
125478    
125479    if( HasRowid(pTab) ){
125480      /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
125481      ** mode, write the rowid into the FIFO. In either of the one-pass modes,
125482      ** leave it in register regOldRowid.  */
125483      sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
125484      if( eOnePass==ONEPASS_OFF ){
125485        sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
125486      }
125487    }else{
125488      /* Read the PK of the current row into an array of registers. In
125489      ** ONEPASS_OFF mode, serialize the array into a record and store it in
125490      ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
125491      ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table 
125492      ** is not required) and leave the PK fields in the array of registers.  */
125493      for(i=0; i<nPk; i++){
125494        assert( pPk->aiColumn[i]>=0 );
125495        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,pPk->aiColumn[i],iPk+i);
125496      }
125497      if( eOnePass ){
125498        sqlite3VdbeChangeToNoop(v, addrOpen);
125499        nKey = nPk;
125500        regKey = iPk;
125501      }else{
125502        sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
125503                          sqlite3IndexAffinityStr(db, pPk), nPk);
125504        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
125505      }
125506    }
125507  
125508    if( eOnePass!=ONEPASS_MULTI ){
125509      sqlite3WhereEnd(pWInfo);
125510    }
125511  
125512    labelBreak = sqlite3VdbeMakeLabel(v);
125513    if( !isView ){
125514      int addrOnce = 0;
125515  
125516      /* Open every index that needs updating. */
125517      if( eOnePass!=ONEPASS_OFF ){
125518        if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
125519        if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
125520      }
125521  
125522      if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
125523        addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
125524      }
125525      sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen,
125526                                 0, 0);
125527      if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
125528    }
125529  
125530    /* Top of the update loop */
125531    if( eOnePass!=ONEPASS_OFF ){
125532      if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){
125533        assert( pPk );
125534        sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
125535        VdbeCoverageNeverTaken(v);
125536      }
125537      if( eOnePass==ONEPASS_SINGLE ){
125538        labelContinue = labelBreak;
125539      }else{
125540        labelContinue = sqlite3VdbeMakeLabel(v);
125541      }
125542      sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
125543      VdbeCoverageIf(v, pPk==0);
125544      VdbeCoverageIf(v, pPk!=0);
125545    }else if( pPk ){
125546      labelContinue = sqlite3VdbeMakeLabel(v);
125547      sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
125548      addrTop = sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
125549      sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
125550      VdbeCoverage(v);
125551    }else{
125552      labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
125553                               regOldRowid);
125554      VdbeCoverage(v);
125555      sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
125556      VdbeCoverage(v);
125557    }
125558  
125559    /* If the record number will change, set register regNewRowid to
125560    ** contain the new value. If the record number is not being modified,
125561    ** then regNewRowid is the same register as regOldRowid, which is
125562    ** already populated.  */
125563    assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
125564    if( chngRowid ){
125565      sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
125566      sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
125567    }
125568  
125569    /* Compute the old pre-UPDATE content of the row being changed, if that
125570    ** information is needed */
125571    if( chngPk || hasFK || pTrigger ){
125572      u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
125573      oldmask |= sqlite3TriggerColmask(pParse, 
125574          pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
125575      );
125576      for(i=0; i<pTab->nCol; i++){
125577        if( oldmask==0xffffffff
125578         || (i<32 && (oldmask & MASKBIT32(i))!=0)
125579         || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
125580        ){
125581          testcase(  oldmask!=0xffffffff && i==31 );
125582          sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
125583        }else{
125584          sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
125585        }
125586      }
125587      if( chngRowid==0 && pPk==0 ){
125588        sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
125589      }
125590    }
125591  
125592    /* Populate the array of registers beginning at regNew with the new
125593    ** row data. This array is used to check constants, create the new
125594    ** table and index records, and as the values for any new.* references
125595    ** made by triggers.
125596    **
125597    ** If there are one or more BEFORE triggers, then do not populate the
125598    ** registers associated with columns that are (a) not modified by
125599    ** this UPDATE statement and (b) not accessed by new.* references. The
125600    ** values for registers not modified by the UPDATE must be reloaded from 
125601    ** the database after the BEFORE triggers are fired anyway (as the trigger 
125602    ** may have modified them). So not loading those that are not going to
125603    ** be used eliminates some redundant opcodes.
125604    */
125605    newmask = sqlite3TriggerColmask(
125606        pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
125607    );
125608    for(i=0; i<pTab->nCol; i++){
125609      if( i==pTab->iPKey ){
125610        sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
125611      }else{
125612        j = aXRef[i];
125613        if( j>=0 ){
125614          sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
125615        }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
125616          /* This branch loads the value of a column that will not be changed 
125617          ** into a register. This is done if there are no BEFORE triggers, or
125618          ** if there are one or more BEFORE triggers that use this value via
125619          ** a new.* reference in a trigger program.
125620          */
125621          testcase( i==31 );
125622          testcase( i==32 );
125623          sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i);
125624        }else{
125625          sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
125626        }
125627      }
125628    }
125629  
125630    /* Fire any BEFORE UPDATE triggers. This happens before constraints are
125631    ** verified. One could argue that this is wrong.
125632    */
125633    if( tmask&TRIGGER_BEFORE ){
125634      sqlite3TableAffinity(v, pTab, regNew);
125635      sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
125636          TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
125637  
125638      /* The row-trigger may have deleted the row being updated. In this
125639      ** case, jump to the next row. No updates or AFTER triggers are 
125640      ** required. This behavior - what happens when the row being updated
125641      ** is deleted or renamed by a BEFORE trigger - is left undefined in the
125642      ** documentation.
125643      */
125644      if( pPk ){
125645        sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
125646        VdbeCoverage(v);
125647      }else{
125648        sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
125649        VdbeCoverage(v);
125650      }
125651  
125652      /* If it did not delete it, the row-trigger may still have modified 
125653      ** some of the columns of the row being updated. Load the values for 
125654      ** all columns not modified by the update statement into their 
125655      ** registers in case this has happened.
125656      */
125657      for(i=0; i<pTab->nCol; i++){
125658        if( aXRef[i]<0 && i!=pTab->iPKey ){
125659          sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
125660        }
125661      }
125662    }
125663  
125664    if( !isView ){
125665      int addr1 = 0;        /* Address of jump instruction */
125666  
125667      /* Do constraint checks. */
125668      assert( regOldRowid>0 );
125669      sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
125670          regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
125671          aXRef);
125672  
125673      /* Do FK constraint checks. */
125674      if( hasFK ){
125675        sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
125676      }
125677  
125678      /* Delete the index entries associated with the current record.  */
125679      if( bReplace || chngKey ){
125680        if( pPk ){
125681          addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
125682        }else{
125683          addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
125684        }
125685        VdbeCoverageNeverTaken(v);
125686      }
125687      sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
125688  
125689      /* If changing the rowid value, or if there are foreign key constraints
125690      ** to process, delete the old record. Otherwise, add a noop OP_Delete
125691      ** to invoke the pre-update hook.
125692      **
125693      ** That (regNew==regnewRowid+1) is true is also important for the 
125694      ** pre-update hook. If the caller invokes preupdate_new(), the returned
125695      ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
125696      ** is the column index supplied by the user.
125697      */
125698      assert( regNew==regNewRowid+1 );
125699  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
125700      sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
125701          OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP),
125702          regNewRowid
125703      );
125704      if( eOnePass==ONEPASS_MULTI ){
125705        assert( hasFK==0 && chngKey==0 );
125706        sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
125707      }
125708      if( !pParse->nested ){
125709        sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
125710      }
125711  #else
125712      if( hasFK>1 || chngKey ){
125713        sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
125714      }
125715  #endif
125716      if( bReplace || chngKey ){
125717        sqlite3VdbeJumpHere(v, addr1);
125718      }
125719  
125720      if( hasFK ){
125721        sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
125722      }
125723    
125724      /* Insert the new index entries and the new record. */
125725      sqlite3CompleteInsertion(
125726          pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx, 
125727          OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0), 
125728          0, 0
125729      );
125730  
125731      /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
125732      ** handle rows (possibly in other tables) that refer via a foreign key
125733      ** to the row just updated. */ 
125734      if( hasFK ){
125735        sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
125736      }
125737    }
125738  
125739    /* Increment the row counter 
125740    */
125741    if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
125742      sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
125743    }
125744  
125745    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
125746        TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
125747  
125748    /* Repeat the above with the next record to be updated, until
125749    ** all record selected by the WHERE clause have been updated.
125750    */
125751    if( eOnePass==ONEPASS_SINGLE ){
125752      /* Nothing to do at end-of-loop for a single-pass */
125753    }else if( eOnePass==ONEPASS_MULTI ){
125754      sqlite3VdbeResolveLabel(v, labelContinue);
125755      sqlite3WhereEnd(pWInfo);
125756    }else if( pPk ){
125757      sqlite3VdbeResolveLabel(v, labelContinue);
125758      sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
125759    }else{
125760      sqlite3VdbeGoto(v, labelContinue);
125761    }
125762    sqlite3VdbeResolveLabel(v, labelBreak);
125763  
125764    /* Update the sqlite_sequence table by storing the content of the
125765    ** maximum rowid counter values recorded while inserting into
125766    ** autoincrement tables.
125767    */
125768    if( pParse->nested==0 && pParse->pTriggerTab==0 ){
125769      sqlite3AutoincrementEnd(pParse);
125770    }
125771  
125772    /*
125773    ** Return the number of rows that were changed. If this routine is 
125774    ** generating code because of a call to sqlite3NestedParse(), do not
125775    ** invoke the callback function.
125776    */
125777    if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
125778      sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
125779      sqlite3VdbeSetNumCols(v, 1);
125780      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
125781    }
125782  
125783  update_cleanup:
125784    sqlite3AuthContextPop(&sContext);
125785    sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
125786    sqlite3SrcListDelete(db, pTabList);
125787    sqlite3ExprListDelete(db, pChanges);
125788    sqlite3ExprDelete(db, pWhere);
125789    return;
125790  }
125791  /* Make sure "isView" and other macros defined above are undefined. Otherwise
125792  ** they may interfere with compilation of other functions in this file
125793  ** (or in another file, if this file becomes part of the amalgamation).  */
125794  #ifdef isView
125795   #undef isView
125796  #endif
125797  #ifdef pTrigger
125798   #undef pTrigger
125799  #endif
125800  
125801  #ifndef SQLITE_OMIT_VIRTUALTABLE
125802  /*
125803  ** Generate code for an UPDATE of a virtual table.
125804  **
125805  ** There are two possible strategies - the default and the special 
125806  ** "onepass" strategy. Onepass is only used if the virtual table 
125807  ** implementation indicates that pWhere may match at most one row.
125808  **
125809  ** The default strategy is to create an ephemeral table that contains
125810  ** for each row to be changed:
125811  **
125812  **   (A)  The original rowid of that row.
125813  **   (B)  The revised rowid for the row.
125814  **   (C)  The content of every column in the row.
125815  **
125816  ** Then loop through the contents of this ephemeral table executing a
125817  ** VUpdate for each row. When finished, drop the ephemeral table.
125818  **
125819  ** The "onepass" strategy does not use an ephemeral table. Instead, it
125820  ** stores the same values (A, B and C above) in a register array and
125821  ** makes a single invocation of VUpdate.
125822  */
125823  static void updateVirtualTable(
125824    Parse *pParse,       /* The parsing context */
125825    SrcList *pSrc,       /* The virtual table to be modified */
125826    Table *pTab,         /* The virtual table */
125827    ExprList *pChanges,  /* The columns to change in the UPDATE statement */
125828    Expr *pRowid,        /* Expression used to recompute the rowid */
125829    int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
125830    Expr *pWhere,        /* WHERE clause of the UPDATE statement */
125831    int onError          /* ON CONFLICT strategy */
125832  ){
125833    Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
125834    int ephemTab;             /* Table holding the result of the SELECT */
125835    int i;                    /* Loop counter */
125836    sqlite3 *db = pParse->db; /* Database connection */
125837    const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
125838    WhereInfo *pWInfo;
125839    int nArg = 2 + pTab->nCol;      /* Number of arguments to VUpdate */
125840    int regArg;                     /* First register in VUpdate arg array */
125841    int regRec;                     /* Register in which to assemble record */
125842    int regRowid;                   /* Register for ephem table rowid */
125843    int iCsr = pSrc->a[0].iCursor;  /* Cursor used for virtual table scan */
125844    int aDummy[2];                  /* Unused arg for sqlite3WhereOkOnePass() */
125845    int bOnePass;                   /* True to use onepass strategy */
125846    int addr;                       /* Address of OP_OpenEphemeral */
125847  
125848    /* Allocate nArg registers to martial the arguments to VUpdate. Then
125849    ** create and open the ephemeral table in which the records created from
125850    ** these arguments will be temporarily stored. */
125851    assert( v );
125852    ephemTab = pParse->nTab++;
125853    addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
125854    regArg = pParse->nMem + 1;
125855    pParse->nMem += nArg;
125856    regRec = ++pParse->nMem;
125857    regRowid = ++pParse->nMem;
125858  
125859    /* Start scanning the virtual table */
125860    pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
125861    if( pWInfo==0 ) return;
125862  
125863    /* Populate the argument registers. */
125864    for(i=0; i<pTab->nCol; i++){
125865      if( aXRef[i]>=0 ){
125866        sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
125867      }else{
125868        sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
125869      }
125870    }
125871    if( HasRowid(pTab) ){
125872      sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
125873      if( pRowid ){
125874        sqlite3ExprCode(pParse, pRowid, regArg+1);
125875      }else{
125876        sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
125877      }
125878    }else{
125879      Index *pPk;   /* PRIMARY KEY index */
125880      i16 iPk;      /* PRIMARY KEY column */
125881      pPk = sqlite3PrimaryKeyIndex(pTab);
125882      assert( pPk!=0 );
125883      assert( pPk->nKeyCol==1 );
125884      iPk = pPk->aiColumn[0];
125885      sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg);
125886      sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1);
125887    }
125888  
125889    bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
125890  
125891    if( bOnePass ){
125892      /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
125893      ** above. Also, if this is a top-level parse (not a trigger), clear the
125894      ** multi-write flag so that the VM does not open a statement journal */
125895      sqlite3VdbeChangeToNoop(v, addr);
125896      if( sqlite3IsToplevel(pParse) ){
125897        pParse->isMultiWrite = 0;
125898      }
125899    }else{
125900      /* Create a record from the argument register contents and insert it into
125901      ** the ephemeral table. */
125902      sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
125903      sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
125904      sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
125905    }
125906  
125907  
125908    if( bOnePass==0 ){
125909      /* End the virtual table scan */
125910      sqlite3WhereEnd(pWInfo);
125911  
125912      /* Begin scannning through the ephemeral table. */
125913      addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
125914  
125915      /* Extract arguments from the current row of the ephemeral table and 
125916      ** invoke the VUpdate method.  */
125917      for(i=0; i<nArg; i++){
125918        sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
125919      }
125920    }
125921    sqlite3VtabMakeWritable(pParse, pTab);
125922    sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
125923    sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
125924    sqlite3MayAbort(pParse);
125925  
125926    /* End of the ephemeral table scan. Or, if using the onepass strategy,
125927    ** jump to here if the scan visited zero rows. */
125928    if( bOnePass==0 ){
125929      sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
125930      sqlite3VdbeJumpHere(v, addr);
125931      sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
125932    }else{
125933      sqlite3WhereEnd(pWInfo);
125934    }
125935  }
125936  #endif /* SQLITE_OMIT_VIRTUALTABLE */
125937  
125938  /************** End of update.c **********************************************/
125939  /************** Begin file vacuum.c ******************************************/
125940  /*
125941  ** 2003 April 6
125942  **
125943  ** The author disclaims copyright to this source code.  In place of
125944  ** a legal notice, here is a blessing:
125945  **
125946  **    May you do good and not evil.
125947  **    May you find forgiveness for yourself and forgive others.
125948  **    May you share freely, never taking more than you give.
125949  **
125950  *************************************************************************
125951  ** This file contains code used to implement the VACUUM command.
125952  **
125953  ** Most of the code in this file may be omitted by defining the
125954  ** SQLITE_OMIT_VACUUM macro.
125955  */
125956  /* #include "sqliteInt.h" */
125957  /* #include "vdbeInt.h" */
125958  
125959  #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
125960  
125961  /*
125962  ** Execute zSql on database db.
125963  **
125964  ** If zSql returns rows, then each row will have exactly one
125965  ** column.  (This will only happen if zSql begins with "SELECT".)
125966  ** Take each row of result and call execSql() again recursively.
125967  **
125968  ** The execSqlF() routine does the same thing, except it accepts
125969  ** a format string as its third argument
125970  */
125971  static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
125972    sqlite3_stmt *pStmt;
125973    int rc;
125974  
125975    /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
125976    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
125977    if( rc!=SQLITE_OK ) return rc;
125978    while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
125979      const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
125980      assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
125981      if( zSubSql ){
125982        assert( zSubSql[0]!='S' );
125983        rc = execSql(db, pzErrMsg, zSubSql);
125984        if( rc!=SQLITE_OK ) break;
125985      }
125986    }
125987    assert( rc!=SQLITE_ROW );
125988    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
125989    if( rc ){
125990      sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
125991    }
125992    (void)sqlite3_finalize(pStmt);
125993    return rc;
125994  }
125995  static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){
125996    char *z;
125997    va_list ap;
125998    int rc;
125999    va_start(ap, zSql);
126000    z = sqlite3VMPrintf(db, zSql, ap);
126001    va_end(ap);
126002    if( z==0 ) return SQLITE_NOMEM;
126003    rc = execSql(db, pzErrMsg, z);
126004    sqlite3DbFree(db, z);
126005    return rc;
126006  }
126007  
126008  /*
126009  ** The VACUUM command is used to clean up the database,
126010  ** collapse free space, etc.  It is modelled after the VACUUM command
126011  ** in PostgreSQL.  The VACUUM command works as follows:
126012  **
126013  **   (1)  Create a new transient database file
126014  **   (2)  Copy all content from the database being vacuumed into
126015  **        the new transient database file
126016  **   (3)  Copy content from the transient database back into the
126017  **        original database.
126018  **
126019  ** The transient database requires temporary disk space approximately
126020  ** equal to the size of the original database.  The copy operation of
126021  ** step (3) requires additional temporary disk space approximately equal
126022  ** to the size of the original database for the rollback journal.
126023  ** Hence, temporary disk space that is approximately 2x the size of the
126024  ** original database is required.  Every page of the database is written
126025  ** approximately 3 times:  Once for step (2) and twice for step (3).
126026  ** Two writes per page are required in step (3) because the original
126027  ** database content must be written into the rollback journal prior to
126028  ** overwriting the database with the vacuumed content.
126029  **
126030  ** Only 1x temporary space and only 1x writes would be required if
126031  ** the copy of step (3) were replaced by deleting the original database
126032  ** and renaming the transient database as the original.  But that will
126033  ** not work if other processes are attached to the original database.
126034  ** And a power loss in between deleting the original and renaming the
126035  ** transient would cause the database file to appear to be deleted
126036  ** following reboot.
126037  */
126038  SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm){
126039    Vdbe *v = sqlite3GetVdbe(pParse);
126040    int iDb = 0;
126041    if( v==0 ) return;
126042    if( pNm ){
126043  #ifndef SQLITE_BUG_COMPATIBLE_20160819
126044      /* Default behavior:  Report an error if the argument to VACUUM is
126045      ** not recognized */
126046      iDb = sqlite3TwoPartName(pParse, pNm, pNm, &pNm);
126047      if( iDb<0 ) return;
126048  #else
126049      /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments
126050      ** to VACUUM are silently ignored.  This is a back-out of a bug fix that
126051      ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270).
126052      ** The buggy behavior is required for binary compatibility with some
126053      ** legacy applications. */
126054      iDb = sqlite3FindDb(pParse->db, pNm);
126055      if( iDb<0 ) iDb = 0;
126056  #endif
126057    }
126058    if( iDb!=1 ){
126059      sqlite3VdbeAddOp1(v, OP_Vacuum, iDb);
126060      sqlite3VdbeUsesBtree(v, iDb);
126061    }
126062    return;
126063  }
126064  
126065  /*
126066  ** This routine implements the OP_Vacuum opcode of the VDBE.
126067  */
126068  SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){
126069    int rc = SQLITE_OK;     /* Return code from service routines */
126070    Btree *pMain;           /* The database being vacuumed */
126071    Btree *pTemp;           /* The temporary database we vacuum into */
126072    u16 saved_mDbFlags;     /* Saved value of db->mDbFlags */
126073    u32 saved_flags;        /* Saved value of db->flags */
126074    int saved_nChange;      /* Saved value of db->nChange */
126075    int saved_nTotalChange; /* Saved value of db->nTotalChange */
126076    u8 saved_mTrace;        /* Saved trace settings */
126077    Db *pDb = 0;            /* Database to detach at end of vacuum */
126078    int isMemDb;            /* True if vacuuming a :memory: database */
126079    int nRes;               /* Bytes of reserved space at the end of each page */
126080    int nDb;                /* Number of attached databases */
126081    const char *zDbMain;    /* Schema name of database to vacuum */
126082  
126083    if( !db->autoCommit ){
126084      sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
126085      return SQLITE_ERROR;
126086    }
126087    if( db->nVdbeActive>1 ){
126088      sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
126089      return SQLITE_ERROR;
126090    }
126091  
126092    /* Save the current value of the database flags so that it can be 
126093    ** restored before returning. Then set the writable-schema flag, and
126094    ** disable CHECK and foreign key constraints.  */
126095    saved_flags = db->flags;
126096    saved_mDbFlags = db->mDbFlags;
126097    saved_nChange = db->nChange;
126098    saved_nTotalChange = db->nTotalChange;
126099    saved_mTrace = db->mTrace;
126100    db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
126101    db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum;
126102    db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_CountRows);
126103    db->mTrace = 0;
126104  
126105    zDbMain = db->aDb[iDb].zDbSName;
126106    pMain = db->aDb[iDb].pBt;
126107    isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
126108  
126109    /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
126110    ** can be set to 'off' for this file, as it is not recovered if a crash
126111    ** occurs anyway. The integrity of the database is maintained by a
126112    ** (possibly synchronous) transaction opened on the main database before
126113    ** sqlite3BtreeCopyFile() is called.
126114    **
126115    ** An optimisation would be to use a non-journaled pager.
126116    ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
126117    ** that actually made the VACUUM run slower.  Very little journalling
126118    ** actually occurs when doing a vacuum since the vacuum_db is initially
126119    ** empty.  Only the journal header is written.  Apparently it takes more
126120    ** time to parse and run the PRAGMA to turn journalling off than it does
126121    ** to write the journal header file.
126122    */
126123    nDb = db->nDb;
126124    rc = execSql(db, pzErrMsg, "ATTACH''AS vacuum_db");
126125    if( rc!=SQLITE_OK ) goto end_of_vacuum;
126126    assert( (db->nDb-1)==nDb );
126127    pDb = &db->aDb[nDb];
126128    assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
126129    pTemp = pDb->pBt;
126130  
126131    /* The call to execSql() to attach the temp database has left the file
126132    ** locked (as there was more than one active statement when the transaction
126133    ** to read the schema was concluded. Unlock it here so that this doesn't
126134    ** cause problems for the call to BtreeSetPageSize() below.  */
126135    sqlite3BtreeCommit(pTemp);
126136  
126137    nRes = sqlite3BtreeGetOptimalReserve(pMain);
126138  
126139    /* A VACUUM cannot change the pagesize of an encrypted database. */
126140  #ifdef SQLITE_HAS_CODEC
126141    if( db->nextPagesize ){
126142      extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
126143      int nKey;
126144      char *zKey;
126145      sqlite3CodecGetKey(db, iDb, (void**)&zKey, &nKey);
126146      if( nKey ) db->nextPagesize = 0;
126147    }
126148  #endif
126149  
126150    sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
126151    sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
126152    sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL);
126153  
126154    /* Begin a transaction and take an exclusive lock on the main database
126155    ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
126156    ** to ensure that we do not try to change the page-size on a WAL database.
126157    */
126158    rc = execSql(db, pzErrMsg, "BEGIN");
126159    if( rc!=SQLITE_OK ) goto end_of_vacuum;
126160    rc = sqlite3BtreeBeginTrans(pMain, 2);
126161    if( rc!=SQLITE_OK ) goto end_of_vacuum;
126162  
126163    /* Do not attempt to change the page size for a WAL database */
126164    if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
126165                                                 ==PAGER_JOURNALMODE_WAL ){
126166      db->nextPagesize = 0;
126167    }
126168  
126169    if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
126170     || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
126171     || NEVER(db->mallocFailed)
126172    ){
126173      rc = SQLITE_NOMEM_BKPT;
126174      goto end_of_vacuum;
126175    }
126176  
126177  #ifndef SQLITE_OMIT_AUTOVACUUM
126178    sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
126179                                             sqlite3BtreeGetAutoVacuum(pMain));
126180  #endif
126181  
126182    /* Query the schema of the main database. Create a mirror schema
126183    ** in the temporary database.
126184    */
126185    db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
126186    rc = execSqlF(db, pzErrMsg,
126187        "SELECT sql FROM \"%w\".sqlite_master"
126188        " WHERE type='table'AND name<>'sqlite_sequence'"
126189        " AND coalesce(rootpage,1)>0",
126190        zDbMain
126191    );
126192    if( rc!=SQLITE_OK ) goto end_of_vacuum;
126193    rc = execSqlF(db, pzErrMsg,
126194        "SELECT sql FROM \"%w\".sqlite_master"
126195        " WHERE type='index' AND length(sql)>10",
126196        zDbMain
126197    );
126198    if( rc!=SQLITE_OK ) goto end_of_vacuum;
126199    db->init.iDb = 0;
126200  
126201    /* Loop through the tables in the main database. For each, do
126202    ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
126203    ** the contents to the temporary database.
126204    */
126205    rc = execSqlF(db, pzErrMsg,
126206        "SELECT'INSERT INTO vacuum_db.'||quote(name)"
126207        "||' SELECT*FROM\"%w\".'||quote(name)"
126208        "FROM vacuum_db.sqlite_master "
126209        "WHERE type='table'AND coalesce(rootpage,1)>0",
126210        zDbMain
126211    );
126212    assert( (db->mDbFlags & DBFLAG_Vacuum)!=0 );
126213    db->mDbFlags &= ~DBFLAG_Vacuum;
126214    if( rc!=SQLITE_OK ) goto end_of_vacuum;
126215  
126216    /* Copy the triggers, views, and virtual tables from the main database
126217    ** over to the temporary database.  None of these objects has any
126218    ** associated storage, so all we have to do is copy their entries
126219    ** from the SQLITE_MASTER table.
126220    */
126221    rc = execSqlF(db, pzErrMsg,
126222        "INSERT INTO vacuum_db.sqlite_master"
126223        " SELECT*FROM \"%w\".sqlite_master"
126224        " WHERE type IN('view','trigger')"
126225        " OR(type='table'AND rootpage=0)",
126226        zDbMain
126227    );
126228    if( rc ) goto end_of_vacuum;
126229  
126230    /* At this point, there is a write transaction open on both the 
126231    ** vacuum database and the main database. Assuming no error occurs,
126232    ** both transactions are closed by this block - the main database
126233    ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
126234    ** call to sqlite3BtreeCommit().
126235    */
126236    {
126237      u32 meta;
126238      int i;
126239  
126240      /* This array determines which meta meta values are preserved in the
126241      ** vacuum.  Even entries are the meta value number and odd entries
126242      ** are an increment to apply to the meta value after the vacuum.
126243      ** The increment is used to increase the schema cookie so that other
126244      ** connections to the same database will know to reread the schema.
126245      */
126246      static const unsigned char aCopy[] = {
126247         BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
126248         BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
126249         BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
126250         BTREE_USER_VERSION,       0,  /* Preserve the user version */
126251         BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
126252      };
126253  
126254      assert( 1==sqlite3BtreeIsInTrans(pTemp) );
126255      assert( 1==sqlite3BtreeIsInTrans(pMain) );
126256  
126257      /* Copy Btree meta values */
126258      for(i=0; i<ArraySize(aCopy); i+=2){
126259        /* GetMeta() and UpdateMeta() cannot fail in this context because
126260        ** we already have page 1 loaded into cache and marked dirty. */
126261        sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
126262        rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
126263        if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
126264      }
126265  
126266      rc = sqlite3BtreeCopyFile(pMain, pTemp);
126267      if( rc!=SQLITE_OK ) goto end_of_vacuum;
126268      rc = sqlite3BtreeCommit(pTemp);
126269      if( rc!=SQLITE_OK ) goto end_of_vacuum;
126270  #ifndef SQLITE_OMIT_AUTOVACUUM
126271      sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
126272  #endif
126273    }
126274  
126275    assert( rc==SQLITE_OK );
126276    rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
126277  
126278  end_of_vacuum:
126279    /* Restore the original value of db->flags */
126280    db->init.iDb = 0;
126281    db->mDbFlags = saved_mDbFlags;
126282    db->flags = saved_flags;
126283    db->nChange = saved_nChange;
126284    db->nTotalChange = saved_nTotalChange;
126285    db->mTrace = saved_mTrace;
126286    sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
126287  
126288    /* Currently there is an SQL level transaction open on the vacuum
126289    ** database. No locks are held on any other files (since the main file
126290    ** was committed at the btree level). So it safe to end the transaction
126291    ** by manually setting the autoCommit flag to true and detaching the
126292    ** vacuum database. The vacuum_db journal file is deleted when the pager
126293    ** is closed by the DETACH.
126294    */
126295    db->autoCommit = 1;
126296  
126297    if( pDb ){
126298      sqlite3BtreeClose(pDb->pBt);
126299      pDb->pBt = 0;
126300      pDb->pSchema = 0;
126301    }
126302  
126303    /* This both clears the schemas and reduces the size of the db->aDb[]
126304    ** array. */ 
126305    sqlite3ResetAllSchemasOfConnection(db);
126306  
126307    return rc;
126308  }
126309  
126310  #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
126311  
126312  /************** End of vacuum.c **********************************************/
126313  /************** Begin file vtab.c ********************************************/
126314  /*
126315  ** 2006 June 10
126316  **
126317  ** The author disclaims copyright to this source code.  In place of
126318  ** a legal notice, here is a blessing:
126319  **
126320  **    May you do good and not evil.
126321  **    May you find forgiveness for yourself and forgive others.
126322  **    May you share freely, never taking more than you give.
126323  **
126324  *************************************************************************
126325  ** This file contains code used to help implement virtual tables.
126326  */
126327  #ifndef SQLITE_OMIT_VIRTUALTABLE
126328  /* #include "sqliteInt.h" */
126329  
126330  /*
126331  ** Before a virtual table xCreate() or xConnect() method is invoked, the
126332  ** sqlite3.pVtabCtx member variable is set to point to an instance of
126333  ** this struct allocated on the stack. It is used by the implementation of 
126334  ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
126335  ** are invoked only from within xCreate and xConnect methods.
126336  */
126337  struct VtabCtx {
126338    VTable *pVTable;    /* The virtual table being constructed */
126339    Table *pTab;        /* The Table object to which the virtual table belongs */
126340    VtabCtx *pPrior;    /* Parent context (if any) */
126341    int bDeclared;      /* True after sqlite3_declare_vtab() is called */
126342  };
126343  
126344  /*
126345  ** Construct and install a Module object for a virtual table.  When this
126346  ** routine is called, it is guaranteed that all appropriate locks are held
126347  ** and the module is not already part of the connection.
126348  */
126349  SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
126350    sqlite3 *db,                    /* Database in which module is registered */
126351    const char *zName,              /* Name assigned to this module */
126352    const sqlite3_module *pModule,  /* The definition of the module */
126353    void *pAux,                     /* Context pointer for xCreate/xConnect */
126354    void (*xDestroy)(void *)        /* Module destructor function */
126355  ){
126356    Module *pMod;
126357    int nName = sqlite3Strlen30(zName);
126358    pMod = (Module *)sqlite3Malloc(sizeof(Module) + nName + 1);
126359    if( pMod==0 ){
126360      sqlite3OomFault(db);
126361    }else{
126362      Module *pDel;
126363      char *zCopy = (char *)(&pMod[1]);
126364      memcpy(zCopy, zName, nName+1);
126365      pMod->zName = zCopy;
126366      pMod->pModule = pModule;
126367      pMod->pAux = pAux;
126368      pMod->xDestroy = xDestroy;
126369      pMod->pEpoTab = 0;
126370      pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
126371      assert( pDel==0 || pDel==pMod );
126372      if( pDel ){
126373        sqlite3OomFault(db);
126374        sqlite3DbFree(db, pDel);
126375        pMod = 0;
126376      }
126377    }
126378    return pMod;
126379  }
126380  
126381  /*
126382  ** The actual function that does the work of creating a new module.
126383  ** This function implements the sqlite3_create_module() and
126384  ** sqlite3_create_module_v2() interfaces.
126385  */
126386  static int createModule(
126387    sqlite3 *db,                    /* Database in which module is registered */
126388    const char *zName,              /* Name assigned to this module */
126389    const sqlite3_module *pModule,  /* The definition of the module */
126390    void *pAux,                     /* Context pointer for xCreate/xConnect */
126391    void (*xDestroy)(void *)        /* Module destructor function */
126392  ){
126393    int rc = SQLITE_OK;
126394  
126395    sqlite3_mutex_enter(db->mutex);
126396    if( sqlite3HashFind(&db->aModule, zName) ){
126397      rc = SQLITE_MISUSE_BKPT;
126398    }else{
126399      (void)sqlite3VtabCreateModule(db, zName, pModule, pAux, xDestroy);
126400    }
126401    rc = sqlite3ApiExit(db, rc);
126402    if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
126403    sqlite3_mutex_leave(db->mutex);
126404    return rc;
126405  }
126406  
126407  
126408  /*
126409  ** External API function used to create a new virtual-table module.
126410  */
126411  SQLITE_API int sqlite3_create_module(
126412    sqlite3 *db,                    /* Database in which module is registered */
126413    const char *zName,              /* Name assigned to this module */
126414    const sqlite3_module *pModule,  /* The definition of the module */
126415    void *pAux                      /* Context pointer for xCreate/xConnect */
126416  ){
126417  #ifdef SQLITE_ENABLE_API_ARMOR
126418    if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
126419  #endif
126420    return createModule(db, zName, pModule, pAux, 0);
126421  }
126422  
126423  /*
126424  ** External API function used to create a new virtual-table module.
126425  */
126426  SQLITE_API int sqlite3_create_module_v2(
126427    sqlite3 *db,                    /* Database in which module is registered */
126428    const char *zName,              /* Name assigned to this module */
126429    const sqlite3_module *pModule,  /* The definition of the module */
126430    void *pAux,                     /* Context pointer for xCreate/xConnect */
126431    void (*xDestroy)(void *)        /* Module destructor function */
126432  ){
126433  #ifdef SQLITE_ENABLE_API_ARMOR
126434    if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
126435  #endif
126436    return createModule(db, zName, pModule, pAux, xDestroy);
126437  }
126438  
126439  /*
126440  ** Lock the virtual table so that it cannot be disconnected.
126441  ** Locks nest.  Every lock should have a corresponding unlock.
126442  ** If an unlock is omitted, resources leaks will occur.  
126443  **
126444  ** If a disconnect is attempted while a virtual table is locked,
126445  ** the disconnect is deferred until all locks have been removed.
126446  */
126447  SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
126448    pVTab->nRef++;
126449  }
126450  
126451  
126452  /*
126453  ** pTab is a pointer to a Table structure representing a virtual-table.
126454  ** Return a pointer to the VTable object used by connection db to access 
126455  ** this virtual-table, if one has been created, or NULL otherwise.
126456  */
126457  SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
126458    VTable *pVtab;
126459    assert( IsVirtual(pTab) );
126460    for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
126461    return pVtab;
126462  }
126463  
126464  /*
126465  ** Decrement the ref-count on a virtual table object. When the ref-count
126466  ** reaches zero, call the xDisconnect() method to delete the object.
126467  */
126468  SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
126469    sqlite3 *db = pVTab->db;
126470  
126471    assert( db );
126472    assert( pVTab->nRef>0 );
126473    assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
126474  
126475    pVTab->nRef--;
126476    if( pVTab->nRef==0 ){
126477      sqlite3_vtab *p = pVTab->pVtab;
126478      if( p ){
126479        p->pModule->xDisconnect(p);
126480      }
126481      sqlite3DbFree(db, pVTab);
126482    }
126483  }
126484  
126485  /*
126486  ** Table p is a virtual table. This function moves all elements in the
126487  ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
126488  ** database connections to be disconnected at the next opportunity. 
126489  ** Except, if argument db is not NULL, then the entry associated with
126490  ** connection db is left in the p->pVTable list.
126491  */
126492  static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
126493    VTable *pRet = 0;
126494    VTable *pVTable = p->pVTable;
126495    p->pVTable = 0;
126496  
126497    /* Assert that the mutex (if any) associated with the BtShared database 
126498    ** that contains table p is held by the caller. See header comments 
126499    ** above function sqlite3VtabUnlockList() for an explanation of why
126500    ** this makes it safe to access the sqlite3.pDisconnect list of any
126501    ** database connection that may have an entry in the p->pVTable list.
126502    */
126503    assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
126504  
126505    while( pVTable ){
126506      sqlite3 *db2 = pVTable->db;
126507      VTable *pNext = pVTable->pNext;
126508      assert( db2 );
126509      if( db2==db ){
126510        pRet = pVTable;
126511        p->pVTable = pRet;
126512        pRet->pNext = 0;
126513      }else{
126514        pVTable->pNext = db2->pDisconnect;
126515        db2->pDisconnect = pVTable;
126516      }
126517      pVTable = pNext;
126518    }
126519  
126520    assert( !db || pRet );
126521    return pRet;
126522  }
126523  
126524  /*
126525  ** Table *p is a virtual table. This function removes the VTable object
126526  ** for table *p associated with database connection db from the linked
126527  ** list in p->pVTab. It also decrements the VTable ref count. This is
126528  ** used when closing database connection db to free all of its VTable
126529  ** objects without disturbing the rest of the Schema object (which may
126530  ** be being used by other shared-cache connections).
126531  */
126532  SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
126533    VTable **ppVTab;
126534  
126535    assert( IsVirtual(p) );
126536    assert( sqlite3BtreeHoldsAllMutexes(db) );
126537    assert( sqlite3_mutex_held(db->mutex) );
126538  
126539    for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
126540      if( (*ppVTab)->db==db  ){
126541        VTable *pVTab = *ppVTab;
126542        *ppVTab = pVTab->pNext;
126543        sqlite3VtabUnlock(pVTab);
126544        break;
126545      }
126546    }
126547  }
126548  
126549  
126550  /*
126551  ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
126552  **
126553  ** This function may only be called when the mutexes associated with all
126554  ** shared b-tree databases opened using connection db are held by the 
126555  ** caller. This is done to protect the sqlite3.pDisconnect list. The
126556  ** sqlite3.pDisconnect list is accessed only as follows:
126557  **
126558  **   1) By this function. In this case, all BtShared mutexes and the mutex
126559  **      associated with the database handle itself must be held.
126560  **
126561  **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
126562  **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
126563  **      associated with the database the virtual table is stored in is held
126564  **      or, if the virtual table is stored in a non-sharable database, then
126565  **      the database handle mutex is held.
126566  **
126567  ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
126568  ** by multiple threads. It is thread-safe.
126569  */
126570  SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
126571    VTable *p = db->pDisconnect;
126572    db->pDisconnect = 0;
126573  
126574    assert( sqlite3BtreeHoldsAllMutexes(db) );
126575    assert( sqlite3_mutex_held(db->mutex) );
126576  
126577    if( p ){
126578      sqlite3ExpirePreparedStatements(db);
126579      do {
126580        VTable *pNext = p->pNext;
126581        sqlite3VtabUnlock(p);
126582        p = pNext;
126583      }while( p );
126584    }
126585  }
126586  
126587  /*
126588  ** Clear any and all virtual-table information from the Table record.
126589  ** This routine is called, for example, just before deleting the Table
126590  ** record.
126591  **
126592  ** Since it is a virtual-table, the Table structure contains a pointer
126593  ** to the head of a linked list of VTable structures. Each VTable 
126594  ** structure is associated with a single sqlite3* user of the schema.
126595  ** The reference count of the VTable structure associated with database 
126596  ** connection db is decremented immediately (which may lead to the 
126597  ** structure being xDisconnected and free). Any other VTable structures
126598  ** in the list are moved to the sqlite3.pDisconnect list of the associated 
126599  ** database connection.
126600  */
126601  SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
126602    if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
126603    if( p->azModuleArg ){
126604      int i;
126605      for(i=0; i<p->nModuleArg; i++){
126606        if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
126607      }
126608      sqlite3DbFree(db, p->azModuleArg);
126609    }
126610  }
126611  
126612  /*
126613  ** Add a new module argument to pTable->azModuleArg[].
126614  ** The string is not copied - the pointer is stored.  The
126615  ** string will be freed automatically when the table is
126616  ** deleted.
126617  */
126618  static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
126619    int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
126620    char **azModuleArg;
126621    azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
126622    if( azModuleArg==0 ){
126623      sqlite3DbFree(db, zArg);
126624    }else{
126625      int i = pTable->nModuleArg++;
126626      azModuleArg[i] = zArg;
126627      azModuleArg[i+1] = 0;
126628      pTable->azModuleArg = azModuleArg;
126629    }
126630  }
126631  
126632  /*
126633  ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
126634  ** statement.  The module name has been parsed, but the optional list
126635  ** of parameters that follow the module name are still pending.
126636  */
126637  SQLITE_PRIVATE void sqlite3VtabBeginParse(
126638    Parse *pParse,        /* Parsing context */
126639    Token *pName1,        /* Name of new table, or database name */
126640    Token *pName2,        /* Name of new table or NULL */
126641    Token *pModuleName,   /* Name of the module for the virtual table */
126642    int ifNotExists       /* No error if the table already exists */
126643  ){
126644    int iDb;              /* The database the table is being created in */
126645    Table *pTable;        /* The new virtual table */
126646    sqlite3 *db;          /* Database connection */
126647  
126648    sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
126649    pTable = pParse->pNewTable;
126650    if( pTable==0 ) return;
126651    assert( 0==pTable->pIndex );
126652  
126653    db = pParse->db;
126654    iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
126655    assert( iDb>=0 );
126656  
126657    assert( pTable->nModuleArg==0 );
126658    addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
126659    addModuleArgument(db, pTable, 0);
126660    addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
126661    assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
126662         || (pParse->sNameToken.z==pName1->z && pName2->z==0)
126663    );
126664    pParse->sNameToken.n = (int)(
126665        &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
126666    );
126667  
126668  #ifndef SQLITE_OMIT_AUTHORIZATION
126669    /* Creating a virtual table invokes the authorization callback twice.
126670    ** The first invocation, to obtain permission to INSERT a row into the
126671    ** sqlite_master table, has already been made by sqlite3StartTable().
126672    ** The second call, to obtain permission to create the table, is made now.
126673    */
126674    if( pTable->azModuleArg ){
126675      sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
126676              pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
126677    }
126678  #endif
126679  }
126680  
126681  /*
126682  ** This routine takes the module argument that has been accumulating
126683  ** in pParse->zArg[] and appends it to the list of arguments on the
126684  ** virtual table currently under construction in pParse->pTable.
126685  */
126686  static void addArgumentToVtab(Parse *pParse){
126687    if( pParse->sArg.z && pParse->pNewTable ){
126688      const char *z = (const char*)pParse->sArg.z;
126689      int n = pParse->sArg.n;
126690      sqlite3 *db = pParse->db;
126691      addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
126692    }
126693  }
126694  
126695  /*
126696  ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
126697  ** has been completely parsed.
126698  */
126699  SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
126700    Table *pTab = pParse->pNewTable;  /* The table being constructed */
126701    sqlite3 *db = pParse->db;         /* The database connection */
126702  
126703    if( pTab==0 ) return;
126704    addArgumentToVtab(pParse);
126705    pParse->sArg.z = 0;
126706    if( pTab->nModuleArg<1 ) return;
126707    
126708    /* If the CREATE VIRTUAL TABLE statement is being entered for the
126709    ** first time (in other words if the virtual table is actually being
126710    ** created now instead of just being read out of sqlite_master) then
126711    ** do additional initialization work and store the statement text
126712    ** in the sqlite_master table.
126713    */
126714    if( !db->init.busy ){
126715      char *zStmt;
126716      char *zWhere;
126717      int iDb;
126718      int iReg;
126719      Vdbe *v;
126720  
126721      /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
126722      if( pEnd ){
126723        pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
126724      }
126725      zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
126726  
126727      /* A slot for the record has already been allocated in the 
126728      ** SQLITE_MASTER table.  We just need to update that slot with all
126729      ** the information we've collected.  
126730      **
126731      ** The VM register number pParse->regRowid holds the rowid of an
126732      ** entry in the sqlite_master table tht was created for this vtab
126733      ** by sqlite3StartTable().
126734      */
126735      iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
126736      sqlite3NestedParse(pParse,
126737        "UPDATE %Q.%s "
126738           "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
126739         "WHERE rowid=#%d",
126740        db->aDb[iDb].zDbSName, MASTER_NAME,
126741        pTab->zName,
126742        pTab->zName,
126743        zStmt,
126744        pParse->regRowid
126745      );
126746      sqlite3DbFree(db, zStmt);
126747      v = sqlite3GetVdbe(pParse);
126748      sqlite3ChangeCookie(pParse, iDb);
126749  
126750      sqlite3VdbeAddOp0(v, OP_Expire);
126751      zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
126752      sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
126753  
126754      iReg = ++pParse->nMem;
126755      sqlite3VdbeLoadString(v, iReg, pTab->zName);
126756      sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
126757    }
126758  
126759    /* If we are rereading the sqlite_master table create the in-memory
126760    ** record of the table. The xConnect() method is not called until
126761    ** the first time the virtual table is used in an SQL statement. This
126762    ** allows a schema that contains virtual tables to be loaded before
126763    ** the required virtual table implementations are registered.  */
126764    else {
126765      Table *pOld;
126766      Schema *pSchema = pTab->pSchema;
126767      const char *zName = pTab->zName;
126768      assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
126769      pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
126770      if( pOld ){
126771        sqlite3OomFault(db);
126772        assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
126773        return;
126774      }
126775      pParse->pNewTable = 0;
126776    }
126777  }
126778  
126779  /*
126780  ** The parser calls this routine when it sees the first token
126781  ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
126782  */
126783  SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
126784    addArgumentToVtab(pParse);
126785    pParse->sArg.z = 0;
126786    pParse->sArg.n = 0;
126787  }
126788  
126789  /*
126790  ** The parser calls this routine for each token after the first token
126791  ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
126792  */
126793  SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
126794    Token *pArg = &pParse->sArg;
126795    if( pArg->z==0 ){
126796      pArg->z = p->z;
126797      pArg->n = p->n;
126798    }else{
126799      assert(pArg->z <= p->z);
126800      pArg->n = (int)(&p->z[p->n] - pArg->z);
126801    }
126802  }
126803  
126804  /*
126805  ** Invoke a virtual table constructor (either xCreate or xConnect). The
126806  ** pointer to the function to invoke is passed as the fourth parameter
126807  ** to this procedure.
126808  */
126809  static int vtabCallConstructor(
126810    sqlite3 *db, 
126811    Table *pTab,
126812    Module *pMod,
126813    int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
126814    char **pzErr
126815  ){
126816    VtabCtx sCtx;
126817    VTable *pVTable;
126818    int rc;
126819    const char *const*azArg = (const char *const*)pTab->azModuleArg;
126820    int nArg = pTab->nModuleArg;
126821    char *zErr = 0;
126822    char *zModuleName;
126823    int iDb;
126824    VtabCtx *pCtx;
126825  
126826    /* Check that the virtual-table is not already being initialized */
126827    for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
126828      if( pCtx->pTab==pTab ){
126829        *pzErr = sqlite3MPrintf(db, 
126830            "vtable constructor called recursively: %s", pTab->zName
126831        );
126832        return SQLITE_LOCKED;
126833      }
126834    }
126835  
126836    zModuleName = sqlite3DbStrDup(db, pTab->zName);
126837    if( !zModuleName ){
126838      return SQLITE_NOMEM_BKPT;
126839    }
126840  
126841    pVTable = sqlite3MallocZero(sizeof(VTable));
126842    if( !pVTable ){
126843      sqlite3OomFault(db);
126844      sqlite3DbFree(db, zModuleName);
126845      return SQLITE_NOMEM_BKPT;
126846    }
126847    pVTable->db = db;
126848    pVTable->pMod = pMod;
126849  
126850    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
126851    pTab->azModuleArg[1] = db->aDb[iDb].zDbSName;
126852  
126853    /* Invoke the virtual table constructor */
126854    assert( &db->pVtabCtx );
126855    assert( xConstruct );
126856    sCtx.pTab = pTab;
126857    sCtx.pVTable = pVTable;
126858    sCtx.pPrior = db->pVtabCtx;
126859    sCtx.bDeclared = 0;
126860    db->pVtabCtx = &sCtx;
126861    rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
126862    db->pVtabCtx = sCtx.pPrior;
126863    if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
126864    assert( sCtx.pTab==pTab );
126865  
126866    if( SQLITE_OK!=rc ){
126867      if( zErr==0 ){
126868        *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
126869      }else {
126870        *pzErr = sqlite3MPrintf(db, "%s", zErr);
126871        sqlite3_free(zErr);
126872      }
126873      sqlite3DbFree(db, pVTable);
126874    }else if( ALWAYS(pVTable->pVtab) ){
126875      /* Justification of ALWAYS():  A correct vtab constructor must allocate
126876      ** the sqlite3_vtab object if successful.  */
126877      memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
126878      pVTable->pVtab->pModule = pMod->pModule;
126879      pVTable->nRef = 1;
126880      if( sCtx.bDeclared==0 ){
126881        const char *zFormat = "vtable constructor did not declare schema: %s";
126882        *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
126883        sqlite3VtabUnlock(pVTable);
126884        rc = SQLITE_ERROR;
126885      }else{
126886        int iCol;
126887        u8 oooHidden = 0;
126888        /* If everything went according to plan, link the new VTable structure
126889        ** into the linked list headed by pTab->pVTable. Then loop through the 
126890        ** columns of the table to see if any of them contain the token "hidden".
126891        ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
126892        ** the type string.  */
126893        pVTable->pNext = pTab->pVTable;
126894        pTab->pVTable = pVTable;
126895  
126896        for(iCol=0; iCol<pTab->nCol; iCol++){
126897          char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
126898          int nType;
126899          int i = 0;
126900          nType = sqlite3Strlen30(zType);
126901          for(i=0; i<nType; i++){
126902            if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
126903             && (i==0 || zType[i-1]==' ')
126904             && (zType[i+6]=='\0' || zType[i+6]==' ')
126905            ){
126906              break;
126907            }
126908          }
126909          if( i<nType ){
126910            int j;
126911            int nDel = 6 + (zType[i+6] ? 1 : 0);
126912            for(j=i; (j+nDel)<=nType; j++){
126913              zType[j] = zType[j+nDel];
126914            }
126915            if( zType[i]=='\0' && i>0 ){
126916              assert(zType[i-1]==' ');
126917              zType[i-1] = '\0';
126918            }
126919            pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
126920            oooHidden = TF_OOOHidden;
126921          }else{
126922            pTab->tabFlags |= oooHidden;
126923          }
126924        }
126925      }
126926    }
126927  
126928    sqlite3DbFree(db, zModuleName);
126929    return rc;
126930  }
126931  
126932  /*
126933  ** This function is invoked by the parser to call the xConnect() method
126934  ** of the virtual table pTab. If an error occurs, an error code is returned 
126935  ** and an error left in pParse.
126936  **
126937  ** This call is a no-op if table pTab is not a virtual table.
126938  */
126939  SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
126940    sqlite3 *db = pParse->db;
126941    const char *zMod;
126942    Module *pMod;
126943    int rc;
126944  
126945    assert( pTab );
126946    if( !IsVirtual(pTab) || sqlite3GetVTable(db, pTab) ){
126947      return SQLITE_OK;
126948    }
126949  
126950    /* Locate the required virtual table module */
126951    zMod = pTab->azModuleArg[0];
126952    pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
126953  
126954    if( !pMod ){
126955      const char *zModule = pTab->azModuleArg[0];
126956      sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
126957      rc = SQLITE_ERROR;
126958    }else{
126959      char *zErr = 0;
126960      rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
126961      if( rc!=SQLITE_OK ){
126962        sqlite3ErrorMsg(pParse, "%s", zErr);
126963        pParse->rc = rc;
126964      }
126965      sqlite3DbFree(db, zErr);
126966    }
126967  
126968    return rc;
126969  }
126970  /*
126971  ** Grow the db->aVTrans[] array so that there is room for at least one
126972  ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
126973  */
126974  static int growVTrans(sqlite3 *db){
126975    const int ARRAY_INCR = 5;
126976  
126977    /* Grow the sqlite3.aVTrans array if required */
126978    if( (db->nVTrans%ARRAY_INCR)==0 ){
126979      VTable **aVTrans;
126980      int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
126981      aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
126982      if( !aVTrans ){
126983        return SQLITE_NOMEM_BKPT;
126984      }
126985      memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
126986      db->aVTrans = aVTrans;
126987    }
126988  
126989    return SQLITE_OK;
126990  }
126991  
126992  /*
126993  ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
126994  ** have already been reserved using growVTrans().
126995  */
126996  static void addToVTrans(sqlite3 *db, VTable *pVTab){
126997    /* Add pVtab to the end of sqlite3.aVTrans */
126998    db->aVTrans[db->nVTrans++] = pVTab;
126999    sqlite3VtabLock(pVTab);
127000  }
127001  
127002  /*
127003  ** This function is invoked by the vdbe to call the xCreate method
127004  ** of the virtual table named zTab in database iDb. 
127005  **
127006  ** If an error occurs, *pzErr is set to point to an English language
127007  ** description of the error and an SQLITE_XXX error code is returned.
127008  ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
127009  */
127010  SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
127011    int rc = SQLITE_OK;
127012    Table *pTab;
127013    Module *pMod;
127014    const char *zMod;
127015  
127016    pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
127017    assert( pTab && IsVirtual(pTab) && !pTab->pVTable );
127018  
127019    /* Locate the required virtual table module */
127020    zMod = pTab->azModuleArg[0];
127021    pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
127022  
127023    /* If the module has been registered and includes a Create method, 
127024    ** invoke it now. If the module has not been registered, return an 
127025    ** error. Otherwise, do nothing.
127026    */
127027    if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
127028      *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
127029      rc = SQLITE_ERROR;
127030    }else{
127031      rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
127032    }
127033  
127034    /* Justification of ALWAYS():  The xConstructor method is required to
127035    ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
127036    if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
127037      rc = growVTrans(db);
127038      if( rc==SQLITE_OK ){
127039        addToVTrans(db, sqlite3GetVTable(db, pTab));
127040      }
127041    }
127042  
127043    return rc;
127044  }
127045  
127046  /*
127047  ** This function is used to set the schema of a virtual table.  It is only
127048  ** valid to call this function from within the xCreate() or xConnect() of a
127049  ** virtual table module.
127050  */
127051  SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
127052    VtabCtx *pCtx;
127053    int rc = SQLITE_OK;
127054    Table *pTab;
127055    char *zErr = 0;
127056    Parse sParse;
127057  
127058  #ifdef SQLITE_ENABLE_API_ARMOR
127059    if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
127060      return SQLITE_MISUSE_BKPT;
127061    }
127062  #endif
127063    sqlite3_mutex_enter(db->mutex);
127064    pCtx = db->pVtabCtx;
127065    if( !pCtx || pCtx->bDeclared ){
127066      sqlite3Error(db, SQLITE_MISUSE);
127067      sqlite3_mutex_leave(db->mutex);
127068      return SQLITE_MISUSE_BKPT;
127069    }
127070    pTab = pCtx->pTab;
127071    assert( IsVirtual(pTab) );
127072  
127073    memset(&sParse, 0, sizeof(sParse));
127074    sParse.declareVtab = 1;
127075    sParse.db = db;
127076    sParse.nQueryLoop = 1;
127077    if( SQLITE_OK==sqlite3RunParser(&sParse, zCreateTable, &zErr) 
127078     && sParse.pNewTable
127079     && !db->mallocFailed
127080     && !sParse.pNewTable->pSelect
127081     && !IsVirtual(sParse.pNewTable)
127082    ){
127083      if( !pTab->aCol ){
127084        Table *pNew = sParse.pNewTable;
127085        Index *pIdx;
127086        pTab->aCol = pNew->aCol;
127087        pTab->nCol = pNew->nCol;
127088        pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
127089        pNew->nCol = 0;
127090        pNew->aCol = 0;
127091        assert( pTab->pIndex==0 );
127092        assert( HasRowid(pNew) || sqlite3PrimaryKeyIndex(pNew)!=0 );
127093        if( !HasRowid(pNew)
127094         && pCtx->pVTable->pMod->pModule->xUpdate!=0
127095         && sqlite3PrimaryKeyIndex(pNew)->nKeyCol!=1
127096        ){
127097          /* WITHOUT ROWID virtual tables must either be read-only (xUpdate==0)
127098          ** or else must have a single-column PRIMARY KEY */
127099          rc = SQLITE_ERROR;
127100        }
127101        pIdx = pNew->pIndex;
127102        if( pIdx ){
127103          assert( pIdx->pNext==0 );
127104          pTab->pIndex = pIdx;
127105          pNew->pIndex = 0;
127106          pIdx->pTable = pTab;
127107        }
127108      }
127109      pCtx->bDeclared = 1;
127110    }else{
127111      sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
127112      sqlite3DbFree(db, zErr);
127113      rc = SQLITE_ERROR;
127114    }
127115    sParse.declareVtab = 0;
127116  
127117    if( sParse.pVdbe ){
127118      sqlite3VdbeFinalize(sParse.pVdbe);
127119    }
127120    sqlite3DeleteTable(db, sParse.pNewTable);
127121    sqlite3ParserReset(&sParse);
127122  
127123    assert( (rc&0xff)==rc );
127124    rc = sqlite3ApiExit(db, rc);
127125    sqlite3_mutex_leave(db->mutex);
127126    return rc;
127127  }
127128  
127129  /*
127130  ** This function is invoked by the vdbe to call the xDestroy method
127131  ** of the virtual table named zTab in database iDb. This occurs
127132  ** when a DROP TABLE is mentioned.
127133  **
127134  ** This call is a no-op if zTab is not a virtual table.
127135  */
127136  SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
127137    int rc = SQLITE_OK;
127138    Table *pTab;
127139  
127140    pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
127141    if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
127142      VTable *p;
127143      int (*xDestroy)(sqlite3_vtab *);
127144      for(p=pTab->pVTable; p; p=p->pNext){
127145        assert( p->pVtab );
127146        if( p->pVtab->nRef>0 ){
127147          return SQLITE_LOCKED;
127148        }
127149      }
127150      p = vtabDisconnectAll(db, pTab);
127151      xDestroy = p->pMod->pModule->xDestroy;
127152      assert( xDestroy!=0 );  /* Checked before the virtual table is created */
127153      rc = xDestroy(p->pVtab);
127154      /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
127155      if( rc==SQLITE_OK ){
127156        assert( pTab->pVTable==p && p->pNext==0 );
127157        p->pVtab = 0;
127158        pTab->pVTable = 0;
127159        sqlite3VtabUnlock(p);
127160      }
127161    }
127162  
127163    return rc;
127164  }
127165  
127166  /*
127167  ** This function invokes either the xRollback or xCommit method
127168  ** of each of the virtual tables in the sqlite3.aVTrans array. The method
127169  ** called is identified by the second argument, "offset", which is
127170  ** the offset of the method to call in the sqlite3_module structure.
127171  **
127172  ** The array is cleared after invoking the callbacks. 
127173  */
127174  static void callFinaliser(sqlite3 *db, int offset){
127175    int i;
127176    if( db->aVTrans ){
127177      VTable **aVTrans = db->aVTrans;
127178      db->aVTrans = 0;
127179      for(i=0; i<db->nVTrans; i++){
127180        VTable *pVTab = aVTrans[i];
127181        sqlite3_vtab *p = pVTab->pVtab;
127182        if( p ){
127183          int (*x)(sqlite3_vtab *);
127184          x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
127185          if( x ) x(p);
127186        }
127187        pVTab->iSavepoint = 0;
127188        sqlite3VtabUnlock(pVTab);
127189      }
127190      sqlite3DbFree(db, aVTrans);
127191      db->nVTrans = 0;
127192    }
127193  }
127194  
127195  /*
127196  ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
127197  ** array. Return the error code for the first error that occurs, or
127198  ** SQLITE_OK if all xSync operations are successful.
127199  **
127200  ** If an error message is available, leave it in p->zErrMsg.
127201  */
127202  SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
127203    int i;
127204    int rc = SQLITE_OK;
127205    VTable **aVTrans = db->aVTrans;
127206  
127207    db->aVTrans = 0;
127208    for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
127209      int (*x)(sqlite3_vtab *);
127210      sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
127211      if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
127212        rc = x(pVtab);
127213        sqlite3VtabImportErrmsg(p, pVtab);
127214      }
127215    }
127216    db->aVTrans = aVTrans;
127217    return rc;
127218  }
127219  
127220  /*
127221  ** Invoke the xRollback method of all virtual tables in the 
127222  ** sqlite3.aVTrans array. Then clear the array itself.
127223  */
127224  SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
127225    callFinaliser(db, offsetof(sqlite3_module,xRollback));
127226    return SQLITE_OK;
127227  }
127228  
127229  /*
127230  ** Invoke the xCommit method of all virtual tables in the 
127231  ** sqlite3.aVTrans array. Then clear the array itself.
127232  */
127233  SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
127234    callFinaliser(db, offsetof(sqlite3_module,xCommit));
127235    return SQLITE_OK;
127236  }
127237  
127238  /*
127239  ** If the virtual table pVtab supports the transaction interface
127240  ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
127241  ** not currently open, invoke the xBegin method now.
127242  **
127243  ** If the xBegin call is successful, place the sqlite3_vtab pointer
127244  ** in the sqlite3.aVTrans array.
127245  */
127246  SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
127247    int rc = SQLITE_OK;
127248    const sqlite3_module *pModule;
127249  
127250    /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
127251    ** than zero, then this function is being called from within a
127252    ** virtual module xSync() callback. It is illegal to write to 
127253    ** virtual module tables in this case, so return SQLITE_LOCKED.
127254    */
127255    if( sqlite3VtabInSync(db) ){
127256      return SQLITE_LOCKED;
127257    }
127258    if( !pVTab ){
127259      return SQLITE_OK;
127260    } 
127261    pModule = pVTab->pVtab->pModule;
127262  
127263    if( pModule->xBegin ){
127264      int i;
127265  
127266      /* If pVtab is already in the aVTrans array, return early */
127267      for(i=0; i<db->nVTrans; i++){
127268        if( db->aVTrans[i]==pVTab ){
127269          return SQLITE_OK;
127270        }
127271      }
127272  
127273      /* Invoke the xBegin method. If successful, add the vtab to the 
127274      ** sqlite3.aVTrans[] array. */
127275      rc = growVTrans(db);
127276      if( rc==SQLITE_OK ){
127277        rc = pModule->xBegin(pVTab->pVtab);
127278        if( rc==SQLITE_OK ){
127279          int iSvpt = db->nStatement + db->nSavepoint;
127280          addToVTrans(db, pVTab);
127281          if( iSvpt && pModule->xSavepoint ){
127282            pVTab->iSavepoint = iSvpt;
127283            rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
127284          }
127285        }
127286      }
127287    }
127288    return rc;
127289  }
127290  
127291  /*
127292  ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
127293  ** virtual tables that currently have an open transaction. Pass iSavepoint
127294  ** as the second argument to the virtual table method invoked.
127295  **
127296  ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
127297  ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is 
127298  ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
127299  ** an open transaction is invoked.
127300  **
127301  ** If any virtual table method returns an error code other than SQLITE_OK, 
127302  ** processing is abandoned and the error returned to the caller of this
127303  ** function immediately. If all calls to virtual table methods are successful,
127304  ** SQLITE_OK is returned.
127305  */
127306  SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
127307    int rc = SQLITE_OK;
127308  
127309    assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
127310    assert( iSavepoint>=-1 );
127311    if( db->aVTrans ){
127312      int i;
127313      for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
127314        VTable *pVTab = db->aVTrans[i];
127315        const sqlite3_module *pMod = pVTab->pMod->pModule;
127316        if( pVTab->pVtab && pMod->iVersion>=2 ){
127317          int (*xMethod)(sqlite3_vtab *, int);
127318          switch( op ){
127319            case SAVEPOINT_BEGIN:
127320              xMethod = pMod->xSavepoint;
127321              pVTab->iSavepoint = iSavepoint+1;
127322              break;
127323            case SAVEPOINT_ROLLBACK:
127324              xMethod = pMod->xRollbackTo;
127325              break;
127326            default:
127327              xMethod = pMod->xRelease;
127328              break;
127329          }
127330          if( xMethod && pVTab->iSavepoint>iSavepoint ){
127331            rc = xMethod(pVTab->pVtab, iSavepoint);
127332          }
127333        }
127334      }
127335    }
127336    return rc;
127337  }
127338  
127339  /*
127340  ** The first parameter (pDef) is a function implementation.  The
127341  ** second parameter (pExpr) is the first argument to this function.
127342  ** If pExpr is a column in a virtual table, then let the virtual
127343  ** table implementation have an opportunity to overload the function.
127344  **
127345  ** This routine is used to allow virtual table implementations to
127346  ** overload MATCH, LIKE, GLOB, and REGEXP operators.
127347  **
127348  ** Return either the pDef argument (indicating no change) or a 
127349  ** new FuncDef structure that is marked as ephemeral using the
127350  ** SQLITE_FUNC_EPHEM flag.
127351  */
127352  SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
127353    sqlite3 *db,    /* Database connection for reporting malloc problems */
127354    FuncDef *pDef,  /* Function to possibly overload */
127355    int nArg,       /* Number of arguments to the function */
127356    Expr *pExpr     /* First argument to the function */
127357  ){
127358    Table *pTab;
127359    sqlite3_vtab *pVtab;
127360    sqlite3_module *pMod;
127361    void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
127362    void *pArg = 0;
127363    FuncDef *pNew;
127364    int rc = 0;
127365    char *zLowerName;
127366    unsigned char *z;
127367  
127368  
127369    /* Check to see the left operand is a column in a virtual table */
127370    if( NEVER(pExpr==0) ) return pDef;
127371    if( pExpr->op!=TK_COLUMN ) return pDef;
127372    pTab = pExpr->pTab;
127373    if( pTab==0 ) return pDef;
127374    if( !IsVirtual(pTab) ) return pDef;
127375    pVtab = sqlite3GetVTable(db, pTab)->pVtab;
127376    assert( pVtab!=0 );
127377    assert( pVtab->pModule!=0 );
127378    pMod = (sqlite3_module *)pVtab->pModule;
127379    if( pMod->xFindFunction==0 ) return pDef;
127380   
127381    /* Call the xFindFunction method on the virtual table implementation
127382    ** to see if the implementation wants to overload this function 
127383    */
127384    zLowerName = sqlite3DbStrDup(db, pDef->zName);
127385    if( zLowerName ){
127386      for(z=(unsigned char*)zLowerName; *z; z++){
127387        *z = sqlite3UpperToLower[*z];
127388      }
127389      rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xSFunc, &pArg);
127390      sqlite3DbFree(db, zLowerName);
127391    }
127392    if( rc==0 ){
127393      return pDef;
127394    }
127395  
127396    /* Create a new ephemeral function definition for the overloaded
127397    ** function */
127398    pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
127399                               + sqlite3Strlen30(pDef->zName) + 1);
127400    if( pNew==0 ){
127401      return pDef;
127402    }
127403    *pNew = *pDef;
127404    pNew->zName = (const char*)&pNew[1];
127405    memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
127406    pNew->xSFunc = xSFunc;
127407    pNew->pUserData = pArg;
127408    pNew->funcFlags |= SQLITE_FUNC_EPHEM;
127409    return pNew;
127410  }
127411  
127412  /*
127413  ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
127414  ** array so that an OP_VBegin will get generated for it.  Add pTab to the
127415  ** array if it is missing.  If pTab is already in the array, this routine
127416  ** is a no-op.
127417  */
127418  SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
127419    Parse *pToplevel = sqlite3ParseToplevel(pParse);
127420    int i, n;
127421    Table **apVtabLock;
127422  
127423    assert( IsVirtual(pTab) );
127424    for(i=0; i<pToplevel->nVtabLock; i++){
127425      if( pTab==pToplevel->apVtabLock[i] ) return;
127426    }
127427    n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
127428    apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
127429    if( apVtabLock ){
127430      pToplevel->apVtabLock = apVtabLock;
127431      pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
127432    }else{
127433      sqlite3OomFault(pToplevel->db);
127434    }
127435  }
127436  
127437  /*
127438  ** Check to see if virtual table module pMod can be have an eponymous
127439  ** virtual table instance.  If it can, create one if one does not already
127440  ** exist. Return non-zero if the eponymous virtual table instance exists
127441  ** when this routine returns, and return zero if it does not exist.
127442  **
127443  ** An eponymous virtual table instance is one that is named after its
127444  ** module, and more importantly, does not require a CREATE VIRTUAL TABLE
127445  ** statement in order to come into existance.  Eponymous virtual table
127446  ** instances always exist.  They cannot be DROP-ed.
127447  **
127448  ** Any virtual table module for which xConnect and xCreate are the same
127449  ** method can have an eponymous virtual table instance.
127450  */
127451  SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
127452    const sqlite3_module *pModule = pMod->pModule;
127453    Table *pTab;
127454    char *zErr = 0;
127455    int rc;
127456    sqlite3 *db = pParse->db;
127457    if( pMod->pEpoTab ) return 1;
127458    if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
127459    pTab = sqlite3DbMallocZero(db, sizeof(Table));
127460    if( pTab==0 ) return 0;
127461    pTab->zName = sqlite3DbStrDup(db, pMod->zName);
127462    if( pTab->zName==0 ){
127463      sqlite3DbFree(db, pTab);
127464      return 0;
127465    }
127466    pMod->pEpoTab = pTab;
127467    pTab->nTabRef = 1;
127468    pTab->pSchema = db->aDb[0].pSchema;
127469    assert( pTab->nModuleArg==0 );
127470    pTab->iPKey = -1;
127471    addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
127472    addModuleArgument(db, pTab, 0);
127473    addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
127474    rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
127475    if( rc ){
127476      sqlite3ErrorMsg(pParse, "%s", zErr);
127477      sqlite3DbFree(db, zErr);
127478      sqlite3VtabEponymousTableClear(db, pMod);
127479      return 0;
127480    }
127481    return 1;
127482  }
127483  
127484  /*
127485  ** Erase the eponymous virtual table instance associated with
127486  ** virtual table module pMod, if it exists.
127487  */
127488  SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
127489    Table *pTab = pMod->pEpoTab;
127490    if( pTab!=0 ){
127491      /* Mark the table as Ephemeral prior to deleting it, so that the
127492      ** sqlite3DeleteTable() routine will know that it is not stored in 
127493      ** the schema. */
127494      pTab->tabFlags |= TF_Ephemeral;
127495      sqlite3DeleteTable(db, pTab);
127496      pMod->pEpoTab = 0;
127497    }
127498  }
127499  
127500  /*
127501  ** Return the ON CONFLICT resolution mode in effect for the virtual
127502  ** table update operation currently in progress.
127503  **
127504  ** The results of this routine are undefined unless it is called from
127505  ** within an xUpdate method.
127506  */
127507  SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
127508    static const unsigned char aMap[] = { 
127509      SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE 
127510    };
127511  #ifdef SQLITE_ENABLE_API_ARMOR
127512    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
127513  #endif
127514    assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
127515    assert( OE_Ignore==4 && OE_Replace==5 );
127516    assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
127517    return (int)aMap[db->vtabOnConflict-1];
127518  }
127519  
127520  /*
127521  ** Call from within the xCreate() or xConnect() methods to provide 
127522  ** the SQLite core with additional information about the behavior
127523  ** of the virtual table being implemented.
127524  */
127525  SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
127526    va_list ap;
127527    int rc = SQLITE_OK;
127528  
127529  #ifdef SQLITE_ENABLE_API_ARMOR
127530    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
127531  #endif
127532    sqlite3_mutex_enter(db->mutex);
127533    va_start(ap, op);
127534    switch( op ){
127535      case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
127536        VtabCtx *p = db->pVtabCtx;
127537        if( !p ){
127538          rc = SQLITE_MISUSE_BKPT;
127539        }else{
127540          assert( p->pTab==0 || IsVirtual(p->pTab) );
127541          p->pVTable->bConstraint = (u8)va_arg(ap, int);
127542        }
127543        break;
127544      }
127545      default:
127546        rc = SQLITE_MISUSE_BKPT;
127547        break;
127548    }
127549    va_end(ap);
127550  
127551    if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
127552    sqlite3_mutex_leave(db->mutex);
127553    return rc;
127554  }
127555  
127556  #endif /* SQLITE_OMIT_VIRTUALTABLE */
127557  
127558  /************** End of vtab.c ************************************************/
127559  /************** Begin file wherecode.c ***************************************/
127560  /*
127561  ** 2015-06-06
127562  **
127563  ** The author disclaims copyright to this source code.  In place of
127564  ** a legal notice, here is a blessing:
127565  **
127566  **    May you do good and not evil.
127567  **    May you find forgiveness for yourself and forgive others.
127568  **    May you share freely, never taking more than you give.
127569  **
127570  *************************************************************************
127571  ** This module contains C code that generates VDBE code used to process
127572  ** the WHERE clause of SQL statements.
127573  **
127574  ** This file was split off from where.c on 2015-06-06 in order to reduce the
127575  ** size of where.c and make it easier to edit.  This file contains the routines
127576  ** that actually generate the bulk of the WHERE loop code.  The original where.c
127577  ** file retains the code that does query planning and analysis.
127578  */
127579  /* #include "sqliteInt.h" */
127580  /************** Include whereInt.h in the middle of wherecode.c **************/
127581  /************** Begin file whereInt.h ****************************************/
127582  /*
127583  ** 2013-11-12
127584  **
127585  ** The author disclaims copyright to this source code.  In place of
127586  ** a legal notice, here is a blessing:
127587  **
127588  **    May you do good and not evil.
127589  **    May you find forgiveness for yourself and forgive others.
127590  **    May you share freely, never taking more than you give.
127591  **
127592  *************************************************************************
127593  **
127594  ** This file contains structure and macro definitions for the query
127595  ** planner logic in "where.c".  These definitions are broken out into
127596  ** a separate source file for easier editing.
127597  */
127598  
127599  /*
127600  ** Trace output macros
127601  */
127602  #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
127603  /***/ int sqlite3WhereTrace;
127604  #endif
127605  #if defined(SQLITE_DEBUG) \
127606      && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
127607  # define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
127608  # define WHERETRACE_ENABLED 1
127609  #else
127610  # define WHERETRACE(K,X)
127611  #endif
127612  
127613  /* Forward references
127614  */
127615  typedef struct WhereClause WhereClause;
127616  typedef struct WhereMaskSet WhereMaskSet;
127617  typedef struct WhereOrInfo WhereOrInfo;
127618  typedef struct WhereAndInfo WhereAndInfo;
127619  typedef struct WhereLevel WhereLevel;
127620  typedef struct WhereLoop WhereLoop;
127621  typedef struct WherePath WherePath;
127622  typedef struct WhereTerm WhereTerm;
127623  typedef struct WhereLoopBuilder WhereLoopBuilder;
127624  typedef struct WhereScan WhereScan;
127625  typedef struct WhereOrCost WhereOrCost;
127626  typedef struct WhereOrSet WhereOrSet;
127627  
127628  /*
127629  ** This object contains information needed to implement a single nested
127630  ** loop in WHERE clause.
127631  **
127632  ** Contrast this object with WhereLoop.  This object describes the
127633  ** implementation of the loop.  WhereLoop describes the algorithm.
127634  ** This object contains a pointer to the WhereLoop algorithm as one of
127635  ** its elements.
127636  **
127637  ** The WhereInfo object contains a single instance of this object for
127638  ** each term in the FROM clause (which is to say, for each of the
127639  ** nested loops as implemented).  The order of WhereLevel objects determines
127640  ** the loop nested order, with WhereInfo.a[0] being the outer loop and
127641  ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
127642  */
127643  struct WhereLevel {
127644    int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
127645    int iTabCur;          /* The VDBE cursor used to access the table */
127646    int iIdxCur;          /* The VDBE cursor used to access pIdx */
127647    int addrBrk;          /* Jump here to break out of the loop */
127648    int addrNxt;          /* Jump here to start the next IN combination */
127649    int addrSkip;         /* Jump here for next iteration of skip-scan */
127650    int addrCont;         /* Jump here to continue with the next loop cycle */
127651    int addrFirst;        /* First instruction of interior of the loop */
127652    int addrBody;         /* Beginning of the body of this loop */
127653  #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
127654    u32 iLikeRepCntr;     /* LIKE range processing counter register (times 2) */
127655    int addrLikeRep;      /* LIKE range processing address */
127656  #endif
127657    u8 iFrom;             /* Which entry in the FROM clause */
127658    u8 op, p3, p5;        /* Opcode, P3 & P5 of the opcode that ends the loop */
127659    int p1, p2;           /* Operands of the opcode used to ends the loop */
127660    union {               /* Information that depends on pWLoop->wsFlags */
127661      struct {
127662        int nIn;              /* Number of entries in aInLoop[] */
127663        struct InLoop {
127664          int iCur;              /* The VDBE cursor used by this IN operator */
127665          int addrInTop;         /* Top of the IN loop */
127666          u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
127667        } *aInLoop;           /* Information about each nested IN operator */
127668      } in;                 /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
127669      Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
127670    } u;
127671    struct WhereLoop *pWLoop;  /* The selected WhereLoop object */
127672    Bitmask notReady;          /* FROM entries not usable at this level */
127673  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
127674    int addrVisit;        /* Address at which row is visited */
127675  #endif
127676  };
127677  
127678  /*
127679  ** Each instance of this object represents an algorithm for evaluating one
127680  ** term of a join.  Every term of the FROM clause will have at least
127681  ** one corresponding WhereLoop object (unless INDEXED BY constraints
127682  ** prevent a query solution - which is an error) and many terms of the
127683  ** FROM clause will have multiple WhereLoop objects, each describing a
127684  ** potential way of implementing that FROM-clause term, together with
127685  ** dependencies and cost estimates for using the chosen algorithm.
127686  **
127687  ** Query planning consists of building up a collection of these WhereLoop
127688  ** objects, then computing a particular sequence of WhereLoop objects, with
127689  ** one WhereLoop object per FROM clause term, that satisfy all dependencies
127690  ** and that minimize the overall cost.
127691  */
127692  struct WhereLoop {
127693    Bitmask prereq;       /* Bitmask of other loops that must run first */
127694    Bitmask maskSelf;     /* Bitmask identifying table iTab */
127695  #ifdef SQLITE_DEBUG
127696    char cId;             /* Symbolic ID of this loop for debugging use */
127697  #endif
127698    u8 iTab;              /* Position in FROM clause of table for this loop */
127699    u8 iSortIdx;          /* Sorting index number.  0==None */
127700    LogEst rSetup;        /* One-time setup cost (ex: create transient index) */
127701    LogEst rRun;          /* Cost of running each loop */
127702    LogEst nOut;          /* Estimated number of output rows */
127703    union {
127704      struct {               /* Information for internal btree tables */
127705        u16 nEq;               /* Number of equality constraints */
127706        u16 nBtm;              /* Size of BTM vector */
127707        u16 nTop;              /* Size of TOP vector */
127708        u16 nIdxCol;           /* Index column used for ORDER BY */
127709        Index *pIndex;         /* Index used, or NULL */
127710      } btree;
127711      struct {               /* Information for virtual tables */
127712        int idxNum;            /* Index number */
127713        u8 needFree;           /* True if sqlite3_free(idxStr) is needed */
127714        i8 isOrdered;          /* True if satisfies ORDER BY */
127715        u16 omitMask;          /* Terms that may be omitted */
127716        char *idxStr;          /* Index identifier string */
127717      } vtab;
127718    } u;
127719    u32 wsFlags;          /* WHERE_* flags describing the plan */
127720    u16 nLTerm;           /* Number of entries in aLTerm[] */
127721    u16 nSkip;            /* Number of NULL aLTerm[] entries */
127722    /**** whereLoopXfer() copies fields above ***********************/
127723  # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
127724    u16 nLSlot;           /* Number of slots allocated for aLTerm[] */
127725    WhereTerm **aLTerm;   /* WhereTerms used */
127726    WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
127727    WhereTerm *aLTermSpace[3];  /* Initial aLTerm[] space */
127728  };
127729  
127730  /* This object holds the prerequisites and the cost of running a
127731  ** subquery on one operand of an OR operator in the WHERE clause.
127732  ** See WhereOrSet for additional information 
127733  */
127734  struct WhereOrCost {
127735    Bitmask prereq;     /* Prerequisites */
127736    LogEst rRun;        /* Cost of running this subquery */
127737    LogEst nOut;        /* Number of outputs for this subquery */
127738  };
127739  
127740  /* The WhereOrSet object holds a set of possible WhereOrCosts that
127741  ** correspond to the subquery(s) of OR-clause processing.  Only the
127742  ** best N_OR_COST elements are retained.
127743  */
127744  #define N_OR_COST 3
127745  struct WhereOrSet {
127746    u16 n;                      /* Number of valid a[] entries */
127747    WhereOrCost a[N_OR_COST];   /* Set of best costs */
127748  };
127749  
127750  /*
127751  ** Each instance of this object holds a sequence of WhereLoop objects
127752  ** that implement some or all of a query plan.
127753  **
127754  ** Think of each WhereLoop object as a node in a graph with arcs
127755  ** showing dependencies and costs for travelling between nodes.  (That is
127756  ** not a completely accurate description because WhereLoop costs are a
127757  ** vector, not a scalar, and because dependencies are many-to-one, not
127758  ** one-to-one as are graph nodes.  But it is a useful visualization aid.)
127759  ** Then a WherePath object is a path through the graph that visits some
127760  ** or all of the WhereLoop objects once.
127761  **
127762  ** The "solver" works by creating the N best WherePath objects of length
127763  ** 1.  Then using those as a basis to compute the N best WherePath objects
127764  ** of length 2.  And so forth until the length of WherePaths equals the
127765  ** number of nodes in the FROM clause.  The best (lowest cost) WherePath
127766  ** at the end is the chosen query plan.
127767  */
127768  struct WherePath {
127769    Bitmask maskLoop;     /* Bitmask of all WhereLoop objects in this path */
127770    Bitmask revLoop;      /* aLoop[]s that should be reversed for ORDER BY */
127771    LogEst nRow;          /* Estimated number of rows generated by this path */
127772    LogEst rCost;         /* Total cost of this path */
127773    LogEst rUnsorted;     /* Total cost of this path ignoring sorting costs */
127774    i8 isOrdered;         /* No. of ORDER BY terms satisfied. -1 for unknown */
127775    WhereLoop **aLoop;    /* Array of WhereLoop objects implementing this path */
127776  };
127777  
127778  /*
127779  ** The query generator uses an array of instances of this structure to
127780  ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
127781  ** clause subexpression is separated from the others by AND operators,
127782  ** usually, or sometimes subexpressions separated by OR.
127783  **
127784  ** All WhereTerms are collected into a single WhereClause structure.  
127785  ** The following identity holds:
127786  **
127787  **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
127788  **
127789  ** When a term is of the form:
127790  **
127791  **              X <op> <expr>
127792  **
127793  ** where X is a column name and <op> is one of certain operators,
127794  ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
127795  ** cursor number and column number for X.  WhereTerm.eOperator records
127796  ** the <op> using a bitmask encoding defined by WO_xxx below.  The
127797  ** use of a bitmask encoding for the operator allows us to search
127798  ** quickly for terms that match any of several different operators.
127799  **
127800  ** A WhereTerm might also be two or more subterms connected by OR:
127801  **
127802  **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
127803  **
127804  ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
127805  ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
127806  ** is collected about the OR clause.
127807  **
127808  ** If a term in the WHERE clause does not match either of the two previous
127809  ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
127810  ** to the original subexpression content and wtFlags is set up appropriately
127811  ** but no other fields in the WhereTerm object are meaningful.
127812  **
127813  ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
127814  ** but they do so indirectly.  A single WhereMaskSet structure translates
127815  ** cursor number into bits and the translated bit is stored in the prereq
127816  ** fields.  The translation is used in order to maximize the number of
127817  ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
127818  ** spread out over the non-negative integers.  For example, the cursor
127819  ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
127820  ** translates these sparse cursor numbers into consecutive integers
127821  ** beginning with 0 in order to make the best possible use of the available
127822  ** bits in the Bitmask.  So, in the example above, the cursor numbers
127823  ** would be mapped into integers 0 through 7.
127824  **
127825  ** The number of terms in a join is limited by the number of bits
127826  ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
127827  ** is only able to process joins with 64 or fewer tables.
127828  */
127829  struct WhereTerm {
127830    Expr *pExpr;            /* Pointer to the subexpression that is this term */
127831    WhereClause *pWC;       /* The clause this term is part of */
127832    LogEst truthProb;       /* Probability of truth for this expression */
127833    u16 wtFlags;            /* TERM_xxx bit flags.  See below */
127834    u16 eOperator;          /* A WO_xx value describing <op> */
127835    u8 nChild;              /* Number of children that must disable us */
127836    u8 eMatchOp;            /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
127837    int iParent;            /* Disable pWC->a[iParent] when this term disabled */
127838    int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
127839    int iField;             /* Field in (?,?,?) IN (SELECT...) vector */
127840    union {
127841      int leftColumn;         /* Column number of X in "X <op> <expr>" */
127842      WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
127843      WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
127844    } u;
127845    Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
127846    Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
127847  };
127848  
127849  /*
127850  ** Allowed values of WhereTerm.wtFlags
127851  */
127852  #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
127853  #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
127854  #define TERM_CODED      0x04   /* This term is already coded */
127855  #define TERM_COPIED     0x08   /* Has a child */
127856  #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
127857  #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
127858  #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
127859  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
127860  #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
127861  #else
127862  #  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
127863  #endif
127864  #define TERM_LIKEOPT    0x100  /* Virtual terms from the LIKE optimization */
127865  #define TERM_LIKECOND   0x200  /* Conditionally this LIKE operator term */
127866  #define TERM_LIKE       0x400  /* The original LIKE operator */
127867  #define TERM_IS         0x800  /* Term.pExpr is an IS operator */
127868  #define TERM_VARSELECT  0x1000 /* Term.pExpr contains a correlated sub-query */
127869  
127870  /*
127871  ** An instance of the WhereScan object is used as an iterator for locating
127872  ** terms in the WHERE clause that are useful to the query planner.
127873  */
127874  struct WhereScan {
127875    WhereClause *pOrigWC;      /* Original, innermost WhereClause */
127876    WhereClause *pWC;          /* WhereClause currently being scanned */
127877    const char *zCollName;     /* Required collating sequence, if not NULL */
127878    Expr *pIdxExpr;            /* Search for this index expression */
127879    char idxaff;               /* Must match this affinity, if zCollName!=NULL */
127880    unsigned char nEquiv;      /* Number of entries in aEquiv[] */
127881    unsigned char iEquiv;      /* Next unused slot in aEquiv[] */
127882    u32 opMask;                /* Acceptable operators */
127883    int k;                     /* Resume scanning at this->pWC->a[this->k] */
127884    int aiCur[11];             /* Cursors in the equivalence class */
127885    i16 aiColumn[11];          /* Corresponding column number in the eq-class */
127886  };
127887  
127888  /*
127889  ** An instance of the following structure holds all information about a
127890  ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
127891  **
127892  ** Explanation of pOuter:  For a WHERE clause of the form
127893  **
127894  **           a AND ((b AND c) OR (d AND e)) AND f
127895  **
127896  ** There are separate WhereClause objects for the whole clause and for
127897  ** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
127898  ** subclauses points to the WhereClause object for the whole clause.
127899  */
127900  struct WhereClause {
127901    WhereInfo *pWInfo;       /* WHERE clause processing context */
127902    WhereClause *pOuter;     /* Outer conjunction */
127903    u8 op;                   /* Split operator.  TK_AND or TK_OR */
127904    int nTerm;               /* Number of terms */
127905    int nSlot;               /* Number of entries in a[] */
127906    WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
127907  #if defined(SQLITE_SMALL_STACK)
127908    WhereTerm aStatic[1];    /* Initial static space for a[] */
127909  #else
127910    WhereTerm aStatic[8];    /* Initial static space for a[] */
127911  #endif
127912  };
127913  
127914  /*
127915  ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
127916  ** a dynamically allocated instance of the following structure.
127917  */
127918  struct WhereOrInfo {
127919    WhereClause wc;          /* Decomposition into subterms */
127920    Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
127921  };
127922  
127923  /*
127924  ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
127925  ** a dynamically allocated instance of the following structure.
127926  */
127927  struct WhereAndInfo {
127928    WhereClause wc;          /* The subexpression broken out */
127929  };
127930  
127931  /*
127932  ** An instance of the following structure keeps track of a mapping
127933  ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
127934  **
127935  ** The VDBE cursor numbers are small integers contained in 
127936  ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
127937  ** clause, the cursor numbers might not begin with 0 and they might
127938  ** contain gaps in the numbering sequence.  But we want to make maximum
127939  ** use of the bits in our bitmasks.  This structure provides a mapping
127940  ** from the sparse cursor numbers into consecutive integers beginning
127941  ** with 0.
127942  **
127943  ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
127944  ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
127945  **
127946  ** For example, if the WHERE clause expression used these VDBE
127947  ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
127948  ** would map those cursor numbers into bits 0 through 5.
127949  **
127950  ** Note that the mapping is not necessarily ordered.  In the example
127951  ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
127952  ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
127953  ** does not really matter.  What is important is that sparse cursor
127954  ** numbers all get mapped into bit numbers that begin with 0 and contain
127955  ** no gaps.
127956  */
127957  struct WhereMaskSet {
127958    int bVarSelect;               /* Used by sqlite3WhereExprUsage() */
127959    int n;                        /* Number of assigned cursor values */
127960    int ix[BMS];                  /* Cursor assigned to each bit */
127961  };
127962  
127963  /*
127964  ** Initialize a WhereMaskSet object
127965  */
127966  #define initMaskSet(P)  (P)->n=0
127967  
127968  /*
127969  ** This object is a convenience wrapper holding all information needed
127970  ** to construct WhereLoop objects for a particular query.
127971  */
127972  struct WhereLoopBuilder {
127973    WhereInfo *pWInfo;        /* Information about this WHERE */
127974    WhereClause *pWC;         /* WHERE clause terms */
127975    ExprList *pOrderBy;       /* ORDER BY clause */
127976    WhereLoop *pNew;          /* Template WhereLoop */
127977    WhereOrSet *pOrSet;       /* Record best loops here, if not NULL */
127978  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
127979    UnpackedRecord *pRec;     /* Probe for stat4 (if required) */
127980    int nRecValid;            /* Number of valid fields currently in pRec */
127981  #endif
127982    unsigned int bldFlags;    /* SQLITE_BLDF_* flags */
127983  };
127984  
127985  /* Allowed values for WhereLoopBuider.bldFlags */
127986  #define SQLITE_BLDF_INDEXED  0x0001   /* An index is used */
127987  #define SQLITE_BLDF_UNIQUE   0x0002   /* All keys of a UNIQUE index used */
127988  
127989  /*
127990  ** The WHERE clause processing routine has two halves.  The
127991  ** first part does the start of the WHERE loop and the second
127992  ** half does the tail of the WHERE loop.  An instance of
127993  ** this structure is returned by the first half and passed
127994  ** into the second half to give some continuity.
127995  **
127996  ** An instance of this object holds the complete state of the query
127997  ** planner.
127998  */
127999  struct WhereInfo {
128000    Parse *pParse;            /* Parsing and code generating context */
128001    SrcList *pTabList;        /* List of tables in the join */
128002    ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
128003    ExprList *pResultSet;     /* Result set of the query */
128004    Expr *pWhere;             /* The complete WHERE clause */
128005    LogEst iLimit;            /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
128006    int aiCurOnePass[2];      /* OP_OpenWrite cursors for the ONEPASS opt */
128007    int iContinue;            /* Jump here to continue with next record */
128008    int iBreak;               /* Jump here to break out of the loop */
128009    int savedNQueryLoop;      /* pParse->nQueryLoop outside the WHERE loop */
128010    u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
128011    u8 nLevel;                /* Number of nested loop */
128012    i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */
128013    u8 sorted;                /* True if really sorted (not just grouped) */
128014    u8 eOnePass;              /* ONEPASS_OFF, or _SINGLE, or _MULTI */
128015    u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
128016    u8 eDistinct;             /* One of the WHERE_DISTINCT_* values */
128017    u8 bOrderedInnerLoop;     /* True if only the inner-most loop is ordered */
128018    int iTop;                 /* The very beginning of the WHERE loop */
128019    WhereLoop *pLoops;        /* List of all WhereLoop objects */
128020    Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
128021    LogEst nRowOut;           /* Estimated number of output rows */
128022    WhereClause sWC;          /* Decomposition of the WHERE clause */
128023    WhereMaskSet sMaskSet;    /* Map cursor numbers to bitmasks */
128024    WhereLevel a[1];          /* Information about each nest loop in WHERE */
128025  };
128026  
128027  /*
128028  ** Private interfaces - callable only by other where.c routines.
128029  **
128030  ** where.c:
128031  */
128032  SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
128033  #ifdef WHERETRACE_ENABLED
128034  SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
128035  #endif
128036  SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
128037    WhereClause *pWC,     /* The WHERE clause to be searched */
128038    int iCur,             /* Cursor number of LHS */
128039    int iColumn,          /* Column number of LHS */
128040    Bitmask notReady,     /* RHS must not overlap with this mask */
128041    u32 op,               /* Mask of WO_xx values describing operator */
128042    Index *pIdx           /* Must be compatible with this index, if not NULL */
128043  );
128044  
128045  /* wherecode.c: */
128046  #ifndef SQLITE_OMIT_EXPLAIN
128047  SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
128048    Parse *pParse,                  /* Parse context */
128049    SrcList *pTabList,              /* Table list this loop refers to */
128050    WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
128051    int iLevel,                     /* Value for "level" column of output */
128052    int iFrom,                      /* Value for "from" column of output */
128053    u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
128054  );
128055  #else
128056  # define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
128057  #endif /* SQLITE_OMIT_EXPLAIN */
128058  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
128059  SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
128060    Vdbe *v,                        /* Vdbe to add scanstatus entry to */
128061    SrcList *pSrclist,              /* FROM clause pLvl reads data from */
128062    WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
128063    int addrExplain                 /* Address of OP_Explain (or 0) */
128064  );
128065  #else
128066  # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
128067  #endif
128068  SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
128069    WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
128070    int iLevel,          /* Which level of pWInfo->a[] should be coded */
128071    Bitmask notReady     /* Which tables are currently available */
128072  );
128073  
128074  /* whereexpr.c: */
128075  SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
128076  SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
128077  SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
128078  SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
128079  SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
128080  SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
128081  SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
128082  
128083  
128084  
128085  
128086  
128087  /*
128088  ** Bitmasks for the operators on WhereTerm objects.  These are all
128089  ** operators that are of interest to the query planner.  An
128090  ** OR-ed combination of these values can be used when searching for
128091  ** particular WhereTerms within a WhereClause.
128092  **
128093  ** Value constraints:
128094  **     WO_EQ    == SQLITE_INDEX_CONSTRAINT_EQ
128095  **     WO_LT    == SQLITE_INDEX_CONSTRAINT_LT
128096  **     WO_LE    == SQLITE_INDEX_CONSTRAINT_LE
128097  **     WO_GT    == SQLITE_INDEX_CONSTRAINT_GT
128098  **     WO_GE    == SQLITE_INDEX_CONSTRAINT_GE
128099  */
128100  #define WO_IN     0x0001
128101  #define WO_EQ     0x0002
128102  #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
128103  #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
128104  #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
128105  #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
128106  #define WO_AUX    0x0040       /* Op useful to virtual tables only */
128107  #define WO_IS     0x0080
128108  #define WO_ISNULL 0x0100
128109  #define WO_OR     0x0200       /* Two or more OR-connected terms */
128110  #define WO_AND    0x0400       /* Two or more AND-connected terms */
128111  #define WO_EQUIV  0x0800       /* Of the form A==B, both columns */
128112  #define WO_NOOP   0x1000       /* This term does not restrict search space */
128113  
128114  #define WO_ALL    0x1fff       /* Mask of all possible WO_* values */
128115  #define WO_SINGLE 0x01ff       /* Mask of all non-compound WO_* values */
128116  
128117  /*
128118  ** These are definitions of bits in the WhereLoop.wsFlags field.
128119  ** The particular combination of bits in each WhereLoop help to
128120  ** determine the algorithm that WhereLoop represents.
128121  */
128122  #define WHERE_COLUMN_EQ    0x00000001  /* x=EXPR */
128123  #define WHERE_COLUMN_RANGE 0x00000002  /* x<EXPR and/or x>EXPR */
128124  #define WHERE_COLUMN_IN    0x00000004  /* x IN (...) */
128125  #define WHERE_COLUMN_NULL  0x00000008  /* x IS NULL */
128126  #define WHERE_CONSTRAINT   0x0000000f  /* Any of the WHERE_COLUMN_xxx values */
128127  #define WHERE_TOP_LIMIT    0x00000010  /* x<EXPR or x<=EXPR constraint */
128128  #define WHERE_BTM_LIMIT    0x00000020  /* x>EXPR or x>=EXPR constraint */
128129  #define WHERE_BOTH_LIMIT   0x00000030  /* Both x>EXPR and x<EXPR */
128130  #define WHERE_IDX_ONLY     0x00000040  /* Use index only - omit table */
128131  #define WHERE_IPK          0x00000100  /* x is the INTEGER PRIMARY KEY */
128132  #define WHERE_INDEXED      0x00000200  /* WhereLoop.u.btree.pIndex is valid */
128133  #define WHERE_VIRTUALTABLE 0x00000400  /* WhereLoop.u.vtab is valid */
128134  #define WHERE_IN_ABLE      0x00000800  /* Able to support an IN operator */
128135  #define WHERE_ONEROW       0x00001000  /* Selects no more than one row */
128136  #define WHERE_MULTI_OR     0x00002000  /* OR using multiple indices */
128137  #define WHERE_AUTO_INDEX   0x00004000  /* Uses an ephemeral index */
128138  #define WHERE_SKIPSCAN     0x00008000  /* Uses the skip-scan algorithm */
128139  #define WHERE_UNQ_WANTED   0x00010000  /* WHERE_ONEROW would have been helpful*/
128140  #define WHERE_PARTIALIDX   0x00020000  /* The automatic index is partial */
128141  
128142  /************** End of whereInt.h ********************************************/
128143  /************** Continuing where we left off in wherecode.c ******************/
128144  
128145  #ifndef SQLITE_OMIT_EXPLAIN
128146  
128147  /*
128148  ** Return the name of the i-th column of the pIdx index.
128149  */
128150  static const char *explainIndexColumnName(Index *pIdx, int i){
128151    i = pIdx->aiColumn[i];
128152    if( i==XN_EXPR ) return "<expr>";
128153    if( i==XN_ROWID ) return "rowid";
128154    return pIdx->pTable->aCol[i].zName;
128155  }
128156  
128157  /*
128158  ** This routine is a helper for explainIndexRange() below
128159  **
128160  ** pStr holds the text of an expression that we are building up one term
128161  ** at a time.  This routine adds a new term to the end of the expression.
128162  ** Terms are separated by AND so add the "AND" text for second and subsequent
128163  ** terms only.
128164  */
128165  static void explainAppendTerm(
128166    StrAccum *pStr,             /* The text expression being built */
128167    Index *pIdx,                /* Index to read column names from */
128168    int nTerm,                  /* Number of terms */
128169    int iTerm,                  /* Zero-based index of first term. */
128170    int bAnd,                   /* Non-zero to append " AND " */
128171    const char *zOp             /* Name of the operator */
128172  ){
128173    int i;
128174  
128175    assert( nTerm>=1 );
128176    if( bAnd ) sqlite3StrAccumAppend(pStr, " AND ", 5);
128177  
128178    if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
128179    for(i=0; i<nTerm; i++){
128180      if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
128181      sqlite3StrAccumAppendAll(pStr, explainIndexColumnName(pIdx, iTerm+i));
128182    }
128183    if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
128184  
128185    sqlite3StrAccumAppend(pStr, zOp, 1);
128186  
128187    if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
128188    for(i=0; i<nTerm; i++){
128189      if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
128190      sqlite3StrAccumAppend(pStr, "?", 1);
128191    }
128192    if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
128193  }
128194  
128195  /*
128196  ** Argument pLevel describes a strategy for scanning table pTab. This 
128197  ** function appends text to pStr that describes the subset of table
128198  ** rows scanned by the strategy in the form of an SQL expression.
128199  **
128200  ** For example, if the query:
128201  **
128202  **   SELECT * FROM t1 WHERE a=1 AND b>2;
128203  **
128204  ** is run and there is an index on (a, b), then this function returns a
128205  ** string similar to:
128206  **
128207  **   "a=? AND b>?"
128208  */
128209  static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
128210    Index *pIndex = pLoop->u.btree.pIndex;
128211    u16 nEq = pLoop->u.btree.nEq;
128212    u16 nSkip = pLoop->nSkip;
128213    int i, j;
128214  
128215    if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
128216    sqlite3StrAccumAppend(pStr, " (", 2);
128217    for(i=0; i<nEq; i++){
128218      const char *z = explainIndexColumnName(pIndex, i);
128219      if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
128220      sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
128221    }
128222  
128223    j = i;
128224    if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
128225      explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
128226      i = 1;
128227    }
128228    if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
128229      explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
128230    }
128231    sqlite3StrAccumAppend(pStr, ")", 1);
128232  }
128233  
128234  /*
128235  ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
128236  ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
128237  ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode 
128238  ** is added to the output to describe the table scan strategy in pLevel.
128239  **
128240  ** If an OP_Explain opcode is added to the VM, its address is returned.
128241  ** Otherwise, if no OP_Explain is coded, zero is returned.
128242  */
128243  SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
128244    Parse *pParse,                  /* Parse context */
128245    SrcList *pTabList,              /* Table list this loop refers to */
128246    WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
128247    int iLevel,                     /* Value for "level" column of output */
128248    int iFrom,                      /* Value for "from" column of output */
128249    u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
128250  ){
128251    int ret = 0;
128252  #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
128253    if( pParse->explain==2 )
128254  #endif
128255    {
128256      struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
128257      Vdbe *v = pParse->pVdbe;      /* VM being constructed */
128258      sqlite3 *db = pParse->db;     /* Database handle */
128259      int iId = pParse->iSelectId;  /* Select id (left-most output column) */
128260      int isSearch;                 /* True for a SEARCH. False for SCAN. */
128261      WhereLoop *pLoop;             /* The controlling WhereLoop object */
128262      u32 flags;                    /* Flags that describe this loop */
128263      char *zMsg;                   /* Text to add to EQP output */
128264      StrAccum str;                 /* EQP output string */
128265      char zBuf[100];               /* Initial space for EQP output string */
128266  
128267      pLoop = pLevel->pWLoop;
128268      flags = pLoop->wsFlags;
128269      if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
128270  
128271      isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
128272              || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
128273              || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
128274  
128275      sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
128276      sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
128277      if( pItem->pSelect ){
128278        sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId);
128279      }else{
128280        sqlite3XPrintf(&str, " TABLE %s", pItem->zName);
128281      }
128282  
128283      if( pItem->zAlias ){
128284        sqlite3XPrintf(&str, " AS %s", pItem->zAlias);
128285      }
128286      if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
128287        const char *zFmt = 0;
128288        Index *pIdx;
128289  
128290        assert( pLoop->u.btree.pIndex!=0 );
128291        pIdx = pLoop->u.btree.pIndex;
128292        assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
128293        if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
128294          if( isSearch ){
128295            zFmt = "PRIMARY KEY";
128296          }
128297        }else if( flags & WHERE_PARTIALIDX ){
128298          zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
128299        }else if( flags & WHERE_AUTO_INDEX ){
128300          zFmt = "AUTOMATIC COVERING INDEX";
128301        }else if( flags & WHERE_IDX_ONLY ){
128302          zFmt = "COVERING INDEX %s";
128303        }else{
128304          zFmt = "INDEX %s";
128305        }
128306        if( zFmt ){
128307          sqlite3StrAccumAppend(&str, " USING ", 7);
128308          sqlite3XPrintf(&str, zFmt, pIdx->zName);
128309          explainIndexRange(&str, pLoop);
128310        }
128311      }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
128312        const char *zRangeOp;
128313        if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
128314          zRangeOp = "=";
128315        }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
128316          zRangeOp = ">? AND rowid<";
128317        }else if( flags&WHERE_BTM_LIMIT ){
128318          zRangeOp = ">";
128319        }else{
128320          assert( flags&WHERE_TOP_LIMIT);
128321          zRangeOp = "<";
128322        }
128323        sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
128324      }
128325  #ifndef SQLITE_OMIT_VIRTUALTABLE
128326      else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
128327        sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s",
128328                    pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
128329      }
128330  #endif
128331  #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
128332      if( pLoop->nOut>=10 ){
128333        sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
128334      }else{
128335        sqlite3StrAccumAppend(&str, " (~1 row)", 9);
128336      }
128337  #endif
128338      zMsg = sqlite3StrAccumFinish(&str);
128339      ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
128340    }
128341    return ret;
128342  }
128343  #endif /* SQLITE_OMIT_EXPLAIN */
128344  
128345  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
128346  /*
128347  ** Configure the VM passed as the first argument with an
128348  ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to 
128349  ** implement level pLvl. Argument pSrclist is a pointer to the FROM 
128350  ** clause that the scan reads data from.
128351  **
128352  ** If argument addrExplain is not 0, it must be the address of an 
128353  ** OP_Explain instruction that describes the same loop.
128354  */
128355  SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
128356    Vdbe *v,                        /* Vdbe to add scanstatus entry to */
128357    SrcList *pSrclist,              /* FROM clause pLvl reads data from */
128358    WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
128359    int addrExplain                 /* Address of OP_Explain (or 0) */
128360  ){
128361    const char *zObj = 0;
128362    WhereLoop *pLoop = pLvl->pWLoop;
128363    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0  &&  pLoop->u.btree.pIndex!=0 ){
128364      zObj = pLoop->u.btree.pIndex->zName;
128365    }else{
128366      zObj = pSrclist->a[pLvl->iFrom].zName;
128367    }
128368    sqlite3VdbeScanStatus(
128369        v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
128370    );
128371  }
128372  #endif
128373  
128374  
128375  /*
128376  ** Disable a term in the WHERE clause.  Except, do not disable the term
128377  ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
128378  ** or USING clause of that join.
128379  **
128380  ** Consider the term t2.z='ok' in the following queries:
128381  **
128382  **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
128383  **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
128384  **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
128385  **
128386  ** The t2.z='ok' is disabled in the in (2) because it originates
128387  ** in the ON clause.  The term is disabled in (3) because it is not part
128388  ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
128389  **
128390  ** Disabling a term causes that term to not be tested in the inner loop
128391  ** of the join.  Disabling is an optimization.  When terms are satisfied
128392  ** by indices, we disable them to prevent redundant tests in the inner
128393  ** loop.  We would get the correct results if nothing were ever disabled,
128394  ** but joins might run a little slower.  The trick is to disable as much
128395  ** as we can without disabling too much.  If we disabled in (1), we'd get
128396  ** the wrong answer.  See ticket #813.
128397  **
128398  ** If all the children of a term are disabled, then that term is also
128399  ** automatically disabled.  In this way, terms get disabled if derived
128400  ** virtual terms are tested first.  For example:
128401  **
128402  **      x GLOB 'abc*' AND x>='abc' AND x<'acd'
128403  **      \___________/     \______/     \_____/
128404  **         parent          child1       child2
128405  **
128406  ** Only the parent term was in the original WHERE clause.  The child1
128407  ** and child2 terms were added by the LIKE optimization.  If both of
128408  ** the virtual child terms are valid, then testing of the parent can be 
128409  ** skipped.
128410  **
128411  ** Usually the parent term is marked as TERM_CODED.  But if the parent
128412  ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
128413  ** The TERM_LIKECOND marking indicates that the term should be coded inside
128414  ** a conditional such that is only evaluated on the second pass of a
128415  ** LIKE-optimization loop, when scanning BLOBs instead of strings.
128416  */
128417  static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
128418    int nLoop = 0;
128419    while( ALWAYS(pTerm!=0)
128420        && (pTerm->wtFlags & TERM_CODED)==0
128421        && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
128422        && (pLevel->notReady & pTerm->prereqAll)==0
128423    ){
128424      if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
128425        pTerm->wtFlags |= TERM_LIKECOND;
128426      }else{
128427        pTerm->wtFlags |= TERM_CODED;
128428      }
128429      if( pTerm->iParent<0 ) break;
128430      pTerm = &pTerm->pWC->a[pTerm->iParent];
128431      pTerm->nChild--;
128432      if( pTerm->nChild!=0 ) break;
128433      nLoop++;
128434    }
128435  }
128436  
128437  /*
128438  ** Code an OP_Affinity opcode to apply the column affinity string zAff
128439  ** to the n registers starting at base. 
128440  **
128441  ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
128442  ** beginning and end of zAff are ignored.  If all entries in zAff are
128443  ** SQLITE_AFF_BLOB, then no code gets generated.
128444  **
128445  ** This routine makes its own copy of zAff so that the caller is free
128446  ** to modify zAff after this routine returns.
128447  */
128448  static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
128449    Vdbe *v = pParse->pVdbe;
128450    if( zAff==0 ){
128451      assert( pParse->db->mallocFailed );
128452      return;
128453    }
128454    assert( v!=0 );
128455  
128456    /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
128457    ** and end of the affinity string.
128458    */
128459    while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
128460      n--;
128461      base++;
128462      zAff++;
128463    }
128464    while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
128465      n--;
128466    }
128467  
128468    /* Code the OP_Affinity opcode if there is anything left to do. */
128469    if( n>0 ){
128470      sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
128471      sqlite3ExprCacheAffinityChange(pParse, base, n);
128472    }
128473  }
128474  
128475  /*
128476  ** Expression pRight, which is the RHS of a comparison operation, is 
128477  ** either a vector of n elements or, if n==1, a scalar expression.
128478  ** Before the comparison operation, affinity zAff is to be applied
128479  ** to the pRight values. This function modifies characters within the
128480  ** affinity string to SQLITE_AFF_BLOB if either:
128481  **
128482  **   * the comparison will be performed with no affinity, or
128483  **   * the affinity change in zAff is guaranteed not to change the value.
128484  */
128485  static void updateRangeAffinityStr(
128486    Expr *pRight,                   /* RHS of comparison */
128487    int n,                          /* Number of vector elements in comparison */
128488    char *zAff                      /* Affinity string to modify */
128489  ){
128490    int i;
128491    for(i=0; i<n; i++){
128492      Expr *p = sqlite3VectorFieldSubexpr(pRight, i);
128493      if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB
128494       || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
128495      ){
128496        zAff[i] = SQLITE_AFF_BLOB;
128497      }
128498    }
128499  }
128500  
128501  /*
128502  ** Generate code for a single equality term of the WHERE clause.  An equality
128503  ** term can be either X=expr or X IN (...).   pTerm is the term to be 
128504  ** coded.
128505  **
128506  ** The current value for the constraint is left in a register, the index
128507  ** of which is returned.  An attempt is made store the result in iTarget but
128508  ** this is only guaranteed for TK_ISNULL and TK_IN constraints.  If the
128509  ** constraint is a TK_EQ or TK_IS, then the current value might be left in
128510  ** some other register and it is the caller's responsibility to compensate.
128511  **
128512  ** For a constraint of the form X=expr, the expression is evaluated in
128513  ** straight-line code.  For constraints of the form X IN (...)
128514  ** this routine sets up a loop that will iterate over all values of X.
128515  */
128516  static int codeEqualityTerm(
128517    Parse *pParse,      /* The parsing context */
128518    WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
128519    WhereLevel *pLevel, /* The level of the FROM clause we are working on */
128520    int iEq,            /* Index of the equality term within this level */
128521    int bRev,           /* True for reverse-order IN operations */
128522    int iTarget         /* Attempt to leave results in this register */
128523  ){
128524    Expr *pX = pTerm->pExpr;
128525    Vdbe *v = pParse->pVdbe;
128526    int iReg;                  /* Register holding results */
128527  
128528    assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
128529    assert( iTarget>0 );
128530    if( pX->op==TK_EQ || pX->op==TK_IS ){
128531      iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
128532    }else if( pX->op==TK_ISNULL ){
128533      iReg = iTarget;
128534      sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
128535  #ifndef SQLITE_OMIT_SUBQUERY
128536    }else{
128537      int eType = IN_INDEX_NOOP;
128538      int iTab;
128539      struct InLoop *pIn;
128540      WhereLoop *pLoop = pLevel->pWLoop;
128541      int i;
128542      int nEq = 0;
128543      int *aiMap = 0;
128544  
128545      if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
128546        && pLoop->u.btree.pIndex!=0
128547        && pLoop->u.btree.pIndex->aSortOrder[iEq]
128548      ){
128549        testcase( iEq==0 );
128550        testcase( bRev );
128551        bRev = !bRev;
128552      }
128553      assert( pX->op==TK_IN );
128554      iReg = iTarget;
128555  
128556      for(i=0; i<iEq; i++){
128557        if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
128558          disableTerm(pLevel, pTerm);
128559          return iTarget;
128560        }
128561      }
128562      for(i=iEq;i<pLoop->nLTerm; i++){
128563        if( ALWAYS(pLoop->aLTerm[i]) && pLoop->aLTerm[i]->pExpr==pX ) nEq++;
128564      }
128565  
128566      if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){
128567        eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0);
128568      }else{
128569        Select *pSelect = pX->x.pSelect;
128570        sqlite3 *db = pParse->db;
128571        u16 savedDbOptFlags = db->dbOptFlags;
128572        ExprList *pOrigRhs = pSelect->pEList;
128573        ExprList *pOrigLhs = pX->pLeft->x.pList;
128574        ExprList *pRhs = 0;         /* New Select.pEList for RHS */
128575        ExprList *pLhs = 0;         /* New pX->pLeft vector */
128576  
128577        for(i=iEq;i<pLoop->nLTerm; i++){
128578          if( pLoop->aLTerm[i]->pExpr==pX ){
128579            int iField = pLoop->aLTerm[i]->iField - 1;
128580            Expr *pNewRhs = sqlite3ExprDup(db, pOrigRhs->a[iField].pExpr, 0);
128581            Expr *pNewLhs = sqlite3ExprDup(db, pOrigLhs->a[iField].pExpr, 0);
128582  
128583            pRhs = sqlite3ExprListAppend(pParse, pRhs, pNewRhs);
128584            pLhs = sqlite3ExprListAppend(pParse, pLhs, pNewLhs);
128585          }
128586        }
128587        if( !db->mallocFailed ){
128588          Expr *pLeft = pX->pLeft;
128589  
128590          if( pSelect->pOrderBy ){
128591            /* If the SELECT statement has an ORDER BY clause, zero the 
128592            ** iOrderByCol variables. These are set to non-zero when an 
128593            ** ORDER BY term exactly matches one of the terms of the 
128594            ** result-set. Since the result-set of the SELECT statement may
128595            ** have been modified or reordered, these variables are no longer 
128596            ** set correctly.  Since setting them is just an optimization, 
128597            ** it's easiest just to zero them here.  */
128598            ExprList *pOrderBy = pSelect->pOrderBy;
128599            for(i=0; i<pOrderBy->nExpr; i++){
128600              pOrderBy->a[i].u.x.iOrderByCol = 0;
128601            }
128602          }
128603  
128604          /* Take care here not to generate a TK_VECTOR containing only a
128605          ** single value. Since the parser never creates such a vector, some
128606          ** of the subroutines do not handle this case.  */
128607          if( pLhs->nExpr==1 ){
128608            pX->pLeft = pLhs->a[0].pExpr;
128609          }else{
128610            pLeft->x.pList = pLhs;
128611            aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int) * nEq);
128612            testcase( aiMap==0 );
128613          }
128614          pSelect->pEList = pRhs;
128615          db->dbOptFlags |= SQLITE_QueryFlattener;
128616          eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap);
128617          db->dbOptFlags = savedDbOptFlags;
128618          testcase( aiMap!=0 && aiMap[0]!=0 );
128619          pSelect->pEList = pOrigRhs;
128620          pLeft->x.pList = pOrigLhs;
128621          pX->pLeft = pLeft;
128622        }
128623        sqlite3ExprListDelete(pParse->db, pLhs);
128624        sqlite3ExprListDelete(pParse->db, pRhs);
128625      }
128626  
128627      if( eType==IN_INDEX_INDEX_DESC ){
128628        testcase( bRev );
128629        bRev = !bRev;
128630      }
128631      iTab = pX->iTable;
128632      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
128633      VdbeCoverageIf(v, bRev);
128634      VdbeCoverageIf(v, !bRev);
128635      assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
128636  
128637      pLoop->wsFlags |= WHERE_IN_ABLE;
128638      if( pLevel->u.in.nIn==0 ){
128639        pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
128640      }
128641  
128642      i = pLevel->u.in.nIn;
128643      pLevel->u.in.nIn += nEq;
128644      pLevel->u.in.aInLoop =
128645         sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
128646                                sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
128647      pIn = pLevel->u.in.aInLoop;
128648      if( pIn ){
128649        int iMap = 0;               /* Index in aiMap[] */
128650        pIn += i;
128651        for(i=iEq;i<pLoop->nLTerm; i++){
128652          if( pLoop->aLTerm[i]->pExpr==pX ){
128653            int iOut = iReg + i - iEq;
128654            if( eType==IN_INDEX_ROWID ){
128655              testcase( nEq>1 );  /* Happens with a UNIQUE index on ROWID */
128656              pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
128657            }else{
128658              int iCol = aiMap ? aiMap[iMap++] : 0;
128659              pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
128660            }
128661            sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
128662            if( i==iEq ){
128663              pIn->iCur = iTab;
128664              pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
128665            }else{
128666              pIn->eEndLoopOp = OP_Noop;
128667            }
128668            pIn++;
128669          }
128670        }
128671      }else{
128672        pLevel->u.in.nIn = 0;
128673      }
128674      sqlite3DbFree(pParse->db, aiMap);
128675  #endif
128676    }
128677    disableTerm(pLevel, pTerm);
128678    return iReg;
128679  }
128680  
128681  /*
128682  ** Generate code that will evaluate all == and IN constraints for an
128683  ** index scan.
128684  **
128685  ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
128686  ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
128687  ** The index has as many as three equality constraints, but in this
128688  ** example, the third "c" value is an inequality.  So only two 
128689  ** constraints are coded.  This routine will generate code to evaluate
128690  ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
128691  ** in consecutive registers and the index of the first register is returned.
128692  **
128693  ** In the example above nEq==2.  But this subroutine works for any value
128694  ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
128695  ** The only thing it does is allocate the pLevel->iMem memory cell and
128696  ** compute the affinity string.
128697  **
128698  ** The nExtraReg parameter is 0 or 1.  It is 0 if all WHERE clause constraints
128699  ** are == or IN and are covered by the nEq.  nExtraReg is 1 if there is
128700  ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
128701  ** occurs after the nEq quality constraints.
128702  **
128703  ** This routine allocates a range of nEq+nExtraReg memory cells and returns
128704  ** the index of the first memory cell in that range. The code that
128705  ** calls this routine will use that memory range to store keys for
128706  ** start and termination conditions of the loop.
128707  ** key value of the loop.  If one or more IN operators appear, then
128708  ** this routine allocates an additional nEq memory cells for internal
128709  ** use.
128710  **
128711  ** Before returning, *pzAff is set to point to a buffer containing a
128712  ** copy of the column affinity string of the index allocated using
128713  ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
128714  ** with equality constraints that use BLOB or NONE affinity are set to
128715  ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
128716  **
128717  **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
128718  **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
128719  **
128720  ** In the example above, the index on t1(a) has TEXT affinity. But since
128721  ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
128722  ** no conversion should be attempted before using a t2.b value as part of
128723  ** a key to search the index. Hence the first byte in the returned affinity
128724  ** string in this example would be set to SQLITE_AFF_BLOB.
128725  */
128726  static int codeAllEqualityTerms(
128727    Parse *pParse,        /* Parsing context */
128728    WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
128729    int bRev,             /* Reverse the order of IN operators */
128730    int nExtraReg,        /* Number of extra registers to allocate */
128731    char **pzAff          /* OUT: Set to point to affinity string */
128732  ){
128733    u16 nEq;                      /* The number of == or IN constraints to code */
128734    u16 nSkip;                    /* Number of left-most columns to skip */
128735    Vdbe *v = pParse->pVdbe;      /* The vm under construction */
128736    Index *pIdx;                  /* The index being used for this loop */
128737    WhereTerm *pTerm;             /* A single constraint term */
128738    WhereLoop *pLoop;             /* The WhereLoop object */
128739    int j;                        /* Loop counter */
128740    int regBase;                  /* Base register */
128741    int nReg;                     /* Number of registers to allocate */
128742    char *zAff;                   /* Affinity string to return */
128743  
128744    /* This module is only called on query plans that use an index. */
128745    pLoop = pLevel->pWLoop;
128746    assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
128747    nEq = pLoop->u.btree.nEq;
128748    nSkip = pLoop->nSkip;
128749    pIdx = pLoop->u.btree.pIndex;
128750    assert( pIdx!=0 );
128751  
128752    /* Figure out how many memory cells we will need then allocate them.
128753    */
128754    regBase = pParse->nMem + 1;
128755    nReg = pLoop->u.btree.nEq + nExtraReg;
128756    pParse->nMem += nReg;
128757  
128758    zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
128759    assert( zAff!=0 || pParse->db->mallocFailed );
128760  
128761    if( nSkip ){
128762      int iIdxCur = pLevel->iIdxCur;
128763      sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
128764      VdbeCoverageIf(v, bRev==0);
128765      VdbeCoverageIf(v, bRev!=0);
128766      VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
128767      j = sqlite3VdbeAddOp0(v, OP_Goto);
128768      pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
128769                              iIdxCur, 0, regBase, nSkip);
128770      VdbeCoverageIf(v, bRev==0);
128771      VdbeCoverageIf(v, bRev!=0);
128772      sqlite3VdbeJumpHere(v, j);
128773      for(j=0; j<nSkip; j++){
128774        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
128775        testcase( pIdx->aiColumn[j]==XN_EXPR );
128776        VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
128777      }
128778    }    
128779  
128780    /* Evaluate the equality constraints
128781    */
128782    assert( zAff==0 || (int)strlen(zAff)>=nEq );
128783    for(j=nSkip; j<nEq; j++){
128784      int r1;
128785      pTerm = pLoop->aLTerm[j];
128786      assert( pTerm!=0 );
128787      /* The following testcase is true for indices with redundant columns. 
128788      ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
128789      testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
128790      testcase( pTerm->wtFlags & TERM_VIRTUAL );
128791      r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
128792      if( r1!=regBase+j ){
128793        if( nReg==1 ){
128794          sqlite3ReleaseTempReg(pParse, regBase);
128795          regBase = r1;
128796        }else{
128797          sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
128798        }
128799      }
128800      if( pTerm->eOperator & WO_IN ){
128801        if( pTerm->pExpr->flags & EP_xIsSelect ){
128802          /* No affinity ever needs to be (or should be) applied to a value
128803          ** from the RHS of an "? IN (SELECT ...)" expression. The 
128804          ** sqlite3FindInIndex() routine has already ensured that the 
128805          ** affinity of the comparison has been applied to the value.  */
128806          if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
128807        }
128808      }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
128809        Expr *pRight = pTerm->pExpr->pRight;
128810        if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
128811          sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
128812          VdbeCoverage(v);
128813        }
128814        if( zAff ){
128815          if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
128816            zAff[j] = SQLITE_AFF_BLOB;
128817          }
128818          if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
128819            zAff[j] = SQLITE_AFF_BLOB;
128820          }
128821        }
128822      }
128823    }
128824    *pzAff = zAff;
128825    return regBase;
128826  }
128827  
128828  #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
128829  /*
128830  ** If the most recently coded instruction is a constant range constraint
128831  ** (a string literal) that originated from the LIKE optimization, then 
128832  ** set P3 and P5 on the OP_String opcode so that the string will be cast
128833  ** to a BLOB at appropriate times.
128834  **
128835  ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
128836  ** expression: "x>='ABC' AND x<'abd'".  But this requires that the range
128837  ** scan loop run twice, once for strings and a second time for BLOBs.
128838  ** The OP_String opcodes on the second pass convert the upper and lower
128839  ** bound string constants to blobs.  This routine makes the necessary changes
128840  ** to the OP_String opcodes for that to happen.
128841  **
128842  ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
128843  ** only the one pass through the string space is required, so this routine
128844  ** becomes a no-op.
128845  */
128846  static void whereLikeOptimizationStringFixup(
128847    Vdbe *v,                /* prepared statement under construction */
128848    WhereLevel *pLevel,     /* The loop that contains the LIKE operator */
128849    WhereTerm *pTerm        /* The upper or lower bound just coded */
128850  ){
128851    if( pTerm->wtFlags & TERM_LIKEOPT ){
128852      VdbeOp *pOp;
128853      assert( pLevel->iLikeRepCntr>0 );
128854      pOp = sqlite3VdbeGetOp(v, -1);
128855      assert( pOp!=0 );
128856      assert( pOp->opcode==OP_String8 
128857              || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
128858      pOp->p3 = (int)(pLevel->iLikeRepCntr>>1);  /* Register holding counter */
128859      pOp->p5 = (u8)(pLevel->iLikeRepCntr&1);    /* ASC or DESC */
128860    }
128861  }
128862  #else
128863  # define whereLikeOptimizationStringFixup(A,B,C)
128864  #endif
128865  
128866  #ifdef SQLITE_ENABLE_CURSOR_HINTS
128867  /*
128868  ** Information is passed from codeCursorHint() down to individual nodes of
128869  ** the expression tree (by sqlite3WalkExpr()) using an instance of this
128870  ** structure.
128871  */
128872  struct CCurHint {
128873    int iTabCur;    /* Cursor for the main table */
128874    int iIdxCur;    /* Cursor for the index, if pIdx!=0.  Unused otherwise */
128875    Index *pIdx;    /* The index used to access the table */
128876  };
128877  
128878  /*
128879  ** This function is called for every node of an expression that is a candidate
128880  ** for a cursor hint on an index cursor.  For TK_COLUMN nodes that reference
128881  ** the table CCurHint.iTabCur, verify that the same column can be
128882  ** accessed through the index.  If it cannot, then set pWalker->eCode to 1.
128883  */
128884  static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
128885    struct CCurHint *pHint = pWalker->u.pCCurHint;
128886    assert( pHint->pIdx!=0 );
128887    if( pExpr->op==TK_COLUMN
128888     && pExpr->iTable==pHint->iTabCur
128889     && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
128890    ){
128891      pWalker->eCode = 1;
128892    }
128893    return WRC_Continue;
128894  }
128895  
128896  /*
128897  ** Test whether or not expression pExpr, which was part of a WHERE clause,
128898  ** should be included in the cursor-hint for a table that is on the rhs
128899  ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the 
128900  ** expression is not suitable.
128901  **
128902  ** An expression is unsuitable if it might evaluate to non NULL even if
128903  ** a TK_COLUMN node that does affect the value of the expression is set
128904  ** to NULL. For example:
128905  **
128906  **   col IS NULL
128907  **   col IS NOT NULL
128908  **   coalesce(col, 1)
128909  **   CASE WHEN col THEN 0 ELSE 1 END
128910  */
128911  static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
128912    if( pExpr->op==TK_IS 
128913     || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT 
128914     || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE 
128915    ){
128916      pWalker->eCode = 1;
128917    }else if( pExpr->op==TK_FUNCTION ){
128918      int d1;
128919      char d2[4];
128920      if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
128921        pWalker->eCode = 1;
128922      }
128923    }
128924  
128925    return WRC_Continue;
128926  }
128927  
128928  
128929  /*
128930  ** This function is called on every node of an expression tree used as an
128931  ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
128932  ** that accesses any table other than the one identified by
128933  ** CCurHint.iTabCur, then do the following:
128934  **
128935  **   1) allocate a register and code an OP_Column instruction to read 
128936  **      the specified column into the new register, and
128937  **
128938  **   2) transform the expression node to a TK_REGISTER node that reads 
128939  **      from the newly populated register.
128940  **
128941  ** Also, if the node is a TK_COLUMN that does access the table idenified
128942  ** by pCCurHint.iTabCur, and an index is being used (which we will
128943  ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
128944  ** an access of the index rather than the original table.
128945  */
128946  static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
128947    int rc = WRC_Continue;
128948    struct CCurHint *pHint = pWalker->u.pCCurHint;
128949    if( pExpr->op==TK_COLUMN ){
128950      if( pExpr->iTable!=pHint->iTabCur ){
128951        Vdbe *v = pWalker->pParse->pVdbe;
128952        int reg = ++pWalker->pParse->nMem;   /* Register for column value */
128953        sqlite3ExprCodeGetColumnOfTable(
128954            v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg
128955        );
128956        pExpr->op = TK_REGISTER;
128957        pExpr->iTable = reg;
128958      }else if( pHint->pIdx!=0 ){
128959        pExpr->iTable = pHint->iIdxCur;
128960        pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
128961        assert( pExpr->iColumn>=0 );
128962      }
128963    }else if( pExpr->op==TK_AGG_FUNCTION ){
128964      /* An aggregate function in the WHERE clause of a query means this must
128965      ** be a correlated sub-query, and expression pExpr is an aggregate from
128966      ** the parent context. Do not walk the function arguments in this case.
128967      **
128968      ** todo: It should be possible to replace this node with a TK_REGISTER
128969      ** expression, as the result of the expression must be stored in a 
128970      ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
128971      rc = WRC_Prune;
128972    }
128973    return rc;
128974  }
128975  
128976  /*
128977  ** Insert an OP_CursorHint instruction if it is appropriate to do so.
128978  */
128979  static void codeCursorHint(
128980    struct SrcList_item *pTabItem,  /* FROM clause item */
128981    WhereInfo *pWInfo,    /* The where clause */
128982    WhereLevel *pLevel,   /* Which loop to provide hints for */
128983    WhereTerm *pEndRange  /* Hint this end-of-scan boundary term if not NULL */
128984  ){
128985    Parse *pParse = pWInfo->pParse;
128986    sqlite3 *db = pParse->db;
128987    Vdbe *v = pParse->pVdbe;
128988    Expr *pExpr = 0;
128989    WhereLoop *pLoop = pLevel->pWLoop;
128990    int iCur;
128991    WhereClause *pWC;
128992    WhereTerm *pTerm;
128993    int i, j;
128994    struct CCurHint sHint;
128995    Walker sWalker;
128996  
128997    if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
128998    iCur = pLevel->iTabCur;
128999    assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
129000    sHint.iTabCur = iCur;
129001    sHint.iIdxCur = pLevel->iIdxCur;
129002    sHint.pIdx = pLoop->u.btree.pIndex;
129003    memset(&sWalker, 0, sizeof(sWalker));
129004    sWalker.pParse = pParse;
129005    sWalker.u.pCCurHint = &sHint;
129006    pWC = &pWInfo->sWC;
129007    for(i=0; i<pWC->nTerm; i++){
129008      pTerm = &pWC->a[i];
129009      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
129010      if( pTerm->prereqAll & pLevel->notReady ) continue;
129011  
129012      /* Any terms specified as part of the ON(...) clause for any LEFT 
129013      ** JOIN for which the current table is not the rhs are omitted
129014      ** from the cursor-hint. 
129015      **
129016      ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms 
129017      ** that were specified as part of the WHERE clause must be excluded.
129018      ** This is to address the following:
129019      **
129020      **   SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
129021      **
129022      ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
129023      ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is 
129024      ** pushed down to the cursor, this row is filtered out, causing
129025      ** SQLite to synthesize a row of NULL values. Which does match the
129026      ** WHERE clause, and so the query returns a row. Which is incorrect.
129027      **
129028      ** For the same reason, WHERE terms such as:
129029      **
129030      **   WHERE 1 = (t2.c IS NULL)
129031      **
129032      ** are also excluded. See codeCursorHintIsOrFunction() for details.
129033      */
129034      if( pTabItem->fg.jointype & JT_LEFT ){
129035        Expr *pExpr = pTerm->pExpr;
129036        if( !ExprHasProperty(pExpr, EP_FromJoin) 
129037         || pExpr->iRightJoinTable!=pTabItem->iCursor
129038        ){
129039          sWalker.eCode = 0;
129040          sWalker.xExprCallback = codeCursorHintIsOrFunction;
129041          sqlite3WalkExpr(&sWalker, pTerm->pExpr);
129042          if( sWalker.eCode ) continue;
129043        }
129044      }else{
129045        if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
129046      }
129047  
129048      /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
129049      ** the cursor.  These terms are not needed as hints for a pure range
129050      ** scan (that has no == terms) so omit them. */
129051      if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
129052        for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
129053        if( j<pLoop->nLTerm ) continue;
129054      }
129055  
129056      /* No subqueries or non-deterministic functions allowed */
129057      if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
129058  
129059      /* For an index scan, make sure referenced columns are actually in
129060      ** the index. */
129061      if( sHint.pIdx!=0 ){
129062        sWalker.eCode = 0;
129063        sWalker.xExprCallback = codeCursorHintCheckExpr;
129064        sqlite3WalkExpr(&sWalker, pTerm->pExpr);
129065        if( sWalker.eCode ) continue;
129066      }
129067  
129068      /* If we survive all prior tests, that means this term is worth hinting */
129069      pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
129070    }
129071    if( pExpr!=0 ){
129072      sWalker.xExprCallback = codeCursorHintFixExpr;
129073      sqlite3WalkExpr(&sWalker, pExpr);
129074      sqlite3VdbeAddOp4(v, OP_CursorHint, 
129075                        (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
129076                        (const char*)pExpr, P4_EXPR);
129077    }
129078  }
129079  #else
129080  # define codeCursorHint(A,B,C,D)  /* No-op */
129081  #endif /* SQLITE_ENABLE_CURSOR_HINTS */
129082  
129083  /*
129084  ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
129085  ** a rowid value just read from cursor iIdxCur, open on index pIdx. This
129086  ** function generates code to do a deferred seek of cursor iCur to the 
129087  ** rowid stored in register iRowid.
129088  **
129089  ** Normally, this is just:
129090  **
129091  **   OP_DeferredSeek $iCur $iRowid
129092  **
129093  ** However, if the scan currently being coded is a branch of an OR-loop and
129094  ** the statement currently being coded is a SELECT, then P3 of OP_DeferredSeek
129095  ** is set to iIdxCur and P4 is set to point to an array of integers
129096  ** containing one entry for each column of the table cursor iCur is open 
129097  ** on. For each table column, if the column is the i'th column of the 
129098  ** index, then the corresponding array entry is set to (i+1). If the column
129099  ** does not appear in the index at all, the array entry is set to 0.
129100  */
129101  static void codeDeferredSeek(
129102    WhereInfo *pWInfo,              /* Where clause context */
129103    Index *pIdx,                    /* Index scan is using */
129104    int iCur,                       /* Cursor for IPK b-tree */
129105    int iIdxCur                     /* Index cursor */
129106  ){
129107    Parse *pParse = pWInfo->pParse; /* Parse context */
129108    Vdbe *v = pParse->pVdbe;        /* Vdbe to generate code within */
129109  
129110    assert( iIdxCur>0 );
129111    assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
129112    
129113    sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur);
129114    if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
129115     && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
129116    ){
129117      int i;
129118      Table *pTab = pIdx->pTable;
129119      int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
129120      if( ai ){
129121        ai[0] = pTab->nCol;
129122        for(i=0; i<pIdx->nColumn-1; i++){
129123          assert( pIdx->aiColumn[i]<pTab->nCol );
129124          if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
129125        }
129126        sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
129127      }
129128    }
129129  }
129130  
129131  /*
129132  ** If the expression passed as the second argument is a vector, generate
129133  ** code to write the first nReg elements of the vector into an array
129134  ** of registers starting with iReg.
129135  **
129136  ** If the expression is not a vector, then nReg must be passed 1. In
129137  ** this case, generate code to evaluate the expression and leave the
129138  ** result in register iReg.
129139  */
129140  static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
129141    assert( nReg>0 );
129142    if( p && sqlite3ExprIsVector(p) ){
129143  #ifndef SQLITE_OMIT_SUBQUERY
129144      if( (p->flags & EP_xIsSelect) ){
129145        Vdbe *v = pParse->pVdbe;
129146        int iSelect = sqlite3CodeSubselect(pParse, p, 0, 0);
129147        sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
129148      }else
129149  #endif
129150      {
129151        int i;
129152        ExprList *pList = p->x.pList;
129153        assert( nReg<=pList->nExpr );
129154        for(i=0; i<nReg; i++){
129155          sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
129156        }
129157      }
129158    }else{
129159      assert( nReg==1 );
129160      sqlite3ExprCode(pParse, p, iReg);
129161    }
129162  }
129163  
129164  /* An instance of the IdxExprTrans object carries information about a
129165  ** mapping from an expression on table columns into a column in an index
129166  ** down through the Walker.
129167  */
129168  typedef struct IdxExprTrans {
129169    Expr *pIdxExpr;    /* The index expression */
129170    int iTabCur;       /* The cursor of the corresponding table */
129171    int iIdxCur;       /* The cursor for the index */
129172    int iIdxCol;       /* The column for the index */
129173  } IdxExprTrans;
129174  
129175  /* The walker node callback used to transform matching expressions into
129176  ** a reference to an index column for an index on an expression.
129177  **
129178  ** If pExpr matches, then transform it into a reference to the index column
129179  ** that contains the value of pExpr.
129180  */
129181  static int whereIndexExprTransNode(Walker *p, Expr *pExpr){
129182    IdxExprTrans *pX = p->u.pIdxTrans;
129183    if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){
129184      pExpr->op = TK_COLUMN;
129185      pExpr->iTable = pX->iIdxCur;
129186      pExpr->iColumn = pX->iIdxCol;
129187      pExpr->pTab = 0;
129188      return WRC_Prune;
129189    }else{
129190      return WRC_Continue;
129191    }
129192  }
129193  
129194  /*
129195  ** For an indexes on expression X, locate every instance of expression X
129196  ** in pExpr and change that subexpression into a reference to the appropriate
129197  ** column of the index.
129198  */
129199  static void whereIndexExprTrans(
129200    Index *pIdx,      /* The Index */
129201    int iTabCur,      /* Cursor of the table that is being indexed */
129202    int iIdxCur,      /* Cursor of the index itself */
129203    WhereInfo *pWInfo /* Transform expressions in this WHERE clause */
129204  ){
129205    int iIdxCol;               /* Column number of the index */
129206    ExprList *aColExpr;        /* Expressions that are indexed */
129207    Walker w;
129208    IdxExprTrans x;
129209    aColExpr = pIdx->aColExpr;
129210    if( aColExpr==0 ) return;  /* Not an index on expressions */
129211    memset(&w, 0, sizeof(w));
129212    w.xExprCallback = whereIndexExprTransNode;
129213    w.u.pIdxTrans = &x;
129214    x.iTabCur = iTabCur;
129215    x.iIdxCur = iIdxCur;
129216    for(iIdxCol=0; iIdxCol<aColExpr->nExpr; iIdxCol++){
129217      if( pIdx->aiColumn[iIdxCol]!=XN_EXPR ) continue;
129218      assert( aColExpr->a[iIdxCol].pExpr!=0 );
129219      x.iIdxCol = iIdxCol;
129220      x.pIdxExpr = aColExpr->a[iIdxCol].pExpr;
129221      sqlite3WalkExpr(&w, pWInfo->pWhere);
129222      sqlite3WalkExprList(&w, pWInfo->pOrderBy);
129223      sqlite3WalkExprList(&w, pWInfo->pResultSet);
129224    }
129225  }
129226  
129227  /*
129228  ** Generate code for the start of the iLevel-th loop in the WHERE clause
129229  ** implementation described by pWInfo.
129230  */
129231  SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
129232    WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
129233    int iLevel,          /* Which level of pWInfo->a[] should be coded */
129234    Bitmask notReady     /* Which tables are currently available */
129235  ){
129236    int j, k;            /* Loop counters */
129237    int iCur;            /* The VDBE cursor for the table */
129238    int addrNxt;         /* Where to jump to continue with the next IN case */
129239    int omitTable;       /* True if we use the index only */
129240    int bRev;            /* True if we need to scan in reverse order */
129241    WhereLevel *pLevel;  /* The where level to be coded */
129242    WhereLoop *pLoop;    /* The WhereLoop object being coded */
129243    WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
129244    WhereTerm *pTerm;               /* A WHERE clause term */
129245    Parse *pParse;                  /* Parsing context */
129246    sqlite3 *db;                    /* Database connection */
129247    Vdbe *v;                        /* The prepared stmt under constructions */
129248    struct SrcList_item *pTabItem;  /* FROM clause term being coded */
129249    int addrBrk;                    /* Jump here to break out of the loop */
129250    int addrHalt;                   /* addrBrk for the outermost loop */
129251    int addrCont;                   /* Jump here to continue with next cycle */
129252    int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
129253    int iReleaseReg = 0;      /* Temp register to free before returning */
129254    Index *pIdx = 0;          /* Index used by loop (if any) */
129255    int iLoop;                /* Iteration of constraint generator loop */
129256  
129257    pParse = pWInfo->pParse;
129258    v = pParse->pVdbe;
129259    pWC = &pWInfo->sWC;
129260    db = pParse->db;
129261    pLevel = &pWInfo->a[iLevel];
129262    pLoop = pLevel->pWLoop;
129263    pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
129264    iCur = pTabItem->iCursor;
129265    pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
129266    bRev = (pWInfo->revMask>>iLevel)&1;
129267    omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 
129268             && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
129269    VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
129270  
129271    /* Create labels for the "break" and "continue" instructions
129272    ** for the current loop.  Jump to addrBrk to break out of a loop.
129273    ** Jump to cont to go immediately to the next iteration of the
129274    ** loop.
129275    **
129276    ** When there is an IN operator, we also have a "addrNxt" label that
129277    ** means to continue with the next IN value combination.  When
129278    ** there are no IN operators in the constraints, the "addrNxt" label
129279    ** is the same as "addrBrk".
129280    */
129281    addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
129282    addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
129283  
129284    /* If this is the right table of a LEFT OUTER JOIN, allocate and
129285    ** initialize a memory cell that records if this table matches any
129286    ** row of the left table of the join.
129287    */
129288    if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
129289      pLevel->iLeftJoin = ++pParse->nMem;
129290      sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
129291      VdbeComment((v, "init LEFT JOIN no-match flag"));
129292    }
129293  
129294    /* Compute a safe address to jump to if we discover that the table for
129295    ** this loop is empty and can never contribute content. */
129296    for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){}
129297    addrHalt = pWInfo->a[j].addrBrk;
129298  
129299    /* Special case of a FROM clause subquery implemented as a co-routine */
129300    if( pTabItem->fg.viaCoroutine ){
129301      int regYield = pTabItem->regReturn;
129302      sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
129303      pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
129304      VdbeCoverage(v);
129305      VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
129306      pLevel->op = OP_Goto;
129307    }else
129308  
129309  #ifndef SQLITE_OMIT_VIRTUALTABLE
129310    if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
129311      /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
129312      **          to access the data.
129313      */
129314      int iReg;   /* P3 Value for OP_VFilter */
129315      int addrNotFound;
129316      int nConstraint = pLoop->nLTerm;
129317      int iIn;    /* Counter for IN constraints */
129318  
129319      sqlite3ExprCachePush(pParse);
129320      iReg = sqlite3GetTempRange(pParse, nConstraint+2);
129321      addrNotFound = pLevel->addrBrk;
129322      for(j=0; j<nConstraint; j++){
129323        int iTarget = iReg+j+2;
129324        pTerm = pLoop->aLTerm[j];
129325        if( NEVER(pTerm==0) ) continue;
129326        if( pTerm->eOperator & WO_IN ){
129327          codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
129328          addrNotFound = pLevel->addrNxt;
129329        }else{
129330          Expr *pRight = pTerm->pExpr->pRight;
129331          codeExprOrVector(pParse, pRight, iTarget, 1);
129332        }
129333      }
129334      sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
129335      sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
129336      sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
129337                        pLoop->u.vtab.idxStr,
129338                        pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
129339      VdbeCoverage(v);
129340      pLoop->u.vtab.needFree = 0;
129341      pLevel->p1 = iCur;
129342      pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
129343      pLevel->p2 = sqlite3VdbeCurrentAddr(v);
129344      iIn = pLevel->u.in.nIn;
129345      for(j=nConstraint-1; j>=0; j--){
129346        pTerm = pLoop->aLTerm[j];
129347        if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
129348          disableTerm(pLevel, pTerm);
129349        }else if( (pTerm->eOperator & WO_IN)!=0 ){
129350          Expr *pCompare;  /* The comparison operator */
129351          Expr *pRight;    /* RHS of the comparison */
129352          VdbeOp *pOp;     /* Opcode to access the value of the IN constraint */
129353  
129354          /* Reload the constraint value into reg[iReg+j+2].  The same value
129355          ** was loaded into the same register prior to the OP_VFilter, but
129356          ** the xFilter implementation might have changed the datatype or
129357          ** encoding of the value in the register, so it *must* be reloaded. */
129358          assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
129359          if( !db->mallocFailed ){
129360            assert( iIn>0 );
129361            pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
129362            assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
129363            assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
129364            assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
129365            testcase( pOp->opcode==OP_Rowid );
129366            sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
129367          }
129368  
129369          /* Generate code that will continue to the next row if 
129370          ** the IN constraint is not satisfied */
129371          pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);
129372          assert( pCompare!=0 || db->mallocFailed );
129373          if( pCompare ){
129374            pCompare->pLeft = pTerm->pExpr->pLeft;
129375            pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
129376            if( pRight ){
129377              pRight->iTable = iReg+j+2;
129378              sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
129379            }
129380            pCompare->pLeft = 0;
129381            sqlite3ExprDelete(db, pCompare);
129382          }
129383        }
129384      }
129385      /* These registers need to be preserved in case there is an IN operator
129386      ** loop.  So we could deallocate the registers here (and potentially
129387      ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0.  But it seems
129388      ** simpler and safer to simply not reuse the registers.
129389      **
129390      **    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
129391      */
129392      sqlite3ExprCachePop(pParse);
129393    }else
129394  #endif /* SQLITE_OMIT_VIRTUALTABLE */
129395  
129396    if( (pLoop->wsFlags & WHERE_IPK)!=0
129397     && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
129398    ){
129399      /* Case 2:  We can directly reference a single row using an
129400      **          equality comparison against the ROWID field.  Or
129401      **          we reference multiple rows using a "rowid IN (...)"
129402      **          construct.
129403      */
129404      assert( pLoop->u.btree.nEq==1 );
129405      pTerm = pLoop->aLTerm[0];
129406      assert( pTerm!=0 );
129407      assert( pTerm->pExpr!=0 );
129408      assert( omitTable==0 );
129409      testcase( pTerm->wtFlags & TERM_VIRTUAL );
129410      iReleaseReg = ++pParse->nMem;
129411      iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
129412      if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
129413      addrNxt = pLevel->addrNxt;
129414      sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
129415      VdbeCoverage(v);
129416      sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
129417      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
129418      VdbeComment((v, "pk"));
129419      pLevel->op = OP_Noop;
129420    }else if( (pLoop->wsFlags & WHERE_IPK)!=0
129421           && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
129422    ){
129423      /* Case 3:  We have an inequality comparison against the ROWID field.
129424      */
129425      int testOp = OP_Noop;
129426      int start;
129427      int memEndValue = 0;
129428      WhereTerm *pStart, *pEnd;
129429  
129430      assert( omitTable==0 );
129431      j = 0;
129432      pStart = pEnd = 0;
129433      if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
129434      if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
129435      assert( pStart!=0 || pEnd!=0 );
129436      if( bRev ){
129437        pTerm = pStart;
129438        pStart = pEnd;
129439        pEnd = pTerm;
129440      }
129441      codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
129442      if( pStart ){
129443        Expr *pX;             /* The expression that defines the start bound */
129444        int r1, rTemp;        /* Registers for holding the start boundary */
129445        int op;               /* Cursor seek operation */
129446  
129447        /* The following constant maps TK_xx codes into corresponding 
129448        ** seek opcodes.  It depends on a particular ordering of TK_xx
129449        */
129450        const u8 aMoveOp[] = {
129451             /* TK_GT */  OP_SeekGT,
129452             /* TK_LE */  OP_SeekLE,
129453             /* TK_LT */  OP_SeekLT,
129454             /* TK_GE */  OP_SeekGE
129455        };
129456        assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
129457        assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
129458        assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
129459  
129460        assert( (pStart->wtFlags & TERM_VNULL)==0 );
129461        testcase( pStart->wtFlags & TERM_VIRTUAL );
129462        pX = pStart->pExpr;
129463        assert( pX!=0 );
129464        testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
129465        if( sqlite3ExprIsVector(pX->pRight) ){
129466          r1 = rTemp = sqlite3GetTempReg(pParse);
129467          codeExprOrVector(pParse, pX->pRight, r1, 1);
129468          op = aMoveOp[(pX->op - TK_GT) | 0x0001];
129469        }else{
129470          r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
129471          disableTerm(pLevel, pStart);
129472          op = aMoveOp[(pX->op - TK_GT)];
129473        }
129474        sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);
129475        VdbeComment((v, "pk"));
129476        VdbeCoverageIf(v, pX->op==TK_GT);
129477        VdbeCoverageIf(v, pX->op==TK_LE);
129478        VdbeCoverageIf(v, pX->op==TK_LT);
129479        VdbeCoverageIf(v, pX->op==TK_GE);
129480        sqlite3ExprCacheAffinityChange(pParse, r1, 1);
129481        sqlite3ReleaseTempReg(pParse, rTemp);
129482      }else{
129483        sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt);
129484        VdbeCoverageIf(v, bRev==0);
129485        VdbeCoverageIf(v, bRev!=0);
129486      }
129487      if( pEnd ){
129488        Expr *pX;
129489        pX = pEnd->pExpr;
129490        assert( pX!=0 );
129491        assert( (pEnd->wtFlags & TERM_VNULL)==0 );
129492        testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
129493        testcase( pEnd->wtFlags & TERM_VIRTUAL );
129494        memEndValue = ++pParse->nMem;
129495        codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
129496        if( 0==sqlite3ExprIsVector(pX->pRight) 
129497         && (pX->op==TK_LT || pX->op==TK_GT) 
129498        ){
129499          testOp = bRev ? OP_Le : OP_Ge;
129500        }else{
129501          testOp = bRev ? OP_Lt : OP_Gt;
129502        }
129503        if( 0==sqlite3ExprIsVector(pX->pRight) ){
129504          disableTerm(pLevel, pEnd);
129505        }
129506      }
129507      start = sqlite3VdbeCurrentAddr(v);
129508      pLevel->op = bRev ? OP_Prev : OP_Next;
129509      pLevel->p1 = iCur;
129510      pLevel->p2 = start;
129511      assert( pLevel->p5==0 );
129512      if( testOp!=OP_Noop ){
129513        iRowidReg = ++pParse->nMem;
129514        sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
129515        sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
129516        sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
129517        VdbeCoverageIf(v, testOp==OP_Le);
129518        VdbeCoverageIf(v, testOp==OP_Lt);
129519        VdbeCoverageIf(v, testOp==OP_Ge);
129520        VdbeCoverageIf(v, testOp==OP_Gt);
129521        sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
129522      }
129523    }else if( pLoop->wsFlags & WHERE_INDEXED ){
129524      /* Case 4: A scan using an index.
129525      **
129526      **         The WHERE clause may contain zero or more equality 
129527      **         terms ("==" or "IN" operators) that refer to the N
129528      **         left-most columns of the index. It may also contain
129529      **         inequality constraints (>, <, >= or <=) on the indexed
129530      **         column that immediately follows the N equalities. Only 
129531      **         the right-most column can be an inequality - the rest must
129532      **         use the "==" and "IN" operators. For example, if the 
129533      **         index is on (x,y,z), then the following clauses are all 
129534      **         optimized:
129535      **
129536      **            x=5
129537      **            x=5 AND y=10
129538      **            x=5 AND y<10
129539      **            x=5 AND y>5 AND y<10
129540      **            x=5 AND y=5 AND z<=10
129541      **
129542      **         The z<10 term of the following cannot be used, only
129543      **         the x=5 term:
129544      **
129545      **            x=5 AND z<10
129546      **
129547      **         N may be zero if there are inequality constraints.
129548      **         If there are no inequality constraints, then N is at
129549      **         least one.
129550      **
129551      **         This case is also used when there are no WHERE clause
129552      **         constraints but an index is selected anyway, in order
129553      **         to force the output order to conform to an ORDER BY.
129554      */  
129555      static const u8 aStartOp[] = {
129556        0,
129557        0,
129558        OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
129559        OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
129560        OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */
129561        OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */
129562        OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */
129563        OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */
129564      };
129565      static const u8 aEndOp[] = {
129566        OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */
129567        OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */
129568        OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */
129569        OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */
129570      };
129571      u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
129572      u16 nBtm = pLoop->u.btree.nBtm;   /* Length of BTM vector */
129573      u16 nTop = pLoop->u.btree.nTop;   /* Length of TOP vector */
129574      int regBase;                 /* Base register holding constraint values */
129575      WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
129576      WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
129577      int startEq;                 /* True if range start uses ==, >= or <= */
129578      int endEq;                   /* True if range end uses ==, >= or <= */
129579      int start_constraints;       /* Start of range is constrained */
129580      int nConstraint;             /* Number of constraint terms */
129581      int iIdxCur;                 /* The VDBE cursor for the index */
129582      int nExtraReg = 0;           /* Number of extra registers needed */
129583      int op;                      /* Instruction opcode */
129584      char *zStartAff;             /* Affinity for start of range constraint */
129585      char *zEndAff = 0;           /* Affinity for end of range constraint */
129586      u8 bSeekPastNull = 0;        /* True to seek past initial nulls */
129587      u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
129588  
129589      pIdx = pLoop->u.btree.pIndex;
129590      iIdxCur = pLevel->iIdxCur;
129591      assert( nEq>=pLoop->nSkip );
129592  
129593      /* If this loop satisfies a sort order (pOrderBy) request that 
129594      ** was passed to this function to implement a "SELECT min(x) ..." 
129595      ** query, then the caller will only allow the loop to run for
129596      ** a single iteration. This means that the first row returned
129597      ** should not have a NULL value stored in 'x'. If column 'x' is
129598      ** the first one after the nEq equality constraints in the index,
129599      ** this requires some special handling.
129600      */
129601      assert( pWInfo->pOrderBy==0
129602           || pWInfo->pOrderBy->nExpr==1
129603           || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
129604      if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
129605       && pWInfo->nOBSat>0
129606       && (pIdx->nKeyCol>nEq)
129607      ){
129608        assert( pLoop->nSkip==0 );
129609        bSeekPastNull = 1;
129610        nExtraReg = 1;
129611      }
129612  
129613      /* Find any inequality constraint terms for the start and end 
129614      ** of the range. 
129615      */
129616      j = nEq;
129617      if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
129618        pRangeStart = pLoop->aLTerm[j++];
129619        nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
129620        /* Like optimization range constraints always occur in pairs */
129621        assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 || 
129622                (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
129623      }
129624      if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
129625        pRangeEnd = pLoop->aLTerm[j++];
129626        nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
129627  #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
129628        if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
129629          assert( pRangeStart!=0 );                     /* LIKE opt constraints */
129630          assert( pRangeStart->wtFlags & TERM_LIKEOPT );   /* occur in pairs */
129631          pLevel->iLikeRepCntr = (u32)++pParse->nMem;
129632          sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
129633          VdbeComment((v, "LIKE loop counter"));
129634          pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
129635          /* iLikeRepCntr actually stores 2x the counter register number.  The
129636          ** bottom bit indicates whether the search order is ASC or DESC. */
129637          testcase( bRev );
129638          testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
129639          assert( (bRev & ~1)==0 );
129640          pLevel->iLikeRepCntr <<=1;
129641          pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
129642        }
129643  #endif
129644        if( pRangeStart==0 ){
129645          j = pIdx->aiColumn[nEq];
129646          if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
129647            bSeekPastNull = 1;
129648          }
129649        }
129650      }
129651      assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
129652  
129653      /* If we are doing a reverse order scan on an ascending index, or
129654      ** a forward order scan on a descending index, interchange the 
129655      ** start and end terms (pRangeStart and pRangeEnd).
129656      */
129657      if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
129658       || (bRev && pIdx->nKeyCol==nEq)
129659      ){
129660        SWAP(WhereTerm *, pRangeEnd, pRangeStart);
129661        SWAP(u8, bSeekPastNull, bStopAtNull);
129662        SWAP(u8, nBtm, nTop);
129663      }
129664  
129665      /* Generate code to evaluate all constraint terms using == or IN
129666      ** and store the values of those terms in an array of registers
129667      ** starting at regBase.
129668      */
129669      codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
129670      regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
129671      assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
129672      if( zStartAff && nTop ){
129673        zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]);
129674      }
129675      addrNxt = pLevel->addrNxt;
129676  
129677      testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
129678      testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
129679      testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
129680      testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
129681      startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
129682      endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
129683      start_constraints = pRangeStart || nEq>0;
129684  
129685      /* Seek the index cursor to the start of the range. */
129686      nConstraint = nEq;
129687      if( pRangeStart ){
129688        Expr *pRight = pRangeStart->pExpr->pRight;
129689        codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);
129690        whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
129691        if( (pRangeStart->wtFlags & TERM_VNULL)==0
129692         && sqlite3ExprCanBeNull(pRight)
129693        ){
129694          sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
129695          VdbeCoverage(v);
129696        }
129697        if( zStartAff ){
129698          updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);
129699        }  
129700        nConstraint += nBtm;
129701        testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
129702        if( sqlite3ExprIsVector(pRight)==0 ){
129703          disableTerm(pLevel, pRangeStart);
129704        }else{
129705          startEq = 1;
129706        }
129707        bSeekPastNull = 0;
129708      }else if( bSeekPastNull ){
129709        sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
129710        nConstraint++;
129711        startEq = 0;
129712        start_constraints = 1;
129713      }
129714      codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
129715      if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
129716        /* The skip-scan logic inside the call to codeAllEqualityConstraints()
129717        ** above has already left the cursor sitting on the correct row,
129718        ** so no further seeking is needed */
129719      }else{
129720        op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
129721        assert( op!=0 );
129722        sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
129723        VdbeCoverage(v);
129724        VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
129725        VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
129726        VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
129727        VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
129728        VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
129729        VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
129730      }
129731  
129732      /* Load the value for the inequality constraint at the end of the
129733      ** range (if any).
129734      */
129735      nConstraint = nEq;
129736      if( pRangeEnd ){
129737        Expr *pRight = pRangeEnd->pExpr->pRight;
129738        sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
129739        codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
129740        whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
129741        if( (pRangeEnd->wtFlags & TERM_VNULL)==0
129742         && sqlite3ExprCanBeNull(pRight)
129743        ){
129744          sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
129745          VdbeCoverage(v);
129746        }
129747        if( zEndAff ){
129748          updateRangeAffinityStr(pRight, nTop, zEndAff);
129749          codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff);
129750        }else{
129751          assert( pParse->db->mallocFailed );
129752        }
129753        nConstraint += nTop;
129754        testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
129755  
129756        if( sqlite3ExprIsVector(pRight)==0 ){
129757          disableTerm(pLevel, pRangeEnd);
129758        }else{
129759          endEq = 1;
129760        }
129761      }else if( bStopAtNull ){
129762        sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
129763        endEq = 0;
129764        nConstraint++;
129765      }
129766      sqlite3DbFree(db, zStartAff);
129767      sqlite3DbFree(db, zEndAff);
129768  
129769      /* Top of the loop body */
129770      pLevel->p2 = sqlite3VdbeCurrentAddr(v);
129771  
129772      /* Check if the index cursor is past the end of the range. */
129773      if( nConstraint ){
129774        op = aEndOp[bRev*2 + endEq];
129775        sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
129776        testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
129777        testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
129778        testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
129779        testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
129780      }
129781  
129782      /* Seek the table cursor, if required */
129783      if( omitTable ){
129784        /* pIdx is a covering index.  No need to access the main table. */
129785      }else if( HasRowid(pIdx->pTable) ){
129786        if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE) || (
129787            (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE) 
129788         && (pWInfo->eOnePass==ONEPASS_SINGLE)
129789        )){
129790          iRowidReg = ++pParse->nMem;
129791          sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
129792          sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
129793          sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
129794          VdbeCoverage(v);
129795        }else{
129796          codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
129797        }
129798      }else if( iCur!=iIdxCur ){
129799        Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
129800        iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
129801        for(j=0; j<pPk->nKeyCol; j++){
129802          k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
129803          sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
129804        }
129805        sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
129806                             iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
129807      }
129808  
129809      /* If pIdx is an index on one or more expressions, then look through
129810      ** all the expressions in pWInfo and try to transform matching expressions
129811      ** into reference to index columns.
129812      */
129813      whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo);
129814  
129815  
129816      /* Record the instruction used to terminate the loop. */
129817      if( pLoop->wsFlags & WHERE_ONEROW ){
129818        pLevel->op = OP_Noop;
129819      }else if( bRev ){
129820        pLevel->op = OP_Prev;
129821      }else{
129822        pLevel->op = OP_Next;
129823      }
129824      pLevel->p1 = iIdxCur;
129825      pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
129826      if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
129827        pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
129828      }else{
129829        assert( pLevel->p5==0 );
129830      }
129831      if( omitTable ) pIdx = 0;
129832    }else
129833  
129834  #ifndef SQLITE_OMIT_OR_OPTIMIZATION
129835    if( pLoop->wsFlags & WHERE_MULTI_OR ){
129836      /* Case 5:  Two or more separately indexed terms connected by OR
129837      **
129838      ** Example:
129839      **
129840      **   CREATE TABLE t1(a,b,c,d);
129841      **   CREATE INDEX i1 ON t1(a);
129842      **   CREATE INDEX i2 ON t1(b);
129843      **   CREATE INDEX i3 ON t1(c);
129844      **
129845      **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
129846      **
129847      ** In the example, there are three indexed terms connected by OR.
129848      ** The top of the loop looks like this:
129849      **
129850      **          Null       1                # Zero the rowset in reg 1
129851      **
129852      ** Then, for each indexed term, the following. The arguments to
129853      ** RowSetTest are such that the rowid of the current row is inserted
129854      ** into the RowSet. If it is already present, control skips the
129855      ** Gosub opcode and jumps straight to the code generated by WhereEnd().
129856      **
129857      **        sqlite3WhereBegin(<term>)
129858      **          RowSetTest                  # Insert rowid into rowset
129859      **          Gosub      2 A
129860      **        sqlite3WhereEnd()
129861      **
129862      ** Following the above, code to terminate the loop. Label A, the target
129863      ** of the Gosub above, jumps to the instruction right after the Goto.
129864      **
129865      **          Null       1                # Zero the rowset in reg 1
129866      **          Goto       B                # The loop is finished.
129867      **
129868      **       A: <loop body>                 # Return data, whatever.
129869      **
129870      **          Return     2                # Jump back to the Gosub
129871      **
129872      **       B: <after the loop>
129873      **
129874      ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
129875      ** use an ephemeral index instead of a RowSet to record the primary
129876      ** keys of the rows we have already seen.
129877      **
129878      */
129879      WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
129880      SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
129881      Index *pCov = 0;             /* Potential covering index (or NULL) */
129882      int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
129883  
129884      int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
129885      int regRowset = 0;                        /* Register for RowSet object */
129886      int regRowid = 0;                         /* Register holding rowid */
129887      int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
129888      int iRetInit;                             /* Address of regReturn init */
129889      int untestedTerms = 0;             /* Some terms not completely tested */
129890      int ii;                            /* Loop counter */
129891      u16 wctrlFlags;                    /* Flags for sub-WHERE clause */
129892      Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
129893      Table *pTab = pTabItem->pTab;
129894  
129895      pTerm = pLoop->aLTerm[0];
129896      assert( pTerm!=0 );
129897      assert( pTerm->eOperator & WO_OR );
129898      assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
129899      pOrWc = &pTerm->u.pOrInfo->wc;
129900      pLevel->op = OP_Return;
129901      pLevel->p1 = regReturn;
129902  
129903      /* Set up a new SrcList in pOrTab containing the table being scanned
129904      ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
129905      ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
129906      */
129907      if( pWInfo->nLevel>1 ){
129908        int nNotReady;                 /* The number of notReady tables */
129909        struct SrcList_item *origSrc;     /* Original list of tables */
129910        nNotReady = pWInfo->nLevel - iLevel - 1;
129911        pOrTab = sqlite3StackAllocRaw(db,
129912                              sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
129913        if( pOrTab==0 ) return notReady;
129914        pOrTab->nAlloc = (u8)(nNotReady + 1);
129915        pOrTab->nSrc = pOrTab->nAlloc;
129916        memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
129917        origSrc = pWInfo->pTabList->a;
129918        for(k=1; k<=nNotReady; k++){
129919          memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
129920        }
129921      }else{
129922        pOrTab = pWInfo->pTabList;
129923      }
129924  
129925      /* Initialize the rowset register to contain NULL. An SQL NULL is 
129926      ** equivalent to an empty rowset.  Or, create an ephemeral index
129927      ** capable of holding primary keys in the case of a WITHOUT ROWID.
129928      **
129929      ** Also initialize regReturn to contain the address of the instruction 
129930      ** immediately following the OP_Return at the bottom of the loop. This
129931      ** is required in a few obscure LEFT JOIN cases where control jumps
129932      ** over the top of the loop into the body of it. In this case the 
129933      ** correct response for the end-of-loop code (the OP_Return) is to 
129934      ** fall through to the next instruction, just as an OP_Next does if
129935      ** called on an uninitialized cursor.
129936      */
129937      if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
129938        if( HasRowid(pTab) ){
129939          regRowset = ++pParse->nMem;
129940          sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
129941        }else{
129942          Index *pPk = sqlite3PrimaryKeyIndex(pTab);
129943          regRowset = pParse->nTab++;
129944          sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
129945          sqlite3VdbeSetP4KeyInfo(pParse, pPk);
129946        }
129947        regRowid = ++pParse->nMem;
129948      }
129949      iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
129950  
129951      /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
129952      ** Then for every term xN, evaluate as the subexpression: xN AND z
129953      ** That way, terms in y that are factored into the disjunction will
129954      ** be picked up by the recursive calls to sqlite3WhereBegin() below.
129955      **
129956      ** Actually, each subexpression is converted to "xN AND w" where w is
129957      ** the "interesting" terms of z - terms that did not originate in the
129958      ** ON or USING clause of a LEFT JOIN, and terms that are usable as 
129959      ** indices.
129960      **
129961      ** This optimization also only applies if the (x1 OR x2 OR ...) term
129962      ** is not contained in the ON clause of a LEFT JOIN.
129963      ** See ticket http://www.sqlite.org/src/info/f2369304e4
129964      */
129965      if( pWC->nTerm>1 ){
129966        int iTerm;
129967        for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
129968          Expr *pExpr = pWC->a[iTerm].pExpr;
129969          if( &pWC->a[iTerm] == pTerm ) continue;
129970          if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
129971          testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
129972          testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
129973          if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
129974          if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
129975          testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
129976          pExpr = sqlite3ExprDup(db, pExpr, 0);
129977          pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
129978        }
129979        if( pAndExpr ){
129980          pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr);
129981        }
129982      }
129983  
129984      /* Run a separate WHERE clause for each term of the OR clause.  After
129985      ** eliminating duplicates from other WHERE clauses, the action for each
129986      ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
129987      */
129988      wctrlFlags =  WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
129989      for(ii=0; ii<pOrWc->nTerm; ii++){
129990        WhereTerm *pOrTerm = &pOrWc->a[ii];
129991        if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
129992          WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
129993          Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
129994          int jmp1 = 0;                   /* Address of jump operation */
129995          if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
129996            pAndExpr->pLeft = pOrExpr;
129997            pOrExpr = pAndExpr;
129998          }
129999          /* Loop through table entries that match term pOrTerm. */
130000          WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
130001          pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
130002                                        wctrlFlags, iCovCur);
130003          assert( pSubWInfo || pParse->nErr || db->mallocFailed );
130004          if( pSubWInfo ){
130005            WhereLoop *pSubLoop;
130006            int addrExplain = sqlite3WhereExplainOneScan(
130007                pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
130008            );
130009            sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
130010  
130011            /* This is the sub-WHERE clause body.  First skip over
130012            ** duplicate rows from prior sub-WHERE clauses, and record the
130013            ** rowid (or PRIMARY KEY) for the current row so that the same
130014            ** row will be skipped in subsequent sub-WHERE clauses.
130015            */
130016            if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
130017              int r;
130018              int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
130019              if( HasRowid(pTab) ){
130020                r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
130021                jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
130022                                             r,iSet);
130023                VdbeCoverage(v);
130024              }else{
130025                Index *pPk = sqlite3PrimaryKeyIndex(pTab);
130026                int nPk = pPk->nKeyCol;
130027                int iPk;
130028  
130029                /* Read the PK into an array of temp registers. */
130030                r = sqlite3GetTempRange(pParse, nPk);
130031                for(iPk=0; iPk<nPk; iPk++){
130032                  int iCol = pPk->aiColumn[iPk];
130033                  sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk);
130034                }
130035  
130036                /* Check if the temp table already contains this key. If so,
130037                ** the row has already been included in the result set and
130038                ** can be ignored (by jumping past the Gosub below). Otherwise,
130039                ** insert the key into the temp table and proceed with processing
130040                ** the row.
130041                **
130042                ** Use some of the same optimizations as OP_RowSetTest: If iSet
130043                ** is zero, assume that the key cannot already be present in
130044                ** the temp table. And if iSet is -1, assume that there is no 
130045                ** need to insert the key into the temp table, as it will never 
130046                ** be tested for.  */ 
130047                if( iSet ){
130048                  jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
130049                  VdbeCoverage(v);
130050                }
130051                if( iSet>=0 ){
130052                  sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
130053                  sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid,
130054                                       r, nPk);
130055                  if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
130056                }
130057  
130058                /* Release the array of temp registers */
130059                sqlite3ReleaseTempRange(pParse, r, nPk);
130060              }
130061            }
130062  
130063            /* Invoke the main loop body as a subroutine */
130064            sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
130065  
130066            /* Jump here (skipping the main loop body subroutine) if the
130067            ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
130068            if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
130069  
130070            /* The pSubWInfo->untestedTerms flag means that this OR term
130071            ** contained one or more AND term from a notReady table.  The
130072            ** terms from the notReady table could not be tested and will
130073            ** need to be tested later.
130074            */
130075            if( pSubWInfo->untestedTerms ) untestedTerms = 1;
130076  
130077            /* If all of the OR-connected terms are optimized using the same
130078            ** index, and the index is opened using the same cursor number
130079            ** by each call to sqlite3WhereBegin() made by this loop, it may
130080            ** be possible to use that index as a covering index.
130081            **
130082            ** If the call to sqlite3WhereBegin() above resulted in a scan that
130083            ** uses an index, and this is either the first OR-connected term
130084            ** processed or the index is the same as that used by all previous
130085            ** terms, set pCov to the candidate covering index. Otherwise, set 
130086            ** pCov to NULL to indicate that no candidate covering index will 
130087            ** be available.
130088            */
130089            pSubLoop = pSubWInfo->a[0].pWLoop;
130090            assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
130091            if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
130092             && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
130093             && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
130094            ){
130095              assert( pSubWInfo->a[0].iIdxCur==iCovCur );
130096              pCov = pSubLoop->u.btree.pIndex;
130097            }else{
130098              pCov = 0;
130099            }
130100  
130101            /* Finish the loop through table entries that match term pOrTerm. */
130102            sqlite3WhereEnd(pSubWInfo);
130103          }
130104        }
130105      }
130106      pLevel->u.pCovidx = pCov;
130107      if( pCov ) pLevel->iIdxCur = iCovCur;
130108      if( pAndExpr ){
130109        pAndExpr->pLeft = 0;
130110        sqlite3ExprDelete(db, pAndExpr);
130111      }
130112      sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
130113      sqlite3VdbeGoto(v, pLevel->addrBrk);
130114      sqlite3VdbeResolveLabel(v, iLoopBody);
130115  
130116      if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
130117      if( !untestedTerms ) disableTerm(pLevel, pTerm);
130118    }else
130119  #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
130120  
130121    {
130122      /* Case 6:  There is no usable index.  We must do a complete
130123      **          scan of the entire table.
130124      */
130125      static const u8 aStep[] = { OP_Next, OP_Prev };
130126      static const u8 aStart[] = { OP_Rewind, OP_Last };
130127      assert( bRev==0 || bRev==1 );
130128      if( pTabItem->fg.isRecursive ){
130129        /* Tables marked isRecursive have only a single row that is stored in
130130        ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
130131        pLevel->op = OP_Noop;
130132      }else{
130133        codeCursorHint(pTabItem, pWInfo, pLevel, 0);
130134        pLevel->op = aStep[bRev];
130135        pLevel->p1 = iCur;
130136        pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);
130137        VdbeCoverageIf(v, bRev==0);
130138        VdbeCoverageIf(v, bRev!=0);
130139        pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
130140      }
130141    }
130142  
130143  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
130144    pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
130145  #endif
130146  
130147    /* Insert code to test every subexpression that can be completely
130148    ** computed using the current set of tables.
130149    **
130150    ** This loop may run between one and three times, depending on the
130151    ** constraints to be generated. The value of stack variable iLoop
130152    ** determines the constraints coded by each iteration, as follows:
130153    **
130154    ** iLoop==1: Code only expressions that are entirely covered by pIdx.
130155    ** iLoop==2: Code remaining expressions that do not contain correlated
130156    **           sub-queries.  
130157    ** iLoop==3: Code all remaining expressions.
130158    **
130159    ** An effort is made to skip unnecessary iterations of the loop.
130160    */
130161    iLoop = (pIdx ? 1 : 2);
130162    do{
130163      int iNext = 0;                /* Next value for iLoop */
130164      for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
130165        Expr *pE;
130166        int skipLikeAddr = 0;
130167        testcase( pTerm->wtFlags & TERM_VIRTUAL );
130168        testcase( pTerm->wtFlags & TERM_CODED );
130169        if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
130170        if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
130171          testcase( pWInfo->untestedTerms==0
130172              && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
130173          pWInfo->untestedTerms = 1;
130174          continue;
130175        }
130176        pE = pTerm->pExpr;
130177        assert( pE!=0 );
130178        if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
130179          continue;
130180        }
130181        
130182        if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){
130183          iNext = 2;
130184          continue;
130185        }
130186        if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){
130187          if( iNext==0 ) iNext = 3;
130188          continue;
130189        }
130190  
130191        if( pTerm->wtFlags & TERM_LIKECOND ){
130192          /* If the TERM_LIKECOND flag is set, that means that the range search
130193          ** is sufficient to guarantee that the LIKE operator is true, so we
130194          ** can skip the call to the like(A,B) function.  But this only works
130195          ** for strings.  So do not skip the call to the function on the pass
130196          ** that compares BLOBs. */
130197  #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
130198          continue;
130199  #else
130200          u32 x = pLevel->iLikeRepCntr;
130201          assert( x>0 );
130202          skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If, (int)(x>>1));
130203          VdbeCoverage(v);
130204  #endif
130205        }
130206  #ifdef WHERETRACE_ENABLED /* 0xffff */
130207        if( sqlite3WhereTrace ){
130208          VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d",
130209                           pWC->nTerm-j, pTerm, iLoop));
130210        }
130211  #endif
130212        sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
130213        if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
130214        pTerm->wtFlags |= TERM_CODED;
130215      }
130216      iLoop = iNext;
130217    }while( iLoop>0 );
130218  
130219    /* Insert code to test for implied constraints based on transitivity
130220    ** of the "==" operator.
130221    **
130222    ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
130223    ** and we are coding the t1 loop and the t2 loop has not yet coded,
130224    ** then we cannot use the "t1.a=t2.b" constraint, but we can code
130225    ** the implied "t1.a=123" constraint.
130226    */
130227    for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
130228      Expr *pE, sEAlt;
130229      WhereTerm *pAlt;
130230      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
130231      if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
130232      if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
130233      if( pTerm->leftCursor!=iCur ) continue;
130234      if( pLevel->iLeftJoin ) continue;
130235      pE = pTerm->pExpr;
130236      assert( !ExprHasProperty(pE, EP_FromJoin) );
130237      assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
130238      pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
130239                      WO_EQ|WO_IN|WO_IS, 0);
130240      if( pAlt==0 ) continue;
130241      if( pAlt->wtFlags & (TERM_CODED) ) continue;
130242      testcase( pAlt->eOperator & WO_EQ );
130243      testcase( pAlt->eOperator & WO_IS );
130244      testcase( pAlt->eOperator & WO_IN );
130245      VdbeModuleComment((v, "begin transitive constraint"));
130246      sEAlt = *pAlt->pExpr;
130247      sEAlt.pLeft = pE->pLeft;
130248      sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);
130249    }
130250  
130251    /* For a LEFT OUTER JOIN, generate code that will record the fact that
130252    ** at least one row of the right table has matched the left table.  
130253    */
130254    if( pLevel->iLeftJoin ){
130255      pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
130256      sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
130257      VdbeComment((v, "record LEFT JOIN hit"));
130258      sqlite3ExprCacheClear(pParse);
130259      for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
130260        testcase( pTerm->wtFlags & TERM_VIRTUAL );
130261        testcase( pTerm->wtFlags & TERM_CODED );
130262        if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
130263        if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
130264          assert( pWInfo->untestedTerms );
130265          continue;
130266        }
130267        assert( pTerm->pExpr );
130268        sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
130269        pTerm->wtFlags |= TERM_CODED;
130270      }
130271    }
130272  
130273    return pLevel->notReady;
130274  }
130275  
130276  /************** End of wherecode.c *******************************************/
130277  /************** Begin file whereexpr.c ***************************************/
130278  /*
130279  ** 2015-06-08
130280  **
130281  ** The author disclaims copyright to this source code.  In place of
130282  ** a legal notice, here is a blessing:
130283  **
130284  **    May you do good and not evil.
130285  **    May you find forgiveness for yourself and forgive others.
130286  **    May you share freely, never taking more than you give.
130287  **
130288  *************************************************************************
130289  ** This module contains C code that generates VDBE code used to process
130290  ** the WHERE clause of SQL statements.
130291  **
130292  ** This file was originally part of where.c but was split out to improve
130293  ** readability and editabiliity.  This file contains utility routines for
130294  ** analyzing Expr objects in the WHERE clause.
130295  */
130296  /* #include "sqliteInt.h" */
130297  /* #include "whereInt.h" */
130298  
130299  /* Forward declarations */
130300  static void exprAnalyze(SrcList*, WhereClause*, int);
130301  
130302  /*
130303  ** Deallocate all memory associated with a WhereOrInfo object.
130304  */
130305  static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
130306    sqlite3WhereClauseClear(&p->wc);
130307    sqlite3DbFree(db, p);
130308  }
130309  
130310  /*
130311  ** Deallocate all memory associated with a WhereAndInfo object.
130312  */
130313  static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
130314    sqlite3WhereClauseClear(&p->wc);
130315    sqlite3DbFree(db, p);
130316  }
130317  
130318  /*
130319  ** Add a single new WhereTerm entry to the WhereClause object pWC.
130320  ** The new WhereTerm object is constructed from Expr p and with wtFlags.
130321  ** The index in pWC->a[] of the new WhereTerm is returned on success.
130322  ** 0 is returned if the new WhereTerm could not be added due to a memory
130323  ** allocation error.  The memory allocation failure will be recorded in
130324  ** the db->mallocFailed flag so that higher-level functions can detect it.
130325  **
130326  ** This routine will increase the size of the pWC->a[] array as necessary.
130327  **
130328  ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
130329  ** for freeing the expression p is assumed by the WhereClause object pWC.
130330  ** This is true even if this routine fails to allocate a new WhereTerm.
130331  **
130332  ** WARNING:  This routine might reallocate the space used to store
130333  ** WhereTerms.  All pointers to WhereTerms should be invalidated after
130334  ** calling this routine.  Such pointers may be reinitialized by referencing
130335  ** the pWC->a[] array.
130336  */
130337  static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
130338    WhereTerm *pTerm;
130339    int idx;
130340    testcase( wtFlags & TERM_VIRTUAL );
130341    if( pWC->nTerm>=pWC->nSlot ){
130342      WhereTerm *pOld = pWC->a;
130343      sqlite3 *db = pWC->pWInfo->pParse->db;
130344      pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
130345      if( pWC->a==0 ){
130346        if( wtFlags & TERM_DYNAMIC ){
130347          sqlite3ExprDelete(db, p);
130348        }
130349        pWC->a = pOld;
130350        return 0;
130351      }
130352      memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
130353      if( pOld!=pWC->aStatic ){
130354        sqlite3DbFree(db, pOld);
130355      }
130356      pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
130357    }
130358    pTerm = &pWC->a[idx = pWC->nTerm++];
130359    if( p && ExprHasProperty(p, EP_Unlikely) ){
130360      pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
130361    }else{
130362      pTerm->truthProb = 1;
130363    }
130364    pTerm->pExpr = sqlite3ExprSkipCollate(p);
130365    pTerm->wtFlags = wtFlags;
130366    pTerm->pWC = pWC;
130367    pTerm->iParent = -1;
130368    memset(&pTerm->eOperator, 0,
130369           sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
130370    return idx;
130371  }
130372  
130373  /*
130374  ** Return TRUE if the given operator is one of the operators that is
130375  ** allowed for an indexable WHERE clause term.  The allowed operators are
130376  ** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
130377  */
130378  static int allowedOp(int op){
130379    assert( TK_GT>TK_EQ && TK_GT<TK_GE );
130380    assert( TK_LT>TK_EQ && TK_LT<TK_GE );
130381    assert( TK_LE>TK_EQ && TK_LE<TK_GE );
130382    assert( TK_GE==TK_EQ+4 );
130383    return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
130384  }
130385  
130386  /*
130387  ** Commute a comparison operator.  Expressions of the form "X op Y"
130388  ** are converted into "Y op X".
130389  **
130390  ** If left/right precedence rules come into play when determining the
130391  ** collating sequence, then COLLATE operators are adjusted to ensure
130392  ** that the collating sequence does not change.  For example:
130393  ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
130394  ** the left hand side of a comparison overrides any collation sequence 
130395  ** attached to the right. For the same reason the EP_Collate flag
130396  ** is not commuted.
130397  */
130398  static void exprCommute(Parse *pParse, Expr *pExpr){
130399    u16 expRight = (pExpr->pRight->flags & EP_Collate);
130400    u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
130401    assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
130402    if( expRight==expLeft ){
130403      /* Either X and Y both have COLLATE operator or neither do */
130404      if( expRight ){
130405        /* Both X and Y have COLLATE operators.  Make sure X is always
130406        ** used by clearing the EP_Collate flag from Y. */
130407        pExpr->pRight->flags &= ~EP_Collate;
130408      }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
130409        /* Neither X nor Y have COLLATE operators, but X has a non-default
130410        ** collating sequence.  So add the EP_Collate marker on X to cause
130411        ** it to be searched first. */
130412        pExpr->pLeft->flags |= EP_Collate;
130413      }
130414    }
130415    SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
130416    if( pExpr->op>=TK_GT ){
130417      assert( TK_LT==TK_GT+2 );
130418      assert( TK_GE==TK_LE+2 );
130419      assert( TK_GT>TK_EQ );
130420      assert( TK_GT<TK_LE );
130421      assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
130422      pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
130423    }
130424  }
130425  
130426  /*
130427  ** Translate from TK_xx operator to WO_xx bitmask.
130428  */
130429  static u16 operatorMask(int op){
130430    u16 c;
130431    assert( allowedOp(op) );
130432    if( op==TK_IN ){
130433      c = WO_IN;
130434    }else if( op==TK_ISNULL ){
130435      c = WO_ISNULL;
130436    }else if( op==TK_IS ){
130437      c = WO_IS;
130438    }else{
130439      assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
130440      c = (u16)(WO_EQ<<(op-TK_EQ));
130441    }
130442    assert( op!=TK_ISNULL || c==WO_ISNULL );
130443    assert( op!=TK_IN || c==WO_IN );
130444    assert( op!=TK_EQ || c==WO_EQ );
130445    assert( op!=TK_LT || c==WO_LT );
130446    assert( op!=TK_LE || c==WO_LE );
130447    assert( op!=TK_GT || c==WO_GT );
130448    assert( op!=TK_GE || c==WO_GE );
130449    assert( op!=TK_IS || c==WO_IS );
130450    return c;
130451  }
130452  
130453  
130454  #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
130455  /*
130456  ** Check to see if the given expression is a LIKE or GLOB operator that
130457  ** can be optimized using inequality constraints.  Return TRUE if it is
130458  ** so and false if not.
130459  **
130460  ** In order for the operator to be optimizible, the RHS must be a string
130461  ** literal that does not begin with a wildcard.  The LHS must be a column
130462  ** that may only be NULL, a string, or a BLOB, never a number. (This means
130463  ** that virtual tables cannot participate in the LIKE optimization.)  The
130464  ** collating sequence for the column on the LHS must be appropriate for
130465  ** the operator.
130466  */
130467  static int isLikeOrGlob(
130468    Parse *pParse,    /* Parsing and code generating context */
130469    Expr *pExpr,      /* Test this expression */
130470    Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
130471    int *pisComplete, /* True if the only wildcard is % in the last character */
130472    int *pnoCase      /* True if uppercase is equivalent to lowercase */
130473  ){
130474    const u8 *z = 0;         /* String on RHS of LIKE operator */
130475    Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
130476    ExprList *pList;           /* List of operands to the LIKE operator */
130477    int c;                     /* One character in z[] */
130478    int cnt;                   /* Number of non-wildcard prefix characters */
130479    char wc[4];                /* Wildcard characters */
130480    sqlite3 *db = pParse->db;  /* Database connection */
130481    sqlite3_value *pVal = 0;
130482    int op;                    /* Opcode of pRight */
130483    int rc;                    /* Result code to return */
130484  
130485    if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
130486      return 0;
130487    }
130488  #ifdef SQLITE_EBCDIC
130489    if( *pnoCase ) return 0;
130490  #endif
130491    pList = pExpr->x.pList;
130492    pLeft = pList->a[1].pExpr;
130493  
130494    pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
130495    op = pRight->op;
130496    if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
130497      Vdbe *pReprepare = pParse->pReprepare;
130498      int iCol = pRight->iColumn;
130499      pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
130500      if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
130501        z = sqlite3_value_text(pVal);
130502      }
130503      sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
130504      assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
130505    }else if( op==TK_STRING ){
130506      z = (u8*)pRight->u.zToken;
130507    }
130508    if( z ){
130509  
130510      /* If the RHS begins with a digit or a minus sign, then the LHS must
130511      ** be an ordinary column (not a virtual table column) with TEXT affinity.
130512      ** Otherwise the LHS might be numeric and "lhs >= rhs" would be false
130513      ** even though "lhs LIKE rhs" is true.  But if the RHS does not start
130514      ** with a digit or '-', then "lhs LIKE rhs" will always be false if
130515      ** the LHS is numeric and so the optimization still works.
130516      */
130517      if( sqlite3Isdigit(z[0]) || z[0]=='-' ){
130518        if( pLeft->op!=TK_COLUMN 
130519         || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT 
130520         || IsVirtual(pLeft->pTab)  /* Value might be numeric */
130521        ){
130522          sqlite3ValueFree(pVal);
130523          return 0;
130524        }
130525      }
130526  
130527      /* Count the number of prefix characters prior to the first wildcard */
130528      cnt = 0;
130529      while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
130530        cnt++;
130531        if( c==wc[3] && z[cnt]!=0 ) cnt++;
130532      }
130533  
130534      /* The optimization is possible only if (1) the pattern does not begin
130535      ** with a wildcard and if (2) the non-wildcard prefix does not end with
130536      ** an (illegal 0xff) character.  The second condition is necessary so
130537      ** that we can increment the prefix key to find an upper bound for the
130538      ** range search. 
130539      */
130540      if( cnt!=0 && 255!=(u8)z[cnt-1] ){
130541        Expr *pPrefix;
130542  
130543        /* A "complete" match if the pattern ends with "*" or "%" */
130544        *pisComplete = c==wc[0] && z[cnt+1]==0;
130545  
130546        /* Get the pattern prefix.  Remove all escapes from the prefix. */
130547        pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);
130548        if( pPrefix ){
130549          int iFrom, iTo;
130550          char *zNew = pPrefix->u.zToken;
130551          zNew[cnt] = 0;
130552          for(iFrom=iTo=0; iFrom<cnt; iFrom++){
130553            if( zNew[iFrom]==wc[3] ) iFrom++;
130554            zNew[iTo++] = zNew[iFrom];
130555          }
130556          zNew[iTo] = 0;
130557        }
130558        *ppPrefix = pPrefix;
130559  
130560        /* If the RHS pattern is a bound parameter, make arrangements to
130561        ** reprepare the statement when that parameter is rebound */
130562        if( op==TK_VARIABLE ){
130563          Vdbe *v = pParse->pVdbe;
130564          sqlite3VdbeSetVarmask(v, pRight->iColumn);
130565          if( *pisComplete && pRight->u.zToken[1] ){
130566            /* If the rhs of the LIKE expression is a variable, and the current
130567            ** value of the variable means there is no need to invoke the LIKE
130568            ** function, then no OP_Variable will be added to the program.
130569            ** This causes problems for the sqlite3_bind_parameter_name()
130570            ** API. To work around them, add a dummy OP_Variable here.
130571            */ 
130572            int r1 = sqlite3GetTempReg(pParse);
130573            sqlite3ExprCodeTarget(pParse, pRight, r1);
130574            sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
130575            sqlite3ReleaseTempReg(pParse, r1);
130576          }
130577        }
130578      }else{
130579        z = 0;
130580      }
130581    }
130582  
130583    rc = (z!=0);
130584    sqlite3ValueFree(pVal);
130585    return rc;
130586  }
130587  #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
130588  
130589  
130590  #ifndef SQLITE_OMIT_VIRTUALTABLE
130591  /*
130592  ** Check to see if the pExpr expression is a form that needs to be passed
130593  ** to the xBestIndex method of virtual tables.  Forms of interest include:
130594  **
130595  **          Expression                   Virtual Table Operator
130596  **          -----------------------      ---------------------------------
130597  **      1.  column MATCH expr            SQLITE_INDEX_CONSTRAINT_MATCH
130598  **      2.  column GLOB expr             SQLITE_INDEX_CONSTRAINT_GLOB
130599  **      3.  column LIKE expr             SQLITE_INDEX_CONSTRAINT_LIKE
130600  **      4.  column REGEXP expr           SQLITE_INDEX_CONSTRAINT_REGEXP
130601  **      5.  column != expr               SQLITE_INDEX_CONSTRAINT_NE
130602  **      6.  expr != column               SQLITE_INDEX_CONSTRAINT_NE
130603  **      7.  column IS NOT expr           SQLITE_INDEX_CONSTRAINT_ISNOT
130604  **      8.  expr IS NOT column           SQLITE_INDEX_CONSTRAINT_ISNOT
130605  **      9.  column IS NOT NULL           SQLITE_INDEX_CONSTRAINT_ISNOTNULL
130606  **
130607  ** In every case, "column" must be a column of a virtual table.  If there
130608  ** is a match, set *ppLeft to the "column" expression, set *ppRight to the 
130609  ** "expr" expression (even though in forms (6) and (8) the column is on the
130610  ** right and the expression is on the left).  Also set *peOp2 to the
130611  ** appropriate virtual table operator.  The return value is 1 or 2 if there
130612  ** is a match.  The usual return is 1, but if the RHS is also a column
130613  ** of virtual table in forms (5) or (7) then return 2.
130614  **
130615  ** If the expression matches none of the patterns above, return 0.
130616  */
130617  static int isAuxiliaryVtabOperator(
130618    Expr *pExpr,                    /* Test this expression */
130619    unsigned char *peOp2,           /* OUT: 0 for MATCH, or else an op2 value */
130620    Expr **ppLeft,                  /* Column expression to left of MATCH/op2 */
130621    Expr **ppRight                  /* Expression to left of MATCH/op2 */
130622  ){
130623    if( pExpr->op==TK_FUNCTION ){
130624      static const struct Op2 {
130625        const char *zOp;
130626        unsigned char eOp2;
130627      } aOp[] = {
130628        { "match",  SQLITE_INDEX_CONSTRAINT_MATCH },
130629        { "glob",   SQLITE_INDEX_CONSTRAINT_GLOB },
130630        { "like",   SQLITE_INDEX_CONSTRAINT_LIKE },
130631        { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
130632      };
130633      ExprList *pList;
130634      Expr *pCol;                     /* Column reference */
130635      int i;
130636  
130637      pList = pExpr->x.pList;
130638      if( pList==0 || pList->nExpr!=2 ){
130639        return 0;
130640      }
130641      pCol = pList->a[1].pExpr;
130642      if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){
130643        return 0;
130644      }
130645      for(i=0; i<ArraySize(aOp); i++){
130646        if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
130647          *peOp2 = aOp[i].eOp2;
130648          *ppRight = pList->a[0].pExpr;
130649          *ppLeft = pCol;
130650          return 1;
130651        }
130652      }
130653    }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
130654      int res = 0;
130655      Expr *pLeft = pExpr->pLeft;
130656      Expr *pRight = pExpr->pRight;
130657      if( pLeft->op==TK_COLUMN && IsVirtual(pLeft->pTab) ){
130658        res++;
130659      }
130660      if( pRight && pRight->op==TK_COLUMN && IsVirtual(pRight->pTab) ){
130661        res++;
130662        SWAP(Expr*, pLeft, pRight);
130663      }
130664      *ppLeft = pLeft;
130665      *ppRight = pRight;
130666      if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE;
130667      if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT;
130668      if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL;
130669      return res;
130670    }
130671    return 0;
130672  }
130673  #endif /* SQLITE_OMIT_VIRTUALTABLE */
130674  
130675  /*
130676  ** If the pBase expression originated in the ON or USING clause of
130677  ** a join, then transfer the appropriate markings over to derived.
130678  */
130679  static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
130680    if( pDerived ){
130681      pDerived->flags |= pBase->flags & EP_FromJoin;
130682      pDerived->iRightJoinTable = pBase->iRightJoinTable;
130683    }
130684  }
130685  
130686  /*
130687  ** Mark term iChild as being a child of term iParent
130688  */
130689  static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
130690    pWC->a[iChild].iParent = iParent;
130691    pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
130692    pWC->a[iParent].nChild++;
130693  }
130694  
130695  /*
130696  ** Return the N-th AND-connected subterm of pTerm.  Or if pTerm is not
130697  ** a conjunction, then return just pTerm when N==0.  If N is exceeds
130698  ** the number of available subterms, return NULL.
130699  */
130700  static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
130701    if( pTerm->eOperator!=WO_AND ){
130702      return N==0 ? pTerm : 0;
130703    }
130704    if( N<pTerm->u.pAndInfo->wc.nTerm ){
130705      return &pTerm->u.pAndInfo->wc.a[N];
130706    }
130707    return 0;
130708  }
130709  
130710  /*
130711  ** Subterms pOne and pTwo are contained within WHERE clause pWC.  The
130712  ** two subterms are in disjunction - they are OR-ed together.
130713  **
130714  ** If these two terms are both of the form:  "A op B" with the same
130715  ** A and B values but different operators and if the operators are
130716  ** compatible (if one is = and the other is <, for example) then
130717  ** add a new virtual AND term to pWC that is the combination of the
130718  ** two.
130719  **
130720  ** Some examples:
130721  **
130722  **    x<y OR x=y    -->     x<=y
130723  **    x=y OR x=y    -->     x=y
130724  **    x<=y OR x<y   -->     x<=y
130725  **
130726  ** The following is NOT generated:
130727  **
130728  **    x<y OR x>y    -->     x!=y     
130729  */
130730  static void whereCombineDisjuncts(
130731    SrcList *pSrc,         /* the FROM clause */
130732    WhereClause *pWC,      /* The complete WHERE clause */
130733    WhereTerm *pOne,       /* First disjunct */
130734    WhereTerm *pTwo        /* Second disjunct */
130735  ){
130736    u16 eOp = pOne->eOperator | pTwo->eOperator;
130737    sqlite3 *db;           /* Database connection (for malloc) */
130738    Expr *pNew;            /* New virtual expression */
130739    int op;                /* Operator for the combined expression */
130740    int idxNew;            /* Index in pWC of the next virtual term */
130741  
130742    if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
130743    if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
130744    if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
130745     && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
130746    assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
130747    assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
130748    if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
130749    if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return;
130750    /* If we reach this point, it means the two subterms can be combined */
130751    if( (eOp & (eOp-1))!=0 ){
130752      if( eOp & (WO_LT|WO_LE) ){
130753        eOp = WO_LE;
130754      }else{
130755        assert( eOp & (WO_GT|WO_GE) );
130756        eOp = WO_GE;
130757      }
130758    }
130759    db = pWC->pWInfo->pParse->db;
130760    pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
130761    if( pNew==0 ) return;
130762    for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
130763    pNew->op = op;
130764    idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
130765    exprAnalyze(pSrc, pWC, idxNew);
130766  }
130767  
130768  #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
130769  /*
130770  ** Analyze a term that consists of two or more OR-connected
130771  ** subterms.  So in:
130772  **
130773  **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
130774  **                          ^^^^^^^^^^^^^^^^^^^^
130775  **
130776  ** This routine analyzes terms such as the middle term in the above example.
130777  ** A WhereOrTerm object is computed and attached to the term under
130778  ** analysis, regardless of the outcome of the analysis.  Hence:
130779  **
130780  **     WhereTerm.wtFlags   |=  TERM_ORINFO
130781  **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
130782  **
130783  ** The term being analyzed must have two or more of OR-connected subterms.
130784  ** A single subterm might be a set of AND-connected sub-subterms.
130785  ** Examples of terms under analysis:
130786  **
130787  **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
130788  **     (B)     x=expr1 OR expr2=x OR x=expr3
130789  **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
130790  **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
130791  **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
130792  **     (F)     x>A OR (x=A AND y>=B)
130793  **
130794  ** CASE 1:
130795  **
130796  ** If all subterms are of the form T.C=expr for some single column of C and
130797  ** a single table T (as shown in example B above) then create a new virtual
130798  ** term that is an equivalent IN expression.  In other words, if the term
130799  ** being analyzed is:
130800  **
130801  **      x = expr1  OR  expr2 = x  OR  x = expr3
130802  **
130803  ** then create a new virtual term like this:
130804  **
130805  **      x IN (expr1,expr2,expr3)
130806  **
130807  ** CASE 2:
130808  **
130809  ** If there are exactly two disjuncts and one side has x>A and the other side
130810  ** has x=A (for the same x and A) then add a new virtual conjunct term to the
130811  ** WHERE clause of the form "x>=A".  Example:
130812  **
130813  **      x>A OR (x=A AND y>B)    adds:    x>=A
130814  **
130815  ** The added conjunct can sometimes be helpful in query planning.
130816  **
130817  ** CASE 3:
130818  **
130819  ** If all subterms are indexable by a single table T, then set
130820  **
130821  **     WhereTerm.eOperator              =  WO_OR
130822  **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
130823  **
130824  ** A subterm is "indexable" if it is of the form
130825  ** "T.C <op> <expr>" where C is any column of table T and 
130826  ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
130827  ** A subterm is also indexable if it is an AND of two or more
130828  ** subsubterms at least one of which is indexable.  Indexable AND 
130829  ** subterms have their eOperator set to WO_AND and they have
130830  ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
130831  **
130832  ** From another point of view, "indexable" means that the subterm could
130833  ** potentially be used with an index if an appropriate index exists.
130834  ** This analysis does not consider whether or not the index exists; that
130835  ** is decided elsewhere.  This analysis only looks at whether subterms
130836  ** appropriate for indexing exist.
130837  **
130838  ** All examples A through E above satisfy case 3.  But if a term
130839  ** also satisfies case 1 (such as B) we know that the optimizer will
130840  ** always prefer case 1, so in that case we pretend that case 3 is not
130841  ** satisfied.
130842  **
130843  ** It might be the case that multiple tables are indexable.  For example,
130844  ** (E) above is indexable on tables P, Q, and R.
130845  **
130846  ** Terms that satisfy case 3 are candidates for lookup by using
130847  ** separate indices to find rowids for each subterm and composing
130848  ** the union of all rowids using a RowSet object.  This is similar
130849  ** to "bitmap indices" in other database engines.
130850  **
130851  ** OTHERWISE:
130852  **
130853  ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
130854  ** zero.  This term is not useful for search.
130855  */
130856  static void exprAnalyzeOrTerm(
130857    SrcList *pSrc,            /* the FROM clause */
130858    WhereClause *pWC,         /* the complete WHERE clause */
130859    int idxTerm               /* Index of the OR-term to be analyzed */
130860  ){
130861    WhereInfo *pWInfo = pWC->pWInfo;        /* WHERE clause processing context */
130862    Parse *pParse = pWInfo->pParse;         /* Parser context */
130863    sqlite3 *db = pParse->db;               /* Database connection */
130864    WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
130865    Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
130866    int i;                                  /* Loop counters */
130867    WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
130868    WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
130869    WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
130870    Bitmask chngToIN;         /* Tables that might satisfy case 1 */
130871    Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
130872  
130873    /*
130874    ** Break the OR clause into its separate subterms.  The subterms are
130875    ** stored in a WhereClause structure containing within the WhereOrInfo
130876    ** object that is attached to the original OR clause term.
130877    */
130878    assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
130879    assert( pExpr->op==TK_OR );
130880    pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
130881    if( pOrInfo==0 ) return;
130882    pTerm->wtFlags |= TERM_ORINFO;
130883    pOrWc = &pOrInfo->wc;
130884    memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
130885    sqlite3WhereClauseInit(pOrWc, pWInfo);
130886    sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
130887    sqlite3WhereExprAnalyze(pSrc, pOrWc);
130888    if( db->mallocFailed ) return;
130889    assert( pOrWc->nTerm>=2 );
130890  
130891    /*
130892    ** Compute the set of tables that might satisfy cases 1 or 3.
130893    */
130894    indexable = ~(Bitmask)0;
130895    chngToIN = ~(Bitmask)0;
130896    for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
130897      if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
130898        WhereAndInfo *pAndInfo;
130899        assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
130900        chngToIN = 0;
130901        pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
130902        if( pAndInfo ){
130903          WhereClause *pAndWC;
130904          WhereTerm *pAndTerm;
130905          int j;
130906          Bitmask b = 0;
130907          pOrTerm->u.pAndInfo = pAndInfo;
130908          pOrTerm->wtFlags |= TERM_ANDINFO;
130909          pOrTerm->eOperator = WO_AND;
130910          pAndWC = &pAndInfo->wc;
130911          memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
130912          sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
130913          sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
130914          sqlite3WhereExprAnalyze(pSrc, pAndWC);
130915          pAndWC->pOuter = pWC;
130916          if( !db->mallocFailed ){
130917            for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
130918              assert( pAndTerm->pExpr );
130919              if( allowedOp(pAndTerm->pExpr->op) 
130920               || pAndTerm->eOperator==WO_AUX
130921              ){
130922                b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
130923              }
130924            }
130925          }
130926          indexable &= b;
130927        }
130928      }else if( pOrTerm->wtFlags & TERM_COPIED ){
130929        /* Skip this term for now.  We revisit it when we process the
130930        ** corresponding TERM_VIRTUAL term */
130931      }else{
130932        Bitmask b;
130933        b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
130934        if( pOrTerm->wtFlags & TERM_VIRTUAL ){
130935          WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
130936          b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
130937        }
130938        indexable &= b;
130939        if( (pOrTerm->eOperator & WO_EQ)==0 ){
130940          chngToIN = 0;
130941        }else{
130942          chngToIN &= b;
130943        }
130944      }
130945    }
130946  
130947    /*
130948    ** Record the set of tables that satisfy case 3.  The set might be
130949    ** empty.
130950    */
130951    pOrInfo->indexable = indexable;
130952    pTerm->eOperator = indexable==0 ? 0 : WO_OR;
130953  
130954    /* For a two-way OR, attempt to implementation case 2.
130955    */
130956    if( indexable && pOrWc->nTerm==2 ){
130957      int iOne = 0;
130958      WhereTerm *pOne;
130959      while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
130960        int iTwo = 0;
130961        WhereTerm *pTwo;
130962        while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
130963          whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
130964        }
130965      }
130966    }
130967  
130968    /*
130969    ** chngToIN holds a set of tables that *might* satisfy case 1.  But
130970    ** we have to do some additional checking to see if case 1 really
130971    ** is satisfied.
130972    **
130973    ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
130974    ** that there is no possibility of transforming the OR clause into an
130975    ** IN operator because one or more terms in the OR clause contain
130976    ** something other than == on a column in the single table.  The 1-bit
130977    ** case means that every term of the OR clause is of the form
130978    ** "table.column=expr" for some single table.  The one bit that is set
130979    ** will correspond to the common table.  We still need to check to make
130980    ** sure the same column is used on all terms.  The 2-bit case is when
130981    ** the all terms are of the form "table1.column=table2.column".  It
130982    ** might be possible to form an IN operator with either table1.column
130983    ** or table2.column as the LHS if either is common to every term of
130984    ** the OR clause.
130985    **
130986    ** Note that terms of the form "table.column1=table.column2" (the
130987    ** same table on both sizes of the ==) cannot be optimized.
130988    */
130989    if( chngToIN ){
130990      int okToChngToIN = 0;     /* True if the conversion to IN is valid */
130991      int iColumn = -1;         /* Column index on lhs of IN operator */
130992      int iCursor = -1;         /* Table cursor common to all terms */
130993      int j = 0;                /* Loop counter */
130994  
130995      /* Search for a table and column that appears on one side or the
130996      ** other of the == operator in every subterm.  That table and column
130997      ** will be recorded in iCursor and iColumn.  There might not be any
130998      ** such table and column.  Set okToChngToIN if an appropriate table
130999      ** and column is found but leave okToChngToIN false if not found.
131000      */
131001      for(j=0; j<2 && !okToChngToIN; j++){
131002        pOrTerm = pOrWc->a;
131003        for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
131004          assert( pOrTerm->eOperator & WO_EQ );
131005          pOrTerm->wtFlags &= ~TERM_OR_OK;
131006          if( pOrTerm->leftCursor==iCursor ){
131007            /* This is the 2-bit case and we are on the second iteration and
131008            ** current term is from the first iteration.  So skip this term. */
131009            assert( j==1 );
131010            continue;
131011          }
131012          if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
131013                                              pOrTerm->leftCursor))==0 ){
131014            /* This term must be of the form t1.a==t2.b where t2 is in the
131015            ** chngToIN set but t1 is not.  This term will be either preceded
131016            ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
131017            ** and use its inversion. */
131018            testcase( pOrTerm->wtFlags & TERM_COPIED );
131019            testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
131020            assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
131021            continue;
131022          }
131023          iColumn = pOrTerm->u.leftColumn;
131024          iCursor = pOrTerm->leftCursor;
131025          break;
131026        }
131027        if( i<0 ){
131028          /* No candidate table+column was found.  This can only occur
131029          ** on the second iteration */
131030          assert( j==1 );
131031          assert( IsPowerOfTwo(chngToIN) );
131032          assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
131033          break;
131034        }
131035        testcase( j==1 );
131036  
131037        /* We have found a candidate table and column.  Check to see if that
131038        ** table and column is common to every term in the OR clause */
131039        okToChngToIN = 1;
131040        for(; i>=0 && okToChngToIN; i--, pOrTerm++){
131041          assert( pOrTerm->eOperator & WO_EQ );
131042          if( pOrTerm->leftCursor!=iCursor ){
131043            pOrTerm->wtFlags &= ~TERM_OR_OK;
131044          }else if( pOrTerm->u.leftColumn!=iColumn ){
131045            okToChngToIN = 0;
131046          }else{
131047            int affLeft, affRight;
131048            /* If the right-hand side is also a column, then the affinities
131049            ** of both right and left sides must be such that no type
131050            ** conversions are required on the right.  (Ticket #2249)
131051            */
131052            affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
131053            affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
131054            if( affRight!=0 && affRight!=affLeft ){
131055              okToChngToIN = 0;
131056            }else{
131057              pOrTerm->wtFlags |= TERM_OR_OK;
131058            }
131059          }
131060        }
131061      }
131062  
131063      /* At this point, okToChngToIN is true if original pTerm satisfies
131064      ** case 1.  In that case, construct a new virtual term that is 
131065      ** pTerm converted into an IN operator.
131066      */
131067      if( okToChngToIN ){
131068        Expr *pDup;            /* A transient duplicate expression */
131069        ExprList *pList = 0;   /* The RHS of the IN operator */
131070        Expr *pLeft = 0;       /* The LHS of the IN operator */
131071        Expr *pNew;            /* The complete IN operator */
131072  
131073        for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
131074          if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
131075          assert( pOrTerm->eOperator & WO_EQ );
131076          assert( pOrTerm->leftCursor==iCursor );
131077          assert( pOrTerm->u.leftColumn==iColumn );
131078          pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
131079          pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
131080          pLeft = pOrTerm->pExpr->pLeft;
131081        }
131082        assert( pLeft!=0 );
131083        pDup = sqlite3ExprDup(db, pLeft, 0);
131084        pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
131085        if( pNew ){
131086          int idxNew;
131087          transferJoinMarkings(pNew, pExpr);
131088          assert( !ExprHasProperty(pNew, EP_xIsSelect) );
131089          pNew->x.pList = pList;
131090          idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
131091          testcase( idxNew==0 );
131092          exprAnalyze(pSrc, pWC, idxNew);
131093          pTerm = &pWC->a[idxTerm];
131094          markTermAsChild(pWC, idxNew, idxTerm);
131095        }else{
131096          sqlite3ExprListDelete(db, pList);
131097        }
131098        pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 3 */
131099      }
131100    }
131101  }
131102  #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
131103  
131104  /*
131105  ** We already know that pExpr is a binary operator where both operands are
131106  ** column references.  This routine checks to see if pExpr is an equivalence
131107  ** relation:
131108  **   1.  The SQLITE_Transitive optimization must be enabled
131109  **   2.  Must be either an == or an IS operator
131110  **   3.  Not originating in the ON clause of an OUTER JOIN
131111  **   4.  The affinities of A and B must be compatible
131112  **   5a. Both operands use the same collating sequence OR
131113  **   5b. The overall collating sequence is BINARY
131114  ** If this routine returns TRUE, that means that the RHS can be substituted
131115  ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
131116  ** This is an optimization.  No harm comes from returning 0.  But if 1 is
131117  ** returned when it should not be, then incorrect answers might result.
131118  */
131119  static int termIsEquivalence(Parse *pParse, Expr *pExpr){
131120    char aff1, aff2;
131121    CollSeq *pColl;
131122    if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
131123    if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
131124    if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
131125    aff1 = sqlite3ExprAffinity(pExpr->pLeft);
131126    aff2 = sqlite3ExprAffinity(pExpr->pRight);
131127    if( aff1!=aff2
131128     && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
131129    ){
131130      return 0;
131131    }
131132    pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
131133    if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
131134    return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight);
131135  }
131136  
131137  /*
131138  ** Recursively walk the expressions of a SELECT statement and generate
131139  ** a bitmask indicating which tables are used in that expression
131140  ** tree.
131141  */
131142  static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
131143    Bitmask mask = 0;
131144    while( pS ){
131145      SrcList *pSrc = pS->pSrc;
131146      mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
131147      mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
131148      mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
131149      mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
131150      mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
131151      if( ALWAYS(pSrc!=0) ){
131152        int i;
131153        for(i=0; i<pSrc->nSrc; i++){
131154          mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
131155          mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
131156        }
131157      }
131158      pS = pS->pPrior;
131159    }
131160    return mask;
131161  }
131162  
131163  /*
131164  ** Expression pExpr is one operand of a comparison operator that might
131165  ** be useful for indexing.  This routine checks to see if pExpr appears
131166  ** in any index.  Return TRUE (1) if pExpr is an indexed term and return
131167  ** FALSE (0) if not.  If TRUE is returned, also set aiCurCol[0] to the cursor
131168  ** number of the table that is indexed and aiCurCol[1] to the column number
131169  ** of the column that is indexed, or XN_EXPR (-2) if an expression is being
131170  ** indexed.
131171  **
131172  ** If pExpr is a TK_COLUMN column reference, then this routine always returns
131173  ** true even if that particular column is not indexed, because the column
131174  ** might be added to an automatic index later.
131175  */
131176  static SQLITE_NOINLINE int exprMightBeIndexed2(
131177    SrcList *pFrom,        /* The FROM clause */
131178    Bitmask mPrereq,       /* Bitmask of FROM clause terms referenced by pExpr */
131179    int *aiCurCol,         /* Write the referenced table cursor and column here */
131180    Expr *pExpr            /* An operand of a comparison operator */
131181  ){
131182    Index *pIdx;
131183    int i;
131184    int iCur;
131185    for(i=0; mPrereq>1; i++, mPrereq>>=1){}
131186    iCur = pFrom->a[i].iCursor;
131187    for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
131188      if( pIdx->aColExpr==0 ) continue;
131189      for(i=0; i<pIdx->nKeyCol; i++){
131190        if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
131191        if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
131192          aiCurCol[0] = iCur;
131193          aiCurCol[1] = XN_EXPR;
131194          return 1;
131195        }
131196      }
131197    }
131198    return 0;
131199  }
131200  static int exprMightBeIndexed(
131201    SrcList *pFrom,        /* The FROM clause */
131202    Bitmask mPrereq,       /* Bitmask of FROM clause terms referenced by pExpr */
131203    int *aiCurCol,         /* Write the referenced table cursor & column here */
131204    Expr *pExpr,           /* An operand of a comparison operator */
131205    int op                 /* The specific comparison operator */
131206  ){
131207    /* If this expression is a vector to the left or right of a 
131208    ** inequality constraint (>, <, >= or <=), perform the processing 
131209    ** on the first element of the vector.  */
131210    assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
131211    assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
131212    assert( op<=TK_GE );
131213    if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
131214      pExpr = pExpr->x.pList->a[0].pExpr;
131215    }
131216  
131217    if( pExpr->op==TK_COLUMN ){
131218      aiCurCol[0] = pExpr->iTable;
131219      aiCurCol[1] = pExpr->iColumn;
131220      return 1;
131221    }
131222    if( mPrereq==0 ) return 0;                 /* No table references */
131223    if( (mPrereq&(mPrereq-1))!=0 ) return 0;   /* Refs more than one table */
131224    return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
131225  }
131226  
131227  /*
131228  ** The input to this routine is an WhereTerm structure with only the
131229  ** "pExpr" field filled in.  The job of this routine is to analyze the
131230  ** subexpression and populate all the other fields of the WhereTerm
131231  ** structure.
131232  **
131233  ** If the expression is of the form "<expr> <op> X" it gets commuted
131234  ** to the standard form of "X <op> <expr>".
131235  **
131236  ** If the expression is of the form "X <op> Y" where both X and Y are
131237  ** columns, then the original expression is unchanged and a new virtual
131238  ** term of the form "Y <op> X" is added to the WHERE clause and
131239  ** analyzed separately.  The original term is marked with TERM_COPIED
131240  ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
131241  ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
131242  ** is a commuted copy of a prior term.)  The original term has nChild=1
131243  ** and the copy has idxParent set to the index of the original term.
131244  */
131245  static void exprAnalyze(
131246    SrcList *pSrc,            /* the FROM clause */
131247    WhereClause *pWC,         /* the WHERE clause */
131248    int idxTerm               /* Index of the term to be analyzed */
131249  ){
131250    WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
131251    WhereTerm *pTerm;                /* The term to be analyzed */
131252    WhereMaskSet *pMaskSet;          /* Set of table index masks */
131253    Expr *pExpr;                     /* The expression to be analyzed */
131254    Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
131255    Bitmask prereqAll;               /* Prerequesites of pExpr */
131256    Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
131257    Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
131258    int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
131259    int noCase = 0;                  /* uppercase equivalent to lowercase */
131260    int op;                          /* Top-level operator.  pExpr->op */
131261    Parse *pParse = pWInfo->pParse;  /* Parsing context */
131262    sqlite3 *db = pParse->db;        /* Database connection */
131263    unsigned char eOp2;              /* op2 value for LIKE/REGEXP/GLOB */
131264    int nLeft;                       /* Number of elements on left side vector */
131265  
131266    if( db->mallocFailed ){
131267      return;
131268    }
131269    pTerm = &pWC->a[idxTerm];
131270    pMaskSet = &pWInfo->sMaskSet;
131271    pExpr = pTerm->pExpr;
131272    assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
131273    prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
131274    op = pExpr->op;
131275    if( op==TK_IN ){
131276      assert( pExpr->pRight==0 );
131277      if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
131278      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
131279        pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
131280      }else{
131281        pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
131282      }
131283    }else if( op==TK_ISNULL ){
131284      pTerm->prereqRight = 0;
131285    }else{
131286      pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
131287    }
131288    pMaskSet->bVarSelect = 0;
131289    prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
131290    if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
131291    if( ExprHasProperty(pExpr, EP_FromJoin) ){
131292      Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
131293      prereqAll |= x;
131294      extraRight = x-1;  /* ON clause terms may not be used with an index
131295                         ** on left table of a LEFT JOIN.  Ticket #3015 */
131296      if( (prereqAll>>1)>=x ){
131297        sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
131298        return;
131299      }
131300    }
131301    pTerm->prereqAll = prereqAll;
131302    pTerm->leftCursor = -1;
131303    pTerm->iParent = -1;
131304    pTerm->eOperator = 0;
131305    if( allowedOp(op) ){
131306      int aiCurCol[2];
131307      Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
131308      Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
131309      u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
131310  
131311      if( pTerm->iField>0 ){
131312        assert( op==TK_IN );
131313        assert( pLeft->op==TK_VECTOR );
131314        pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
131315      }
131316  
131317      if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
131318        pTerm->leftCursor = aiCurCol[0];
131319        pTerm->u.leftColumn = aiCurCol[1];
131320        pTerm->eOperator = operatorMask(op) & opMask;
131321      }
131322      if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
131323      if( pRight 
131324       && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
131325      ){
131326        WhereTerm *pNew;
131327        Expr *pDup;
131328        u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
131329        assert( pTerm->iField==0 );
131330        if( pTerm->leftCursor>=0 ){
131331          int idxNew;
131332          pDup = sqlite3ExprDup(db, pExpr, 0);
131333          if( db->mallocFailed ){
131334            sqlite3ExprDelete(db, pDup);
131335            return;
131336          }
131337          idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
131338          if( idxNew==0 ) return;
131339          pNew = &pWC->a[idxNew];
131340          markTermAsChild(pWC, idxNew, idxTerm);
131341          if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
131342          pTerm = &pWC->a[idxTerm];
131343          pTerm->wtFlags |= TERM_COPIED;
131344  
131345          if( termIsEquivalence(pParse, pDup) ){
131346            pTerm->eOperator |= WO_EQUIV;
131347            eExtraOp = WO_EQUIV;
131348          }
131349        }else{
131350          pDup = pExpr;
131351          pNew = pTerm;
131352        }
131353        exprCommute(pParse, pDup);
131354        pNew->leftCursor = aiCurCol[0];
131355        pNew->u.leftColumn = aiCurCol[1];
131356        testcase( (prereqLeft | extraRight) != prereqLeft );
131357        pNew->prereqRight = prereqLeft | extraRight;
131358        pNew->prereqAll = prereqAll;
131359        pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
131360      }
131361    }
131362  
131363  #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
131364    /* If a term is the BETWEEN operator, create two new virtual terms
131365    ** that define the range that the BETWEEN implements.  For example:
131366    **
131367    **      a BETWEEN b AND c
131368    **
131369    ** is converted into:
131370    **
131371    **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
131372    **
131373    ** The two new terms are added onto the end of the WhereClause object.
131374    ** The new terms are "dynamic" and are children of the original BETWEEN
131375    ** term.  That means that if the BETWEEN term is coded, the children are
131376    ** skipped.  Or, if the children are satisfied by an index, the original
131377    ** BETWEEN term is skipped.
131378    */
131379    else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
131380      ExprList *pList = pExpr->x.pList;
131381      int i;
131382      static const u8 ops[] = {TK_GE, TK_LE};
131383      assert( pList!=0 );
131384      assert( pList->nExpr==2 );
131385      for(i=0; i<2; i++){
131386        Expr *pNewExpr;
131387        int idxNew;
131388        pNewExpr = sqlite3PExpr(pParse, ops[i], 
131389                               sqlite3ExprDup(db, pExpr->pLeft, 0),
131390                               sqlite3ExprDup(db, pList->a[i].pExpr, 0));
131391        transferJoinMarkings(pNewExpr, pExpr);
131392        idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
131393        testcase( idxNew==0 );
131394        exprAnalyze(pSrc, pWC, idxNew);
131395        pTerm = &pWC->a[idxTerm];
131396        markTermAsChild(pWC, idxNew, idxTerm);
131397      }
131398    }
131399  #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
131400  
131401  #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
131402    /* Analyze a term that is composed of two or more subterms connected by
131403    ** an OR operator.
131404    */
131405    else if( pExpr->op==TK_OR ){
131406      assert( pWC->op==TK_AND );
131407      exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
131408      pTerm = &pWC->a[idxTerm];
131409    }
131410  #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
131411  
131412  #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
131413    /* Add constraints to reduce the search space on a LIKE or GLOB
131414    ** operator.
131415    **
131416    ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
131417    **
131418    **          x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
131419    **
131420    ** The last character of the prefix "abc" is incremented to form the
131421    ** termination condition "abd".  If case is not significant (the default
131422    ** for LIKE) then the lower-bound is made all uppercase and the upper-
131423    ** bound is made all lowercase so that the bounds also work when comparing
131424    ** BLOBs.
131425    */
131426    if( pWC->op==TK_AND 
131427     && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
131428    ){
131429      Expr *pLeft;       /* LHS of LIKE/GLOB operator */
131430      Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
131431      Expr *pNewExpr1;
131432      Expr *pNewExpr2;
131433      int idxNew1;
131434      int idxNew2;
131435      const char *zCollSeqName;     /* Name of collating sequence */
131436      const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
131437  
131438      pLeft = pExpr->x.pList->a[1].pExpr;
131439      pStr2 = sqlite3ExprDup(db, pStr1, 0);
131440  
131441      /* Convert the lower bound to upper-case and the upper bound to
131442      ** lower-case (upper-case is less than lower-case in ASCII) so that
131443      ** the range constraints also work for BLOBs
131444      */
131445      if( noCase && !pParse->db->mallocFailed ){
131446        int i;
131447        char c;
131448        pTerm->wtFlags |= TERM_LIKE;
131449        for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
131450          pStr1->u.zToken[i] = sqlite3Toupper(c);
131451          pStr2->u.zToken[i] = sqlite3Tolower(c);
131452        }
131453      }
131454  
131455      if( !db->mallocFailed ){
131456        u8 c, *pC;       /* Last character before the first wildcard */
131457        pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
131458        c = *pC;
131459        if( noCase ){
131460          /* The point is to increment the last character before the first
131461          ** wildcard.  But if we increment '@', that will push it into the
131462          ** alphabetic range where case conversions will mess up the 
131463          ** inequality.  To avoid this, make sure to also run the full
131464          ** LIKE on all candidate expressions by clearing the isComplete flag
131465          */
131466          if( c=='A'-1 ) isComplete = 0;
131467          c = sqlite3UpperToLower[c];
131468        }
131469        *pC = c + 1;
131470      }
131471      zCollSeqName = noCase ? "NOCASE" : "BINARY";
131472      pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
131473      pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
131474             sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
131475             pStr1);
131476      transferJoinMarkings(pNewExpr1, pExpr);
131477      idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
131478      testcase( idxNew1==0 );
131479      exprAnalyze(pSrc, pWC, idxNew1);
131480      pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
131481      pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
131482             sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
131483             pStr2);
131484      transferJoinMarkings(pNewExpr2, pExpr);
131485      idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
131486      testcase( idxNew2==0 );
131487      exprAnalyze(pSrc, pWC, idxNew2);
131488      pTerm = &pWC->a[idxTerm];
131489      if( isComplete ){
131490        markTermAsChild(pWC, idxNew1, idxTerm);
131491        markTermAsChild(pWC, idxNew2, idxTerm);
131492      }
131493    }
131494  #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
131495  
131496  #ifndef SQLITE_OMIT_VIRTUALTABLE
131497    /* Add a WO_AUX auxiliary term to the constraint set if the
131498    ** current expression is of the form "column OP expr" where OP
131499    ** is an operator that gets passed into virtual tables but which is
131500    ** not normally optimized for ordinary tables.  In other words, OP
131501    ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL.
131502    ** This information is used by the xBestIndex methods of
131503    ** virtual tables.  The native query optimizer does not attempt
131504    ** to do anything with MATCH functions.
131505    */
131506    if( pWC->op==TK_AND ){
131507      Expr *pRight, *pLeft;
131508      int res = isAuxiliaryVtabOperator(pExpr, &eOp2, &pLeft, &pRight);
131509      while( res-- > 0 ){
131510        int idxNew;
131511        WhereTerm *pNewTerm;
131512        Bitmask prereqColumn, prereqExpr;
131513  
131514        prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
131515        prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
131516        if( (prereqExpr & prereqColumn)==0 ){
131517          Expr *pNewExpr;
131518          pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
131519              0, sqlite3ExprDup(db, pRight, 0));
131520          if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){
131521            ExprSetProperty(pNewExpr, EP_FromJoin);
131522          }
131523          idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
131524          testcase( idxNew==0 );
131525          pNewTerm = &pWC->a[idxNew];
131526          pNewTerm->prereqRight = prereqExpr;
131527          pNewTerm->leftCursor = pLeft->iTable;
131528          pNewTerm->u.leftColumn = pLeft->iColumn;
131529          pNewTerm->eOperator = WO_AUX;
131530          pNewTerm->eMatchOp = eOp2;
131531          markTermAsChild(pWC, idxNew, idxTerm);
131532          pTerm = &pWC->a[idxTerm];
131533          pTerm->wtFlags |= TERM_COPIED;
131534          pNewTerm->prereqAll = pTerm->prereqAll;
131535        }
131536        SWAP(Expr*, pLeft, pRight);
131537      }
131538    }
131539  #endif /* SQLITE_OMIT_VIRTUALTABLE */
131540  
131541    /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
131542    ** new terms for each component comparison - "a = ?" and "b = ?".  The
131543    ** new terms completely replace the original vector comparison, which is
131544    ** no longer used.
131545    **
131546    ** This is only required if at least one side of the comparison operation
131547    ** is not a sub-select.  */
131548    if( pWC->op==TK_AND 
131549    && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
131550    && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
131551    && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
131552    && ( (pExpr->pLeft->flags & EP_xIsSelect)==0 
131553      || (pExpr->pRight->flags & EP_xIsSelect)==0)
131554    ){
131555      int i;
131556      for(i=0; i<nLeft; i++){
131557        int idxNew;
131558        Expr *pNew;
131559        Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
131560        Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
131561  
131562        pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
131563        transferJoinMarkings(pNew, pExpr);
131564        idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
131565        exprAnalyze(pSrc, pWC, idxNew);
131566      }
131567      pTerm = &pWC->a[idxTerm];
131568      pTerm->wtFlags = TERM_CODED|TERM_VIRTUAL;  /* Disable the original */
131569      pTerm->eOperator = 0;
131570    }
131571  
131572    /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
131573    ** a virtual term for each vector component. The expression object
131574    ** used by each such virtual term is pExpr (the full vector IN(...) 
131575    ** expression). The WhereTerm.iField variable identifies the index within
131576    ** the vector on the LHS that the virtual term represents.
131577    **
131578    ** This only works if the RHS is a simple SELECT, not a compound
131579    */
131580    if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
131581     && pExpr->pLeft->op==TK_VECTOR
131582     && pExpr->x.pSelect->pPrior==0
131583    ){
131584      int i;
131585      for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
131586        int idxNew;
131587        idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
131588        pWC->a[idxNew].iField = i+1;
131589        exprAnalyze(pSrc, pWC, idxNew);
131590        markTermAsChild(pWC, idxNew, idxTerm);
131591      }
131592    }
131593  
131594  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
131595    /* When sqlite_stat3 histogram data is available an operator of the
131596    ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
131597    ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
131598    ** virtual term of that form.
131599    **
131600    ** Note that the virtual term must be tagged with TERM_VNULL.
131601    */
131602    if( pExpr->op==TK_NOTNULL
131603     && pExpr->pLeft->op==TK_COLUMN
131604     && pExpr->pLeft->iColumn>=0
131605     && OptimizationEnabled(db, SQLITE_Stat34)
131606    ){
131607      Expr *pNewExpr;
131608      Expr *pLeft = pExpr->pLeft;
131609      int idxNew;
131610      WhereTerm *pNewTerm;
131611  
131612      pNewExpr = sqlite3PExpr(pParse, TK_GT,
131613                              sqlite3ExprDup(db, pLeft, 0),
131614                              sqlite3ExprAlloc(db, TK_NULL, 0, 0));
131615  
131616      idxNew = whereClauseInsert(pWC, pNewExpr,
131617                                TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
131618      if( idxNew ){
131619        pNewTerm = &pWC->a[idxNew];
131620        pNewTerm->prereqRight = 0;
131621        pNewTerm->leftCursor = pLeft->iTable;
131622        pNewTerm->u.leftColumn = pLeft->iColumn;
131623        pNewTerm->eOperator = WO_GT;
131624        markTermAsChild(pWC, idxNew, idxTerm);
131625        pTerm = &pWC->a[idxTerm];
131626        pTerm->wtFlags |= TERM_COPIED;
131627        pNewTerm->prereqAll = pTerm->prereqAll;
131628      }
131629    }
131630  #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
131631  
131632    /* Prevent ON clause terms of a LEFT JOIN from being used to drive
131633    ** an index for tables to the left of the join.
131634    */
131635    testcase( pTerm!=&pWC->a[idxTerm] );
131636    pTerm = &pWC->a[idxTerm];
131637    pTerm->prereqRight |= extraRight;
131638  }
131639  
131640  /***************************************************************************
131641  ** Routines with file scope above.  Interface to the rest of the where.c
131642  ** subsystem follows.
131643  ***************************************************************************/
131644  
131645  /*
131646  ** This routine identifies subexpressions in the WHERE clause where
131647  ** each subexpression is separated by the AND operator or some other
131648  ** operator specified in the op parameter.  The WhereClause structure
131649  ** is filled with pointers to subexpressions.  For example:
131650  **
131651  **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
131652  **           \________/     \_______________/     \________________/
131653  **            slot[0]            slot[1]               slot[2]
131654  **
131655  ** The original WHERE clause in pExpr is unaltered.  All this routine
131656  ** does is make slot[] entries point to substructure within pExpr.
131657  **
131658  ** In the previous sentence and in the diagram, "slot[]" refers to
131659  ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
131660  ** all terms of the WHERE clause.
131661  */
131662  SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
131663    Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
131664    pWC->op = op;
131665    if( pE2==0 ) return;
131666    if( pE2->op!=op ){
131667      whereClauseInsert(pWC, pExpr, 0);
131668    }else{
131669      sqlite3WhereSplit(pWC, pE2->pLeft, op);
131670      sqlite3WhereSplit(pWC, pE2->pRight, op);
131671    }
131672  }
131673  
131674  /*
131675  ** Initialize a preallocated WhereClause structure.
131676  */
131677  SQLITE_PRIVATE void sqlite3WhereClauseInit(
131678    WhereClause *pWC,        /* The WhereClause to be initialized */
131679    WhereInfo *pWInfo        /* The WHERE processing context */
131680  ){
131681    pWC->pWInfo = pWInfo;
131682    pWC->pOuter = 0;
131683    pWC->nTerm = 0;
131684    pWC->nSlot = ArraySize(pWC->aStatic);
131685    pWC->a = pWC->aStatic;
131686  }
131687  
131688  /*
131689  ** Deallocate a WhereClause structure.  The WhereClause structure
131690  ** itself is not freed.  This routine is the inverse of
131691  ** sqlite3WhereClauseInit().
131692  */
131693  SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
131694    int i;
131695    WhereTerm *a;
131696    sqlite3 *db = pWC->pWInfo->pParse->db;
131697    for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
131698      if( a->wtFlags & TERM_DYNAMIC ){
131699        sqlite3ExprDelete(db, a->pExpr);
131700      }
131701      if( a->wtFlags & TERM_ORINFO ){
131702        whereOrInfoDelete(db, a->u.pOrInfo);
131703      }else if( a->wtFlags & TERM_ANDINFO ){
131704        whereAndInfoDelete(db, a->u.pAndInfo);
131705      }
131706    }
131707    if( pWC->a!=pWC->aStatic ){
131708      sqlite3DbFree(db, pWC->a);
131709    }
131710  }
131711  
131712  
131713  /*
131714  ** These routines walk (recursively) an expression tree and generate
131715  ** a bitmask indicating which tables are used in that expression
131716  ** tree.
131717  */
131718  SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
131719    Bitmask mask;
131720    if( p==0 ) return 0;
131721    if( p->op==TK_COLUMN ){
131722      return sqlite3WhereGetMask(pMaskSet, p->iTable);
131723    }
131724    mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
131725    assert( !ExprHasProperty(p, EP_TokenOnly) );
131726    if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
131727    if( p->pRight ){
131728      mask |= sqlite3WhereExprUsage(pMaskSet, p->pRight);
131729      assert( p->x.pList==0 );
131730    }else if( ExprHasProperty(p, EP_xIsSelect) ){
131731      if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
131732      mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
131733    }else if( p->x.pList ){
131734      mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
131735    }
131736    return mask;
131737  }
131738  SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
131739    int i;
131740    Bitmask mask = 0;
131741    if( pList ){
131742      for(i=0; i<pList->nExpr; i++){
131743        mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
131744      }
131745    }
131746    return mask;
131747  }
131748  
131749  
131750  /*
131751  ** Call exprAnalyze on all terms in a WHERE clause.  
131752  **
131753  ** Note that exprAnalyze() might add new virtual terms onto the
131754  ** end of the WHERE clause.  We do not want to analyze these new
131755  ** virtual terms, so start analyzing at the end and work forward
131756  ** so that the added virtual terms are never processed.
131757  */
131758  SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
131759    SrcList *pTabList,       /* the FROM clause */
131760    WhereClause *pWC         /* the WHERE clause to be analyzed */
131761  ){
131762    int i;
131763    for(i=pWC->nTerm-1; i>=0; i--){
131764      exprAnalyze(pTabList, pWC, i);
131765    }
131766  }
131767  
131768  /*
131769  ** For table-valued-functions, transform the function arguments into
131770  ** new WHERE clause terms.  
131771  **
131772  ** Each function argument translates into an equality constraint against
131773  ** a HIDDEN column in the table.
131774  */
131775  SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
131776    Parse *pParse,                    /* Parsing context */
131777    struct SrcList_item *pItem,       /* The FROM clause term to process */
131778    WhereClause *pWC                  /* Xfer function arguments to here */
131779  ){
131780    Table *pTab;
131781    int j, k;
131782    ExprList *pArgs;
131783    Expr *pColRef;
131784    Expr *pTerm;
131785    if( pItem->fg.isTabFunc==0 ) return;
131786    pTab = pItem->pTab;
131787    assert( pTab!=0 );
131788    pArgs = pItem->u1.pFuncArg;
131789    if( pArgs==0 ) return;
131790    for(j=k=0; j<pArgs->nExpr; j++){
131791      while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
131792      if( k>=pTab->nCol ){
131793        sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
131794                        pTab->zName, j);
131795        return;
131796      }
131797      pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
131798      if( pColRef==0 ) return;
131799      pColRef->iTable = pItem->iCursor;
131800      pColRef->iColumn = k++;
131801      pColRef->pTab = pTab;
131802      pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
131803                           sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0));
131804      whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
131805    }
131806  }
131807  
131808  /************** End of whereexpr.c *******************************************/
131809  /************** Begin file where.c *******************************************/
131810  /*
131811  ** 2001 September 15
131812  **
131813  ** The author disclaims copyright to this source code.  In place of
131814  ** a legal notice, here is a blessing:
131815  **
131816  **    May you do good and not evil.
131817  **    May you find forgiveness for yourself and forgive others.
131818  **    May you share freely, never taking more than you give.
131819  **
131820  *************************************************************************
131821  ** This module contains C code that generates VDBE code used to process
131822  ** the WHERE clause of SQL statements.  This module is responsible for
131823  ** generating the code that loops through a table looking for applicable
131824  ** rows.  Indices are selected and used to speed the search when doing
131825  ** so is applicable.  Because this module is responsible for selecting
131826  ** indices, you might also think of this module as the "query optimizer".
131827  */
131828  /* #include "sqliteInt.h" */
131829  /* #include "whereInt.h" */
131830  
131831  /* Forward declaration of methods */
131832  static int whereLoopResize(sqlite3*, WhereLoop*, int);
131833  
131834  /* Test variable that can be set to enable WHERE tracing */
131835  #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
131836  /***/ int sqlite3WhereTrace = 0;
131837  #endif
131838  
131839  
131840  /*
131841  ** Return the estimated number of output rows from a WHERE clause
131842  */
131843  SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
131844    return pWInfo->nRowOut;
131845  }
131846  
131847  /*
131848  ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
131849  ** WHERE clause returns outputs for DISTINCT processing.
131850  */
131851  SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
131852    return pWInfo->eDistinct;
131853  }
131854  
131855  /*
131856  ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
131857  ** Return FALSE if the output needs to be sorted.
131858  */
131859  SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
131860    return pWInfo->nOBSat;
131861  }
131862  
131863  /*
131864  ** Return TRUE if the innermost loop of the WHERE clause implementation
131865  ** returns rows in ORDER BY order for complete run of the inner loop.
131866  **
131867  ** Across multiple iterations of outer loops, the output rows need not be
131868  ** sorted.  As long as rows are sorted for just the innermost loop, this
131869  ** routine can return TRUE.
131870  */
131871  SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo *pWInfo){
131872    return pWInfo->bOrderedInnerLoop;
131873  }
131874  
131875  /*
131876  ** Return the VDBE address or label to jump to in order to continue
131877  ** immediately with the next row of a WHERE clause.
131878  */
131879  SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
131880    assert( pWInfo->iContinue!=0 );
131881    return pWInfo->iContinue;
131882  }
131883  
131884  /*
131885  ** Return the VDBE address or label to jump to in order to break
131886  ** out of a WHERE loop.
131887  */
131888  SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
131889    return pWInfo->iBreak;
131890  }
131891  
131892  /*
131893  ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
131894  ** operate directly on the rowis returned by a WHERE clause.  Return
131895  ** ONEPASS_SINGLE (1) if the statement can operation directly because only
131896  ** a single row is to be changed.  Return ONEPASS_MULTI (2) if the one-pass
131897  ** optimization can be used on multiple 
131898  **
131899  ** If the ONEPASS optimization is used (if this routine returns true)
131900  ** then also write the indices of open cursors used by ONEPASS
131901  ** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data
131902  ** table and iaCur[1] gets the cursor used by an auxiliary index.
131903  ** Either value may be -1, indicating that cursor is not used.
131904  ** Any cursors returned will have been opened for writing.
131905  **
131906  ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
131907  ** unable to use the ONEPASS optimization.
131908  */
131909  SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
131910    memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
131911  #ifdef WHERETRACE_ENABLED
131912    if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
131913      sqlite3DebugPrintf("%s cursors: %d %d\n",
131914           pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
131915           aiCur[0], aiCur[1]);
131916    }
131917  #endif
131918    return pWInfo->eOnePass;
131919  }
131920  
131921  /*
131922  ** Move the content of pSrc into pDest
131923  */
131924  static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
131925    pDest->n = pSrc->n;
131926    memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
131927  }
131928  
131929  /*
131930  ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
131931  **
131932  ** The new entry might overwrite an existing entry, or it might be
131933  ** appended, or it might be discarded.  Do whatever is the right thing
131934  ** so that pSet keeps the N_OR_COST best entries seen so far.
131935  */
131936  static int whereOrInsert(
131937    WhereOrSet *pSet,      /* The WhereOrSet to be updated */
131938    Bitmask prereq,        /* Prerequisites of the new entry */
131939    LogEst rRun,           /* Run-cost of the new entry */
131940    LogEst nOut            /* Number of outputs for the new entry */
131941  ){
131942    u16 i;
131943    WhereOrCost *p;
131944    for(i=pSet->n, p=pSet->a; i>0; i--, p++){
131945      if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
131946        goto whereOrInsert_done;
131947      }
131948      if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
131949        return 0;
131950      }
131951    }
131952    if( pSet->n<N_OR_COST ){
131953      p = &pSet->a[pSet->n++];
131954      p->nOut = nOut;
131955    }else{
131956      p = pSet->a;
131957      for(i=1; i<pSet->n; i++){
131958        if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
131959      }
131960      if( p->rRun<=rRun ) return 0;
131961    }
131962  whereOrInsert_done:
131963    p->prereq = prereq;
131964    p->rRun = rRun;
131965    if( p->nOut>nOut ) p->nOut = nOut;
131966    return 1;
131967  }
131968  
131969  /*
131970  ** Return the bitmask for the given cursor number.  Return 0 if
131971  ** iCursor is not in the set.
131972  */
131973  SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
131974    int i;
131975    assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
131976    for(i=0; i<pMaskSet->n; i++){
131977      if( pMaskSet->ix[i]==iCursor ){
131978        return MASKBIT(i);
131979      }
131980    }
131981    return 0;
131982  }
131983  
131984  /*
131985  ** Create a new mask for cursor iCursor.
131986  **
131987  ** There is one cursor per table in the FROM clause.  The number of
131988  ** tables in the FROM clause is limited by a test early in the
131989  ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
131990  ** array will never overflow.
131991  */
131992  static void createMask(WhereMaskSet *pMaskSet, int iCursor){
131993    assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
131994    pMaskSet->ix[pMaskSet->n++] = iCursor;
131995  }
131996  
131997  /*
131998  ** Advance to the next WhereTerm that matches according to the criteria
131999  ** established when the pScan object was initialized by whereScanInit().
132000  ** Return NULL if there are no more matching WhereTerms.
132001  */
132002  static WhereTerm *whereScanNext(WhereScan *pScan){
132003    int iCur;            /* The cursor on the LHS of the term */
132004    i16 iColumn;         /* The column on the LHS of the term.  -1 for IPK */
132005    Expr *pX;            /* An expression being tested */
132006    WhereClause *pWC;    /* Shorthand for pScan->pWC */
132007    WhereTerm *pTerm;    /* The term being tested */
132008    int k = pScan->k;    /* Where to start scanning */
132009  
132010    assert( pScan->iEquiv<=pScan->nEquiv );
132011    pWC = pScan->pWC;
132012    while(1){
132013      iColumn = pScan->aiColumn[pScan->iEquiv-1];
132014      iCur = pScan->aiCur[pScan->iEquiv-1];
132015      assert( pWC!=0 );
132016      do{
132017        for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
132018          if( pTerm->leftCursor==iCur
132019           && pTerm->u.leftColumn==iColumn
132020           && (iColumn!=XN_EXPR
132021               || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,
132022                                         pScan->pIdxExpr,iCur)==0)
132023           && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
132024          ){
132025            if( (pTerm->eOperator & WO_EQUIV)!=0
132026             && pScan->nEquiv<ArraySize(pScan->aiCur)
132027             && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
132028            ){
132029              int j;
132030              for(j=0; j<pScan->nEquiv; j++){
132031                if( pScan->aiCur[j]==pX->iTable
132032                 && pScan->aiColumn[j]==pX->iColumn ){
132033                    break;
132034                }
132035              }
132036              if( j==pScan->nEquiv ){
132037                pScan->aiCur[j] = pX->iTable;
132038                pScan->aiColumn[j] = pX->iColumn;
132039                pScan->nEquiv++;
132040              }
132041            }
132042            if( (pTerm->eOperator & pScan->opMask)!=0 ){
132043              /* Verify the affinity and collating sequence match */
132044              if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
132045                CollSeq *pColl;
132046                Parse *pParse = pWC->pWInfo->pParse;
132047                pX = pTerm->pExpr;
132048                if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
132049                  continue;
132050                }
132051                assert(pX->pLeft);
132052                pColl = sqlite3BinaryCompareCollSeq(pParse,
132053                                                    pX->pLeft, pX->pRight);
132054                if( pColl==0 ) pColl = pParse->db->pDfltColl;
132055                if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
132056                  continue;
132057                }
132058              }
132059              if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
132060               && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
132061               && pX->iTable==pScan->aiCur[0]
132062               && pX->iColumn==pScan->aiColumn[0]
132063              ){
132064                testcase( pTerm->eOperator & WO_IS );
132065                continue;
132066              }
132067              pScan->pWC = pWC;
132068              pScan->k = k+1;
132069              return pTerm;
132070            }
132071          }
132072        }
132073        pWC = pWC->pOuter;
132074        k = 0;
132075      }while( pWC!=0 );
132076      if( pScan->iEquiv>=pScan->nEquiv ) break;
132077      pWC = pScan->pOrigWC;
132078      k = 0;
132079      pScan->iEquiv++;
132080    }
132081    return 0;
132082  }
132083  
132084  /*
132085  ** Initialize a WHERE clause scanner object.  Return a pointer to the
132086  ** first match.  Return NULL if there are no matches.
132087  **
132088  ** The scanner will be searching the WHERE clause pWC.  It will look
132089  ** for terms of the form "X <op> <expr>" where X is column iColumn of table
132090  ** iCur.   Or if pIdx!=0 then X is column iColumn of index pIdx.  pIdx
132091  ** must be one of the indexes of table iCur.
132092  **
132093  ** The <op> must be one of the operators described by opMask.
132094  **
132095  ** If the search is for X and the WHERE clause contains terms of the
132096  ** form X=Y then this routine might also return terms of the form
132097  ** "Y <op> <expr>".  The number of levels of transitivity is limited,
132098  ** but is enough to handle most commonly occurring SQL statements.
132099  **
132100  ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
132101  ** index pIdx.
132102  */
132103  static WhereTerm *whereScanInit(
132104    WhereScan *pScan,       /* The WhereScan object being initialized */
132105    WhereClause *pWC,       /* The WHERE clause to be scanned */
132106    int iCur,               /* Cursor to scan for */
132107    int iColumn,            /* Column to scan for */
132108    u32 opMask,             /* Operator(s) to scan for */
132109    Index *pIdx             /* Must be compatible with this index */
132110  ){
132111    pScan->pOrigWC = pWC;
132112    pScan->pWC = pWC;
132113    pScan->pIdxExpr = 0;
132114    pScan->idxaff = 0;
132115    pScan->zCollName = 0;
132116    if( pIdx ){
132117      int j = iColumn;
132118      iColumn = pIdx->aiColumn[j];
132119      if( iColumn==XN_EXPR ){
132120        pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
132121        pScan->zCollName = pIdx->azColl[j];
132122      }else if( iColumn==pIdx->pTable->iPKey ){
132123        iColumn = XN_ROWID;
132124      }else if( iColumn>=0 ){
132125        pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
132126        pScan->zCollName = pIdx->azColl[j];
132127      }
132128    }else if( iColumn==XN_EXPR ){
132129      return 0;
132130    }
132131    pScan->opMask = opMask;
132132    pScan->k = 0;
132133    pScan->aiCur[0] = iCur;
132134    pScan->aiColumn[0] = iColumn;
132135    pScan->nEquiv = 1;
132136    pScan->iEquiv = 1;
132137    return whereScanNext(pScan);
132138  }
132139  
132140  /*
132141  ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
132142  ** where X is a reference to the iColumn of table iCur or of index pIdx
132143  ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
132144  ** the op parameter.  Return a pointer to the term.  Return 0 if not found.
132145  **
132146  ** If pIdx!=0 then it must be one of the indexes of table iCur.  
132147  ** Search for terms matching the iColumn-th column of pIdx
132148  ** rather than the iColumn-th column of table iCur.
132149  **
132150  ** The term returned might by Y=<expr> if there is another constraint in
132151  ** the WHERE clause that specifies that X=Y.  Any such constraints will be
132152  ** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
132153  ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
132154  ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
132155  ** other equivalent values.  Hence a search for X will return <expr> if X=A1
132156  ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
132157  **
132158  ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
132159  ** then try for the one with no dependencies on <expr> - in other words where
132160  ** <expr> is a constant expression of some kind.  Only return entries of
132161  ** the form "X <op> Y" where Y is a column in another table if no terms of
132162  ** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
132163  ** exist, try to return a term that does not use WO_EQUIV.
132164  */
132165  SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
132166    WhereClause *pWC,     /* The WHERE clause to be searched */
132167    int iCur,             /* Cursor number of LHS */
132168    int iColumn,          /* Column number of LHS */
132169    Bitmask notReady,     /* RHS must not overlap with this mask */
132170    u32 op,               /* Mask of WO_xx values describing operator */
132171    Index *pIdx           /* Must be compatible with this index, if not NULL */
132172  ){
132173    WhereTerm *pResult = 0;
132174    WhereTerm *p;
132175    WhereScan scan;
132176  
132177    p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
132178    op &= WO_EQ|WO_IS;
132179    while( p ){
132180      if( (p->prereqRight & notReady)==0 ){
132181        if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
132182          testcase( p->eOperator & WO_IS );
132183          return p;
132184        }
132185        if( pResult==0 ) pResult = p;
132186      }
132187      p = whereScanNext(&scan);
132188    }
132189    return pResult;
132190  }
132191  
132192  /*
132193  ** This function searches pList for an entry that matches the iCol-th column
132194  ** of index pIdx.
132195  **
132196  ** If such an expression is found, its index in pList->a[] is returned. If
132197  ** no expression is found, -1 is returned.
132198  */
132199  static int findIndexCol(
132200    Parse *pParse,                  /* Parse context */
132201    ExprList *pList,                /* Expression list to search */
132202    int iBase,                      /* Cursor for table associated with pIdx */
132203    Index *pIdx,                    /* Index to match column of */
132204    int iCol                        /* Column of index to match */
132205  ){
132206    int i;
132207    const char *zColl = pIdx->azColl[iCol];
132208  
132209    for(i=0; i<pList->nExpr; i++){
132210      Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
132211      if( p->op==TK_COLUMN
132212       && p->iColumn==pIdx->aiColumn[iCol]
132213       && p->iTable==iBase
132214      ){
132215        CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr);
132216        if( 0==sqlite3StrICmp(pColl->zName, zColl) ){
132217          return i;
132218        }
132219      }
132220    }
132221  
132222    return -1;
132223  }
132224  
132225  /*
132226  ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
132227  */
132228  static int indexColumnNotNull(Index *pIdx, int iCol){
132229    int j;
132230    assert( pIdx!=0 );
132231    assert( iCol>=0 && iCol<pIdx->nColumn );
132232    j = pIdx->aiColumn[iCol];
132233    if( j>=0 ){
132234      return pIdx->pTable->aCol[j].notNull;
132235    }else if( j==(-1) ){
132236      return 1;
132237    }else{
132238      assert( j==(-2) );
132239      return 0;  /* Assume an indexed expression can always yield a NULL */
132240  
132241    }
132242  }
132243  
132244  /*
132245  ** Return true if the DISTINCT expression-list passed as the third argument
132246  ** is redundant.
132247  **
132248  ** A DISTINCT list is redundant if any subset of the columns in the
132249  ** DISTINCT list are collectively unique and individually non-null.
132250  */
132251  static int isDistinctRedundant(
132252    Parse *pParse,            /* Parsing context */
132253    SrcList *pTabList,        /* The FROM clause */
132254    WhereClause *pWC,         /* The WHERE clause */
132255    ExprList *pDistinct       /* The result set that needs to be DISTINCT */
132256  ){
132257    Table *pTab;
132258    Index *pIdx;
132259    int i;                          
132260    int iBase;
132261  
132262    /* If there is more than one table or sub-select in the FROM clause of
132263    ** this query, then it will not be possible to show that the DISTINCT 
132264    ** clause is redundant. */
132265    if( pTabList->nSrc!=1 ) return 0;
132266    iBase = pTabList->a[0].iCursor;
132267    pTab = pTabList->a[0].pTab;
132268  
132269    /* If any of the expressions is an IPK column on table iBase, then return 
132270    ** true. Note: The (p->iTable==iBase) part of this test may be false if the
132271    ** current SELECT is a correlated sub-query.
132272    */
132273    for(i=0; i<pDistinct->nExpr; i++){
132274      Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
132275      if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
132276    }
132277  
132278    /* Loop through all indices on the table, checking each to see if it makes
132279    ** the DISTINCT qualifier redundant. It does so if:
132280    **
132281    **   1. The index is itself UNIQUE, and
132282    **
132283    **   2. All of the columns in the index are either part of the pDistinct
132284    **      list, or else the WHERE clause contains a term of the form "col=X",
132285    **      where X is a constant value. The collation sequences of the
132286    **      comparison and select-list expressions must match those of the index.
132287    **
132288    **   3. All of those index columns for which the WHERE clause does not
132289    **      contain a "col=X" term are subject to a NOT NULL constraint.
132290    */
132291    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
132292      if( !IsUniqueIndex(pIdx) ) continue;
132293      for(i=0; i<pIdx->nKeyCol; i++){
132294        if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
132295          if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
132296          if( indexColumnNotNull(pIdx, i)==0 ) break;
132297        }
132298      }
132299      if( i==pIdx->nKeyCol ){
132300        /* This index implies that the DISTINCT qualifier is redundant. */
132301        return 1;
132302      }
132303    }
132304  
132305    return 0;
132306  }
132307  
132308  
132309  /*
132310  ** Estimate the logarithm of the input value to base 2.
132311  */
132312  static LogEst estLog(LogEst N){
132313    return N<=10 ? 0 : sqlite3LogEst(N) - 33;
132314  }
132315  
132316  /*
132317  ** Convert OP_Column opcodes to OP_Copy in previously generated code.
132318  **
132319  ** This routine runs over generated VDBE code and translates OP_Column
132320  ** opcodes into OP_Copy when the table is being accessed via co-routine 
132321  ** instead of via table lookup.
132322  **
132323  ** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
132324  ** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
132325  ** then each OP_Rowid is transformed into an instruction to increment the
132326  ** value stored in its output register.
132327  */
132328  static void translateColumnToCopy(
132329    Parse *pParse,      /* Parsing context */
132330    int iStart,         /* Translate from this opcode to the end */
132331    int iTabCur,        /* OP_Column/OP_Rowid references to this table */
132332    int iRegister,      /* The first column is in this register */
132333    int bIncrRowid      /* If non-zero, transform OP_rowid to OP_AddImm(1) */
132334  ){
132335    Vdbe *v = pParse->pVdbe;
132336    VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
132337    int iEnd = sqlite3VdbeCurrentAddr(v);
132338    if( pParse->db->mallocFailed ) return;
132339    for(; iStart<iEnd; iStart++, pOp++){
132340      if( pOp->p1!=iTabCur ) continue;
132341      if( pOp->opcode==OP_Column ){
132342        pOp->opcode = OP_Copy;
132343        pOp->p1 = pOp->p2 + iRegister;
132344        pOp->p2 = pOp->p3;
132345        pOp->p3 = 0;
132346      }else if( pOp->opcode==OP_Rowid ){
132347        if( bIncrRowid ){
132348          /* Increment the value stored in the P2 operand of the OP_Rowid. */
132349          pOp->opcode = OP_AddImm;
132350          pOp->p1 = pOp->p2;
132351          pOp->p2 = 1;
132352        }else{
132353          pOp->opcode = OP_Null;
132354          pOp->p1 = 0;
132355          pOp->p3 = 0;
132356        }
132357      }
132358    }
132359  }
132360  
132361  /*
132362  ** Two routines for printing the content of an sqlite3_index_info
132363  ** structure.  Used for testing and debugging only.  If neither
132364  ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
132365  ** are no-ops.
132366  */
132367  #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
132368  static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
132369    int i;
132370    if( !sqlite3WhereTrace ) return;
132371    for(i=0; i<p->nConstraint; i++){
132372      sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
132373         i,
132374         p->aConstraint[i].iColumn,
132375         p->aConstraint[i].iTermOffset,
132376         p->aConstraint[i].op,
132377         p->aConstraint[i].usable);
132378    }
132379    for(i=0; i<p->nOrderBy; i++){
132380      sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
132381         i,
132382         p->aOrderBy[i].iColumn,
132383         p->aOrderBy[i].desc);
132384    }
132385  }
132386  static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
132387    int i;
132388    if( !sqlite3WhereTrace ) return;
132389    for(i=0; i<p->nConstraint; i++){
132390      sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
132391         i,
132392         p->aConstraintUsage[i].argvIndex,
132393         p->aConstraintUsage[i].omit);
132394    }
132395    sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
132396    sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
132397    sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
132398    sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
132399    sqlite3DebugPrintf("  estimatedRows=%lld\n", p->estimatedRows);
132400  }
132401  #else
132402  #define TRACE_IDX_INPUTS(A)
132403  #define TRACE_IDX_OUTPUTS(A)
132404  #endif
132405  
132406  #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
132407  /*
132408  ** Return TRUE if the WHERE clause term pTerm is of a form where it
132409  ** could be used with an index to access pSrc, assuming an appropriate
132410  ** index existed.
132411  */
132412  static int termCanDriveIndex(
132413    WhereTerm *pTerm,              /* WHERE clause term to check */
132414    struct SrcList_item *pSrc,     /* Table we are trying to access */
132415    Bitmask notReady               /* Tables in outer loops of the join */
132416  ){
132417    char aff;
132418    if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
132419    if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
132420    if( (pSrc->fg.jointype & JT_LEFT) 
132421     && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
132422     && (pTerm->eOperator & WO_IS)
132423    ){
132424      /* Cannot use an IS term from the WHERE clause as an index driver for
132425      ** the RHS of a LEFT JOIN. Such a term can only be used if it is from
132426      ** the ON clause.  */
132427      return 0;
132428    }
132429    if( (pTerm->prereqRight & notReady)!=0 ) return 0;
132430    if( pTerm->u.leftColumn<0 ) return 0;
132431    aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
132432    if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
132433    testcase( pTerm->pExpr->op==TK_IS );
132434    return 1;
132435  }
132436  #endif
132437  
132438  
132439  #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
132440  /*
132441  ** Generate code to construct the Index object for an automatic index
132442  ** and to set up the WhereLevel object pLevel so that the code generator
132443  ** makes use of the automatic index.
132444  */
132445  static void constructAutomaticIndex(
132446    Parse *pParse,              /* The parsing context */
132447    WhereClause *pWC,           /* The WHERE clause */
132448    struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
132449    Bitmask notReady,           /* Mask of cursors that are not available */
132450    WhereLevel *pLevel          /* Write new index here */
132451  ){
132452    int nKeyCol;                /* Number of columns in the constructed index */
132453    WhereTerm *pTerm;           /* A single term of the WHERE clause */
132454    WhereTerm *pWCEnd;          /* End of pWC->a[] */
132455    Index *pIdx;                /* Object describing the transient index */
132456    Vdbe *v;                    /* Prepared statement under construction */
132457    int addrInit;               /* Address of the initialization bypass jump */
132458    Table *pTable;              /* The table being indexed */
132459    int addrTop;                /* Top of the index fill loop */
132460    int regRecord;              /* Register holding an index record */
132461    int n;                      /* Column counter */
132462    int i;                      /* Loop counter */
132463    int mxBitCol;               /* Maximum column in pSrc->colUsed */
132464    CollSeq *pColl;             /* Collating sequence to on a column */
132465    WhereLoop *pLoop;           /* The Loop object */
132466    char *zNotUsed;             /* Extra space on the end of pIdx */
132467    Bitmask idxCols;            /* Bitmap of columns used for indexing */
132468    Bitmask extraCols;          /* Bitmap of additional columns */
132469    u8 sentWarning = 0;         /* True if a warnning has been issued */
132470    Expr *pPartial = 0;         /* Partial Index Expression */
132471    int iContinue = 0;          /* Jump here to skip excluded rows */
132472    struct SrcList_item *pTabItem;  /* FROM clause term being indexed */
132473    int addrCounter = 0;        /* Address where integer counter is initialized */
132474    int regBase;                /* Array of registers where record is assembled */
132475  
132476    /* Generate code to skip over the creation and initialization of the
132477    ** transient index on 2nd and subsequent iterations of the loop. */
132478    v = pParse->pVdbe;
132479    assert( v!=0 );
132480    addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
132481  
132482    /* Count the number of columns that will be added to the index
132483    ** and used to match WHERE clause constraints */
132484    nKeyCol = 0;
132485    pTable = pSrc->pTab;
132486    pWCEnd = &pWC->a[pWC->nTerm];
132487    pLoop = pLevel->pWLoop;
132488    idxCols = 0;
132489    for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
132490      Expr *pExpr = pTerm->pExpr;
132491      assert( !ExprHasProperty(pExpr, EP_FromJoin)    /* prereq always non-zero */
132492           || pExpr->iRightJoinTable!=pSrc->iCursor   /*   for the right-hand   */
132493           || pLoop->prereq!=0 );                     /*   table of a LEFT JOIN */
132494      if( pLoop->prereq==0
132495       && (pTerm->wtFlags & TERM_VIRTUAL)==0
132496       && !ExprHasProperty(pExpr, EP_FromJoin)
132497       && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
132498        pPartial = sqlite3ExprAnd(pParse->db, pPartial,
132499                                  sqlite3ExprDup(pParse->db, pExpr, 0));
132500      }
132501      if( termCanDriveIndex(pTerm, pSrc, notReady) ){
132502        int iCol = pTerm->u.leftColumn;
132503        Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
132504        testcase( iCol==BMS );
132505        testcase( iCol==BMS-1 );
132506        if( !sentWarning ){
132507          sqlite3_log(SQLITE_WARNING_AUTOINDEX,
132508              "automatic index on %s(%s)", pTable->zName,
132509              pTable->aCol[iCol].zName);
132510          sentWarning = 1;
132511        }
132512        if( (idxCols & cMask)==0 ){
132513          if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
132514            goto end_auto_index_create;
132515          }
132516          pLoop->aLTerm[nKeyCol++] = pTerm;
132517          idxCols |= cMask;
132518        }
132519      }
132520    }
132521    assert( nKeyCol>0 );
132522    pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
132523    pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
132524                       | WHERE_AUTO_INDEX;
132525  
132526    /* Count the number of additional columns needed to create a
132527    ** covering index.  A "covering index" is an index that contains all
132528    ** columns that are needed by the query.  With a covering index, the
132529    ** original table never needs to be accessed.  Automatic indices must
132530    ** be a covering index because the index will not be updated if the
132531    ** original table changes and the index and table cannot both be used
132532    ** if they go out of sync.
132533    */
132534    extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
132535    mxBitCol = MIN(BMS-1,pTable->nCol);
132536    testcase( pTable->nCol==BMS-1 );
132537    testcase( pTable->nCol==BMS-2 );
132538    for(i=0; i<mxBitCol; i++){
132539      if( extraCols & MASKBIT(i) ) nKeyCol++;
132540    }
132541    if( pSrc->colUsed & MASKBIT(BMS-1) ){
132542      nKeyCol += pTable->nCol - BMS + 1;
132543    }
132544  
132545    /* Construct the Index object to describe this index */
132546    pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
132547    if( pIdx==0 ) goto end_auto_index_create;
132548    pLoop->u.btree.pIndex = pIdx;
132549    pIdx->zName = "auto-index";
132550    pIdx->pTable = pTable;
132551    n = 0;
132552    idxCols = 0;
132553    for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
132554      if( termCanDriveIndex(pTerm, pSrc, notReady) ){
132555        int iCol = pTerm->u.leftColumn;
132556        Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
132557        testcase( iCol==BMS-1 );
132558        testcase( iCol==BMS );
132559        if( (idxCols & cMask)==0 ){
132560          Expr *pX = pTerm->pExpr;
132561          idxCols |= cMask;
132562          pIdx->aiColumn[n] = pTerm->u.leftColumn;
132563          pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
132564          pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
132565          n++;
132566        }
132567      }
132568    }
132569    assert( (u32)n==pLoop->u.btree.nEq );
132570  
132571    /* Add additional columns needed to make the automatic index into
132572    ** a covering index */
132573    for(i=0; i<mxBitCol; i++){
132574      if( extraCols & MASKBIT(i) ){
132575        pIdx->aiColumn[n] = i;
132576        pIdx->azColl[n] = sqlite3StrBINARY;
132577        n++;
132578      }
132579    }
132580    if( pSrc->colUsed & MASKBIT(BMS-1) ){
132581      for(i=BMS-1; i<pTable->nCol; i++){
132582        pIdx->aiColumn[n] = i;
132583        pIdx->azColl[n] = sqlite3StrBINARY;
132584        n++;
132585      }
132586    }
132587    assert( n==nKeyCol );
132588    pIdx->aiColumn[n] = XN_ROWID;
132589    pIdx->azColl[n] = sqlite3StrBINARY;
132590  
132591    /* Create the automatic index */
132592    assert( pLevel->iIdxCur>=0 );
132593    pLevel->iIdxCur = pParse->nTab++;
132594    sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
132595    sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
132596    VdbeComment((v, "for %s", pTable->zName));
132597  
132598    /* Fill the automatic index with content */
132599    sqlite3ExprCachePush(pParse);
132600    pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
132601    if( pTabItem->fg.viaCoroutine ){
132602      int regYield = pTabItem->regReturn;
132603      addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
132604      sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
132605      addrTop =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
132606      VdbeCoverage(v);
132607      VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
132608    }else{
132609      addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
132610    }
132611    if( pPartial ){
132612      iContinue = sqlite3VdbeMakeLabel(v);
132613      sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
132614      pLoop->wsFlags |= WHERE_PARTIALIDX;
132615    }
132616    regRecord = sqlite3GetTempReg(pParse);
132617    regBase = sqlite3GenerateIndexKey(
132618        pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
132619    );
132620    sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
132621    sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
132622    if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
132623    if( pTabItem->fg.viaCoroutine ){
132624      sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
132625      testcase( pParse->db->mallocFailed );
132626      translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
132627                            pTabItem->regResult, 1);
132628      sqlite3VdbeGoto(v, addrTop);
132629      pTabItem->fg.viaCoroutine = 0;
132630    }else{
132631      sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
132632    }
132633    sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
132634    sqlite3VdbeJumpHere(v, addrTop);
132635    sqlite3ReleaseTempReg(pParse, regRecord);
132636    sqlite3ExprCachePop(pParse);
132637    
132638    /* Jump here when skipping the initialization */
132639    sqlite3VdbeJumpHere(v, addrInit);
132640  
132641  end_auto_index_create:
132642    sqlite3ExprDelete(pParse->db, pPartial);
132643  }
132644  #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
132645  
132646  #ifndef SQLITE_OMIT_VIRTUALTABLE
132647  /*
132648  ** Allocate and populate an sqlite3_index_info structure. It is the 
132649  ** responsibility of the caller to eventually release the structure
132650  ** by passing the pointer returned by this function to sqlite3_free().
132651  */
132652  static sqlite3_index_info *allocateIndexInfo(
132653    Parse *pParse,
132654    WhereClause *pWC,
132655    Bitmask mUnusable,              /* Ignore terms with these prereqs */
132656    struct SrcList_item *pSrc,
132657    ExprList *pOrderBy,
132658    u16 *pmNoOmit                   /* Mask of terms not to omit */
132659  ){
132660    int i, j;
132661    int nTerm;
132662    struct sqlite3_index_constraint *pIdxCons;
132663    struct sqlite3_index_orderby *pIdxOrderBy;
132664    struct sqlite3_index_constraint_usage *pUsage;
132665    WhereTerm *pTerm;
132666    int nOrderBy;
132667    sqlite3_index_info *pIdxInfo;
132668    u16 mNoOmit = 0;
132669  
132670    /* Count the number of possible WHERE clause constraints referring
132671    ** to this virtual table */
132672    for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
132673      if( pTerm->leftCursor != pSrc->iCursor ) continue;
132674      if( pTerm->prereqRight & mUnusable ) continue;
132675      assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
132676      testcase( pTerm->eOperator & WO_IN );
132677      testcase( pTerm->eOperator & WO_ISNULL );
132678      testcase( pTerm->eOperator & WO_IS );
132679      testcase( pTerm->eOperator & WO_ALL );
132680      if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
132681      if( pTerm->wtFlags & TERM_VNULL ) continue;
132682      assert( pTerm->u.leftColumn>=(-1) );
132683      nTerm++;
132684    }
132685  
132686    /* If the ORDER BY clause contains only columns in the current 
132687    ** virtual table then allocate space for the aOrderBy part of
132688    ** the sqlite3_index_info structure.
132689    */
132690    nOrderBy = 0;
132691    if( pOrderBy ){
132692      int n = pOrderBy->nExpr;
132693      for(i=0; i<n; i++){
132694        Expr *pExpr = pOrderBy->a[i].pExpr;
132695        if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
132696      }
132697      if( i==n){
132698        nOrderBy = n;
132699      }
132700    }
132701  
132702    /* Allocate the sqlite3_index_info structure
132703    */
132704    pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
132705                             + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
132706                             + sizeof(*pIdxOrderBy)*nOrderBy );
132707    if( pIdxInfo==0 ){
132708      sqlite3ErrorMsg(pParse, "out of memory");
132709      return 0;
132710    }
132711  
132712    /* Initialize the structure.  The sqlite3_index_info structure contains
132713    ** many fields that are declared "const" to prevent xBestIndex from
132714    ** changing them.  We have to do some funky casting in order to
132715    ** initialize those fields.
132716    */
132717    pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
132718    pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
132719    pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
132720    *(int*)&pIdxInfo->nConstraint = nTerm;
132721    *(int*)&pIdxInfo->nOrderBy = nOrderBy;
132722    *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
132723    *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
132724    *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
132725                                                                     pUsage;
132726  
132727    for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
132728      u16 op;
132729      if( pTerm->leftCursor != pSrc->iCursor ) continue;
132730      if( pTerm->prereqRight & mUnusable ) continue;
132731      assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
132732      testcase( pTerm->eOperator & WO_IN );
132733      testcase( pTerm->eOperator & WO_IS );
132734      testcase( pTerm->eOperator & WO_ISNULL );
132735      testcase( pTerm->eOperator & WO_ALL );
132736      if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
132737      if( pTerm->wtFlags & TERM_VNULL ) continue;
132738      assert( pTerm->u.leftColumn>=(-1) );
132739      pIdxCons[j].iColumn = pTerm->u.leftColumn;
132740      pIdxCons[j].iTermOffset = i;
132741      op = pTerm->eOperator & WO_ALL;
132742      if( op==WO_IN ) op = WO_EQ;
132743      if( op==WO_AUX ){
132744        pIdxCons[j].op = pTerm->eMatchOp;
132745      }else if( op & (WO_ISNULL|WO_IS) ){
132746        if( op==WO_ISNULL ){
132747          pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL;
132748        }else{
132749          pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS;
132750        }
132751      }else{
132752        pIdxCons[j].op = (u8)op;
132753        /* The direct assignment in the previous line is possible only because
132754        ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
132755        ** following asserts verify this fact. */
132756        assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
132757        assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
132758        assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
132759        assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
132760        assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
132761        assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );
132762  
132763        if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
132764         && sqlite3ExprIsVector(pTerm->pExpr->pRight) 
132765        ){
132766          if( i<16 ) mNoOmit |= (1 << i);
132767          if( op==WO_LT ) pIdxCons[j].op = WO_LE;
132768          if( op==WO_GT ) pIdxCons[j].op = WO_GE;
132769        }
132770      }
132771  
132772      j++;
132773    }
132774    for(i=0; i<nOrderBy; i++){
132775      Expr *pExpr = pOrderBy->a[i].pExpr;
132776      pIdxOrderBy[i].iColumn = pExpr->iColumn;
132777      pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
132778    }
132779  
132780    *pmNoOmit = mNoOmit;
132781    return pIdxInfo;
132782  }
132783  
132784  /*
132785  ** The table object reference passed as the second argument to this function
132786  ** must represent a virtual table. This function invokes the xBestIndex()
132787  ** method of the virtual table with the sqlite3_index_info object that
132788  ** comes in as the 3rd argument to this function.
132789  **
132790  ** If an error occurs, pParse is populated with an error message and a
132791  ** non-zero value is returned. Otherwise, 0 is returned and the output
132792  ** part of the sqlite3_index_info structure is left populated.
132793  **
132794  ** Whether or not an error is returned, it is the responsibility of the
132795  ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
132796  ** that this is required.
132797  */
132798  static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
132799    sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
132800    int rc;
132801  
132802    TRACE_IDX_INPUTS(p);
132803    rc = pVtab->pModule->xBestIndex(pVtab, p);
132804    TRACE_IDX_OUTPUTS(p);
132805  
132806    if( rc!=SQLITE_OK ){
132807      if( rc==SQLITE_NOMEM ){
132808        sqlite3OomFault(pParse->db);
132809      }else if( !pVtab->zErrMsg ){
132810        sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
132811      }else{
132812        sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
132813      }
132814    }
132815    sqlite3_free(pVtab->zErrMsg);
132816    pVtab->zErrMsg = 0;
132817  
132818  #if 0
132819    /* This error is now caught by the caller.
132820    ** Search for "xBestIndex malfunction" below */
132821    for(i=0; i<p->nConstraint; i++){
132822      if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
132823        sqlite3ErrorMsg(pParse, 
132824            "table %s: xBestIndex returned an invalid plan", pTab->zName);
132825      }
132826    }
132827  #endif
132828  
132829    return pParse->nErr;
132830  }
132831  #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
132832  
132833  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
132834  /*
132835  ** Estimate the location of a particular key among all keys in an
132836  ** index.  Store the results in aStat as follows:
132837  **
132838  **    aStat[0]      Est. number of rows less than pRec
132839  **    aStat[1]      Est. number of rows equal to pRec
132840  **
132841  ** Return the index of the sample that is the smallest sample that
132842  ** is greater than or equal to pRec. Note that this index is not an index
132843  ** into the aSample[] array - it is an index into a virtual set of samples
132844  ** based on the contents of aSample[] and the number of fields in record 
132845  ** pRec. 
132846  */
132847  static int whereKeyStats(
132848    Parse *pParse,              /* Database connection */
132849    Index *pIdx,                /* Index to consider domain of */
132850    UnpackedRecord *pRec,       /* Vector of values to consider */
132851    int roundUp,                /* Round up if true.  Round down if false */
132852    tRowcnt *aStat              /* OUT: stats written here */
132853  ){
132854    IndexSample *aSample = pIdx->aSample;
132855    int iCol;                   /* Index of required stats in anEq[] etc. */
132856    int i;                      /* Index of first sample >= pRec */
132857    int iSample;                /* Smallest sample larger than or equal to pRec */
132858    int iMin = 0;               /* Smallest sample not yet tested */
132859    int iTest;                  /* Next sample to test */
132860    int res;                    /* Result of comparison operation */
132861    int nField;                 /* Number of fields in pRec */
132862    tRowcnt iLower = 0;         /* anLt[] + anEq[] of largest sample pRec is > */
132863  
132864  #ifndef SQLITE_DEBUG
132865    UNUSED_PARAMETER( pParse );
132866  #endif
132867    assert( pRec!=0 );
132868    assert( pIdx->nSample>0 );
132869    assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
132870  
132871    /* Do a binary search to find the first sample greater than or equal
132872    ** to pRec. If pRec contains a single field, the set of samples to search
132873    ** is simply the aSample[] array. If the samples in aSample[] contain more
132874    ** than one fields, all fields following the first are ignored.
132875    **
132876    ** If pRec contains N fields, where N is more than one, then as well as the
132877    ** samples in aSample[] (truncated to N fields), the search also has to
132878    ** consider prefixes of those samples. For example, if the set of samples
132879    ** in aSample is:
132880    **
132881    **     aSample[0] = (a, 5) 
132882    **     aSample[1] = (a, 10) 
132883    **     aSample[2] = (b, 5) 
132884    **     aSample[3] = (c, 100) 
132885    **     aSample[4] = (c, 105)
132886    **
132887    ** Then the search space should ideally be the samples above and the 
132888    ** unique prefixes [a], [b] and [c]. But since that is hard to organize, 
132889    ** the code actually searches this set:
132890    **
132891    **     0: (a) 
132892    **     1: (a, 5) 
132893    **     2: (a, 10) 
132894    **     3: (a, 10) 
132895    **     4: (b) 
132896    **     5: (b, 5) 
132897    **     6: (c) 
132898    **     7: (c, 100) 
132899    **     8: (c, 105)
132900    **     9: (c, 105)
132901    **
132902    ** For each sample in the aSample[] array, N samples are present in the
132903    ** effective sample array. In the above, samples 0 and 1 are based on 
132904    ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
132905    **
132906    ** Often, sample i of each block of N effective samples has (i+1) fields.
132907    ** Except, each sample may be extended to ensure that it is greater than or
132908    ** equal to the previous sample in the array. For example, in the above, 
132909    ** sample 2 is the first sample of a block of N samples, so at first it 
132910    ** appears that it should be 1 field in size. However, that would make it 
132911    ** smaller than sample 1, so the binary search would not work. As a result, 
132912    ** it is extended to two fields. The duplicates that this creates do not 
132913    ** cause any problems.
132914    */
132915    nField = pRec->nField;
132916    iCol = 0;
132917    iSample = pIdx->nSample * nField;
132918    do{
132919      int iSamp;                    /* Index in aSample[] of test sample */
132920      int n;                        /* Number of fields in test sample */
132921  
132922      iTest = (iMin+iSample)/2;
132923      iSamp = iTest / nField;
132924      if( iSamp>0 ){
132925        /* The proposed effective sample is a prefix of sample aSample[iSamp].
132926        ** Specifically, the shortest prefix of at least (1 + iTest%nField) 
132927        ** fields that is greater than the previous effective sample.  */
132928        for(n=(iTest % nField) + 1; n<nField; n++){
132929          if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
132930        }
132931      }else{
132932        n = iTest + 1;
132933      }
132934  
132935      pRec->nField = n;
132936      res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
132937      if( res<0 ){
132938        iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
132939        iMin = iTest+1;
132940      }else if( res==0 && n<nField ){
132941        iLower = aSample[iSamp].anLt[n-1];
132942        iMin = iTest+1;
132943        res = -1;
132944      }else{
132945        iSample = iTest;
132946        iCol = n-1;
132947      }
132948    }while( res && iMin<iSample );
132949    i = iSample / nField;
132950  
132951  #ifdef SQLITE_DEBUG
132952    /* The following assert statements check that the binary search code
132953    ** above found the right answer. This block serves no purpose other
132954    ** than to invoke the asserts.  */
132955    if( pParse->db->mallocFailed==0 ){
132956      if( res==0 ){
132957        /* If (res==0) is true, then pRec must be equal to sample i. */
132958        assert( i<pIdx->nSample );
132959        assert( iCol==nField-1 );
132960        pRec->nField = nField;
132961        assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec) 
132962             || pParse->db->mallocFailed 
132963        );
132964      }else{
132965        /* Unless i==pIdx->nSample, indicating that pRec is larger than
132966        ** all samples in the aSample[] array, pRec must be smaller than the
132967        ** (iCol+1) field prefix of sample i.  */
132968        assert( i<=pIdx->nSample && i>=0 );
132969        pRec->nField = iCol+1;
132970        assert( i==pIdx->nSample 
132971             || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
132972             || pParse->db->mallocFailed );
132973  
132974        /* if i==0 and iCol==0, then record pRec is smaller than all samples
132975        ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
132976        ** be greater than or equal to the (iCol) field prefix of sample i.
132977        ** If (i>0), then pRec must also be greater than sample (i-1).  */
132978        if( iCol>0 ){
132979          pRec->nField = iCol;
132980          assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
132981               || pParse->db->mallocFailed );
132982        }
132983        if( i>0 ){
132984          pRec->nField = nField;
132985          assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
132986               || pParse->db->mallocFailed );
132987        }
132988      }
132989    }
132990  #endif /* ifdef SQLITE_DEBUG */
132991  
132992    if( res==0 ){
132993      /* Record pRec is equal to sample i */
132994      assert( iCol==nField-1 );
132995      aStat[0] = aSample[i].anLt[iCol];
132996      aStat[1] = aSample[i].anEq[iCol];
132997    }else{
132998      /* At this point, the (iCol+1) field prefix of aSample[i] is the first 
132999      ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
133000      ** is larger than all samples in the array. */
133001      tRowcnt iUpper, iGap;
133002      if( i>=pIdx->nSample ){
133003        iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
133004      }else{
133005        iUpper = aSample[i].anLt[iCol];
133006      }
133007  
133008      if( iLower>=iUpper ){
133009        iGap = 0;
133010      }else{
133011        iGap = iUpper - iLower;
133012      }
133013      if( roundUp ){
133014        iGap = (iGap*2)/3;
133015      }else{
133016        iGap = iGap/3;
133017      }
133018      aStat[0] = iLower + iGap;
133019      aStat[1] = pIdx->aAvgEq[nField-1];
133020    }
133021  
133022    /* Restore the pRec->nField value before returning.  */
133023    pRec->nField = nField;
133024    return i;
133025  }
133026  #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
133027  
133028  /*
133029  ** If it is not NULL, pTerm is a term that provides an upper or lower
133030  ** bound on a range scan. Without considering pTerm, it is estimated 
133031  ** that the scan will visit nNew rows. This function returns the number
133032  ** estimated to be visited after taking pTerm into account.
133033  **
133034  ** If the user explicitly specified a likelihood() value for this term,
133035  ** then the return value is the likelihood multiplied by the number of
133036  ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
133037  ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
133038  */
133039  static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
133040    LogEst nRet = nNew;
133041    if( pTerm ){
133042      if( pTerm->truthProb<=0 ){
133043        nRet += pTerm->truthProb;
133044      }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
133045        nRet -= 20;        assert( 20==sqlite3LogEst(4) );
133046      }
133047    }
133048    return nRet;
133049  }
133050  
133051  
133052  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
133053  /*
133054  ** Return the affinity for a single column of an index.
133055  */
133056  SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
133057    assert( iCol>=0 && iCol<pIdx->nColumn );
133058    if( !pIdx->zColAff ){
133059      if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
133060    }
133061    return pIdx->zColAff[iCol];
133062  }
133063  #endif
133064  
133065  
133066  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
133067  /* 
133068  ** This function is called to estimate the number of rows visited by a
133069  ** range-scan on a skip-scan index. For example:
133070  **
133071  **   CREATE INDEX i1 ON t1(a, b, c);
133072  **   SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
133073  **
133074  ** Value pLoop->nOut is currently set to the estimated number of rows 
133075  ** visited for scanning (a=? AND b=?). This function reduces that estimate 
133076  ** by some factor to account for the (c BETWEEN ? AND ?) expression based
133077  ** on the stat4 data for the index. this scan will be peformed multiple 
133078  ** times (once for each (a,b) combination that matches a=?) is dealt with 
133079  ** by the caller.
133080  **
133081  ** It does this by scanning through all stat4 samples, comparing values
133082  ** extracted from pLower and pUpper with the corresponding column in each
133083  ** sample. If L and U are the number of samples found to be less than or
133084  ** equal to the values extracted from pLower and pUpper respectively, and
133085  ** N is the total number of samples, the pLoop->nOut value is adjusted
133086  ** as follows:
133087  **
133088  **   nOut = nOut * ( min(U - L, 1) / N )
133089  **
133090  ** If pLower is NULL, or a value cannot be extracted from the term, L is
133091  ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
133092  ** U is set to N.
133093  **
133094  ** Normally, this function sets *pbDone to 1 before returning. However,
133095  ** if no value can be extracted from either pLower or pUpper (and so the
133096  ** estimate of the number of rows delivered remains unchanged), *pbDone
133097  ** is left as is.
133098  **
133099  ** If an error occurs, an SQLite error code is returned. Otherwise, 
133100  ** SQLITE_OK.
133101  */
133102  static int whereRangeSkipScanEst(
133103    Parse *pParse,       /* Parsing & code generating context */
133104    WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
133105    WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
133106    WhereLoop *pLoop,    /* Update the .nOut value of this loop */
133107    int *pbDone          /* Set to true if at least one expr. value extracted */
133108  ){
133109    Index *p = pLoop->u.btree.pIndex;
133110    int nEq = pLoop->u.btree.nEq;
133111    sqlite3 *db = pParse->db;
133112    int nLower = -1;
133113    int nUpper = p->nSample+1;
133114    int rc = SQLITE_OK;
133115    u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
133116    CollSeq *pColl;
133117    
133118    sqlite3_value *p1 = 0;          /* Value extracted from pLower */
133119    sqlite3_value *p2 = 0;          /* Value extracted from pUpper */
133120    sqlite3_value *pVal = 0;        /* Value extracted from record */
133121  
133122    pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
133123    if( pLower ){
133124      rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
133125      nLower = 0;
133126    }
133127    if( pUpper && rc==SQLITE_OK ){
133128      rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
133129      nUpper = p2 ? 0 : p->nSample;
133130    }
133131  
133132    if( p1 || p2 ){
133133      int i;
133134      int nDiff;
133135      for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
133136        rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
133137        if( rc==SQLITE_OK && p1 ){
133138          int res = sqlite3MemCompare(p1, pVal, pColl);
133139          if( res>=0 ) nLower++;
133140        }
133141        if( rc==SQLITE_OK && p2 ){
133142          int res = sqlite3MemCompare(p2, pVal, pColl);
133143          if( res>=0 ) nUpper++;
133144        }
133145      }
133146      nDiff = (nUpper - nLower);
133147      if( nDiff<=0 ) nDiff = 1;
133148  
133149      /* If there is both an upper and lower bound specified, and the 
133150      ** comparisons indicate that they are close together, use the fallback
133151      ** method (assume that the scan visits 1/64 of the rows) for estimating
133152      ** the number of rows visited. Otherwise, estimate the number of rows
133153      ** using the method described in the header comment for this function. */
133154      if( nDiff!=1 || pUpper==0 || pLower==0 ){
133155        int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
133156        pLoop->nOut -= nAdjust;
133157        *pbDone = 1;
133158        WHERETRACE(0x10, ("range skip-scan regions: %u..%u  adjust=%d est=%d\n",
133159                             nLower, nUpper, nAdjust*-1, pLoop->nOut));
133160      }
133161  
133162    }else{
133163      assert( *pbDone==0 );
133164    }
133165  
133166    sqlite3ValueFree(p1);
133167    sqlite3ValueFree(p2);
133168    sqlite3ValueFree(pVal);
133169  
133170    return rc;
133171  }
133172  #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
133173  
133174  /*
133175  ** This function is used to estimate the number of rows that will be visited
133176  ** by scanning an index for a range of values. The range may have an upper
133177  ** bound, a lower bound, or both. The WHERE clause terms that set the upper
133178  ** and lower bounds are represented by pLower and pUpper respectively. For
133179  ** example, assuming that index p is on t1(a):
133180  **
133181  **   ... FROM t1 WHERE a > ? AND a < ? ...
133182  **                    |_____|   |_____|
133183  **                       |         |
133184  **                     pLower    pUpper
133185  **
133186  ** If either of the upper or lower bound is not present, then NULL is passed in
133187  ** place of the corresponding WhereTerm.
133188  **
133189  ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
133190  ** column subject to the range constraint. Or, equivalently, the number of
133191  ** equality constraints optimized by the proposed index scan. For example,
133192  ** assuming index p is on t1(a, b), and the SQL query is:
133193  **
133194  **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
133195  **
133196  ** then nEq is set to 1 (as the range restricted column, b, is the second 
133197  ** left-most column of the index). Or, if the query is:
133198  **
133199  **   ... FROM t1 WHERE a > ? AND a < ? ...
133200  **
133201  ** then nEq is set to 0.
133202  **
133203  ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
133204  ** number of rows that the index scan is expected to visit without 
133205  ** considering the range constraints. If nEq is 0, then *pnOut is the number of 
133206  ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
133207  ** to account for the range constraints pLower and pUpper.
133208  ** 
133209  ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
133210  ** used, a single range inequality reduces the search space by a factor of 4. 
133211  ** and a pair of constraints (x>? AND x<?) reduces the expected number of
133212  ** rows visited by a factor of 64.
133213  */
133214  static int whereRangeScanEst(
133215    Parse *pParse,       /* Parsing & code generating context */
133216    WhereLoopBuilder *pBuilder,
133217    WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
133218    WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
133219    WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */
133220  ){
133221    int rc = SQLITE_OK;
133222    int nOut = pLoop->nOut;
133223    LogEst nNew;
133224  
133225  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
133226    Index *p = pLoop->u.btree.pIndex;
133227    int nEq = pLoop->u.btree.nEq;
133228  
133229    if( p->nSample>0 && nEq<p->nSampleCol ){
133230      if( nEq==pBuilder->nRecValid ){
133231        UnpackedRecord *pRec = pBuilder->pRec;
133232        tRowcnt a[2];
133233        int nBtm = pLoop->u.btree.nBtm;
133234        int nTop = pLoop->u.btree.nTop;
133235  
133236        /* Variable iLower will be set to the estimate of the number of rows in 
133237        ** the index that are less than the lower bound of the range query. The
133238        ** lower bound being the concatenation of $P and $L, where $P is the
133239        ** key-prefix formed by the nEq values matched against the nEq left-most
133240        ** columns of the index, and $L is the value in pLower.
133241        **
133242        ** Or, if pLower is NULL or $L cannot be extracted from it (because it
133243        ** is not a simple variable or literal value), the lower bound of the
133244        ** range is $P. Due to a quirk in the way whereKeyStats() works, even
133245        ** if $L is available, whereKeyStats() is called for both ($P) and 
133246        ** ($P:$L) and the larger of the two returned values is used.
133247        **
133248        ** Similarly, iUpper is to be set to the estimate of the number of rows
133249        ** less than the upper bound of the range query. Where the upper bound
133250        ** is either ($P) or ($P:$U). Again, even if $U is available, both values
133251        ** of iUpper are requested of whereKeyStats() and the smaller used.
133252        **
133253        ** The number of rows between the two bounds is then just iUpper-iLower.
133254        */
133255        tRowcnt iLower;     /* Rows less than the lower bound */
133256        tRowcnt iUpper;     /* Rows less than the upper bound */
133257        int iLwrIdx = -2;   /* aSample[] for the lower bound */
133258        int iUprIdx = -1;   /* aSample[] for the upper bound */
133259  
133260        if( pRec ){
133261          testcase( pRec->nField!=pBuilder->nRecValid );
133262          pRec->nField = pBuilder->nRecValid;
133263        }
133264        /* Determine iLower and iUpper using ($P) only. */
133265        if( nEq==0 ){
133266          iLower = 0;
133267          iUpper = p->nRowEst0;
133268        }else{
133269          /* Note: this call could be optimized away - since the same values must 
133270          ** have been requested when testing key $P in whereEqualScanEst().  */
133271          whereKeyStats(pParse, p, pRec, 0, a);
133272          iLower = a[0];
133273          iUpper = a[0] + a[1];
133274        }
133275  
133276        assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
133277        assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
133278        assert( p->aSortOrder!=0 );
133279        if( p->aSortOrder[nEq] ){
133280          /* The roles of pLower and pUpper are swapped for a DESC index */
133281          SWAP(WhereTerm*, pLower, pUpper);
133282          SWAP(int, nBtm, nTop);
133283        }
133284  
133285        /* If possible, improve on the iLower estimate using ($P:$L). */
133286        if( pLower ){
133287          int n;                    /* Values extracted from pExpr */
133288          Expr *pExpr = pLower->pExpr->pRight;
133289          rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
133290          if( rc==SQLITE_OK && n ){
133291            tRowcnt iNew;
133292            u16 mask = WO_GT|WO_LE;
133293            if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
133294            iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
133295            iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
133296            if( iNew>iLower ) iLower = iNew;
133297            nOut--;
133298            pLower = 0;
133299          }
133300        }
133301  
133302        /* If possible, improve on the iUpper estimate using ($P:$U). */
133303        if( pUpper ){
133304          int n;                    /* Values extracted from pExpr */
133305          Expr *pExpr = pUpper->pExpr->pRight;
133306          rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
133307          if( rc==SQLITE_OK && n ){
133308            tRowcnt iNew;
133309            u16 mask = WO_GT|WO_LE;
133310            if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
133311            iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
133312            iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
133313            if( iNew<iUpper ) iUpper = iNew;
133314            nOut--;
133315            pUpper = 0;
133316          }
133317        }
133318  
133319        pBuilder->pRec = pRec;
133320        if( rc==SQLITE_OK ){
133321          if( iUpper>iLower ){
133322            nNew = sqlite3LogEst(iUpper - iLower);
133323            /* TUNING:  If both iUpper and iLower are derived from the same
133324            ** sample, then assume they are 4x more selective.  This brings
133325            ** the estimated selectivity more in line with what it would be
133326            ** if estimated without the use of STAT3/4 tables. */
133327            if( iLwrIdx==iUprIdx ) nNew -= 20;  assert( 20==sqlite3LogEst(4) );
133328          }else{
133329            nNew = 10;        assert( 10==sqlite3LogEst(2) );
133330          }
133331          if( nNew<nOut ){
133332            nOut = nNew;
133333          }
133334          WHERETRACE(0x10, ("STAT4 range scan: %u..%u  est=%d\n",
133335                             (u32)iLower, (u32)iUpper, nOut));
133336        }
133337      }else{
133338        int bDone = 0;
133339        rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
133340        if( bDone ) return rc;
133341      }
133342    }
133343  #else
133344    UNUSED_PARAMETER(pParse);
133345    UNUSED_PARAMETER(pBuilder);
133346    assert( pLower || pUpper );
133347  #endif
133348    assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
133349    nNew = whereRangeAdjust(pLower, nOut);
133350    nNew = whereRangeAdjust(pUpper, nNew);
133351  
133352    /* TUNING: If there is both an upper and lower limit and neither limit
133353    ** has an application-defined likelihood(), assume the range is
133354    ** reduced by an additional 75%. This means that, by default, an open-ended
133355    ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
133356    ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
133357    ** match 1/64 of the index. */ 
133358    if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
133359      nNew -= 20;
133360    }
133361  
133362    nOut -= (pLower!=0) + (pUpper!=0);
133363    if( nNew<10 ) nNew = 10;
133364    if( nNew<nOut ) nOut = nNew;
133365  #if defined(WHERETRACE_ENABLED)
133366    if( pLoop->nOut>nOut ){
133367      WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
133368                      pLoop->nOut, nOut));
133369    }
133370  #endif
133371    pLoop->nOut = (LogEst)nOut;
133372    return rc;
133373  }
133374  
133375  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
133376  /*
133377  ** Estimate the number of rows that will be returned based on
133378  ** an equality constraint x=VALUE and where that VALUE occurs in
133379  ** the histogram data.  This only works when x is the left-most
133380  ** column of an index and sqlite_stat3 histogram data is available
133381  ** for that index.  When pExpr==NULL that means the constraint is
133382  ** "x IS NULL" instead of "x=VALUE".
133383  **
133384  ** Write the estimated row count into *pnRow and return SQLITE_OK. 
133385  ** If unable to make an estimate, leave *pnRow unchanged and return
133386  ** non-zero.
133387  **
133388  ** This routine can fail if it is unable to load a collating sequence
133389  ** required for string comparison, or if unable to allocate memory
133390  ** for a UTF conversion required for comparison.  The error is stored
133391  ** in the pParse structure.
133392  */
133393  static int whereEqualScanEst(
133394    Parse *pParse,       /* Parsing & code generating context */
133395    WhereLoopBuilder *pBuilder,
133396    Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
133397    tRowcnt *pnRow       /* Write the revised row estimate here */
133398  ){
133399    Index *p = pBuilder->pNew->u.btree.pIndex;
133400    int nEq = pBuilder->pNew->u.btree.nEq;
133401    UnpackedRecord *pRec = pBuilder->pRec;
133402    int rc;                   /* Subfunction return code */
133403    tRowcnt a[2];             /* Statistics */
133404    int bOk;
133405  
133406    assert( nEq>=1 );
133407    assert( nEq<=p->nColumn );
133408    assert( p->aSample!=0 );
133409    assert( p->nSample>0 );
133410    assert( pBuilder->nRecValid<nEq );
133411  
133412    /* If values are not available for all fields of the index to the left
133413    ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
133414    if( pBuilder->nRecValid<(nEq-1) ){
133415      return SQLITE_NOTFOUND;
133416    }
133417  
133418    /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
133419    ** below would return the same value.  */
133420    if( nEq>=p->nColumn ){
133421      *pnRow = 1;
133422      return SQLITE_OK;
133423    }
133424  
133425    rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
133426    pBuilder->pRec = pRec;
133427    if( rc!=SQLITE_OK ) return rc;
133428    if( bOk==0 ) return SQLITE_NOTFOUND;
133429    pBuilder->nRecValid = nEq;
133430  
133431    whereKeyStats(pParse, p, pRec, 0, a);
133432    WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
133433                     p->zName, nEq-1, (int)a[1]));
133434    *pnRow = a[1];
133435    
133436    return rc;
133437  }
133438  #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
133439  
133440  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
133441  /*
133442  ** Estimate the number of rows that will be returned based on
133443  ** an IN constraint where the right-hand side of the IN operator
133444  ** is a list of values.  Example:
133445  **
133446  **        WHERE x IN (1,2,3,4)
133447  **
133448  ** Write the estimated row count into *pnRow and return SQLITE_OK. 
133449  ** If unable to make an estimate, leave *pnRow unchanged and return
133450  ** non-zero.
133451  **
133452  ** This routine can fail if it is unable to load a collating sequence
133453  ** required for string comparison, or if unable to allocate memory
133454  ** for a UTF conversion required for comparison.  The error is stored
133455  ** in the pParse structure.
133456  */
133457  static int whereInScanEst(
133458    Parse *pParse,       /* Parsing & code generating context */
133459    WhereLoopBuilder *pBuilder,
133460    ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
133461    tRowcnt *pnRow       /* Write the revised row estimate here */
133462  ){
133463    Index *p = pBuilder->pNew->u.btree.pIndex;
133464    i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
133465    int nRecValid = pBuilder->nRecValid;
133466    int rc = SQLITE_OK;     /* Subfunction return code */
133467    tRowcnt nEst;           /* Number of rows for a single term */
133468    tRowcnt nRowEst = 0;    /* New estimate of the number of rows */
133469    int i;                  /* Loop counter */
133470  
133471    assert( p->aSample!=0 );
133472    for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
133473      nEst = nRow0;
133474      rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
133475      nRowEst += nEst;
133476      pBuilder->nRecValid = nRecValid;
133477    }
133478  
133479    if( rc==SQLITE_OK ){
133480      if( nRowEst > nRow0 ) nRowEst = nRow0;
133481      *pnRow = nRowEst;
133482      WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
133483    }
133484    assert( pBuilder->nRecValid==nRecValid );
133485    return rc;
133486  }
133487  #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
133488  
133489  
133490  #ifdef WHERETRACE_ENABLED
133491  /*
133492  ** Print the content of a WhereTerm object
133493  */
133494  static void whereTermPrint(WhereTerm *pTerm, int iTerm){
133495    if( pTerm==0 ){
133496      sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
133497    }else{
133498      char zType[4];
133499      char zLeft[50];
133500      memcpy(zType, "...", 4);
133501      if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
133502      if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
133503      if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
133504      if( pTerm->eOperator & WO_SINGLE ){
133505        sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
133506                         pTerm->leftCursor, pTerm->u.leftColumn);
133507      }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
133508        sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld", 
133509                         pTerm->u.pOrInfo->indexable);
133510      }else{
133511        sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
133512      }
133513      sqlite3DebugPrintf(
133514         "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x",
133515         iTerm, pTerm, zType, zLeft, pTerm->truthProb,
133516         pTerm->eOperator, pTerm->wtFlags);
133517      if( pTerm->iField ){
133518        sqlite3DebugPrintf(" iField=%d\n", pTerm->iField);
133519      }else{
133520        sqlite3DebugPrintf("\n");
133521      }
133522      sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
133523    }
133524  }
133525  #endif
133526  
133527  #ifdef WHERETRACE_ENABLED
133528  /*
133529  ** Show the complete content of a WhereClause
133530  */
133531  SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
133532    int i;
133533    for(i=0; i<pWC->nTerm; i++){
133534      whereTermPrint(&pWC->a[i], i);
133535    }
133536  }
133537  #endif
133538  
133539  #ifdef WHERETRACE_ENABLED
133540  /*
133541  ** Print a WhereLoop object for debugging purposes
133542  */
133543  static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
133544    WhereInfo *pWInfo = pWC->pWInfo;
133545    int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
133546    struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
133547    Table *pTab = pItem->pTab;
133548    Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
133549    sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
133550                       p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
133551    sqlite3DebugPrintf(" %12s",
133552                       pItem->zAlias ? pItem->zAlias : pTab->zName);
133553    if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
133554      const char *zName;
133555      if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
133556        if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
133557          int i = sqlite3Strlen30(zName) - 1;
133558          while( zName[i]!='_' ) i--;
133559          zName += i;
133560        }
133561        sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
133562      }else{
133563        sqlite3DebugPrintf("%20s","");
133564      }
133565    }else{
133566      char *z;
133567      if( p->u.vtab.idxStr ){
133568        z = sqlite3_mprintf("(%d,\"%s\",%x)",
133569                  p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
133570      }else{
133571        z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
133572      }
133573      sqlite3DebugPrintf(" %-19s", z);
133574      sqlite3_free(z);
133575    }
133576    if( p->wsFlags & WHERE_SKIPSCAN ){
133577      sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
133578    }else{
133579      sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
133580    }
133581    sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
133582    if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
133583      int i;
133584      for(i=0; i<p->nLTerm; i++){
133585        whereTermPrint(p->aLTerm[i], i);
133586      }
133587    }
133588  }
133589  #endif
133590  
133591  /*
133592  ** Convert bulk memory into a valid WhereLoop that can be passed
133593  ** to whereLoopClear harmlessly.
133594  */
133595  static void whereLoopInit(WhereLoop *p){
133596    p->aLTerm = p->aLTermSpace;
133597    p->nLTerm = 0;
133598    p->nLSlot = ArraySize(p->aLTermSpace);
133599    p->wsFlags = 0;
133600  }
133601  
133602  /*
133603  ** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.
133604  */
133605  static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
133606    if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
133607      if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
133608        sqlite3_free(p->u.vtab.idxStr);
133609        p->u.vtab.needFree = 0;
133610        p->u.vtab.idxStr = 0;
133611      }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
133612        sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
133613        sqlite3DbFreeNN(db, p->u.btree.pIndex);
133614        p->u.btree.pIndex = 0;
133615      }
133616    }
133617  }
133618  
133619  /*
133620  ** Deallocate internal memory used by a WhereLoop object
133621  */
133622  static void whereLoopClear(sqlite3 *db, WhereLoop *p){
133623    if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
133624    whereLoopClearUnion(db, p);
133625    whereLoopInit(p);
133626  }
133627  
133628  /*
133629  ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
133630  */
133631  static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
133632    WhereTerm **paNew;
133633    if( p->nLSlot>=n ) return SQLITE_OK;
133634    n = (n+7)&~7;
133635    paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
133636    if( paNew==0 ) return SQLITE_NOMEM_BKPT;
133637    memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
133638    if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
133639    p->aLTerm = paNew;
133640    p->nLSlot = n;
133641    return SQLITE_OK;
133642  }
133643  
133644  /*
133645  ** Transfer content from the second pLoop into the first.
133646  */
133647  static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
133648    whereLoopClearUnion(db, pTo);
133649    if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
133650      memset(&pTo->u, 0, sizeof(pTo->u));
133651      return SQLITE_NOMEM_BKPT;
133652    }
133653    memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
133654    memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
133655    if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
133656      pFrom->u.vtab.needFree = 0;
133657    }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
133658      pFrom->u.btree.pIndex = 0;
133659    }
133660    return SQLITE_OK;
133661  }
133662  
133663  /*
133664  ** Delete a WhereLoop object
133665  */
133666  static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
133667    whereLoopClear(db, p);
133668    sqlite3DbFreeNN(db, p);
133669  }
133670  
133671  /*
133672  ** Free a WhereInfo structure
133673  */
133674  static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
133675    if( ALWAYS(pWInfo) ){
133676      int i;
133677      for(i=0; i<pWInfo->nLevel; i++){
133678        WhereLevel *pLevel = &pWInfo->a[i];
133679        if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
133680          sqlite3DbFree(db, pLevel->u.in.aInLoop);
133681        }
133682      }
133683      sqlite3WhereClauseClear(&pWInfo->sWC);
133684      while( pWInfo->pLoops ){
133685        WhereLoop *p = pWInfo->pLoops;
133686        pWInfo->pLoops = p->pNextLoop;
133687        whereLoopDelete(db, p);
133688      }
133689      sqlite3DbFreeNN(db, pWInfo);
133690    }
133691  }
133692  
133693  /*
133694  ** Return TRUE if all of the following are true:
133695  **
133696  **   (1)  X has the same or lower cost that Y
133697  **   (2)  X uses fewer WHERE clause terms than Y
133698  **   (3)  Every WHERE clause term used by X is also used by Y
133699  **   (4)  X skips at least as many columns as Y
133700  **   (5)  If X is a covering index, than Y is too
133701  **
133702  ** Conditions (2) and (3) mean that X is a "proper subset" of Y.
133703  ** If X is a proper subset of Y then Y is a better choice and ought
133704  ** to have a lower cost.  This routine returns TRUE when that cost 
133705  ** relationship is inverted and needs to be adjusted.  Constraint (4)
133706  ** was added because if X uses skip-scan less than Y it still might
133707  ** deserve a lower cost even if it is a proper subset of Y.  Constraint (5)
133708  ** was added because a covering index probably deserves to have a lower cost
133709  ** than a non-covering index even if it is a proper subset.
133710  */
133711  static int whereLoopCheaperProperSubset(
133712    const WhereLoop *pX,       /* First WhereLoop to compare */
133713    const WhereLoop *pY        /* Compare against this WhereLoop */
133714  ){
133715    int i, j;
133716    if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
133717      return 0; /* X is not a subset of Y */
133718    }
133719    if( pY->nSkip > pX->nSkip ) return 0;
133720    if( pX->rRun >= pY->rRun ){
133721      if( pX->rRun > pY->rRun ) return 0;    /* X costs more than Y */
133722      if( pX->nOut > pY->nOut ) return 0;    /* X costs more than Y */
133723    }
133724    for(i=pX->nLTerm-1; i>=0; i--){
133725      if( pX->aLTerm[i]==0 ) continue;
133726      for(j=pY->nLTerm-1; j>=0; j--){
133727        if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
133728      }
133729      if( j<0 ) return 0;  /* X not a subset of Y since term X[i] not used by Y */
133730    }
133731    if( (pX->wsFlags&WHERE_IDX_ONLY)!=0 
133732     && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){
133733      return 0;  /* Constraint (5) */
133734    }
133735    return 1;  /* All conditions meet */
133736  }
133737  
133738  /*
133739  ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
133740  ** that:
133741  **
133742  **   (1) pTemplate costs less than any other WhereLoops that are a proper
133743  **       subset of pTemplate
133744  **
133745  **   (2) pTemplate costs more than any other WhereLoops for which pTemplate
133746  **       is a proper subset.
133747  **
133748  ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
133749  ** WHERE clause terms than Y and that every WHERE clause term used by X is
133750  ** also used by Y.
133751  */
133752  static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
133753    if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
133754    for(; p; p=p->pNextLoop){
133755      if( p->iTab!=pTemplate->iTab ) continue;
133756      if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
133757      if( whereLoopCheaperProperSubset(p, pTemplate) ){
133758        /* Adjust pTemplate cost downward so that it is cheaper than its 
133759        ** subset p. */
133760        WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
133761                         pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
133762        pTemplate->rRun = p->rRun;
133763        pTemplate->nOut = p->nOut - 1;
133764      }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
133765        /* Adjust pTemplate cost upward so that it is costlier than p since
133766        ** pTemplate is a proper subset of p */
133767        WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
133768                         pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
133769        pTemplate->rRun = p->rRun;
133770        pTemplate->nOut = p->nOut + 1;
133771      }
133772    }
133773  }
133774  
133775  /*
133776  ** Search the list of WhereLoops in *ppPrev looking for one that can be
133777  ** replaced by pTemplate.
133778  **
133779  ** Return NULL if pTemplate does not belong on the WhereLoop list.
133780  ** In other words if pTemplate ought to be dropped from further consideration.
133781  **
133782  ** If pX is a WhereLoop that pTemplate can replace, then return the
133783  ** link that points to pX.
133784  **
133785  ** If pTemplate cannot replace any existing element of the list but needs
133786  ** to be added to the list as a new entry, then return a pointer to the
133787  ** tail of the list.
133788  */
133789  static WhereLoop **whereLoopFindLesser(
133790    WhereLoop **ppPrev,
133791    const WhereLoop *pTemplate
133792  ){
133793    WhereLoop *p;
133794    for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
133795      if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
133796        /* If either the iTab or iSortIdx values for two WhereLoop are different
133797        ** then those WhereLoops need to be considered separately.  Neither is
133798        ** a candidate to replace the other. */
133799        continue;
133800      }
133801      /* In the current implementation, the rSetup value is either zero
133802      ** or the cost of building an automatic index (NlogN) and the NlogN
133803      ** is the same for compatible WhereLoops. */
133804      assert( p->rSetup==0 || pTemplate->rSetup==0 
133805                   || p->rSetup==pTemplate->rSetup );
133806  
133807      /* whereLoopAddBtree() always generates and inserts the automatic index
133808      ** case first.  Hence compatible candidate WhereLoops never have a larger
133809      ** rSetup. Call this SETUP-INVARIANT */
133810      assert( p->rSetup>=pTemplate->rSetup );
133811  
133812      /* Any loop using an appliation-defined index (or PRIMARY KEY or
133813      ** UNIQUE constraint) with one or more == constraints is better
133814      ** than an automatic index. Unless it is a skip-scan. */
133815      if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
133816       && (pTemplate->nSkip)==0
133817       && (pTemplate->wsFlags & WHERE_INDEXED)!=0
133818       && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
133819       && (p->prereq & pTemplate->prereq)==pTemplate->prereq
133820      ){
133821        break;
133822      }
133823  
133824      /* If existing WhereLoop p is better than pTemplate, pTemplate can be
133825      ** discarded.  WhereLoop p is better if:
133826      **   (1)  p has no more dependencies than pTemplate, and
133827      **   (2)  p has an equal or lower cost than pTemplate
133828      */
133829      if( (p->prereq & pTemplate->prereq)==p->prereq    /* (1)  */
133830       && p->rSetup<=pTemplate->rSetup                  /* (2a) */
133831       && p->rRun<=pTemplate->rRun                      /* (2b) */
133832       && p->nOut<=pTemplate->nOut                      /* (2c) */
133833      ){
133834        return 0;  /* Discard pTemplate */
133835      }
133836  
133837      /* If pTemplate is always better than p, then cause p to be overwritten
133838      ** with pTemplate.  pTemplate is better than p if:
133839      **   (1)  pTemplate has no more dependences than p, and
133840      **   (2)  pTemplate has an equal or lower cost than p.
133841      */
133842      if( (p->prereq & pTemplate->prereq)==pTemplate->prereq   /* (1)  */
133843       && p->rRun>=pTemplate->rRun                             /* (2a) */
133844       && p->nOut>=pTemplate->nOut                             /* (2b) */
133845      ){
133846        assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
133847        break;   /* Cause p to be overwritten by pTemplate */
133848      }
133849    }
133850    return ppPrev;
133851  }
133852  
133853  /*
133854  ** Insert or replace a WhereLoop entry using the template supplied.
133855  **
133856  ** An existing WhereLoop entry might be overwritten if the new template
133857  ** is better and has fewer dependencies.  Or the template will be ignored
133858  ** and no insert will occur if an existing WhereLoop is faster and has
133859  ** fewer dependencies than the template.  Otherwise a new WhereLoop is
133860  ** added based on the template.
133861  **
133862  ** If pBuilder->pOrSet is not NULL then we care about only the
133863  ** prerequisites and rRun and nOut costs of the N best loops.  That
133864  ** information is gathered in the pBuilder->pOrSet object.  This special
133865  ** processing mode is used only for OR clause processing.
133866  **
133867  ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
133868  ** still might overwrite similar loops with the new template if the
133869  ** new template is better.  Loops may be overwritten if the following 
133870  ** conditions are met:
133871  **
133872  **    (1)  They have the same iTab.
133873  **    (2)  They have the same iSortIdx.
133874  **    (3)  The template has same or fewer dependencies than the current loop
133875  **    (4)  The template has the same or lower cost than the current loop
133876  */
133877  static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
133878    WhereLoop **ppPrev, *p;
133879    WhereInfo *pWInfo = pBuilder->pWInfo;
133880    sqlite3 *db = pWInfo->pParse->db;
133881    int rc;
133882  
133883    /* If pBuilder->pOrSet is defined, then only keep track of the costs
133884    ** and prereqs.
133885    */
133886    if( pBuilder->pOrSet!=0 ){
133887      if( pTemplate->nLTerm ){
133888  #if WHERETRACE_ENABLED
133889        u16 n = pBuilder->pOrSet->n;
133890        int x =
133891  #endif
133892        whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
133893                                      pTemplate->nOut);
133894  #if WHERETRACE_ENABLED /* 0x8 */
133895        if( sqlite3WhereTrace & 0x8 ){
133896          sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
133897          whereLoopPrint(pTemplate, pBuilder->pWC);
133898        }
133899  #endif
133900      }
133901      return SQLITE_OK;
133902    }
133903  
133904    /* Look for an existing WhereLoop to replace with pTemplate
133905    */
133906    whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
133907    ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
133908  
133909    if( ppPrev==0 ){
133910      /* There already exists a WhereLoop on the list that is better
133911      ** than pTemplate, so just ignore pTemplate */
133912  #if WHERETRACE_ENABLED /* 0x8 */
133913      if( sqlite3WhereTrace & 0x8 ){
133914        sqlite3DebugPrintf("   skip: ");
133915        whereLoopPrint(pTemplate, pBuilder->pWC);
133916      }
133917  #endif
133918      return SQLITE_OK;  
133919    }else{
133920      p = *ppPrev;
133921    }
133922  
133923    /* If we reach this point it means that either p[] should be overwritten
133924    ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
133925    ** WhereLoop and insert it.
133926    */
133927  #if WHERETRACE_ENABLED /* 0x8 */
133928    if( sqlite3WhereTrace & 0x8 ){
133929      if( p!=0 ){
133930        sqlite3DebugPrintf("replace: ");
133931        whereLoopPrint(p, pBuilder->pWC);
133932        sqlite3DebugPrintf("   with: ");
133933      }else{
133934        sqlite3DebugPrintf("    add: ");
133935      }
133936      whereLoopPrint(pTemplate, pBuilder->pWC);
133937    }
133938  #endif
133939    if( p==0 ){
133940      /* Allocate a new WhereLoop to add to the end of the list */
133941      *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
133942      if( p==0 ) return SQLITE_NOMEM_BKPT;
133943      whereLoopInit(p);
133944      p->pNextLoop = 0;
133945    }else{
133946      /* We will be overwriting WhereLoop p[].  But before we do, first
133947      ** go through the rest of the list and delete any other entries besides
133948      ** p[] that are also supplated by pTemplate */
133949      WhereLoop **ppTail = &p->pNextLoop;
133950      WhereLoop *pToDel;
133951      while( *ppTail ){
133952        ppTail = whereLoopFindLesser(ppTail, pTemplate);
133953        if( ppTail==0 ) break;
133954        pToDel = *ppTail;
133955        if( pToDel==0 ) break;
133956        *ppTail = pToDel->pNextLoop;
133957  #if WHERETRACE_ENABLED /* 0x8 */
133958        if( sqlite3WhereTrace & 0x8 ){
133959          sqlite3DebugPrintf(" delete: ");
133960          whereLoopPrint(pToDel, pBuilder->pWC);
133961        }
133962  #endif
133963        whereLoopDelete(db, pToDel);
133964      }
133965    }
133966    rc = whereLoopXfer(db, p, pTemplate);
133967    if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
133968      Index *pIndex = p->u.btree.pIndex;
133969      if( pIndex && pIndex->tnum==0 ){
133970        p->u.btree.pIndex = 0;
133971      }
133972    }
133973    return rc;
133974  }
133975  
133976  /*
133977  ** Adjust the WhereLoop.nOut value downward to account for terms of the
133978  ** WHERE clause that reference the loop but which are not used by an
133979  ** index.
133980  *
133981  ** For every WHERE clause term that is not used by the index
133982  ** and which has a truth probability assigned by one of the likelihood(),
133983  ** likely(), or unlikely() SQL functions, reduce the estimated number
133984  ** of output rows by the probability specified.
133985  **
133986  ** TUNING:  For every WHERE clause term that is not used by the index
133987  ** and which does not have an assigned truth probability, heuristics
133988  ** described below are used to try to estimate the truth probability.
133989  ** TODO --> Perhaps this is something that could be improved by better
133990  ** table statistics.
133991  **
133992  ** Heuristic 1:  Estimate the truth probability as 93.75%.  The 93.75%
133993  ** value corresponds to -1 in LogEst notation, so this means decrement
133994  ** the WhereLoop.nOut field for every such WHERE clause term.
133995  **
133996  ** Heuristic 2:  If there exists one or more WHERE clause terms of the
133997  ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
133998  ** final output row estimate is no greater than 1/4 of the total number
133999  ** of rows in the table.  In other words, assume that x==EXPR will filter
134000  ** out at least 3 out of 4 rows.  If EXPR is -1 or 0 or 1, then maybe the
134001  ** "x" column is boolean or else -1 or 0 or 1 is a common default value
134002  ** on the "x" column and so in that case only cap the output row estimate
134003  ** at 1/2 instead of 1/4.
134004  */
134005  static void whereLoopOutputAdjust(
134006    WhereClause *pWC,      /* The WHERE clause */
134007    WhereLoop *pLoop,      /* The loop to adjust downward */
134008    LogEst nRow            /* Number of rows in the entire table */
134009  ){
134010    WhereTerm *pTerm, *pX;
134011    Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
134012    int i, j, k;
134013    LogEst iReduce = 0;    /* pLoop->nOut should not exceed nRow-iReduce */
134014  
134015    assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
134016    for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
134017      if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
134018      if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
134019      if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
134020      for(j=pLoop->nLTerm-1; j>=0; j--){
134021        pX = pLoop->aLTerm[j];
134022        if( pX==0 ) continue;
134023        if( pX==pTerm ) break;
134024        if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
134025      }
134026      if( j<0 ){
134027        if( pTerm->truthProb<=0 ){
134028          /* If a truth probability is specified using the likelihood() hints,
134029          ** then use the probability provided by the application. */
134030          pLoop->nOut += pTerm->truthProb;
134031        }else{
134032          /* In the absence of explicit truth probabilities, use heuristics to
134033          ** guess a reasonable truth probability. */
134034          pLoop->nOut--;
134035          if( pTerm->eOperator&(WO_EQ|WO_IS) ){
134036            Expr *pRight = pTerm->pExpr->pRight;
134037            testcase( pTerm->pExpr->op==TK_IS );
134038            if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
134039              k = 10;
134040            }else{
134041              k = 20;
134042            }
134043            if( iReduce<k ) iReduce = k;
134044          }
134045        }
134046      }
134047    }
134048    if( pLoop->nOut > nRow-iReduce )  pLoop->nOut = nRow - iReduce;
134049  }
134050  
134051  /* 
134052  ** Term pTerm is a vector range comparison operation. The first comparison
134053  ** in the vector can be optimized using column nEq of the index. This
134054  ** function returns the total number of vector elements that can be used
134055  ** as part of the range comparison.
134056  **
134057  ** For example, if the query is:
134058  **
134059  **   WHERE a = ? AND (b, c, d) > (?, ?, ?)
134060  **
134061  ** and the index:
134062  **
134063  **   CREATE INDEX ... ON (a, b, c, d, e)
134064  **
134065  ** then this function would be invoked with nEq=1. The value returned in
134066  ** this case is 3.
134067  */
134068  static int whereRangeVectorLen(
134069    Parse *pParse,       /* Parsing context */
134070    int iCur,            /* Cursor open on pIdx */
134071    Index *pIdx,         /* The index to be used for a inequality constraint */
134072    int nEq,             /* Number of prior equality constraints on same index */
134073    WhereTerm *pTerm     /* The vector inequality constraint */
134074  ){
134075    int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
134076    int i;
134077  
134078    nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
134079    for(i=1; i<nCmp; i++){
134080      /* Test if comparison i of pTerm is compatible with column (i+nEq) 
134081      ** of the index. If not, exit the loop.  */
134082      char aff;                     /* Comparison affinity */
134083      char idxaff = 0;              /* Indexed columns affinity */
134084      CollSeq *pColl;               /* Comparison collation sequence */
134085      Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
134086      Expr *pRhs = pTerm->pExpr->pRight;
134087      if( pRhs->flags & EP_xIsSelect ){
134088        pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
134089      }else{
134090        pRhs = pRhs->x.pList->a[i].pExpr;
134091      }
134092  
134093      /* Check that the LHS of the comparison is a column reference to
134094      ** the right column of the right source table. And that the sort
134095      ** order of the index column is the same as the sort order of the
134096      ** leftmost index column.  */
134097      if( pLhs->op!=TK_COLUMN 
134098       || pLhs->iTable!=iCur 
134099       || pLhs->iColumn!=pIdx->aiColumn[i+nEq] 
134100       || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
134101      ){
134102        break;
134103      }
134104  
134105      testcase( pLhs->iColumn==XN_ROWID );
134106      aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
134107      idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
134108      if( aff!=idxaff ) break;
134109  
134110      pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
134111      if( pColl==0 ) break;
134112      if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
134113    }
134114    return i;
134115  }
134116  
134117  /*
134118  ** Adjust the cost C by the costMult facter T.  This only occurs if
134119  ** compiled with -DSQLITE_ENABLE_COSTMULT
134120  */
134121  #ifdef SQLITE_ENABLE_COSTMULT
134122  # define ApplyCostMultiplier(C,T)  C += T
134123  #else
134124  # define ApplyCostMultiplier(C,T)
134125  #endif
134126  
134127  /*
134128  ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the 
134129  ** index pIndex. Try to match one more.
134130  **
134131  ** When this function is called, pBuilder->pNew->nOut contains the 
134132  ** number of rows expected to be visited by filtering using the nEq 
134133  ** terms only. If it is modified, this value is restored before this 
134134  ** function returns.
134135  **
134136  ** If pProbe->tnum==0, that means pIndex is a fake index used for the
134137  ** INTEGER PRIMARY KEY.
134138  */
134139  static int whereLoopAddBtreeIndex(
134140    WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
134141    struct SrcList_item *pSrc,      /* FROM clause term being analyzed */
134142    Index *pProbe,                  /* An index on pSrc */
134143    LogEst nInMul                   /* log(Number of iterations due to IN) */
134144  ){
134145    WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */
134146    Parse *pParse = pWInfo->pParse;        /* Parsing context */
134147    sqlite3 *db = pParse->db;       /* Database connection malloc context */
134148    WhereLoop *pNew;                /* Template WhereLoop under construction */
134149    WhereTerm *pTerm;               /* A WhereTerm under consideration */
134150    int opMask;                     /* Valid operators for constraints */
134151    WhereScan scan;                 /* Iterator for WHERE terms */
134152    Bitmask saved_prereq;           /* Original value of pNew->prereq */
134153    u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
134154    u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */
134155    u16 saved_nBtm;                 /* Original value of pNew->u.btree.nBtm */
134156    u16 saved_nTop;                 /* Original value of pNew->u.btree.nTop */
134157    u16 saved_nSkip;                /* Original value of pNew->nSkip */
134158    u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
134159    LogEst saved_nOut;              /* Original value of pNew->nOut */
134160    int rc = SQLITE_OK;             /* Return code */
134161    LogEst rSize;                   /* Number of rows in the table */
134162    LogEst rLogSize;                /* Logarithm of table size */
134163    WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
134164  
134165    pNew = pBuilder->pNew;
134166    if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
134167    WHERETRACE(0x800, ("BEGIN addBtreeIdx(%s), nEq=%d\n",
134168                       pProbe->zName, pNew->u.btree.nEq));
134169  
134170    assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
134171    assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
134172    if( pNew->wsFlags & WHERE_BTM_LIMIT ){
134173      opMask = WO_LT|WO_LE;
134174    }else{
134175      assert( pNew->u.btree.nBtm==0 );
134176      opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
134177    }
134178    if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
134179  
134180    assert( pNew->u.btree.nEq<pProbe->nColumn );
134181  
134182    saved_nEq = pNew->u.btree.nEq;
134183    saved_nBtm = pNew->u.btree.nBtm;
134184    saved_nTop = pNew->u.btree.nTop;
134185    saved_nSkip = pNew->nSkip;
134186    saved_nLTerm = pNew->nLTerm;
134187    saved_wsFlags = pNew->wsFlags;
134188    saved_prereq = pNew->prereq;
134189    saved_nOut = pNew->nOut;
134190    pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
134191                          opMask, pProbe);
134192    pNew->rSetup = 0;
134193    rSize = pProbe->aiRowLogEst[0];
134194    rLogSize = estLog(rSize);
134195    for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
134196      u16 eOp = pTerm->eOperator;   /* Shorthand for pTerm->eOperator */
134197      LogEst rCostIdx;
134198      LogEst nOutUnadjusted;        /* nOut before IN() and WHERE adjustments */
134199      int nIn = 0;
134200  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
134201      int nRecValid = pBuilder->nRecValid;
134202  #endif
134203      if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
134204       && indexColumnNotNull(pProbe, saved_nEq)
134205      ){
134206        continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
134207      }
134208      if( pTerm->prereqRight & pNew->maskSelf ) continue;
134209  
134210      /* Do not allow the upper bound of a LIKE optimization range constraint
134211      ** to mix with a lower range bound from some other source */
134212      if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
134213  
134214      /* Do not allow IS constraints from the WHERE clause to be used by the
134215      ** right table of a LEFT JOIN.  Only constraints in the ON clause are
134216      ** allowed */
134217      if( (pSrc->fg.jointype & JT_LEFT)!=0
134218       && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
134219       && (eOp & (WO_IS|WO_ISNULL))!=0
134220      ){
134221        testcase( eOp & WO_IS );
134222        testcase( eOp & WO_ISNULL );
134223        continue;
134224      }
134225  
134226      if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
134227        pBuilder->bldFlags |= SQLITE_BLDF_UNIQUE;
134228      }else{
134229        pBuilder->bldFlags |= SQLITE_BLDF_INDEXED;
134230      }
134231      pNew->wsFlags = saved_wsFlags;
134232      pNew->u.btree.nEq = saved_nEq;
134233      pNew->u.btree.nBtm = saved_nBtm;
134234      pNew->u.btree.nTop = saved_nTop;
134235      pNew->nLTerm = saved_nLTerm;
134236      if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
134237      pNew->aLTerm[pNew->nLTerm++] = pTerm;
134238      pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
134239  
134240      assert( nInMul==0
134241          || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0 
134242          || (pNew->wsFlags & WHERE_COLUMN_IN)!=0 
134243          || (pNew->wsFlags & WHERE_SKIPSCAN)!=0 
134244      );
134245  
134246      if( eOp & WO_IN ){
134247        Expr *pExpr = pTerm->pExpr;
134248        pNew->wsFlags |= WHERE_COLUMN_IN;
134249        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
134250          /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
134251          int i;
134252          nIn = 46;  assert( 46==sqlite3LogEst(25) );
134253  
134254          /* The expression may actually be of the form (x, y) IN (SELECT...).
134255          ** In this case there is a separate term for each of (x) and (y).
134256          ** However, the nIn multiplier should only be applied once, not once
134257          ** for each such term. The following loop checks that pTerm is the
134258          ** first such term in use, and sets nIn back to 0 if it is not. */
134259          for(i=0; i<pNew->nLTerm-1; i++){
134260            if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
134261          }
134262        }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
134263          /* "x IN (value, value, ...)" */
134264          nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
134265          assert( nIn>0 );  /* RHS always has 2 or more terms...  The parser
134266                            ** changes "x IN (?)" into "x=?". */
134267        }
134268      }else if( eOp & (WO_EQ|WO_IS) ){
134269        int iCol = pProbe->aiColumn[saved_nEq];
134270        pNew->wsFlags |= WHERE_COLUMN_EQ;
134271        assert( saved_nEq==pNew->u.btree.nEq );
134272        if( iCol==XN_ROWID 
134273         || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
134274        ){
134275          if( iCol>=0 && pProbe->uniqNotNull==0 ){
134276            pNew->wsFlags |= WHERE_UNQ_WANTED;
134277          }else{
134278            pNew->wsFlags |= WHERE_ONEROW;
134279          }
134280        }
134281      }else if( eOp & WO_ISNULL ){
134282        pNew->wsFlags |= WHERE_COLUMN_NULL;
134283      }else if( eOp & (WO_GT|WO_GE) ){
134284        testcase( eOp & WO_GT );
134285        testcase( eOp & WO_GE );
134286        pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
134287        pNew->u.btree.nBtm = whereRangeVectorLen(
134288            pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
134289        );
134290        pBtm = pTerm;
134291        pTop = 0;
134292        if( pTerm->wtFlags & TERM_LIKEOPT ){
134293          /* Range contraints that come from the LIKE optimization are
134294          ** always used in pairs. */
134295          pTop = &pTerm[1];
134296          assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
134297          assert( pTop->wtFlags & TERM_LIKEOPT );
134298          assert( pTop->eOperator==WO_LT );
134299          if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
134300          pNew->aLTerm[pNew->nLTerm++] = pTop;
134301          pNew->wsFlags |= WHERE_TOP_LIMIT;
134302          pNew->u.btree.nTop = 1;
134303        }
134304      }else{
134305        assert( eOp & (WO_LT|WO_LE) );
134306        testcase( eOp & WO_LT );
134307        testcase( eOp & WO_LE );
134308        pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
134309        pNew->u.btree.nTop = whereRangeVectorLen(
134310            pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
134311        );
134312        pTop = pTerm;
134313        pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
134314                       pNew->aLTerm[pNew->nLTerm-2] : 0;
134315      }
134316  
134317      /* At this point pNew->nOut is set to the number of rows expected to
134318      ** be visited by the index scan before considering term pTerm, or the
134319      ** values of nIn and nInMul. In other words, assuming that all 
134320      ** "x IN(...)" terms are replaced with "x = ?". This block updates
134321      ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */
134322      assert( pNew->nOut==saved_nOut );
134323      if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
134324        /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
134325        ** data, using some other estimate.  */
134326        whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
134327      }else{
134328        int nEq = ++pNew->u.btree.nEq;
134329        assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
134330  
134331        assert( pNew->nOut==saved_nOut );
134332        if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
134333          assert( (eOp & WO_IN) || nIn==0 );
134334          testcase( eOp & WO_IN );
134335          pNew->nOut += pTerm->truthProb;
134336          pNew->nOut -= nIn;
134337        }else{
134338  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
134339          tRowcnt nOut = 0;
134340          if( nInMul==0 
134341           && pProbe->nSample 
134342           && pNew->u.btree.nEq<=pProbe->nSampleCol
134343           && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
134344          ){
134345            Expr *pExpr = pTerm->pExpr;
134346            if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
134347              testcase( eOp & WO_EQ );
134348              testcase( eOp & WO_IS );
134349              testcase( eOp & WO_ISNULL );
134350              rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
134351            }else{
134352              rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
134353            }
134354            if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
134355            if( rc!=SQLITE_OK ) break;          /* Jump out of the pTerm loop */
134356            if( nOut ){
134357              pNew->nOut = sqlite3LogEst(nOut);
134358              if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
134359              pNew->nOut -= nIn;
134360            }
134361          }
134362          if( nOut==0 )
134363  #endif
134364          {
134365            pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
134366            if( eOp & WO_ISNULL ){
134367              /* TUNING: If there is no likelihood() value, assume that a 
134368              ** "col IS NULL" expression matches twice as many rows 
134369              ** as (col=?). */
134370              pNew->nOut += 10;
134371            }
134372          }
134373        }
134374      }
134375  
134376      /* Set rCostIdx to the cost of visiting selected rows in index. Add
134377      ** it to pNew->rRun, which is currently set to the cost of the index
134378      ** seek only. Then, if this is a non-covering index, add the cost of
134379      ** visiting the rows in the main table.  */
134380      rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
134381      pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
134382      if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
134383        pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
134384      }
134385      ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
134386  
134387      nOutUnadjusted = pNew->nOut;
134388      pNew->rRun += nInMul + nIn;
134389      pNew->nOut += nInMul + nIn;
134390      whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
134391      rc = whereLoopInsert(pBuilder, pNew);
134392  
134393      if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
134394        pNew->nOut = saved_nOut;
134395      }else{
134396        pNew->nOut = nOutUnadjusted;
134397      }
134398  
134399      if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
134400       && pNew->u.btree.nEq<pProbe->nColumn
134401      ){
134402        whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
134403      }
134404      pNew->nOut = saved_nOut;
134405  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
134406      pBuilder->nRecValid = nRecValid;
134407  #endif
134408    }
134409    pNew->prereq = saved_prereq;
134410    pNew->u.btree.nEq = saved_nEq;
134411    pNew->u.btree.nBtm = saved_nBtm;
134412    pNew->u.btree.nTop = saved_nTop;
134413    pNew->nSkip = saved_nSkip;
134414    pNew->wsFlags = saved_wsFlags;
134415    pNew->nOut = saved_nOut;
134416    pNew->nLTerm = saved_nLTerm;
134417  
134418    /* Consider using a skip-scan if there are no WHERE clause constraints
134419    ** available for the left-most terms of the index, and if the average
134420    ** number of repeats in the left-most terms is at least 18. 
134421    **
134422    ** The magic number 18 is selected on the basis that scanning 17 rows
134423    ** is almost always quicker than an index seek (even though if the index
134424    ** contains fewer than 2^17 rows we assume otherwise in other parts of
134425    ** the code). And, even if it is not, it should not be too much slower. 
134426    ** On the other hand, the extra seeks could end up being significantly
134427    ** more expensive.  */
134428    assert( 42==sqlite3LogEst(18) );
134429    if( saved_nEq==saved_nSkip
134430     && saved_nEq+1<pProbe->nKeyCol
134431     && pProbe->noSkipScan==0
134432     && pProbe->aiRowLogEst[saved_nEq+1]>=42  /* TUNING: Minimum for skip-scan */
134433     && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
134434    ){
134435      LogEst nIter;
134436      pNew->u.btree.nEq++;
134437      pNew->nSkip++;
134438      pNew->aLTerm[pNew->nLTerm++] = 0;
134439      pNew->wsFlags |= WHERE_SKIPSCAN;
134440      nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
134441      pNew->nOut -= nIter;
134442      /* TUNING:  Because uncertainties in the estimates for skip-scan queries,
134443      ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
134444      nIter += 5;
134445      whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
134446      pNew->nOut = saved_nOut;
134447      pNew->u.btree.nEq = saved_nEq;
134448      pNew->nSkip = saved_nSkip;
134449      pNew->wsFlags = saved_wsFlags;
134450    }
134451  
134452    WHERETRACE(0x800, ("END addBtreeIdx(%s), nEq=%d, rc=%d\n",
134453                        pProbe->zName, saved_nEq, rc));
134454    return rc;
134455  }
134456  
134457  /*
134458  ** Return True if it is possible that pIndex might be useful in
134459  ** implementing the ORDER BY clause in pBuilder.
134460  **
134461  ** Return False if pBuilder does not contain an ORDER BY clause or
134462  ** if there is no way for pIndex to be useful in implementing that
134463  ** ORDER BY clause.
134464  */
134465  static int indexMightHelpWithOrderBy(
134466    WhereLoopBuilder *pBuilder,
134467    Index *pIndex,
134468    int iCursor
134469  ){
134470    ExprList *pOB;
134471    ExprList *aColExpr;
134472    int ii, jj;
134473  
134474    if( pIndex->bUnordered ) return 0;
134475    if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
134476    for(ii=0; ii<pOB->nExpr; ii++){
134477      Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
134478      if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
134479        if( pExpr->iColumn<0 ) return 1;
134480        for(jj=0; jj<pIndex->nKeyCol; jj++){
134481          if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
134482        }
134483      }else if( (aColExpr = pIndex->aColExpr)!=0 ){
134484        for(jj=0; jj<pIndex->nKeyCol; jj++){
134485          if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
134486          if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
134487            return 1;
134488          }
134489        }
134490      }
134491    }
134492    return 0;
134493  }
134494  
134495  /*
134496  ** Return a bitmask where 1s indicate that the corresponding column of
134497  ** the table is used by an index.  Only the first 63 columns are considered.
134498  */
134499  static Bitmask columnsInIndex(Index *pIdx){
134500    Bitmask m = 0;
134501    int j;
134502    for(j=pIdx->nColumn-1; j>=0; j--){
134503      int x = pIdx->aiColumn[j];
134504      if( x>=0 ){
134505        testcase( x==BMS-1 );
134506        testcase( x==BMS-2 );
134507        if( x<BMS-1 ) m |= MASKBIT(x);
134508      }
134509    }
134510    return m;
134511  }
134512  
134513  /* Check to see if a partial index with pPartIndexWhere can be used
134514  ** in the current query.  Return true if it can be and false if not.
134515  */
134516  static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
134517    int i;
134518    WhereTerm *pTerm;
134519    Parse *pParse = pWC->pWInfo->pParse;
134520    while( pWhere->op==TK_AND ){
134521      if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
134522      pWhere = pWhere->pRight;
134523    }
134524    if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0;
134525    for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
134526      Expr *pExpr = pTerm->pExpr;
134527      if( (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
134528       && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab) 
134529      ){
134530        return 1;
134531      }
134532    }
134533    return 0;
134534  }
134535  
134536  /*
134537  ** Add all WhereLoop objects for a single table of the join where the table
134538  ** is identified by pBuilder->pNew->iTab.  That table is guaranteed to be
134539  ** a b-tree table, not a virtual table.
134540  **
134541  ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
134542  ** are calculated as follows:
134543  **
134544  ** For a full scan, assuming the table (or index) contains nRow rows:
134545  **
134546  **     cost = nRow * 3.0                    // full-table scan
134547  **     cost = nRow * K                      // scan of covering index
134548  **     cost = nRow * (K+3.0)                // scan of non-covering index
134549  **
134550  ** where K is a value between 1.1 and 3.0 set based on the relative 
134551  ** estimated average size of the index and table records.
134552  **
134553  ** For an index scan, where nVisit is the number of index rows visited
134554  ** by the scan, and nSeek is the number of seek operations required on 
134555  ** the index b-tree:
134556  **
134557  **     cost = nSeek * (log(nRow) + K * nVisit)          // covering index
134558  **     cost = nSeek * (log(nRow) + (K+3.0) * nVisit)    // non-covering index
134559  **
134560  ** Normally, nSeek is 1. nSeek values greater than 1 come about if the 
134561  ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when 
134562  ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
134563  **
134564  ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
134565  ** of uncertainty.  For this reason, scoring is designed to pick plans that
134566  ** "do the least harm" if the estimates are inaccurate.  For example, a
134567  ** log(nRow) factor is omitted from a non-covering index scan in order to
134568  ** bias the scoring in favor of using an index, since the worst-case
134569  ** performance of using an index is far better than the worst-case performance
134570  ** of a full table scan.
134571  */
134572  static int whereLoopAddBtree(
134573    WhereLoopBuilder *pBuilder, /* WHERE clause information */
134574    Bitmask mPrereq             /* Extra prerequesites for using this table */
134575  ){
134576    WhereInfo *pWInfo;          /* WHERE analysis context */
134577    Index *pProbe;              /* An index we are evaluating */
134578    Index sPk;                  /* A fake index object for the primary key */
134579    LogEst aiRowEstPk[2];       /* The aiRowLogEst[] value for the sPk index */
134580    i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
134581    SrcList *pTabList;          /* The FROM clause */
134582    struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
134583    WhereLoop *pNew;            /* Template WhereLoop object */
134584    int rc = SQLITE_OK;         /* Return code */
134585    int iSortIdx = 1;           /* Index number */
134586    int b;                      /* A boolean value */
134587    LogEst rSize;               /* number of rows in the table */
134588    LogEst rLogSize;            /* Logarithm of the number of rows in the table */
134589    WhereClause *pWC;           /* The parsed WHERE clause */
134590    Table *pTab;                /* Table being queried */
134591    
134592    pNew = pBuilder->pNew;
134593    pWInfo = pBuilder->pWInfo;
134594    pTabList = pWInfo->pTabList;
134595    pSrc = pTabList->a + pNew->iTab;
134596    pTab = pSrc->pTab;
134597    pWC = pBuilder->pWC;
134598    assert( !IsVirtual(pSrc->pTab) );
134599  
134600    if( pSrc->pIBIndex ){
134601      /* An INDEXED BY clause specifies a particular index to use */
134602      pProbe = pSrc->pIBIndex;
134603    }else if( !HasRowid(pTab) ){
134604      pProbe = pTab->pIndex;
134605    }else{
134606      /* There is no INDEXED BY clause.  Create a fake Index object in local
134607      ** variable sPk to represent the rowid primary key index.  Make this
134608      ** fake index the first in a chain of Index objects with all of the real
134609      ** indices to follow */
134610      Index *pFirst;                  /* First of real indices on the table */
134611      memset(&sPk, 0, sizeof(Index));
134612      sPk.nKeyCol = 1;
134613      sPk.nColumn = 1;
134614      sPk.aiColumn = &aiColumnPk;
134615      sPk.aiRowLogEst = aiRowEstPk;
134616      sPk.onError = OE_Replace;
134617      sPk.pTable = pTab;
134618      sPk.szIdxRow = pTab->szTabRow;
134619      aiRowEstPk[0] = pTab->nRowLogEst;
134620      aiRowEstPk[1] = 0;
134621      pFirst = pSrc->pTab->pIndex;
134622      if( pSrc->fg.notIndexed==0 ){
134623        /* The real indices of the table are only considered if the
134624        ** NOT INDEXED qualifier is omitted from the FROM clause */
134625        sPk.pNext = pFirst;
134626      }
134627      pProbe = &sPk;
134628    }
134629    rSize = pTab->nRowLogEst;
134630    rLogSize = estLog(rSize);
134631  
134632  #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
134633    /* Automatic indexes */
134634    if( !pBuilder->pOrSet      /* Not part of an OR optimization */
134635     && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
134636     && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
134637     && pSrc->pIBIndex==0      /* Has no INDEXED BY clause */
134638     && !pSrc->fg.notIndexed   /* Has no NOT INDEXED clause */
134639     && HasRowid(pTab)         /* Not WITHOUT ROWID table. (FIXME: Why not?) */
134640     && !pSrc->fg.isCorrelated /* Not a correlated subquery */
134641     && !pSrc->fg.isRecursive  /* Not a recursive common table expression. */
134642    ){
134643      /* Generate auto-index WhereLoops */
134644      WhereTerm *pTerm;
134645      WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
134646      for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
134647        if( pTerm->prereqRight & pNew->maskSelf ) continue;
134648        if( termCanDriveIndex(pTerm, pSrc, 0) ){
134649          pNew->u.btree.nEq = 1;
134650          pNew->nSkip = 0;
134651          pNew->u.btree.pIndex = 0;
134652          pNew->nLTerm = 1;
134653          pNew->aLTerm[0] = pTerm;
134654          /* TUNING: One-time cost for computing the automatic index is
134655          ** estimated to be X*N*log2(N) where N is the number of rows in
134656          ** the table being indexed and where X is 7 (LogEst=28) for normal
134657          ** tables or 1.375 (LogEst=4) for views and subqueries.  The value
134658          ** of X is smaller for views and subqueries so that the query planner
134659          ** will be more aggressive about generating automatic indexes for
134660          ** those objects, since there is no opportunity to add schema
134661          ** indexes on subqueries and views. */
134662          pNew->rSetup = rLogSize + rSize + 4;
134663          if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
134664            pNew->rSetup += 24;
134665          }
134666          ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
134667          if( pNew->rSetup<0 ) pNew->rSetup = 0;
134668          /* TUNING: Each index lookup yields 20 rows in the table.  This
134669          ** is more than the usual guess of 10 rows, since we have no way
134670          ** of knowing how selective the index will ultimately be.  It would
134671          ** not be unreasonable to make this value much larger. */
134672          pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
134673          pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
134674          pNew->wsFlags = WHERE_AUTO_INDEX;
134675          pNew->prereq = mPrereq | pTerm->prereqRight;
134676          rc = whereLoopInsert(pBuilder, pNew);
134677        }
134678      }
134679    }
134680  #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
134681  
134682    /* Loop over all indices
134683    */
134684    for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
134685      if( pProbe->pPartIdxWhere!=0
134686       && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
134687        testcase( pNew->iTab!=pSrc->iCursor );  /* See ticket [98d973b8f5] */
134688        continue;  /* Partial index inappropriate for this query */
134689      }
134690      rSize = pProbe->aiRowLogEst[0];
134691      pNew->u.btree.nEq = 0;
134692      pNew->u.btree.nBtm = 0;
134693      pNew->u.btree.nTop = 0;
134694      pNew->nSkip = 0;
134695      pNew->nLTerm = 0;
134696      pNew->iSortIdx = 0;
134697      pNew->rSetup = 0;
134698      pNew->prereq = mPrereq;
134699      pNew->nOut = rSize;
134700      pNew->u.btree.pIndex = pProbe;
134701      b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
134702      /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
134703      assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
134704      if( pProbe->tnum<=0 ){
134705        /* Integer primary key index */
134706        pNew->wsFlags = WHERE_IPK;
134707  
134708        /* Full table scan */
134709        pNew->iSortIdx = b ? iSortIdx : 0;
134710        /* TUNING: Cost of full table scan is (N*3.0). */
134711        pNew->rRun = rSize + 16;
134712        ApplyCostMultiplier(pNew->rRun, pTab->costMult);
134713        whereLoopOutputAdjust(pWC, pNew, rSize);
134714        rc = whereLoopInsert(pBuilder, pNew);
134715        pNew->nOut = rSize;
134716        if( rc ) break;
134717      }else{
134718        Bitmask m;
134719        if( pProbe->isCovering ){
134720          pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
134721          m = 0;
134722        }else{
134723          m = pSrc->colUsed & ~columnsInIndex(pProbe);
134724          pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
134725        }
134726  
134727        /* Full scan via index */
134728        if( b
134729         || !HasRowid(pTab)
134730         || pProbe->pPartIdxWhere!=0
134731         || ( m==0
134732           && pProbe->bUnordered==0
134733           && (pProbe->szIdxRow<pTab->szTabRow)
134734           && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
134735           && sqlite3GlobalConfig.bUseCis
134736           && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
134737            )
134738        ){
134739          pNew->iSortIdx = b ? iSortIdx : 0;
134740  
134741          /* The cost of visiting the index rows is N*K, where K is
134742          ** between 1.1 and 3.0, depending on the relative sizes of the
134743          ** index and table rows. */
134744          pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
134745          if( m!=0 ){
134746            /* If this is a non-covering index scan, add in the cost of
134747            ** doing table lookups.  The cost will be 3x the number of
134748            ** lookups.  Take into account WHERE clause terms that can be
134749            ** satisfied using just the index, and that do not require a
134750            ** table lookup. */
134751            LogEst nLookup = rSize + 16;  /* Base cost:  N*3 */
134752            int ii;
134753            int iCur = pSrc->iCursor;
134754            WhereClause *pWC2 = &pWInfo->sWC;
134755            for(ii=0; ii<pWC2->nTerm; ii++){
134756              WhereTerm *pTerm = &pWC2->a[ii];
134757              if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
134758                break;
134759              }
134760              /* pTerm can be evaluated using just the index.  So reduce
134761              ** the expected number of table lookups accordingly */
134762              if( pTerm->truthProb<=0 ){
134763                nLookup += pTerm->truthProb;
134764              }else{
134765                nLookup--;
134766                if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
134767              }
134768            }
134769            
134770            pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
134771          }
134772          ApplyCostMultiplier(pNew->rRun, pTab->costMult);
134773          whereLoopOutputAdjust(pWC, pNew, rSize);
134774          rc = whereLoopInsert(pBuilder, pNew);
134775          pNew->nOut = rSize;
134776          if( rc ) break;
134777        }
134778      }
134779  
134780      pBuilder->bldFlags = 0;
134781      rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
134782      if( pBuilder->bldFlags==SQLITE_BLDF_INDEXED ){
134783        /* If a non-unique index is used, or if a prefix of the key for
134784        ** unique index is used (making the index functionally non-unique)
134785        ** then the sqlite_stat1 data becomes important for scoring the
134786        ** plan */
134787        pTab->tabFlags |= TF_StatsUsed;
134788      }
134789  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
134790      sqlite3Stat4ProbeFree(pBuilder->pRec);
134791      pBuilder->nRecValid = 0;
134792      pBuilder->pRec = 0;
134793  #endif
134794  
134795      /* If there was an INDEXED BY clause, then only that one index is
134796      ** considered. */
134797      if( pSrc->pIBIndex ) break;
134798    }
134799    return rc;
134800  }
134801  
134802  #ifndef SQLITE_OMIT_VIRTUALTABLE
134803  
134804  /*
134805  ** Argument pIdxInfo is already populated with all constraints that may
134806  ** be used by the virtual table identified by pBuilder->pNew->iTab. This
134807  ** function marks a subset of those constraints usable, invokes the
134808  ** xBestIndex method and adds the returned plan to pBuilder.
134809  **
134810  ** A constraint is marked usable if:
134811  **
134812  **   * Argument mUsable indicates that its prerequisites are available, and
134813  **
134814  **   * It is not one of the operators specified in the mExclude mask passed
134815  **     as the fourth argument (which in practice is either WO_IN or 0).
134816  **
134817  ** Argument mPrereq is a mask of tables that must be scanned before the
134818  ** virtual table in question. These are added to the plans prerequisites
134819  ** before it is added to pBuilder.
134820  **
134821  ** Output parameter *pbIn is set to true if the plan added to pBuilder
134822  ** uses one or more WO_IN terms, or false otherwise.
134823  */
134824  static int whereLoopAddVirtualOne(
134825    WhereLoopBuilder *pBuilder,
134826    Bitmask mPrereq,                /* Mask of tables that must be used. */
134827    Bitmask mUsable,                /* Mask of usable tables */
134828    u16 mExclude,                   /* Exclude terms using these operators */
134829    sqlite3_index_info *pIdxInfo,   /* Populated object for xBestIndex */
134830    u16 mNoOmit,                    /* Do not omit these constraints */
134831    int *pbIn                       /* OUT: True if plan uses an IN(...) op */
134832  ){
134833    WhereClause *pWC = pBuilder->pWC;
134834    struct sqlite3_index_constraint *pIdxCons;
134835    struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
134836    int i;
134837    int mxTerm;
134838    int rc = SQLITE_OK;
134839    WhereLoop *pNew = pBuilder->pNew;
134840    Parse *pParse = pBuilder->pWInfo->pParse;
134841    struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
134842    int nConstraint = pIdxInfo->nConstraint;
134843  
134844    assert( (mUsable & mPrereq)==mPrereq );
134845    *pbIn = 0;
134846    pNew->prereq = mPrereq;
134847  
134848    /* Set the usable flag on the subset of constraints identified by 
134849    ** arguments mUsable and mExclude. */
134850    pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
134851    for(i=0; i<nConstraint; i++, pIdxCons++){
134852      WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
134853      pIdxCons->usable = 0;
134854      if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight 
134855       && (pTerm->eOperator & mExclude)==0
134856      ){
134857        pIdxCons->usable = 1;
134858      }
134859    }
134860  
134861    /* Initialize the output fields of the sqlite3_index_info structure */
134862    memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
134863    assert( pIdxInfo->needToFreeIdxStr==0 );
134864    pIdxInfo->idxStr = 0;
134865    pIdxInfo->idxNum = 0;
134866    pIdxInfo->orderByConsumed = 0;
134867    pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
134868    pIdxInfo->estimatedRows = 25;
134869    pIdxInfo->idxFlags = 0;
134870    pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
134871  
134872    /* Invoke the virtual table xBestIndex() method */
134873    rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
134874    if( rc ) return rc;
134875  
134876    mxTerm = -1;
134877    assert( pNew->nLSlot>=nConstraint );
134878    for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
134879    pNew->u.vtab.omitMask = 0;
134880    pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
134881    for(i=0; i<nConstraint; i++, pIdxCons++){
134882      int iTerm;
134883      if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
134884        WhereTerm *pTerm;
134885        int j = pIdxCons->iTermOffset;
134886        if( iTerm>=nConstraint
134887         || j<0
134888         || j>=pWC->nTerm
134889         || pNew->aLTerm[iTerm]!=0
134890         || pIdxCons->usable==0
134891        ){
134892          rc = SQLITE_ERROR;
134893          sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
134894          return rc;
134895        }
134896        testcase( iTerm==nConstraint-1 );
134897        testcase( j==0 );
134898        testcase( j==pWC->nTerm-1 );
134899        pTerm = &pWC->a[j];
134900        pNew->prereq |= pTerm->prereqRight;
134901        assert( iTerm<pNew->nLSlot );
134902        pNew->aLTerm[iTerm] = pTerm;
134903        if( iTerm>mxTerm ) mxTerm = iTerm;
134904        testcase( iTerm==15 );
134905        testcase( iTerm==16 );
134906        if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
134907        if( (pTerm->eOperator & WO_IN)!=0 ){
134908          /* A virtual table that is constrained by an IN clause may not
134909          ** consume the ORDER BY clause because (1) the order of IN terms
134910          ** is not necessarily related to the order of output terms and
134911          ** (2) Multiple outputs from a single IN value will not merge
134912          ** together.  */
134913          pIdxInfo->orderByConsumed = 0;
134914          pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
134915          *pbIn = 1; assert( (mExclude & WO_IN)==0 );
134916        }
134917      }
134918    }
134919    pNew->u.vtab.omitMask &= ~mNoOmit;
134920  
134921    pNew->nLTerm = mxTerm+1;
134922    assert( pNew->nLTerm<=pNew->nLSlot );
134923    pNew->u.vtab.idxNum = pIdxInfo->idxNum;
134924    pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
134925    pIdxInfo->needToFreeIdxStr = 0;
134926    pNew->u.vtab.idxStr = pIdxInfo->idxStr;
134927    pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
134928        pIdxInfo->nOrderBy : 0);
134929    pNew->rSetup = 0;
134930    pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
134931    pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
134932  
134933    /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
134934    ** that the scan will visit at most one row. Clear it otherwise. */
134935    if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
134936      pNew->wsFlags |= WHERE_ONEROW;
134937    }else{
134938      pNew->wsFlags &= ~WHERE_ONEROW;
134939    }
134940    rc = whereLoopInsert(pBuilder, pNew);
134941    if( pNew->u.vtab.needFree ){
134942      sqlite3_free(pNew->u.vtab.idxStr);
134943      pNew->u.vtab.needFree = 0;
134944    }
134945    WHERETRACE(0xffff, ("  bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
134946                        *pbIn, (sqlite3_uint64)mPrereq,
134947                        (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
134948  
134949    return rc;
134950  }
134951  
134952  
134953  /*
134954  ** Add all WhereLoop objects for a table of the join identified by
134955  ** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
134956  **
134957  ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
134958  ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
134959  ** entries that occur before the virtual table in the FROM clause and are
134960  ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
134961  ** mUnusable mask contains all FROM clause entries that occur after the
134962  ** virtual table and are separated from it by at least one LEFT or 
134963  ** CROSS JOIN. 
134964  **
134965  ** For example, if the query were:
134966  **
134967  **   ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
134968  **
134969  ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
134970  **
134971  ** All the tables in mPrereq must be scanned before the current virtual 
134972  ** table. So any terms for which all prerequisites are satisfied by 
134973  ** mPrereq may be specified as "usable" in all calls to xBestIndex. 
134974  ** Conversely, all tables in mUnusable must be scanned after the current
134975  ** virtual table, so any terms for which the prerequisites overlap with
134976  ** mUnusable should always be configured as "not-usable" for xBestIndex.
134977  */
134978  static int whereLoopAddVirtual(
134979    WhereLoopBuilder *pBuilder,  /* WHERE clause information */
134980    Bitmask mPrereq,             /* Tables that must be scanned before this one */
134981    Bitmask mUnusable            /* Tables that must be scanned after this one */
134982  ){
134983    int rc = SQLITE_OK;          /* Return code */
134984    WhereInfo *pWInfo;           /* WHERE analysis context */
134985    Parse *pParse;               /* The parsing context */
134986    WhereClause *pWC;            /* The WHERE clause */
134987    struct SrcList_item *pSrc;   /* The FROM clause term to search */
134988    sqlite3_index_info *p;       /* Object to pass to xBestIndex() */
134989    int nConstraint;             /* Number of constraints in p */
134990    int bIn;                     /* True if plan uses IN(...) operator */
134991    WhereLoop *pNew;
134992    Bitmask mBest;               /* Tables used by best possible plan */
134993    u16 mNoOmit;
134994  
134995    assert( (mPrereq & mUnusable)==0 );
134996    pWInfo = pBuilder->pWInfo;
134997    pParse = pWInfo->pParse;
134998    pWC = pBuilder->pWC;
134999    pNew = pBuilder->pNew;
135000    pSrc = &pWInfo->pTabList->a[pNew->iTab];
135001    assert( IsVirtual(pSrc->pTab) );
135002    p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy, 
135003        &mNoOmit);
135004    if( p==0 ) return SQLITE_NOMEM_BKPT;
135005    pNew->rSetup = 0;
135006    pNew->wsFlags = WHERE_VIRTUALTABLE;
135007    pNew->nLTerm = 0;
135008    pNew->u.vtab.needFree = 0;
135009    nConstraint = p->nConstraint;
135010    if( whereLoopResize(pParse->db, pNew, nConstraint) ){
135011      sqlite3DbFree(pParse->db, p);
135012      return SQLITE_NOMEM_BKPT;
135013    }
135014  
135015    /* First call xBestIndex() with all constraints usable. */
135016    WHERETRACE(0x40, ("  VirtualOne: all usable\n"));
135017    rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn);
135018  
135019    /* If the call to xBestIndex() with all terms enabled produced a plan
135020    ** that does not require any source tables (IOW: a plan with mBest==0),
135021    ** then there is no point in making any further calls to xBestIndex() 
135022    ** since they will all return the same result (if the xBestIndex()
135023    ** implementation is sane). */
135024    if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){
135025      int seenZero = 0;             /* True if a plan with no prereqs seen */
135026      int seenZeroNoIN = 0;         /* Plan with no prereqs and no IN(...) seen */
135027      Bitmask mPrev = 0;
135028      Bitmask mBestNoIn = 0;
135029  
135030      /* If the plan produced by the earlier call uses an IN(...) term, call
135031      ** xBestIndex again, this time with IN(...) terms disabled. */
135032      if( bIn ){
135033        WHERETRACE(0x40, ("  VirtualOne: all usable w/o IN\n"));
135034        rc = whereLoopAddVirtualOne(
135035            pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn);
135036        assert( bIn==0 );
135037        mBestNoIn = pNew->prereq & ~mPrereq;
135038        if( mBestNoIn==0 ){
135039          seenZero = 1;
135040          seenZeroNoIN = 1;
135041        }
135042      }
135043  
135044      /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq) 
135045      ** in the set of terms that apply to the current virtual table.  */
135046      while( rc==SQLITE_OK ){
135047        int i;
135048        Bitmask mNext = ALLBITS;
135049        assert( mNext>0 );
135050        for(i=0; i<nConstraint; i++){
135051          Bitmask mThis = (
135052              pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
135053          );
135054          if( mThis>mPrev && mThis<mNext ) mNext = mThis;
135055        }
135056        mPrev = mNext;
135057        if( mNext==ALLBITS ) break;
135058        if( mNext==mBest || mNext==mBestNoIn ) continue;
135059        WHERETRACE(0x40, ("  VirtualOne: mPrev=%04llx mNext=%04llx\n",
135060                         (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
135061        rc = whereLoopAddVirtualOne(
135062            pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn);
135063        if( pNew->prereq==mPrereq ){
135064          seenZero = 1;
135065          if( bIn==0 ) seenZeroNoIN = 1;
135066        }
135067      }
135068  
135069      /* If the calls to xBestIndex() in the above loop did not find a plan
135070      ** that requires no source tables at all (i.e. one guaranteed to be
135071      ** usable), make a call here with all source tables disabled */
135072      if( rc==SQLITE_OK && seenZero==0 ){
135073        WHERETRACE(0x40, ("  VirtualOne: all disabled\n"));
135074        rc = whereLoopAddVirtualOne(
135075            pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn);
135076        if( bIn==0 ) seenZeroNoIN = 1;
135077      }
135078  
135079      /* If the calls to xBestIndex() have so far failed to find a plan
135080      ** that requires no source tables at all and does not use an IN(...)
135081      ** operator, make a final call to obtain one here.  */
135082      if( rc==SQLITE_OK && seenZeroNoIN==0 ){
135083        WHERETRACE(0x40, ("  VirtualOne: all disabled and w/o IN\n"));
135084        rc = whereLoopAddVirtualOne(
135085            pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn);
135086      }
135087    }
135088  
135089    if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
135090    sqlite3DbFreeNN(pParse->db, p);
135091    return rc;
135092  }
135093  #endif /* SQLITE_OMIT_VIRTUALTABLE */
135094  
135095  /*
135096  ** Add WhereLoop entries to handle OR terms.  This works for either
135097  ** btrees or virtual tables.
135098  */
135099  static int whereLoopAddOr(
135100    WhereLoopBuilder *pBuilder, 
135101    Bitmask mPrereq, 
135102    Bitmask mUnusable
135103  ){
135104    WhereInfo *pWInfo = pBuilder->pWInfo;
135105    WhereClause *pWC;
135106    WhereLoop *pNew;
135107    WhereTerm *pTerm, *pWCEnd;
135108    int rc = SQLITE_OK;
135109    int iCur;
135110    WhereClause tempWC;
135111    WhereLoopBuilder sSubBuild;
135112    WhereOrSet sSum, sCur;
135113    struct SrcList_item *pItem;
135114    
135115    pWC = pBuilder->pWC;
135116    pWCEnd = pWC->a + pWC->nTerm;
135117    pNew = pBuilder->pNew;
135118    memset(&sSum, 0, sizeof(sSum));
135119    pItem = pWInfo->pTabList->a + pNew->iTab;
135120    iCur = pItem->iCursor;
135121  
135122    for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
135123      if( (pTerm->eOperator & WO_OR)!=0
135124       && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0 
135125      ){
135126        WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
135127        WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
135128        WhereTerm *pOrTerm;
135129        int once = 1;
135130        int i, j;
135131      
135132        sSubBuild = *pBuilder;
135133        sSubBuild.pOrderBy = 0;
135134        sSubBuild.pOrSet = &sCur;
135135  
135136        WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
135137        for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
135138          if( (pOrTerm->eOperator & WO_AND)!=0 ){
135139            sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
135140          }else if( pOrTerm->leftCursor==iCur ){
135141            tempWC.pWInfo = pWC->pWInfo;
135142            tempWC.pOuter = pWC;
135143            tempWC.op = TK_AND;
135144            tempWC.nTerm = 1;
135145            tempWC.a = pOrTerm;
135146            sSubBuild.pWC = &tempWC;
135147          }else{
135148            continue;
135149          }
135150          sCur.n = 0;
135151  #ifdef WHERETRACE_ENABLED
135152          WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n", 
135153                     (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
135154          if( sqlite3WhereTrace & 0x400 ){
135155            sqlite3WhereClausePrint(sSubBuild.pWC);
135156          }
135157  #endif
135158  #ifndef SQLITE_OMIT_VIRTUALTABLE
135159          if( IsVirtual(pItem->pTab) ){
135160            rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
135161          }else
135162  #endif
135163          {
135164            rc = whereLoopAddBtree(&sSubBuild, mPrereq);
135165          }
135166          if( rc==SQLITE_OK ){
135167            rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
135168          }
135169          assert( rc==SQLITE_OK || sCur.n==0 );
135170          if( sCur.n==0 ){
135171            sSum.n = 0;
135172            break;
135173          }else if( once ){
135174            whereOrMove(&sSum, &sCur);
135175            once = 0;
135176          }else{
135177            WhereOrSet sPrev;
135178            whereOrMove(&sPrev, &sSum);
135179            sSum.n = 0;
135180            for(i=0; i<sPrev.n; i++){
135181              for(j=0; j<sCur.n; j++){
135182                whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
135183                              sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
135184                              sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
135185              }
135186            }
135187          }
135188        }
135189        pNew->nLTerm = 1;
135190        pNew->aLTerm[0] = pTerm;
135191        pNew->wsFlags = WHERE_MULTI_OR;
135192        pNew->rSetup = 0;
135193        pNew->iSortIdx = 0;
135194        memset(&pNew->u, 0, sizeof(pNew->u));
135195        for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
135196          /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
135197          ** of all sub-scans required by the OR-scan. However, due to rounding
135198          ** errors, it may be that the cost of the OR-scan is equal to its
135199          ** most expensive sub-scan. Add the smallest possible penalty 
135200          ** (equivalent to multiplying the cost by 1.07) to ensure that 
135201          ** this does not happen. Otherwise, for WHERE clauses such as the
135202          ** following where there is an index on "y":
135203          **
135204          **     WHERE likelihood(x=?, 0.99) OR y=?
135205          **
135206          ** the planner may elect to "OR" together a full-table scan and an
135207          ** index lookup. And other similarly odd results.  */
135208          pNew->rRun = sSum.a[i].rRun + 1;
135209          pNew->nOut = sSum.a[i].nOut;
135210          pNew->prereq = sSum.a[i].prereq;
135211          rc = whereLoopInsert(pBuilder, pNew);
135212        }
135213        WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
135214      }
135215    }
135216    return rc;
135217  }
135218  
135219  /*
135220  ** Add all WhereLoop objects for all tables 
135221  */
135222  static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
135223    WhereInfo *pWInfo = pBuilder->pWInfo;
135224    Bitmask mPrereq = 0;
135225    Bitmask mPrior = 0;
135226    int iTab;
135227    SrcList *pTabList = pWInfo->pTabList;
135228    struct SrcList_item *pItem;
135229    struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
135230    sqlite3 *db = pWInfo->pParse->db;
135231    int rc = SQLITE_OK;
135232    WhereLoop *pNew;
135233    u8 priorJointype = 0;
135234  
135235    /* Loop over the tables in the join, from left to right */
135236    pNew = pBuilder->pNew;
135237    whereLoopInit(pNew);
135238    for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
135239      Bitmask mUnusable = 0;
135240      pNew->iTab = iTab;
135241      pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
135242      if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
135243        /* This condition is true when pItem is the FROM clause term on the
135244        ** right-hand-side of a LEFT or CROSS JOIN.  */
135245        mPrereq = mPrior;
135246      }
135247      priorJointype = pItem->fg.jointype;
135248  #ifndef SQLITE_OMIT_VIRTUALTABLE
135249      if( IsVirtual(pItem->pTab) ){
135250        struct SrcList_item *p;
135251        for(p=&pItem[1]; p<pEnd; p++){
135252          if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
135253            mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
135254          }
135255        }
135256        rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
135257      }else
135258  #endif /* SQLITE_OMIT_VIRTUALTABLE */
135259      {
135260        rc = whereLoopAddBtree(pBuilder, mPrereq);
135261      }
135262      if( rc==SQLITE_OK ){
135263        rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
135264      }
135265      mPrior |= pNew->maskSelf;
135266      if( rc || db->mallocFailed ) break;
135267    }
135268  
135269    whereLoopClear(db, pNew);
135270    return rc;
135271  }
135272  
135273  /*
135274  ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
135275  ** parameters) to see if it outputs rows in the requested ORDER BY
135276  ** (or GROUP BY) without requiring a separate sort operation.  Return N:
135277  ** 
135278  **   N>0:   N terms of the ORDER BY clause are satisfied
135279  **   N==0:  No terms of the ORDER BY clause are satisfied
135280  **   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.   
135281  **
135282  ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
135283  ** strict.  With GROUP BY and DISTINCT the only requirement is that
135284  ** equivalent rows appear immediately adjacent to one another.  GROUP BY
135285  ** and DISTINCT do not require rows to appear in any particular order as long
135286  ** as equivalent rows are grouped together.  Thus for GROUP BY and DISTINCT
135287  ** the pOrderBy terms can be matched in any order.  With ORDER BY, the 
135288  ** pOrderBy terms must be matched in strict left-to-right order.
135289  */
135290  static i8 wherePathSatisfiesOrderBy(
135291    WhereInfo *pWInfo,    /* The WHERE clause */
135292    ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */
135293    WherePath *pPath,     /* The WherePath to check */
135294    u16 wctrlFlags,       /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
135295    u16 nLoop,            /* Number of entries in pPath->aLoop[] */
135296    WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */
135297    Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */
135298  ){
135299    u8 revSet;            /* True if rev is known */
135300    u8 rev;               /* Composite sort order */
135301    u8 revIdx;            /* Index sort order */
135302    u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */
135303    u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */
135304    u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */
135305    u16 eqOpMask;         /* Allowed equality operators */
135306    u16 nKeyCol;          /* Number of key columns in pIndex */
135307    u16 nColumn;          /* Total number of ordered columns in the index */
135308    u16 nOrderBy;         /* Number terms in the ORDER BY clause */
135309    int iLoop;            /* Index of WhereLoop in pPath being processed */
135310    int i, j;             /* Loop counters */
135311    int iCur;             /* Cursor number for current WhereLoop */
135312    int iColumn;          /* A column number within table iCur */
135313    WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
135314    WhereTerm *pTerm;     /* A single term of the WHERE clause */
135315    Expr *pOBExpr;        /* An expression from the ORDER BY clause */
135316    CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */
135317    Index *pIndex;        /* The index associated with pLoop */
135318    sqlite3 *db = pWInfo->pParse->db;  /* Database connection */
135319    Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */
135320    Bitmask obDone;       /* Mask of all ORDER BY terms */
135321    Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */
135322    Bitmask ready;              /* Mask of inner loops */
135323  
135324    /*
135325    ** We say the WhereLoop is "one-row" if it generates no more than one
135326    ** row of output.  A WhereLoop is one-row if all of the following are true:
135327    **  (a) All index columns match with WHERE_COLUMN_EQ.
135328    **  (b) The index is unique
135329    ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
135330    ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
135331    **
135332    ** We say the WhereLoop is "order-distinct" if the set of columns from
135333    ** that WhereLoop that are in the ORDER BY clause are different for every
135334    ** row of the WhereLoop.  Every one-row WhereLoop is automatically
135335    ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
135336    ** is not order-distinct. To be order-distinct is not quite the same as being
135337    ** UNIQUE since a UNIQUE column or index can have multiple rows that 
135338    ** are NULL and NULL values are equivalent for the purpose of order-distinct.
135339    ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
135340    **
135341    ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
135342    ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
135343    ** automatically order-distinct.
135344    */
135345  
135346    assert( pOrderBy!=0 );
135347    if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
135348  
135349    nOrderBy = pOrderBy->nExpr;
135350    testcase( nOrderBy==BMS-1 );
135351    if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */
135352    isOrderDistinct = 1;
135353    obDone = MASKBIT(nOrderBy)-1;
135354    orderDistinctMask = 0;
135355    ready = 0;
135356    eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
135357    if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;
135358    for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
135359      if( iLoop>0 ) ready |= pLoop->maskSelf;
135360      if( iLoop<nLoop ){
135361        pLoop = pPath->aLoop[iLoop];
135362        if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
135363      }else{
135364        pLoop = pLast;
135365      }
135366      if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
135367        if( pLoop->u.vtab.isOrdered ) obSat = obDone;
135368        break;
135369      }else{
135370        pLoop->u.btree.nIdxCol = 0;
135371      }
135372      iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
135373  
135374      /* Mark off any ORDER BY term X that is a column in the table of
135375      ** the current loop for which there is term in the WHERE
135376      ** clause of the form X IS NULL or X=? that reference only outer
135377      ** loops.
135378      */
135379      for(i=0; i<nOrderBy; i++){
135380        if( MASKBIT(i) & obSat ) continue;
135381        pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
135382        if( pOBExpr->op!=TK_COLUMN ) continue;
135383        if( pOBExpr->iTable!=iCur ) continue;
135384        pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
135385                         ~ready, eqOpMask, 0);
135386        if( pTerm==0 ) continue;
135387        if( pTerm->eOperator==WO_IN ){
135388          /* IN terms are only valid for sorting in the ORDER BY LIMIT 
135389          ** optimization, and then only if they are actually used
135390          ** by the query plan */
135391          assert( wctrlFlags & WHERE_ORDERBY_LIMIT );
135392          for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
135393          if( j>=pLoop->nLTerm ) continue;
135394        }
135395        if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
135396          if( sqlite3ExprCollSeqMatch(pWInfo->pParse, 
135397                    pOrderBy->a[i].pExpr, pTerm->pExpr)==0 ){
135398            continue;
135399          }
135400          testcase( pTerm->pExpr->op==TK_IS );
135401        }
135402        obSat |= MASKBIT(i);
135403      }
135404  
135405      if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
135406        if( pLoop->wsFlags & WHERE_IPK ){
135407          pIndex = 0;
135408          nKeyCol = 0;
135409          nColumn = 1;
135410        }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
135411          return 0;
135412        }else{
135413          nKeyCol = pIndex->nKeyCol;
135414          nColumn = pIndex->nColumn;
135415          assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
135416          assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
135417                            || !HasRowid(pIndex->pTable));
135418          isOrderDistinct = IsUniqueIndex(pIndex);
135419        }
135420  
135421        /* Loop through all columns of the index and deal with the ones
135422        ** that are not constrained by == or IN.
135423        */
135424        rev = revSet = 0;
135425        distinctColumns = 0;
135426        for(j=0; j<nColumn; j++){
135427          u8 bOnce = 1; /* True to run the ORDER BY search loop */
135428  
135429          assert( j>=pLoop->u.btree.nEq 
135430              || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
135431          );
135432          if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
135433            u16 eOp = pLoop->aLTerm[j]->eOperator;
135434  
135435            /* Skip over == and IS and ISNULL terms.  (Also skip IN terms when
135436            ** doing WHERE_ORDERBY_LIMIT processing). 
135437            **
135438            ** If the current term is a column of an ((?,?) IN (SELECT...)) 
135439            ** expression for which the SELECT returns more than one column,
135440            ** check that it is the only column used by this loop. Otherwise,
135441            ** if it is one of two or more, none of the columns can be
135442            ** considered to match an ORDER BY term.  */
135443            if( (eOp & eqOpMask)!=0 ){
135444              if( eOp & WO_ISNULL ){
135445                testcase( isOrderDistinct );
135446                isOrderDistinct = 0;
135447              }
135448              continue;  
135449            }else if( ALWAYS(eOp & WO_IN) ){
135450              /* ALWAYS() justification: eOp is an equality operator due to the
135451              ** j<pLoop->u.btree.nEq constraint above.  Any equality other
135452              ** than WO_IN is captured by the previous "if".  So this one
135453              ** always has to be WO_IN. */
135454              Expr *pX = pLoop->aLTerm[j]->pExpr;
135455              for(i=j+1; i<pLoop->u.btree.nEq; i++){
135456                if( pLoop->aLTerm[i]->pExpr==pX ){
135457                  assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
135458                  bOnce = 0;
135459                  break;
135460                }
135461              }
135462            }
135463          }
135464  
135465          /* Get the column number in the table (iColumn) and sort order
135466          ** (revIdx) for the j-th column of the index.
135467          */
135468          if( pIndex ){
135469            iColumn = pIndex->aiColumn[j];
135470            revIdx = pIndex->aSortOrder[j];
135471            if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID;
135472          }else{
135473            iColumn = XN_ROWID;
135474            revIdx = 0;
135475          }
135476  
135477          /* An unconstrained column that might be NULL means that this
135478          ** WhereLoop is not well-ordered
135479          */
135480          if( isOrderDistinct
135481           && iColumn>=0
135482           && j>=pLoop->u.btree.nEq
135483           && pIndex->pTable->aCol[iColumn].notNull==0
135484          ){
135485            isOrderDistinct = 0;
135486          }
135487  
135488          /* Find the ORDER BY term that corresponds to the j-th column
135489          ** of the index and mark that ORDER BY term off 
135490          */
135491          isMatch = 0;
135492          for(i=0; bOnce && i<nOrderBy; i++){
135493            if( MASKBIT(i) & obSat ) continue;
135494            pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
135495            testcase( wctrlFlags & WHERE_GROUPBY );
135496            testcase( wctrlFlags & WHERE_DISTINCTBY );
135497            if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
135498            if( iColumn>=XN_ROWID ){
135499              if( pOBExpr->op!=TK_COLUMN ) continue;
135500              if( pOBExpr->iTable!=iCur ) continue;
135501              if( pOBExpr->iColumn!=iColumn ) continue;
135502            }else{
135503              Expr *pIdxExpr = pIndex->aColExpr->a[j].pExpr;
135504              if( sqlite3ExprCompareSkip(pOBExpr, pIdxExpr, iCur) ){
135505                continue;
135506              }
135507            }
135508            if( iColumn!=XN_ROWID ){
135509              pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
135510              if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
135511            }
135512            pLoop->u.btree.nIdxCol = j+1;
135513            isMatch = 1;
135514            break;
135515          }
135516          if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
135517            /* Make sure the sort order is compatible in an ORDER BY clause.
135518            ** Sort order is irrelevant for a GROUP BY clause. */
135519            if( revSet ){
135520              if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
135521            }else{
135522              rev = revIdx ^ pOrderBy->a[i].sortOrder;
135523              if( rev ) *pRevMask |= MASKBIT(iLoop);
135524              revSet = 1;
135525            }
135526          }
135527          if( isMatch ){
135528            if( iColumn==XN_ROWID ){
135529              testcase( distinctColumns==0 );
135530              distinctColumns = 1;
135531            }
135532            obSat |= MASKBIT(i);
135533          }else{
135534            /* No match found */
135535            if( j==0 || j<nKeyCol ){
135536              testcase( isOrderDistinct!=0 );
135537              isOrderDistinct = 0;
135538            }
135539            break;
135540          }
135541        } /* end Loop over all index columns */
135542        if( distinctColumns ){
135543          testcase( isOrderDistinct==0 );
135544          isOrderDistinct = 1;
135545        }
135546      } /* end-if not one-row */
135547  
135548      /* Mark off any other ORDER BY terms that reference pLoop */
135549      if( isOrderDistinct ){
135550        orderDistinctMask |= pLoop->maskSelf;
135551        for(i=0; i<nOrderBy; i++){
135552          Expr *p;
135553          Bitmask mTerm;
135554          if( MASKBIT(i) & obSat ) continue;
135555          p = pOrderBy->a[i].pExpr;
135556          mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
135557          if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
135558          if( (mTerm&~orderDistinctMask)==0 ){
135559            obSat |= MASKBIT(i);
135560          }
135561        }
135562      }
135563    } /* End the loop over all WhereLoops from outer-most down to inner-most */
135564    if( obSat==obDone ) return (i8)nOrderBy;
135565    if( !isOrderDistinct ){
135566      for(i=nOrderBy-1; i>0; i--){
135567        Bitmask m = MASKBIT(i) - 1;
135568        if( (obSat&m)==m ) return i;
135569      }
135570      return 0;
135571    }
135572    return -1;
135573  }
135574  
135575  
135576  /*
135577  ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
135578  ** the planner assumes that the specified pOrderBy list is actually a GROUP
135579  ** BY clause - and so any order that groups rows as required satisfies the
135580  ** request.
135581  **
135582  ** Normally, in this case it is not possible for the caller to determine
135583  ** whether or not the rows are really being delivered in sorted order, or
135584  ** just in some other order that provides the required grouping. However,
135585  ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
135586  ** this function may be called on the returned WhereInfo object. It returns
135587  ** true if the rows really will be sorted in the specified order, or false
135588  ** otherwise.
135589  **
135590  ** For example, assuming:
135591  **
135592  **   CREATE INDEX i1 ON t1(x, Y);
135593  **
135594  ** then
135595  **
135596  **   SELECT * FROM t1 GROUP BY x,y ORDER BY x,y;   -- IsSorted()==1
135597  **   SELECT * FROM t1 GROUP BY y,x ORDER BY y,x;   -- IsSorted()==0
135598  */
135599  SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
135600    assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
135601    assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
135602    return pWInfo->sorted;
135603  }
135604  
135605  #ifdef WHERETRACE_ENABLED
135606  /* For debugging use only: */
135607  static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
135608    static char zName[65];
135609    int i;
135610    for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
135611    if( pLast ) zName[i++] = pLast->cId;
135612    zName[i] = 0;
135613    return zName;
135614  }
135615  #endif
135616  
135617  /*
135618  ** Return the cost of sorting nRow rows, assuming that the keys have 
135619  ** nOrderby columns and that the first nSorted columns are already in
135620  ** order.
135621  */
135622  static LogEst whereSortingCost(
135623    WhereInfo *pWInfo,
135624    LogEst nRow,
135625    int nOrderBy,
135626    int nSorted
135627  ){
135628    /* TUNING: Estimated cost of a full external sort, where N is 
135629    ** the number of rows to sort is:
135630    **
135631    **   cost = (3.0 * N * log(N)).
135632    ** 
135633    ** Or, if the order-by clause has X terms but only the last Y 
135634    ** terms are out of order, then block-sorting will reduce the 
135635    ** sorting cost to:
135636    **
135637    **   cost = (3.0 * N * log(N)) * (Y/X)
135638    **
135639    ** The (Y/X) term is implemented using stack variable rScale
135640    ** below.  */
135641    LogEst rScale, rSortCost;
135642    assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
135643    rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
135644    rSortCost = nRow + rScale + 16;
135645  
135646    /* Multiple by log(M) where M is the number of output rows.
135647    ** Use the LIMIT for M if it is smaller */
135648    if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
135649      nRow = pWInfo->iLimit;
135650    }
135651    rSortCost += estLog(nRow);
135652    return rSortCost;
135653  }
135654  
135655  /*
135656  ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
135657  ** attempts to find the lowest cost path that visits each WhereLoop
135658  ** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
135659  **
135660  ** Assume that the total number of output rows that will need to be sorted
135661  ** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
135662  ** costs if nRowEst==0.
135663  **
135664  ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
135665  ** error occurs.
135666  */
135667  static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
135668    int mxChoice;             /* Maximum number of simultaneous paths tracked */
135669    int nLoop;                /* Number of terms in the join */
135670    Parse *pParse;            /* Parsing context */
135671    sqlite3 *db;              /* The database connection */
135672    int iLoop;                /* Loop counter over the terms of the join */
135673    int ii, jj;               /* Loop counters */
135674    int mxI = 0;              /* Index of next entry to replace */
135675    int nOrderBy;             /* Number of ORDER BY clause terms */
135676    LogEst mxCost = 0;        /* Maximum cost of a set of paths */
135677    LogEst mxUnsorted = 0;    /* Maximum unsorted cost of a set of path */
135678    int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
135679    WherePath *aFrom;         /* All nFrom paths at the previous level */
135680    WherePath *aTo;           /* The nTo best paths at the current level */
135681    WherePath *pFrom;         /* An element of aFrom[] that we are working on */
135682    WherePath *pTo;           /* An element of aTo[] that we are working on */
135683    WhereLoop *pWLoop;        /* One of the WhereLoop objects */
135684    WhereLoop **pX;           /* Used to divy up the pSpace memory */
135685    LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */
135686    char *pSpace;             /* Temporary memory used by this routine */
135687    int nSpace;               /* Bytes of space allocated at pSpace */
135688  
135689    pParse = pWInfo->pParse;
135690    db = pParse->db;
135691    nLoop = pWInfo->nLevel;
135692    /* TUNING: For simple queries, only the best path is tracked.
135693    ** For 2-way joins, the 5 best paths are followed.
135694    ** For joins of 3 or more tables, track the 10 best paths */
135695    mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
135696    assert( nLoop<=pWInfo->pTabList->nSrc );
135697    WHERETRACE(0x002, ("---- begin solver.  (nRowEst=%d)\n", nRowEst));
135698  
135699    /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
135700    ** case the purpose of this call is to estimate the number of rows returned
135701    ** by the overall query. Once this estimate has been obtained, the caller
135702    ** will invoke this function a second time, passing the estimate as the
135703    ** nRowEst parameter.  */
135704    if( pWInfo->pOrderBy==0 || nRowEst==0 ){
135705      nOrderBy = 0;
135706    }else{
135707      nOrderBy = pWInfo->pOrderBy->nExpr;
135708    }
135709  
135710    /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
135711    nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
135712    nSpace += sizeof(LogEst) * nOrderBy;
135713    pSpace = sqlite3DbMallocRawNN(db, nSpace);
135714    if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
135715    aTo = (WherePath*)pSpace;
135716    aFrom = aTo+mxChoice;
135717    memset(aFrom, 0, sizeof(aFrom[0]));
135718    pX = (WhereLoop**)(aFrom+mxChoice);
135719    for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
135720      pFrom->aLoop = pX;
135721    }
135722    if( nOrderBy ){
135723      /* If there is an ORDER BY clause and it is not being ignored, set up
135724      ** space for the aSortCost[] array. Each element of the aSortCost array
135725      ** is either zero - meaning it has not yet been initialized - or the
135726      ** cost of sorting nRowEst rows of data where the first X terms of
135727      ** the ORDER BY clause are already in order, where X is the array 
135728      ** index.  */
135729      aSortCost = (LogEst*)pX;
135730      memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
135731    }
135732    assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
135733    assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
135734  
135735    /* Seed the search with a single WherePath containing zero WhereLoops.
135736    **
135737    ** TUNING: Do not let the number of iterations go above 28.  If the cost
135738    ** of computing an automatic index is not paid back within the first 28
135739    ** rows, then do not use the automatic index. */
135740    aFrom[0].nRow = MIN(pParse->nQueryLoop, 48);  assert( 48==sqlite3LogEst(28) );
135741    nFrom = 1;
135742    assert( aFrom[0].isOrdered==0 );
135743    if( nOrderBy ){
135744      /* If nLoop is zero, then there are no FROM terms in the query. Since
135745      ** in this case the query may return a maximum of one row, the results
135746      ** are already in the requested order. Set isOrdered to nOrderBy to
135747      ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
135748      ** -1, indicating that the result set may or may not be ordered, 
135749      ** depending on the loops added to the current plan.  */
135750      aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
135751    }
135752  
135753    /* Compute successively longer WherePaths using the previous generation
135754    ** of WherePaths as the basis for the next.  Keep track of the mxChoice
135755    ** best paths at each generation */
135756    for(iLoop=0; iLoop<nLoop; iLoop++){
135757      nTo = 0;
135758      for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
135759        for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
135760          LogEst nOut;                      /* Rows visited by (pFrom+pWLoop) */
135761          LogEst rCost;                     /* Cost of path (pFrom+pWLoop) */
135762          LogEst rUnsorted;                 /* Unsorted cost of (pFrom+pWLoop) */
135763          i8 isOrdered = pFrom->isOrdered;  /* isOrdered for (pFrom+pWLoop) */
135764          Bitmask maskNew;                  /* Mask of src visited by (..) */
135765          Bitmask revMask = 0;              /* Mask of rev-order loops for (..) */
135766  
135767          if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
135768          if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
135769          if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<10 ){
135770            /* Do not use an automatic index if the this loop is expected
135771            ** to run less than 2 times. */
135772            assert( 10==sqlite3LogEst(2) );
135773            continue;
135774          }
135775          /* At this point, pWLoop is a candidate to be the next loop. 
135776          ** Compute its cost */
135777          rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
135778          rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
135779          nOut = pFrom->nRow + pWLoop->nOut;
135780          maskNew = pFrom->maskLoop | pWLoop->maskSelf;
135781          if( isOrdered<0 ){
135782            isOrdered = wherePathSatisfiesOrderBy(pWInfo,
135783                         pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
135784                         iLoop, pWLoop, &revMask);
135785          }else{
135786            revMask = pFrom->revLoop;
135787          }
135788          if( isOrdered>=0 && isOrdered<nOrderBy ){
135789            if( aSortCost[isOrdered]==0 ){
135790              aSortCost[isOrdered] = whereSortingCost(
135791                  pWInfo, nRowEst, nOrderBy, isOrdered
135792              );
135793            }
135794            rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
135795  
135796            WHERETRACE(0x002,
135797                ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
135798                 aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy, 
135799                 rUnsorted, rCost));
135800          }else{
135801            rCost = rUnsorted;
135802            rUnsorted -= 2;  /* TUNING:  Slight bias in favor of no-sort plans */
135803          }
135804  
135805          /* Check to see if pWLoop should be added to the set of
135806          ** mxChoice best-so-far paths.
135807          **
135808          ** First look for an existing path among best-so-far paths
135809          ** that covers the same set of loops and has the same isOrdered
135810          ** setting as the current path candidate.
135811          **
135812          ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
135813          ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
135814          ** of legal values for isOrdered, -1..64.
135815          */
135816          for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
135817            if( pTo->maskLoop==maskNew
135818             && ((pTo->isOrdered^isOrdered)&0x80)==0
135819            ){
135820              testcase( jj==nTo-1 );
135821              break;
135822            }
135823          }
135824          if( jj>=nTo ){
135825            /* None of the existing best-so-far paths match the candidate. */
135826            if( nTo>=mxChoice
135827             && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
135828            ){
135829              /* The current candidate is no better than any of the mxChoice
135830              ** paths currently in the best-so-far buffer.  So discard
135831              ** this candidate as not viable. */
135832  #ifdef WHERETRACE_ENABLED /* 0x4 */
135833              if( sqlite3WhereTrace&0x4 ){
135834                sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d,%3d order=%c\n",
135835                    wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
135836                    isOrdered>=0 ? isOrdered+'0' : '?');
135837              }
135838  #endif
135839              continue;
135840            }
135841            /* If we reach this points it means that the new candidate path
135842            ** needs to be added to the set of best-so-far paths. */
135843            if( nTo<mxChoice ){
135844              /* Increase the size of the aTo set by one */
135845              jj = nTo++;
135846            }else{
135847              /* New path replaces the prior worst to keep count below mxChoice */
135848              jj = mxI;
135849            }
135850            pTo = &aTo[jj];
135851  #ifdef WHERETRACE_ENABLED /* 0x4 */
135852            if( sqlite3WhereTrace&0x4 ){
135853              sqlite3DebugPrintf("New    %s cost=%-3d,%3d,%3d order=%c\n",
135854                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
135855                  isOrdered>=0 ? isOrdered+'0' : '?');
135856            }
135857  #endif
135858          }else{
135859            /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
135860            ** same set of loops and has the same isOrdered setting as the
135861            ** candidate path.  Check to see if the candidate should replace
135862            ** pTo or if the candidate should be skipped.
135863            ** 
135864            ** The conditional is an expanded vector comparison equivalent to:
135865            **   (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
135866            */
135867            if( pTo->rCost<rCost 
135868             || (pTo->rCost==rCost
135869                 && (pTo->nRow<nOut
135870                     || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)
135871                    )
135872                )
135873            ){
135874  #ifdef WHERETRACE_ENABLED /* 0x4 */
135875              if( sqlite3WhereTrace&0x4 ){
135876                sqlite3DebugPrintf(
135877                    "Skip   %s cost=%-3d,%3d,%3d order=%c",
135878                    wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
135879                    isOrdered>=0 ? isOrdered+'0' : '?');
135880                sqlite3DebugPrintf("   vs %s cost=%-3d,%3d,%3d order=%c\n",
135881                    wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
135882                    pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
135883              }
135884  #endif
135885              /* Discard the candidate path from further consideration */
135886              testcase( pTo->rCost==rCost );
135887              continue;
135888            }
135889            testcase( pTo->rCost==rCost+1 );
135890            /* Control reaches here if the candidate path is better than the
135891            ** pTo path.  Replace pTo with the candidate. */
135892  #ifdef WHERETRACE_ENABLED /* 0x4 */
135893            if( sqlite3WhereTrace&0x4 ){
135894              sqlite3DebugPrintf(
135895                  "Update %s cost=%-3d,%3d,%3d order=%c",
135896                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
135897                  isOrdered>=0 ? isOrdered+'0' : '?');
135898              sqlite3DebugPrintf("  was %s cost=%-3d,%3d,%3d order=%c\n",
135899                  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
135900                  pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
135901            }
135902  #endif
135903          }
135904          /* pWLoop is a winner.  Add it to the set of best so far */
135905          pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
135906          pTo->revLoop = revMask;
135907          pTo->nRow = nOut;
135908          pTo->rCost = rCost;
135909          pTo->rUnsorted = rUnsorted;
135910          pTo->isOrdered = isOrdered;
135911          memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
135912          pTo->aLoop[iLoop] = pWLoop;
135913          if( nTo>=mxChoice ){
135914            mxI = 0;
135915            mxCost = aTo[0].rCost;
135916            mxUnsorted = aTo[0].nRow;
135917            for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
135918              if( pTo->rCost>mxCost 
135919               || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted) 
135920              ){
135921                mxCost = pTo->rCost;
135922                mxUnsorted = pTo->rUnsorted;
135923                mxI = jj;
135924              }
135925            }
135926          }
135927        }
135928      }
135929  
135930  #ifdef WHERETRACE_ENABLED  /* >=2 */
135931      if( sqlite3WhereTrace & 0x02 ){
135932        sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
135933        for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
135934          sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
135935             wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
135936             pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
135937          if( pTo->isOrdered>0 ){
135938            sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
135939          }else{
135940            sqlite3DebugPrintf("\n");
135941          }
135942        }
135943      }
135944  #endif
135945  
135946      /* Swap the roles of aFrom and aTo for the next generation */
135947      pFrom = aTo;
135948      aTo = aFrom;
135949      aFrom = pFrom;
135950      nFrom = nTo;
135951    }
135952  
135953    if( nFrom==0 ){
135954      sqlite3ErrorMsg(pParse, "no query solution");
135955      sqlite3DbFreeNN(db, pSpace);
135956      return SQLITE_ERROR;
135957    }
135958    
135959    /* Find the lowest cost path.  pFrom will be left pointing to that path */
135960    pFrom = aFrom;
135961    for(ii=1; ii<nFrom; ii++){
135962      if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
135963    }
135964    assert( pWInfo->nLevel==nLoop );
135965    /* Load the lowest cost path into pWInfo */
135966    for(iLoop=0; iLoop<nLoop; iLoop++){
135967      WhereLevel *pLevel = pWInfo->a + iLoop;
135968      pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
135969      pLevel->iFrom = pWLoop->iTab;
135970      pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
135971    }
135972    if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
135973     && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
135974     && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
135975     && nRowEst
135976    ){
135977      Bitmask notUsed;
135978      int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
135979                   WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
135980      if( rc==pWInfo->pResultSet->nExpr ){
135981        pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
135982      }
135983    }
135984    if( pWInfo->pOrderBy ){
135985      if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
135986        if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
135987          pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
135988        }
135989      }else{
135990        pWInfo->nOBSat = pFrom->isOrdered;
135991        pWInfo->revMask = pFrom->revLoop;
135992        if( pWInfo->nOBSat<=0 ){
135993          pWInfo->nOBSat = 0;
135994          if( nLoop>0 ){
135995            u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
135996            if( (wsFlags & WHERE_ONEROW)==0 
135997             && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
135998            ){
135999              Bitmask m = 0;
136000              int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
136001                        WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
136002              testcase( wsFlags & WHERE_IPK );
136003              testcase( wsFlags & WHERE_COLUMN_IN );
136004              if( rc==pWInfo->pOrderBy->nExpr ){
136005                pWInfo->bOrderedInnerLoop = 1;
136006                pWInfo->revMask = m;
136007              }
136008            }
136009          }
136010        }
136011      }
136012      if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
136013          && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
136014      ){
136015        Bitmask revMask = 0;
136016        int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, 
136017            pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
136018        );
136019        assert( pWInfo->sorted==0 );
136020        if( nOrder==pWInfo->pOrderBy->nExpr ){
136021          pWInfo->sorted = 1;
136022          pWInfo->revMask = revMask;
136023        }
136024      }
136025    }
136026  
136027  
136028    pWInfo->nRowOut = pFrom->nRow;
136029  
136030    /* Free temporary memory and return success */
136031    sqlite3DbFreeNN(db, pSpace);
136032    return SQLITE_OK;
136033  }
136034  
136035  /*
136036  ** Most queries use only a single table (they are not joins) and have
136037  ** simple == constraints against indexed fields.  This routine attempts
136038  ** to plan those simple cases using much less ceremony than the
136039  ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
136040  ** times for the common case.
136041  **
136042  ** Return non-zero on success, if this query can be handled by this
136043  ** no-frills query planner.  Return zero if this query needs the 
136044  ** general-purpose query planner.
136045  */
136046  static int whereShortCut(WhereLoopBuilder *pBuilder){
136047    WhereInfo *pWInfo;
136048    struct SrcList_item *pItem;
136049    WhereClause *pWC;
136050    WhereTerm *pTerm;
136051    WhereLoop *pLoop;
136052    int iCur;
136053    int j;
136054    Table *pTab;
136055    Index *pIdx;
136056  
136057    pWInfo = pBuilder->pWInfo;
136058    if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
136059    assert( pWInfo->pTabList->nSrc>=1 );
136060    pItem = pWInfo->pTabList->a;
136061    pTab = pItem->pTab;
136062    if( IsVirtual(pTab) ) return 0;
136063    if( pItem->fg.isIndexedBy ) return 0;
136064    iCur = pItem->iCursor;
136065    pWC = &pWInfo->sWC;
136066    pLoop = pBuilder->pNew;
136067    pLoop->wsFlags = 0;
136068    pLoop->nSkip = 0;
136069    pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
136070    if( pTerm ){
136071      testcase( pTerm->eOperator & WO_IS );
136072      pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
136073      pLoop->aLTerm[0] = pTerm;
136074      pLoop->nLTerm = 1;
136075      pLoop->u.btree.nEq = 1;
136076      /* TUNING: Cost of a rowid lookup is 10 */
136077      pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
136078    }else{
136079      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
136080        int opMask;
136081        assert( pLoop->aLTermSpace==pLoop->aLTerm );
136082        if( !IsUniqueIndex(pIdx)
136083         || pIdx->pPartIdxWhere!=0 
136084         || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace) 
136085        ) continue;
136086        opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
136087        for(j=0; j<pIdx->nKeyCol; j++){
136088          pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
136089          if( pTerm==0 ) break;
136090          testcase( pTerm->eOperator & WO_IS );
136091          pLoop->aLTerm[j] = pTerm;
136092        }
136093        if( j!=pIdx->nKeyCol ) continue;
136094        pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
136095        if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
136096          pLoop->wsFlags |= WHERE_IDX_ONLY;
136097        }
136098        pLoop->nLTerm = j;
136099        pLoop->u.btree.nEq = j;
136100        pLoop->u.btree.pIndex = pIdx;
136101        /* TUNING: Cost of a unique index lookup is 15 */
136102        pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
136103        break;
136104      }
136105    }
136106    if( pLoop->wsFlags ){
136107      pLoop->nOut = (LogEst)1;
136108      pWInfo->a[0].pWLoop = pLoop;
136109      assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
136110      pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
136111      pWInfo->a[0].iTabCur = iCur;
136112      pWInfo->nRowOut = 1;
136113      if( pWInfo->pOrderBy ) pWInfo->nOBSat =  pWInfo->pOrderBy->nExpr;
136114      if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
136115        pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
136116      }
136117  #ifdef SQLITE_DEBUG
136118      pLoop->cId = '0';
136119  #endif
136120      return 1;
136121    }
136122    return 0;
136123  }
136124  
136125  /*
136126  ** Helper function for exprIsDeterministic().
136127  */
136128  static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){
136129    if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){
136130      pWalker->eCode = 0;
136131      return WRC_Abort;
136132    }
136133    return WRC_Continue;
136134  }
136135  
136136  /*
136137  ** Return true if the expression contains no non-deterministic SQL 
136138  ** functions. Do not consider non-deterministic SQL functions that are 
136139  ** part of sub-select statements.
136140  */
136141  static int exprIsDeterministic(Expr *p){
136142    Walker w;
136143    memset(&w, 0, sizeof(w));
136144    w.eCode = 1;
136145    w.xExprCallback = exprNodeIsDeterministic;
136146    w.xSelectCallback = sqlite3SelectWalkFail;
136147    sqlite3WalkExpr(&w, p);
136148    return w.eCode;
136149  }
136150  
136151  /*
136152  ** Generate the beginning of the loop used for WHERE clause processing.
136153  ** The return value is a pointer to an opaque structure that contains
136154  ** information needed to terminate the loop.  Later, the calling routine
136155  ** should invoke sqlite3WhereEnd() with the return value of this function
136156  ** in order to complete the WHERE clause processing.
136157  **
136158  ** If an error occurs, this routine returns NULL.
136159  **
136160  ** The basic idea is to do a nested loop, one loop for each table in
136161  ** the FROM clause of a select.  (INSERT and UPDATE statements are the
136162  ** same as a SELECT with only a single table in the FROM clause.)  For
136163  ** example, if the SQL is this:
136164  **
136165  **       SELECT * FROM t1, t2, t3 WHERE ...;
136166  **
136167  ** Then the code generated is conceptually like the following:
136168  **
136169  **      foreach row1 in t1 do       \    Code generated
136170  **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
136171  **          foreach row3 in t3 do   /
136172  **            ...
136173  **          end                     \    Code generated
136174  **        end                        |-- by sqlite3WhereEnd()
136175  **      end                         /
136176  **
136177  ** Note that the loops might not be nested in the order in which they
136178  ** appear in the FROM clause if a different order is better able to make
136179  ** use of indices.  Note also that when the IN operator appears in
136180  ** the WHERE clause, it might result in additional nested loops for
136181  ** scanning through all values on the right-hand side of the IN.
136182  **
136183  ** There are Btree cursors associated with each table.  t1 uses cursor
136184  ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
136185  ** And so forth.  This routine generates code to open those VDBE cursors
136186  ** and sqlite3WhereEnd() generates the code to close them.
136187  **
136188  ** The code that sqlite3WhereBegin() generates leaves the cursors named
136189  ** in pTabList pointing at their appropriate entries.  The [...] code
136190  ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
136191  ** data from the various tables of the loop.
136192  **
136193  ** If the WHERE clause is empty, the foreach loops must each scan their
136194  ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
136195  ** the tables have indices and there are terms in the WHERE clause that
136196  ** refer to those indices, a complete table scan can be avoided and the
136197  ** code will run much faster.  Most of the work of this routine is checking
136198  ** to see if there are indices that can be used to speed up the loop.
136199  **
136200  ** Terms of the WHERE clause are also used to limit which rows actually
136201  ** make it to the "..." in the middle of the loop.  After each "foreach",
136202  ** terms of the WHERE clause that use only terms in that loop and outer
136203  ** loops are evaluated and if false a jump is made around all subsequent
136204  ** inner loops (or around the "..." if the test occurs within the inner-
136205  ** most loop)
136206  **
136207  ** OUTER JOINS
136208  **
136209  ** An outer join of tables t1 and t2 is conceptally coded as follows:
136210  **
136211  **    foreach row1 in t1 do
136212  **      flag = 0
136213  **      foreach row2 in t2 do
136214  **        start:
136215  **          ...
136216  **          flag = 1
136217  **      end
136218  **      if flag==0 then
136219  **        move the row2 cursor to a null row
136220  **        goto start
136221  **      fi
136222  **    end
136223  **
136224  ** ORDER BY CLAUSE PROCESSING
136225  **
136226  ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
136227  ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
136228  ** if there is one.  If there is no ORDER BY clause or if this routine
136229  ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
136230  **
136231  ** The iIdxCur parameter is the cursor number of an index.  If 
136232  ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
136233  ** to use for OR clause processing.  The WHERE clause should use this
136234  ** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
136235  ** the first cursor in an array of cursors for all indices.  iIdxCur should
136236  ** be used to compute the appropriate cursor depending on which index is
136237  ** used.
136238  */
136239  SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
136240    Parse *pParse,          /* The parser context */
136241    SrcList *pTabList,      /* FROM clause: A list of all tables to be scanned */
136242    Expr *pWhere,           /* The WHERE clause */
136243    ExprList *pOrderBy,     /* An ORDER BY (or GROUP BY) clause, or NULL */
136244    ExprList *pResultSet,   /* Query result set.  Req'd for DISTINCT */
136245    u16 wctrlFlags,         /* The WHERE_* flags defined in sqliteInt.h */
136246    int iAuxArg             /* If WHERE_OR_SUBCLAUSE is set, index cursor number
136247                            ** If WHERE_USE_LIMIT, then the limit amount */
136248  ){
136249    int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
136250    int nTabList;              /* Number of elements in pTabList */
136251    WhereInfo *pWInfo;         /* Will become the return value of this function */
136252    Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
136253    Bitmask notReady;          /* Cursors that are not yet positioned */
136254    WhereLoopBuilder sWLB;     /* The WhereLoop builder */
136255    WhereMaskSet *pMaskSet;    /* The expression mask set */
136256    WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
136257    WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */
136258    int ii;                    /* Loop counter */
136259    sqlite3 *db;               /* Database connection */
136260    int rc;                    /* Return code */
136261    u8 bFordelete = 0;         /* OPFLAG_FORDELETE or zero, as appropriate */
136262  
136263    assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
136264          (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 
136265       && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 
136266    ));
136267  
136268    /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
136269    assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
136270              || (wctrlFlags & WHERE_USE_LIMIT)==0 );
136271  
136272    /* Variable initialization */
136273    db = pParse->db;
136274    memset(&sWLB, 0, sizeof(sWLB));
136275  
136276    /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
136277    testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
136278    if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
136279    sWLB.pOrderBy = pOrderBy;
136280  
136281    /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
136282    ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
136283    if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
136284      wctrlFlags &= ~WHERE_WANT_DISTINCT;
136285    }
136286  
136287    /* The number of tables in the FROM clause is limited by the number of
136288    ** bits in a Bitmask 
136289    */
136290    testcase( pTabList->nSrc==BMS );
136291    if( pTabList->nSrc>BMS ){
136292      sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
136293      return 0;
136294    }
136295  
136296    /* This function normally generates a nested loop for all tables in 
136297    ** pTabList.  But if the WHERE_OR_SUBCLAUSE flag is set, then we should
136298    ** only generate code for the first table in pTabList and assume that
136299    ** any cursors associated with subsequent tables are uninitialized.
136300    */
136301    nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
136302  
136303    /* Allocate and initialize the WhereInfo structure that will become the
136304    ** return value. A single allocation is used to store the WhereInfo
136305    ** struct, the contents of WhereInfo.a[], the WhereClause structure
136306    ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
136307    ** field (type Bitmask) it must be aligned on an 8-byte boundary on
136308    ** some architectures. Hence the ROUND8() below.
136309    */
136310    nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
136311    pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
136312    if( db->mallocFailed ){
136313      sqlite3DbFree(db, pWInfo);
136314      pWInfo = 0;
136315      goto whereBeginError;
136316    }
136317    pWInfo->pParse = pParse;
136318    pWInfo->pTabList = pTabList;
136319    pWInfo->pOrderBy = pOrderBy;
136320    pWInfo->pWhere = pWhere;
136321    pWInfo->pResultSet = pResultSet;
136322    pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
136323    pWInfo->nLevel = nTabList;
136324    pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
136325    pWInfo->wctrlFlags = wctrlFlags;
136326    pWInfo->iLimit = iAuxArg;
136327    pWInfo->savedNQueryLoop = pParse->nQueryLoop;
136328    memset(&pWInfo->nOBSat, 0, 
136329           offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
136330    memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
136331    assert( pWInfo->eOnePass==ONEPASS_OFF );  /* ONEPASS defaults to OFF */
136332    pMaskSet = &pWInfo->sMaskSet;
136333    sWLB.pWInfo = pWInfo;
136334    sWLB.pWC = &pWInfo->sWC;
136335    sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
136336    assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
136337    whereLoopInit(sWLB.pNew);
136338  #ifdef SQLITE_DEBUG
136339    sWLB.pNew->cId = '*';
136340  #endif
136341  
136342    /* Split the WHERE clause into separate subexpressions where each
136343    ** subexpression is separated by an AND operator.
136344    */
136345    initMaskSet(pMaskSet);
136346    sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
136347    sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
136348      
136349    /* Special case: No FROM clause
136350    */
136351    if( nTabList==0 ){
136352      if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
136353      if( wctrlFlags & WHERE_WANT_DISTINCT ){
136354        pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
136355      }
136356    }else{
136357      /* Assign a bit from the bitmask to every term in the FROM clause.
136358      **
136359      ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
136360      **
136361      ** The rule of the previous sentence ensures thta if X is the bitmask for
136362      ** a table T, then X-1 is the bitmask for all other tables to the left of T.
136363      ** Knowing the bitmask for all tables to the left of a left join is
136364      ** important.  Ticket #3015.
136365      **
136366      ** Note that bitmasks are created for all pTabList->nSrc tables in
136367      ** pTabList, not just the first nTabList tables.  nTabList is normally
136368      ** equal to pTabList->nSrc but might be shortened to 1 if the
136369      ** WHERE_OR_SUBCLAUSE flag is set.
136370      */
136371      ii = 0;
136372      do{
136373        createMask(pMaskSet, pTabList->a[ii].iCursor);
136374        sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
136375      }while( (++ii)<pTabList->nSrc );
136376    #ifdef SQLITE_DEBUG
136377      {
136378        Bitmask mx = 0;
136379        for(ii=0; ii<pTabList->nSrc; ii++){
136380          Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
136381          assert( m>=mx );
136382          mx = m;
136383        }
136384      }
136385    #endif
136386    }
136387    
136388    /* Analyze all of the subexpressions. */
136389    sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
136390    if( db->mallocFailed ) goto whereBeginError;
136391  
136392    /* Special case: WHERE terms that do not refer to any tables in the join
136393    ** (constant expressions). Evaluate each such term, and jump over all the
136394    ** generated code if the result is not true.  
136395    **
136396    ** Do not do this if the expression contains non-deterministic functions
136397    ** that are not within a sub-select. This is not strictly required, but
136398    ** preserves SQLite's legacy behaviour in the following two cases:
136399    **
136400    **   FROM ... WHERE random()>0;           -- eval random() once per row
136401    **   FROM ... WHERE (SELECT random())>0;  -- eval random() once overall
136402    */
136403    for(ii=0; ii<sWLB.pWC->nTerm; ii++){
136404      WhereTerm *pT = &sWLB.pWC->a[ii];
136405      if( pT->prereqAll==0 && (nTabList==0 || exprIsDeterministic(pT->pExpr)) ){
136406        sqlite3ExprIfFalse(pParse, pT->pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL);
136407        pT->wtFlags |= TERM_CODED;
136408      }
136409    }
136410  
136411    if( wctrlFlags & WHERE_WANT_DISTINCT ){
136412      if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
136413        /* The DISTINCT marking is pointless.  Ignore it. */
136414        pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
136415      }else if( pOrderBy==0 ){
136416        /* Try to ORDER BY the result set to make distinct processing easier */
136417        pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
136418        pWInfo->pOrderBy = pResultSet;
136419      }
136420    }
136421  
136422    /* Construct the WhereLoop objects */
136423  #if defined(WHERETRACE_ENABLED)
136424    if( sqlite3WhereTrace & 0xffff ){
136425      sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
136426      if( wctrlFlags & WHERE_USE_LIMIT ){
136427        sqlite3DebugPrintf(", limit: %d", iAuxArg);
136428      }
136429      sqlite3DebugPrintf(")\n");
136430    }
136431    if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
136432      sqlite3WhereClausePrint(sWLB.pWC);
136433    }
136434  #endif
136435  
136436    if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
136437      rc = whereLoopAddAll(&sWLB);
136438      if( rc ) goto whereBeginError;
136439    
136440  #ifdef WHERETRACE_ENABLED
136441      if( sqlite3WhereTrace ){    /* Display all of the WhereLoop objects */
136442        WhereLoop *p;
136443        int i;
136444        static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
136445                                               "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
136446        for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
136447          p->cId = zLabel[i%(sizeof(zLabel)-1)];
136448          whereLoopPrint(p, sWLB.pWC);
136449        }
136450      }
136451  #endif
136452    
136453      wherePathSolver(pWInfo, 0);
136454      if( db->mallocFailed ) goto whereBeginError;
136455      if( pWInfo->pOrderBy ){
136456         wherePathSolver(pWInfo, pWInfo->nRowOut+1);
136457         if( db->mallocFailed ) goto whereBeginError;
136458      }
136459    }
136460    if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
136461       pWInfo->revMask = ALLBITS;
136462    }
136463    if( pParse->nErr || NEVER(db->mallocFailed) ){
136464      goto whereBeginError;
136465    }
136466  #ifdef WHERETRACE_ENABLED
136467    if( sqlite3WhereTrace ){
136468      sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
136469      if( pWInfo->nOBSat>0 ){
136470        sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
136471      }
136472      switch( pWInfo->eDistinct ){
136473        case WHERE_DISTINCT_UNIQUE: {
136474          sqlite3DebugPrintf("  DISTINCT=unique");
136475          break;
136476        }
136477        case WHERE_DISTINCT_ORDERED: {
136478          sqlite3DebugPrintf("  DISTINCT=ordered");
136479          break;
136480        }
136481        case WHERE_DISTINCT_UNORDERED: {
136482          sqlite3DebugPrintf("  DISTINCT=unordered");
136483          break;
136484        }
136485      }
136486      sqlite3DebugPrintf("\n");
136487      for(ii=0; ii<pWInfo->nLevel; ii++){
136488        whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
136489      }
136490    }
136491  #endif
136492    /* Attempt to omit tables from the join that do not effect the result */
136493    if( pWInfo->nLevel>=2
136494     && pResultSet!=0
136495     && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
136496    ){
136497      Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
136498      if( sWLB.pOrderBy ){
136499        tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
136500      }
136501      while( pWInfo->nLevel>=2 ){
136502        WhereTerm *pTerm, *pEnd;
136503        pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
136504        if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break;
136505        if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
136506         && (pLoop->wsFlags & WHERE_ONEROW)==0
136507        ){
136508          break;
136509        }
136510        if( (tabUsed & pLoop->maskSelf)!=0 ) break;
136511        pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
136512        for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
136513          if( (pTerm->prereqAll & pLoop->maskSelf)!=0
136514           && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
136515          ){
136516            break;
136517          }
136518        }
136519        if( pTerm<pEnd ) break;
136520        WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
136521        pWInfo->nLevel--;
136522        nTabList--;
136523      }
136524    }
136525    WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
136526    pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
136527  
136528    /* If the caller is an UPDATE or DELETE statement that is requesting
136529    ** to use a one-pass algorithm, determine if this is appropriate.
136530    */
136531    assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
136532    if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
136533      int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
136534      int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
136535      if( bOnerow
136536       || ((wctrlFlags & WHERE_ONEPASS_MULTIROW)!=0
136537             && 0==(wsFlags & WHERE_VIRTUALTABLE))
136538      ){
136539        pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
136540        if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
136541          if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
136542            bFordelete = OPFLAG_FORDELETE;
136543          }
136544          pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
136545        }
136546      }
136547    }
136548  
136549    /* Open all tables in the pTabList and any indices selected for
136550    ** searching those tables.
136551    */
136552    for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
136553      Table *pTab;     /* Table to open */
136554      int iDb;         /* Index of database containing table/index */
136555      struct SrcList_item *pTabItem;
136556  
136557      pTabItem = &pTabList->a[pLevel->iFrom];
136558      pTab = pTabItem->pTab;
136559      iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
136560      pLoop = pLevel->pWLoop;
136561      if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
136562        /* Do nothing */
136563      }else
136564  #ifndef SQLITE_OMIT_VIRTUALTABLE
136565      if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
136566        const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
136567        int iCur = pTabItem->iCursor;
136568        sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
136569      }else if( IsVirtual(pTab) ){
136570        /* noop */
136571      }else
136572  #endif
136573      if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
136574           && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
136575        int op = OP_OpenRead;
136576        if( pWInfo->eOnePass!=ONEPASS_OFF ){
136577          op = OP_OpenWrite;
136578          pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
136579        };
136580        sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
136581        assert( pTabItem->iCursor==pLevel->iTabCur );
136582        testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
136583        testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
136584        if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
136585          Bitmask b = pTabItem->colUsed;
136586          int n = 0;
136587          for(; b; b=b>>1, n++){}
136588          sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
136589          assert( n<=pTab->nCol );
136590        }
136591  #ifdef SQLITE_ENABLE_CURSOR_HINTS
136592        if( pLoop->u.btree.pIndex!=0 ){
136593          sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
136594        }else
136595  #endif
136596        {
136597          sqlite3VdbeChangeP5(v, bFordelete);
136598        }
136599  #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
136600        sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
136601                              (const u8*)&pTabItem->colUsed, P4_INT64);
136602  #endif
136603      }else{
136604        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
136605      }
136606      if( pLoop->wsFlags & WHERE_INDEXED ){
136607        Index *pIx = pLoop->u.btree.pIndex;
136608        int iIndexCur;
136609        int op = OP_OpenRead;
136610        /* iAuxArg is always set to a positive value if ONEPASS is possible */
136611        assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
136612        if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
136613         && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
136614        ){
136615          /* This is one term of an OR-optimization using the PRIMARY KEY of a
136616          ** WITHOUT ROWID table.  No need for a separate index */
136617          iIndexCur = pLevel->iTabCur;
136618          op = 0;
136619        }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
136620          Index *pJ = pTabItem->pTab->pIndex;
136621          iIndexCur = iAuxArg;
136622          assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
136623          while( ALWAYS(pJ) && pJ!=pIx ){
136624            iIndexCur++;
136625            pJ = pJ->pNext;
136626          }
136627          op = OP_OpenWrite;
136628          pWInfo->aiCurOnePass[1] = iIndexCur;
136629        }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
136630          iIndexCur = iAuxArg;
136631          op = OP_ReopenIdx;
136632        }else{
136633          iIndexCur = pParse->nTab++;
136634        }
136635        pLevel->iIdxCur = iIndexCur;
136636        assert( pIx->pSchema==pTab->pSchema );
136637        assert( iIndexCur>=0 );
136638        if( op ){
136639          sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
136640          sqlite3VdbeSetP4KeyInfo(pParse, pIx);
136641          if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
136642           && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
136643           && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
136644           && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
136645          ){
136646            sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
136647          }
136648          VdbeComment((v, "%s", pIx->zName));
136649  #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
136650          {
136651            u64 colUsed = 0;
136652            int ii, jj;
136653            for(ii=0; ii<pIx->nColumn; ii++){
136654              jj = pIx->aiColumn[ii];
136655              if( jj<0 ) continue;
136656              if( jj>63 ) jj = 63;
136657              if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
136658              colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
136659            }
136660            sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
136661                                  (u8*)&colUsed, P4_INT64);
136662          }
136663  #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
136664        }
136665      }
136666      if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
136667    }
136668    pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
136669    if( db->mallocFailed ) goto whereBeginError;
136670  
136671    /* Generate the code to do the search.  Each iteration of the for
136672    ** loop below generates code for a single nested loop of the VM
136673    ** program.
136674    */
136675    notReady = ~(Bitmask)0;
136676    for(ii=0; ii<nTabList; ii++){
136677      int addrExplain;
136678      int wsFlags;
136679      pLevel = &pWInfo->a[ii];
136680      wsFlags = pLevel->pWLoop->wsFlags;
136681  #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
136682      if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
136683        constructAutomaticIndex(pParse, &pWInfo->sWC,
136684                  &pTabList->a[pLevel->iFrom], notReady, pLevel);
136685        if( db->mallocFailed ) goto whereBeginError;
136686      }
136687  #endif
136688      addrExplain = sqlite3WhereExplainOneScan(
136689          pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
136690      );
136691      pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
136692      notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
136693      pWInfo->iContinue = pLevel->addrCont;
136694      if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
136695        sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
136696      }
136697    }
136698  
136699    /* Done. */
136700    VdbeModuleComment((v, "Begin WHERE-core"));
136701    return pWInfo;
136702  
136703    /* Jump here if malloc fails */
136704  whereBeginError:
136705    if( pWInfo ){
136706      pParse->nQueryLoop = pWInfo->savedNQueryLoop;
136707      whereInfoFree(db, pWInfo);
136708    }
136709    return 0;
136710  }
136711  
136712  /*
136713  ** Generate the end of the WHERE loop.  See comments on 
136714  ** sqlite3WhereBegin() for additional information.
136715  */
136716  SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
136717    Parse *pParse = pWInfo->pParse;
136718    Vdbe *v = pParse->pVdbe;
136719    int i;
136720    WhereLevel *pLevel;
136721    WhereLoop *pLoop;
136722    SrcList *pTabList = pWInfo->pTabList;
136723    sqlite3 *db = pParse->db;
136724  
136725    /* Generate loop termination code.
136726    */
136727    VdbeModuleComment((v, "End WHERE-core"));
136728    sqlite3ExprCacheClear(pParse);
136729    for(i=pWInfo->nLevel-1; i>=0; i--){
136730      int addr;
136731      pLevel = &pWInfo->a[i];
136732      pLoop = pLevel->pWLoop;
136733      if( pLevel->op!=OP_Noop ){
136734  #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
136735        int addrSeek = 0;
136736        Index *pIdx;
136737        int n;
136738        if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
136739         && (pLoop->wsFlags & WHERE_INDEXED)!=0
136740         && (pIdx = pLoop->u.btree.pIndex)->hasStat1
136741         && (n = pLoop->u.btree.nIdxCol)>0
136742         && pIdx->aiRowLogEst[n]>=36
136743        ){
136744          int r1 = pParse->nMem+1;
136745          int j, op;
136746          for(j=0; j<n; j++){
136747            sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
136748          }
136749          pParse->nMem += n+1;
136750          op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
136751          addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
136752          VdbeCoverageIf(v, op==OP_SeekLT);
136753          VdbeCoverageIf(v, op==OP_SeekGT);
136754          sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
136755        }
136756  #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
136757        /* The common case: Advance to the next row */
136758        sqlite3VdbeResolveLabel(v, pLevel->addrCont);
136759        sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
136760        sqlite3VdbeChangeP5(v, pLevel->p5);
136761        VdbeCoverage(v);
136762        VdbeCoverageIf(v, pLevel->op==OP_Next);
136763        VdbeCoverageIf(v, pLevel->op==OP_Prev);
136764        VdbeCoverageIf(v, pLevel->op==OP_VNext);
136765  #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
136766        if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);
136767  #endif
136768      }else{
136769        sqlite3VdbeResolveLabel(v, pLevel->addrCont);
136770      }
136771      if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
136772        struct InLoop *pIn;
136773        int j;
136774        sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
136775        for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
136776          sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
136777          if( pIn->eEndLoopOp!=OP_Noop ){
136778            sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
136779            VdbeCoverage(v);
136780            VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
136781            VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
136782          }
136783          sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
136784        }
136785      }
136786      sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
136787      if( pLevel->addrSkip ){
136788        sqlite3VdbeGoto(v, pLevel->addrSkip);
136789        VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
136790        sqlite3VdbeJumpHere(v, pLevel->addrSkip);
136791        sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
136792      }
136793  #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
136794      if( pLevel->addrLikeRep ){
136795        sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
136796                          pLevel->addrLikeRep);
136797        VdbeCoverage(v);
136798      }
136799  #endif
136800      if( pLevel->iLeftJoin ){
136801        int ws = pLoop->wsFlags;
136802        addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
136803        assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
136804        if( (ws & WHERE_IDX_ONLY)==0 ){
136805          sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
136806        }
136807        if( (ws & WHERE_INDEXED) 
136808         || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx) 
136809        ){
136810          sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
136811        }
136812        if( pLevel->op==OP_Return ){
136813          sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
136814        }else{
136815          sqlite3VdbeGoto(v, pLevel->addrFirst);
136816        }
136817        sqlite3VdbeJumpHere(v, addr);
136818      }
136819      VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
136820                       pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
136821    }
136822  
136823    /* The "break" point is here, just past the end of the outer loop.
136824    ** Set it.
136825    */
136826    sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
136827  
136828    assert( pWInfo->nLevel<=pTabList->nSrc );
136829    for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
136830      int k, last;
136831      VdbeOp *pOp;
136832      Index *pIdx = 0;
136833      struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
136834      Table *pTab = pTabItem->pTab;
136835      assert( pTab!=0 );
136836      pLoop = pLevel->pWLoop;
136837  
136838      /* For a co-routine, change all OP_Column references to the table of
136839      ** the co-routine into OP_Copy of result contained in a register.
136840      ** OP_Rowid becomes OP_Null.
136841      */
136842      if( pTabItem->fg.viaCoroutine ){
136843        testcase( pParse->db->mallocFailed );
136844        translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
136845                              pTabItem->regResult, 0);
136846        continue;
136847      }
136848  
136849      /* If this scan uses an index, make VDBE code substitutions to read data
136850      ** from the index instead of from the table where possible.  In some cases
136851      ** this optimization prevents the table from ever being read, which can
136852      ** yield a significant performance boost.
136853      ** 
136854      ** Calls to the code generator in between sqlite3WhereBegin and
136855      ** sqlite3WhereEnd will have created code that references the table
136856      ** directly.  This loop scans all that code looking for opcodes
136857      ** that reference the table and converts them into opcodes that
136858      ** reference the index.
136859      */
136860      if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
136861        pIdx = pLoop->u.btree.pIndex;
136862      }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
136863        pIdx = pLevel->u.pCovidx;
136864      }
136865      if( pIdx
136866       && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
136867       && !db->mallocFailed
136868      ){
136869        last = sqlite3VdbeCurrentAddr(v);
136870        k = pLevel->addrBody;
136871        pOp = sqlite3VdbeGetOp(v, k);
136872        for(; k<last; k++, pOp++){
136873          if( pOp->p1!=pLevel->iTabCur ) continue;
136874          if( pOp->opcode==OP_Column ){
136875            int x = pOp->p2;
136876            assert( pIdx->pTable==pTab );
136877            if( !HasRowid(pTab) ){
136878              Index *pPk = sqlite3PrimaryKeyIndex(pTab);
136879              x = pPk->aiColumn[x];
136880              assert( x>=0 );
136881            }
136882            x = sqlite3ColumnOfIndex(pIdx, x);
136883            if( x>=0 ){
136884              pOp->p2 = x;
136885              pOp->p1 = pLevel->iIdxCur;
136886            }
136887            assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 
136888                || pWInfo->eOnePass );
136889          }else if( pOp->opcode==OP_Rowid ){
136890            pOp->p1 = pLevel->iIdxCur;
136891            pOp->opcode = OP_IdxRowid;
136892          }else if( pOp->opcode==OP_IfNullRow ){
136893            pOp->p1 = pLevel->iIdxCur;
136894          }
136895        }
136896      }
136897    }
136898  
136899    /* Final cleanup
136900    */
136901    pParse->nQueryLoop = pWInfo->savedNQueryLoop;
136902    whereInfoFree(db, pWInfo);
136903    return;
136904  }
136905  
136906  /************** End of where.c ***********************************************/
136907  /************** Begin file parse.c *******************************************/
136908  /*
136909  ** 2000-05-29
136910  **
136911  ** The author disclaims copyright to this source code.  In place of
136912  ** a legal notice, here is a blessing:
136913  **
136914  **    May you do good and not evil.
136915  **    May you find forgiveness for yourself and forgive others.
136916  **    May you share freely, never taking more than you give.
136917  **
136918  *************************************************************************
136919  ** Driver template for the LEMON parser generator.
136920  **
136921  ** The "lemon" program processes an LALR(1) input grammar file, then uses
136922  ** this template to construct a parser.  The "lemon" program inserts text
136923  ** at each "%%" line.  Also, any "P-a-r-s-e" identifer prefix (without the
136924  ** interstitial "-" characters) contained in this template is changed into
136925  ** the value of the %name directive from the grammar.  Otherwise, the content
136926  ** of this template is copied straight through into the generate parser
136927  ** source file.
136928  **
136929  ** The following is the concatenation of all %include directives from the
136930  ** input grammar file:
136931  */
136932  /* #include <stdio.h> */
136933  /************ Begin %include sections from the grammar ************************/
136934  
136935  /* #include "sqliteInt.h" */
136936  
136937  /*
136938  ** Disable all error recovery processing in the parser push-down
136939  ** automaton.
136940  */
136941  #define YYNOERRORRECOVERY 1
136942  
136943  /*
136944  ** Make yytestcase() the same as testcase()
136945  */
136946  #define yytestcase(X) testcase(X)
136947  
136948  /*
136949  ** Indicate that sqlite3ParserFree() will never be called with a null
136950  ** pointer.
136951  */
136952  #define YYPARSEFREENEVERNULL 1
136953  
136954  /*
136955  ** In the amalgamation, the parse.c file generated by lemon and the
136956  ** tokenize.c file are concatenated.  In that case, sqlite3RunParser()
136957  ** has access to the the size of the yyParser object and so the parser
136958  ** engine can be allocated from stack.  In that case, only the
136959  ** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked
136960  ** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be
136961  ** omitted.
136962  */
136963  #ifdef SQLITE_AMALGAMATION
136964  # define sqlite3Parser_ENGINEALWAYSONSTACK 1
136965  #endif
136966  
136967  /*
136968  ** Alternative datatype for the argument to the malloc() routine passed
136969  ** into sqlite3ParserAlloc().  The default is size_t.
136970  */
136971  #define YYMALLOCARGTYPE  u64
136972  
136973  /*
136974  ** An instance of this structure holds information about the
136975  ** LIMIT clause of a SELECT statement.
136976  */
136977  struct LimitVal {
136978    Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
136979    Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
136980  };
136981  
136982  /*
136983  ** An instance of the following structure describes the event of a
136984  ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
136985  ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
136986  **
136987  **      UPDATE ON (a,b,c)
136988  **
136989  ** Then the "b" IdList records the list "a,b,c".
136990  */
136991  struct TrigEvent { int a; IdList * b; };
136992  
136993  /*
136994  ** Disable lookaside memory allocation for objects that might be
136995  ** shared across database connections.
136996  */
136997  static void disableLookaside(Parse *pParse){
136998    pParse->disableLookaside++;
136999    pParse->db->lookaside.bDisable++;
137000  }
137001  
137002  
137003    /*
137004    ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
137005    ** all elements in the list.  And make sure list length does not exceed
137006    ** SQLITE_LIMIT_COMPOUND_SELECT.
137007    */
137008    static void parserDoubleLinkSelect(Parse *pParse, Select *p){
137009      if( p->pPrior ){
137010        Select *pNext = 0, *pLoop;
137011        int mxSelect, cnt = 0;
137012        for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
137013          pLoop->pNext = pNext;
137014          pLoop->selFlags |= SF_Compound;
137015        }
137016        if( (p->selFlags & SF_MultiValue)==0 && 
137017          (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
137018          cnt>mxSelect
137019        ){
137020          sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
137021        }
137022      }
137023    }
137024  
137025    /* This is a utility routine used to set the ExprSpan.zStart and
137026    ** ExprSpan.zEnd values of pOut so that the span covers the complete
137027    ** range of text beginning with pStart and going to the end of pEnd.
137028    */
137029    static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
137030      pOut->zStart = pStart->z;
137031      pOut->zEnd = &pEnd->z[pEnd->n];
137032    }
137033  
137034    /* Construct a new Expr object from a single identifier.  Use the
137035    ** new Expr to populate pOut.  Set the span of pOut to be the identifier
137036    ** that created the expression.
137037    */
137038    static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token t){
137039      Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
137040      if( p ){
137041        memset(p, 0, sizeof(Expr));
137042        p->op = (u8)op;
137043        p->flags = EP_Leaf;
137044        p->iAgg = -1;
137045        p->u.zToken = (char*)&p[1];
137046        memcpy(p->u.zToken, t.z, t.n);
137047        p->u.zToken[t.n] = 0;
137048        if( sqlite3Isquote(p->u.zToken[0]) ){
137049          if( p->u.zToken[0]=='"' ) p->flags |= EP_DblQuoted;
137050          sqlite3Dequote(p->u.zToken);
137051        }
137052  #if SQLITE_MAX_EXPR_DEPTH>0
137053        p->nHeight = 1;
137054  #endif  
137055      }
137056      pOut->pExpr = p;
137057      pOut->zStart = t.z;
137058      pOut->zEnd = &t.z[t.n];
137059    }
137060  
137061    /* This routine constructs a binary expression node out of two ExprSpan
137062    ** objects and uses the result to populate a new ExprSpan object.
137063    */
137064    static void spanBinaryExpr(
137065      Parse *pParse,      /* The parsing context.  Errors accumulate here */
137066      int op,             /* The binary operation */
137067      ExprSpan *pLeft,    /* The left operand, and output */
137068      ExprSpan *pRight    /* The right operand */
137069    ){
137070      pLeft->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr);
137071      pLeft->zEnd = pRight->zEnd;
137072    }
137073  
137074    /* If doNot is true, then add a TK_NOT Expr-node wrapper around the
137075    ** outside of *ppExpr.
137076    */
137077    static void exprNot(Parse *pParse, int doNot, ExprSpan *pSpan){
137078      if( doNot ){
137079        pSpan->pExpr = sqlite3PExpr(pParse, TK_NOT, pSpan->pExpr, 0);
137080      }
137081    }
137082  
137083    /* Construct an expression node for a unary postfix operator
137084    */
137085    static void spanUnaryPostfix(
137086      Parse *pParse,         /* Parsing context to record errors */
137087      int op,                /* The operator */
137088      ExprSpan *pOperand,    /* The operand, and output */
137089      Token *pPostOp         /* The operand token for setting the span */
137090    ){
137091      pOperand->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0);
137092      pOperand->zEnd = &pPostOp->z[pPostOp->n];
137093    }                           
137094  
137095    /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
137096    ** unary TK_ISNULL or TK_NOTNULL expression. */
137097    static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
137098      sqlite3 *db = pParse->db;
137099      if( pA && pY && pY->op==TK_NULL ){
137100        pA->op = (u8)op;
137101        sqlite3ExprDelete(db, pA->pRight);
137102        pA->pRight = 0;
137103      }
137104    }
137105  
137106    /* Construct an expression node for a unary prefix operator
137107    */
137108    static void spanUnaryPrefix(
137109      ExprSpan *pOut,        /* Write the new expression node here */
137110      Parse *pParse,         /* Parsing context to record errors */
137111      int op,                /* The operator */
137112      ExprSpan *pOperand,    /* The operand */
137113      Token *pPreOp         /* The operand token for setting the span */
137114    ){
137115      pOut->zStart = pPreOp->z;
137116      pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0);
137117      pOut->zEnd = pOperand->zEnd;
137118    }
137119  
137120    /* Add a single new term to an ExprList that is used to store a
137121    ** list of identifiers.  Report an error if the ID list contains
137122    ** a COLLATE clause or an ASC or DESC keyword, except ignore the
137123    ** error while parsing a legacy schema.
137124    */
137125    static ExprList *parserAddExprIdListTerm(
137126      Parse *pParse,
137127      ExprList *pPrior,
137128      Token *pIdToken,
137129      int hasCollate,
137130      int sortOrder
137131    ){
137132      ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
137133      if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
137134          && pParse->db->init.busy==0
137135      ){
137136        sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
137137                           pIdToken->n, pIdToken->z);
137138      }
137139      sqlite3ExprListSetName(pParse, p, pIdToken, 1);
137140      return p;
137141    }
137142  /**************** End of %include directives **********************************/
137143  /* These constants specify the various numeric values for terminal symbols
137144  ** in a format understandable to "makeheaders".  This section is blank unless
137145  ** "lemon" is run with the "-m" command-line option.
137146  ***************** Begin makeheaders token definitions *************************/
137147  /**************** End makeheaders token definitions ***************************/
137148  
137149  /* The next sections is a series of control #defines.
137150  ** various aspects of the generated parser.
137151  **    YYCODETYPE         is the data type used to store the integer codes
137152  **                       that represent terminal and non-terminal symbols.
137153  **                       "unsigned char" is used if there are fewer than
137154  **                       256 symbols.  Larger types otherwise.
137155  **    YYNOCODE           is a number of type YYCODETYPE that is not used for
137156  **                       any terminal or nonterminal symbol.
137157  **    YYFALLBACK         If defined, this indicates that one or more tokens
137158  **                       (also known as: "terminal symbols") have fall-back
137159  **                       values which should be used if the original symbol
137160  **                       would not parse.  This permits keywords to sometimes
137161  **                       be used as identifiers, for example.
137162  **    YYACTIONTYPE       is the data type used for "action codes" - numbers
137163  **                       that indicate what to do in response to the next
137164  **                       token.
137165  **    sqlite3ParserTOKENTYPE     is the data type used for minor type for terminal
137166  **                       symbols.  Background: A "minor type" is a semantic
137167  **                       value associated with a terminal or non-terminal
137168  **                       symbols.  For example, for an "ID" terminal symbol,
137169  **                       the minor type might be the name of the identifier.
137170  **                       Each non-terminal can have a different minor type.
137171  **                       Terminal symbols all have the same minor type, though.
137172  **                       This macros defines the minor type for terminal 
137173  **                       symbols.
137174  **    YYMINORTYPE        is the data type used for all minor types.
137175  **                       This is typically a union of many types, one of
137176  **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
137177  **                       for terminal symbols is called "yy0".
137178  **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
137179  **                       zero the stack is dynamically sized using realloc()
137180  **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
137181  **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
137182  **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
137183  **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
137184  **    YYERRORSYMBOL      is the code number of the error symbol.  If not
137185  **                       defined, then do no error processing.
137186  **    YYNSTATE           the combined number of states.
137187  **    YYNRULE            the number of rules in the grammar
137188  **    YY_MAX_SHIFT       Maximum value for shift actions
137189  **    YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
137190  **    YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
137191  **    YY_MIN_REDUCE      Minimum value for reduce actions
137192  **    YY_MAX_REDUCE      Maximum value for reduce actions
137193  **    YY_ERROR_ACTION    The yy_action[] code for syntax error
137194  **    YY_ACCEPT_ACTION   The yy_action[] code for accept
137195  **    YY_NO_ACTION       The yy_action[] code for no-op
137196  */
137197  #ifndef INTERFACE
137198  # define INTERFACE 1
137199  #endif
137200  /************* Begin control #defines *****************************************/
137201  #define YYCODETYPE unsigned char
137202  #define YYNOCODE 252
137203  #define YYACTIONTYPE unsigned short int
137204  #define YYWILDCARD 83
137205  #define sqlite3ParserTOKENTYPE Token
137206  typedef union {
137207    int yyinit;
137208    sqlite3ParserTOKENTYPE yy0;
137209    Expr* yy72;
137210    TriggerStep* yy145;
137211    ExprList* yy148;
137212    SrcList* yy185;
137213    ExprSpan yy190;
137214    int yy194;
137215    Select* yy243;
137216    IdList* yy254;
137217    With* yy285;
137218    struct TrigEvent yy332;
137219    struct LimitVal yy354;
137220    struct {int value; int mask;} yy497;
137221  } YYMINORTYPE;
137222  #ifndef YYSTACKDEPTH
137223  #define YYSTACKDEPTH 100
137224  #endif
137225  #define sqlite3ParserARG_SDECL Parse *pParse;
137226  #define sqlite3ParserARG_PDECL ,Parse *pParse
137227  #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
137228  #define sqlite3ParserARG_STORE yypParser->pParse = pParse
137229  #define YYFALLBACK 1
137230  #define YYNSTATE             455
137231  #define YYNRULE              329
137232  #define YY_MAX_SHIFT         454
137233  #define YY_MIN_SHIFTREDUCE   664
137234  #define YY_MAX_SHIFTREDUCE   992
137235  #define YY_MIN_REDUCE        993
137236  #define YY_MAX_REDUCE        1321
137237  #define YY_ERROR_ACTION      1322
137238  #define YY_ACCEPT_ACTION     1323
137239  #define YY_NO_ACTION         1324
137240  /************* End control #defines *******************************************/
137241  
137242  /* Define the yytestcase() macro to be a no-op if is not already defined
137243  ** otherwise.
137244  **
137245  ** Applications can choose to define yytestcase() in the %include section
137246  ** to a macro that can assist in verifying code coverage.  For production
137247  ** code the yytestcase() macro should be turned off.  But it is useful
137248  ** for testing.
137249  */
137250  #ifndef yytestcase
137251  # define yytestcase(X)
137252  #endif
137253  
137254  
137255  /* Next are the tables used to determine what action to take based on the
137256  ** current state and lookahead token.  These tables are used to implement
137257  ** functions that take a state number and lookahead value and return an
137258  ** action integer.  
137259  **
137260  ** Suppose the action integer is N.  Then the action is determined as
137261  ** follows
137262  **
137263  **   0 <= N <= YY_MAX_SHIFT             Shift N.  That is, push the lookahead
137264  **                                      token onto the stack and goto state N.
137265  **
137266  **   N between YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
137267  **     and YY_MAX_SHIFTREDUCE           reduce by rule N-YY_MIN_SHIFTREDUCE.
137268  **
137269  **   N between YY_MIN_REDUCE            Reduce by rule N-YY_MIN_REDUCE
137270  **     and YY_MAX_REDUCE
137271  **
137272  **   N == YY_ERROR_ACTION               A syntax error has occurred.
137273  **
137274  **   N == YY_ACCEPT_ACTION              The parser accepts its input.
137275  **
137276  **   N == YY_NO_ACTION                  No such action.  Denotes unused
137277  **                                      slots in the yy_action[] table.
137278  **
137279  ** The action table is constructed as a single large table named yy_action[].
137280  ** Given state S and lookahead X, the action is computed as either:
137281  **
137282  **    (A)   N = yy_action[ yy_shift_ofst[S] + X ]
137283  **    (B)   N = yy_default[S]
137284  **
137285  ** The (A) formula is preferred.  The B formula is used instead if:
137286  **    (1)  The yy_shift_ofst[S]+X value is out of range, or
137287  **    (2)  yy_lookahead[yy_shift_ofst[S]+X] is not equal to X, or
137288  **    (3)  yy_shift_ofst[S] equal YY_SHIFT_USE_DFLT.
137289  ** (Implementation note: YY_SHIFT_USE_DFLT is chosen so that
137290  ** YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X.
137291  ** Hence only tests (1) and (2) need to be evaluated.)
137292  **
137293  ** The formulas above are for computing the action when the lookahead is
137294  ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
137295  ** a reduce action) then the yy_reduce_ofst[] array is used in place of
137296  ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
137297  ** YY_SHIFT_USE_DFLT.
137298  **
137299  ** The following are the tables generated in this section:
137300  **
137301  **  yy_action[]        A single table containing all actions.
137302  **  yy_lookahead[]     A table containing the lookahead for each entry in
137303  **                     yy_action.  Used to detect hash collisions.
137304  **  yy_shift_ofst[]    For each state, the offset into yy_action for
137305  **                     shifting terminals.
137306  **  yy_reduce_ofst[]   For each state, the offset into yy_action for
137307  **                     shifting non-terminals after a reduce.
137308  **  yy_default[]       Default action for each state.
137309  **
137310  *********** Begin parsing tables **********************************************/
137311  #define YY_ACTTAB_COUNT (1566)
137312  static const YYACTIONTYPE yy_action[] = {
137313   /*     0 */   324, 1323,  155,  155,    2,  203,   94,   94,   94,   93,
137314   /*    10 */   350,   98,   98,   98,   98,   91,   95,   95,   94,   94,
137315   /*    20 */    94,   93,  350,  268,   99,  100,   90,  971,  971,  847,
137316   /*    30 */   850,  839,  839,   97,   97,   98,   98,   98,   98,  350,
137317   /*    40 */   969,   96,   96,   96,   96,   95,   95,   94,   94,   94,
137318   /*    50 */    93,  350,  950,   96,   96,   96,   96,   95,   95,   94,
137319   /*    60 */    94,   94,   93,  350,  250,   96,   96,   96,   96,   95,
137320   /*    70 */    95,   94,   94,   94,   93,  350,  224,  224,  969,  132,
137321   /*    80 */   888,  348,  347,  415,  172,  324, 1286,  449,  414,  950,
137322   /*    90 */   951,  952,  808,  977, 1032,  950,  300,  786,  428,  132,
137323   /*   100 */   975,  362,  976,    9,    9,  787,  132,   52,   52,   99,
137324   /*   110 */   100,   90,  971,  971,  847,  850,  839,  839,   97,   97,
137325   /*   120 */    98,   98,   98,   98,  372,  978,  241,  978,  262,  369,
137326   /*   130 */   261,  120,  950,  951,  952,  194,   58,  324,  401,  398,
137327   /*   140 */   397,  808,  427,  429,   75,  808, 1260, 1260,  132,  396,
137328   /*   150 */    96,   96,   96,   96,   95,   95,   94,   94,   94,   93,
137329   /*   160 */   350,   99,  100,   90,  971,  971,  847,  850,  839,  839,
137330   /*   170 */    97,   97,   98,   98,   98,   98,  786,  262,  369,  261,
137331   /*   180 */   826,  262,  364,  251,  787, 1084,  101, 1114,   72,  324,
137332   /*   190 */   227, 1113,  242,  411,  442,  819,   92,   89,  178,  818,
137333   /*   200 */  1022,  268,   96,   96,   96,   96,   95,   95,   94,   94,
137334   /*   210 */    94,   93,  350,   99,  100,   90,  971,  971,  847,  850,
137335   /*   220 */   839,  839,   97,   97,   98,   98,   98,   98,  449,  372,
137336   /*   230 */   818,  818,  820,   92,   89,  178,   60,   92,   89,  178,
137337   /*   240 */  1025,  324,  357,  930, 1316,  300,   61, 1316,   52,   52,
137338   /*   250 */   836,  836,  848,  851,   96,   96,   96,   96,   95,   95,
137339   /*   260 */    94,   94,   94,   93,  350,   99,  100,   90,  971,  971,
137340   /*   270 */   847,  850,  839,  839,   97,   97,   98,   98,   98,   98,
137341   /*   280 */    92,   89,  178,  427,  412,  198,  930, 1317,  454,  995,
137342   /*   290 */  1317,  355, 1024,  324,  243,  231,  114,  277,  348,  347,
137343   /*   300 */  1242,  950,  416, 1071,  928,  840,   96,   96,   96,   96,
137344   /*   310 */    95,   95,   94,   94,   94,   93,  350,   99,  100,   90,
137345   /*   320 */   971,  971,  847,  850,  839,  839,   97,   97,   98,   98,
137346   /*   330 */    98,   98,  449,  328,  449,  120,   23,  256,  950,  951,
137347   /*   340 */   952,  968,  978,  438,  978,  324,  329,  928,  954,  701,
137348   /*   350 */   200,  175,   52,   52,   52,   52,  939,  353,   96,   96,
137349   /*   360 */    96,   96,   95,   95,   94,   94,   94,   93,  350,   99,
137350   /*   370 */   100,   90,  971,  971,  847,  850,  839,  839,   97,   97,
137351   /*   380 */    98,   98,   98,   98,  354,  449,  954,  427,  417,  427,
137352   /*   390 */   426, 1290,   92,   89,  178,  268,  253,  324,  255, 1058,
137353   /*   400 */  1037,  694,   93,  350,  383,   52,   52,  380, 1058,  374,
137354   /*   410 */    96,   96,   96,   96,   95,   95,   94,   94,   94,   93,
137355   /*   420 */   350,   99,  100,   90,  971,  971,  847,  850,  839,  839,
137356   /*   430 */    97,   97,   98,   98,   98,   98,  228,  449,  167,  449,
137357   /*   440 */   427,  407,  157,  446,  446,  446,  349,  349,  349,  324,
137358   /*   450 */   310,  316,  991,  827,  320,  242,  411,   51,   51,   36,
137359   /*   460 */    36,  254,   96,   96,   96,   96,   95,   95,   94,   94,
137360   /*   470 */    94,   93,  350,   99,  100,   90,  971,  971,  847,  850,
137361   /*   480 */   839,  839,   97,   97,   98,   98,   98,   98,  194,  316,
137362   /*   490 */   929,  401,  398,  397,  224,  224, 1265,  939,  353, 1318,
137363   /*   500 */   317,  324,  396, 1063, 1063,  813,  414, 1061, 1061,  950,
137364   /*   510 */   299,  448,  992,  268,   96,   96,   96,   96,   95,   95,
137365   /*   520 */    94,   94,   94,   93,  350,   99,  100,   90,  971,  971,
137366   /*   530 */   847,  850,  839,  839,   97,   97,   98,   98,   98,   98,
137367   /*   540 */   757, 1041,  449,  893,  893,  386,  950,  951,  952,  410,
137368   /*   550 */   992,  747,  747,  324,  229,  268,  221,  296,  268,  771,
137369   /*   560 */   890,  378,   52,   52,  890,  421,   96,   96,   96,   96,
137370   /*   570 */    95,   95,   94,   94,   94,   93,  350,   99,  100,   90,
137371   /*   580 */   971,  971,  847,  850,  839,  839,   97,   97,   98,   98,
137372   /*   590 */    98,   98,  103,  449,  275,  384, 1241,  343,  157, 1207,
137373   /*   600 */   909,  669,  670,  671,  176,  197,  196,  195,  324,  298,
137374   /*   610 */   319, 1266,    2,   37,   37,  910, 1134, 1040,   96,   96,
137375   /*   620 */    96,   96,   95,   95,   94,   94,   94,   93,  350,  697,
137376   /*   630 */   911,  177,   99,  100,   90,  971,  971,  847,  850,  839,
137377   /*   640 */   839,   97,   97,   98,   98,   98,   98,  230,  146,  120,
137378   /*   650 */   735, 1235,  826,  270, 1141,  273, 1141,  771,  171,  170,
137379   /*   660 */   736, 1141,   82,  324,   80,  268,  697,  819,  158,  268,
137380   /*   670 */   378,  818,   78,   96,   96,   96,   96,   95,   95,   94,
137381   /*   680 */    94,   94,   93,  350,  120,  950,  393,   99,  100,   90,
137382   /*   690 */   971,  971,  847,  850,  839,  839,   97,   97,   98,   98,
137383   /*   700 */    98,   98,  818,  818,  820, 1141, 1070,  370,  331,  133,
137384   /*   710 */  1066, 1141, 1250,  198,  268,  324, 1016,  330,  245,  333,
137385   /*   720 */    24,  334,  950,  951,  952,  368,  335,   81,   96,   96,
137386   /*   730 */    96,   96,   95,   95,   94,   94,   94,   93,  350,   99,
137387   /*   740 */   100,   90,  971,  971,  847,  850,  839,  839,   97,   97,
137388   /*   750 */    98,   98,   98,   98,  132,  267,  260,  445,  330,  223,
137389   /*   760 */   175, 1289,  925,  752,  724,  318, 1073,  324,  751,  246,
137390   /*   770 */   385,  301,  301,  378,  329,  361,  344,  414, 1233,  280,
137391   /*   780 */    96,   96,   96,   96,   95,   95,   94,   94,   94,   93,
137392   /*   790 */   350,   99,   88,   90,  971,  971,  847,  850,  839,  839,
137393   /*   800 */    97,   97,   98,   98,   98,   98,  337,  346,  721,  722,
137394   /*   810 */   449,  120,  118,  887,  162,  887,  810,  371,  324,  202,
137395   /*   820 */   202,  373,  249,  263,  202,  394,   74,  704,  208, 1069,
137396   /*   830 */    12,   12,   96,   96,   96,   96,   95,   95,   94,   94,
137397   /*   840 */    94,   93,  350,  100,   90,  971,  971,  847,  850,  839,
137398   /*   850 */   839,   97,   97,   98,   98,   98,   98,  449,  771,  232,
137399   /*   860 */   449,  278,  120,  286,   74,  704,  714,  713,  324,  342,
137400   /*   870 */   749,  877, 1209,   77,  285, 1255,  780,   52,   52,  202,
137401   /*   880 */    27,   27,  418,   96,   96,   96,   96,   95,   95,   94,
137402   /*   890 */    94,   94,   93,  350,   90,  971,  971,  847,  850,  839,
137403   /*   900 */   839,   97,   97,   98,   98,   98,   98,   86,  444,  877,
137404   /*   910 */     3, 1193,  422, 1013,  873,  435,  886,  208,  886,  689,
137405   /*   920 */  1091,  257,  116,  822,  447, 1230,  117, 1229,   86,  444,
137406   /*   930 */   177,    3,  381,   96,   96,   96,   96,   95,   95,   94,
137407   /*   940 */    94,   94,   93,  350,  339,  447,  120,  351,  120,  212,
137408   /*   950 */   169,  287,  404,  282,  403,  199,  771,  950,  433,  419,
137409   /*   960 */   439,  822,  280,  691, 1039,  264,  269,  132,  351,  153,
137410   /*   970 */   826,  376,   74,  272,  274,  276,   83,   84, 1054,  433,
137411   /*   980 */   147, 1038,  443,   85,  351,  451,  450,  281,  132,  818,
137412   /*   990 */    25,  826,  449,  120,  950,  951,  952,   83,   84,   86,
137413   /*  1000 */   444,  691,    3,  408,   85,  351,  451,  450,  449,    5,
137414   /*  1010 */   818,  203,   32,   32, 1107,  120,  447,  950,  225, 1140,
137415   /*  1020 */   818,  818,  820,  821,   19,  203,  226,  950,   38,   38,
137416   /*  1030 */  1087,  314,  314,  313,  215,  311,  120,  449,  678,  351,
137417   /*  1040 */   237,  818,  818,  820,  821,   19,  969,  409,  377,    1,
137418   /*  1050 */   433,  180,  706,  248,  950,  951,  952,   10,   10,  449,
137419   /*  1060 */   969,  247,  826, 1098,  950,  951,  952,  430,   83,   84,
137420   /*  1070 */   756,  336,  950,   20,  431,   85,  351,  451,  450,   10,
137421   /*  1080 */    10,  818,   86,  444,  969,    3,  950,  449,  302,  303,
137422   /*  1090 */   182,  950, 1146,  338, 1021, 1015, 1004,  183,  969,  447,
137423   /*  1100 */   132,  181,   76,  444,   21,    3,  449,   10,   10,  950,
137424   /*  1110 */   951,  952,  818,  818,  820,  821,   19,  715, 1279,  447,
137425   /*  1120 */   389,  233,  351,  950,  951,  952,   10,   10,  950,  951,
137426   /*  1130 */   952, 1003,  218,  433, 1005,  325, 1273,  773,  289,  291,
137427   /*  1140 */   424,  293,  351,    7,  159,  826,  363,  402,  315,  360,
137428   /*  1150 */  1129,   83,   84,  433, 1232,  716,  772,  259,   85,  351,
137429   /*  1160 */   451,  450,  358,  375,  818,  826,  360,  359,  399, 1211,
137430   /*  1170 */   157,   83,   84,  681,   98,   98,   98,   98,   85,  351,
137431   /*  1180 */   451,  450,  323,  252,  818,  295, 1211, 1213, 1235,  173,
137432   /*  1190 */  1037,  284,  434,  340, 1204,  818,  818,  820,  821,   19,
137433   /*  1200 */   308,  234,  449,  234,   96,   96,   96,   96,   95,   95,
137434   /*  1210 */    94,   94,   94,   93,  350,  818,  818,  820,  821,   19,
137435   /*  1220 */   909,  120,   39,   39, 1203,  449,  168,  360,  449, 1276,
137436   /*  1230 */   367,  449,  135,  449,  986,  910,  449, 1249,  449, 1247,
137437   /*  1240 */   449,  205,  983,  449,  370,   40,   40, 1211,   41,   41,
137438   /*  1250 */   911,   42,   42,   28,   28,  870,   29,   29,   31,   31,
137439   /*  1260 */    43,   43,  379,   44,   44,  449,   59,  449,  332,  449,
137440   /*  1270 */   432,   62,  144,  156,  449,  130,  449,   72,  449,  137,
137441   /*  1280 */   449,  365,  449,  392,  139,   45,   45,   11,   11,   46,
137442   /*  1290 */    46,  140, 1200,  449,  105,  105,   47,   47,   48,   48,
137443   /*  1300 */    33,   33,   49,   49, 1126,  449,  141,  366,  449,  185,
137444   /*  1310 */   142,  449, 1234,   50,   50,  449,  160,  449,  148,  449,
137445   /*  1320 */  1136,  382,  449,   67,  449,   34,   34,  449,  122,  122,
137446   /*  1330 */   449,  123,  123,  449, 1198,  124,  124,   56,   56,   35,
137447   /*  1340 */    35,  449,  106,  106,   53,   53,  449,  107,  107,  449,
137448   /*  1350 */   108,  108,  449,  104,  104,  449,  406,  449,  388,  449,
137449   /*  1360 */   189,  121,  121,  449,  190,  449,  119,  119,  449,  112,
137450   /*  1370 */   112,  449,  111,  111, 1218,  109,  109,  110,  110,   55,
137451   /*  1380 */    55,  266,  752,   57,   57,   54,   54,  751,   26,   26,
137452   /*  1390 */  1099,   30,   30,  219,  154,  390,  271,  191,  321, 1006,
137453   /*  1400 */   192,  405, 1057, 1056, 1055,  341, 1048,  706, 1047, 1029,
137454   /*  1410 */   322,  420, 1028,   71, 1095,  283,  288, 1027, 1288,  204,
137455   /*  1420 */     6,  297,   79, 1184,  437, 1096, 1094,  290,  345,  292,
137456   /*  1430 */   441, 1093,  294,  102,  425,   73,  423,  213, 1012,   22,
137457   /*  1440 */   452,  945,  214, 1077,  216,  217,  238,  453,  306,  304,
137458   /*  1450 */   307,  239,  240, 1001,  305,  125,  996,  126,  115,  235,
137459   /*  1460 */   127,  665,  352,  166,  244,  179,  356,  113,  885,  883,
137460   /*  1470 */   806,  136,  128,  738,  326,  138,  327,  258,  184,  899,
137461   /*  1480 */   143,  129,  145,   63,   64,   65,   66,  902,  186,  187,
137462   /*  1490 */   898,    8,   13,  188,  134,  265,  891,  202,  980,  387,
137463   /*  1500 */   150,  149,  680,  161,  391,  193,  285,  279,  395,  151,
137464   /*  1510 */    68,  717,   14,   15,  400,   69,   16,  131,  236,  825,
137465   /*  1520 */   824,  853,  746,  750,    4,   70,  174,  413,  220,  222,
137466   /*  1530 */   152,  779,  774,   77,  868,   74,  854,  201,   17,  852,
137467   /*  1540 */   908,  206,  907,  207,   18,  857,  934,  163,  436,  210,
137468   /*  1550 */   935,  164,  209,  165,  440,  856,  823,  312,  690,   87,
137469   /*  1560 */   211,  309, 1281,  940,  995, 1280,
137470  };
137471  static const YYCODETYPE yy_lookahead[] = {
137472   /*     0 */    19,  144,  145,  146,  147,   24,   90,   91,   92,   93,
137473   /*    10 */    94,   54,   55,   56,   57,   58,   88,   89,   90,   91,
137474   /*    20 */    92,   93,   94,  152,   43,   44,   45,   46,   47,   48,
137475   /*    30 */    49,   50,   51,   52,   53,   54,   55,   56,   57,   94,
137476   /*    40 */    59,   84,   85,   86,   87,   88,   89,   90,   91,   92,
137477   /*    50 */    93,   94,   59,   84,   85,   86,   87,   88,   89,   90,
137478   /*    60 */    91,   92,   93,   94,  193,   84,   85,   86,   87,   88,
137479   /*    70 */    89,   90,   91,   92,   93,   94,  194,  195,   97,   79,
137480   /*    80 */    11,   88,   89,  152,   26,   19,  171,  152,  206,   96,
137481   /*    90 */    97,   98,   72,  100,  179,   59,  152,   31,  163,   79,
137482   /*   100 */   107,  219,  109,  172,  173,   39,   79,  172,  173,   43,
137483   /*   110 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
137484   /*   120 */    54,   55,   56,   57,  152,  132,  199,  134,  108,  109,
137485   /*   130 */   110,  196,   96,   97,   98,   99,  209,   19,  102,  103,
137486   /*   140 */   104,   72,  207,  208,   26,   72,  119,  120,   79,  113,
137487   /*   150 */    84,   85,   86,   87,   88,   89,   90,   91,   92,   93,
137488   /*   160 */    94,   43,   44,   45,   46,   47,   48,   49,   50,   51,
137489   /*   170 */    52,   53,   54,   55,   56,   57,   31,  108,  109,  110,
137490   /*   180 */    82,  108,  109,  110,   39,  210,   68,  175,  130,   19,
137491   /*   190 */   218,  175,  119,  120,  250,   97,  221,  222,  223,  101,
137492   /*   200 */   172,  152,   84,   85,   86,   87,   88,   89,   90,   91,
137493   /*   210 */    92,   93,   94,   43,   44,   45,   46,   47,   48,   49,
137494   /*   220 */    50,   51,   52,   53,   54,   55,   56,   57,  152,  152,
137495   /*   230 */   132,  133,  134,  221,  222,  223,   66,  221,  222,  223,
137496   /*   240 */   172,   19,  193,   22,   23,  152,   24,   26,  172,  173,
137497   /*   250 */    46,   47,   48,   49,   84,   85,   86,   87,   88,   89,
137498   /*   260 */    90,   91,   92,   93,   94,   43,   44,   45,   46,   47,
137499   /*   270 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
137500   /*   280 */   221,  222,  223,  207,  208,   46,   22,   23,  148,  149,
137501   /*   290 */    26,  242,  172,   19,  154,  218,  156,   23,   88,   89,
137502   /*   300 */   241,   59,  163,  163,   83,  101,   84,   85,   86,   87,
137503   /*   310 */    88,   89,   90,   91,   92,   93,   94,   43,   44,   45,
137504   /*   320 */    46,   47,   48,   49,   50,   51,   52,   53,   54,   55,
137505   /*   330 */    56,   57,  152,  157,  152,  196,  196,   16,   96,   97,
137506   /*   340 */    98,   26,  132,  250,  134,   19,  107,   83,   59,   23,
137507   /*   350 */   211,  212,  172,  173,  172,  173,    1,    2,   84,   85,
137508   /*   360 */    86,   87,   88,   89,   90,   91,   92,   93,   94,   43,
137509   /*   370 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
137510   /*   380 */    54,   55,   56,   57,  244,  152,   97,  207,  208,  207,
137511   /*   390 */   208,  185,  221,  222,  223,  152,   75,   19,   77,  179,
137512   /*   400 */   180,   23,   93,   94,  228,  172,  173,  231,  188,  152,
137513   /*   410 */    84,   85,   86,   87,   88,   89,   90,   91,   92,   93,
137514   /*   420 */    94,   43,   44,   45,   46,   47,   48,   49,   50,   51,
137515   /*   430 */    52,   53,   54,   55,   56,   57,  193,  152,  123,  152,
137516   /*   440 */   207,  208,  152,  168,  169,  170,  168,  169,  170,   19,
137517   /*   450 */   160,   22,   23,   23,  164,  119,  120,  172,  173,  172,
137518   /*   460 */   173,  140,   84,   85,   86,   87,   88,   89,   90,   91,
137519   /*   470 */    92,   93,   94,   43,   44,   45,   46,   47,   48,   49,
137520   /*   480 */    50,   51,   52,   53,   54,   55,   56,   57,   99,   22,
137521   /*   490 */    23,  102,  103,  104,  194,  195,    0,    1,    2,  247,
137522   /*   500 */   248,   19,  113,  190,  191,   23,  206,  190,  191,   59,
137523   /*   510 */   225,  152,   83,  152,   84,   85,   86,   87,   88,   89,
137524   /*   520 */    90,   91,   92,   93,   94,   43,   44,   45,   46,   47,
137525   /*   530 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
137526   /*   540 */    90,  181,  152,  108,  109,  110,   96,   97,   98,  115,
137527   /*   550 */    83,  117,  118,   19,  193,  152,   23,  152,  152,   26,
137528   /*   560 */    29,  152,  172,  173,   33,  152,   84,   85,   86,   87,
137529   /*   570 */    88,   89,   90,   91,   92,   93,   94,   43,   44,   45,
137530   /*   580 */    46,   47,   48,   49,   50,   51,   52,   53,   54,   55,
137531   /*   590 */    56,   57,   22,  152,   16,   64,  193,  207,  152,  193,
137532   /*   600 */    12,    7,    8,    9,  152,  108,  109,  110,   19,  152,
137533   /*   610 */   164,  146,  147,  172,  173,   27,  163,  181,   84,   85,
137534   /*   620 */    86,   87,   88,   89,   90,   91,   92,   93,   94,   59,
137535   /*   630 */    42,   98,   43,   44,   45,   46,   47,   48,   49,   50,
137536   /*   640 */    51,   52,   53,   54,   55,   56,   57,  238,   22,  196,
137537   /*   650 */    62,  163,   82,   75,  152,   77,  152,  124,   88,   89,
137538   /*   660 */    72,  152,  137,   19,  139,  152,   96,   97,   24,  152,
137539   /*   670 */   152,  101,  138,   84,   85,   86,   87,   88,   89,   90,
137540   /*   680 */    91,   92,   93,   94,  196,   59,   19,   43,   44,   45,
137541   /*   690 */    46,   47,   48,   49,   50,   51,   52,   53,   54,   55,
137542   /*   700 */    56,   57,  132,  133,  134,  152,  193,  219,  245,  246,
137543   /*   710 */   193,  152,  152,   46,  152,   19,  166,  167,  152,  217,
137544   /*   720 */   232,  217,   96,   97,   98,  237,  217,  138,   84,   85,
137545   /*   730 */    86,   87,   88,   89,   90,   91,   92,   93,   94,   43,
137546   /*   740 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
137547   /*   750 */    54,   55,   56,   57,   79,  193,  238,  166,  167,  211,
137548   /*   760 */   212,   23,   23,  116,   26,   26,  195,   19,  121,  152,
137549   /*   770 */   217,  152,  152,  152,  107,  100,  217,  206,  163,  112,
137550   /*   780 */    84,   85,   86,   87,   88,   89,   90,   91,   92,   93,
137551   /*   790 */    94,   43,   44,   45,   46,   47,   48,   49,   50,   51,
137552   /*   800 */    52,   53,   54,   55,   56,   57,  187,  187,    7,    8,
137553   /*   810 */   152,  196,   22,  132,   24,  134,   23,   23,   19,   26,
137554   /*   820 */    26,   23,  152,   23,   26,   23,   26,   59,   26,  163,
137555   /*   830 */   172,  173,   84,   85,   86,   87,   88,   89,   90,   91,
137556   /*   840 */    92,   93,   94,   44,   45,   46,   47,   48,   49,   50,
137557   /*   850 */    51,   52,   53,   54,   55,   56,   57,  152,   26,  238,
137558   /*   860 */   152,   23,  196,  101,   26,   97,  100,  101,   19,   19,
137559   /*   870 */    23,   59,  152,   26,  112,  152,   23,  172,  173,   26,
137560   /*   880 */   172,  173,   19,   84,   85,   86,   87,   88,   89,   90,
137561   /*   890 */    91,   92,   93,   94,   45,   46,   47,   48,   49,   50,
137562   /*   900 */    51,   52,   53,   54,   55,   56,   57,   19,   20,   97,
137563   /*   910 */    22,   23,  207,  163,   23,  163,  132,   26,  134,   23,
137564   /*   920 */   213,  152,   26,   59,   36,  152,   22,  152,   19,   20,
137565   /*   930 */    98,   22,  152,   84,   85,   86,   87,   88,   89,   90,
137566   /*   940 */    91,   92,   93,   94,   94,   36,  196,   59,  196,   99,
137567   /*   950 */   100,  101,  102,  103,  104,  105,  124,   59,   70,   96,
137568   /*   960 */   163,   97,  112,   59,  181,  152,  152,   79,   59,   71,
137569   /*   970 */    82,   19,   26,  152,  152,  152,   88,   89,  152,   70,
137570   /*   980 */    22,  152,  163,   95,   96,   97,   98,  152,   79,  101,
137571   /*   990 */    22,   82,  152,  196,   96,   97,   98,   88,   89,   19,
137572   /*  1000 */    20,   97,   22,  163,   95,   96,   97,   98,  152,   22,
137573   /*  1010 */   101,   24,  172,  173,  152,  196,   36,   59,   22,  152,
137574   /*  1020 */   132,  133,  134,  135,  136,   24,    5,   59,  172,  173,
137575   /*  1030 */   152,   10,   11,   12,   13,   14,  196,  152,   17,   59,
137576   /*  1040 */   210,  132,  133,  134,  135,  136,   59,  207,   96,   22,
137577   /*  1050 */    70,   30,  106,   32,   96,   97,   98,  172,  173,  152,
137578   /*  1060 */    59,   40,   82,  152,   96,   97,   98,  152,   88,   89,
137579   /*  1070 */    90,  186,   59,   22,  191,   95,   96,   97,   98,  172,
137580   /*  1080 */   173,  101,   19,   20,   97,   22,   59,  152,  152,  152,
137581   /*  1090 */    69,   59,  152,  186,  152,  152,  152,   76,   97,   36,
137582   /*  1100 */    79,   80,   19,   20,   53,   22,  152,  172,  173,   96,
137583   /*  1110 */    97,   98,  132,  133,  134,  135,  136,   35,  122,   36,
137584   /*  1120 */   234,  186,   59,   96,   97,   98,  172,  173,   96,   97,
137585   /*  1130 */    98,  152,  233,   70,  152,  114,  152,  124,  210,  210,
137586   /*  1140 */   186,  210,   59,  198,  197,   82,  214,   65,  150,  152,
137587   /*  1150 */   201,   88,   89,   70,  201,   73,  124,  239,   95,   96,
137588   /*  1160 */    97,   98,  141,  239,  101,   82,  169,  170,  176,  152,
137589   /*  1170 */   152,   88,   89,   21,   54,   55,   56,   57,   95,   96,
137590   /*  1180 */    97,   98,  164,  214,  101,  214,  169,  170,  163,  184,
137591   /*  1190 */   180,  175,  227,  111,  175,  132,  133,  134,  135,  136,
137592   /*  1200 */   200,  183,  152,  185,   84,   85,   86,   87,   88,   89,
137593   /*  1210 */    90,   91,   92,   93,   94,  132,  133,  134,  135,  136,
137594   /*  1220 */    12,  196,  172,  173,  175,  152,  198,  230,  152,  155,
137595   /*  1230 */    78,  152,  243,  152,   60,   27,  152,  159,  152,  159,
137596   /*  1240 */   152,  122,   38,  152,  219,  172,  173,  230,  172,  173,
137597   /*  1250 */    42,  172,  173,  172,  173,  103,  172,  173,  172,  173,
137598   /*  1260 */   172,  173,  237,  172,  173,  152,  240,  152,  159,  152,
137599   /*  1270 */    62,  240,   22,  220,  152,   43,  152,  130,  152,  189,
137600   /*  1280 */   152,   18,  152,   18,  192,  172,  173,  172,  173,  172,
137601   /*  1290 */   173,  192,  140,  152,  172,  173,  172,  173,  172,  173,
137602   /*  1300 */   172,  173,  172,  173,  201,  152,  192,  159,  152,  158,
137603   /*  1310 */   192,  152,  201,  172,  173,  152,  220,  152,  189,  152,
137604   /*  1320 */   189,  159,  152,  137,  152,  172,  173,  152,  172,  173,
137605   /*  1330 */   152,  172,  173,  152,  201,  172,  173,  172,  173,  172,
137606   /*  1340 */   173,  152,  172,  173,  172,  173,  152,  172,  173,  152,
137607   /*  1350 */   172,  173,  152,  172,  173,  152,   90,  152,   61,  152,
137608   /*  1360 */   158,  172,  173,  152,  158,  152,  172,  173,  152,  172,
137609   /*  1370 */   173,  152,  172,  173,  236,  172,  173,  172,  173,  172,
137610   /*  1380 */   173,  235,  116,  172,  173,  172,  173,  121,  172,  173,
137611   /*  1390 */   159,  172,  173,  159,   22,  177,  159,  158,  177,  159,
137612   /*  1400 */   158,  107,  174,  174,  174,   63,  182,  106,  182,  174,
137613   /*  1410 */   177,  125,  176,  107,  216,  174,  215,  174,  174,  159,
137614   /*  1420 */    22,  159,  137,  224,  177,  216,  216,  215,   94,  215,
137615   /*  1430 */   177,  216,  215,  129,  126,  128,  127,   25,  162,   26,
137616   /*  1440 */   161,   13,  153,  205,  153,    6,  226,  151,  202,  204,
137617   /*  1450 */   201,  229,  229,  151,  203,  165,  151,  165,  178,  178,
137618   /*  1460 */   165,    4,    3,   22,  142,   15,   81,   16,   23,   23,
137619   /*  1470 */   120,  131,  111,   20,  249,  123,  249,   16,  125,    1,
137620   /*  1480 */   123,  111,  131,   53,   53,   53,   53,   96,   34,  122,
137621   /*  1490 */     1,    5,   22,  107,  246,  140,   67,   26,   74,   41,
137622   /*  1500 */   107,   67,   20,   24,   19,  105,  112,   23,   66,   22,
137623   /*  1510 */    22,   28,   22,   22,   66,   22,   22,   37,   66,   23,
137624   /*  1520 */    23,   23,  116,   23,   22,   26,  122,   26,   23,   23,
137625   /*  1530 */    22,   96,  124,   26,   23,   26,   23,   34,   34,   23,
137626   /*  1540 */    23,   26,   23,   22,   34,   11,   23,   22,   24,  122,
137627   /*  1550 */    23,   22,   26,   22,   24,   23,   23,   15,   23,   22,
137628   /*  1560 */   122,   23,  122,    1,  251,  122,
137629  };
137630  #define YY_SHIFT_USE_DFLT (1566)
137631  #define YY_SHIFT_COUNT    (454)
137632  #define YY_SHIFT_MIN      (-84)
137633  #define YY_SHIFT_MAX      (1562)
137634  static const short yy_shift_ofst[] = {
137635   /*     0 */   355,  888, 1021,  909, 1063, 1063, 1063, 1063,   20,  -19,
137636   /*    10 */    66,   66,  170, 1063, 1063, 1063, 1063, 1063, 1063, 1063,
137637   /*    20 */    -7,   -7,   36,   73,   69,   27,  118,  222,  274,  326,
137638   /*    30 */   378,  430,  482,  534,  589,  644,  696,  696,  696,  696,
137639   /*    40 */   696,  696,  696,  696,  696,  696,  696,  696,  696,  696,
137640   /*    50 */   696,  696,  696,  748,  696,  799,  849,  849,  980, 1063,
137641   /*    60 */  1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063,
137642   /*    70 */  1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063,
137643   /*    80 */  1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063,
137644   /*    90 */  1083, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063,
137645   /*   100 */  1063, 1063, 1063, 1063,  -43, 1120, 1120, 1120, 1120, 1120,
137646   /*   110 */   -31,  -72,  -84,  242, 1152,  667,  210,  210,  242,  309,
137647   /*   120 */   336,  -55, 1566, 1566, 1566,  850,  850,  850,  626,  626,
137648   /*   130 */   588,  588,  898,  221,  264,  242,  242,  242,  242,  242,
137649   /*   140 */   242,  242,  242,  242,  242,  242,  242,  242,  242,  242,
137650   /*   150 */   242,  242,  242,  242,  242,  496,  675,  289,  289,  336,
137651   /*   160 */     0,    0,    0,    0,    0,    0, 1566, 1566, 1566,  570,
137652   /*   170 */    98,   98,  958,  389,  450,  968, 1013, 1032, 1027,  242,
137653   /*   180 */   242,  242,  242,  242,  242,  242,  242,  242,  242,  242,
137654   /*   190 */   242,  242,  242,  242,  242, 1082, 1082, 1082,  242,  242,
137655   /*   200 */   533,  242,  242,  242,  987,  242,  242, 1208,  242,  242,
137656   /*   210 */   242,  242,  242,  242,  242,  242,  242,  242,  435,  531,
137657   /*   220 */  1001, 1001, 1001,  832,  434, 1266,  594,   58,  863,  863,
137658   /*   230 */   952,   58,  952,  946,  738,  239,  145,  863,  525,  145,
137659   /*   240 */   145,  315,  647,  790, 1174, 1119, 1119, 1204, 1204, 1119,
137660   /*   250 */  1250, 1232, 1147, 1263, 1263, 1263, 1263, 1119, 1265, 1147,
137661   /*   260 */  1250, 1232, 1232, 1147, 1119, 1265, 1186, 1297, 1119, 1119,
137662   /*   270 */  1265, 1372, 1119, 1265, 1119, 1265, 1372, 1294, 1294, 1294,
137663   /*   280 */  1342, 1372, 1294, 1301, 1294, 1342, 1294, 1294, 1286, 1306,
137664   /*   290 */  1286, 1306, 1286, 1306, 1286, 1306, 1119, 1398, 1119, 1285,
137665   /*   300 */  1372, 1334, 1334, 1372, 1304, 1308, 1307, 1309, 1147, 1412,
137666   /*   310 */  1413, 1428, 1428, 1439, 1439, 1439, 1566, 1566, 1566, 1566,
137667   /*   320 */  1566, 1566, 1566, 1566,  204,  321,  429,  467,  578,  497,
137668   /*   330 */   904,  739, 1051,  793,  794,  798,  800,  802,  838,  768,
137669   /*   340 */   766,  801,  762,  847,  853,  812,  891,  681,  784,  896,
137670   /*   350 */   864,  996, 1457, 1459, 1441, 1322, 1450, 1385, 1451, 1445,
137671   /*   360 */  1446, 1350, 1340, 1361, 1352, 1453, 1353, 1461, 1478, 1357,
137672   /*   370 */  1351, 1430, 1431, 1432, 1433, 1370, 1391, 1454, 1367, 1489,
137673   /*   380 */  1486, 1470, 1386, 1355, 1429, 1471, 1434, 1424, 1458, 1393,
137674   /*   390 */  1479, 1482, 1485, 1394, 1400, 1487, 1442, 1488, 1490, 1484,
137675   /*   400 */  1491, 1448, 1483, 1493, 1452, 1480, 1496, 1497, 1498, 1499,
137676   /*   410 */  1406, 1494, 1500, 1502, 1501, 1404, 1505, 1506, 1435, 1503,
137677   /*   420 */  1508, 1408, 1507, 1504, 1509, 1510, 1511, 1507, 1513, 1516,
137678   /*   430 */  1517, 1515, 1519, 1521, 1534, 1523, 1525, 1524, 1526, 1527,
137679   /*   440 */  1529, 1530, 1526, 1532, 1531, 1533, 1535, 1537, 1427, 1438,
137680   /*   450 */  1440, 1443, 1538, 1542, 1562,
137681  };
137682  #define YY_REDUCE_USE_DFLT (-144)
137683  #define YY_REDUCE_COUNT (323)
137684  #define YY_REDUCE_MIN   (-143)
137685  #define YY_REDUCE_MAX   (1305)
137686  static const short yy_reduce_ofst[] = {
137687   /*     0 */  -143,  -65,  140,  840,   76,  180,  182,  233,  488,  -25,
137688   /*    10 */    12,   16,   59,  885,  907,  935,  390,  705,  954,  285,
137689   /*    20 */   997, 1017, 1018, -118, 1025,  139,  171,  171,  171,  171,
137690   /*    30 */   171,  171,  171,  171,  171,  171,  171,  171,  171,  171,
137691   /*    40 */   171,  171,  171,  171,  171,  171,  171,  171,  171,  171,
137692   /*    50 */   171,  171,  171,  171,  171,  171,  171,  171,  -69,  287,
137693   /*    60 */   441,  658,  708,  856, 1050, 1073, 1076, 1079, 1081, 1084,
137694   /*    70 */  1086, 1088, 1091, 1113, 1115, 1117, 1122, 1124, 1126, 1128,
137695   /*    80 */  1130, 1141, 1153, 1156, 1159, 1163, 1165, 1167, 1170, 1172,
137696   /*    90 */  1175, 1178, 1181, 1189, 1194, 1197, 1200, 1203, 1205, 1207,
137697   /*   100 */  1211, 1213, 1216, 1219,  171,  171,  171,  171,  171,  171,
137698   /*   110 */   171,  171,  171,   49,  176,  220,  275,  278,  290,  171,
137699   /*   120 */   300,  171,  171,  171,  171,  -85,  -85,  -85,  -28,   77,
137700   /*   130 */   313,  317,  -56,  252,  252,  446, -129,  243,  361,  403,
137701   /*   140 */   406,  513,  517,  409,  502,  518,  504,  509,  621,  553,
137702   /*   150 */   562,  619,  559,   93,  620,  465,  453,  550,  591,  571,
137703   /*   160 */   615,  666,  750,  752,  797,  819,  463,  548,  -73,   28,
137704   /*   170 */    68,  120,  257,  206,  359,  405,  413,  452,  457,  560,
137705   /*   180 */   566,  617,  670,  720,  723,  769,  773,  775,  780,  813,
137706   /*   190 */   814,  821,  822,  823,  826,  360,  436,  783,  829,  835,
137707   /*   200 */   707,  862,  867,  878,  830,  911,  915,  883,  936,  937,
137708   /*   210 */   940,  359,  942,  943,  944,  979,  982,  984,  886,  899,
137709   /*   220 */   928,  929,  931,  707,  947,  945,  998,  949,  932,  969,
137710   /*   230 */   918,  953,  924,  992, 1005, 1010, 1016,  971,  965, 1019,
137711   /*   240 */  1049, 1000, 1028, 1074,  989, 1078, 1080, 1026, 1031, 1109,
137712   /*   250 */  1053, 1090, 1103, 1092, 1099, 1114, 1118, 1148, 1151, 1111,
137713   /*   260 */  1096, 1129, 1131, 1133, 1162, 1202, 1138, 1146, 1231, 1234,
137714   /*   270 */  1206, 1218, 1237, 1239, 1240, 1242, 1221, 1228, 1229, 1230,
137715   /*   280 */  1224, 1233, 1235, 1236, 1241, 1226, 1243, 1244, 1198, 1201,
137716   /*   290 */  1209, 1212, 1210, 1214, 1215, 1217, 1260, 1199, 1262, 1220,
137717   /*   300 */  1247, 1222, 1223, 1253, 1238, 1245, 1251, 1246, 1249, 1276,
137718   /*   310 */  1279, 1289, 1291, 1296, 1302, 1305, 1225, 1227, 1248, 1290,
137719   /*   320 */  1292, 1280, 1281, 1295,
137720  };
137721  static const YYACTIONTYPE yy_default[] = {
137722   /*     0 */  1270, 1260, 1260, 1260, 1193, 1193, 1193, 1193, 1260, 1088,
137723   /*    10 */  1117, 1117, 1244, 1322, 1322, 1322, 1322, 1322, 1322, 1192,
137724   /*    20 */  1322, 1322, 1322, 1322, 1260, 1092, 1123, 1322, 1322, 1322,
137725   /*    30 */  1322, 1194, 1195, 1322, 1322, 1322, 1243, 1245, 1133, 1132,
137726   /*    40 */  1131, 1130, 1226, 1104, 1128, 1121, 1125, 1194, 1188, 1189,
137727   /*    50 */  1187, 1191, 1195, 1322, 1124, 1158, 1172, 1157, 1322, 1322,
137728   /*    60 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137729   /*    70 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137730   /*    80 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137731   /*    90 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137732   /*   100 */  1322, 1322, 1322, 1322, 1166, 1171, 1178, 1170, 1167, 1160,
137733   /*   110 */  1159, 1161, 1162, 1322, 1011, 1059, 1322, 1322, 1322, 1163,
137734   /*   120 */  1322, 1164, 1175, 1174, 1173, 1251, 1278, 1277, 1322, 1322,
137735   /*   130 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137736   /*   140 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137737   /*   150 */  1322, 1322, 1322, 1322, 1322, 1270, 1260, 1017, 1017, 1322,
137738   /*   160 */  1260, 1260, 1260, 1260, 1260, 1260, 1256, 1092, 1083, 1322,
137739   /*   170 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137740   /*   180 */  1248, 1246, 1322, 1208, 1322, 1322, 1322, 1322, 1322, 1322,
137741   /*   190 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137742   /*   200 */  1322, 1322, 1322, 1322, 1088, 1322, 1322, 1322, 1322, 1322,
137743   /*   210 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1272, 1322, 1221,
137744   /*   220 */  1088, 1088, 1088, 1090, 1072, 1082,  997, 1127, 1106, 1106,
137745   /*   230 */  1311, 1127, 1311, 1034, 1292, 1031, 1117, 1106, 1190, 1117,
137746   /*   240 */  1117, 1089, 1082, 1322, 1314, 1097, 1097, 1313, 1313, 1097,
137747   /*   250 */  1138, 1062, 1127, 1068, 1068, 1068, 1068, 1097, 1008, 1127,
137748   /*   260 */  1138, 1062, 1062, 1127, 1097, 1008, 1225, 1308, 1097, 1097,
137749   /*   270 */  1008, 1201, 1097, 1008, 1097, 1008, 1201, 1060, 1060, 1060,
137750   /*   280 */  1049, 1201, 1060, 1034, 1060, 1049, 1060, 1060, 1110, 1105,
137751   /*   290 */  1110, 1105, 1110, 1105, 1110, 1105, 1097, 1196, 1097, 1322,
137752   /*   300 */  1201, 1205, 1205, 1201, 1122, 1111, 1120, 1118, 1127, 1014,
137753   /*   310 */  1052, 1275, 1275, 1271, 1271, 1271, 1319, 1319, 1256, 1287,
137754   /*   320 */  1287, 1036, 1036, 1287, 1322, 1322, 1322, 1322, 1322, 1322,
137755   /*   330 */  1282, 1322, 1210, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137756   /*   340 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137757   /*   350 */  1322, 1143, 1322,  993, 1253, 1322, 1322, 1252, 1322, 1322,
137758   /*   360 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137759   /*   370 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1310, 1322,
137760   /*   380 */  1322, 1322, 1322, 1322, 1322, 1224, 1223, 1322, 1322, 1322,
137761   /*   390 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137762   /*   400 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137763   /*   410 */  1074, 1322, 1322, 1322, 1296, 1322, 1322, 1322, 1322, 1322,
137764   /*   420 */  1322, 1322, 1119, 1322, 1112, 1322, 1322, 1301, 1322, 1322,
137765   /*   430 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1262, 1322,
137766   /*   440 */  1322, 1322, 1261, 1322, 1322, 1322, 1322, 1322, 1145, 1322,
137767   /*   450 */  1144, 1148, 1322, 1002, 1322,
137768  };
137769  /********** End of lemon-generated parsing tables *****************************/
137770  
137771  /* The next table maps tokens (terminal symbols) into fallback tokens.  
137772  ** If a construct like the following:
137773  ** 
137774  **      %fallback ID X Y Z.
137775  **
137776  ** appears in the grammar, then ID becomes a fallback token for X, Y,
137777  ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
137778  ** but it does not parse, the type of the token is changed to ID and
137779  ** the parse is retried before an error is thrown.
137780  **
137781  ** This feature can be used, for example, to cause some keywords in a language
137782  ** to revert to identifiers if they keyword does not apply in the context where
137783  ** it appears.
137784  */
137785  #ifdef YYFALLBACK
137786  static const YYCODETYPE yyFallback[] = {
137787      0,  /*          $ => nothing */
137788      0,  /*       SEMI => nothing */
137789     59,  /*    EXPLAIN => ID */
137790     59,  /*      QUERY => ID */
137791     59,  /*       PLAN => ID */
137792     59,  /*      BEGIN => ID */
137793      0,  /* TRANSACTION => nothing */
137794     59,  /*   DEFERRED => ID */
137795     59,  /*  IMMEDIATE => ID */
137796     59,  /*  EXCLUSIVE => ID */
137797      0,  /*     COMMIT => nothing */
137798     59,  /*        END => ID */
137799     59,  /*   ROLLBACK => ID */
137800     59,  /*  SAVEPOINT => ID */
137801     59,  /*    RELEASE => ID */
137802      0,  /*         TO => nothing */
137803      0,  /*      TABLE => nothing */
137804      0,  /*     CREATE => nothing */
137805     59,  /*         IF => ID */
137806      0,  /*        NOT => nothing */
137807      0,  /*     EXISTS => nothing */
137808     59,  /*       TEMP => ID */
137809      0,  /*         LP => nothing */
137810      0,  /*         RP => nothing */
137811      0,  /*         AS => nothing */
137812     59,  /*    WITHOUT => ID */
137813      0,  /*      COMMA => nothing */
137814     59,  /*      ABORT => ID */
137815     59,  /*     ACTION => ID */
137816     59,  /*      AFTER => ID */
137817     59,  /*    ANALYZE => ID */
137818     59,  /*        ASC => ID */
137819     59,  /*     ATTACH => ID */
137820     59,  /*     BEFORE => ID */
137821     59,  /*         BY => ID */
137822     59,  /*    CASCADE => ID */
137823     59,  /*       CAST => ID */
137824     59,  /*   CONFLICT => ID */
137825     59,  /*   DATABASE => ID */
137826     59,  /*       DESC => ID */
137827     59,  /*     DETACH => ID */
137828     59,  /*       EACH => ID */
137829     59,  /*       FAIL => ID */
137830      0,  /*         OR => nothing */
137831      0,  /*        AND => nothing */
137832      0,  /*         IS => nothing */
137833     59,  /*      MATCH => ID */
137834     59,  /*    LIKE_KW => ID */
137835      0,  /*    BETWEEN => nothing */
137836      0,  /*         IN => nothing */
137837      0,  /*     ISNULL => nothing */
137838      0,  /*    NOTNULL => nothing */
137839      0,  /*         NE => nothing */
137840      0,  /*         EQ => nothing */
137841      0,  /*         GT => nothing */
137842      0,  /*         LE => nothing */
137843      0,  /*         LT => nothing */
137844      0,  /*         GE => nothing */
137845      0,  /*     ESCAPE => nothing */
137846      0,  /*         ID => nothing */
137847     59,  /*   COLUMNKW => ID */
137848     59,  /*        FOR => ID */
137849     59,  /*     IGNORE => ID */
137850     59,  /*  INITIALLY => ID */
137851     59,  /*    INSTEAD => ID */
137852     59,  /*         NO => ID */
137853     59,  /*        KEY => ID */
137854     59,  /*         OF => ID */
137855     59,  /*     OFFSET => ID */
137856     59,  /*     PRAGMA => ID */
137857     59,  /*      RAISE => ID */
137858     59,  /*  RECURSIVE => ID */
137859     59,  /*    REPLACE => ID */
137860     59,  /*   RESTRICT => ID */
137861     59,  /*        ROW => ID */
137862     59,  /*    TRIGGER => ID */
137863     59,  /*     VACUUM => ID */
137864     59,  /*       VIEW => ID */
137865     59,  /*    VIRTUAL => ID */
137866     59,  /*       WITH => ID */
137867     59,  /*    REINDEX => ID */
137868     59,  /*     RENAME => ID */
137869     59,  /*   CTIME_KW => ID */
137870  };
137871  #endif /* YYFALLBACK */
137872  
137873  /* The following structure represents a single element of the
137874  ** parser's stack.  Information stored includes:
137875  **
137876  **   +  The state number for the parser at this level of the stack.
137877  **
137878  **   +  The value of the token stored at this level of the stack.
137879  **      (In other words, the "major" token.)
137880  **
137881  **   +  The semantic value stored at this level of the stack.  This is
137882  **      the information used by the action routines in the grammar.
137883  **      It is sometimes called the "minor" token.
137884  **
137885  ** After the "shift" half of a SHIFTREDUCE action, the stateno field
137886  ** actually contains the reduce action for the second half of the
137887  ** SHIFTREDUCE.
137888  */
137889  struct yyStackEntry {
137890    YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
137891    YYCODETYPE major;      /* The major token value.  This is the code
137892                           ** number for the token at this stack level */
137893    YYMINORTYPE minor;     /* The user-supplied minor token value.  This
137894                           ** is the value of the token  */
137895  };
137896  typedef struct yyStackEntry yyStackEntry;
137897  
137898  /* The state of the parser is completely contained in an instance of
137899  ** the following structure */
137900  struct yyParser {
137901    yyStackEntry *yytos;          /* Pointer to top element of the stack */
137902  #ifdef YYTRACKMAXSTACKDEPTH
137903    int yyhwm;                    /* High-water mark of the stack */
137904  #endif
137905  #ifndef YYNOERRORRECOVERY
137906    int yyerrcnt;                 /* Shifts left before out of the error */
137907  #endif
137908    sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
137909  #if YYSTACKDEPTH<=0
137910    int yystksz;                  /* Current side of the stack */
137911    yyStackEntry *yystack;        /* The parser's stack */
137912    yyStackEntry yystk0;          /* First stack entry */
137913  #else
137914    yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
137915    yyStackEntry *yystackEnd;            /* Last entry in the stack */
137916  #endif
137917  };
137918  typedef struct yyParser yyParser;
137919  
137920  #ifndef NDEBUG
137921  /* #include <stdio.h> */
137922  static FILE *yyTraceFILE = 0;
137923  static char *yyTracePrompt = 0;
137924  #endif /* NDEBUG */
137925  
137926  #ifndef NDEBUG
137927  /* 
137928  ** Turn parser tracing on by giving a stream to which to write the trace
137929  ** and a prompt to preface each trace message.  Tracing is turned off
137930  ** by making either argument NULL 
137931  **
137932  ** Inputs:
137933  ** <ul>
137934  ** <li> A FILE* to which trace output should be written.
137935  **      If NULL, then tracing is turned off.
137936  ** <li> A prefix string written at the beginning of every
137937  **      line of trace output.  If NULL, then tracing is
137938  **      turned off.
137939  ** </ul>
137940  **
137941  ** Outputs:
137942  ** None.
137943  */
137944  SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
137945    yyTraceFILE = TraceFILE;
137946    yyTracePrompt = zTracePrompt;
137947    if( yyTraceFILE==0 ) yyTracePrompt = 0;
137948    else if( yyTracePrompt==0 ) yyTraceFILE = 0;
137949  }
137950  #endif /* NDEBUG */
137951  
137952  #ifndef NDEBUG
137953  /* For tracing shifts, the names of all terminals and nonterminals
137954  ** are required.  The following table supplies these names */
137955  static const char *const yyTokenName[] = { 
137956    "$",             "SEMI",          "EXPLAIN",       "QUERY",       
137957    "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
137958    "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
137959    "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
137960    "TABLE",         "CREATE",        "IF",            "NOT",         
137961    "EXISTS",        "TEMP",          "LP",            "RP",          
137962    "AS",            "WITHOUT",       "COMMA",         "ABORT",       
137963    "ACTION",        "AFTER",         "ANALYZE",       "ASC",         
137964    "ATTACH",        "BEFORE",        "BY",            "CASCADE",     
137965    "CAST",          "CONFLICT",      "DATABASE",      "DESC",        
137966    "DETACH",        "EACH",          "FAIL",          "OR",          
137967    "AND",           "IS",            "MATCH",         "LIKE_KW",     
137968    "BETWEEN",       "IN",            "ISNULL",        "NOTNULL",     
137969    "NE",            "EQ",            "GT",            "LE",          
137970    "LT",            "GE",            "ESCAPE",        "ID",          
137971    "COLUMNKW",      "FOR",           "IGNORE",        "INITIALLY",   
137972    "INSTEAD",       "NO",            "KEY",           "OF",          
137973    "OFFSET",        "PRAGMA",        "RAISE",         "RECURSIVE",   
137974    "REPLACE",       "RESTRICT",      "ROW",           "TRIGGER",     
137975    "VACUUM",        "VIEW",          "VIRTUAL",       "WITH",        
137976    "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
137977    "BITAND",        "BITOR",         "LSHIFT",        "RSHIFT",      
137978    "PLUS",          "MINUS",         "STAR",          "SLASH",       
137979    "REM",           "CONCAT",        "COLLATE",       "BITNOT",      
137980    "INDEXED",       "STRING",        "JOIN_KW",       "CONSTRAINT",  
137981    "DEFAULT",       "NULL",          "PRIMARY",       "UNIQUE",      
137982    "CHECK",         "REFERENCES",    "AUTOINCR",      "ON",          
137983    "INSERT",        "DELETE",        "UPDATE",        "SET",         
137984    "DEFERRABLE",    "FOREIGN",       "DROP",          "UNION",       
137985    "ALL",           "EXCEPT",        "INTERSECT",     "SELECT",      
137986    "VALUES",        "DISTINCT",      "DOT",           "FROM",        
137987    "JOIN",          "USING",         "ORDER",         "GROUP",       
137988    "HAVING",        "LIMIT",         "WHERE",         "INTO",        
137989    "FLOAT",         "BLOB",          "INTEGER",       "VARIABLE",    
137990    "CASE",          "WHEN",          "THEN",          "ELSE",        
137991    "INDEX",         "ALTER",         "ADD",           "error",       
137992    "input",         "cmdlist",       "ecmd",          "explain",     
137993    "cmdx",          "cmd",           "transtype",     "trans_opt",   
137994    "nm",            "savepoint_opt",  "create_table",  "create_table_args",
137995    "createkw",      "temp",          "ifnotexists",   "dbnm",        
137996    "columnlist",    "conslist_opt",  "table_options",  "select",      
137997    "columnname",    "carglist",      "typetoken",     "typename",    
137998    "signed",        "plus_num",      "minus_num",     "ccons",       
137999    "term",          "expr",          "onconf",        "sortorder",   
138000    "autoinc",       "eidlist_opt",   "refargs",       "defer_subclause",
138001    "refarg",        "refact",        "init_deferred_pred_opt",  "conslist",    
138002    "tconscomma",    "tcons",         "sortlist",      "eidlist",     
138003    "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",   
138004    "ifexists",      "fullname",      "selectnowith",  "oneselect",   
138005    "with",          "multiselect_op",  "distinct",      "selcollist",  
138006    "from",          "where_opt",     "groupby_opt",   "having_opt",  
138007    "orderby_opt",   "limit_opt",     "values",        "nexprlist",   
138008    "exprlist",      "sclp",          "as",            "seltablist",  
138009    "stl_prefix",    "joinop",        "indexed_opt",   "on_opt",      
138010    "using_opt",     "idlist",        "setlist",       "insert_cmd",  
138011    "idlist_opt",    "likeop",        "between_op",    "in_op",       
138012    "paren_exprlist",  "case_operand",  "case_exprlist",  "case_else",   
138013    "uniqueflag",    "collate",       "nmnum",         "trigger_decl",
138014    "trigger_cmd_list",  "trigger_time",  "trigger_event",  "foreach_clause",
138015    "when_clause",   "trigger_cmd",   "trnm",          "tridxby",     
138016    "database_kw_opt",  "key_opt",       "add_column_fullname",  "kwcolumn_opt",
138017    "create_vtab",   "vtabarglist",   "vtabarg",       "vtabargtoken",
138018    "lp",            "anylist",       "wqlist",      
138019  };
138020  #endif /* NDEBUG */
138021  
138022  #ifndef NDEBUG
138023  /* For tracing reduce actions, the names of all rules are required.
138024  */
138025  static const char *const yyRuleName[] = {
138026   /*   0 */ "explain ::= EXPLAIN",
138027   /*   1 */ "explain ::= EXPLAIN QUERY PLAN",
138028   /*   2 */ "cmdx ::= cmd",
138029   /*   3 */ "cmd ::= BEGIN transtype trans_opt",
138030   /*   4 */ "transtype ::=",
138031   /*   5 */ "transtype ::= DEFERRED",
138032   /*   6 */ "transtype ::= IMMEDIATE",
138033   /*   7 */ "transtype ::= EXCLUSIVE",
138034   /*   8 */ "cmd ::= COMMIT|END trans_opt",
138035   /*   9 */ "cmd ::= ROLLBACK trans_opt",
138036   /*  10 */ "cmd ::= SAVEPOINT nm",
138037   /*  11 */ "cmd ::= RELEASE savepoint_opt nm",
138038   /*  12 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
138039   /*  13 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
138040   /*  14 */ "createkw ::= CREATE",
138041   /*  15 */ "ifnotexists ::=",
138042   /*  16 */ "ifnotexists ::= IF NOT EXISTS",
138043   /*  17 */ "temp ::= TEMP",
138044   /*  18 */ "temp ::=",
138045   /*  19 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
138046   /*  20 */ "create_table_args ::= AS select",
138047   /*  21 */ "table_options ::=",
138048   /*  22 */ "table_options ::= WITHOUT nm",
138049   /*  23 */ "columnname ::= nm typetoken",
138050   /*  24 */ "typetoken ::=",
138051   /*  25 */ "typetoken ::= typename LP signed RP",
138052   /*  26 */ "typetoken ::= typename LP signed COMMA signed RP",
138053   /*  27 */ "typename ::= typename ID|STRING",
138054   /*  28 */ "ccons ::= CONSTRAINT nm",
138055   /*  29 */ "ccons ::= DEFAULT term",
138056   /*  30 */ "ccons ::= DEFAULT LP expr RP",
138057   /*  31 */ "ccons ::= DEFAULT PLUS term",
138058   /*  32 */ "ccons ::= DEFAULT MINUS term",
138059   /*  33 */ "ccons ::= DEFAULT ID|INDEXED",
138060   /*  34 */ "ccons ::= NOT NULL onconf",
138061   /*  35 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
138062   /*  36 */ "ccons ::= UNIQUE onconf",
138063   /*  37 */ "ccons ::= CHECK LP expr RP",
138064   /*  38 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
138065   /*  39 */ "ccons ::= defer_subclause",
138066   /*  40 */ "ccons ::= COLLATE ID|STRING",
138067   /*  41 */ "autoinc ::=",
138068   /*  42 */ "autoinc ::= AUTOINCR",
138069   /*  43 */ "refargs ::=",
138070   /*  44 */ "refargs ::= refargs refarg",
138071   /*  45 */ "refarg ::= MATCH nm",
138072   /*  46 */ "refarg ::= ON INSERT refact",
138073   /*  47 */ "refarg ::= ON DELETE refact",
138074   /*  48 */ "refarg ::= ON UPDATE refact",
138075   /*  49 */ "refact ::= SET NULL",
138076   /*  50 */ "refact ::= SET DEFAULT",
138077   /*  51 */ "refact ::= CASCADE",
138078   /*  52 */ "refact ::= RESTRICT",
138079   /*  53 */ "refact ::= NO ACTION",
138080   /*  54 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
138081   /*  55 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
138082   /*  56 */ "init_deferred_pred_opt ::=",
138083   /*  57 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
138084   /*  58 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
138085   /*  59 */ "conslist_opt ::=",
138086   /*  60 */ "tconscomma ::= COMMA",
138087   /*  61 */ "tcons ::= CONSTRAINT nm",
138088   /*  62 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
138089   /*  63 */ "tcons ::= UNIQUE LP sortlist RP onconf",
138090   /*  64 */ "tcons ::= CHECK LP expr RP onconf",
138091   /*  65 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
138092   /*  66 */ "defer_subclause_opt ::=",
138093   /*  67 */ "onconf ::=",
138094   /*  68 */ "onconf ::= ON CONFLICT resolvetype",
138095   /*  69 */ "orconf ::=",
138096   /*  70 */ "orconf ::= OR resolvetype",
138097   /*  71 */ "resolvetype ::= IGNORE",
138098   /*  72 */ "resolvetype ::= REPLACE",
138099   /*  73 */ "cmd ::= DROP TABLE ifexists fullname",
138100   /*  74 */ "ifexists ::= IF EXISTS",
138101   /*  75 */ "ifexists ::=",
138102   /*  76 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
138103   /*  77 */ "cmd ::= DROP VIEW ifexists fullname",
138104   /*  78 */ "cmd ::= select",
138105   /*  79 */ "select ::= with selectnowith",
138106   /*  80 */ "selectnowith ::= selectnowith multiselect_op oneselect",
138107   /*  81 */ "multiselect_op ::= UNION",
138108   /*  82 */ "multiselect_op ::= UNION ALL",
138109   /*  83 */ "multiselect_op ::= EXCEPT|INTERSECT",
138110   /*  84 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
138111   /*  85 */ "values ::= VALUES LP nexprlist RP",
138112   /*  86 */ "values ::= values COMMA LP exprlist RP",
138113   /*  87 */ "distinct ::= DISTINCT",
138114   /*  88 */ "distinct ::= ALL",
138115   /*  89 */ "distinct ::=",
138116   /*  90 */ "sclp ::=",
138117   /*  91 */ "selcollist ::= sclp expr as",
138118   /*  92 */ "selcollist ::= sclp STAR",
138119   /*  93 */ "selcollist ::= sclp nm DOT STAR",
138120   /*  94 */ "as ::= AS nm",
138121   /*  95 */ "as ::=",
138122   /*  96 */ "from ::=",
138123   /*  97 */ "from ::= FROM seltablist",
138124   /*  98 */ "stl_prefix ::= seltablist joinop",
138125   /*  99 */ "stl_prefix ::=",
138126   /* 100 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
138127   /* 101 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
138128   /* 102 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
138129   /* 103 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
138130   /* 104 */ "dbnm ::=",
138131   /* 105 */ "dbnm ::= DOT nm",
138132   /* 106 */ "fullname ::= nm dbnm",
138133   /* 107 */ "joinop ::= COMMA|JOIN",
138134   /* 108 */ "joinop ::= JOIN_KW JOIN",
138135   /* 109 */ "joinop ::= JOIN_KW nm JOIN",
138136   /* 110 */ "joinop ::= JOIN_KW nm nm JOIN",
138137   /* 111 */ "on_opt ::= ON expr",
138138   /* 112 */ "on_opt ::=",
138139   /* 113 */ "indexed_opt ::=",
138140   /* 114 */ "indexed_opt ::= INDEXED BY nm",
138141   /* 115 */ "indexed_opt ::= NOT INDEXED",
138142   /* 116 */ "using_opt ::= USING LP idlist RP",
138143   /* 117 */ "using_opt ::=",
138144   /* 118 */ "orderby_opt ::=",
138145   /* 119 */ "orderby_opt ::= ORDER BY sortlist",
138146   /* 120 */ "sortlist ::= sortlist COMMA expr sortorder",
138147   /* 121 */ "sortlist ::= expr sortorder",
138148   /* 122 */ "sortorder ::= ASC",
138149   /* 123 */ "sortorder ::= DESC",
138150   /* 124 */ "sortorder ::=",
138151   /* 125 */ "groupby_opt ::=",
138152   /* 126 */ "groupby_opt ::= GROUP BY nexprlist",
138153   /* 127 */ "having_opt ::=",
138154   /* 128 */ "having_opt ::= HAVING expr",
138155   /* 129 */ "limit_opt ::=",
138156   /* 130 */ "limit_opt ::= LIMIT expr",
138157   /* 131 */ "limit_opt ::= LIMIT expr OFFSET expr",
138158   /* 132 */ "limit_opt ::= LIMIT expr COMMA expr",
138159   /* 133 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
138160   /* 134 */ "where_opt ::=",
138161   /* 135 */ "where_opt ::= WHERE expr",
138162   /* 136 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
138163   /* 137 */ "setlist ::= setlist COMMA nm EQ expr",
138164   /* 138 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
138165   /* 139 */ "setlist ::= nm EQ expr",
138166   /* 140 */ "setlist ::= LP idlist RP EQ expr",
138167   /* 141 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select",
138168   /* 142 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES",
138169   /* 143 */ "insert_cmd ::= INSERT orconf",
138170   /* 144 */ "insert_cmd ::= REPLACE",
138171   /* 145 */ "idlist_opt ::=",
138172   /* 146 */ "idlist_opt ::= LP idlist RP",
138173   /* 147 */ "idlist ::= idlist COMMA nm",
138174   /* 148 */ "idlist ::= nm",
138175   /* 149 */ "expr ::= LP expr RP",
138176   /* 150 */ "expr ::= ID|INDEXED",
138177   /* 151 */ "expr ::= JOIN_KW",
138178   /* 152 */ "expr ::= nm DOT nm",
138179   /* 153 */ "expr ::= nm DOT nm DOT nm",
138180   /* 154 */ "term ::= NULL|FLOAT|BLOB",
138181   /* 155 */ "term ::= STRING",
138182   /* 156 */ "term ::= INTEGER",
138183   /* 157 */ "expr ::= VARIABLE",
138184   /* 158 */ "expr ::= expr COLLATE ID|STRING",
138185   /* 159 */ "expr ::= CAST LP expr AS typetoken RP",
138186   /* 160 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
138187   /* 161 */ "expr ::= ID|INDEXED LP STAR RP",
138188   /* 162 */ "term ::= CTIME_KW",
138189   /* 163 */ "expr ::= LP nexprlist COMMA expr RP",
138190   /* 164 */ "expr ::= expr AND expr",
138191   /* 165 */ "expr ::= expr OR expr",
138192   /* 166 */ "expr ::= expr LT|GT|GE|LE expr",
138193   /* 167 */ "expr ::= expr EQ|NE expr",
138194   /* 168 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
138195   /* 169 */ "expr ::= expr PLUS|MINUS expr",
138196   /* 170 */ "expr ::= expr STAR|SLASH|REM expr",
138197   /* 171 */ "expr ::= expr CONCAT expr",
138198   /* 172 */ "likeop ::= NOT LIKE_KW|MATCH",
138199   /* 173 */ "expr ::= expr likeop expr",
138200   /* 174 */ "expr ::= expr likeop expr ESCAPE expr",
138201   /* 175 */ "expr ::= expr ISNULL|NOTNULL",
138202   /* 176 */ "expr ::= expr NOT NULL",
138203   /* 177 */ "expr ::= expr IS expr",
138204   /* 178 */ "expr ::= expr IS NOT expr",
138205   /* 179 */ "expr ::= NOT expr",
138206   /* 180 */ "expr ::= BITNOT expr",
138207   /* 181 */ "expr ::= MINUS expr",
138208   /* 182 */ "expr ::= PLUS expr",
138209   /* 183 */ "between_op ::= BETWEEN",
138210   /* 184 */ "between_op ::= NOT BETWEEN",
138211   /* 185 */ "expr ::= expr between_op expr AND expr",
138212   /* 186 */ "in_op ::= IN",
138213   /* 187 */ "in_op ::= NOT IN",
138214   /* 188 */ "expr ::= expr in_op LP exprlist RP",
138215   /* 189 */ "expr ::= LP select RP",
138216   /* 190 */ "expr ::= expr in_op LP select RP",
138217   /* 191 */ "expr ::= expr in_op nm dbnm paren_exprlist",
138218   /* 192 */ "expr ::= EXISTS LP select RP",
138219   /* 193 */ "expr ::= CASE case_operand case_exprlist case_else END",
138220   /* 194 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
138221   /* 195 */ "case_exprlist ::= WHEN expr THEN expr",
138222   /* 196 */ "case_else ::= ELSE expr",
138223   /* 197 */ "case_else ::=",
138224   /* 198 */ "case_operand ::= expr",
138225   /* 199 */ "case_operand ::=",
138226   /* 200 */ "exprlist ::=",
138227   /* 201 */ "nexprlist ::= nexprlist COMMA expr",
138228   /* 202 */ "nexprlist ::= expr",
138229   /* 203 */ "paren_exprlist ::=",
138230   /* 204 */ "paren_exprlist ::= LP exprlist RP",
138231   /* 205 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
138232   /* 206 */ "uniqueflag ::= UNIQUE",
138233   /* 207 */ "uniqueflag ::=",
138234   /* 208 */ "eidlist_opt ::=",
138235   /* 209 */ "eidlist_opt ::= LP eidlist RP",
138236   /* 210 */ "eidlist ::= eidlist COMMA nm collate sortorder",
138237   /* 211 */ "eidlist ::= nm collate sortorder",
138238   /* 212 */ "collate ::=",
138239   /* 213 */ "collate ::= COLLATE ID|STRING",
138240   /* 214 */ "cmd ::= DROP INDEX ifexists fullname",
138241   /* 215 */ "cmd ::= VACUUM",
138242   /* 216 */ "cmd ::= VACUUM nm",
138243   /* 217 */ "cmd ::= PRAGMA nm dbnm",
138244   /* 218 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
138245   /* 219 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
138246   /* 220 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
138247   /* 221 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
138248   /* 222 */ "plus_num ::= PLUS INTEGER|FLOAT",
138249   /* 223 */ "minus_num ::= MINUS INTEGER|FLOAT",
138250   /* 224 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
138251   /* 225 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
138252   /* 226 */ "trigger_time ::= BEFORE|AFTER",
138253   /* 227 */ "trigger_time ::= INSTEAD OF",
138254   /* 228 */ "trigger_time ::=",
138255   /* 229 */ "trigger_event ::= DELETE|INSERT",
138256   /* 230 */ "trigger_event ::= UPDATE",
138257   /* 231 */ "trigger_event ::= UPDATE OF idlist",
138258   /* 232 */ "when_clause ::=",
138259   /* 233 */ "when_clause ::= WHEN expr",
138260   /* 234 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
138261   /* 235 */ "trigger_cmd_list ::= trigger_cmd SEMI",
138262   /* 236 */ "trnm ::= nm DOT nm",
138263   /* 237 */ "tridxby ::= INDEXED BY nm",
138264   /* 238 */ "tridxby ::= NOT INDEXED",
138265   /* 239 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
138266   /* 240 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select",
138267   /* 241 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
138268   /* 242 */ "trigger_cmd ::= select",
138269   /* 243 */ "expr ::= RAISE LP IGNORE RP",
138270   /* 244 */ "expr ::= RAISE LP raisetype COMMA nm RP",
138271   /* 245 */ "raisetype ::= ROLLBACK",
138272   /* 246 */ "raisetype ::= ABORT",
138273   /* 247 */ "raisetype ::= FAIL",
138274   /* 248 */ "cmd ::= DROP TRIGGER ifexists fullname",
138275   /* 249 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
138276   /* 250 */ "cmd ::= DETACH database_kw_opt expr",
138277   /* 251 */ "key_opt ::=",
138278   /* 252 */ "key_opt ::= KEY expr",
138279   /* 253 */ "cmd ::= REINDEX",
138280   /* 254 */ "cmd ::= REINDEX nm dbnm",
138281   /* 255 */ "cmd ::= ANALYZE",
138282   /* 256 */ "cmd ::= ANALYZE nm dbnm",
138283   /* 257 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
138284   /* 258 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
138285   /* 259 */ "add_column_fullname ::= fullname",
138286   /* 260 */ "cmd ::= create_vtab",
138287   /* 261 */ "cmd ::= create_vtab LP vtabarglist RP",
138288   /* 262 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
138289   /* 263 */ "vtabarg ::=",
138290   /* 264 */ "vtabargtoken ::= ANY",
138291   /* 265 */ "vtabargtoken ::= lp anylist RP",
138292   /* 266 */ "lp ::= LP",
138293   /* 267 */ "with ::=",
138294   /* 268 */ "with ::= WITH wqlist",
138295   /* 269 */ "with ::= WITH RECURSIVE wqlist",
138296   /* 270 */ "wqlist ::= nm eidlist_opt AS LP select RP",
138297   /* 271 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
138298   /* 272 */ "input ::= cmdlist",
138299   /* 273 */ "cmdlist ::= cmdlist ecmd",
138300   /* 274 */ "cmdlist ::= ecmd",
138301   /* 275 */ "ecmd ::= SEMI",
138302   /* 276 */ "ecmd ::= explain cmdx SEMI",
138303   /* 277 */ "explain ::=",
138304   /* 278 */ "trans_opt ::=",
138305   /* 279 */ "trans_opt ::= TRANSACTION",
138306   /* 280 */ "trans_opt ::= TRANSACTION nm",
138307   /* 281 */ "savepoint_opt ::= SAVEPOINT",
138308   /* 282 */ "savepoint_opt ::=",
138309   /* 283 */ "cmd ::= create_table create_table_args",
138310   /* 284 */ "columnlist ::= columnlist COMMA columnname carglist",
138311   /* 285 */ "columnlist ::= columnname carglist",
138312   /* 286 */ "nm ::= ID|INDEXED",
138313   /* 287 */ "nm ::= STRING",
138314   /* 288 */ "nm ::= JOIN_KW",
138315   /* 289 */ "typetoken ::= typename",
138316   /* 290 */ "typename ::= ID|STRING",
138317   /* 291 */ "signed ::= plus_num",
138318   /* 292 */ "signed ::= minus_num",
138319   /* 293 */ "carglist ::= carglist ccons",
138320   /* 294 */ "carglist ::=",
138321   /* 295 */ "ccons ::= NULL onconf",
138322   /* 296 */ "conslist_opt ::= COMMA conslist",
138323   /* 297 */ "conslist ::= conslist tconscomma tcons",
138324   /* 298 */ "conslist ::= tcons",
138325   /* 299 */ "tconscomma ::=",
138326   /* 300 */ "defer_subclause_opt ::= defer_subclause",
138327   /* 301 */ "resolvetype ::= raisetype",
138328   /* 302 */ "selectnowith ::= oneselect",
138329   /* 303 */ "oneselect ::= values",
138330   /* 304 */ "sclp ::= selcollist COMMA",
138331   /* 305 */ "as ::= ID|STRING",
138332   /* 306 */ "expr ::= term",
138333   /* 307 */ "likeop ::= LIKE_KW|MATCH",
138334   /* 308 */ "exprlist ::= nexprlist",
138335   /* 309 */ "nmnum ::= plus_num",
138336   /* 310 */ "nmnum ::= nm",
138337   /* 311 */ "nmnum ::= ON",
138338   /* 312 */ "nmnum ::= DELETE",
138339   /* 313 */ "nmnum ::= DEFAULT",
138340   /* 314 */ "plus_num ::= INTEGER|FLOAT",
138341   /* 315 */ "foreach_clause ::=",
138342   /* 316 */ "foreach_clause ::= FOR EACH ROW",
138343   /* 317 */ "trnm ::= nm",
138344   /* 318 */ "tridxby ::=",
138345   /* 319 */ "database_kw_opt ::= DATABASE",
138346   /* 320 */ "database_kw_opt ::=",
138347   /* 321 */ "kwcolumn_opt ::=",
138348   /* 322 */ "kwcolumn_opt ::= COLUMNKW",
138349   /* 323 */ "vtabarglist ::= vtabarg",
138350   /* 324 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
138351   /* 325 */ "vtabarg ::= vtabarg vtabargtoken",
138352   /* 326 */ "anylist ::=",
138353   /* 327 */ "anylist ::= anylist LP anylist RP",
138354   /* 328 */ "anylist ::= anylist ANY",
138355  };
138356  #endif /* NDEBUG */
138357  
138358  
138359  #if YYSTACKDEPTH<=0
138360  /*
138361  ** Try to increase the size of the parser stack.  Return the number
138362  ** of errors.  Return 0 on success.
138363  */
138364  static int yyGrowStack(yyParser *p){
138365    int newSize;
138366    int idx;
138367    yyStackEntry *pNew;
138368  
138369    newSize = p->yystksz*2 + 100;
138370    idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
138371    if( p->yystack==&p->yystk0 ){
138372      pNew = malloc(newSize*sizeof(pNew[0]));
138373      if( pNew ) pNew[0] = p->yystk0;
138374    }else{
138375      pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
138376    }
138377    if( pNew ){
138378      p->yystack = pNew;
138379      p->yytos = &p->yystack[idx];
138380  #ifndef NDEBUG
138381      if( yyTraceFILE ){
138382        fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
138383                yyTracePrompt, p->yystksz, newSize);
138384      }
138385  #endif
138386      p->yystksz = newSize;
138387    }
138388    return pNew==0; 
138389  }
138390  #endif
138391  
138392  /* Datatype of the argument to the memory allocated passed as the
138393  ** second argument to sqlite3ParserAlloc() below.  This can be changed by
138394  ** putting an appropriate #define in the %include section of the input
138395  ** grammar.
138396  */
138397  #ifndef YYMALLOCARGTYPE
138398  # define YYMALLOCARGTYPE size_t
138399  #endif
138400  
138401  /* Initialize a new parser that has already been allocated.
138402  */
138403  SQLITE_PRIVATE void sqlite3ParserInit(void *yypParser){
138404    yyParser *pParser = (yyParser*)yypParser;
138405  #ifdef YYTRACKMAXSTACKDEPTH
138406    pParser->yyhwm = 0;
138407  #endif
138408  #if YYSTACKDEPTH<=0
138409    pParser->yytos = NULL;
138410    pParser->yystack = NULL;
138411    pParser->yystksz = 0;
138412    if( yyGrowStack(pParser) ){
138413      pParser->yystack = &pParser->yystk0;
138414      pParser->yystksz = 1;
138415    }
138416  #endif
138417  #ifndef YYNOERRORRECOVERY
138418    pParser->yyerrcnt = -1;
138419  #endif
138420    pParser->yytos = pParser->yystack;
138421    pParser->yystack[0].stateno = 0;
138422    pParser->yystack[0].major = 0;
138423  #if YYSTACKDEPTH>0
138424    pParser->yystackEnd = &pParser->yystack[YYSTACKDEPTH-1];
138425  #endif
138426  }
138427  
138428  #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
138429  /* 
138430  ** This function allocates a new parser.
138431  ** The only argument is a pointer to a function which works like
138432  ** malloc.
138433  **
138434  ** Inputs:
138435  ** A pointer to the function used to allocate memory.
138436  **
138437  ** Outputs:
138438  ** A pointer to a parser.  This pointer is used in subsequent calls
138439  ** to sqlite3Parser and sqlite3ParserFree.
138440  */
138441  SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE)){
138442    yyParser *pParser;
138443    pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
138444    if( pParser ) sqlite3ParserInit(pParser);
138445    return pParser;
138446  }
138447  #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
138448  
138449  
138450  /* The following function deletes the "minor type" or semantic value
138451  ** associated with a symbol.  The symbol can be either a terminal
138452  ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
138453  ** a pointer to the value to be deleted.  The code used to do the 
138454  ** deletions is derived from the %destructor and/or %token_destructor
138455  ** directives of the input grammar.
138456  */
138457  static void yy_destructor(
138458    yyParser *yypParser,    /* The parser */
138459    YYCODETYPE yymajor,     /* Type code for object to destroy */
138460    YYMINORTYPE *yypminor   /* The object to be destroyed */
138461  ){
138462    sqlite3ParserARG_FETCH;
138463    switch( yymajor ){
138464      /* Here is inserted the actions which take place when a
138465      ** terminal or non-terminal is destroyed.  This can happen
138466      ** when the symbol is popped from the stack during a
138467      ** reduce or during error processing or when a parser is 
138468      ** being destroyed before it is finished parsing.
138469      **
138470      ** Note: during a reduce, the only symbols destroyed are those
138471      ** which appear on the RHS of the rule, but which are *not* used
138472      ** inside the C code.
138473      */
138474  /********* Begin destructor definitions ***************************************/
138475      case 163: /* select */
138476      case 194: /* selectnowith */
138477      case 195: /* oneselect */
138478      case 206: /* values */
138479  {
138480  sqlite3SelectDelete(pParse->db, (yypminor->yy243));
138481  }
138482        break;
138483      case 172: /* term */
138484      case 173: /* expr */
138485  {
138486  sqlite3ExprDelete(pParse->db, (yypminor->yy190).pExpr);
138487  }
138488        break;
138489      case 177: /* eidlist_opt */
138490      case 186: /* sortlist */
138491      case 187: /* eidlist */
138492      case 199: /* selcollist */
138493      case 202: /* groupby_opt */
138494      case 204: /* orderby_opt */
138495      case 207: /* nexprlist */
138496      case 208: /* exprlist */
138497      case 209: /* sclp */
138498      case 218: /* setlist */
138499      case 224: /* paren_exprlist */
138500      case 226: /* case_exprlist */
138501  {
138502  sqlite3ExprListDelete(pParse->db, (yypminor->yy148));
138503  }
138504        break;
138505      case 193: /* fullname */
138506      case 200: /* from */
138507      case 211: /* seltablist */
138508      case 212: /* stl_prefix */
138509  {
138510  sqlite3SrcListDelete(pParse->db, (yypminor->yy185));
138511  }
138512        break;
138513      case 196: /* with */
138514      case 250: /* wqlist */
138515  {
138516  sqlite3WithDelete(pParse->db, (yypminor->yy285));
138517  }
138518        break;
138519      case 201: /* where_opt */
138520      case 203: /* having_opt */
138521      case 215: /* on_opt */
138522      case 225: /* case_operand */
138523      case 227: /* case_else */
138524      case 236: /* when_clause */
138525      case 241: /* key_opt */
138526  {
138527  sqlite3ExprDelete(pParse->db, (yypminor->yy72));
138528  }
138529        break;
138530      case 216: /* using_opt */
138531      case 217: /* idlist */
138532      case 220: /* idlist_opt */
138533  {
138534  sqlite3IdListDelete(pParse->db, (yypminor->yy254));
138535  }
138536        break;
138537      case 232: /* trigger_cmd_list */
138538      case 237: /* trigger_cmd */
138539  {
138540  sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy145));
138541  }
138542        break;
138543      case 234: /* trigger_event */
138544  {
138545  sqlite3IdListDelete(pParse->db, (yypminor->yy332).b);
138546  }
138547        break;
138548  /********* End destructor definitions *****************************************/
138549      default:  break;   /* If no destructor action specified: do nothing */
138550    }
138551  }
138552  
138553  /*
138554  ** Pop the parser's stack once.
138555  **
138556  ** If there is a destructor routine associated with the token which
138557  ** is popped from the stack, then call it.
138558  */
138559  static void yy_pop_parser_stack(yyParser *pParser){
138560    yyStackEntry *yytos;
138561    assert( pParser->yytos!=0 );
138562    assert( pParser->yytos > pParser->yystack );
138563    yytos = pParser->yytos--;
138564  #ifndef NDEBUG
138565    if( yyTraceFILE ){
138566      fprintf(yyTraceFILE,"%sPopping %s\n",
138567        yyTracePrompt,
138568        yyTokenName[yytos->major]);
138569    }
138570  #endif
138571    yy_destructor(pParser, yytos->major, &yytos->minor);
138572  }
138573  
138574  /*
138575  ** Clear all secondary memory allocations from the parser
138576  */
138577  SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){
138578    yyParser *pParser = (yyParser*)p;
138579    while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
138580  #if YYSTACKDEPTH<=0
138581    if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
138582  #endif
138583  }
138584  
138585  #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
138586  /* 
138587  ** Deallocate and destroy a parser.  Destructors are called for
138588  ** all stack elements before shutting the parser down.
138589  **
138590  ** If the YYPARSEFREENEVERNULL macro exists (for example because it
138591  ** is defined in a %include section of the input grammar) then it is
138592  ** assumed that the input pointer is never NULL.
138593  */
138594  SQLITE_PRIVATE void sqlite3ParserFree(
138595    void *p,                    /* The parser to be deleted */
138596    void (*freeProc)(void*)     /* Function used to reclaim memory */
138597  ){
138598  #ifndef YYPARSEFREENEVERNULL
138599    if( p==0 ) return;
138600  #endif
138601    sqlite3ParserFinalize(p);
138602    (*freeProc)(p);
138603  }
138604  #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
138605  
138606  /*
138607  ** Return the peak depth of the stack for a parser.
138608  */
138609  #ifdef YYTRACKMAXSTACKDEPTH
138610  SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
138611    yyParser *pParser = (yyParser*)p;
138612    return pParser->yyhwm;
138613  }
138614  #endif
138615  
138616  /*
138617  ** Find the appropriate action for a parser given the terminal
138618  ** look-ahead token iLookAhead.
138619  */
138620  static unsigned int yy_find_shift_action(
138621    yyParser *pParser,        /* The parser */
138622    YYCODETYPE iLookAhead     /* The look-ahead token */
138623  ){
138624    int i;
138625    int stateno = pParser->yytos->stateno;
138626   
138627    if( stateno>=YY_MIN_REDUCE ) return stateno;
138628    assert( stateno <= YY_SHIFT_COUNT );
138629    do{
138630      i = yy_shift_ofst[stateno];
138631      assert( iLookAhead!=YYNOCODE );
138632      i += iLookAhead;
138633      if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
138634  #ifdef YYFALLBACK
138635        YYCODETYPE iFallback;            /* Fallback token */
138636        if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
138637               && (iFallback = yyFallback[iLookAhead])!=0 ){
138638  #ifndef NDEBUG
138639          if( yyTraceFILE ){
138640            fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
138641               yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
138642          }
138643  #endif
138644          assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
138645          iLookAhead = iFallback;
138646          continue;
138647        }
138648  #endif
138649  #ifdef YYWILDCARD
138650        {
138651          int j = i - iLookAhead + YYWILDCARD;
138652          if( 
138653  #if YY_SHIFT_MIN+YYWILDCARD<0
138654            j>=0 &&
138655  #endif
138656  #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
138657            j<YY_ACTTAB_COUNT &&
138658  #endif
138659            yy_lookahead[j]==YYWILDCARD && iLookAhead>0
138660          ){
138661  #ifndef NDEBUG
138662            if( yyTraceFILE ){
138663              fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
138664                 yyTracePrompt, yyTokenName[iLookAhead],
138665                 yyTokenName[YYWILDCARD]);
138666            }
138667  #endif /* NDEBUG */
138668            return yy_action[j];
138669          }
138670        }
138671  #endif /* YYWILDCARD */
138672        return yy_default[stateno];
138673      }else{
138674        return yy_action[i];
138675      }
138676    }while(1);
138677  }
138678  
138679  /*
138680  ** Find the appropriate action for a parser given the non-terminal
138681  ** look-ahead token iLookAhead.
138682  */
138683  static int yy_find_reduce_action(
138684    int stateno,              /* Current state number */
138685    YYCODETYPE iLookAhead     /* The look-ahead token */
138686  ){
138687    int i;
138688  #ifdef YYERRORSYMBOL
138689    if( stateno>YY_REDUCE_COUNT ){
138690      return yy_default[stateno];
138691    }
138692  #else
138693    assert( stateno<=YY_REDUCE_COUNT );
138694  #endif
138695    i = yy_reduce_ofst[stateno];
138696    assert( i!=YY_REDUCE_USE_DFLT );
138697    assert( iLookAhead!=YYNOCODE );
138698    i += iLookAhead;
138699  #ifdef YYERRORSYMBOL
138700    if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
138701      return yy_default[stateno];
138702    }
138703  #else
138704    assert( i>=0 && i<YY_ACTTAB_COUNT );
138705    assert( yy_lookahead[i]==iLookAhead );
138706  #endif
138707    return yy_action[i];
138708  }
138709  
138710  /*
138711  ** The following routine is called if the stack overflows.
138712  */
138713  static void yyStackOverflow(yyParser *yypParser){
138714     sqlite3ParserARG_FETCH;
138715  #ifndef NDEBUG
138716     if( yyTraceFILE ){
138717       fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
138718     }
138719  #endif
138720     while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
138721     /* Here code is inserted which will execute if the parser
138722     ** stack every overflows */
138723  /******** Begin %stack_overflow code ******************************************/
138724  
138725    sqlite3ErrorMsg(pParse, "parser stack overflow");
138726  /******** End %stack_overflow code ********************************************/
138727     sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
138728  }
138729  
138730  /*
138731  ** Print tracing information for a SHIFT action
138732  */
138733  #ifndef NDEBUG
138734  static void yyTraceShift(yyParser *yypParser, int yyNewState){
138735    if( yyTraceFILE ){
138736      if( yyNewState<YYNSTATE ){
138737        fprintf(yyTraceFILE,"%sShift '%s', go to state %d\n",
138738           yyTracePrompt,yyTokenName[yypParser->yytos->major],
138739           yyNewState);
138740      }else{
138741        fprintf(yyTraceFILE,"%sShift '%s'\n",
138742           yyTracePrompt,yyTokenName[yypParser->yytos->major]);
138743      }
138744    }
138745  }
138746  #else
138747  # define yyTraceShift(X,Y)
138748  #endif
138749  
138750  /*
138751  ** Perform a shift action.
138752  */
138753  static void yy_shift(
138754    yyParser *yypParser,          /* The parser to be shifted */
138755    int yyNewState,               /* The new state to shift in */
138756    int yyMajor,                  /* The major token to shift in */
138757    sqlite3ParserTOKENTYPE yyMinor        /* The minor token to shift in */
138758  ){
138759    yyStackEntry *yytos;
138760    yypParser->yytos++;
138761  #ifdef YYTRACKMAXSTACKDEPTH
138762    if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
138763      yypParser->yyhwm++;
138764      assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
138765    }
138766  #endif
138767  #if YYSTACKDEPTH>0 
138768    if( yypParser->yytos>yypParser->yystackEnd ){
138769      yypParser->yytos--;
138770      yyStackOverflow(yypParser);
138771      return;
138772    }
138773  #else
138774    if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
138775      if( yyGrowStack(yypParser) ){
138776        yypParser->yytos--;
138777        yyStackOverflow(yypParser);
138778        return;
138779      }
138780    }
138781  #endif
138782    if( yyNewState > YY_MAX_SHIFT ){
138783      yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
138784    }
138785    yytos = yypParser->yytos;
138786    yytos->stateno = (YYACTIONTYPE)yyNewState;
138787    yytos->major = (YYCODETYPE)yyMajor;
138788    yytos->minor.yy0 = yyMinor;
138789    yyTraceShift(yypParser, yyNewState);
138790  }
138791  
138792  /* The following table contains information about every rule that
138793  ** is used during the reduce.
138794  */
138795  static const struct {
138796    YYCODETYPE lhs;       /* Symbol on the left-hand side of the rule */
138797    signed char nrhs;     /* Negative of the number of RHS symbols in the rule */
138798  } yyRuleInfo[] = {
138799    { 147, -1 },
138800    { 147, -3 },
138801    { 148, -1 },
138802    { 149, -3 },
138803    { 150, 0 },
138804    { 150, -1 },
138805    { 150, -1 },
138806    { 150, -1 },
138807    { 149, -2 },
138808    { 149, -2 },
138809    { 149, -2 },
138810    { 149, -3 },
138811    { 149, -5 },
138812    { 154, -6 },
138813    { 156, -1 },
138814    { 158, 0 },
138815    { 158, -3 },
138816    { 157, -1 },
138817    { 157, 0 },
138818    { 155, -5 },
138819    { 155, -2 },
138820    { 162, 0 },
138821    { 162, -2 },
138822    { 164, -2 },
138823    { 166, 0 },
138824    { 166, -4 },
138825    { 166, -6 },
138826    { 167, -2 },
138827    { 171, -2 },
138828    { 171, -2 },
138829    { 171, -4 },
138830    { 171, -3 },
138831    { 171, -3 },
138832    { 171, -2 },
138833    { 171, -3 },
138834    { 171, -5 },
138835    { 171, -2 },
138836    { 171, -4 },
138837    { 171, -4 },
138838    { 171, -1 },
138839    { 171, -2 },
138840    { 176, 0 },
138841    { 176, -1 },
138842    { 178, 0 },
138843    { 178, -2 },
138844    { 180, -2 },
138845    { 180, -3 },
138846    { 180, -3 },
138847    { 180, -3 },
138848    { 181, -2 },
138849    { 181, -2 },
138850    { 181, -1 },
138851    { 181, -1 },
138852    { 181, -2 },
138853    { 179, -3 },
138854    { 179, -2 },
138855    { 182, 0 },
138856    { 182, -2 },
138857    { 182, -2 },
138858    { 161, 0 },
138859    { 184, -1 },
138860    { 185, -2 },
138861    { 185, -7 },
138862    { 185, -5 },
138863    { 185, -5 },
138864    { 185, -10 },
138865    { 188, 0 },
138866    { 174, 0 },
138867    { 174, -3 },
138868    { 189, 0 },
138869    { 189, -2 },
138870    { 190, -1 },
138871    { 190, -1 },
138872    { 149, -4 },
138873    { 192, -2 },
138874    { 192, 0 },
138875    { 149, -9 },
138876    { 149, -4 },
138877    { 149, -1 },
138878    { 163, -2 },
138879    { 194, -3 },
138880    { 197, -1 },
138881    { 197, -2 },
138882    { 197, -1 },
138883    { 195, -9 },
138884    { 206, -4 },
138885    { 206, -5 },
138886    { 198, -1 },
138887    { 198, -1 },
138888    { 198, 0 },
138889    { 209, 0 },
138890    { 199, -3 },
138891    { 199, -2 },
138892    { 199, -4 },
138893    { 210, -2 },
138894    { 210, 0 },
138895    { 200, 0 },
138896    { 200, -2 },
138897    { 212, -2 },
138898    { 212, 0 },
138899    { 211, -7 },
138900    { 211, -9 },
138901    { 211, -7 },
138902    { 211, -7 },
138903    { 159, 0 },
138904    { 159, -2 },
138905    { 193, -2 },
138906    { 213, -1 },
138907    { 213, -2 },
138908    { 213, -3 },
138909    { 213, -4 },
138910    { 215, -2 },
138911    { 215, 0 },
138912    { 214, 0 },
138913    { 214, -3 },
138914    { 214, -2 },
138915    { 216, -4 },
138916    { 216, 0 },
138917    { 204, 0 },
138918    { 204, -3 },
138919    { 186, -4 },
138920    { 186, -2 },
138921    { 175, -1 },
138922    { 175, -1 },
138923    { 175, 0 },
138924    { 202, 0 },
138925    { 202, -3 },
138926    { 203, 0 },
138927    { 203, -2 },
138928    { 205, 0 },
138929    { 205, -2 },
138930    { 205, -4 },
138931    { 205, -4 },
138932    { 149, -6 },
138933    { 201, 0 },
138934    { 201, -2 },
138935    { 149, -8 },
138936    { 218, -5 },
138937    { 218, -7 },
138938    { 218, -3 },
138939    { 218, -5 },
138940    { 149, -6 },
138941    { 149, -7 },
138942    { 219, -2 },
138943    { 219, -1 },
138944    { 220, 0 },
138945    { 220, -3 },
138946    { 217, -3 },
138947    { 217, -1 },
138948    { 173, -3 },
138949    { 173, -1 },
138950    { 173, -1 },
138951    { 173, -3 },
138952    { 173, -5 },
138953    { 172, -1 },
138954    { 172, -1 },
138955    { 172, -1 },
138956    { 173, -1 },
138957    { 173, -3 },
138958    { 173, -6 },
138959    { 173, -5 },
138960    { 173, -4 },
138961    { 172, -1 },
138962    { 173, -5 },
138963    { 173, -3 },
138964    { 173, -3 },
138965    { 173, -3 },
138966    { 173, -3 },
138967    { 173, -3 },
138968    { 173, -3 },
138969    { 173, -3 },
138970    { 173, -3 },
138971    { 221, -2 },
138972    { 173, -3 },
138973    { 173, -5 },
138974    { 173, -2 },
138975    { 173, -3 },
138976    { 173, -3 },
138977    { 173, -4 },
138978    { 173, -2 },
138979    { 173, -2 },
138980    { 173, -2 },
138981    { 173, -2 },
138982    { 222, -1 },
138983    { 222, -2 },
138984    { 173, -5 },
138985    { 223, -1 },
138986    { 223, -2 },
138987    { 173, -5 },
138988    { 173, -3 },
138989    { 173, -5 },
138990    { 173, -5 },
138991    { 173, -4 },
138992    { 173, -5 },
138993    { 226, -5 },
138994    { 226, -4 },
138995    { 227, -2 },
138996    { 227, 0 },
138997    { 225, -1 },
138998    { 225, 0 },
138999    { 208, 0 },
139000    { 207, -3 },
139001    { 207, -1 },
139002    { 224, 0 },
139003    { 224, -3 },
139004    { 149, -12 },
139005    { 228, -1 },
139006    { 228, 0 },
139007    { 177, 0 },
139008    { 177, -3 },
139009    { 187, -5 },
139010    { 187, -3 },
139011    { 229, 0 },
139012    { 229, -2 },
139013    { 149, -4 },
139014    { 149, -1 },
139015    { 149, -2 },
139016    { 149, -3 },
139017    { 149, -5 },
139018    { 149, -6 },
139019    { 149, -5 },
139020    { 149, -6 },
139021    { 169, -2 },
139022    { 170, -2 },
139023    { 149, -5 },
139024    { 231, -11 },
139025    { 233, -1 },
139026    { 233, -2 },
139027    { 233, 0 },
139028    { 234, -1 },
139029    { 234, -1 },
139030    { 234, -3 },
139031    { 236, 0 },
139032    { 236, -2 },
139033    { 232, -3 },
139034    { 232, -2 },
139035    { 238, -3 },
139036    { 239, -3 },
139037    { 239, -2 },
139038    { 237, -7 },
139039    { 237, -5 },
139040    { 237, -5 },
139041    { 237, -1 },
139042    { 173, -4 },
139043    { 173, -6 },
139044    { 191, -1 },
139045    { 191, -1 },
139046    { 191, -1 },
139047    { 149, -4 },
139048    { 149, -6 },
139049    { 149, -3 },
139050    { 241, 0 },
139051    { 241, -2 },
139052    { 149, -1 },
139053    { 149, -3 },
139054    { 149, -1 },
139055    { 149, -3 },
139056    { 149, -6 },
139057    { 149, -7 },
139058    { 242, -1 },
139059    { 149, -1 },
139060    { 149, -4 },
139061    { 244, -8 },
139062    { 246, 0 },
139063    { 247, -1 },
139064    { 247, -3 },
139065    { 248, -1 },
139066    { 196, 0 },
139067    { 196, -2 },
139068    { 196, -3 },
139069    { 250, -6 },
139070    { 250, -8 },
139071    { 144, -1 },
139072    { 145, -2 },
139073    { 145, -1 },
139074    { 146, -1 },
139075    { 146, -3 },
139076    { 147, 0 },
139077    { 151, 0 },
139078    { 151, -1 },
139079    { 151, -2 },
139080    { 153, -1 },
139081    { 153, 0 },
139082    { 149, -2 },
139083    { 160, -4 },
139084    { 160, -2 },
139085    { 152, -1 },
139086    { 152, -1 },
139087    { 152, -1 },
139088    { 166, -1 },
139089    { 167, -1 },
139090    { 168, -1 },
139091    { 168, -1 },
139092    { 165, -2 },
139093    { 165, 0 },
139094    { 171, -2 },
139095    { 161, -2 },
139096    { 183, -3 },
139097    { 183, -1 },
139098    { 184, 0 },
139099    { 188, -1 },
139100    { 190, -1 },
139101    { 194, -1 },
139102    { 195, -1 },
139103    { 209, -2 },
139104    { 210, -1 },
139105    { 173, -1 },
139106    { 221, -1 },
139107    { 208, -1 },
139108    { 230, -1 },
139109    { 230, -1 },
139110    { 230, -1 },
139111    { 230, -1 },
139112    { 230, -1 },
139113    { 169, -1 },
139114    { 235, 0 },
139115    { 235, -3 },
139116    { 238, -1 },
139117    { 239, 0 },
139118    { 240, -1 },
139119    { 240, 0 },
139120    { 243, 0 },
139121    { 243, -1 },
139122    { 245, -1 },
139123    { 245, -3 },
139124    { 246, -2 },
139125    { 249, 0 },
139126    { 249, -4 },
139127    { 249, -2 },
139128  };
139129  
139130  static void yy_accept(yyParser*);  /* Forward Declaration */
139131  
139132  /*
139133  ** Perform a reduce action and the shift that must immediately
139134  ** follow the reduce.
139135  */
139136  static void yy_reduce(
139137    yyParser *yypParser,         /* The parser */
139138    unsigned int yyruleno        /* Number of the rule by which to reduce */
139139  ){
139140    int yygoto;                     /* The next state */
139141    int yyact;                      /* The next action */
139142    yyStackEntry *yymsp;            /* The top of the parser's stack */
139143    int yysize;                     /* Amount to pop the stack */
139144    sqlite3ParserARG_FETCH;
139145    yymsp = yypParser->yytos;
139146  #ifndef NDEBUG
139147    if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
139148      yysize = yyRuleInfo[yyruleno].nrhs;
139149      fprintf(yyTraceFILE, "%sReduce [%s], go to state %d.\n", yyTracePrompt,
139150        yyRuleName[yyruleno], yymsp[yysize].stateno);
139151    }
139152  #endif /* NDEBUG */
139153  
139154    /* Check that the stack is large enough to grow by a single entry
139155    ** if the RHS of the rule is empty.  This ensures that there is room
139156    ** enough on the stack to push the LHS value */
139157    if( yyRuleInfo[yyruleno].nrhs==0 ){
139158  #ifdef YYTRACKMAXSTACKDEPTH
139159      if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
139160        yypParser->yyhwm++;
139161        assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
139162      }
139163  #endif
139164  #if YYSTACKDEPTH>0 
139165      if( yypParser->yytos>=yypParser->yystackEnd ){
139166        yyStackOverflow(yypParser);
139167        return;
139168      }
139169  #else
139170      if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
139171        if( yyGrowStack(yypParser) ){
139172          yyStackOverflow(yypParser);
139173          return;
139174        }
139175        yymsp = yypParser->yytos;
139176      }
139177  #endif
139178    }
139179  
139180    switch( yyruleno ){
139181    /* Beginning here are the reduction cases.  A typical example
139182    ** follows:
139183    **   case 0:
139184    **  #line <lineno> <grammarfile>
139185    **     { ... }           // User supplied code
139186    **  #line <lineno> <thisfile>
139187    **     break;
139188    */
139189  /********** Begin reduce actions **********************************************/
139190          YYMINORTYPE yylhsminor;
139191        case 0: /* explain ::= EXPLAIN */
139192  { pParse->explain = 1; }
139193          break;
139194        case 1: /* explain ::= EXPLAIN QUERY PLAN */
139195  { pParse->explain = 2; }
139196          break;
139197        case 2: /* cmdx ::= cmd */
139198  { sqlite3FinishCoding(pParse); }
139199          break;
139200        case 3: /* cmd ::= BEGIN transtype trans_opt */
139201  {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy194);}
139202          break;
139203        case 4: /* transtype ::= */
139204  {yymsp[1].minor.yy194 = TK_DEFERRED;}
139205          break;
139206        case 5: /* transtype ::= DEFERRED */
139207        case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
139208        case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
139209  {yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-X*/}
139210          break;
139211        case 8: /* cmd ::= COMMIT|END trans_opt */
139212        case 9: /* cmd ::= ROLLBACK trans_opt */ yytestcase(yyruleno==9);
139213  {sqlite3EndTransaction(pParse,yymsp[-1].major);}
139214          break;
139215        case 10: /* cmd ::= SAVEPOINT nm */
139216  {
139217    sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
139218  }
139219          break;
139220        case 11: /* cmd ::= RELEASE savepoint_opt nm */
139221  {
139222    sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
139223  }
139224          break;
139225        case 12: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
139226  {
139227    sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
139228  }
139229          break;
139230        case 13: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
139231  {
139232     sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy194,0,0,yymsp[-2].minor.yy194);
139233  }
139234          break;
139235        case 14: /* createkw ::= CREATE */
139236  {disableLookaside(pParse);}
139237          break;
139238        case 15: /* ifnotexists ::= */
139239        case 18: /* temp ::= */ yytestcase(yyruleno==18);
139240        case 21: /* table_options ::= */ yytestcase(yyruleno==21);
139241        case 41: /* autoinc ::= */ yytestcase(yyruleno==41);
139242        case 56: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==56);
139243        case 66: /* defer_subclause_opt ::= */ yytestcase(yyruleno==66);
139244        case 75: /* ifexists ::= */ yytestcase(yyruleno==75);
139245        case 89: /* distinct ::= */ yytestcase(yyruleno==89);
139246        case 212: /* collate ::= */ yytestcase(yyruleno==212);
139247  {yymsp[1].minor.yy194 = 0;}
139248          break;
139249        case 16: /* ifnotexists ::= IF NOT EXISTS */
139250  {yymsp[-2].minor.yy194 = 1;}
139251          break;
139252        case 17: /* temp ::= TEMP */
139253        case 42: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==42);
139254  {yymsp[0].minor.yy194 = 1;}
139255          break;
139256        case 19: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
139257  {
139258    sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy194,0);
139259  }
139260          break;
139261        case 20: /* create_table_args ::= AS select */
139262  {
139263    sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy243);
139264    sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
139265  }
139266          break;
139267        case 22: /* table_options ::= WITHOUT nm */
139268  {
139269    if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
139270      yymsp[-1].minor.yy194 = TF_WithoutRowid | TF_NoVisibleRowid;
139271    }else{
139272      yymsp[-1].minor.yy194 = 0;
139273      sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
139274    }
139275  }
139276          break;
139277        case 23: /* columnname ::= nm typetoken */
139278  {sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
139279          break;
139280        case 24: /* typetoken ::= */
139281        case 59: /* conslist_opt ::= */ yytestcase(yyruleno==59);
139282        case 95: /* as ::= */ yytestcase(yyruleno==95);
139283  {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
139284          break;
139285        case 25: /* typetoken ::= typename LP signed RP */
139286  {
139287    yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
139288  }
139289          break;
139290        case 26: /* typetoken ::= typename LP signed COMMA signed RP */
139291  {
139292    yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
139293  }
139294          break;
139295        case 27: /* typename ::= typename ID|STRING */
139296  {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
139297          break;
139298        case 28: /* ccons ::= CONSTRAINT nm */
139299        case 61: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==61);
139300  {pParse->constraintName = yymsp[0].minor.yy0;}
139301          break;
139302        case 29: /* ccons ::= DEFAULT term */
139303        case 31: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==31);
139304  {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy190);}
139305          break;
139306        case 30: /* ccons ::= DEFAULT LP expr RP */
139307  {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy190);}
139308          break;
139309        case 32: /* ccons ::= DEFAULT MINUS term */
139310  {
139311    ExprSpan v;
139312    v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy190.pExpr, 0);
139313    v.zStart = yymsp[-1].minor.yy0.z;
139314    v.zEnd = yymsp[0].minor.yy190.zEnd;
139315    sqlite3AddDefaultValue(pParse,&v);
139316  }
139317          break;
139318        case 33: /* ccons ::= DEFAULT ID|INDEXED */
139319  {
139320    ExprSpan v;
139321    spanExpr(&v, pParse, TK_STRING, yymsp[0].minor.yy0);
139322    sqlite3AddDefaultValue(pParse,&v);
139323  }
139324          break;
139325        case 34: /* ccons ::= NOT NULL onconf */
139326  {sqlite3AddNotNull(pParse, yymsp[0].minor.yy194);}
139327          break;
139328        case 35: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
139329  {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy194,yymsp[0].minor.yy194,yymsp[-2].minor.yy194);}
139330          break;
139331        case 36: /* ccons ::= UNIQUE onconf */
139332  {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy194,0,0,0,0,
139333                                     SQLITE_IDXTYPE_UNIQUE);}
139334          break;
139335        case 37: /* ccons ::= CHECK LP expr RP */
139336  {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy190.pExpr);}
139337          break;
139338        case 38: /* ccons ::= REFERENCES nm eidlist_opt refargs */
139339  {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy148,yymsp[0].minor.yy194);}
139340          break;
139341        case 39: /* ccons ::= defer_subclause */
139342  {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy194);}
139343          break;
139344        case 40: /* ccons ::= COLLATE ID|STRING */
139345  {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
139346          break;
139347        case 43: /* refargs ::= */
139348  { yymsp[1].minor.yy194 = OE_None*0x0101; /* EV: R-19803-45884 */}
139349          break;
139350        case 44: /* refargs ::= refargs refarg */
139351  { yymsp[-1].minor.yy194 = (yymsp[-1].minor.yy194 & ~yymsp[0].minor.yy497.mask) | yymsp[0].minor.yy497.value; }
139352          break;
139353        case 45: /* refarg ::= MATCH nm */
139354  { yymsp[-1].minor.yy497.value = 0;     yymsp[-1].minor.yy497.mask = 0x000000; }
139355          break;
139356        case 46: /* refarg ::= ON INSERT refact */
139357  { yymsp[-2].minor.yy497.value = 0;     yymsp[-2].minor.yy497.mask = 0x000000; }
139358          break;
139359        case 47: /* refarg ::= ON DELETE refact */
139360  { yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194;     yymsp[-2].minor.yy497.mask = 0x0000ff; }
139361          break;
139362        case 48: /* refarg ::= ON UPDATE refact */
139363  { yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194<<8;  yymsp[-2].minor.yy497.mask = 0x00ff00; }
139364          break;
139365        case 49: /* refact ::= SET NULL */
139366  { yymsp[-1].minor.yy194 = OE_SetNull;  /* EV: R-33326-45252 */}
139367          break;
139368        case 50: /* refact ::= SET DEFAULT */
139369  { yymsp[-1].minor.yy194 = OE_SetDflt;  /* EV: R-33326-45252 */}
139370          break;
139371        case 51: /* refact ::= CASCADE */
139372  { yymsp[0].minor.yy194 = OE_Cascade;  /* EV: R-33326-45252 */}
139373          break;
139374        case 52: /* refact ::= RESTRICT */
139375  { yymsp[0].minor.yy194 = OE_Restrict; /* EV: R-33326-45252 */}
139376          break;
139377        case 53: /* refact ::= NO ACTION */
139378  { yymsp[-1].minor.yy194 = OE_None;     /* EV: R-33326-45252 */}
139379          break;
139380        case 54: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
139381  {yymsp[-2].minor.yy194 = 0;}
139382          break;
139383        case 55: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
139384        case 70: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==70);
139385        case 143: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==143);
139386  {yymsp[-1].minor.yy194 = yymsp[0].minor.yy194;}
139387          break;
139388        case 57: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
139389        case 74: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==74);
139390        case 184: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==184);
139391        case 187: /* in_op ::= NOT IN */ yytestcase(yyruleno==187);
139392        case 213: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==213);
139393  {yymsp[-1].minor.yy194 = 1;}
139394          break;
139395        case 58: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
139396  {yymsp[-1].minor.yy194 = 0;}
139397          break;
139398        case 60: /* tconscomma ::= COMMA */
139399  {pParse->constraintName.n = 0;}
139400          break;
139401        case 62: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
139402  {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy148,yymsp[0].minor.yy194,yymsp[-2].minor.yy194,0);}
139403          break;
139404        case 63: /* tcons ::= UNIQUE LP sortlist RP onconf */
139405  {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy148,yymsp[0].minor.yy194,0,0,0,0,
139406                                         SQLITE_IDXTYPE_UNIQUE);}
139407          break;
139408        case 64: /* tcons ::= CHECK LP expr RP onconf */
139409  {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy190.pExpr);}
139410          break;
139411        case 65: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
139412  {
139413      sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy148, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[-1].minor.yy194);
139414      sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy194);
139415  }
139416          break;
139417        case 67: /* onconf ::= */
139418        case 69: /* orconf ::= */ yytestcase(yyruleno==69);
139419  {yymsp[1].minor.yy194 = OE_Default;}
139420          break;
139421        case 68: /* onconf ::= ON CONFLICT resolvetype */
139422  {yymsp[-2].minor.yy194 = yymsp[0].minor.yy194;}
139423          break;
139424        case 71: /* resolvetype ::= IGNORE */
139425  {yymsp[0].minor.yy194 = OE_Ignore;}
139426          break;
139427        case 72: /* resolvetype ::= REPLACE */
139428        case 144: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==144);
139429  {yymsp[0].minor.yy194 = OE_Replace;}
139430          break;
139431        case 73: /* cmd ::= DROP TABLE ifexists fullname */
139432  {
139433    sqlite3DropTable(pParse, yymsp[0].minor.yy185, 0, yymsp[-1].minor.yy194);
139434  }
139435          break;
139436        case 76: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
139437  {
139438    sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[0].minor.yy243, yymsp[-7].minor.yy194, yymsp[-5].minor.yy194);
139439  }
139440          break;
139441        case 77: /* cmd ::= DROP VIEW ifexists fullname */
139442  {
139443    sqlite3DropTable(pParse, yymsp[0].minor.yy185, 1, yymsp[-1].minor.yy194);
139444  }
139445          break;
139446        case 78: /* cmd ::= select */
139447  {
139448    SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
139449    sqlite3Select(pParse, yymsp[0].minor.yy243, &dest);
139450    sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
139451  }
139452          break;
139453        case 79: /* select ::= with selectnowith */
139454  {
139455    Select *p = yymsp[0].minor.yy243;
139456    if( p ){
139457      p->pWith = yymsp[-1].minor.yy285;
139458      parserDoubleLinkSelect(pParse, p);
139459    }else{
139460      sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy285);
139461    }
139462    yymsp[-1].minor.yy243 = p; /*A-overwrites-W*/
139463  }
139464          break;
139465        case 80: /* selectnowith ::= selectnowith multiselect_op oneselect */
139466  {
139467    Select *pRhs = yymsp[0].minor.yy243;
139468    Select *pLhs = yymsp[-2].minor.yy243;
139469    if( pRhs && pRhs->pPrior ){
139470      SrcList *pFrom;
139471      Token x;
139472      x.n = 0;
139473      parserDoubleLinkSelect(pParse, pRhs);
139474      pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
139475      pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
139476    }
139477    if( pRhs ){
139478      pRhs->op = (u8)yymsp[-1].minor.yy194;
139479      pRhs->pPrior = pLhs;
139480      if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
139481      pRhs->selFlags &= ~SF_MultiValue;
139482      if( yymsp[-1].minor.yy194!=TK_ALL ) pParse->hasCompound = 1;
139483    }else{
139484      sqlite3SelectDelete(pParse->db, pLhs);
139485    }
139486    yymsp[-2].minor.yy243 = pRhs;
139487  }
139488          break;
139489        case 81: /* multiselect_op ::= UNION */
139490        case 83: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==83);
139491  {yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-OP*/}
139492          break;
139493        case 82: /* multiselect_op ::= UNION ALL */
139494  {yymsp[-1].minor.yy194 = TK_ALL;}
139495          break;
139496        case 84: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
139497  {
139498  #if SELECTTRACE_ENABLED
139499    Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/
139500  #endif
139501    yymsp[-8].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy148,yymsp[-5].minor.yy185,yymsp[-4].minor.yy72,yymsp[-3].minor.yy148,yymsp[-2].minor.yy72,yymsp[-1].minor.yy148,yymsp[-7].minor.yy194,yymsp[0].minor.yy354.pLimit,yymsp[0].minor.yy354.pOffset);
139502  #if SELECTTRACE_ENABLED
139503    /* Populate the Select.zSelName[] string that is used to help with
139504    ** query planner debugging, to differentiate between multiple Select
139505    ** objects in a complex query.
139506    **
139507    ** If the SELECT keyword is immediately followed by a C-style comment
139508    ** then extract the first few alphanumeric characters from within that
139509    ** comment to be the zSelName value.  Otherwise, the label is #N where
139510    ** is an integer that is incremented with each SELECT statement seen.
139511    */
139512    if( yymsp[-8].minor.yy243!=0 ){
139513      const char *z = s.z+6;
139514      int i;
139515      sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "#%d",
139516                       ++pParse->nSelect);
139517      while( z[0]==' ' ) z++;
139518      if( z[0]=='/' && z[1]=='*' ){
139519        z += 2;
139520        while( z[0]==' ' ) z++;
139521        for(i=0; sqlite3Isalnum(z[i]); i++){}
139522        sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "%.*s", i, z);
139523      }
139524    }
139525  #endif /* SELECTRACE_ENABLED */
139526  }
139527          break;
139528        case 85: /* values ::= VALUES LP nexprlist RP */
139529  {
139530    yymsp[-3].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values,0,0);
139531  }
139532          break;
139533        case 86: /* values ::= values COMMA LP exprlist RP */
139534  {
139535    Select *pRight, *pLeft = yymsp[-4].minor.yy243;
139536    pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
139537    if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
139538    if( pRight ){
139539      pRight->op = TK_ALL;
139540      pRight->pPrior = pLeft;
139541      yymsp[-4].minor.yy243 = pRight;
139542    }else{
139543      yymsp[-4].minor.yy243 = pLeft;
139544    }
139545  }
139546          break;
139547        case 87: /* distinct ::= DISTINCT */
139548  {yymsp[0].minor.yy194 = SF_Distinct;}
139549          break;
139550        case 88: /* distinct ::= ALL */
139551  {yymsp[0].minor.yy194 = SF_All;}
139552          break;
139553        case 90: /* sclp ::= */
139554        case 118: /* orderby_opt ::= */ yytestcase(yyruleno==118);
139555        case 125: /* groupby_opt ::= */ yytestcase(yyruleno==125);
139556        case 200: /* exprlist ::= */ yytestcase(yyruleno==200);
139557        case 203: /* paren_exprlist ::= */ yytestcase(yyruleno==203);
139558        case 208: /* eidlist_opt ::= */ yytestcase(yyruleno==208);
139559  {yymsp[1].minor.yy148 = 0;}
139560          break;
139561        case 91: /* selcollist ::= sclp expr as */
139562  {
139563     yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy148, yymsp[-1].minor.yy190.pExpr);
139564     if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-2].minor.yy148, &yymsp[0].minor.yy0, 1);
139565     sqlite3ExprListSetSpan(pParse,yymsp[-2].minor.yy148,&yymsp[-1].minor.yy190);
139566  }
139567          break;
139568        case 92: /* selcollist ::= sclp STAR */
139569  {
139570    Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
139571    yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy148, p);
139572  }
139573          break;
139574        case 93: /* selcollist ::= sclp nm DOT STAR */
139575  {
139576    Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
139577    Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
139578    Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
139579    yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, pDot);
139580  }
139581          break;
139582        case 94: /* as ::= AS nm */
139583        case 105: /* dbnm ::= DOT nm */ yytestcase(yyruleno==105);
139584        case 222: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==222);
139585        case 223: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==223);
139586  {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
139587          break;
139588        case 96: /* from ::= */
139589  {yymsp[1].minor.yy185 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy185));}
139590          break;
139591        case 97: /* from ::= FROM seltablist */
139592  {
139593    yymsp[-1].minor.yy185 = yymsp[0].minor.yy185;
139594    sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy185);
139595  }
139596          break;
139597        case 98: /* stl_prefix ::= seltablist joinop */
139598  {
139599     if( ALWAYS(yymsp[-1].minor.yy185 && yymsp[-1].minor.yy185->nSrc>0) ) yymsp[-1].minor.yy185->a[yymsp[-1].minor.yy185->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy194;
139600  }
139601          break;
139602        case 99: /* stl_prefix ::= */
139603  {yymsp[1].minor.yy185 = 0;}
139604          break;
139605        case 100: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
139606  {
139607    yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
139608    sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy185, &yymsp[-2].minor.yy0);
139609  }
139610          break;
139611        case 101: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
139612  {
139613    yymsp[-8].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy185,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
139614    sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy185, yymsp[-4].minor.yy148);
139615  }
139616          break;
139617        case 102: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
139618  {
139619      yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy243,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
139620    }
139621          break;
139622        case 103: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
139623  {
139624      if( yymsp[-6].minor.yy185==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy72==0 && yymsp[0].minor.yy254==0 ){
139625        yymsp[-6].minor.yy185 = yymsp[-4].minor.yy185;
139626      }else if( yymsp[-4].minor.yy185->nSrc==1 ){
139627        yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
139628        if( yymsp[-6].minor.yy185 ){
139629          struct SrcList_item *pNew = &yymsp[-6].minor.yy185->a[yymsp[-6].minor.yy185->nSrc-1];
139630          struct SrcList_item *pOld = yymsp[-4].minor.yy185->a;
139631          pNew->zName = pOld->zName;
139632          pNew->zDatabase = pOld->zDatabase;
139633          pNew->pSelect = pOld->pSelect;
139634          pOld->zName = pOld->zDatabase = 0;
139635          pOld->pSelect = 0;
139636        }
139637        sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy185);
139638      }else{
139639        Select *pSubquery;
139640        sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy185);
139641        pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy185,0,0,0,0,SF_NestedFrom,0,0);
139642        yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
139643      }
139644    }
139645          break;
139646        case 104: /* dbnm ::= */
139647        case 113: /* indexed_opt ::= */ yytestcase(yyruleno==113);
139648  {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
139649          break;
139650        case 106: /* fullname ::= nm dbnm */
139651  {yymsp[-1].minor.yy185 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
139652          break;
139653        case 107: /* joinop ::= COMMA|JOIN */
139654  { yymsp[0].minor.yy194 = JT_INNER; }
139655          break;
139656        case 108: /* joinop ::= JOIN_KW JOIN */
139657  {yymsp[-1].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0);  /*X-overwrites-A*/}
139658          break;
139659        case 109: /* joinop ::= JOIN_KW nm JOIN */
139660  {yymsp[-2].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
139661          break;
139662        case 110: /* joinop ::= JOIN_KW nm nm JOIN */
139663  {yymsp[-3].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
139664          break;
139665        case 111: /* on_opt ::= ON expr */
139666        case 128: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==128);
139667        case 135: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==135);
139668        case 196: /* case_else ::= ELSE expr */ yytestcase(yyruleno==196);
139669  {yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr;}
139670          break;
139671        case 112: /* on_opt ::= */
139672        case 127: /* having_opt ::= */ yytestcase(yyruleno==127);
139673        case 134: /* where_opt ::= */ yytestcase(yyruleno==134);
139674        case 197: /* case_else ::= */ yytestcase(yyruleno==197);
139675        case 199: /* case_operand ::= */ yytestcase(yyruleno==199);
139676  {yymsp[1].minor.yy72 = 0;}
139677          break;
139678        case 114: /* indexed_opt ::= INDEXED BY nm */
139679  {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
139680          break;
139681        case 115: /* indexed_opt ::= NOT INDEXED */
139682  {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
139683          break;
139684        case 116: /* using_opt ::= USING LP idlist RP */
139685  {yymsp[-3].minor.yy254 = yymsp[-1].minor.yy254;}
139686          break;
139687        case 117: /* using_opt ::= */
139688        case 145: /* idlist_opt ::= */ yytestcase(yyruleno==145);
139689  {yymsp[1].minor.yy254 = 0;}
139690          break;
139691        case 119: /* orderby_opt ::= ORDER BY sortlist */
139692        case 126: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==126);
139693  {yymsp[-2].minor.yy148 = yymsp[0].minor.yy148;}
139694          break;
139695        case 120: /* sortlist ::= sortlist COMMA expr sortorder */
139696  {
139697    yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148,yymsp[-1].minor.yy190.pExpr);
139698    sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy148,yymsp[0].minor.yy194);
139699  }
139700          break;
139701        case 121: /* sortlist ::= expr sortorder */
139702  {
139703    yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy190.pExpr); /*A-overwrites-Y*/
139704    sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy148,yymsp[0].minor.yy194);
139705  }
139706          break;
139707        case 122: /* sortorder ::= ASC */
139708  {yymsp[0].minor.yy194 = SQLITE_SO_ASC;}
139709          break;
139710        case 123: /* sortorder ::= DESC */
139711  {yymsp[0].minor.yy194 = SQLITE_SO_DESC;}
139712          break;
139713        case 124: /* sortorder ::= */
139714  {yymsp[1].minor.yy194 = SQLITE_SO_UNDEFINED;}
139715          break;
139716        case 129: /* limit_opt ::= */
139717  {yymsp[1].minor.yy354.pLimit = 0; yymsp[1].minor.yy354.pOffset = 0;}
139718          break;
139719        case 130: /* limit_opt ::= LIMIT expr */
139720  {yymsp[-1].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr; yymsp[-1].minor.yy354.pOffset = 0;}
139721          break;
139722        case 131: /* limit_opt ::= LIMIT expr OFFSET expr */
139723  {yymsp[-3].minor.yy354.pLimit = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pOffset = yymsp[0].minor.yy190.pExpr;}
139724          break;
139725        case 132: /* limit_opt ::= LIMIT expr COMMA expr */
139726  {yymsp[-3].minor.yy354.pOffset = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr;}
139727          break;
139728        case 133: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
139729  {
139730    sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
139731    sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy185, &yymsp[-1].minor.yy0);
139732    sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy185,yymsp[0].minor.yy72);
139733  }
139734          break;
139735        case 136: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
139736  {
139737    sqlite3WithPush(pParse, yymsp[-7].minor.yy285, 1);
139738    sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy185, &yymsp[-3].minor.yy0);
139739    sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy148,"set list"); 
139740    sqlite3Update(pParse,yymsp[-4].minor.yy185,yymsp[-1].minor.yy148,yymsp[0].minor.yy72,yymsp[-5].minor.yy194);
139741  }
139742          break;
139743        case 137: /* setlist ::= setlist COMMA nm EQ expr */
139744  {
139745    yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
139746    sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, 1);
139747  }
139748          break;
139749        case 138: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
139750  {
139751    yymsp[-6].minor.yy148 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy148, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr);
139752  }
139753          break;
139754        case 139: /* setlist ::= nm EQ expr */
139755  {
139756    yylhsminor.yy148 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy190.pExpr);
139757    sqlite3ExprListSetName(pParse, yylhsminor.yy148, &yymsp[-2].minor.yy0, 1);
139758  }
139759    yymsp[-2].minor.yy148 = yylhsminor.yy148;
139760          break;
139761        case 140: /* setlist ::= LP idlist RP EQ expr */
139762  {
139763    yymsp[-4].minor.yy148 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr);
139764  }
139765          break;
139766        case 141: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */
139767  {
139768    sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
139769    sqlite3Insert(pParse, yymsp[-2].minor.yy185, yymsp[0].minor.yy243, yymsp[-1].minor.yy254, yymsp[-4].minor.yy194);
139770  }
139771          break;
139772        case 142: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
139773  {
139774    sqlite3WithPush(pParse, yymsp[-6].minor.yy285, 1);
139775    sqlite3Insert(pParse, yymsp[-3].minor.yy185, 0, yymsp[-2].minor.yy254, yymsp[-5].minor.yy194);
139776  }
139777          break;
139778        case 146: /* idlist_opt ::= LP idlist RP */
139779  {yymsp[-2].minor.yy254 = yymsp[-1].minor.yy254;}
139780          break;
139781        case 147: /* idlist ::= idlist COMMA nm */
139782  {yymsp[-2].minor.yy254 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy254,&yymsp[0].minor.yy0);}
139783          break;
139784        case 148: /* idlist ::= nm */
139785  {yymsp[0].minor.yy254 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
139786          break;
139787        case 149: /* expr ::= LP expr RP */
139788  {spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/  yymsp[-2].minor.yy190.pExpr = yymsp[-1].minor.yy190.pExpr;}
139789          break;
139790        case 150: /* expr ::= ID|INDEXED */
139791        case 151: /* expr ::= JOIN_KW */ yytestcase(yyruleno==151);
139792  {spanExpr(&yymsp[0].minor.yy190,pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
139793          break;
139794        case 152: /* expr ::= nm DOT nm */
139795  {
139796    Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
139797    Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
139798    spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
139799    yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
139800  }
139801          break;
139802        case 153: /* expr ::= nm DOT nm DOT nm */
139803  {
139804    Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1);
139805    Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
139806    Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
139807    Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
139808    spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
139809    yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
139810  }
139811          break;
139812        case 154: /* term ::= NULL|FLOAT|BLOB */
139813        case 155: /* term ::= STRING */ yytestcase(yyruleno==155);
139814  {spanExpr(&yymsp[0].minor.yy190,pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}
139815          break;
139816        case 156: /* term ::= INTEGER */
139817  {
139818    yylhsminor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
139819    yylhsminor.yy190.zStart = yymsp[0].minor.yy0.z;
139820    yylhsminor.yy190.zEnd = yymsp[0].minor.yy0.z + yymsp[0].minor.yy0.n;
139821  }
139822    yymsp[0].minor.yy190 = yylhsminor.yy190;
139823          break;
139824        case 157: /* expr ::= VARIABLE */
139825  {
139826    if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
139827      u32 n = yymsp[0].minor.yy0.n;
139828      spanExpr(&yymsp[0].minor.yy190, pParse, TK_VARIABLE, yymsp[0].minor.yy0);
139829      sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy190.pExpr, n);
139830    }else{
139831      /* When doing a nested parse, one can include terms in an expression
139832      ** that look like this:   #1 #2 ...  These terms refer to registers
139833      ** in the virtual machine.  #N is the N-th register. */
139834      Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
139835      assert( t.n>=2 );
139836      spanSet(&yymsp[0].minor.yy190, &t, &t);
139837      if( pParse->nested==0 ){
139838        sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
139839        yymsp[0].minor.yy190.pExpr = 0;
139840      }else{
139841        yymsp[0].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
139842        if( yymsp[0].minor.yy190.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy190.pExpr->iTable);
139843      }
139844    }
139845  }
139846          break;
139847        case 158: /* expr ::= expr COLLATE ID|STRING */
139848  {
139849    yymsp[-2].minor.yy190.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy190.pExpr, &yymsp[0].minor.yy0, 1);
139850    yymsp[-2].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
139851  }
139852          break;
139853        case 159: /* expr ::= CAST LP expr AS typetoken RP */
139854  {
139855    spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
139856    yymsp[-5].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
139857    sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, 0);
139858  }
139859          break;
139860        case 160: /* expr ::= ID|INDEXED LP distinct exprlist RP */
139861  {
139862    if( yymsp[-1].minor.yy148 && yymsp[-1].minor.yy148->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
139863      sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
139864    }
139865    yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy148, &yymsp[-4].minor.yy0);
139866    spanSet(&yylhsminor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
139867    if( yymsp[-2].minor.yy194==SF_Distinct && yylhsminor.yy190.pExpr ){
139868      yylhsminor.yy190.pExpr->flags |= EP_Distinct;
139869    }
139870  }
139871    yymsp[-4].minor.yy190 = yylhsminor.yy190;
139872          break;
139873        case 161: /* expr ::= ID|INDEXED LP STAR RP */
139874  {
139875    yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
139876    spanSet(&yylhsminor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
139877  }
139878    yymsp[-3].minor.yy190 = yylhsminor.yy190;
139879          break;
139880        case 162: /* term ::= CTIME_KW */
139881  {
139882    yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
139883    spanSet(&yylhsminor.yy190, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
139884  }
139885    yymsp[0].minor.yy190 = yylhsminor.yy190;
139886          break;
139887        case 163: /* expr ::= LP nexprlist COMMA expr RP */
139888  {
139889    ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy148, yymsp[-1].minor.yy190.pExpr);
139890    yylhsminor.yy190.pExpr = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
139891    if( yylhsminor.yy190.pExpr ){
139892      yylhsminor.yy190.pExpr->x.pList = pList;
139893      spanSet(&yylhsminor.yy190, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
139894    }else{
139895      sqlite3ExprListDelete(pParse->db, pList);
139896    }
139897  }
139898    yymsp[-4].minor.yy190 = yylhsminor.yy190;
139899          break;
139900        case 164: /* expr ::= expr AND expr */
139901        case 165: /* expr ::= expr OR expr */ yytestcase(yyruleno==165);
139902        case 166: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==166);
139903        case 167: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==167);
139904        case 168: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==168);
139905        case 169: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==169);
139906        case 170: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==170);
139907        case 171: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==171);
139908  {spanBinaryExpr(pParse,yymsp[-1].major,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);}
139909          break;
139910        case 172: /* likeop ::= NOT LIKE_KW|MATCH */
139911  {yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
139912          break;
139913        case 173: /* expr ::= expr likeop expr */
139914  {
139915    ExprList *pList;
139916    int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
139917    yymsp[-1].minor.yy0.n &= 0x7fffffff;
139918    pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy190.pExpr);
139919    pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy190.pExpr);
139920    yymsp[-2].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0);
139921    exprNot(pParse, bNot, &yymsp[-2].minor.yy190);
139922    yymsp[-2].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
139923    if( yymsp[-2].minor.yy190.pExpr ) yymsp[-2].minor.yy190.pExpr->flags |= EP_InfixFunc;
139924  }
139925          break;
139926        case 174: /* expr ::= expr likeop expr ESCAPE expr */
139927  {
139928    ExprList *pList;
139929    int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
139930    yymsp[-3].minor.yy0.n &= 0x7fffffff;
139931    pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
139932    pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy190.pExpr);
139933    pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
139934    yymsp[-4].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0);
139935    exprNot(pParse, bNot, &yymsp[-4].minor.yy190);
139936    yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
139937    if( yymsp[-4].minor.yy190.pExpr ) yymsp[-4].minor.yy190.pExpr->flags |= EP_InfixFunc;
139938  }
139939          break;
139940        case 175: /* expr ::= expr ISNULL|NOTNULL */
139941  {spanUnaryPostfix(pParse,yymsp[0].major,&yymsp[-1].minor.yy190,&yymsp[0].minor.yy0);}
139942          break;
139943        case 176: /* expr ::= expr NOT NULL */
139944  {spanUnaryPostfix(pParse,TK_NOTNULL,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy0);}
139945          break;
139946        case 177: /* expr ::= expr IS expr */
139947  {
139948    spanBinaryExpr(pParse,TK_IS,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);
139949    binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-2].minor.yy190.pExpr, TK_ISNULL);
139950  }
139951          break;
139952        case 178: /* expr ::= expr IS NOT expr */
139953  {
139954    spanBinaryExpr(pParse,TK_ISNOT,&yymsp[-3].minor.yy190,&yymsp[0].minor.yy190);
139955    binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, TK_NOTNULL);
139956  }
139957          break;
139958        case 179: /* expr ::= NOT expr */
139959        case 180: /* expr ::= BITNOT expr */ yytestcase(yyruleno==180);
139960  {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,yymsp[-1].major,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
139961          break;
139962        case 181: /* expr ::= MINUS expr */
139963  {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UMINUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
139964          break;
139965        case 182: /* expr ::= PLUS expr */
139966  {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UPLUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
139967          break;
139968        case 183: /* between_op ::= BETWEEN */
139969        case 186: /* in_op ::= IN */ yytestcase(yyruleno==186);
139970  {yymsp[0].minor.yy194 = 0;}
139971          break;
139972        case 185: /* expr ::= expr between_op expr AND expr */
139973  {
139974    ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
139975    pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
139976    yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy190.pExpr, 0);
139977    if( yymsp[-4].minor.yy190.pExpr ){
139978      yymsp[-4].minor.yy190.pExpr->x.pList = pList;
139979    }else{
139980      sqlite3ExprListDelete(pParse->db, pList);
139981    } 
139982    exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
139983    yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
139984  }
139985          break;
139986        case 188: /* expr ::= expr in_op LP exprlist RP */
139987  {
139988      if( yymsp[-1].minor.yy148==0 ){
139989        /* Expressions of the form
139990        **
139991        **      expr1 IN ()
139992        **      expr1 NOT IN ()
139993        **
139994        ** simplify to constants 0 (false) and 1 (true), respectively,
139995        ** regardless of the value of expr1.
139996        */
139997        sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy190.pExpr);
139998        yymsp[-4].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[yymsp[-3].minor.yy194],1);
139999      }else if( yymsp[-1].minor.yy148->nExpr==1 ){
140000        /* Expressions of the form:
140001        **
140002        **      expr1 IN (?1)
140003        **      expr1 NOT IN (?2)
140004        **
140005        ** with exactly one value on the RHS can be simplified to something
140006        ** like this:
140007        **
140008        **      expr1 == ?1
140009        **      expr1 <> ?2
140010        **
140011        ** But, the RHS of the == or <> is marked with the EP_Generic flag
140012        ** so that it may not contribute to the computation of comparison
140013        ** affinity or the collating sequence to use for comparison.  Otherwise,
140014        ** the semantics would be subtly different from IN or NOT IN.
140015        */
140016        Expr *pRHS = yymsp[-1].minor.yy148->a[0].pExpr;
140017        yymsp[-1].minor.yy148->a[0].pExpr = 0;
140018        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
140019        /* pRHS cannot be NULL because a malloc error would have been detected
140020        ** before now and control would have never reached this point */
140021        if( ALWAYS(pRHS) ){
140022          pRHS->flags &= ~EP_Collate;
140023          pRHS->flags |= EP_Generic;
140024        }
140025        yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy194 ? TK_NE : TK_EQ, yymsp[-4].minor.yy190.pExpr, pRHS);
140026      }else{
140027        yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0);
140028        if( yymsp[-4].minor.yy190.pExpr ){
140029          yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy148;
140030          sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
140031        }else{
140032          sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
140033        }
140034        exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
140035      }
140036      yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
140037    }
140038          break;
140039        case 189: /* expr ::= LP select RP */
140040  {
140041      spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
140042      yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
140043      sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy190.pExpr, yymsp[-1].minor.yy243);
140044    }
140045          break;
140046        case 190: /* expr ::= expr in_op LP select RP */
140047  {
140048      yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0);
140049      sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, yymsp[-1].minor.yy243);
140050      exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
140051      yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
140052    }
140053          break;
140054        case 191: /* expr ::= expr in_op nm dbnm paren_exprlist */
140055  {
140056      SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
140057      Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
140058      if( yymsp[0].minor.yy148 )  sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy148);
140059      yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0);
140060      sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, pSelect);
140061      exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
140062      yymsp[-4].minor.yy190.zEnd = yymsp[-1].minor.yy0.z ? &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n] : &yymsp[-2].minor.yy0.z[yymsp[-2].minor.yy0.n];
140063    }
140064          break;
140065        case 192: /* expr ::= EXISTS LP select RP */
140066  {
140067      Expr *p;
140068      spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
140069      p = yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
140070      sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy243);
140071    }
140072          break;
140073        case 193: /* expr ::= CASE case_operand case_exprlist case_else END */
140074  {
140075    spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);  /*A-overwrites-C*/
140076    yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy72, 0);
140077    if( yymsp[-4].minor.yy190.pExpr ){
140078      yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy72 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[-1].minor.yy72) : yymsp[-2].minor.yy148;
140079      sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
140080    }else{
140081      sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy148);
140082      sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy72);
140083    }
140084  }
140085          break;
140086        case 194: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
140087  {
140088    yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[-2].minor.yy190.pExpr);
140089    yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
140090  }
140091          break;
140092        case 195: /* case_exprlist ::= WHEN expr THEN expr */
140093  {
140094    yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
140095    yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, yymsp[0].minor.yy190.pExpr);
140096  }
140097          break;
140098        case 198: /* case_operand ::= expr */
140099  {yymsp[0].minor.yy72 = yymsp[0].minor.yy190.pExpr; /*A-overwrites-X*/}
140100          break;
140101        case 201: /* nexprlist ::= nexprlist COMMA expr */
140102  {yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[0].minor.yy190.pExpr);}
140103          break;
140104        case 202: /* nexprlist ::= expr */
140105  {yymsp[0].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy190.pExpr); /*A-overwrites-Y*/}
140106          break;
140107        case 204: /* paren_exprlist ::= LP exprlist RP */
140108        case 209: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==209);
140109  {yymsp[-2].minor.yy148 = yymsp[-1].minor.yy148;}
140110          break;
140111        case 205: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
140112  {
140113    sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, 
140114                       sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy148, yymsp[-10].minor.yy194,
140115                        &yymsp[-11].minor.yy0, yymsp[0].minor.yy72, SQLITE_SO_ASC, yymsp[-8].minor.yy194, SQLITE_IDXTYPE_APPDEF);
140116  }
140117          break;
140118        case 206: /* uniqueflag ::= UNIQUE */
140119        case 246: /* raisetype ::= ABORT */ yytestcase(yyruleno==246);
140120  {yymsp[0].minor.yy194 = OE_Abort;}
140121          break;
140122        case 207: /* uniqueflag ::= */
140123  {yymsp[1].minor.yy194 = OE_None;}
140124          break;
140125        case 210: /* eidlist ::= eidlist COMMA nm collate sortorder */
140126  {
140127    yymsp[-4].minor.yy148 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194);
140128  }
140129          break;
140130        case 211: /* eidlist ::= nm collate sortorder */
140131  {
140132    yymsp[-2].minor.yy148 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); /*A-overwrites-Y*/
140133  }
140134          break;
140135        case 214: /* cmd ::= DROP INDEX ifexists fullname */
140136  {sqlite3DropIndex(pParse, yymsp[0].minor.yy185, yymsp[-1].minor.yy194);}
140137          break;
140138        case 215: /* cmd ::= VACUUM */
140139  {sqlite3Vacuum(pParse,0);}
140140          break;
140141        case 216: /* cmd ::= VACUUM nm */
140142  {sqlite3Vacuum(pParse,&yymsp[0].minor.yy0);}
140143          break;
140144        case 217: /* cmd ::= PRAGMA nm dbnm */
140145  {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
140146          break;
140147        case 218: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
140148  {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
140149          break;
140150        case 219: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
140151  {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
140152          break;
140153        case 220: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
140154  {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
140155          break;
140156        case 221: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
140157  {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
140158          break;
140159        case 224: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
140160  {
140161    Token all;
140162    all.z = yymsp[-3].minor.yy0.z;
140163    all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
140164    sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy145, &all);
140165  }
140166          break;
140167        case 225: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
140168  {
140169    sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy194, yymsp[-4].minor.yy332.a, yymsp[-4].minor.yy332.b, yymsp[-2].minor.yy185, yymsp[0].minor.yy72, yymsp[-10].minor.yy194, yymsp[-8].minor.yy194);
140170    yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
140171  }
140172          break;
140173        case 226: /* trigger_time ::= BEFORE|AFTER */
140174  { yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-X*/ }
140175          break;
140176        case 227: /* trigger_time ::= INSTEAD OF */
140177  { yymsp[-1].minor.yy194 = TK_INSTEAD;}
140178          break;
140179        case 228: /* trigger_time ::= */
140180  { yymsp[1].minor.yy194 = TK_BEFORE; }
140181          break;
140182        case 229: /* trigger_event ::= DELETE|INSERT */
140183        case 230: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==230);
140184  {yymsp[0].minor.yy332.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy332.b = 0;}
140185          break;
140186        case 231: /* trigger_event ::= UPDATE OF idlist */
140187  {yymsp[-2].minor.yy332.a = TK_UPDATE; yymsp[-2].minor.yy332.b = yymsp[0].minor.yy254;}
140188          break;
140189        case 232: /* when_clause ::= */
140190        case 251: /* key_opt ::= */ yytestcase(yyruleno==251);
140191  { yymsp[1].minor.yy72 = 0; }
140192          break;
140193        case 233: /* when_clause ::= WHEN expr */
140194        case 252: /* key_opt ::= KEY expr */ yytestcase(yyruleno==252);
140195  { yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr; }
140196          break;
140197        case 234: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
140198  {
140199    assert( yymsp[-2].minor.yy145!=0 );
140200    yymsp[-2].minor.yy145->pLast->pNext = yymsp[-1].minor.yy145;
140201    yymsp[-2].minor.yy145->pLast = yymsp[-1].minor.yy145;
140202  }
140203          break;
140204        case 235: /* trigger_cmd_list ::= trigger_cmd SEMI */
140205  { 
140206    assert( yymsp[-1].minor.yy145!=0 );
140207    yymsp[-1].minor.yy145->pLast = yymsp[-1].minor.yy145;
140208  }
140209          break;
140210        case 236: /* trnm ::= nm DOT nm */
140211  {
140212    yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
140213    sqlite3ErrorMsg(pParse, 
140214          "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
140215          "statements within triggers");
140216  }
140217          break;
140218        case 237: /* tridxby ::= INDEXED BY nm */
140219  {
140220    sqlite3ErrorMsg(pParse,
140221          "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
140222          "within triggers");
140223  }
140224          break;
140225        case 238: /* tridxby ::= NOT INDEXED */
140226  {
140227    sqlite3ErrorMsg(pParse,
140228          "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
140229          "within triggers");
140230  }
140231          break;
140232        case 239: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
140233  {yymsp[-6].minor.yy145 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy148, yymsp[0].minor.yy72, yymsp[-5].minor.yy194);}
140234          break;
140235        case 240: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */
140236  {yymsp[-4].minor.yy145 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy254, yymsp[0].minor.yy243, yymsp[-4].minor.yy194);/*A-overwrites-R*/}
140237          break;
140238        case 241: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
140239  {yymsp[-4].minor.yy145 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy72);}
140240          break;
140241        case 242: /* trigger_cmd ::= select */
140242  {yymsp[0].minor.yy145 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy243); /*A-overwrites-X*/}
140243          break;
140244        case 243: /* expr ::= RAISE LP IGNORE RP */
140245  {
140246    spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);  /*A-overwrites-X*/
140247    yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0); 
140248    if( yymsp[-3].minor.yy190.pExpr ){
140249      yymsp[-3].minor.yy190.pExpr->affinity = OE_Ignore;
140250    }
140251  }
140252          break;
140253        case 244: /* expr ::= RAISE LP raisetype COMMA nm RP */
140254  {
140255    spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);  /*A-overwrites-X*/
140256    yymsp[-5].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1); 
140257    if( yymsp[-5].minor.yy190.pExpr ) {
140258      yymsp[-5].minor.yy190.pExpr->affinity = (char)yymsp[-3].minor.yy194;
140259    }
140260  }
140261          break;
140262        case 245: /* raisetype ::= ROLLBACK */
140263  {yymsp[0].minor.yy194 = OE_Rollback;}
140264          break;
140265        case 247: /* raisetype ::= FAIL */
140266  {yymsp[0].minor.yy194 = OE_Fail;}
140267          break;
140268        case 248: /* cmd ::= DROP TRIGGER ifexists fullname */
140269  {
140270    sqlite3DropTrigger(pParse,yymsp[0].minor.yy185,yymsp[-1].minor.yy194);
140271  }
140272          break;
140273        case 249: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
140274  {
140275    sqlite3Attach(pParse, yymsp[-3].minor.yy190.pExpr, yymsp[-1].minor.yy190.pExpr, yymsp[0].minor.yy72);
140276  }
140277          break;
140278        case 250: /* cmd ::= DETACH database_kw_opt expr */
140279  {
140280    sqlite3Detach(pParse, yymsp[0].minor.yy190.pExpr);
140281  }
140282          break;
140283        case 253: /* cmd ::= REINDEX */
140284  {sqlite3Reindex(pParse, 0, 0);}
140285          break;
140286        case 254: /* cmd ::= REINDEX nm dbnm */
140287  {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
140288          break;
140289        case 255: /* cmd ::= ANALYZE */
140290  {sqlite3Analyze(pParse, 0, 0);}
140291          break;
140292        case 256: /* cmd ::= ANALYZE nm dbnm */
140293  {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
140294          break;
140295        case 257: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
140296  {
140297    sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy185,&yymsp[0].minor.yy0);
140298  }
140299          break;
140300        case 258: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
140301  {
140302    yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
140303    sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
140304  }
140305          break;
140306        case 259: /* add_column_fullname ::= fullname */
140307  {
140308    disableLookaside(pParse);
140309    sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy185);
140310  }
140311          break;
140312        case 260: /* cmd ::= create_vtab */
140313  {sqlite3VtabFinishParse(pParse,0);}
140314          break;
140315        case 261: /* cmd ::= create_vtab LP vtabarglist RP */
140316  {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
140317          break;
140318        case 262: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
140319  {
140320      sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy194);
140321  }
140322          break;
140323        case 263: /* vtabarg ::= */
140324  {sqlite3VtabArgInit(pParse);}
140325          break;
140326        case 264: /* vtabargtoken ::= ANY */
140327        case 265: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==265);
140328        case 266: /* lp ::= LP */ yytestcase(yyruleno==266);
140329  {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
140330          break;
140331        case 267: /* with ::= */
140332  {yymsp[1].minor.yy285 = 0;}
140333          break;
140334        case 268: /* with ::= WITH wqlist */
140335  { yymsp[-1].minor.yy285 = yymsp[0].minor.yy285; }
140336          break;
140337        case 269: /* with ::= WITH RECURSIVE wqlist */
140338  { yymsp[-2].minor.yy285 = yymsp[0].minor.yy285; }
140339          break;
140340        case 270: /* wqlist ::= nm eidlist_opt AS LP select RP */
140341  {
140342    yymsp[-5].minor.yy285 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); /*A-overwrites-X*/
140343  }
140344          break;
140345        case 271: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
140346  {
140347    yymsp[-7].minor.yy285 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy285, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243);
140348  }
140349          break;
140350        default:
140351        /* (272) input ::= cmdlist */ yytestcase(yyruleno==272);
140352        /* (273) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==273);
140353        /* (274) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=274);
140354        /* (275) ecmd ::= SEMI */ yytestcase(yyruleno==275);
140355        /* (276) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==276);
140356        /* (277) explain ::= */ yytestcase(yyruleno==277);
140357        /* (278) trans_opt ::= */ yytestcase(yyruleno==278);
140358        /* (279) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==279);
140359        /* (280) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==280);
140360        /* (281) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==281);
140361        /* (282) savepoint_opt ::= */ yytestcase(yyruleno==282);
140362        /* (283) cmd ::= create_table create_table_args */ yytestcase(yyruleno==283);
140363        /* (284) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==284);
140364        /* (285) columnlist ::= columnname carglist */ yytestcase(yyruleno==285);
140365        /* (286) nm ::= ID|INDEXED */ yytestcase(yyruleno==286);
140366        /* (287) nm ::= STRING */ yytestcase(yyruleno==287);
140367        /* (288) nm ::= JOIN_KW */ yytestcase(yyruleno==288);
140368        /* (289) typetoken ::= typename */ yytestcase(yyruleno==289);
140369        /* (290) typename ::= ID|STRING */ yytestcase(yyruleno==290);
140370        /* (291) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=291);
140371        /* (292) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=292);
140372        /* (293) carglist ::= carglist ccons */ yytestcase(yyruleno==293);
140373        /* (294) carglist ::= */ yytestcase(yyruleno==294);
140374        /* (295) ccons ::= NULL onconf */ yytestcase(yyruleno==295);
140375        /* (296) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==296);
140376        /* (297) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==297);
140377        /* (298) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=298);
140378        /* (299) tconscomma ::= */ yytestcase(yyruleno==299);
140379        /* (300) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=300);
140380        /* (301) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=301);
140381        /* (302) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=302);
140382        /* (303) oneselect ::= values */ yytestcase(yyruleno==303);
140383        /* (304) sclp ::= selcollist COMMA */ yytestcase(yyruleno==304);
140384        /* (305) as ::= ID|STRING */ yytestcase(yyruleno==305);
140385        /* (306) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=306);
140386        /* (307) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==307);
140387        /* (308) exprlist ::= nexprlist */ yytestcase(yyruleno==308);
140388        /* (309) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=309);
140389        /* (310) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=310);
140390        /* (311) nmnum ::= ON */ yytestcase(yyruleno==311);
140391        /* (312) nmnum ::= DELETE */ yytestcase(yyruleno==312);
140392        /* (313) nmnum ::= DEFAULT */ yytestcase(yyruleno==313);
140393        /* (314) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==314);
140394        /* (315) foreach_clause ::= */ yytestcase(yyruleno==315);
140395        /* (316) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==316);
140396        /* (317) trnm ::= nm */ yytestcase(yyruleno==317);
140397        /* (318) tridxby ::= */ yytestcase(yyruleno==318);
140398        /* (319) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==319);
140399        /* (320) database_kw_opt ::= */ yytestcase(yyruleno==320);
140400        /* (321) kwcolumn_opt ::= */ yytestcase(yyruleno==321);
140401        /* (322) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==322);
140402        /* (323) vtabarglist ::= vtabarg */ yytestcase(yyruleno==323);
140403        /* (324) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==324);
140404        /* (325) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==325);
140405        /* (326) anylist ::= */ yytestcase(yyruleno==326);
140406        /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
140407        /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
140408          break;
140409  /********** End reduce actions ************************************************/
140410    };
140411    assert( yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
140412    yygoto = yyRuleInfo[yyruleno].lhs;
140413    yysize = yyRuleInfo[yyruleno].nrhs;
140414    yyact = yy_find_reduce_action(yymsp[yysize].stateno,(YYCODETYPE)yygoto);
140415  
140416    /* There are no SHIFTREDUCE actions on nonterminals because the table
140417    ** generator has simplified them to pure REDUCE actions. */
140418    assert( !(yyact>YY_MAX_SHIFT && yyact<=YY_MAX_SHIFTREDUCE) );
140419  
140420    /* It is not possible for a REDUCE to be followed by an error */
140421    assert( yyact!=YY_ERROR_ACTION );
140422  
140423    if( yyact==YY_ACCEPT_ACTION ){
140424      yypParser->yytos += yysize;
140425      yy_accept(yypParser);
140426    }else{
140427      yymsp += yysize+1;
140428      yypParser->yytos = yymsp;
140429      yymsp->stateno = (YYACTIONTYPE)yyact;
140430      yymsp->major = (YYCODETYPE)yygoto;
140431      yyTraceShift(yypParser, yyact);
140432    }
140433  }
140434  
140435  /*
140436  ** The following code executes when the parse fails
140437  */
140438  #ifndef YYNOERRORRECOVERY
140439  static void yy_parse_failed(
140440    yyParser *yypParser           /* The parser */
140441  ){
140442    sqlite3ParserARG_FETCH;
140443  #ifndef NDEBUG
140444    if( yyTraceFILE ){
140445      fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
140446    }
140447  #endif
140448    while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
140449    /* Here code is inserted which will be executed whenever the
140450    ** parser fails */
140451  /************ Begin %parse_failure code ***************************************/
140452  /************ End %parse_failure code *****************************************/
140453    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
140454  }
140455  #endif /* YYNOERRORRECOVERY */
140456  
140457  /*
140458  ** The following code executes when a syntax error first occurs.
140459  */
140460  static void yy_syntax_error(
140461    yyParser *yypParser,           /* The parser */
140462    int yymajor,                   /* The major type of the error token */
140463    sqlite3ParserTOKENTYPE yyminor         /* The minor type of the error token */
140464  ){
140465    sqlite3ParserARG_FETCH;
140466  #define TOKEN yyminor
140467  /************ Begin %syntax_error code ****************************************/
140468  
140469    UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
140470    assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
140471    sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
140472  /************ End %syntax_error code ******************************************/
140473    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
140474  }
140475  
140476  /*
140477  ** The following is executed when the parser accepts
140478  */
140479  static void yy_accept(
140480    yyParser *yypParser           /* The parser */
140481  ){
140482    sqlite3ParserARG_FETCH;
140483  #ifndef NDEBUG
140484    if( yyTraceFILE ){
140485      fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
140486    }
140487  #endif
140488  #ifndef YYNOERRORRECOVERY
140489    yypParser->yyerrcnt = -1;
140490  #endif
140491    assert( yypParser->yytos==yypParser->yystack );
140492    /* Here code is inserted which will be executed whenever the
140493    ** parser accepts */
140494  /*********** Begin %parse_accept code *****************************************/
140495  /*********** End %parse_accept code *******************************************/
140496    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
140497  }
140498  
140499  /* The main parser program.
140500  ** The first argument is a pointer to a structure obtained from
140501  ** "sqlite3ParserAlloc" which describes the current state of the parser.
140502  ** The second argument is the major token number.  The third is
140503  ** the minor token.  The fourth optional argument is whatever the
140504  ** user wants (and specified in the grammar) and is available for
140505  ** use by the action routines.
140506  **
140507  ** Inputs:
140508  ** <ul>
140509  ** <li> A pointer to the parser (an opaque structure.)
140510  ** <li> The major token number.
140511  ** <li> The minor token number.
140512  ** <li> An option argument of a grammar-specified type.
140513  ** </ul>
140514  **
140515  ** Outputs:
140516  ** None.
140517  */
140518  SQLITE_PRIVATE void sqlite3Parser(
140519    void *yyp,                   /* The parser */
140520    int yymajor,                 /* The major token code number */
140521    sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
140522    sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
140523  ){
140524    YYMINORTYPE yyminorunion;
140525    unsigned int yyact;   /* The parser action. */
140526  #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
140527    int yyendofinput;     /* True if we are at the end of input */
140528  #endif
140529  #ifdef YYERRORSYMBOL
140530    int yyerrorhit = 0;   /* True if yymajor has invoked an error */
140531  #endif
140532    yyParser *yypParser;  /* The parser */
140533  
140534    yypParser = (yyParser*)yyp;
140535    assert( yypParser->yytos!=0 );
140536  #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
140537    yyendofinput = (yymajor==0);
140538  #endif
140539    sqlite3ParserARG_STORE;
140540  
140541  #ifndef NDEBUG
140542    if( yyTraceFILE ){
140543      fprintf(yyTraceFILE,"%sInput '%s'\n",yyTracePrompt,yyTokenName[yymajor]);
140544    }
140545  #endif
140546  
140547    do{
140548      yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
140549      if( yyact <= YY_MAX_SHIFTREDUCE ){
140550        yy_shift(yypParser,yyact,yymajor,yyminor);
140551  #ifndef YYNOERRORRECOVERY
140552        yypParser->yyerrcnt--;
140553  #endif
140554        yymajor = YYNOCODE;
140555      }else if( yyact <= YY_MAX_REDUCE ){
140556        yy_reduce(yypParser,yyact-YY_MIN_REDUCE);
140557      }else{
140558        assert( yyact == YY_ERROR_ACTION );
140559        yyminorunion.yy0 = yyminor;
140560  #ifdef YYERRORSYMBOL
140561        int yymx;
140562  #endif
140563  #ifndef NDEBUG
140564        if( yyTraceFILE ){
140565          fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
140566        }
140567  #endif
140568  #ifdef YYERRORSYMBOL
140569        /* A syntax error has occurred.
140570        ** The response to an error depends upon whether or not the
140571        ** grammar defines an error token "ERROR".  
140572        **
140573        ** This is what we do if the grammar does define ERROR:
140574        **
140575        **  * Call the %syntax_error function.
140576        **
140577        **  * Begin popping the stack until we enter a state where
140578        **    it is legal to shift the error symbol, then shift
140579        **    the error symbol.
140580        **
140581        **  * Set the error count to three.
140582        **
140583        **  * Begin accepting and shifting new tokens.  No new error
140584        **    processing will occur until three tokens have been
140585        **    shifted successfully.
140586        **
140587        */
140588        if( yypParser->yyerrcnt<0 ){
140589          yy_syntax_error(yypParser,yymajor,yyminor);
140590        }
140591        yymx = yypParser->yytos->major;
140592        if( yymx==YYERRORSYMBOL || yyerrorhit ){
140593  #ifndef NDEBUG
140594          if( yyTraceFILE ){
140595            fprintf(yyTraceFILE,"%sDiscard input token %s\n",
140596               yyTracePrompt,yyTokenName[yymajor]);
140597          }
140598  #endif
140599          yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
140600          yymajor = YYNOCODE;
140601        }else{
140602          while( yypParser->yytos >= yypParser->yystack
140603              && yymx != YYERRORSYMBOL
140604              && (yyact = yy_find_reduce_action(
140605                          yypParser->yytos->stateno,
140606                          YYERRORSYMBOL)) >= YY_MIN_REDUCE
140607          ){
140608            yy_pop_parser_stack(yypParser);
140609          }
140610          if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
140611            yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
140612            yy_parse_failed(yypParser);
140613  #ifndef YYNOERRORRECOVERY
140614            yypParser->yyerrcnt = -1;
140615  #endif
140616            yymajor = YYNOCODE;
140617          }else if( yymx!=YYERRORSYMBOL ){
140618            yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
140619          }
140620        }
140621        yypParser->yyerrcnt = 3;
140622        yyerrorhit = 1;
140623  #elif defined(YYNOERRORRECOVERY)
140624        /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
140625        ** do any kind of error recovery.  Instead, simply invoke the syntax
140626        ** error routine and continue going as if nothing had happened.
140627        **
140628        ** Applications can set this macro (for example inside %include) if
140629        ** they intend to abandon the parse upon the first syntax error seen.
140630        */
140631        yy_syntax_error(yypParser,yymajor, yyminor);
140632        yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
140633        yymajor = YYNOCODE;
140634        
140635  #else  /* YYERRORSYMBOL is not defined */
140636        /* This is what we do if the grammar does not define ERROR:
140637        **
140638        **  * Report an error message, and throw away the input token.
140639        **
140640        **  * If the input token is $, then fail the parse.
140641        **
140642        ** As before, subsequent error messages are suppressed until
140643        ** three input tokens have been successfully shifted.
140644        */
140645        if( yypParser->yyerrcnt<=0 ){
140646          yy_syntax_error(yypParser,yymajor, yyminor);
140647        }
140648        yypParser->yyerrcnt = 3;
140649        yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
140650        if( yyendofinput ){
140651          yy_parse_failed(yypParser);
140652  #ifndef YYNOERRORRECOVERY
140653          yypParser->yyerrcnt = -1;
140654  #endif
140655        }
140656        yymajor = YYNOCODE;
140657  #endif
140658      }
140659    }while( yymajor!=YYNOCODE && yypParser->yytos>yypParser->yystack );
140660  #ifndef NDEBUG
140661    if( yyTraceFILE ){
140662      yyStackEntry *i;
140663      char cDiv = '[';
140664      fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
140665      for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
140666        fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
140667        cDiv = ' ';
140668      }
140669      fprintf(yyTraceFILE,"]\n");
140670    }
140671  #endif
140672    return;
140673  }
140674  
140675  /************** End of parse.c ***********************************************/
140676  /************** Begin file tokenize.c ****************************************/
140677  /*
140678  ** 2001 September 15
140679  **
140680  ** The author disclaims copyright to this source code.  In place of
140681  ** a legal notice, here is a blessing:
140682  **
140683  **    May you do good and not evil.
140684  **    May you find forgiveness for yourself and forgive others.
140685  **    May you share freely, never taking more than you give.
140686  **
140687  *************************************************************************
140688  ** An tokenizer for SQL
140689  **
140690  ** This file contains C code that splits an SQL input string up into
140691  ** individual tokens and sends those tokens one-by-one over to the
140692  ** parser for analysis.
140693  */
140694  /* #include "sqliteInt.h" */
140695  /* #include <stdlib.h> */
140696  
140697  /* Character classes for tokenizing
140698  **
140699  ** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
140700  ** using a lookup table, whereas a switch() directly on c uses a binary search.
140701  ** The lookup table is much faster.  To maximize speed, and to ensure that
140702  ** a lookup table is used, all of the classes need to be small integers and
140703  ** all of them need to be used within the switch.
140704  */
140705  #define CC_X          0    /* The letter 'x', or start of BLOB literal */
140706  #define CC_KYWD       1    /* Alphabetics or '_'.  Usable in a keyword */
140707  #define CC_ID         2    /* unicode characters usable in IDs */
140708  #define CC_DIGIT      3    /* Digits */
140709  #define CC_DOLLAR     4    /* '$' */
140710  #define CC_VARALPHA   5    /* '@', '#', ':'.  Alphabetic SQL variables */
140711  #define CC_VARNUM     6    /* '?'.  Numeric SQL variables */
140712  #define CC_SPACE      7    /* Space characters */
140713  #define CC_QUOTE      8    /* '"', '\'', or '`'.  String literals, quoted ids */
140714  #define CC_QUOTE2     9    /* '['.   [...] style quoted ids */
140715  #define CC_PIPE      10    /* '|'.   Bitwise OR or concatenate */
140716  #define CC_MINUS     11    /* '-'.  Minus or SQL-style comment */
140717  #define CC_LT        12    /* '<'.  Part of < or <= or <> */
140718  #define CC_GT        13    /* '>'.  Part of > or >= */
140719  #define CC_EQ        14    /* '='.  Part of = or == */
140720  #define CC_BANG      15    /* '!'.  Part of != */
140721  #define CC_SLASH     16    /* '/'.  / or c-style comment */
140722  #define CC_LP        17    /* '(' */
140723  #define CC_RP        18    /* ')' */
140724  #define CC_SEMI      19    /* ';' */
140725  #define CC_PLUS      20    /* '+' */
140726  #define CC_STAR      21    /* '*' */
140727  #define CC_PERCENT   22    /* '%' */
140728  #define CC_COMMA     23    /* ',' */
140729  #define CC_AND       24    /* '&' */
140730  #define CC_TILDA     25    /* '~' */
140731  #define CC_DOT       26    /* '.' */
140732  #define CC_ILLEGAL   27    /* Illegal character */
140733  
140734  static const unsigned char aiClass[] = {
140735  #ifdef SQLITE_ASCII
140736  /*         x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf */
140737  /* 0x */   27, 27, 27, 27, 27, 27, 27, 27, 27,  7,  7, 27,  7,  7, 27, 27,
140738  /* 1x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
140739  /* 2x */    7, 15,  8,  5,  4, 22, 24,  8, 17, 18, 21, 20, 23, 11, 26, 16,
140740  /* 3x */    3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  5, 19, 12, 14, 13,  6,
140741  /* 4x */    5,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
140742  /* 5x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  9, 27, 27, 27,  1,
140743  /* 6x */    8,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
140744  /* 7x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1, 27, 10, 27, 25, 27,
140745  /* 8x */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
140746  /* 9x */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
140747  /* Ax */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
140748  /* Bx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
140749  /* Cx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
140750  /* Dx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
140751  /* Ex */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
140752  /* Fx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2
140753  #endif
140754  #ifdef SQLITE_EBCDIC
140755  /*         x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf */
140756  /* 0x */   27, 27, 27, 27, 27,  7, 27, 27, 27, 27, 27, 27,  7,  7, 27, 27,
140757  /* 1x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
140758  /* 2x */   27, 27, 27, 27, 27,  7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
140759  /* 3x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
140760  /* 4x */    7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 12, 17, 20, 10,
140761  /* 5x */   24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15,  4, 21, 18, 19, 27,
140762  /* 6x */   11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22,  1, 13,  6,
140763  /* 7x */   27, 27, 27, 27, 27, 27, 27, 27, 27,  8,  5,  5,  5,  8, 14,  8,
140764  /* 8x */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
140765  /* 9x */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
140766  /* Ax */   27, 25,  1,  1,  1,  1,  1,  0,  1,  1, 27, 27, 27, 27, 27, 27,
140767  /* Bx */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  9, 27, 27, 27, 27, 27,
140768  /* Cx */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
140769  /* Dx */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
140770  /* Ex */   27, 27,  1,  1,  1,  1,  1,  0,  1,  1, 27, 27, 27, 27, 27, 27,
140771  /* Fx */    3,  3,  3,  3,  3,  3,  3,  3,  3,  3, 27, 27, 27, 27, 27, 27,
140772  #endif
140773  };
140774  
140775  /*
140776  ** The charMap() macro maps alphabetic characters (only) into their
140777  ** lower-case ASCII equivalent.  On ASCII machines, this is just
140778  ** an upper-to-lower case map.  On EBCDIC machines we also need
140779  ** to adjust the encoding.  The mapping is only valid for alphabetics
140780  ** which are the only characters for which this feature is used. 
140781  **
140782  ** Used by keywordhash.h
140783  */
140784  #ifdef SQLITE_ASCII
140785  # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
140786  #endif
140787  #ifdef SQLITE_EBCDIC
140788  # define charMap(X) ebcdicToAscii[(unsigned char)X]
140789  const unsigned char ebcdicToAscii[] = {
140790  /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
140791     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
140792     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
140793     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
140794     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
140795     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
140796     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
140797     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
140798     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
140799     0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
140800     0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
140801     0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
140802     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
140803     0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
140804     0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
140805     0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
140806     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
140807  };
140808  #endif
140809  
140810  /*
140811  ** The sqlite3KeywordCode function looks up an identifier to determine if
140812  ** it is a keyword.  If it is a keyword, the token code of that keyword is 
140813  ** returned.  If the input is not a keyword, TK_ID is returned.
140814  **
140815  ** The implementation of this routine was generated by a program,
140816  ** mkkeywordhash.c, located in the tool subdirectory of the distribution.
140817  ** The output of the mkkeywordhash.c program is written into a file
140818  ** named keywordhash.h and then included into this source file by
140819  ** the #include below.
140820  */
140821  /************** Include keywordhash.h in the middle of tokenize.c ************/
140822  /************** Begin file keywordhash.h *************************************/
140823  /***** This file contains automatically generated code ******
140824  **
140825  ** The code in this file has been automatically generated by
140826  **
140827  **   sqlite/tool/mkkeywordhash.c
140828  **
140829  ** The code in this file implements a function that determines whether
140830  ** or not a given identifier is really an SQL keyword.  The same thing
140831  ** might be implemented more directly using a hand-written hash table.
140832  ** But by using this automatically generated code, the size of the code
140833  ** is substantially reduced.  This is important for embedded applications
140834  ** on platforms with limited memory.
140835  */
140836  /* Hash score: 182 */
140837  /* zKWText[] encodes 834 bytes of keyword text in 554 bytes */
140838  /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
140839  /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
140840  /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
140841  /*   UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE         */
140842  /*   BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH     */
140843  /*   IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN     */
140844  /*   WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT         */
140845  /*   CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL        */
140846  /*   FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING        */
140847  /*   VACUUMVIEWINITIALLY                                                */
140848  static const char zKWText[553] = {
140849    'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
140850    'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
140851    'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
140852    'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
140853    'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
140854    'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
140855    'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
140856    'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
140857    'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
140858    'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
140859    'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
140860    'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
140861    'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
140862    'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
140863    'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
140864    'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
140865    'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
140866    'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
140867    'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
140868    'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
140869    'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
140870    'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
140871    'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
140872    'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
140873    'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
140874    'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
140875    'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
140876    'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
140877    'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
140878    'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
140879    'V','I','E','W','I','N','I','T','I','A','L','L','Y',
140880  };
140881  /* aKWHash[i] is the hash value for the i-th keyword */
140882  static const unsigned char aKWHash[127] = {
140883      76, 105, 117,  74,   0,  45,   0,   0,  82,   0,  77,   0,   0,
140884      42,  12,  78,  15,   0, 116,  85,  54, 112,   0,  19,   0,   0,
140885     121,   0, 119, 115,   0,  22,  93,   0,   9,   0,   0,  70,  71,
140886       0,  69,   6,   0,  48,  90, 102,   0, 118, 101,   0,   0,  44,
140887       0, 103,  24,   0,  17,   0, 122,  53,  23,   0,   5, 110,  25,
140888      96,   0,   0, 124, 106,  60, 123,  57,  28,  55,   0,  91,   0,
140889     100,  26,   0,  99,   0,   0,   0,  95,  92,  97,  88, 109,  14,
140890      39, 108,   0,  81,   0,  18,  89, 111,  32,   0, 120,  80, 113,
140891      62,  46,  84,   0,   0,  94,  40,  59, 114,   0,  36,   0,   0,
140892      29,   0,  86,  63,  64,   0,  20,  61,   0,  56,
140893  };
140894  /* aKWNext[] forms the hash collision chain.  If aKWHash[i]==0
140895  ** then the i-th keyword has no more hash collisions.  Otherwise,
140896  ** the next keyword with the same hash is aKWHash[i]-1. */
140897  static const unsigned char aKWNext[124] = {
140898       0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
140899       0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
140900       0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
140901       0,   0,   0,   0,  33,   0,  21,   0,   0,   0,   0,   0,  50,
140902       0,  43,   3,  47,   0,   0,   0,   0,  30,   0,  58,   0,  38,
140903       0,   0,   0,   1,  66,   0,   0,  67,   0,  41,   0,   0,   0,
140904       0,   0,   0,  49,  65,   0,   0,   0,   0,  31,  52,  16,  34,
140905      10,   0,   0,   0,   0,   0,   0,   0,  11,  72,  79,   0,   8,
140906       0, 104,  98,   0, 107,   0,  87,   0,  75,  51,   0,  27,  37,
140907      73,  83,   0,  35,  68,   0,   0,
140908  };
140909  /* aKWLen[i] is the length (in bytes) of the i-th keyword */
140910  static const unsigned char aKWLen[124] = {
140911       7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
140912       7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
140913      11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
140914       4,   6,   2,   3,   9,   4,   2,   6,   5,   7,   4,   5,   7,
140915       6,   6,   5,   6,   5,   5,   9,   7,   7,   3,   2,   4,   4,
140916       7,   3,   6,   4,   7,   6,  12,   6,   9,   4,   6,   5,   4,
140917       7,   6,   5,   6,   7,   5,   4,   5,   6,   5,   7,   3,   7,
140918      13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   8,   8,
140919       2,   4,   4,   4,   4,   4,   2,   2,   6,   5,   8,   5,   8,
140920       3,   5,   5,   6,   4,   9,   3,
140921  };
140922  /* aKWOffset[i] is the index into zKWText[] of the start of
140923  ** the text for the i-th keyword. */
140924  static const unsigned short int aKWOffset[124] = {
140925       0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
140926      36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
140927      86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
140928     159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
140929     199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
140930     250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
140931     320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
140932     387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
140933     460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
140934     521, 524, 529, 534, 540, 544, 549,
140935  };
140936  /* aKWCode[i] is the parser symbol code for the i-th keyword */
140937  static const unsigned char aKWCode[124] = {
140938    TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
140939    TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
140940    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
140941    TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
140942    TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
140943    TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
140944    TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
140945    TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
140946    TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
140947    TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_WITHOUT,    TK_WITH,       
140948    TK_JOIN_KW,    TK_RELEASE,    TK_ATTACH,     TK_HAVING,     TK_GROUP,      
140949    TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RECURSIVE,  TK_BETWEEN,    
140950    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       TK_LIKE_KW,    
140951    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       TK_COLLATE,    
140952    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  TK_JOIN,       
140953    TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,     
140954    TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      TK_WHEN,       
140955    TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    TK_AND,        
140956    TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         TK_CAST,       
140957    TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    TK_CTIME_KW,   
140958    TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   TK_IS,         
140959    TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    TK_LIKE_KW,    
140960    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      TK_RESTRICT,   
140961    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        TK_UNION,      TK_USING,      
140962    TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  TK_ALL,        
140963  };
140964  /* Check to see if z[0..n-1] is a keyword. If it is, write the
140965  ** parser symbol code for that keyword into *pType.  Always
140966  ** return the integer n (the length of the token). */
140967  static int keywordCode(const char *z, int n, int *pType){
140968    int i, j;
140969    const char *zKW;
140970    if( n>=2 ){
140971      i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
140972      for(i=((int)aKWHash[i])-1; i>=0; i=((int)aKWNext[i])-1){
140973        if( aKWLen[i]!=n ) continue;
140974        j = 0;
140975        zKW = &zKWText[aKWOffset[i]];
140976  #ifdef SQLITE_ASCII
140977        while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
140978  #endif
140979  #ifdef SQLITE_EBCDIC
140980        while( j<n && toupper(z[j])==zKW[j] ){ j++; }
140981  #endif
140982        if( j<n ) continue;
140983        testcase( i==0 ); /* REINDEX */
140984        testcase( i==1 ); /* INDEXED */
140985        testcase( i==2 ); /* INDEX */
140986        testcase( i==3 ); /* DESC */
140987        testcase( i==4 ); /* ESCAPE */
140988        testcase( i==5 ); /* EACH */
140989        testcase( i==6 ); /* CHECK */
140990        testcase( i==7 ); /* KEY */
140991        testcase( i==8 ); /* BEFORE */
140992        testcase( i==9 ); /* FOREIGN */
140993        testcase( i==10 ); /* FOR */
140994        testcase( i==11 ); /* IGNORE */
140995        testcase( i==12 ); /* REGEXP */
140996        testcase( i==13 ); /* EXPLAIN */
140997        testcase( i==14 ); /* INSTEAD */
140998        testcase( i==15 ); /* ADD */
140999        testcase( i==16 ); /* DATABASE */
141000        testcase( i==17 ); /* AS */
141001        testcase( i==18 ); /* SELECT */
141002        testcase( i==19 ); /* TABLE */
141003        testcase( i==20 ); /* LEFT */
141004        testcase( i==21 ); /* THEN */
141005        testcase( i==22 ); /* END */
141006        testcase( i==23 ); /* DEFERRABLE */
141007        testcase( i==24 ); /* ELSE */
141008        testcase( i==25 ); /* EXCEPT */
141009        testcase( i==26 ); /* TRANSACTION */
141010        testcase( i==27 ); /* ACTION */
141011        testcase( i==28 ); /* ON */
141012        testcase( i==29 ); /* NATURAL */
141013        testcase( i==30 ); /* ALTER */
141014        testcase( i==31 ); /* RAISE */
141015        testcase( i==32 ); /* EXCLUSIVE */
141016        testcase( i==33 ); /* EXISTS */
141017        testcase( i==34 ); /* SAVEPOINT */
141018        testcase( i==35 ); /* INTERSECT */
141019        testcase( i==36 ); /* TRIGGER */
141020        testcase( i==37 ); /* REFERENCES */
141021        testcase( i==38 ); /* CONSTRAINT */
141022        testcase( i==39 ); /* INTO */
141023        testcase( i==40 ); /* OFFSET */
141024        testcase( i==41 ); /* OF */
141025        testcase( i==42 ); /* SET */
141026        testcase( i==43 ); /* TEMPORARY */
141027        testcase( i==44 ); /* TEMP */
141028        testcase( i==45 ); /* OR */
141029        testcase( i==46 ); /* UNIQUE */
141030        testcase( i==47 ); /* QUERY */
141031        testcase( i==48 ); /* WITHOUT */
141032        testcase( i==49 ); /* WITH */
141033        testcase( i==50 ); /* OUTER */
141034        testcase( i==51 ); /* RELEASE */
141035        testcase( i==52 ); /* ATTACH */
141036        testcase( i==53 ); /* HAVING */
141037        testcase( i==54 ); /* GROUP */
141038        testcase( i==55 ); /* UPDATE */
141039        testcase( i==56 ); /* BEGIN */
141040        testcase( i==57 ); /* INNER */
141041        testcase( i==58 ); /* RECURSIVE */
141042        testcase( i==59 ); /* BETWEEN */
141043        testcase( i==60 ); /* NOTNULL */
141044        testcase( i==61 ); /* NOT */
141045        testcase( i==62 ); /* NO */
141046        testcase( i==63 ); /* NULL */
141047        testcase( i==64 ); /* LIKE */
141048        testcase( i==65 ); /* CASCADE */
141049        testcase( i==66 ); /* ASC */
141050        testcase( i==67 ); /* DELETE */
141051        testcase( i==68 ); /* CASE */
141052        testcase( i==69 ); /* COLLATE */
141053        testcase( i==70 ); /* CREATE */
141054        testcase( i==71 ); /* CURRENT_DATE */
141055        testcase( i==72 ); /* DETACH */
141056        testcase( i==73 ); /* IMMEDIATE */
141057        testcase( i==74 ); /* JOIN */
141058        testcase( i==75 ); /* INSERT */
141059        testcase( i==76 ); /* MATCH */
141060        testcase( i==77 ); /* PLAN */
141061        testcase( i==78 ); /* ANALYZE */
141062        testcase( i==79 ); /* PRAGMA */
141063        testcase( i==80 ); /* ABORT */
141064        testcase( i==81 ); /* VALUES */
141065        testcase( i==82 ); /* VIRTUAL */
141066        testcase( i==83 ); /* LIMIT */
141067        testcase( i==84 ); /* WHEN */
141068        testcase( i==85 ); /* WHERE */
141069        testcase( i==86 ); /* RENAME */
141070        testcase( i==87 ); /* AFTER */
141071        testcase( i==88 ); /* REPLACE */
141072        testcase( i==89 ); /* AND */
141073        testcase( i==90 ); /* DEFAULT */
141074        testcase( i==91 ); /* AUTOINCREMENT */
141075        testcase( i==92 ); /* TO */
141076        testcase( i==93 ); /* IN */
141077        testcase( i==94 ); /* CAST */
141078        testcase( i==95 ); /* COLUMN */
141079        testcase( i==96 ); /* COMMIT */
141080        testcase( i==97 ); /* CONFLICT */
141081        testcase( i==98 ); /* CROSS */
141082        testcase( i==99 ); /* CURRENT_TIMESTAMP */
141083        testcase( i==100 ); /* CURRENT_TIME */
141084        testcase( i==101 ); /* PRIMARY */
141085        testcase( i==102 ); /* DEFERRED */
141086        testcase( i==103 ); /* DISTINCT */
141087        testcase( i==104 ); /* IS */
141088        testcase( i==105 ); /* DROP */
141089        testcase( i==106 ); /* FAIL */
141090        testcase( i==107 ); /* FROM */
141091        testcase( i==108 ); /* FULL */
141092        testcase( i==109 ); /* GLOB */
141093        testcase( i==110 ); /* BY */
141094        testcase( i==111 ); /* IF */
141095        testcase( i==112 ); /* ISNULL */
141096        testcase( i==113 ); /* ORDER */
141097        testcase( i==114 ); /* RESTRICT */
141098        testcase( i==115 ); /* RIGHT */
141099        testcase( i==116 ); /* ROLLBACK */
141100        testcase( i==117 ); /* ROW */
141101        testcase( i==118 ); /* UNION */
141102        testcase( i==119 ); /* USING */
141103        testcase( i==120 ); /* VACUUM */
141104        testcase( i==121 ); /* VIEW */
141105        testcase( i==122 ); /* INITIALLY */
141106        testcase( i==123 ); /* ALL */
141107        *pType = aKWCode[i];
141108        break;
141109      }
141110    }
141111    return n;
141112  }
141113  SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
141114    int id = TK_ID;
141115    keywordCode((char*)z, n, &id);
141116    return id;
141117  }
141118  #define SQLITE_N_KEYWORD 124
141119  
141120  /************** End of keywordhash.h *****************************************/
141121  /************** Continuing where we left off in tokenize.c *******************/
141122  
141123  
141124  /*
141125  ** If X is a character that can be used in an identifier then
141126  ** IdChar(X) will be true.  Otherwise it is false.
141127  **
141128  ** For ASCII, any character with the high-order bit set is
141129  ** allowed in an identifier.  For 7-bit characters, 
141130  ** sqlite3IsIdChar[X] must be 1.
141131  **
141132  ** For EBCDIC, the rules are more complex but have the same
141133  ** end result.
141134  **
141135  ** Ticket #1066.  the SQL standard does not allow '$' in the
141136  ** middle of identifiers.  But many SQL implementations do. 
141137  ** SQLite will allow '$' in identifiers for compatibility.
141138  ** But the feature is undocumented.
141139  */
141140  #ifdef SQLITE_ASCII
141141  #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
141142  #endif
141143  #ifdef SQLITE_EBCDIC
141144  SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
141145  /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
141146      0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
141147      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
141148      0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
141149      0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
141150      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
141151      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
141152      1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
141153      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
141154      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
141155      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
141156      0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
141157      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
141158  };
141159  #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
141160  #endif
141161  
141162  /* Make the IdChar function accessible from ctime.c */
141163  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
141164  SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
141165  #endif
141166  
141167  
141168  /*
141169  ** Return the length (in bytes) of the token that begins at z[0]. 
141170  ** Store the token type in *tokenType before returning.
141171  */
141172  SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
141173    int i, c;
141174    switch( aiClass[*z] ){  /* Switch on the character-class of the first byte
141175                            ** of the token. See the comment on the CC_ defines
141176                            ** above. */
141177      case CC_SPACE: {
141178        testcase( z[0]==' ' );
141179        testcase( z[0]=='\t' );
141180        testcase( z[0]=='\n' );
141181        testcase( z[0]=='\f' );
141182        testcase( z[0]=='\r' );
141183        for(i=1; sqlite3Isspace(z[i]); i++){}
141184        *tokenType = TK_SPACE;
141185        return i;
141186      }
141187      case CC_MINUS: {
141188        if( z[1]=='-' ){
141189          for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
141190          *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
141191          return i;
141192        }
141193        *tokenType = TK_MINUS;
141194        return 1;
141195      }
141196      case CC_LP: {
141197        *tokenType = TK_LP;
141198        return 1;
141199      }
141200      case CC_RP: {
141201        *tokenType = TK_RP;
141202        return 1;
141203      }
141204      case CC_SEMI: {
141205        *tokenType = TK_SEMI;
141206        return 1;
141207      }
141208      case CC_PLUS: {
141209        *tokenType = TK_PLUS;
141210        return 1;
141211      }
141212      case CC_STAR: {
141213        *tokenType = TK_STAR;
141214        return 1;
141215      }
141216      case CC_SLASH: {
141217        if( z[1]!='*' || z[2]==0 ){
141218          *tokenType = TK_SLASH;
141219          return 1;
141220        }
141221        for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
141222        if( c ) i++;
141223        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
141224        return i;
141225      }
141226      case CC_PERCENT: {
141227        *tokenType = TK_REM;
141228        return 1;
141229      }
141230      case CC_EQ: {
141231        *tokenType = TK_EQ;
141232        return 1 + (z[1]=='=');
141233      }
141234      case CC_LT: {
141235        if( (c=z[1])=='=' ){
141236          *tokenType = TK_LE;
141237          return 2;
141238        }else if( c=='>' ){
141239          *tokenType = TK_NE;
141240          return 2;
141241        }else if( c=='<' ){
141242          *tokenType = TK_LSHIFT;
141243          return 2;
141244        }else{
141245          *tokenType = TK_LT;
141246          return 1;
141247        }
141248      }
141249      case CC_GT: {
141250        if( (c=z[1])=='=' ){
141251          *tokenType = TK_GE;
141252          return 2;
141253        }else if( c=='>' ){
141254          *tokenType = TK_RSHIFT;
141255          return 2;
141256        }else{
141257          *tokenType = TK_GT;
141258          return 1;
141259        }
141260      }
141261      case CC_BANG: {
141262        if( z[1]!='=' ){
141263          *tokenType = TK_ILLEGAL;
141264          return 1;
141265        }else{
141266          *tokenType = TK_NE;
141267          return 2;
141268        }
141269      }
141270      case CC_PIPE: {
141271        if( z[1]!='|' ){
141272          *tokenType = TK_BITOR;
141273          return 1;
141274        }else{
141275          *tokenType = TK_CONCAT;
141276          return 2;
141277        }
141278      }
141279      case CC_COMMA: {
141280        *tokenType = TK_COMMA;
141281        return 1;
141282      }
141283      case CC_AND: {
141284        *tokenType = TK_BITAND;
141285        return 1;
141286      }
141287      case CC_TILDA: {
141288        *tokenType = TK_BITNOT;
141289        return 1;
141290      }
141291      case CC_QUOTE: {
141292        int delim = z[0];
141293        testcase( delim=='`' );
141294        testcase( delim=='\'' );
141295        testcase( delim=='"' );
141296        for(i=1; (c=z[i])!=0; i++){
141297          if( c==delim ){
141298            if( z[i+1]==delim ){
141299              i++;
141300            }else{
141301              break;
141302            }
141303          }
141304        }
141305        if( c=='\'' ){
141306          *tokenType = TK_STRING;
141307          return i+1;
141308        }else if( c!=0 ){
141309          *tokenType = TK_ID;
141310          return i+1;
141311        }else{
141312          *tokenType = TK_ILLEGAL;
141313          return i;
141314        }
141315      }
141316      case CC_DOT: {
141317  #ifndef SQLITE_OMIT_FLOATING_POINT
141318        if( !sqlite3Isdigit(z[1]) )
141319  #endif
141320        {
141321          *tokenType = TK_DOT;
141322          return 1;
141323        }
141324        /* If the next character is a digit, this is a floating point
141325        ** number that begins with ".".  Fall thru into the next case */
141326      }
141327      case CC_DIGIT: {
141328        testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
141329        testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
141330        testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
141331        testcase( z[0]=='9' );
141332        *tokenType = TK_INTEGER;
141333  #ifndef SQLITE_OMIT_HEX_INTEGER
141334        if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
141335          for(i=3; sqlite3Isxdigit(z[i]); i++){}
141336          return i;
141337        }
141338  #endif
141339        for(i=0; sqlite3Isdigit(z[i]); i++){}
141340  #ifndef SQLITE_OMIT_FLOATING_POINT
141341        if( z[i]=='.' ){
141342          i++;
141343          while( sqlite3Isdigit(z[i]) ){ i++; }
141344          *tokenType = TK_FLOAT;
141345        }
141346        if( (z[i]=='e' || z[i]=='E') &&
141347             ( sqlite3Isdigit(z[i+1]) 
141348              || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
141349             )
141350        ){
141351          i += 2;
141352          while( sqlite3Isdigit(z[i]) ){ i++; }
141353          *tokenType = TK_FLOAT;
141354        }
141355  #endif
141356        while( IdChar(z[i]) ){
141357          *tokenType = TK_ILLEGAL;
141358          i++;
141359        }
141360        return i;
141361      }
141362      case CC_QUOTE2: {
141363        for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
141364        *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
141365        return i;
141366      }
141367      case CC_VARNUM: {
141368        *tokenType = TK_VARIABLE;
141369        for(i=1; sqlite3Isdigit(z[i]); i++){}
141370        return i;
141371      }
141372      case CC_DOLLAR:
141373      case CC_VARALPHA: {
141374        int n = 0;
141375        testcase( z[0]=='$' );  testcase( z[0]=='@' );
141376        testcase( z[0]==':' );  testcase( z[0]=='#' );
141377        *tokenType = TK_VARIABLE;
141378        for(i=1; (c=z[i])!=0; i++){
141379          if( IdChar(c) ){
141380            n++;
141381  #ifndef SQLITE_OMIT_TCL_VARIABLE
141382          }else if( c=='(' && n>0 ){
141383            do{
141384              i++;
141385            }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
141386            if( c==')' ){
141387              i++;
141388            }else{
141389              *tokenType = TK_ILLEGAL;
141390            }
141391            break;
141392          }else if( c==':' && z[i+1]==':' ){
141393            i++;
141394  #endif
141395          }else{
141396            break;
141397          }
141398        }
141399        if( n==0 ) *tokenType = TK_ILLEGAL;
141400        return i;
141401      }
141402      case CC_KYWD: {
141403        for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
141404        if( IdChar(z[i]) ){
141405          /* This token started out using characters that can appear in keywords,
141406          ** but z[i] is a character not allowed within keywords, so this must
141407          ** be an identifier instead */
141408          i++;
141409          break;
141410        }
141411        *tokenType = TK_ID;
141412        return keywordCode((char*)z, i, tokenType);
141413      }
141414      case CC_X: {
141415  #ifndef SQLITE_OMIT_BLOB_LITERAL
141416        testcase( z[0]=='x' ); testcase( z[0]=='X' );
141417        if( z[1]=='\'' ){
141418          *tokenType = TK_BLOB;
141419          for(i=2; sqlite3Isxdigit(z[i]); i++){}
141420          if( z[i]!='\'' || i%2 ){
141421            *tokenType = TK_ILLEGAL;
141422            while( z[i] && z[i]!='\'' ){ i++; }
141423          }
141424          if( z[i] ) i++;
141425          return i;
141426        }
141427  #endif
141428        /* If it is not a BLOB literal, then it must be an ID, since no
141429        ** SQL keywords start with the letter 'x'.  Fall through */
141430      }
141431      case CC_ID: {
141432        i = 1;
141433        break;
141434      }
141435      default: {
141436        *tokenType = TK_ILLEGAL;
141437        return 1;
141438      }
141439    }
141440    while( IdChar(z[i]) ){ i++; }
141441    *tokenType = TK_ID;
141442    return i;
141443  }
141444  
141445  /*
141446  ** Run the parser on the given SQL string.  The parser structure is
141447  ** passed in.  An SQLITE_ status code is returned.  If an error occurs
141448  ** then an and attempt is made to write an error message into 
141449  ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
141450  ** error message.
141451  */
141452  SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
141453    int nErr = 0;                   /* Number of errors encountered */
141454    void *pEngine;                  /* The LEMON-generated LALR(1) parser */
141455    int n = 0;                      /* Length of the next token token */
141456    int tokenType;                  /* type of the next token */
141457    int lastTokenParsed = -1;       /* type of the previous token */
141458    sqlite3 *db = pParse->db;       /* The database connection */
141459    int mxSqlLen;                   /* Max length of an SQL string */
141460  #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
141461    yyParser sEngine;    /* Space to hold the Lemon-generated Parser object */
141462  #endif
141463  
141464    assert( zSql!=0 );
141465    mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
141466    if( db->nVdbeActive==0 ){
141467      db->u1.isInterrupted = 0;
141468    }
141469    pParse->rc = SQLITE_OK;
141470    pParse->zTail = zSql;
141471    assert( pzErrMsg!=0 );
141472    /* sqlite3ParserTrace(stdout, "parser: "); */
141473  #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
141474    pEngine = &sEngine;
141475    sqlite3ParserInit(pEngine);
141476  #else
141477    pEngine = sqlite3ParserAlloc(sqlite3Malloc);
141478    if( pEngine==0 ){
141479      sqlite3OomFault(db);
141480      return SQLITE_NOMEM_BKPT;
141481    }
141482  #endif
141483    assert( pParse->pNewTable==0 );
141484    assert( pParse->pNewTrigger==0 );
141485    assert( pParse->nVar==0 );
141486    assert( pParse->pVList==0 );
141487    while( 1 ){
141488      if( zSql[0]!=0 ){
141489        n = sqlite3GetToken((u8*)zSql, &tokenType);
141490        mxSqlLen -= n;
141491        if( mxSqlLen<0 ){
141492          pParse->rc = SQLITE_TOOBIG;
141493          break;
141494        }
141495      }else{
141496        /* Upon reaching the end of input, call the parser two more times
141497        ** with tokens TK_SEMI and 0, in that order. */
141498        if( lastTokenParsed==TK_SEMI ){
141499          tokenType = 0;
141500        }else if( lastTokenParsed==0 ){
141501          break;
141502        }else{
141503          tokenType = TK_SEMI;
141504        }
141505        zSql -= n;
141506      }
141507      if( tokenType>=TK_SPACE ){
141508        assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
141509        if( db->u1.isInterrupted ){
141510          pParse->rc = SQLITE_INTERRUPT;
141511          break;
141512        }
141513        if( tokenType==TK_ILLEGAL ){
141514          sqlite3ErrorMsg(pParse, "unrecognized token: \"%.*s\"", n, zSql);
141515          break;
141516        }
141517        zSql += n;
141518      }else{
141519        pParse->sLastToken.z = zSql;
141520        pParse->sLastToken.n = n;
141521        sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
141522        lastTokenParsed = tokenType;
141523        zSql += n;
141524        if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
141525      }
141526    }
141527    assert( nErr==0 );
141528    pParse->zTail = zSql;
141529  #ifdef YYTRACKMAXSTACKDEPTH
141530    sqlite3_mutex_enter(sqlite3MallocMutex());
141531    sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
141532        sqlite3ParserStackPeak(pEngine)
141533    );
141534    sqlite3_mutex_leave(sqlite3MallocMutex());
141535  #endif /* YYDEBUG */
141536  #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
141537    sqlite3ParserFinalize(pEngine);
141538  #else
141539    sqlite3ParserFree(pEngine, sqlite3_free);
141540  #endif
141541    if( db->mallocFailed ){
141542      pParse->rc = SQLITE_NOMEM_BKPT;
141543    }
141544    if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
141545      pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
141546    }
141547    assert( pzErrMsg!=0 );
141548    if( pParse->zErrMsg ){
141549      *pzErrMsg = pParse->zErrMsg;
141550      sqlite3_log(pParse->rc, "%s", *pzErrMsg);
141551      pParse->zErrMsg = 0;
141552      nErr++;
141553    }
141554    if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
141555      sqlite3VdbeDelete(pParse->pVdbe);
141556      pParse->pVdbe = 0;
141557    }
141558  #ifndef SQLITE_OMIT_SHARED_CACHE
141559    if( pParse->nested==0 ){
141560      sqlite3DbFree(db, pParse->aTableLock);
141561      pParse->aTableLock = 0;
141562      pParse->nTableLock = 0;
141563    }
141564  #endif
141565  #ifndef SQLITE_OMIT_VIRTUALTABLE
141566    sqlite3_free(pParse->apVtabLock);
141567  #endif
141568  
141569    if( !IN_DECLARE_VTAB ){
141570      /* If the pParse->declareVtab flag is set, do not delete any table 
141571      ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
141572      ** will take responsibility for freeing the Table structure.
141573      */
141574      sqlite3DeleteTable(db, pParse->pNewTable);
141575    }
141576  
141577    if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
141578    sqlite3DeleteTrigger(db, pParse->pNewTrigger);
141579    sqlite3DbFree(db, pParse->pVList);
141580    while( pParse->pAinc ){
141581      AutoincInfo *p = pParse->pAinc;
141582      pParse->pAinc = p->pNext;
141583      sqlite3DbFreeNN(db, p);
141584    }
141585    while( pParse->pZombieTab ){
141586      Table *p = pParse->pZombieTab;
141587      pParse->pZombieTab = p->pNextZombie;
141588      sqlite3DeleteTable(db, p);
141589    }
141590    assert( nErr==0 || pParse->rc!=SQLITE_OK );
141591    return nErr;
141592  }
141593  
141594  /************** End of tokenize.c ********************************************/
141595  /************** Begin file complete.c ****************************************/
141596  /*
141597  ** 2001 September 15
141598  **
141599  ** The author disclaims copyright to this source code.  In place of
141600  ** a legal notice, here is a blessing:
141601  **
141602  **    May you do good and not evil.
141603  **    May you find forgiveness for yourself and forgive others.
141604  **    May you share freely, never taking more than you give.
141605  **
141606  *************************************************************************
141607  ** An tokenizer for SQL
141608  **
141609  ** This file contains C code that implements the sqlite3_complete() API.
141610  ** This code used to be part of the tokenizer.c source file.  But by
141611  ** separating it out, the code will be automatically omitted from
141612  ** static links that do not use it.
141613  */
141614  /* #include "sqliteInt.h" */
141615  #ifndef SQLITE_OMIT_COMPLETE
141616  
141617  /*
141618  ** This is defined in tokenize.c.  We just have to import the definition.
141619  */
141620  #ifndef SQLITE_AMALGAMATION
141621  #ifdef SQLITE_ASCII
141622  #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
141623  #endif
141624  #ifdef SQLITE_EBCDIC
141625  SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
141626  #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
141627  #endif
141628  #endif /* SQLITE_AMALGAMATION */
141629  
141630  
141631  /*
141632  ** Token types used by the sqlite3_complete() routine.  See the header
141633  ** comments on that procedure for additional information.
141634  */
141635  #define tkSEMI    0
141636  #define tkWS      1
141637  #define tkOTHER   2
141638  #ifndef SQLITE_OMIT_TRIGGER
141639  #define tkEXPLAIN 3
141640  #define tkCREATE  4
141641  #define tkTEMP    5
141642  #define tkTRIGGER 6
141643  #define tkEND     7
141644  #endif
141645  
141646  /*
141647  ** Return TRUE if the given SQL string ends in a semicolon.
141648  **
141649  ** Special handling is require for CREATE TRIGGER statements.
141650  ** Whenever the CREATE TRIGGER keywords are seen, the statement
141651  ** must end with ";END;".
141652  **
141653  ** This implementation uses a state machine with 8 states:
141654  **
141655  **   (0) INVALID   We have not yet seen a non-whitespace character.
141656  **
141657  **   (1) START     At the beginning or end of an SQL statement.  This routine
141658  **                 returns 1 if it ends in the START state and 0 if it ends
141659  **                 in any other state.
141660  **
141661  **   (2) NORMAL    We are in the middle of statement which ends with a single
141662  **                 semicolon.
141663  **
141664  **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
141665  **                 a statement.
141666  **
141667  **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
141668  **                 statement, possibly preceded by EXPLAIN and/or followed by
141669  **                 TEMP or TEMPORARY
141670  **
141671  **   (5) TRIGGER   We are in the middle of a trigger definition that must be
141672  **                 ended by a semicolon, the keyword END, and another semicolon.
141673  **
141674  **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
141675  **                 the end of a trigger definition.
141676  **
141677  **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
141678  **                 of a trigger definition.
141679  **
141680  ** Transitions between states above are determined by tokens extracted
141681  ** from the input.  The following tokens are significant:
141682  **
141683  **   (0) tkSEMI      A semicolon.
141684  **   (1) tkWS        Whitespace.
141685  **   (2) tkOTHER     Any other SQL token.
141686  **   (3) tkEXPLAIN   The "explain" keyword.
141687  **   (4) tkCREATE    The "create" keyword.
141688  **   (5) tkTEMP      The "temp" or "temporary" keyword.
141689  **   (6) tkTRIGGER   The "trigger" keyword.
141690  **   (7) tkEND       The "end" keyword.
141691  **
141692  ** Whitespace never causes a state transition and is always ignored.
141693  ** This means that a SQL string of all whitespace is invalid.
141694  **
141695  ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
141696  ** to recognize the end of a trigger can be omitted.  All we have to do
141697  ** is look for a semicolon that is not part of an string or comment.
141698  */
141699  SQLITE_API int sqlite3_complete(const char *zSql){
141700    u8 state = 0;   /* Current state, using numbers defined in header comment */
141701    u8 token;       /* Value of the next token */
141702  
141703  #ifndef SQLITE_OMIT_TRIGGER
141704    /* A complex statement machine used to detect the end of a CREATE TRIGGER
141705    ** statement.  This is the normal case.
141706    */
141707    static const u8 trans[8][8] = {
141708                       /* Token:                                                */
141709       /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
141710       /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
141711       /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
141712       /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
141713       /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
141714       /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
141715       /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
141716       /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
141717       /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
141718    };
141719  #else
141720    /* If triggers are not supported by this compile then the statement machine
141721    ** used to detect the end of a statement is much simpler
141722    */
141723    static const u8 trans[3][3] = {
141724                       /* Token:           */
141725       /* State:       **  SEMI  WS  OTHER */
141726       /* 0 INVALID: */ {    1,  0,     2, },
141727       /* 1   START: */ {    1,  1,     2, },
141728       /* 2  NORMAL: */ {    1,  2,     2, },
141729    };
141730  #endif /* SQLITE_OMIT_TRIGGER */
141731  
141732  #ifdef SQLITE_ENABLE_API_ARMOR
141733    if( zSql==0 ){
141734      (void)SQLITE_MISUSE_BKPT;
141735      return 0;
141736    }
141737  #endif
141738  
141739    while( *zSql ){
141740      switch( *zSql ){
141741        case ';': {  /* A semicolon */
141742          token = tkSEMI;
141743          break;
141744        }
141745        case ' ':
141746        case '\r':
141747        case '\t':
141748        case '\n':
141749        case '\f': {  /* White space is ignored */
141750          token = tkWS;
141751          break;
141752        }
141753        case '/': {   /* C-style comments */
141754          if( zSql[1]!='*' ){
141755            token = tkOTHER;
141756            break;
141757          }
141758          zSql += 2;
141759          while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
141760          if( zSql[0]==0 ) return 0;
141761          zSql++;
141762          token = tkWS;
141763          break;
141764        }
141765        case '-': {   /* SQL-style comments from "--" to end of line */
141766          if( zSql[1]!='-' ){
141767            token = tkOTHER;
141768            break;
141769          }
141770          while( *zSql && *zSql!='\n' ){ zSql++; }
141771          if( *zSql==0 ) return state==1;
141772          token = tkWS;
141773          break;
141774        }
141775        case '[': {   /* Microsoft-style identifiers in [...] */
141776          zSql++;
141777          while( *zSql && *zSql!=']' ){ zSql++; }
141778          if( *zSql==0 ) return 0;
141779          token = tkOTHER;
141780          break;
141781        }
141782        case '`':     /* Grave-accent quoted symbols used by MySQL */
141783        case '"':     /* single- and double-quoted strings */
141784        case '\'': {
141785          int c = *zSql;
141786          zSql++;
141787          while( *zSql && *zSql!=c ){ zSql++; }
141788          if( *zSql==0 ) return 0;
141789          token = tkOTHER;
141790          break;
141791        }
141792        default: {
141793  #ifdef SQLITE_EBCDIC
141794          unsigned char c;
141795  #endif
141796          if( IdChar((u8)*zSql) ){
141797            /* Keywords and unquoted identifiers */
141798            int nId;
141799            for(nId=1; IdChar(zSql[nId]); nId++){}
141800  #ifdef SQLITE_OMIT_TRIGGER
141801            token = tkOTHER;
141802  #else
141803            switch( *zSql ){
141804              case 'c': case 'C': {
141805                if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
141806                  token = tkCREATE;
141807                }else{
141808                  token = tkOTHER;
141809                }
141810                break;
141811              }
141812              case 't': case 'T': {
141813                if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
141814                  token = tkTRIGGER;
141815                }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
141816                  token = tkTEMP;
141817                }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
141818                  token = tkTEMP;
141819                }else{
141820                  token = tkOTHER;
141821                }
141822                break;
141823              }
141824              case 'e':  case 'E': {
141825                if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
141826                  token = tkEND;
141827                }else
141828  #ifndef SQLITE_OMIT_EXPLAIN
141829                if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
141830                  token = tkEXPLAIN;
141831                }else
141832  #endif
141833                {
141834                  token = tkOTHER;
141835                }
141836                break;
141837              }
141838              default: {
141839                token = tkOTHER;
141840                break;
141841              }
141842            }
141843  #endif /* SQLITE_OMIT_TRIGGER */
141844            zSql += nId-1;
141845          }else{
141846            /* Operators and special symbols */
141847            token = tkOTHER;
141848          }
141849          break;
141850        }
141851      }
141852      state = trans[state][token];
141853      zSql++;
141854    }
141855    return state==1;
141856  }
141857  
141858  #ifndef SQLITE_OMIT_UTF16
141859  /*
141860  ** This routine is the same as the sqlite3_complete() routine described
141861  ** above, except that the parameter is required to be UTF-16 encoded, not
141862  ** UTF-8.
141863  */
141864  SQLITE_API int sqlite3_complete16(const void *zSql){
141865    sqlite3_value *pVal;
141866    char const *zSql8;
141867    int rc;
141868  
141869  #ifndef SQLITE_OMIT_AUTOINIT
141870    rc = sqlite3_initialize();
141871    if( rc ) return rc;
141872  #endif
141873    pVal = sqlite3ValueNew(0);
141874    sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
141875    zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
141876    if( zSql8 ){
141877      rc = sqlite3_complete(zSql8);
141878    }else{
141879      rc = SQLITE_NOMEM_BKPT;
141880    }
141881    sqlite3ValueFree(pVal);
141882    return rc & 0xff;
141883  }
141884  #endif /* SQLITE_OMIT_UTF16 */
141885  #endif /* SQLITE_OMIT_COMPLETE */
141886  
141887  /************** End of complete.c ********************************************/
141888  /************** Begin file main.c ********************************************/
141889  /*
141890  ** 2001 September 15
141891  **
141892  ** The author disclaims copyright to this source code.  In place of
141893  ** a legal notice, here is a blessing:
141894  **
141895  **    May you do good and not evil.
141896  **    May you find forgiveness for yourself and forgive others.
141897  **    May you share freely, never taking more than you give.
141898  **
141899  *************************************************************************
141900  ** Main file for the SQLite library.  The routines in this file
141901  ** implement the programmer interface to the library.  Routines in
141902  ** other files are for internal use by SQLite and should not be
141903  ** accessed by users of the library.
141904  */
141905  /* #include "sqliteInt.h" */
141906  
141907  #ifdef SQLITE_ENABLE_FTS3
141908  /************** Include fts3.h in the middle of main.c ***********************/
141909  /************** Begin file fts3.h ********************************************/
141910  /*
141911  ** 2006 Oct 10
141912  **
141913  ** The author disclaims copyright to this source code.  In place of
141914  ** a legal notice, here is a blessing:
141915  **
141916  **    May you do good and not evil.
141917  **    May you find forgiveness for yourself and forgive others.
141918  **    May you share freely, never taking more than you give.
141919  **
141920  ******************************************************************************
141921  **
141922  ** This header file is used by programs that want to link against the
141923  ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
141924  */
141925  /* #include "sqlite3.h" */
141926  
141927  #if 0
141928  extern "C" {
141929  #endif  /* __cplusplus */
141930  
141931  SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
141932  
141933  #if 0
141934  }  /* extern "C" */
141935  #endif  /* __cplusplus */
141936  
141937  /************** End of fts3.h ************************************************/
141938  /************** Continuing where we left off in main.c ***********************/
141939  #endif
141940  #ifdef SQLITE_ENABLE_RTREE
141941  /************** Include rtree.h in the middle of main.c **********************/
141942  /************** Begin file rtree.h *******************************************/
141943  /*
141944  ** 2008 May 26
141945  **
141946  ** The author disclaims copyright to this source code.  In place of
141947  ** a legal notice, here is a blessing:
141948  **
141949  **    May you do good and not evil.
141950  **    May you find forgiveness for yourself and forgive others.
141951  **    May you share freely, never taking more than you give.
141952  **
141953  ******************************************************************************
141954  **
141955  ** This header file is used by programs that want to link against the
141956  ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
141957  */
141958  /* #include "sqlite3.h" */
141959  
141960  #if 0
141961  extern "C" {
141962  #endif  /* __cplusplus */
141963  
141964  SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
141965  
141966  #if 0
141967  }  /* extern "C" */
141968  #endif  /* __cplusplus */
141969  
141970  /************** End of rtree.h ***********************************************/
141971  /************** Continuing where we left off in main.c ***********************/
141972  #endif
141973  #ifdef SQLITE_ENABLE_ICU
141974  /************** Include sqliteicu.h in the middle of main.c ******************/
141975  /************** Begin file sqliteicu.h ***************************************/
141976  /*
141977  ** 2008 May 26
141978  **
141979  ** The author disclaims copyright to this source code.  In place of
141980  ** a legal notice, here is a blessing:
141981  **
141982  **    May you do good and not evil.
141983  **    May you find forgiveness for yourself and forgive others.
141984  **    May you share freely, never taking more than you give.
141985  **
141986  ******************************************************************************
141987  **
141988  ** This header file is used by programs that want to link against the
141989  ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
141990  */
141991  /* #include "sqlite3.h" */
141992  
141993  #if 0
141994  extern "C" {
141995  #endif  /* __cplusplus */
141996  
141997  SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
141998  
141999  #if 0
142000  }  /* extern "C" */
142001  #endif  /* __cplusplus */
142002  
142003  
142004  /************** End of sqliteicu.h *******************************************/
142005  /************** Continuing where we left off in main.c ***********************/
142006  #endif
142007  #ifdef SQLITE_ENABLE_JSON1
142008  SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
142009  #endif
142010  #ifdef SQLITE_ENABLE_STMTVTAB
142011  SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3*);
142012  #endif
142013  #ifdef SQLITE_ENABLE_FTS5
142014  SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
142015  #endif
142016  
142017  #ifndef SQLITE_AMALGAMATION
142018  /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
142019  ** contains the text of SQLITE_VERSION macro. 
142020  */
142021  SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
142022  #endif
142023  
142024  /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
142025  ** a pointer to the to the sqlite3_version[] string constant. 
142026  */
142027  SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
142028  
142029  /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
142030  ** pointer to a string constant whose value is the same as the
142031  ** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
142032  ** an edited copy of the amalgamation, then the last four characters of
142033  ** the hash might be different from SQLITE_SOURCE_ID.
142034  */
142035  /* SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } */
142036  
142037  /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
142038  ** returns an integer equal to SQLITE_VERSION_NUMBER.
142039  */
142040  SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
142041  
142042  /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
142043  ** zero if and only if SQLite was compiled with mutexing code omitted due to
142044  ** the SQLITE_THREADSAFE compile-time option being set to 0.
142045  */
142046  SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
142047  
142048  /*
142049  ** When compiling the test fixture or with debugging enabled (on Win32),
142050  ** this variable being set to non-zero will cause OSTRACE macros to emit
142051  ** extra diagnostic information.
142052  */
142053  #ifdef SQLITE_HAVE_OS_TRACE
142054  # ifndef SQLITE_DEBUG_OS_TRACE
142055  #   define SQLITE_DEBUG_OS_TRACE 0
142056  # endif
142057    int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
142058  #endif
142059  
142060  #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
142061  /*
142062  ** If the following function pointer is not NULL and if
142063  ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
142064  ** I/O active are written using this function.  These messages
142065  ** are intended for debugging activity only.
142066  */
142067  SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
142068  #endif
142069  
142070  /*
142071  ** If the following global variable points to a string which is the
142072  ** name of a directory, then that directory will be used to store
142073  ** temporary files.
142074  **
142075  ** See also the "PRAGMA temp_store_directory" SQL command.
142076  */
142077  SQLITE_API char *sqlite3_temp_directory = 0;
142078  
142079  /*
142080  ** If the following global variable points to a string which is the
142081  ** name of a directory, then that directory will be used to store
142082  ** all database files specified with a relative pathname.
142083  **
142084  ** See also the "PRAGMA data_store_directory" SQL command.
142085  */
142086  SQLITE_API char *sqlite3_data_directory = 0;
142087  
142088  /*
142089  ** Initialize SQLite.  
142090  **
142091  ** This routine must be called to initialize the memory allocation,
142092  ** VFS, and mutex subsystems prior to doing any serious work with
142093  ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
142094  ** this routine will be called automatically by key routines such as
142095  ** sqlite3_open().  
142096  **
142097  ** This routine is a no-op except on its very first call for the process,
142098  ** or for the first call after a call to sqlite3_shutdown.
142099  **
142100  ** The first thread to call this routine runs the initialization to
142101  ** completion.  If subsequent threads call this routine before the first
142102  ** thread has finished the initialization process, then the subsequent
142103  ** threads must block until the first thread finishes with the initialization.
142104  **
142105  ** The first thread might call this routine recursively.  Recursive
142106  ** calls to this routine should not block, of course.  Otherwise the
142107  ** initialization process would never complete.
142108  **
142109  ** Let X be the first thread to enter this routine.  Let Y be some other
142110  ** thread.  Then while the initial invocation of this routine by X is
142111  ** incomplete, it is required that:
142112  **
142113  **    *  Calls to this routine from Y must block until the outer-most
142114  **       call by X completes.
142115  **
142116  **    *  Recursive calls to this routine from thread X return immediately
142117  **       without blocking.
142118  */
142119  SQLITE_API int sqlite3_initialize(void){
142120    MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
142121    int rc;                                      /* Result code */
142122  #ifdef SQLITE_EXTRA_INIT
142123    int bRunExtraInit = 0;                       /* Extra initialization needed */
142124  #endif
142125  
142126  #ifdef SQLITE_OMIT_WSD
142127    rc = sqlite3_wsd_init(4096, 24);
142128    if( rc!=SQLITE_OK ){
142129      return rc;
142130    }
142131  #endif
142132  
142133    /* If the following assert() fails on some obscure processor/compiler
142134    ** combination, the work-around is to set the correct pointer
142135    ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
142136    assert( SQLITE_PTRSIZE==sizeof(char*) );
142137  
142138    /* If SQLite is already completely initialized, then this call
142139    ** to sqlite3_initialize() should be a no-op.  But the initialization
142140    ** must be complete.  So isInit must not be set until the very end
142141    ** of this routine.
142142    */
142143    if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
142144  
142145    /* Make sure the mutex subsystem is initialized.  If unable to 
142146    ** initialize the mutex subsystem, return early with the error.
142147    ** If the system is so sick that we are unable to allocate a mutex,
142148    ** there is not much SQLite is going to be able to do.
142149    **
142150    ** The mutex subsystem must take care of serializing its own
142151    ** initialization.
142152    */
142153    rc = sqlite3MutexInit();
142154    if( rc ) return rc;
142155  
142156    /* Initialize the malloc() system and the recursive pInitMutex mutex.
142157    ** This operation is protected by the STATIC_MASTER mutex.  Note that
142158    ** MutexAlloc() is called for a static mutex prior to initializing the
142159    ** malloc subsystem - this implies that the allocation of a static
142160    ** mutex must not require support from the malloc subsystem.
142161    */
142162    MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
142163    sqlite3_mutex_enter(pMaster);
142164    sqlite3GlobalConfig.isMutexInit = 1;
142165    if( !sqlite3GlobalConfig.isMallocInit ){
142166      rc = sqlite3MallocInit();
142167    }
142168    if( rc==SQLITE_OK ){
142169      sqlite3GlobalConfig.isMallocInit = 1;
142170      if( !sqlite3GlobalConfig.pInitMutex ){
142171        sqlite3GlobalConfig.pInitMutex =
142172             sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
142173        if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
142174          rc = SQLITE_NOMEM_BKPT;
142175        }
142176      }
142177    }
142178    if( rc==SQLITE_OK ){
142179      sqlite3GlobalConfig.nRefInitMutex++;
142180    }
142181    sqlite3_mutex_leave(pMaster);
142182  
142183    /* If rc is not SQLITE_OK at this point, then either the malloc
142184    ** subsystem could not be initialized or the system failed to allocate
142185    ** the pInitMutex mutex. Return an error in either case.  */
142186    if( rc!=SQLITE_OK ){
142187      return rc;
142188    }
142189  
142190    /* Do the rest of the initialization under the recursive mutex so
142191    ** that we will be able to handle recursive calls into
142192    ** sqlite3_initialize().  The recursive calls normally come through
142193    ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
142194    ** recursive calls might also be possible.
142195    **
142196    ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
142197    ** to the xInit method, so the xInit method need not be threadsafe.
142198    **
142199    ** The following mutex is what serializes access to the appdef pcache xInit
142200    ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
142201    ** call to sqlite3PcacheInitialize().
142202    */
142203    sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
142204    if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
142205      sqlite3GlobalConfig.inProgress = 1;
142206  #ifdef SQLITE_ENABLE_SQLLOG
142207      {
142208        extern void sqlite3_init_sqllog(void);
142209        sqlite3_init_sqllog();
142210      }
142211  #endif
142212      memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
142213      sqlite3RegisterBuiltinFunctions();
142214      if( sqlite3GlobalConfig.isPCacheInit==0 ){
142215        rc = sqlite3PcacheInitialize();
142216      }
142217      if( rc==SQLITE_OK ){
142218        sqlite3GlobalConfig.isPCacheInit = 1;
142219        rc = sqlite3OsInit();
142220      }
142221      if( rc==SQLITE_OK ){
142222        sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
142223            sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
142224        sqlite3GlobalConfig.isInit = 1;
142225  #ifdef SQLITE_EXTRA_INIT
142226        bRunExtraInit = 1;
142227  #endif
142228      }
142229      sqlite3GlobalConfig.inProgress = 0;
142230    }
142231    sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
142232  
142233    /* Go back under the static mutex and clean up the recursive
142234    ** mutex to prevent a resource leak.
142235    */
142236    sqlite3_mutex_enter(pMaster);
142237    sqlite3GlobalConfig.nRefInitMutex--;
142238    if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
142239      assert( sqlite3GlobalConfig.nRefInitMutex==0 );
142240      sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
142241      sqlite3GlobalConfig.pInitMutex = 0;
142242    }
142243    sqlite3_mutex_leave(pMaster);
142244  
142245    /* The following is just a sanity check to make sure SQLite has
142246    ** been compiled correctly.  It is important to run this code, but
142247    ** we don't want to run it too often and soak up CPU cycles for no
142248    ** reason.  So we run it once during initialization.
142249    */
142250  #ifndef NDEBUG
142251  #ifndef SQLITE_OMIT_FLOATING_POINT
142252    /* This section of code's only "output" is via assert() statements. */
142253    if ( rc==SQLITE_OK ){
142254      u64 x = (((u64)1)<<63)-1;
142255      double y;
142256      assert(sizeof(x)==8);
142257      assert(sizeof(x)==sizeof(y));
142258      memcpy(&y, &x, 8);
142259      assert( sqlite3IsNaN(y) );
142260    }
142261  #endif
142262  #endif
142263  
142264    /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
142265    ** compile-time option.
142266    */
142267  #ifdef SQLITE_EXTRA_INIT
142268    if( bRunExtraInit ){
142269      int SQLITE_EXTRA_INIT(const char*);
142270      rc = SQLITE_EXTRA_INIT(0);
142271    }
142272  #endif
142273  
142274    return rc;
142275  }
142276  
142277  /*
142278  ** Undo the effects of sqlite3_initialize().  Must not be called while
142279  ** there are outstanding database connections or memory allocations or
142280  ** while any part of SQLite is otherwise in use in any thread.  This
142281  ** routine is not threadsafe.  But it is safe to invoke this routine
142282  ** on when SQLite is already shut down.  If SQLite is already shut down
142283  ** when this routine is invoked, then this routine is a harmless no-op.
142284  */
142285  SQLITE_API int sqlite3_shutdown(void){
142286  #ifdef SQLITE_OMIT_WSD
142287    int rc = sqlite3_wsd_init(4096, 24);
142288    if( rc!=SQLITE_OK ){
142289      return rc;
142290    }
142291  #endif
142292  
142293    if( sqlite3GlobalConfig.isInit ){
142294  #ifdef SQLITE_EXTRA_SHUTDOWN
142295      void SQLITE_EXTRA_SHUTDOWN(void);
142296      SQLITE_EXTRA_SHUTDOWN();
142297  #endif
142298      sqlite3_os_end();
142299      sqlite3_reset_auto_extension();
142300      sqlite3GlobalConfig.isInit = 0;
142301    }
142302    if( sqlite3GlobalConfig.isPCacheInit ){
142303      sqlite3PcacheShutdown();
142304      sqlite3GlobalConfig.isPCacheInit = 0;
142305    }
142306    if( sqlite3GlobalConfig.isMallocInit ){
142307      sqlite3MallocEnd();
142308      sqlite3GlobalConfig.isMallocInit = 0;
142309  
142310  #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
142311      /* The heap subsystem has now been shutdown and these values are supposed
142312      ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
142313      ** which would rely on that heap subsystem; therefore, make sure these
142314      ** values cannot refer to heap memory that was just invalidated when the
142315      ** heap subsystem was shutdown.  This is only done if the current call to
142316      ** this function resulted in the heap subsystem actually being shutdown.
142317      */
142318      sqlite3_data_directory = 0;
142319      sqlite3_temp_directory = 0;
142320  #endif
142321    }
142322    if( sqlite3GlobalConfig.isMutexInit ){
142323      sqlite3MutexEnd();
142324      sqlite3GlobalConfig.isMutexInit = 0;
142325    }
142326  
142327    return SQLITE_OK;
142328  }
142329  
142330  /*
142331  ** This API allows applications to modify the global configuration of
142332  ** the SQLite library at run-time.
142333  **
142334  ** This routine should only be called when there are no outstanding
142335  ** database connections or memory allocations.  This routine is not
142336  ** threadsafe.  Failure to heed these warnings can lead to unpredictable
142337  ** behavior.
142338  */
142339  SQLITE_API int sqlite3_config(int op, ...){
142340    va_list ap;
142341    int rc = SQLITE_OK;
142342  
142343    /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
142344    ** the SQLite library is in use. */
142345    if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
142346  
142347    va_start(ap, op);
142348    switch( op ){
142349  
142350      /* Mutex configuration options are only available in a threadsafe
142351      ** compile.
142352      */
142353  #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0  /* IMP: R-54466-46756 */
142354      case SQLITE_CONFIG_SINGLETHREAD: {
142355        /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
142356        ** Single-thread. */
142357        sqlite3GlobalConfig.bCoreMutex = 0;  /* Disable mutex on core */
142358        sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
142359        break;
142360      }
142361  #endif
142362  #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
142363      case SQLITE_CONFIG_MULTITHREAD: {
142364        /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
142365        ** Multi-thread. */
142366        sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
142367        sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
142368        break;
142369      }
142370  #endif
142371  #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
142372      case SQLITE_CONFIG_SERIALIZED: {
142373        /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
142374        ** Serialized. */
142375        sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
142376        sqlite3GlobalConfig.bFullMutex = 1;  /* Enable mutex on connections */
142377        break;
142378      }
142379  #endif
142380  #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
142381      case SQLITE_CONFIG_MUTEX: {
142382        /* Specify an alternative mutex implementation */
142383        sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
142384        break;
142385      }
142386  #endif
142387  #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
142388      case SQLITE_CONFIG_GETMUTEX: {
142389        /* Retrieve the current mutex implementation */
142390        *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
142391        break;
142392      }
142393  #endif
142394  
142395      case SQLITE_CONFIG_MALLOC: {
142396        /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
142397        ** single argument which is a pointer to an instance of the
142398        ** sqlite3_mem_methods structure. The argument specifies alternative
142399        ** low-level memory allocation routines to be used in place of the memory
142400        ** allocation routines built into SQLite. */
142401        sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
142402        break;
142403      }
142404      case SQLITE_CONFIG_GETMALLOC: {
142405        /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
142406        ** single argument which is a pointer to an instance of the
142407        ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
142408        ** filled with the currently defined memory allocation routines. */
142409        if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
142410        *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
142411        break;
142412      }
142413      case SQLITE_CONFIG_MEMSTATUS: {
142414        /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
142415        ** single argument of type int, interpreted as a boolean, which enables
142416        ** or disables the collection of memory allocation statistics. */
142417        sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
142418        break;
142419      }
142420      case SQLITE_CONFIG_SMALL_MALLOC: {
142421        sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
142422        break;
142423      }
142424      case SQLITE_CONFIG_PAGECACHE: {
142425        /* EVIDENCE-OF: R-18761-36601 There are three arguments to
142426        ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
142427        ** the size of each page cache line (sz), and the number of cache lines
142428        ** (N). */
142429        sqlite3GlobalConfig.pPage = va_arg(ap, void*);
142430        sqlite3GlobalConfig.szPage = va_arg(ap, int);
142431        sqlite3GlobalConfig.nPage = va_arg(ap, int);
142432        break;
142433      }
142434      case SQLITE_CONFIG_PCACHE_HDRSZ: {
142435        /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
142436        ** a single parameter which is a pointer to an integer and writes into
142437        ** that integer the number of extra bytes per page required for each page
142438        ** in SQLITE_CONFIG_PAGECACHE. */
142439        *va_arg(ap, int*) = 
142440            sqlite3HeaderSizeBtree() +
142441            sqlite3HeaderSizePcache() +
142442            sqlite3HeaderSizePcache1();
142443        break;
142444      }
142445  
142446      case SQLITE_CONFIG_PCACHE: {
142447        /* no-op */
142448        break;
142449      }
142450      case SQLITE_CONFIG_GETPCACHE: {
142451        /* now an error */
142452        rc = SQLITE_ERROR;
142453        break;
142454      }
142455  
142456      case SQLITE_CONFIG_PCACHE2: {
142457        /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
142458        ** single argument which is a pointer to an sqlite3_pcache_methods2
142459        ** object. This object specifies the interface to a custom page cache
142460        ** implementation. */
142461        sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
142462        break;
142463      }
142464      case SQLITE_CONFIG_GETPCACHE2: {
142465        /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
142466        ** single argument which is a pointer to an sqlite3_pcache_methods2
142467        ** object. SQLite copies of the current page cache implementation into
142468        ** that object. */
142469        if( sqlite3GlobalConfig.pcache2.xInit==0 ){
142470          sqlite3PCacheSetDefault();
142471        }
142472        *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
142473        break;
142474      }
142475  
142476  /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
142477  ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
142478  ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
142479  #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
142480      case SQLITE_CONFIG_HEAP: {
142481        /* EVIDENCE-OF: R-19854-42126 There are three arguments to
142482        ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
142483        ** number of bytes in the memory buffer, and the minimum allocation size.
142484        */
142485        sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
142486        sqlite3GlobalConfig.nHeap = va_arg(ap, int);
142487        sqlite3GlobalConfig.mnReq = va_arg(ap, int);
142488  
142489        if( sqlite3GlobalConfig.mnReq<1 ){
142490          sqlite3GlobalConfig.mnReq = 1;
142491        }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
142492          /* cap min request size at 2^12 */
142493          sqlite3GlobalConfig.mnReq = (1<<12);
142494        }
142495  
142496        if( sqlite3GlobalConfig.pHeap==0 ){
142497          /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
142498          ** is NULL, then SQLite reverts to using its default memory allocator
142499          ** (the system malloc() implementation), undoing any prior invocation of
142500          ** SQLITE_CONFIG_MALLOC.
142501          **
142502          ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
142503          ** revert to its default implementation when sqlite3_initialize() is run
142504          */
142505          memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
142506        }else{
142507          /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
142508          ** alternative memory allocator is engaged to handle all of SQLites
142509          ** memory allocation needs. */
142510  #ifdef SQLITE_ENABLE_MEMSYS3
142511          sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
142512  #endif
142513  #ifdef SQLITE_ENABLE_MEMSYS5
142514          sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
142515  #endif
142516        }
142517        break;
142518      }
142519  #endif
142520  
142521      case SQLITE_CONFIG_LOOKASIDE: {
142522        sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
142523        sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
142524        break;
142525      }
142526      
142527      /* Record a pointer to the logger function and its first argument.
142528      ** The default is NULL.  Logging is disabled if the function pointer is
142529      ** NULL.
142530      */
142531      case SQLITE_CONFIG_LOG: {
142532        /* MSVC is picky about pulling func ptrs from va lists.
142533        ** http://support.microsoft.com/kb/47961
142534        ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
142535        */
142536        typedef void(*LOGFUNC_t)(void*,int,const char*);
142537        sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
142538        sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
142539        break;
142540      }
142541  
142542      /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
142543      ** can be changed at start-time using the
142544      ** sqlite3_config(SQLITE_CONFIG_URI,1) or
142545      ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
142546      */
142547      case SQLITE_CONFIG_URI: {
142548        /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
142549        ** argument of type int. If non-zero, then URI handling is globally
142550        ** enabled. If the parameter is zero, then URI handling is globally
142551        ** disabled. */
142552        sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
142553        break;
142554      }
142555  
142556      case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
142557        /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
142558        ** option takes a single integer argument which is interpreted as a
142559        ** boolean in order to enable or disable the use of covering indices for
142560        ** full table scans in the query optimizer. */
142561        sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
142562        break;
142563      }
142564  
142565  #ifdef SQLITE_ENABLE_SQLLOG
142566      case SQLITE_CONFIG_SQLLOG: {
142567        typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
142568        sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
142569        sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
142570        break;
142571      }
142572  #endif
142573  
142574      case SQLITE_CONFIG_MMAP_SIZE: {
142575        /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
142576        ** integer (sqlite3_int64) values that are the default mmap size limit
142577        ** (the default setting for PRAGMA mmap_size) and the maximum allowed
142578        ** mmap size limit. */
142579        sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
142580        sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
142581        /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
142582        ** negative, then that argument is changed to its compile-time default.
142583        **
142584        ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
142585        ** silently truncated if necessary so that it does not exceed the
142586        ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
142587        ** compile-time option.
142588        */
142589        if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
142590          mxMmap = SQLITE_MAX_MMAP_SIZE;
142591        }
142592        if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
142593        if( szMmap>mxMmap) szMmap = mxMmap;
142594        sqlite3GlobalConfig.mxMmap = mxMmap;
142595        sqlite3GlobalConfig.szMmap = szMmap;
142596        break;
142597      }
142598  
142599  #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
142600      case SQLITE_CONFIG_WIN32_HEAPSIZE: {
142601        /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
142602        ** unsigned integer value that specifies the maximum size of the created
142603        ** heap. */
142604        sqlite3GlobalConfig.nHeap = va_arg(ap, int);
142605        break;
142606      }
142607  #endif
142608  
142609      case SQLITE_CONFIG_PMASZ: {
142610        sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
142611        break;
142612      }
142613  
142614      case SQLITE_CONFIG_STMTJRNL_SPILL: {
142615        sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
142616        break;
142617      }
142618  
142619      default: {
142620        rc = SQLITE_ERROR;
142621        break;
142622      }
142623    }
142624    va_end(ap);
142625    return rc;
142626  }
142627  
142628  /*
142629  ** Set up the lookaside buffers for a database connection.
142630  ** Return SQLITE_OK on success.  
142631  ** If lookaside is already active, return SQLITE_BUSY.
142632  **
142633  ** The sz parameter is the number of bytes in each lookaside slot.
142634  ** The cnt parameter is the number of slots.  If pStart is NULL the
142635  ** space for the lookaside memory is obtained from sqlite3_malloc().
142636  ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
142637  ** the lookaside memory.
142638  */
142639  static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
142640  #ifndef SQLITE_OMIT_LOOKASIDE
142641    void *pStart;
142642    
142643    if( sqlite3LookasideUsed(db,0)>0 ){
142644      return SQLITE_BUSY;
142645    }
142646    /* Free any existing lookaside buffer for this handle before
142647    ** allocating a new one so we don't have to have space for 
142648    ** both at the same time.
142649    */
142650    if( db->lookaside.bMalloced ){
142651      sqlite3_free(db->lookaside.pStart);
142652    }
142653    /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
142654    ** than a pointer to be useful.
142655    */
142656    sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
142657    if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
142658    if( cnt<0 ) cnt = 0;
142659    if( sz==0 || cnt==0 ){
142660      sz = 0;
142661      pStart = 0;
142662    }else if( pBuf==0 ){
142663      sqlite3BeginBenignMalloc();
142664      pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
142665      sqlite3EndBenignMalloc();
142666      if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
142667    }else{
142668      pStart = pBuf;
142669    }
142670    db->lookaside.pStart = pStart;
142671    db->lookaside.pInit = 0;
142672    db->lookaside.pFree = 0;
142673    db->lookaside.sz = (u16)sz;
142674    if( pStart ){
142675      int i;
142676      LookasideSlot *p;
142677      assert( sz > (int)sizeof(LookasideSlot*) );
142678      db->lookaside.nSlot = cnt;
142679      p = (LookasideSlot*)pStart;
142680      for(i=cnt-1; i>=0; i--){
142681        p->pNext = db->lookaside.pInit;
142682        db->lookaside.pInit = p;
142683        p = (LookasideSlot*)&((u8*)p)[sz];
142684      }
142685      db->lookaside.pEnd = p;
142686      db->lookaside.bDisable = 0;
142687      db->lookaside.bMalloced = pBuf==0 ?1:0;
142688    }else{
142689      db->lookaside.pStart = db;
142690      db->lookaside.pEnd = db;
142691      db->lookaside.bDisable = 1;
142692      db->lookaside.bMalloced = 0;
142693      db->lookaside.nSlot = 0;
142694    }
142695  #endif /* SQLITE_OMIT_LOOKASIDE */
142696    return SQLITE_OK;
142697  }
142698  
142699  /*
142700  ** Return the mutex associated with a database connection.
142701  */
142702  SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
142703  #ifdef SQLITE_ENABLE_API_ARMOR
142704    if( !sqlite3SafetyCheckOk(db) ){
142705      (void)SQLITE_MISUSE_BKPT;
142706      return 0;
142707    }
142708  #endif
142709    return db->mutex;
142710  }
142711  
142712  /*
142713  ** Free up as much memory as we can from the given database
142714  ** connection.
142715  */
142716  SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
142717    int i;
142718  
142719  #ifdef SQLITE_ENABLE_API_ARMOR
142720    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
142721  #endif
142722    sqlite3_mutex_enter(db->mutex);
142723    sqlite3BtreeEnterAll(db);
142724    for(i=0; i<db->nDb; i++){
142725      Btree *pBt = db->aDb[i].pBt;
142726      if( pBt ){
142727        Pager *pPager = sqlite3BtreePager(pBt);
142728        sqlite3PagerShrink(pPager);
142729      }
142730    }
142731    sqlite3BtreeLeaveAll(db);
142732    sqlite3_mutex_leave(db->mutex);
142733    return SQLITE_OK;
142734  }
142735  
142736  /*
142737  ** Flush any dirty pages in the pager-cache for any attached database
142738  ** to disk.
142739  */
142740  SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){
142741    int i;
142742    int rc = SQLITE_OK;
142743    int bSeenBusy = 0;
142744  
142745  #ifdef SQLITE_ENABLE_API_ARMOR
142746    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
142747  #endif
142748    sqlite3_mutex_enter(db->mutex);
142749    sqlite3BtreeEnterAll(db);
142750    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
142751      Btree *pBt = db->aDb[i].pBt;
142752      if( pBt && sqlite3BtreeIsInTrans(pBt) ){
142753        Pager *pPager = sqlite3BtreePager(pBt);
142754        rc = sqlite3PagerFlush(pPager);
142755        if( rc==SQLITE_BUSY ){
142756          bSeenBusy = 1;
142757          rc = SQLITE_OK;
142758        }
142759      }
142760    }
142761    sqlite3BtreeLeaveAll(db);
142762    sqlite3_mutex_leave(db->mutex);
142763    return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
142764  }
142765  
142766  /*
142767  ** Configuration settings for an individual database connection
142768  */
142769  SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
142770    va_list ap;
142771    int rc;
142772    va_start(ap, op);
142773    switch( op ){
142774      case SQLITE_DBCONFIG_MAINDBNAME: {
142775        /* IMP: R-06824-28531 */
142776        /* IMP: R-36257-52125 */
142777        db->aDb[0].zDbSName = va_arg(ap,char*);
142778        rc = SQLITE_OK;
142779        break;
142780      }
142781      case SQLITE_DBCONFIG_LOOKASIDE: {
142782        void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
142783        int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
142784        int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
142785        rc = setupLookaside(db, pBuf, sz, cnt);
142786        break;
142787      }
142788      default: {
142789        static const struct {
142790          int op;      /* The opcode */
142791          u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
142792        } aFlagOp[] = {
142793          { SQLITE_DBCONFIG_ENABLE_FKEY,           SQLITE_ForeignKeys    },
142794          { SQLITE_DBCONFIG_ENABLE_TRIGGER,        SQLITE_EnableTrigger  },
142795          { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer  },
142796          { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension  },
142797          { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE,      SQLITE_NoCkptOnClose  },
142798          { SQLITE_DBCONFIG_ENABLE_QPSG,           SQLITE_EnableQPSG     },
142799        };
142800        unsigned int i;
142801        rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
142802        for(i=0; i<ArraySize(aFlagOp); i++){
142803          if( aFlagOp[i].op==op ){
142804            int onoff = va_arg(ap, int);
142805            int *pRes = va_arg(ap, int*);
142806            u32 oldFlags = db->flags;
142807            if( onoff>0 ){
142808              db->flags |= aFlagOp[i].mask;
142809            }else if( onoff==0 ){
142810              db->flags &= ~aFlagOp[i].mask;
142811            }
142812            if( oldFlags!=db->flags ){
142813              sqlite3ExpirePreparedStatements(db);
142814            }
142815            if( pRes ){
142816              *pRes = (db->flags & aFlagOp[i].mask)!=0;
142817            }
142818            rc = SQLITE_OK;
142819            break;
142820          }
142821        }
142822        break;
142823      }
142824    }
142825    va_end(ap);
142826    return rc;
142827  }
142828  
142829  
142830  /*
142831  ** Return true if the buffer z[0..n-1] contains all spaces.
142832  */
142833  static int allSpaces(const char *z, int n){
142834    while( n>0 && z[n-1]==' ' ){ n--; }
142835    return n==0;
142836  }
142837  
142838  /*
142839  ** This is the default collating function named "BINARY" which is always
142840  ** available.
142841  **
142842  ** If the padFlag argument is not NULL then space padding at the end
142843  ** of strings is ignored.  This implements the RTRIM collation.
142844  */
142845  static int binCollFunc(
142846    void *padFlag,
142847    int nKey1, const void *pKey1,
142848    int nKey2, const void *pKey2
142849  ){
142850    int rc, n;
142851    n = nKey1<nKey2 ? nKey1 : nKey2;
142852    /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
142853    ** strings byte by byte using the memcmp() function from the standard C
142854    ** library. */
142855    assert( pKey1 && pKey2 );
142856    rc = memcmp(pKey1, pKey2, n);
142857    if( rc==0 ){
142858      if( padFlag
142859       && allSpaces(((char*)pKey1)+n, nKey1-n)
142860       && allSpaces(((char*)pKey2)+n, nKey2-n)
142861      ){
142862        /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
142863        ** spaces at the end of either string do not change the result. In other
142864        ** words, strings will compare equal to one another as long as they
142865        ** differ only in the number of spaces at the end.
142866        */
142867      }else{
142868        rc = nKey1 - nKey2;
142869      }
142870    }
142871    return rc;
142872  }
142873  
142874  /*
142875  ** Another built-in collating sequence: NOCASE. 
142876  **
142877  ** This collating sequence is intended to be used for "case independent
142878  ** comparison". SQLite's knowledge of upper and lower case equivalents
142879  ** extends only to the 26 characters used in the English language.
142880  **
142881  ** At the moment there is only a UTF-8 implementation.
142882  */
142883  static int nocaseCollatingFunc(
142884    void *NotUsed,
142885    int nKey1, const void *pKey1,
142886    int nKey2, const void *pKey2
142887  ){
142888    int r = sqlite3StrNICmp(
142889        (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
142890    UNUSED_PARAMETER(NotUsed);
142891    if( 0==r ){
142892      r = nKey1-nKey2;
142893    }
142894    return r;
142895  }
142896  
142897  /*
142898  ** Return the ROWID of the most recent insert
142899  */
142900  SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
142901  #ifdef SQLITE_ENABLE_API_ARMOR
142902    if( !sqlite3SafetyCheckOk(db) ){
142903      (void)SQLITE_MISUSE_BKPT;
142904      return 0;
142905    }
142906  #endif
142907    return db->lastRowid;
142908  }
142909  
142910  /*
142911  ** Set the value returned by the sqlite3_last_insert_rowid() API function.
142912  */
142913  SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
142914  #ifdef SQLITE_ENABLE_API_ARMOR
142915    if( !sqlite3SafetyCheckOk(db) ){
142916      (void)SQLITE_MISUSE_BKPT;
142917      return;
142918    }
142919  #endif
142920    sqlite3_mutex_enter(db->mutex);
142921    db->lastRowid = iRowid;
142922    sqlite3_mutex_leave(db->mutex);
142923  }
142924  
142925  /*
142926  ** Return the number of changes in the most recent call to sqlite3_exec().
142927  */
142928  SQLITE_API int sqlite3_changes(sqlite3 *db){
142929  #ifdef SQLITE_ENABLE_API_ARMOR
142930    if( !sqlite3SafetyCheckOk(db) ){
142931      (void)SQLITE_MISUSE_BKPT;
142932      return 0;
142933    }
142934  #endif
142935    return db->nChange;
142936  }
142937  
142938  /*
142939  ** Return the number of changes since the database handle was opened.
142940  */
142941  SQLITE_API int sqlite3_total_changes(sqlite3 *db){
142942  #ifdef SQLITE_ENABLE_API_ARMOR
142943    if( !sqlite3SafetyCheckOk(db) ){
142944      (void)SQLITE_MISUSE_BKPT;
142945      return 0;
142946    }
142947  #endif
142948    return db->nTotalChange;
142949  }
142950  
142951  /*
142952  ** Close all open savepoints. This function only manipulates fields of the
142953  ** database handle object, it does not close any savepoints that may be open
142954  ** at the b-tree/pager level.
142955  */
142956  SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
142957    while( db->pSavepoint ){
142958      Savepoint *pTmp = db->pSavepoint;
142959      db->pSavepoint = pTmp->pNext;
142960      sqlite3DbFree(db, pTmp);
142961    }
142962    db->nSavepoint = 0;
142963    db->nStatement = 0;
142964    db->isTransactionSavepoint = 0;
142965  }
142966  
142967  /*
142968  ** Invoke the destructor function associated with FuncDef p, if any. Except,
142969  ** if this is not the last copy of the function, do not invoke it. Multiple
142970  ** copies of a single function are created when create_function() is called
142971  ** with SQLITE_ANY as the encoding.
142972  */
142973  static void functionDestroy(sqlite3 *db, FuncDef *p){
142974    FuncDestructor *pDestructor = p->u.pDestructor;
142975    if( pDestructor ){
142976      pDestructor->nRef--;
142977      if( pDestructor->nRef==0 ){
142978        pDestructor->xDestroy(pDestructor->pUserData);
142979        sqlite3DbFree(db, pDestructor);
142980      }
142981    }
142982  }
142983  
142984  /*
142985  ** Disconnect all sqlite3_vtab objects that belong to database connection
142986  ** db. This is called when db is being closed.
142987  */
142988  static void disconnectAllVtab(sqlite3 *db){
142989  #ifndef SQLITE_OMIT_VIRTUALTABLE
142990    int i;
142991    HashElem *p;
142992    sqlite3BtreeEnterAll(db);
142993    for(i=0; i<db->nDb; i++){
142994      Schema *pSchema = db->aDb[i].pSchema;
142995      if( db->aDb[i].pSchema ){
142996        for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
142997          Table *pTab = (Table *)sqliteHashData(p);
142998          if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
142999        }
143000      }
143001    }
143002    for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
143003      Module *pMod = (Module *)sqliteHashData(p);
143004      if( pMod->pEpoTab ){
143005        sqlite3VtabDisconnect(db, pMod->pEpoTab);
143006      }
143007    }
143008    sqlite3VtabUnlockList(db);
143009    sqlite3BtreeLeaveAll(db);
143010  #else
143011    UNUSED_PARAMETER(db);
143012  #endif
143013  }
143014  
143015  /*
143016  ** Return TRUE if database connection db has unfinalized prepared
143017  ** statements or unfinished sqlite3_backup objects.  
143018  */
143019  static int connectionIsBusy(sqlite3 *db){
143020    int j;
143021    assert( sqlite3_mutex_held(db->mutex) );
143022    if( db->pVdbe ) return 1;
143023    for(j=0; j<db->nDb; j++){
143024      Btree *pBt = db->aDb[j].pBt;
143025      if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
143026    }
143027    return 0;
143028  }
143029  
143030  /*
143031  ** Close an existing SQLite database
143032  */
143033  static int sqlite3Close(sqlite3 *db, int forceZombie){
143034    if( !db ){
143035      /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
143036      ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
143037      return SQLITE_OK;
143038    }
143039    if( !sqlite3SafetyCheckSickOrOk(db) ){
143040      return SQLITE_MISUSE_BKPT;
143041    }
143042    sqlite3_mutex_enter(db->mutex);
143043    if( db->mTrace & SQLITE_TRACE_CLOSE ){
143044      db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
143045    }
143046  
143047    /* Force xDisconnect calls on all virtual tables */
143048    disconnectAllVtab(db);
143049  
143050    /* If a transaction is open, the disconnectAllVtab() call above
143051    ** will not have called the xDisconnect() method on any virtual
143052    ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
143053    ** call will do so. We need to do this before the check for active
143054    ** SQL statements below, as the v-table implementation may be storing
143055    ** some prepared statements internally.
143056    */
143057    sqlite3VtabRollback(db);
143058  
143059    /* Legacy behavior (sqlite3_close() behavior) is to return
143060    ** SQLITE_BUSY if the connection can not be closed immediately.
143061    */
143062    if( !forceZombie && connectionIsBusy(db) ){
143063      sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
143064         "statements or unfinished backups");
143065      sqlite3_mutex_leave(db->mutex);
143066      return SQLITE_BUSY;
143067    }
143068  
143069  #ifdef SQLITE_ENABLE_SQLLOG
143070    if( sqlite3GlobalConfig.xSqllog ){
143071      /* Closing the handle. Fourth parameter is passed the value 2. */
143072      sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
143073    }
143074  #endif
143075  
143076    /* Convert the connection into a zombie and then close it.
143077    */
143078    db->magic = SQLITE_MAGIC_ZOMBIE;
143079    sqlite3LeaveMutexAndCloseZombie(db);
143080    return SQLITE_OK;
143081  }
143082  
143083  /*
143084  ** Two variations on the public interface for closing a database
143085  ** connection. The sqlite3_close() version returns SQLITE_BUSY and
143086  ** leaves the connection option if there are unfinalized prepared
143087  ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
143088  ** version forces the connection to become a zombie if there are
143089  ** unclosed resources, and arranges for deallocation when the last
143090  ** prepare statement or sqlite3_backup closes.
143091  */
143092  SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
143093  SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
143094  
143095  
143096  /*
143097  ** Close the mutex on database connection db.
143098  **
143099  ** Furthermore, if database connection db is a zombie (meaning that there
143100  ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
143101  ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
143102  ** finished, then free all resources.
143103  */
143104  SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
143105    HashElem *i;                    /* Hash table iterator */
143106    int j;
143107  
143108    /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
143109    ** or if the connection has not yet been closed by sqlite3_close_v2(),
143110    ** then just leave the mutex and return.
143111    */
143112    if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
143113      sqlite3_mutex_leave(db->mutex);
143114      return;
143115    }
143116  
143117    /* If we reach this point, it means that the database connection has
143118    ** closed all sqlite3_stmt and sqlite3_backup objects and has been
143119    ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
143120    ** go ahead and free all resources.
143121    */
143122  
143123    /* If a transaction is open, roll it back. This also ensures that if
143124    ** any database schemas have been modified by an uncommitted transaction
143125    ** they are reset. And that the required b-tree mutex is held to make
143126    ** the pager rollback and schema reset an atomic operation. */
143127    sqlite3RollbackAll(db, SQLITE_OK);
143128  
143129    /* Free any outstanding Savepoint structures. */
143130    sqlite3CloseSavepoints(db);
143131  
143132    /* Close all database connections */
143133    for(j=0; j<db->nDb; j++){
143134      struct Db *pDb = &db->aDb[j];
143135      if( pDb->pBt ){
143136        sqlite3BtreeClose(pDb->pBt);
143137        pDb->pBt = 0;
143138        if( j!=1 ){
143139          pDb->pSchema = 0;
143140        }
143141      }
143142    }
143143    /* Clear the TEMP schema separately and last */
143144    if( db->aDb[1].pSchema ){
143145      sqlite3SchemaClear(db->aDb[1].pSchema);
143146    }
143147    sqlite3VtabUnlockList(db);
143148  
143149    /* Free up the array of auxiliary databases */
143150    sqlite3CollapseDatabaseArray(db);
143151    assert( db->nDb<=2 );
143152    assert( db->aDb==db->aDbStatic );
143153  
143154    /* Tell the code in notify.c that the connection no longer holds any
143155    ** locks and does not require any further unlock-notify callbacks.
143156    */
143157    sqlite3ConnectionClosed(db);
143158  
143159    for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
143160      FuncDef *pNext, *p;
143161      p = sqliteHashData(i);
143162      do{
143163        functionDestroy(db, p);
143164        pNext = p->pNext;
143165        sqlite3DbFree(db, p);
143166        p = pNext;
143167      }while( p );
143168    }
143169    sqlite3HashClear(&db->aFunc);
143170    for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
143171      CollSeq *pColl = (CollSeq *)sqliteHashData(i);
143172      /* Invoke any destructors registered for collation sequence user data. */
143173      for(j=0; j<3; j++){
143174        if( pColl[j].xDel ){
143175          pColl[j].xDel(pColl[j].pUser);
143176        }
143177      }
143178      sqlite3DbFree(db, pColl);
143179    }
143180    sqlite3HashClear(&db->aCollSeq);
143181  #ifndef SQLITE_OMIT_VIRTUALTABLE
143182    for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
143183      Module *pMod = (Module *)sqliteHashData(i);
143184      if( pMod->xDestroy ){
143185        pMod->xDestroy(pMod->pAux);
143186      }
143187      sqlite3VtabEponymousTableClear(db, pMod);
143188      sqlite3DbFree(db, pMod);
143189    }
143190    sqlite3HashClear(&db->aModule);
143191  #endif
143192  
143193    sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
143194    sqlite3ValueFree(db->pErr);
143195    sqlite3CloseExtensions(db);
143196  #if SQLITE_USER_AUTHENTICATION
143197    sqlite3_free(db->auth.zAuthUser);
143198    sqlite3_free(db->auth.zAuthPW);
143199  #endif
143200  
143201    db->magic = SQLITE_MAGIC_ERROR;
143202  
143203    /* The temp-database schema is allocated differently from the other schema
143204    ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
143205    ** So it needs to be freed here. Todo: Why not roll the temp schema into
143206    ** the same sqliteMalloc() as the one that allocates the database 
143207    ** structure?
143208    */
143209    sqlite3DbFree(db, db->aDb[1].pSchema);
143210    sqlite3_mutex_leave(db->mutex);
143211    db->magic = SQLITE_MAGIC_CLOSED;
143212    sqlite3_mutex_free(db->mutex);
143213    assert( sqlite3LookasideUsed(db,0)==0 );
143214    if( db->lookaside.bMalloced ){
143215      sqlite3_free(db->lookaside.pStart);
143216    }
143217    sqlite3_free(db);
143218  }
143219  
143220  /*
143221  ** Rollback all database files.  If tripCode is not SQLITE_OK, then
143222  ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
143223  ** breaker") and made to return tripCode if there are any further
143224  ** attempts to use that cursor.  Read cursors remain open and valid
143225  ** but are "saved" in case the table pages are moved around.
143226  */
143227  SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
143228    int i;
143229    int inTrans = 0;
143230    int schemaChange;
143231    assert( sqlite3_mutex_held(db->mutex) );
143232    sqlite3BeginBenignMalloc();
143233  
143234    /* Obtain all b-tree mutexes before making any calls to BtreeRollback(). 
143235    ** This is important in case the transaction being rolled back has
143236    ** modified the database schema. If the b-tree mutexes are not taken
143237    ** here, then another shared-cache connection might sneak in between
143238    ** the database rollback and schema reset, which can cause false
143239    ** corruption reports in some cases.  */
143240    sqlite3BtreeEnterAll(db);
143241    schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
143242  
143243    for(i=0; i<db->nDb; i++){
143244      Btree *p = db->aDb[i].pBt;
143245      if( p ){
143246        if( sqlite3BtreeIsInTrans(p) ){
143247          inTrans = 1;
143248        }
143249        sqlite3BtreeRollback(p, tripCode, !schemaChange);
143250      }
143251    }
143252    sqlite3VtabRollback(db);
143253    sqlite3EndBenignMalloc();
143254  
143255    if( (db->mDbFlags&DBFLAG_SchemaChange)!=0 && db->init.busy==0 ){
143256      sqlite3ExpirePreparedStatements(db);
143257      sqlite3ResetAllSchemasOfConnection(db);
143258    }
143259    sqlite3BtreeLeaveAll(db);
143260  
143261    /* Any deferred constraint violations have now been resolved. */
143262    db->nDeferredCons = 0;
143263    db->nDeferredImmCons = 0;
143264    db->flags &= ~SQLITE_DeferFKs;
143265  
143266    /* If one has been configured, invoke the rollback-hook callback */
143267    if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
143268      db->xRollbackCallback(db->pRollbackArg);
143269    }
143270  }
143271  
143272  /*
143273  ** Return a static string containing the name corresponding to the error code
143274  ** specified in the argument.
143275  */
143276  #if defined(SQLITE_NEED_ERR_NAME)
143277  SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
143278    const char *zName = 0;
143279    int i, origRc = rc;
143280    for(i=0; i<2 && zName==0; i++, rc &= 0xff){
143281      switch( rc ){
143282        case SQLITE_OK:                 zName = "SQLITE_OK";                break;
143283        case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
143284        case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
143285        case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
143286        case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
143287        case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
143288        case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
143289        case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
143290        case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
143291        case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
143292        case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
143293        case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
143294        case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
143295        case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
143296        case SQLITE_READONLY_CANTLOCK:  zName = "SQLITE_READONLY_CANTLOCK"; break;
143297        case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
143298        case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
143299        case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
143300        case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
143301        case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
143302        case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
143303        case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
143304        case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
143305        case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
143306        case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
143307        case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
143308        case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
143309        case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
143310        case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
143311        case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
143312        case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
143313        case SQLITE_IOERR_CHECKRESERVEDLOCK:
143314                                  zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
143315        case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
143316        case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
143317        case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
143318        case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
143319        case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
143320        case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
143321        case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
143322        case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
143323        case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
143324        case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
143325        case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
143326        case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
143327        case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
143328        case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
143329        case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
143330        case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
143331        case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
143332        case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
143333        case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
143334        case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
143335        case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
143336        case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
143337        case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
143338        case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
143339        case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
143340        case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
143341        case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
143342        case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
143343        case SQLITE_CONSTRAINT_FOREIGNKEY:
143344                                  zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
143345        case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
143346        case SQLITE_CONSTRAINT_PRIMARYKEY:
143347                                  zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
143348        case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
143349        case SQLITE_CONSTRAINT_COMMITHOOK:
143350                                  zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
143351        case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
143352        case SQLITE_CONSTRAINT_FUNCTION:
143353                                  zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
143354        case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
143355        case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
143356        case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
143357        case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
143358        case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
143359        case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
143360        case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
143361        case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
143362        case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
143363        case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
143364        case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
143365        case SQLITE_NOTICE_RECOVER_ROLLBACK:
143366                                  zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
143367        case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
143368        case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
143369        case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
143370      }
143371    }
143372    if( zName==0 ){
143373      static char zBuf[50];
143374      sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
143375      zName = zBuf;
143376    }
143377    return zName;
143378  }
143379  #endif
143380  
143381  /*
143382  ** Return a static string that describes the kind of error specified in the
143383  ** argument.
143384  */
143385  SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
143386    static const char* const aMsg[] = {
143387      /* SQLITE_OK          */ "not an error",
143388      /* SQLITE_ERROR       */ "SQL logic error",
143389      /* SQLITE_INTERNAL    */ 0,
143390      /* SQLITE_PERM        */ "access permission denied",
143391      /* SQLITE_ABORT       */ "query aborted",
143392      /* SQLITE_BUSY        */ "database is locked",
143393      /* SQLITE_LOCKED      */ "database table is locked",
143394      /* SQLITE_NOMEM       */ "out of memory",
143395      /* SQLITE_READONLY    */ "attempt to write a readonly database",
143396      /* SQLITE_INTERRUPT   */ "interrupted",
143397      /* SQLITE_IOERR       */ "disk I/O error",
143398      /* SQLITE_CORRUPT     */ "database disk image is malformed",
143399      /* SQLITE_NOTFOUND    */ "unknown operation",
143400      /* SQLITE_FULL        */ "database or disk is full",
143401      /* SQLITE_CANTOPEN    */ "unable to open database file",
143402      /* SQLITE_PROTOCOL    */ "locking protocol",
143403      /* SQLITE_EMPTY       */ 0,
143404      /* SQLITE_SCHEMA      */ "database schema has changed",
143405      /* SQLITE_TOOBIG      */ "string or blob too big",
143406      /* SQLITE_CONSTRAINT  */ "constraint failed",
143407      /* SQLITE_MISMATCH    */ "datatype mismatch",
143408      /* SQLITE_MISUSE      */ "bad parameter or other API misuse",
143409  #ifdef SQLITE_DISABLE_LFS
143410      /* SQLITE_NOLFS       */ "large file support is disabled",
143411  #else
143412      /* SQLITE_NOLFS       */ 0,
143413  #endif
143414      /* SQLITE_AUTH        */ "authorization denied",
143415      /* SQLITE_FORMAT      */ 0,
143416      /* SQLITE_RANGE       */ "column index out of range",
143417      /* SQLITE_NOTADB      */ "file is not a database",
143418    };
143419    const char *zErr = "unknown error";
143420    switch( rc ){
143421      case SQLITE_ABORT_ROLLBACK: {
143422        zErr = "abort due to ROLLBACK";
143423        break;
143424      }
143425      default: {
143426        rc &= 0xff;
143427        if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
143428          zErr = aMsg[rc];
143429        }
143430        break;
143431      }
143432    }
143433    return zErr;
143434  }
143435  
143436  /*
143437  ** This routine implements a busy callback that sleeps and tries
143438  ** again until a timeout value is reached.  The timeout value is
143439  ** an integer number of milliseconds passed in as the first
143440  ** argument.
143441  */
143442  static int sqliteDefaultBusyCallback(
143443   void *ptr,               /* Database connection */
143444   int count                /* Number of times table has been busy */
143445  ){
143446  #if SQLITE_OS_WIN || HAVE_USLEEP
143447    static const u8 delays[] =
143448       { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
143449    static const u8 totals[] =
143450       { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
143451  # define NDELAY ArraySize(delays)
143452    sqlite3 *db = (sqlite3 *)ptr;
143453    int timeout = db->busyTimeout;
143454    int delay, prior;
143455  
143456    assert( count>=0 );
143457    if( count < NDELAY ){
143458      delay = delays[count];
143459      prior = totals[count];
143460    }else{
143461      delay = delays[NDELAY-1];
143462      prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
143463    }
143464    if( prior + delay > timeout ){
143465      delay = timeout - prior;
143466      if( delay<=0 ) return 0;
143467    }
143468    sqlite3OsSleep(db->pVfs, delay*1000);
143469    return 1;
143470  #else
143471    sqlite3 *db = (sqlite3 *)ptr;
143472    int timeout = ((sqlite3 *)ptr)->busyTimeout;
143473    if( (count+1)*1000 > timeout ){
143474      return 0;
143475    }
143476    sqlite3OsSleep(db->pVfs, 1000000);
143477    return 1;
143478  #endif
143479  }
143480  
143481  /*
143482  ** Invoke the given busy handler.
143483  **
143484  ** This routine is called when an operation failed with a lock.
143485  ** If this routine returns non-zero, the lock is retried.  If it
143486  ** returns 0, the operation aborts with an SQLITE_BUSY error.
143487  */
143488  SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
143489    int rc;
143490    if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
143491    rc = p->xFunc(p->pArg, p->nBusy);
143492    if( rc==0 ){
143493      p->nBusy = -1;
143494    }else{
143495      p->nBusy++;
143496    }
143497    return rc; 
143498  }
143499  
143500  /*
143501  ** This routine sets the busy callback for an Sqlite database to the
143502  ** given callback function with the given argument.
143503  */
143504  SQLITE_API int sqlite3_busy_handler(
143505    sqlite3 *db,
143506    int (*xBusy)(void*,int),
143507    void *pArg
143508  ){
143509  #ifdef SQLITE_ENABLE_API_ARMOR
143510    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
143511  #endif
143512    sqlite3_mutex_enter(db->mutex);
143513    db->busyHandler.xFunc = xBusy;
143514    db->busyHandler.pArg = pArg;
143515    db->busyHandler.nBusy = 0;
143516    db->busyTimeout = 0;
143517    sqlite3_mutex_leave(db->mutex);
143518    return SQLITE_OK;
143519  }
143520  
143521  #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
143522  /*
143523  ** This routine sets the progress callback for an Sqlite database to the
143524  ** given callback function with the given argument. The progress callback will
143525  ** be invoked every nOps opcodes.
143526  */
143527  SQLITE_API void sqlite3_progress_handler(
143528    sqlite3 *db, 
143529    int nOps,
143530    int (*xProgress)(void*), 
143531    void *pArg
143532  ){
143533  #ifdef SQLITE_ENABLE_API_ARMOR
143534    if( !sqlite3SafetyCheckOk(db) ){
143535      (void)SQLITE_MISUSE_BKPT;
143536      return;
143537    }
143538  #endif
143539    sqlite3_mutex_enter(db->mutex);
143540    if( nOps>0 ){
143541      db->xProgress = xProgress;
143542      db->nProgressOps = (unsigned)nOps;
143543      db->pProgressArg = pArg;
143544    }else{
143545      db->xProgress = 0;
143546      db->nProgressOps = 0;
143547      db->pProgressArg = 0;
143548    }
143549    sqlite3_mutex_leave(db->mutex);
143550  }
143551  #endif
143552  
143553  
143554  /*
143555  ** This routine installs a default busy handler that waits for the
143556  ** specified number of milliseconds before returning 0.
143557  */
143558  SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
143559  #ifdef SQLITE_ENABLE_API_ARMOR
143560    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
143561  #endif
143562    if( ms>0 ){
143563      sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
143564      db->busyTimeout = ms;
143565    }else{
143566      sqlite3_busy_handler(db, 0, 0);
143567    }
143568    return SQLITE_OK;
143569  }
143570  
143571  /*
143572  ** Cause any pending operation to stop at its earliest opportunity.
143573  */
143574  SQLITE_API void sqlite3_interrupt(sqlite3 *db){
143575  #ifdef SQLITE_ENABLE_API_ARMOR
143576    if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){
143577      (void)SQLITE_MISUSE_BKPT;
143578      return;
143579    }
143580  #endif
143581    db->u1.isInterrupted = 1;
143582  }
143583  
143584  
143585  /*
143586  ** This function is exactly the same as sqlite3_create_function(), except
143587  ** that it is designed to be called by internal code. The difference is
143588  ** that if a malloc() fails in sqlite3_create_function(), an error code
143589  ** is returned and the mallocFailed flag cleared. 
143590  */
143591  SQLITE_PRIVATE int sqlite3CreateFunc(
143592    sqlite3 *db,
143593    const char *zFunctionName,
143594    int nArg,
143595    int enc,
143596    void *pUserData,
143597    void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
143598    void (*xStep)(sqlite3_context*,int,sqlite3_value **),
143599    void (*xFinal)(sqlite3_context*),
143600    FuncDestructor *pDestructor
143601  ){
143602    FuncDef *p;
143603    int nName;
143604    int extraFlags;
143605  
143606    assert( sqlite3_mutex_held(db->mutex) );
143607    if( zFunctionName==0 ||
143608        (xSFunc && (xFinal || xStep)) || 
143609        (!xSFunc && (xFinal && !xStep)) ||
143610        (!xSFunc && (!xFinal && xStep)) ||
143611        (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
143612        (255<(nName = sqlite3Strlen30( zFunctionName))) ){
143613      return SQLITE_MISUSE_BKPT;
143614    }
143615  
143616    assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
143617    extraFlags = enc &  SQLITE_DETERMINISTIC;
143618    enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
143619    
143620  #ifndef SQLITE_OMIT_UTF16
143621    /* If SQLITE_UTF16 is specified as the encoding type, transform this
143622    ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
143623    ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
143624    **
143625    ** If SQLITE_ANY is specified, add three versions of the function
143626    ** to the hash table.
143627    */
143628    if( enc==SQLITE_UTF16 ){
143629      enc = SQLITE_UTF16NATIVE;
143630    }else if( enc==SQLITE_ANY ){
143631      int rc;
143632      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
143633           pUserData, xSFunc, xStep, xFinal, pDestructor);
143634      if( rc==SQLITE_OK ){
143635        rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
143636            pUserData, xSFunc, xStep, xFinal, pDestructor);
143637      }
143638      if( rc!=SQLITE_OK ){
143639        return rc;
143640      }
143641      enc = SQLITE_UTF16BE;
143642    }
143643  #else
143644    enc = SQLITE_UTF8;
143645  #endif
143646    
143647    /* Check if an existing function is being overridden or deleted. If so,
143648    ** and there are active VMs, then return SQLITE_BUSY. If a function
143649    ** is being overridden/deleted but there are no active VMs, allow the
143650    ** operation to continue but invalidate all precompiled statements.
143651    */
143652    p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
143653    if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
143654      if( db->nVdbeActive ){
143655        sqlite3ErrorWithMsg(db, SQLITE_BUSY, 
143656          "unable to delete/modify user-function due to active statements");
143657        assert( !db->mallocFailed );
143658        return SQLITE_BUSY;
143659      }else{
143660        sqlite3ExpirePreparedStatements(db);
143661      }
143662    }
143663  
143664    p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
143665    assert(p || db->mallocFailed);
143666    if( !p ){
143667      return SQLITE_NOMEM_BKPT;
143668    }
143669  
143670    /* If an older version of the function with a configured destructor is
143671    ** being replaced invoke the destructor function here. */
143672    functionDestroy(db, p);
143673  
143674    if( pDestructor ){
143675      pDestructor->nRef++;
143676    }
143677    p->u.pDestructor = pDestructor;
143678    p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
143679    testcase( p->funcFlags & SQLITE_DETERMINISTIC );
143680    p->xSFunc = xSFunc ? xSFunc : xStep;
143681    p->xFinalize = xFinal;
143682    p->pUserData = pUserData;
143683    p->nArg = (u16)nArg;
143684    return SQLITE_OK;
143685  }
143686  
143687  /*
143688  ** Create new user functions.
143689  */
143690  SQLITE_API int sqlite3_create_function(
143691    sqlite3 *db,
143692    const char *zFunc,
143693    int nArg,
143694    int enc,
143695    void *p,
143696    void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
143697    void (*xStep)(sqlite3_context*,int,sqlite3_value **),
143698    void (*xFinal)(sqlite3_context*)
143699  ){
143700    return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep,
143701                                      xFinal, 0);
143702  }
143703  
143704  SQLITE_API int sqlite3_create_function_v2(
143705    sqlite3 *db,
143706    const char *zFunc,
143707    int nArg,
143708    int enc,
143709    void *p,
143710    void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
143711    void (*xStep)(sqlite3_context*,int,sqlite3_value **),
143712    void (*xFinal)(sqlite3_context*),
143713    void (*xDestroy)(void *)
143714  ){
143715    int rc = SQLITE_ERROR;
143716    FuncDestructor *pArg = 0;
143717  
143718  #ifdef SQLITE_ENABLE_API_ARMOR
143719    if( !sqlite3SafetyCheckOk(db) ){
143720      return SQLITE_MISUSE_BKPT;
143721    }
143722  #endif
143723    sqlite3_mutex_enter(db->mutex);
143724    if( xDestroy ){
143725      pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
143726      if( !pArg ){
143727        xDestroy(p);
143728        goto out;
143729      }
143730      pArg->xDestroy = xDestroy;
143731      pArg->pUserData = p;
143732    }
143733    rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg);
143734    if( pArg && pArg->nRef==0 ){
143735      assert( rc!=SQLITE_OK );
143736      xDestroy(p);
143737      sqlite3DbFree(db, pArg);
143738    }
143739  
143740   out:
143741    rc = sqlite3ApiExit(db, rc);
143742    sqlite3_mutex_leave(db->mutex);
143743    return rc;
143744  }
143745  
143746  #ifndef SQLITE_OMIT_UTF16
143747  SQLITE_API int sqlite3_create_function16(
143748    sqlite3 *db,
143749    const void *zFunctionName,
143750    int nArg,
143751    int eTextRep,
143752    void *p,
143753    void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
143754    void (*xStep)(sqlite3_context*,int,sqlite3_value**),
143755    void (*xFinal)(sqlite3_context*)
143756  ){
143757    int rc;
143758    char *zFunc8;
143759  
143760  #ifdef SQLITE_ENABLE_API_ARMOR
143761    if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
143762  #endif
143763    sqlite3_mutex_enter(db->mutex);
143764    assert( !db->mallocFailed );
143765    zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
143766    rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0);
143767    sqlite3DbFree(db, zFunc8);
143768    rc = sqlite3ApiExit(db, rc);
143769    sqlite3_mutex_leave(db->mutex);
143770    return rc;
143771  }
143772  #endif
143773  
143774  
143775  /*
143776  ** Declare that a function has been overloaded by a virtual table.
143777  **
143778  ** If the function already exists as a regular global function, then
143779  ** this routine is a no-op.  If the function does not exist, then create
143780  ** a new one that always throws a run-time error.  
143781  **
143782  ** When virtual tables intend to provide an overloaded function, they
143783  ** should call this routine to make sure the global function exists.
143784  ** A global function must exist in order for name resolution to work
143785  ** properly.
143786  */
143787  SQLITE_API int sqlite3_overload_function(
143788    sqlite3 *db,
143789    const char *zName,
143790    int nArg
143791  ){
143792    int rc = SQLITE_OK;
143793  
143794  #ifdef SQLITE_ENABLE_API_ARMOR
143795    if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
143796      return SQLITE_MISUSE_BKPT;
143797    }
143798  #endif
143799    sqlite3_mutex_enter(db->mutex);
143800    if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){
143801      rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
143802                             0, sqlite3InvalidFunction, 0, 0, 0);
143803    }
143804    rc = sqlite3ApiExit(db, rc);
143805    sqlite3_mutex_leave(db->mutex);
143806    return rc;
143807  }
143808  
143809  #ifndef SQLITE_OMIT_TRACE
143810  /*
143811  ** Register a trace function.  The pArg from the previously registered trace
143812  ** is returned.  
143813  **
143814  ** A NULL trace function means that no tracing is executes.  A non-NULL
143815  ** trace is a pointer to a function that is invoked at the start of each
143816  ** SQL statement.
143817  */
143818  #ifndef SQLITE_OMIT_DEPRECATED
143819  SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
143820    void *pOld;
143821  
143822  #ifdef SQLITE_ENABLE_API_ARMOR
143823    if( !sqlite3SafetyCheckOk(db) ){
143824      (void)SQLITE_MISUSE_BKPT;
143825      return 0;
143826    }
143827  #endif
143828    sqlite3_mutex_enter(db->mutex);
143829    pOld = db->pTraceArg;
143830    db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
143831    db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
143832    db->pTraceArg = pArg;
143833    sqlite3_mutex_leave(db->mutex);
143834    return pOld;
143835  }
143836  #endif /* SQLITE_OMIT_DEPRECATED */
143837  
143838  /* Register a trace callback using the version-2 interface.
143839  */
143840  SQLITE_API int sqlite3_trace_v2(
143841    sqlite3 *db,                               /* Trace this connection */
143842    unsigned mTrace,                           /* Mask of events to be traced */
143843    int(*xTrace)(unsigned,void*,void*,void*),  /* Callback to invoke */
143844    void *pArg                                 /* Context */
143845  ){
143846  #ifdef SQLITE_ENABLE_API_ARMOR
143847    if( !sqlite3SafetyCheckOk(db) ){
143848      return SQLITE_MISUSE_BKPT;
143849    }
143850  #endif
143851    sqlite3_mutex_enter(db->mutex);
143852    if( mTrace==0 ) xTrace = 0;
143853    if( xTrace==0 ) mTrace = 0;
143854    db->mTrace = mTrace;
143855    db->xTrace = xTrace;
143856    db->pTraceArg = pArg;
143857    sqlite3_mutex_leave(db->mutex);
143858    return SQLITE_OK;
143859  }
143860  
143861  #ifndef SQLITE_OMIT_DEPRECATED
143862  /*
143863  ** Register a profile function.  The pArg from the previously registered 
143864  ** profile function is returned.  
143865  **
143866  ** A NULL profile function means that no profiling is executes.  A non-NULL
143867  ** profile is a pointer to a function that is invoked at the conclusion of
143868  ** each SQL statement that is run.
143869  */
143870  SQLITE_API void *sqlite3_profile(
143871    sqlite3 *db,
143872    void (*xProfile)(void*,const char*,sqlite_uint64),
143873    void *pArg
143874  ){
143875    void *pOld;
143876  
143877  #ifdef SQLITE_ENABLE_API_ARMOR
143878    if( !sqlite3SafetyCheckOk(db) ){
143879      (void)SQLITE_MISUSE_BKPT;
143880      return 0;
143881    }
143882  #endif
143883    sqlite3_mutex_enter(db->mutex);
143884    pOld = db->pProfileArg;
143885    db->xProfile = xProfile;
143886    db->pProfileArg = pArg;
143887    sqlite3_mutex_leave(db->mutex);
143888    return pOld;
143889  }
143890  #endif /* SQLITE_OMIT_DEPRECATED */
143891  #endif /* SQLITE_OMIT_TRACE */
143892  
143893  /*
143894  ** Register a function to be invoked when a transaction commits.
143895  ** If the invoked function returns non-zero, then the commit becomes a
143896  ** rollback.
143897  */
143898  SQLITE_API void *sqlite3_commit_hook(
143899    sqlite3 *db,              /* Attach the hook to this database */
143900    int (*xCallback)(void*),  /* Function to invoke on each commit */
143901    void *pArg                /* Argument to the function */
143902  ){
143903    void *pOld;
143904  
143905  #ifdef SQLITE_ENABLE_API_ARMOR
143906    if( !sqlite3SafetyCheckOk(db) ){
143907      (void)SQLITE_MISUSE_BKPT;
143908      return 0;
143909    }
143910  #endif
143911    sqlite3_mutex_enter(db->mutex);
143912    pOld = db->pCommitArg;
143913    db->xCommitCallback = xCallback;
143914    db->pCommitArg = pArg;
143915    sqlite3_mutex_leave(db->mutex);
143916    return pOld;
143917  }
143918  
143919  /*
143920  ** Register a callback to be invoked each time a row is updated,
143921  ** inserted or deleted using this database connection.
143922  */
143923  SQLITE_API void *sqlite3_update_hook(
143924    sqlite3 *db,              /* Attach the hook to this database */
143925    void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
143926    void *pArg                /* Argument to the function */
143927  ){
143928    void *pRet;
143929  
143930  #ifdef SQLITE_ENABLE_API_ARMOR
143931    if( !sqlite3SafetyCheckOk(db) ){
143932      (void)SQLITE_MISUSE_BKPT;
143933      return 0;
143934    }
143935  #endif
143936    sqlite3_mutex_enter(db->mutex);
143937    pRet = db->pUpdateArg;
143938    db->xUpdateCallback = xCallback;
143939    db->pUpdateArg = pArg;
143940    sqlite3_mutex_leave(db->mutex);
143941    return pRet;
143942  }
143943  
143944  /*
143945  ** Register a callback to be invoked each time a transaction is rolled
143946  ** back by this database connection.
143947  */
143948  SQLITE_API void *sqlite3_rollback_hook(
143949    sqlite3 *db,              /* Attach the hook to this database */
143950    void (*xCallback)(void*), /* Callback function */
143951    void *pArg                /* Argument to the function */
143952  ){
143953    void *pRet;
143954  
143955  #ifdef SQLITE_ENABLE_API_ARMOR
143956    if( !sqlite3SafetyCheckOk(db) ){
143957      (void)SQLITE_MISUSE_BKPT;
143958      return 0;
143959    }
143960  #endif
143961    sqlite3_mutex_enter(db->mutex);
143962    pRet = db->pRollbackArg;
143963    db->xRollbackCallback = xCallback;
143964    db->pRollbackArg = pArg;
143965    sqlite3_mutex_leave(db->mutex);
143966    return pRet;
143967  }
143968  
143969  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
143970  /*
143971  ** Register a callback to be invoked each time a row is updated,
143972  ** inserted or deleted using this database connection.
143973  */
143974  SQLITE_API void *sqlite3_preupdate_hook(
143975    sqlite3 *db,              /* Attach the hook to this database */
143976    void(*xCallback)(         /* Callback function */
143977      void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
143978    void *pArg                /* First callback argument */
143979  ){
143980    void *pRet;
143981    sqlite3_mutex_enter(db->mutex);
143982    pRet = db->pPreUpdateArg;
143983    db->xPreUpdateCallback = xCallback;
143984    db->pPreUpdateArg = pArg;
143985    sqlite3_mutex_leave(db->mutex);
143986    return pRet;
143987  }
143988  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
143989  
143990  #ifndef SQLITE_OMIT_WAL
143991  /*
143992  ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
143993  ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
143994  ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
143995  ** wal_autocheckpoint()).
143996  */ 
143997  SQLITE_PRIVATE int sqlite3WalDefaultHook(
143998    void *pClientData,     /* Argument */
143999    sqlite3 *db,           /* Connection */
144000    const char *zDb,       /* Database */
144001    int nFrame             /* Size of WAL */
144002  ){
144003    if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
144004      sqlite3BeginBenignMalloc();
144005      sqlite3_wal_checkpoint(db, zDb);
144006      sqlite3EndBenignMalloc();
144007    }
144008    return SQLITE_OK;
144009  }
144010  #endif /* SQLITE_OMIT_WAL */
144011  
144012  /*
144013  ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
144014  ** a database after committing a transaction if there are nFrame or
144015  ** more frames in the log file. Passing zero or a negative value as the
144016  ** nFrame parameter disables automatic checkpoints entirely.
144017  **
144018  ** The callback registered by this function replaces any existing callback
144019  ** registered using sqlite3_wal_hook(). Likewise, registering a callback
144020  ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
144021  ** configured by this function.
144022  */
144023  SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
144024  #ifdef SQLITE_OMIT_WAL
144025    UNUSED_PARAMETER(db);
144026    UNUSED_PARAMETER(nFrame);
144027  #else
144028  #ifdef SQLITE_ENABLE_API_ARMOR
144029    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
144030  #endif
144031    if( nFrame>0 ){
144032      sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
144033    }else{
144034      sqlite3_wal_hook(db, 0, 0);
144035    }
144036  #endif
144037    return SQLITE_OK;
144038  }
144039  
144040  /*
144041  ** Register a callback to be invoked each time a transaction is written
144042  ** into the write-ahead-log by this database connection.
144043  */
144044  SQLITE_API void *sqlite3_wal_hook(
144045    sqlite3 *db,                    /* Attach the hook to this db handle */
144046    int(*xCallback)(void *, sqlite3*, const char*, int),
144047    void *pArg                      /* First argument passed to xCallback() */
144048  ){
144049  #ifndef SQLITE_OMIT_WAL
144050    void *pRet;
144051  #ifdef SQLITE_ENABLE_API_ARMOR
144052    if( !sqlite3SafetyCheckOk(db) ){
144053      (void)SQLITE_MISUSE_BKPT;
144054      return 0;
144055    }
144056  #endif
144057    sqlite3_mutex_enter(db->mutex);
144058    pRet = db->pWalArg;
144059    db->xWalCallback = xCallback;
144060    db->pWalArg = pArg;
144061    sqlite3_mutex_leave(db->mutex);
144062    return pRet;
144063  #else
144064    return 0;
144065  #endif
144066  }
144067  
144068  /*
144069  ** Checkpoint database zDb.
144070  */
144071  SQLITE_API int sqlite3_wal_checkpoint_v2(
144072    sqlite3 *db,                    /* Database handle */
144073    const char *zDb,                /* Name of attached database (or NULL) */
144074    int eMode,                      /* SQLITE_CHECKPOINT_* value */
144075    int *pnLog,                     /* OUT: Size of WAL log in frames */
144076    int *pnCkpt                     /* OUT: Total number of frames checkpointed */
144077  ){
144078  #ifdef SQLITE_OMIT_WAL
144079    return SQLITE_OK;
144080  #else
144081    int rc;                         /* Return code */
144082    int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
144083  
144084  #ifdef SQLITE_ENABLE_API_ARMOR
144085    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
144086  #endif
144087  
144088    /* Initialize the output variables to -1 in case an error occurs. */
144089    if( pnLog ) *pnLog = -1;
144090    if( pnCkpt ) *pnCkpt = -1;
144091  
144092    assert( SQLITE_CHECKPOINT_PASSIVE==0 );
144093    assert( SQLITE_CHECKPOINT_FULL==1 );
144094    assert( SQLITE_CHECKPOINT_RESTART==2 );
144095    assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
144096    if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
144097      /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
144098      ** mode: */
144099      return SQLITE_MISUSE;
144100    }
144101  
144102    sqlite3_mutex_enter(db->mutex);
144103    if( zDb && zDb[0] ){
144104      iDb = sqlite3FindDbName(db, zDb);
144105    }
144106    if( iDb<0 ){
144107      rc = SQLITE_ERROR;
144108      sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
144109    }else{
144110      db->busyHandler.nBusy = 0;
144111      rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
144112      sqlite3Error(db, rc);
144113    }
144114    rc = sqlite3ApiExit(db, rc);
144115  
144116    /* If there are no active statements, clear the interrupt flag at this
144117    ** point.  */
144118    if( db->nVdbeActive==0 ){
144119      db->u1.isInterrupted = 0;
144120    }
144121  
144122    sqlite3_mutex_leave(db->mutex);
144123    return rc;
144124  #endif
144125  }
144126  
144127  
144128  /*
144129  ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
144130  ** to contains a zero-length string, all attached databases are 
144131  ** checkpointed.
144132  */
144133  SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
144134    /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
144135    ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
144136    return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
144137  }
144138  
144139  #ifndef SQLITE_OMIT_WAL
144140  /*
144141  ** Run a checkpoint on database iDb. This is a no-op if database iDb is
144142  ** not currently open in WAL mode.
144143  **
144144  ** If a transaction is open on the database being checkpointed, this 
144145  ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
144146  ** an error occurs while running the checkpoint, an SQLite error code is 
144147  ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
144148  **
144149  ** The mutex on database handle db should be held by the caller. The mutex
144150  ** associated with the specific b-tree being checkpointed is taken by
144151  ** this function while the checkpoint is running.
144152  **
144153  ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
144154  ** checkpointed. If an error is encountered it is returned immediately -
144155  ** no attempt is made to checkpoint any remaining databases.
144156  **
144157  ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
144158  ** or TRUNCATE.
144159  */
144160  SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
144161    int rc = SQLITE_OK;             /* Return code */
144162    int i;                          /* Used to iterate through attached dbs */
144163    int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
144164  
144165    assert( sqlite3_mutex_held(db->mutex) );
144166    assert( !pnLog || *pnLog==-1 );
144167    assert( !pnCkpt || *pnCkpt==-1 );
144168  
144169    for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
144170      if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
144171        rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
144172        pnLog = 0;
144173        pnCkpt = 0;
144174        if( rc==SQLITE_BUSY ){
144175          bBusy = 1;
144176          rc = SQLITE_OK;
144177        }
144178      }
144179    }
144180  
144181    return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
144182  }
144183  #endif /* SQLITE_OMIT_WAL */
144184  
144185  /*
144186  ** This function returns true if main-memory should be used instead of
144187  ** a temporary file for transient pager files and statement journals.
144188  ** The value returned depends on the value of db->temp_store (runtime
144189  ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
144190  ** following table describes the relationship between these two values
144191  ** and this functions return value.
144192  **
144193  **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
144194  **   -----------------     --------------     ------------------------------
144195  **   0                     any                file      (return 0)
144196  **   1                     1                  file      (return 0)
144197  **   1                     2                  memory    (return 1)
144198  **   1                     0                  file      (return 0)
144199  **   2                     1                  file      (return 0)
144200  **   2                     2                  memory    (return 1)
144201  **   2                     0                  memory    (return 1)
144202  **   3                     any                memory    (return 1)
144203  */
144204  SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
144205  #if SQLITE_TEMP_STORE==1
144206    return ( db->temp_store==2 );
144207  #endif
144208  #if SQLITE_TEMP_STORE==2
144209    return ( db->temp_store!=1 );
144210  #endif
144211  #if SQLITE_TEMP_STORE==3
144212    UNUSED_PARAMETER(db);
144213    return 1;
144214  #endif
144215  #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
144216    UNUSED_PARAMETER(db);
144217    return 0;
144218  #endif
144219  }
144220  
144221  /*
144222  ** Return UTF-8 encoded English language explanation of the most recent
144223  ** error.
144224  */
144225  SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
144226    const char *z;
144227    if( !db ){
144228      return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
144229    }
144230    if( !sqlite3SafetyCheckSickOrOk(db) ){
144231      return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
144232    }
144233    sqlite3_mutex_enter(db->mutex);
144234    if( db->mallocFailed ){
144235      z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
144236    }else{
144237      testcase( db->pErr==0 );
144238      z = (char*)sqlite3_value_text(db->pErr);
144239      assert( !db->mallocFailed );
144240      if( z==0 ){
144241        z = sqlite3ErrStr(db->errCode);
144242      }
144243    }
144244    sqlite3_mutex_leave(db->mutex);
144245    return z;
144246  }
144247  
144248  #ifndef SQLITE_OMIT_UTF16
144249  /*
144250  ** Return UTF-16 encoded English language explanation of the most recent
144251  ** error.
144252  */
144253  SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
144254    static const u16 outOfMem[] = {
144255      'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
144256    };
144257    static const u16 misuse[] = {
144258      'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
144259      'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
144260      'm', 'i', 's', 'u', 's', 'e', 0
144261    };
144262  
144263    const void *z;
144264    if( !db ){
144265      return (void *)outOfMem;
144266    }
144267    if( !sqlite3SafetyCheckSickOrOk(db) ){
144268      return (void *)misuse;
144269    }
144270    sqlite3_mutex_enter(db->mutex);
144271    if( db->mallocFailed ){
144272      z = (void *)outOfMem;
144273    }else{
144274      z = sqlite3_value_text16(db->pErr);
144275      if( z==0 ){
144276        sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
144277        z = sqlite3_value_text16(db->pErr);
144278      }
144279      /* A malloc() may have failed within the call to sqlite3_value_text16()
144280      ** above. If this is the case, then the db->mallocFailed flag needs to
144281      ** be cleared before returning. Do this directly, instead of via
144282      ** sqlite3ApiExit(), to avoid setting the database handle error message.
144283      */
144284      sqlite3OomClear(db);
144285    }
144286    sqlite3_mutex_leave(db->mutex);
144287    return z;
144288  }
144289  #endif /* SQLITE_OMIT_UTF16 */
144290  
144291  /*
144292  ** Return the most recent error code generated by an SQLite routine. If NULL is
144293  ** passed to this function, we assume a malloc() failed during sqlite3_open().
144294  */
144295  SQLITE_API int sqlite3_errcode(sqlite3 *db){
144296    if( db && !sqlite3SafetyCheckSickOrOk(db) ){
144297      return SQLITE_MISUSE_BKPT;
144298    }
144299    if( !db || db->mallocFailed ){
144300      return SQLITE_NOMEM_BKPT;
144301    }
144302    return db->errCode & db->errMask;
144303  }
144304  SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
144305    if( db && !sqlite3SafetyCheckSickOrOk(db) ){
144306      return SQLITE_MISUSE_BKPT;
144307    }
144308    if( !db || db->mallocFailed ){
144309      return SQLITE_NOMEM_BKPT;
144310    }
144311    return db->errCode;
144312  }
144313  SQLITE_API int sqlite3_system_errno(sqlite3 *db){
144314    return db ? db->iSysErrno : 0;
144315  }  
144316  
144317  /*
144318  ** Return a string that describes the kind of error specified in the
144319  ** argument.  For now, this simply calls the internal sqlite3ErrStr()
144320  ** function.
144321  */
144322  SQLITE_API const char *sqlite3_errstr(int rc){
144323    return sqlite3ErrStr(rc);
144324  }
144325  
144326  /*
144327  ** Create a new collating function for database "db".  The name is zName
144328  ** and the encoding is enc.
144329  */
144330  static int createCollation(
144331    sqlite3* db,
144332    const char *zName, 
144333    u8 enc,
144334    void* pCtx,
144335    int(*xCompare)(void*,int,const void*,int,const void*),
144336    void(*xDel)(void*)
144337  ){
144338    CollSeq *pColl;
144339    int enc2;
144340    
144341    assert( sqlite3_mutex_held(db->mutex) );
144342  
144343    /* If SQLITE_UTF16 is specified as the encoding type, transform this
144344    ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
144345    ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
144346    */
144347    enc2 = enc;
144348    testcase( enc2==SQLITE_UTF16 );
144349    testcase( enc2==SQLITE_UTF16_ALIGNED );
144350    if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
144351      enc2 = SQLITE_UTF16NATIVE;
144352    }
144353    if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
144354      return SQLITE_MISUSE_BKPT;
144355    }
144356  
144357    /* Check if this call is removing or replacing an existing collation 
144358    ** sequence. If so, and there are active VMs, return busy. If there
144359    ** are no active VMs, invalidate any pre-compiled statements.
144360    */
144361    pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
144362    if( pColl && pColl->xCmp ){
144363      if( db->nVdbeActive ){
144364        sqlite3ErrorWithMsg(db, SQLITE_BUSY, 
144365          "unable to delete/modify collation sequence due to active statements");
144366        return SQLITE_BUSY;
144367      }
144368      sqlite3ExpirePreparedStatements(db);
144369  
144370      /* If collation sequence pColl was created directly by a call to
144371      ** sqlite3_create_collation, and not generated by synthCollSeq(),
144372      ** then any copies made by synthCollSeq() need to be invalidated.
144373      ** Also, collation destructor - CollSeq.xDel() - function may need
144374      ** to be called.
144375      */ 
144376      if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
144377        CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
144378        int j;
144379        for(j=0; j<3; j++){
144380          CollSeq *p = &aColl[j];
144381          if( p->enc==pColl->enc ){
144382            if( p->xDel ){
144383              p->xDel(p->pUser);
144384            }
144385            p->xCmp = 0;
144386          }
144387        }
144388      }
144389    }
144390  
144391    pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
144392    if( pColl==0 ) return SQLITE_NOMEM_BKPT;
144393    pColl->xCmp = xCompare;
144394    pColl->pUser = pCtx;
144395    pColl->xDel = xDel;
144396    pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
144397    sqlite3Error(db, SQLITE_OK);
144398    return SQLITE_OK;
144399  }
144400  
144401  
144402  /*
144403  ** This array defines hard upper bounds on limit values.  The
144404  ** initializer must be kept in sync with the SQLITE_LIMIT_*
144405  ** #defines in sqlite3.h.
144406  */
144407  static const int aHardLimit[] = {
144408    SQLITE_MAX_LENGTH,
144409    SQLITE_MAX_SQL_LENGTH,
144410    SQLITE_MAX_COLUMN,
144411    SQLITE_MAX_EXPR_DEPTH,
144412    SQLITE_MAX_COMPOUND_SELECT,
144413    SQLITE_MAX_VDBE_OP,
144414    SQLITE_MAX_FUNCTION_ARG,
144415    SQLITE_MAX_ATTACHED,
144416    SQLITE_MAX_LIKE_PATTERN_LENGTH,
144417    SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
144418    SQLITE_MAX_TRIGGER_DEPTH,
144419    SQLITE_MAX_WORKER_THREADS,
144420  };
144421  
144422  /*
144423  ** Make sure the hard limits are set to reasonable values
144424  */
144425  #if SQLITE_MAX_LENGTH<100
144426  # error SQLITE_MAX_LENGTH must be at least 100
144427  #endif
144428  #if SQLITE_MAX_SQL_LENGTH<100
144429  # error SQLITE_MAX_SQL_LENGTH must be at least 100
144430  #endif
144431  #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
144432  # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
144433  #endif
144434  #if SQLITE_MAX_COMPOUND_SELECT<2
144435  # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
144436  #endif
144437  #if SQLITE_MAX_VDBE_OP<40
144438  # error SQLITE_MAX_VDBE_OP must be at least 40
144439  #endif
144440  #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
144441  # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
144442  #endif
144443  #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
144444  # error SQLITE_MAX_ATTACHED must be between 0 and 125
144445  #endif
144446  #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
144447  # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
144448  #endif
144449  #if SQLITE_MAX_COLUMN>32767
144450  # error SQLITE_MAX_COLUMN must not exceed 32767
144451  #endif
144452  #if SQLITE_MAX_TRIGGER_DEPTH<1
144453  # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
144454  #endif
144455  #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
144456  # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
144457  #endif
144458  
144459  
144460  /*
144461  ** Change the value of a limit.  Report the old value.
144462  ** If an invalid limit index is supplied, report -1.
144463  ** Make no changes but still report the old value if the
144464  ** new limit is negative.
144465  **
144466  ** A new lower limit does not shrink existing constructs.
144467  ** It merely prevents new constructs that exceed the limit
144468  ** from forming.
144469  */
144470  SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
144471    int oldLimit;
144472  
144473  #ifdef SQLITE_ENABLE_API_ARMOR
144474    if( !sqlite3SafetyCheckOk(db) ){
144475      (void)SQLITE_MISUSE_BKPT;
144476      return -1;
144477    }
144478  #endif
144479  
144480    /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
144481    ** there is a hard upper bound set at compile-time by a C preprocessor
144482    ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
144483    ** "_MAX_".)
144484    */
144485    assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
144486    assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
144487    assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
144488    assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
144489    assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
144490    assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
144491    assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
144492    assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
144493    assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
144494                                                 SQLITE_MAX_LIKE_PATTERN_LENGTH );
144495    assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
144496    assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
144497    assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
144498    assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
144499  
144500  
144501    if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
144502      return -1;
144503    }
144504    oldLimit = db->aLimit[limitId];
144505    if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
144506      if( newLimit>aHardLimit[limitId] ){
144507        newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
144508      }
144509      db->aLimit[limitId] = newLimit;
144510    }
144511    return oldLimit;                     /* IMP: R-53341-35419 */
144512  }
144513  
144514  /*
144515  ** This function is used to parse both URIs and non-URI filenames passed by the
144516  ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
144517  ** URIs specified as part of ATTACH statements.
144518  **
144519  ** The first argument to this function is the name of the VFS to use (or
144520  ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
144521  ** query parameter. The second argument contains the URI (or non-URI filename)
144522  ** itself. When this function is called the *pFlags variable should contain
144523  ** the default flags to open the database handle with. The value stored in
144524  ** *pFlags may be updated before returning if the URI filename contains 
144525  ** "cache=xxx" or "mode=xxx" query parameters.
144526  **
144527  ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
144528  ** the VFS that should be used to open the database file. *pzFile is set to
144529  ** point to a buffer containing the name of the file to open. It is the 
144530  ** responsibility of the caller to eventually call sqlite3_free() to release
144531  ** this buffer.
144532  **
144533  ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
144534  ** may be set to point to a buffer containing an English language error 
144535  ** message. It is the responsibility of the caller to eventually release
144536  ** this buffer by calling sqlite3_free().
144537  */
144538  SQLITE_PRIVATE int sqlite3ParseUri(
144539    const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
144540    const char *zUri,               /* Nul-terminated URI to parse */
144541    unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
144542    sqlite3_vfs **ppVfs,            /* OUT: VFS to use */ 
144543    char **pzFile,                  /* OUT: Filename component of URI */
144544    char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
144545  ){
144546    int rc = SQLITE_OK;
144547    unsigned int flags = *pFlags;
144548    const char *zVfs = zDefaultVfs;
144549    char *zFile;
144550    char c;
144551    int nUri = sqlite3Strlen30(zUri);
144552  
144553    assert( *pzErrMsg==0 );
144554  
144555    if( ((flags & SQLITE_OPEN_URI)             /* IMP: R-48725-32206 */
144556              || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
144557     && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
144558    ){
144559      char *zOpt;
144560      int eState;                   /* Parser state when parsing URI */
144561      int iIn;                      /* Input character index */
144562      int iOut = 0;                 /* Output character index */
144563      u64 nByte = nUri+2;           /* Bytes of space to allocate */
144564  
144565      /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen 
144566      ** method that there may be extra parameters following the file-name.  */
144567      flags |= SQLITE_OPEN_URI;
144568  
144569      for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
144570      zFile = sqlite3_malloc64(nByte);
144571      if( !zFile ) return SQLITE_NOMEM_BKPT;
144572  
144573      iIn = 5;
144574  #ifdef SQLITE_ALLOW_URI_AUTHORITY
144575      if( strncmp(zUri+5, "///", 3)==0 ){
144576        iIn = 7;
144577        /* The following condition causes URIs with five leading / characters
144578        ** like file://///host/path to be converted into UNCs like //host/path.
144579        ** The correct URI for that UNC has only two or four leading / characters
144580        ** file://host/path or file:////host/path.  But 5 leading slashes is a 
144581        ** common error, we are told, so we handle it as a special case. */
144582        if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
144583      }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
144584        iIn = 16;
144585      }
144586  #else
144587      /* Discard the scheme and authority segments of the URI. */
144588      if( zUri[5]=='/' && zUri[6]=='/' ){
144589        iIn = 7;
144590        while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
144591        if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
144592          *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", 
144593              iIn-7, &zUri[7]);
144594          rc = SQLITE_ERROR;
144595          goto parse_uri_out;
144596        }
144597      }
144598  #endif
144599  
144600      /* Copy the filename and any query parameters into the zFile buffer. 
144601      ** Decode %HH escape codes along the way. 
144602      **
144603      ** Within this loop, variable eState may be set to 0, 1 or 2, depending
144604      ** on the parsing context. As follows:
144605      **
144606      **   0: Parsing file-name.
144607      **   1: Parsing name section of a name=value query parameter.
144608      **   2: Parsing value section of a name=value query parameter.
144609      */
144610      eState = 0;
144611      while( (c = zUri[iIn])!=0 && c!='#' ){
144612        iIn++;
144613        if( c=='%' 
144614         && sqlite3Isxdigit(zUri[iIn]) 
144615         && sqlite3Isxdigit(zUri[iIn+1]) 
144616        ){
144617          int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
144618          octet += sqlite3HexToInt(zUri[iIn++]);
144619  
144620          assert( octet>=0 && octet<256 );
144621          if( octet==0 ){
144622  #ifndef SQLITE_ENABLE_URI_00_ERROR
144623            /* This branch is taken when "%00" appears within the URI. In this
144624            ** case we ignore all text in the remainder of the path, name or
144625            ** value currently being parsed. So ignore the current character
144626            ** and skip to the next "?", "=" or "&", as appropriate. */
144627            while( (c = zUri[iIn])!=0 && c!='#' 
144628                && (eState!=0 || c!='?')
144629                && (eState!=1 || (c!='=' && c!='&'))
144630                && (eState!=2 || c!='&')
144631            ){
144632              iIn++;
144633            }
144634            continue;
144635  #else
144636            /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
144637            *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
144638            rc = SQLITE_ERROR;
144639            goto parse_uri_out;
144640  #endif
144641          }
144642          c = octet;
144643        }else if( eState==1 && (c=='&' || c=='=') ){
144644          if( zFile[iOut-1]==0 ){
144645            /* An empty option name. Ignore this option altogether. */
144646            while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
144647            continue;
144648          }
144649          if( c=='&' ){
144650            zFile[iOut++] = '\0';
144651          }else{
144652            eState = 2;
144653          }
144654          c = 0;
144655        }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
144656          c = 0;
144657          eState = 1;
144658        }
144659        zFile[iOut++] = c;
144660      }
144661      if( eState==1 ) zFile[iOut++] = '\0';
144662      zFile[iOut++] = '\0';
144663      zFile[iOut++] = '\0';
144664  
144665      /* Check if there were any options specified that should be interpreted 
144666      ** here. Options that are interpreted here include "vfs" and those that
144667      ** correspond to flags that may be passed to the sqlite3_open_v2()
144668      ** method. */
144669      zOpt = &zFile[sqlite3Strlen30(zFile)+1];
144670      while( zOpt[0] ){
144671        int nOpt = sqlite3Strlen30(zOpt);
144672        char *zVal = &zOpt[nOpt+1];
144673        int nVal = sqlite3Strlen30(zVal);
144674  
144675        if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
144676          zVfs = zVal;
144677        }else{
144678          struct OpenMode {
144679            const char *z;
144680            int mode;
144681          } *aMode = 0;
144682          char *zModeType = 0;
144683          int mask = 0;
144684          int limit = 0;
144685  
144686          if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
144687            static struct OpenMode aCacheMode[] = {
144688              { "shared",  SQLITE_OPEN_SHAREDCACHE },
144689              { "private", SQLITE_OPEN_PRIVATECACHE },
144690              { 0, 0 }
144691            };
144692  
144693            mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
144694            aMode = aCacheMode;
144695            limit = mask;
144696            zModeType = "cache";
144697          }
144698          if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
144699            static struct OpenMode aOpenMode[] = {
144700              { "ro",  SQLITE_OPEN_READONLY },
144701              { "rw",  SQLITE_OPEN_READWRITE }, 
144702              { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
144703              { "memory", SQLITE_OPEN_MEMORY },
144704              { 0, 0 }
144705            };
144706  
144707            mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
144708                     | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
144709            aMode = aOpenMode;
144710            limit = mask & flags;
144711            zModeType = "access";
144712          }
144713  
144714          if( aMode ){
144715            int i;
144716            int mode = 0;
144717            for(i=0; aMode[i].z; i++){
144718              const char *z = aMode[i].z;
144719              if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
144720                mode = aMode[i].mode;
144721                break;
144722              }
144723            }
144724            if( mode==0 ){
144725              *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
144726              rc = SQLITE_ERROR;
144727              goto parse_uri_out;
144728            }
144729            if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
144730              *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
144731                                          zModeType, zVal);
144732              rc = SQLITE_PERM;
144733              goto parse_uri_out;
144734            }
144735            flags = (flags & ~mask) | mode;
144736          }
144737        }
144738  
144739        zOpt = &zVal[nVal+1];
144740      }
144741  
144742    }else{
144743      zFile = sqlite3_malloc64(nUri+2);
144744      if( !zFile ) return SQLITE_NOMEM_BKPT;
144745      if( nUri ){
144746        memcpy(zFile, zUri, nUri);
144747      }
144748      zFile[nUri] = '\0';
144749      zFile[nUri+1] = '\0';
144750      flags &= ~SQLITE_OPEN_URI;
144751    }
144752  
144753    *ppVfs = sqlite3_vfs_find(zVfs);
144754    if( *ppVfs==0 ){
144755      *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
144756      rc = SQLITE_ERROR;
144757    }
144758   parse_uri_out:
144759    if( rc!=SQLITE_OK ){
144760      sqlite3_free(zFile);
144761      zFile = 0;
144762    }
144763    *pFlags = flags;
144764    *pzFile = zFile;
144765    return rc;
144766  }
144767  
144768  
144769  /*
144770  ** This routine does the work of opening a database on behalf of
144771  ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
144772  ** is UTF-8 encoded.
144773  */
144774  static int openDatabase(
144775    const char *zFilename, /* Database filename UTF-8 encoded */
144776    sqlite3 **ppDb,        /* OUT: Returned database handle */
144777    unsigned int flags,    /* Operational flags */
144778    const char *zVfs       /* Name of the VFS to use */
144779  ){
144780    sqlite3 *db;                    /* Store allocated handle here */
144781    int rc;                         /* Return code */
144782    int isThreadsafe;               /* True for threadsafe connections */
144783    char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
144784    char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
144785  
144786  #ifdef SQLITE_ENABLE_API_ARMOR
144787    if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
144788  #endif
144789    *ppDb = 0;
144790  #ifndef SQLITE_OMIT_AUTOINIT
144791    rc = sqlite3_initialize();
144792    if( rc ) return rc;
144793  #endif
144794  
144795    if( sqlite3GlobalConfig.bCoreMutex==0 ){
144796      isThreadsafe = 0;
144797    }else if( flags & SQLITE_OPEN_NOMUTEX ){
144798      isThreadsafe = 0;
144799    }else if( flags & SQLITE_OPEN_FULLMUTEX ){
144800      isThreadsafe = 1;
144801    }else{
144802      isThreadsafe = sqlite3GlobalConfig.bFullMutex;
144803    }
144804    if( flags & SQLITE_OPEN_PRIVATECACHE ){
144805      flags &= ~SQLITE_OPEN_SHAREDCACHE;
144806    }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
144807      flags |= SQLITE_OPEN_SHAREDCACHE;
144808    }
144809  
144810    /* Remove harmful bits from the flags parameter
144811    **
144812    ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
144813    ** dealt with in the previous code block.  Besides these, the only
144814    ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
144815    ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
144816    ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
144817    ** off all other flags.
144818    */
144819    flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
144820                 SQLITE_OPEN_EXCLUSIVE |
144821                 SQLITE_OPEN_MAIN_DB |
144822                 SQLITE_OPEN_TEMP_DB | 
144823                 SQLITE_OPEN_TRANSIENT_DB | 
144824                 SQLITE_OPEN_MAIN_JOURNAL | 
144825                 SQLITE_OPEN_TEMP_JOURNAL | 
144826                 SQLITE_OPEN_SUBJOURNAL | 
144827                 SQLITE_OPEN_MASTER_JOURNAL |
144828                 SQLITE_OPEN_NOMUTEX |
144829                 SQLITE_OPEN_FULLMUTEX |
144830                 SQLITE_OPEN_WAL
144831               );
144832  
144833    /* Allocate the sqlite data structure */
144834    db = sqlite3MallocZero( sizeof(sqlite3) );
144835    if( db==0 ) goto opendb_out;
144836    if( isThreadsafe ){
144837      db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
144838      if( db->mutex==0 ){
144839        sqlite3_free(db);
144840        db = 0;
144841        goto opendb_out;
144842      }
144843    }
144844    sqlite3_mutex_enter(db->mutex);
144845    db->errMask = 0xff;
144846    db->nDb = 2;
144847    db->magic = SQLITE_MAGIC_BUSY;
144848    db->aDb = db->aDbStatic;
144849  
144850    assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
144851    memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
144852    db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
144853    db->autoCommit = 1;
144854    db->nextAutovac = -1;
144855    db->szMmap = sqlite3GlobalConfig.szMmap;
144856    db->nextPagesize = 0;
144857    db->nMaxSorterMmap = 0x7FFFFFFF;
144858    db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
144859  #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
144860                   | SQLITE_AutoIndex
144861  #endif
144862  #if SQLITE_DEFAULT_CKPTFULLFSYNC
144863                   | SQLITE_CkptFullFSync
144864  #endif
144865  #if SQLITE_DEFAULT_FILE_FORMAT<4
144866                   | SQLITE_LegacyFileFmt
144867  #endif
144868  #ifdef SQLITE_ENABLE_LOAD_EXTENSION
144869                   | SQLITE_LoadExtension
144870  #endif
144871  #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
144872                   | SQLITE_RecTriggers
144873  #endif
144874  #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
144875                   | SQLITE_ForeignKeys
144876  #endif
144877  #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
144878                   | SQLITE_ReverseOrder
144879  #endif
144880  #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
144881                   | SQLITE_CellSizeCk
144882  #endif
144883  #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
144884                   | SQLITE_Fts3Tokenizer
144885  #endif
144886  #if defined(SQLITE_ENABLE_QPSG)
144887                   | SQLITE_EnableQPSG
144888  #endif
144889        ;
144890    sqlite3HashInit(&db->aCollSeq);
144891  #ifndef SQLITE_OMIT_VIRTUALTABLE
144892    sqlite3HashInit(&db->aModule);
144893  #endif
144894  
144895    /* Add the default collation sequence BINARY. BINARY works for both UTF-8
144896    ** and UTF-16, so add a version for each to avoid any unnecessary
144897    ** conversions. The only error that can occur here is a malloc() failure.
144898    **
144899    ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
144900    ** functions:
144901    */
144902    createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
144903    createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
144904    createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
144905    createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
144906    createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
144907    if( db->mallocFailed ){
144908      goto opendb_out;
144909    }
144910    /* EVIDENCE-OF: R-08308-17224 The default collating function for all
144911    ** strings is BINARY. 
144912    */
144913    db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
144914    assert( db->pDfltColl!=0 );
144915  
144916    /* Parse the filename/URI argument
144917    **
144918    ** Only allow sensible combinations of bits in the flags argument.  
144919    ** Throw an error if any non-sense combination is used.  If we
144920    ** do not block illegal combinations here, it could trigger
144921    ** assert() statements in deeper layers.  Sensible combinations
144922    ** are:
144923    **
144924    **  1:  SQLITE_OPEN_READONLY
144925    **  2:  SQLITE_OPEN_READWRITE
144926    **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
144927    */
144928    db->openFlags = flags;
144929    assert( SQLITE_OPEN_READONLY  == 0x01 );
144930    assert( SQLITE_OPEN_READWRITE == 0x02 );
144931    assert( SQLITE_OPEN_CREATE    == 0x04 );
144932    testcase( (1<<(flags&7))==0x02 ); /* READONLY */
144933    testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
144934    testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
144935    if( ((1<<(flags&7)) & 0x46)==0 ){
144936      rc = SQLITE_MISUSE_BKPT;  /* IMP: R-65497-44594 */
144937    }else{
144938      rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
144939    }
144940    if( rc!=SQLITE_OK ){
144941      if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
144942      sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
144943      sqlite3_free(zErrMsg);
144944      goto opendb_out;
144945    }
144946  
144947    /* Open the backend database driver */
144948    rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
144949                          flags | SQLITE_OPEN_MAIN_DB);
144950    if( rc!=SQLITE_OK ){
144951      if( rc==SQLITE_IOERR_NOMEM ){
144952        rc = SQLITE_NOMEM_BKPT;
144953      }
144954      sqlite3Error(db, rc);
144955      goto opendb_out;
144956    }
144957    sqlite3BtreeEnter(db->aDb[0].pBt);
144958    db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
144959    if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
144960    sqlite3BtreeLeave(db->aDb[0].pBt);
144961    db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
144962  
144963    /* The default safety_level for the main database is FULL; for the temp
144964    ** database it is OFF. This matches the pager layer defaults.  
144965    */
144966    db->aDb[0].zDbSName = "main";
144967    db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
144968    db->aDb[1].zDbSName = "temp";
144969    db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
144970  
144971    db->magic = SQLITE_MAGIC_OPEN;
144972    if( db->mallocFailed ){
144973      goto opendb_out;
144974    }
144975  
144976    /* Register all built-in functions, but do not attempt to read the
144977    ** database schema yet. This is delayed until the first time the database
144978    ** is accessed.
144979    */
144980    sqlite3Error(db, SQLITE_OK);
144981    sqlite3RegisterPerConnectionBuiltinFunctions(db);
144982    rc = sqlite3_errcode(db);
144983  
144984  #ifdef SQLITE_ENABLE_FTS5
144985    /* Register any built-in FTS5 module before loading the automatic
144986    ** extensions. This allows automatic extensions to register FTS5 
144987    ** tokenizers and auxiliary functions.  */
144988    if( !db->mallocFailed && rc==SQLITE_OK ){
144989      rc = sqlite3Fts5Init(db);
144990    }
144991  #endif
144992  
144993    /* Load automatic extensions - extensions that have been registered
144994    ** using the sqlite3_automatic_extension() API.
144995    */
144996    if( rc==SQLITE_OK ){
144997      sqlite3AutoLoadExtensions(db);
144998      rc = sqlite3_errcode(db);
144999      if( rc!=SQLITE_OK ){
145000        goto opendb_out;
145001      }
145002    }
145003  
145004  #ifdef SQLITE_ENABLE_FTS1
145005    if( !db->mallocFailed ){
145006      extern int sqlite3Fts1Init(sqlite3*);
145007      rc = sqlite3Fts1Init(db);
145008    }
145009  #endif
145010  
145011  #ifdef SQLITE_ENABLE_FTS2
145012    if( !db->mallocFailed && rc==SQLITE_OK ){
145013      extern int sqlite3Fts2Init(sqlite3*);
145014      rc = sqlite3Fts2Init(db);
145015    }
145016  #endif
145017  
145018  #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
145019    if( !db->mallocFailed && rc==SQLITE_OK ){
145020      rc = sqlite3Fts3Init(db);
145021    }
145022  #endif
145023  
145024  #ifdef SQLITE_ENABLE_ICU
145025    if( !db->mallocFailed && rc==SQLITE_OK ){
145026      rc = sqlite3IcuInit(db);
145027    }
145028  #endif
145029  
145030  #ifdef SQLITE_ENABLE_RTREE
145031    if( !db->mallocFailed && rc==SQLITE_OK){
145032      rc = sqlite3RtreeInit(db);
145033    }
145034  #endif
145035  
145036  #ifdef SQLITE_ENABLE_DBPAGE_VTAB
145037    if( !db->mallocFailed && rc==SQLITE_OK){
145038      rc = sqlite3DbpageRegister(db);
145039    }
145040  #endif
145041  
145042  #ifdef SQLITE_ENABLE_DBSTAT_VTAB
145043    if( !db->mallocFailed && rc==SQLITE_OK){
145044      rc = sqlite3DbstatRegister(db);
145045    }
145046  #endif
145047  
145048  #ifdef SQLITE_ENABLE_JSON1
145049    if( !db->mallocFailed && rc==SQLITE_OK){
145050      rc = sqlite3Json1Init(db);
145051    }
145052  #endif
145053  
145054  #ifdef SQLITE_ENABLE_STMTVTAB
145055    if( !db->mallocFailed && rc==SQLITE_OK){
145056      rc = sqlite3StmtVtabInit(db);
145057    }
145058  #endif
145059  
145060    /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
145061    ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
145062    ** mode.  Doing nothing at all also makes NORMAL the default.
145063    */
145064  #ifdef SQLITE_DEFAULT_LOCKING_MODE
145065    db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
145066    sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
145067                            SQLITE_DEFAULT_LOCKING_MODE);
145068  #endif
145069  
145070    if( rc ) sqlite3Error(db, rc);
145071  
145072    /* Enable the lookaside-malloc subsystem */
145073    setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
145074                          sqlite3GlobalConfig.nLookaside);
145075  
145076    sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
145077  
145078  opendb_out:
145079    if( db ){
145080      assert( db->mutex!=0 || isThreadsafe==0
145081             || sqlite3GlobalConfig.bFullMutex==0 );
145082      sqlite3_mutex_leave(db->mutex);
145083    }
145084    rc = sqlite3_errcode(db);
145085    assert( db!=0 || rc==SQLITE_NOMEM );
145086    if( rc==SQLITE_NOMEM ){
145087      sqlite3_close(db);
145088      db = 0;
145089    }else if( rc!=SQLITE_OK ){
145090      db->magic = SQLITE_MAGIC_SICK;
145091    }
145092    *ppDb = db;
145093  #ifdef SQLITE_ENABLE_SQLLOG
145094    if( sqlite3GlobalConfig.xSqllog ){
145095      /* Opening a db handle. Fourth parameter is passed 0. */
145096      void *pArg = sqlite3GlobalConfig.pSqllogArg;
145097      sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
145098    }
145099  #endif
145100  #if defined(SQLITE_HAS_CODEC)
145101    if( rc==SQLITE_OK ){
145102      const char *zKey;
145103      if( (zKey = sqlite3_uri_parameter(zOpen, "hexkey"))!=0 && zKey[0] ){
145104        u8 iByte;
145105        int i;
145106        char zDecoded[40];
145107        for(i=0, iByte=0; i<sizeof(zDecoded)*2 && sqlite3Isxdigit(zKey[i]); i++){
145108          iByte = (iByte<<4) + sqlite3HexToInt(zKey[i]);
145109          if( (i&1)!=0 ) zDecoded[i/2] = iByte;
145110        }
145111        sqlite3_key_v2(db, 0, zDecoded, i/2);
145112      }else if( (zKey = sqlite3_uri_parameter(zOpen, "key"))!=0 ){
145113        sqlite3_key_v2(db, 0, zKey, sqlite3Strlen30(zKey));
145114      }
145115    }
145116  #endif
145117    sqlite3_free(zOpen);
145118    return rc & 0xff;
145119  }
145120  
145121  /*
145122  ** Open a new database handle.
145123  */
145124  SQLITE_API int sqlite3_open(
145125    const char *zFilename, 
145126    sqlite3 **ppDb 
145127  ){
145128    return openDatabase(zFilename, ppDb,
145129                        SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
145130  }
145131  SQLITE_API int sqlite3_open_v2(
145132    const char *filename,   /* Database filename (UTF-8) */
145133    sqlite3 **ppDb,         /* OUT: SQLite db handle */
145134    int flags,              /* Flags */
145135    const char *zVfs        /* Name of VFS module to use */
145136  ){
145137    return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
145138  }
145139  
145140  #ifndef SQLITE_OMIT_UTF16
145141  /*
145142  ** Open a new database handle.
145143  */
145144  SQLITE_API int sqlite3_open16(
145145    const void *zFilename, 
145146    sqlite3 **ppDb
145147  ){
145148    char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
145149    sqlite3_value *pVal;
145150    int rc;
145151  
145152  #ifdef SQLITE_ENABLE_API_ARMOR
145153    if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
145154  #endif
145155    *ppDb = 0;
145156  #ifndef SQLITE_OMIT_AUTOINIT
145157    rc = sqlite3_initialize();
145158    if( rc ) return rc;
145159  #endif
145160    if( zFilename==0 ) zFilename = "\000\000";
145161    pVal = sqlite3ValueNew(0);
145162    sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
145163    zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
145164    if( zFilename8 ){
145165      rc = openDatabase(zFilename8, ppDb,
145166                        SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
145167      assert( *ppDb || rc==SQLITE_NOMEM );
145168      if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
145169        SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
145170      }
145171    }else{
145172      rc = SQLITE_NOMEM_BKPT;
145173    }
145174    sqlite3ValueFree(pVal);
145175  
145176    return rc & 0xff;
145177  }
145178  #endif /* SQLITE_OMIT_UTF16 */
145179  
145180  /*
145181  ** Register a new collation sequence with the database handle db.
145182  */
145183  SQLITE_API int sqlite3_create_collation(
145184    sqlite3* db, 
145185    const char *zName, 
145186    int enc, 
145187    void* pCtx,
145188    int(*xCompare)(void*,int,const void*,int,const void*)
145189  ){
145190    return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
145191  }
145192  
145193  /*
145194  ** Register a new collation sequence with the database handle db.
145195  */
145196  SQLITE_API int sqlite3_create_collation_v2(
145197    sqlite3* db, 
145198    const char *zName, 
145199    int enc, 
145200    void* pCtx,
145201    int(*xCompare)(void*,int,const void*,int,const void*),
145202    void(*xDel)(void*)
145203  ){
145204    int rc;
145205  
145206  #ifdef SQLITE_ENABLE_API_ARMOR
145207    if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
145208  #endif
145209    sqlite3_mutex_enter(db->mutex);
145210    assert( !db->mallocFailed );
145211    rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
145212    rc = sqlite3ApiExit(db, rc);
145213    sqlite3_mutex_leave(db->mutex);
145214    return rc;
145215  }
145216  
145217  #ifndef SQLITE_OMIT_UTF16
145218  /*
145219  ** Register a new collation sequence with the database handle db.
145220  */
145221  SQLITE_API int sqlite3_create_collation16(
145222    sqlite3* db, 
145223    const void *zName,
145224    int enc, 
145225    void* pCtx,
145226    int(*xCompare)(void*,int,const void*,int,const void*)
145227  ){
145228    int rc = SQLITE_OK;
145229    char *zName8;
145230  
145231  #ifdef SQLITE_ENABLE_API_ARMOR
145232    if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
145233  #endif
145234    sqlite3_mutex_enter(db->mutex);
145235    assert( !db->mallocFailed );
145236    zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
145237    if( zName8 ){
145238      rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
145239      sqlite3DbFree(db, zName8);
145240    }
145241    rc = sqlite3ApiExit(db, rc);
145242    sqlite3_mutex_leave(db->mutex);
145243    return rc;
145244  }
145245  #endif /* SQLITE_OMIT_UTF16 */
145246  
145247  /*
145248  ** Register a collation sequence factory callback with the database handle
145249  ** db. Replace any previously installed collation sequence factory.
145250  */
145251  SQLITE_API int sqlite3_collation_needed(
145252    sqlite3 *db, 
145253    void *pCollNeededArg, 
145254    void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
145255  ){
145256  #ifdef SQLITE_ENABLE_API_ARMOR
145257    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
145258  #endif
145259    sqlite3_mutex_enter(db->mutex);
145260    db->xCollNeeded = xCollNeeded;
145261    db->xCollNeeded16 = 0;
145262    db->pCollNeededArg = pCollNeededArg;
145263    sqlite3_mutex_leave(db->mutex);
145264    return SQLITE_OK;
145265  }
145266  
145267  #ifndef SQLITE_OMIT_UTF16
145268  /*
145269  ** Register a collation sequence factory callback with the database handle
145270  ** db. Replace any previously installed collation sequence factory.
145271  */
145272  SQLITE_API int sqlite3_collation_needed16(
145273    sqlite3 *db, 
145274    void *pCollNeededArg, 
145275    void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
145276  ){
145277  #ifdef SQLITE_ENABLE_API_ARMOR
145278    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
145279  #endif
145280    sqlite3_mutex_enter(db->mutex);
145281    db->xCollNeeded = 0;
145282    db->xCollNeeded16 = xCollNeeded16;
145283    db->pCollNeededArg = pCollNeededArg;
145284    sqlite3_mutex_leave(db->mutex);
145285    return SQLITE_OK;
145286  }
145287  #endif /* SQLITE_OMIT_UTF16 */
145288  
145289  #ifndef SQLITE_OMIT_DEPRECATED
145290  /*
145291  ** This function is now an anachronism. It used to be used to recover from a
145292  ** malloc() failure, but SQLite now does this automatically.
145293  */
145294  SQLITE_API int sqlite3_global_recover(void){
145295    return SQLITE_OK;
145296  }
145297  #endif
145298  
145299  /*
145300  ** Test to see whether or not the database connection is in autocommit
145301  ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
145302  ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
145303  ** by the next COMMIT or ROLLBACK.
145304  */
145305  SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
145306  #ifdef SQLITE_ENABLE_API_ARMOR
145307    if( !sqlite3SafetyCheckOk(db) ){
145308      (void)SQLITE_MISUSE_BKPT;
145309      return 0;
145310    }
145311  #endif
145312    return db->autoCommit;
145313  }
145314  
145315  /*
145316  ** The following routines are substitutes for constants SQLITE_CORRUPT,
145317  ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
145318  ** constants.  They serve two purposes:
145319  **
145320  **   1.  Serve as a convenient place to set a breakpoint in a debugger
145321  **       to detect when version error conditions occurs.
145322  **
145323  **   2.  Invoke sqlite3_log() to provide the source code location where
145324  **       a low-level error is first detected.
145325  */
145326  static int reportError(int iErr, int lineno, const char *zType){
145327    sqlite3_log(iErr, "%s at line %d of [%.10s]",
145328                zType, lineno, 20+sqlite3_sourceid());
145329    return iErr;
145330  }
145331  SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
145332    testcase( sqlite3GlobalConfig.xLog!=0 );
145333    return reportError(SQLITE_CORRUPT, lineno, "database corruption");
145334  }
145335  SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
145336    testcase( sqlite3GlobalConfig.xLog!=0 );
145337    return reportError(SQLITE_MISUSE, lineno, "misuse");
145338  }
145339  SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
145340    testcase( sqlite3GlobalConfig.xLog!=0 );
145341    return reportError(SQLITE_CANTOPEN, lineno, "cannot open file");
145342  }
145343  #ifdef SQLITE_DEBUG
145344  SQLITE_PRIVATE int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
145345    char zMsg[100];
145346    sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
145347    testcase( sqlite3GlobalConfig.xLog!=0 );
145348    return reportError(SQLITE_CORRUPT, lineno, zMsg);
145349  }
145350  SQLITE_PRIVATE int sqlite3NomemError(int lineno){
145351    testcase( sqlite3GlobalConfig.xLog!=0 );
145352    return reportError(SQLITE_NOMEM, lineno, "OOM");
145353  }
145354  SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
145355    testcase( sqlite3GlobalConfig.xLog!=0 );
145356    return reportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
145357  }
145358  #endif
145359  
145360  #ifndef SQLITE_OMIT_DEPRECATED
145361  /*
145362  ** This is a convenience routine that makes sure that all thread-specific
145363  ** data for this thread has been deallocated.
145364  **
145365  ** SQLite no longer uses thread-specific data so this routine is now a
145366  ** no-op.  It is retained for historical compatibility.
145367  */
145368  SQLITE_API void sqlite3_thread_cleanup(void){
145369  }
145370  #endif
145371  
145372  /*
145373  ** Return meta information about a specific column of a database table.
145374  ** See comment in sqlite3.h (sqlite.h.in) for details.
145375  */
145376  SQLITE_API int sqlite3_table_column_metadata(
145377    sqlite3 *db,                /* Connection handle */
145378    const char *zDbName,        /* Database name or NULL */
145379    const char *zTableName,     /* Table name */
145380    const char *zColumnName,    /* Column name */
145381    char const **pzDataType,    /* OUTPUT: Declared data type */
145382    char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
145383    int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
145384    int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
145385    int *pAutoinc               /* OUTPUT: True if column is auto-increment */
145386  ){
145387    int rc;
145388    char *zErrMsg = 0;
145389    Table *pTab = 0;
145390    Column *pCol = 0;
145391    int iCol = 0;
145392    char const *zDataType = 0;
145393    char const *zCollSeq = 0;
145394    int notnull = 0;
145395    int primarykey = 0;
145396    int autoinc = 0;
145397  
145398  
145399  #ifdef SQLITE_ENABLE_API_ARMOR
145400    if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
145401      return SQLITE_MISUSE_BKPT;
145402    }
145403  #endif
145404  
145405    /* Ensure the database schema has been loaded */
145406    sqlite3_mutex_enter(db->mutex);
145407    sqlite3BtreeEnterAll(db);
145408    rc = sqlite3Init(db, &zErrMsg);
145409    if( SQLITE_OK!=rc ){
145410      goto error_out;
145411    }
145412  
145413    /* Locate the table in question */
145414    pTab = sqlite3FindTable(db, zTableName, zDbName);
145415    if( !pTab || pTab->pSelect ){
145416      pTab = 0;
145417      goto error_out;
145418    }
145419  
145420    /* Find the column for which info is requested */
145421    if( zColumnName==0 ){
145422      /* Query for existance of table only */
145423    }else{
145424      for(iCol=0; iCol<pTab->nCol; iCol++){
145425        pCol = &pTab->aCol[iCol];
145426        if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
145427          break;
145428        }
145429      }
145430      if( iCol==pTab->nCol ){
145431        if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
145432          iCol = pTab->iPKey;
145433          pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
145434        }else{
145435          pTab = 0;
145436          goto error_out;
145437        }
145438      }
145439    }
145440  
145441    /* The following block stores the meta information that will be returned
145442    ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
145443    ** and autoinc. At this point there are two possibilities:
145444    ** 
145445    **     1. The specified column name was rowid", "oid" or "_rowid_" 
145446    **        and there is no explicitly declared IPK column. 
145447    **
145448    **     2. The table is not a view and the column name identified an 
145449    **        explicitly declared column. Copy meta information from *pCol.
145450    */ 
145451    if( pCol ){
145452      zDataType = sqlite3ColumnType(pCol,0);
145453      zCollSeq = pCol->zColl;
145454      notnull = pCol->notNull!=0;
145455      primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
145456      autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
145457    }else{
145458      zDataType = "INTEGER";
145459      primarykey = 1;
145460    }
145461    if( !zCollSeq ){
145462      zCollSeq = sqlite3StrBINARY;
145463    }
145464  
145465  error_out:
145466    sqlite3BtreeLeaveAll(db);
145467  
145468    /* Whether the function call succeeded or failed, set the output parameters
145469    ** to whatever their local counterparts contain. If an error did occur,
145470    ** this has the effect of zeroing all output parameters.
145471    */
145472    if( pzDataType ) *pzDataType = zDataType;
145473    if( pzCollSeq ) *pzCollSeq = zCollSeq;
145474    if( pNotNull ) *pNotNull = notnull;
145475    if( pPrimaryKey ) *pPrimaryKey = primarykey;
145476    if( pAutoinc ) *pAutoinc = autoinc;
145477  
145478    if( SQLITE_OK==rc && !pTab ){
145479      sqlite3DbFree(db, zErrMsg);
145480      zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
145481          zColumnName);
145482      rc = SQLITE_ERROR;
145483    }
145484    sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
145485    sqlite3DbFree(db, zErrMsg);
145486    rc = sqlite3ApiExit(db, rc);
145487    sqlite3_mutex_leave(db->mutex);
145488    return rc;
145489  }
145490  
145491  /*
145492  ** Sleep for a little while.  Return the amount of time slept.
145493  */
145494  SQLITE_API int sqlite3_sleep(int ms){
145495    sqlite3_vfs *pVfs;
145496    int rc;
145497    pVfs = sqlite3_vfs_find(0);
145498    if( pVfs==0 ) return 0;
145499  
145500    /* This function works in milliseconds, but the underlying OsSleep() 
145501    ** API uses microseconds. Hence the 1000's.
145502    */
145503    rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
145504    return rc;
145505  }
145506  
145507  /*
145508  ** Enable or disable the extended result codes.
145509  */
145510  SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
145511  #ifdef SQLITE_ENABLE_API_ARMOR
145512    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
145513  #endif
145514    sqlite3_mutex_enter(db->mutex);
145515    db->errMask = onoff ? 0xffffffff : 0xff;
145516    sqlite3_mutex_leave(db->mutex);
145517    return SQLITE_OK;
145518  }
145519  
145520  /*
145521  ** Invoke the xFileControl method on a particular database.
145522  */
145523  SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
145524    int rc = SQLITE_ERROR;
145525    Btree *pBtree;
145526  
145527  #ifdef SQLITE_ENABLE_API_ARMOR
145528    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
145529  #endif
145530    sqlite3_mutex_enter(db->mutex);
145531    pBtree = sqlite3DbNameToBtree(db, zDbName);
145532    if( pBtree ){
145533      Pager *pPager;
145534      sqlite3_file *fd;
145535      sqlite3BtreeEnter(pBtree);
145536      pPager = sqlite3BtreePager(pBtree);
145537      assert( pPager!=0 );
145538      fd = sqlite3PagerFile(pPager);
145539      assert( fd!=0 );
145540      if( op==SQLITE_FCNTL_FILE_POINTER ){
145541        *(sqlite3_file**)pArg = fd;
145542        rc = SQLITE_OK;
145543      }else if( op==SQLITE_FCNTL_VFS_POINTER ){
145544        *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
145545        rc = SQLITE_OK;
145546      }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
145547        *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
145548        rc = SQLITE_OK;
145549      }else if( fd->pMethods ){
145550        rc = sqlite3OsFileControl(fd, op, pArg);
145551      }else{
145552        rc = SQLITE_NOTFOUND;
145553      }
145554      sqlite3BtreeLeave(pBtree);
145555    }
145556    sqlite3_mutex_leave(db->mutex);
145557    return rc;
145558  }
145559  
145560  /*
145561  ** Interface to the testing logic.
145562  */
145563  SQLITE_API int sqlite3_test_control(int op, ...){
145564    int rc = 0;
145565  #ifdef SQLITE_UNTESTABLE
145566    UNUSED_PARAMETER(op);
145567  #else
145568    va_list ap;
145569    va_start(ap, op);
145570    switch( op ){
145571  
145572      /*
145573      ** Save the current state of the PRNG.
145574      */
145575      case SQLITE_TESTCTRL_PRNG_SAVE: {
145576        sqlite3PrngSaveState();
145577        break;
145578      }
145579  
145580      /*
145581      ** Restore the state of the PRNG to the last state saved using
145582      ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
145583      ** this verb acts like PRNG_RESET.
145584      */
145585      case SQLITE_TESTCTRL_PRNG_RESTORE: {
145586        sqlite3PrngRestoreState();
145587        break;
145588      }
145589  
145590      /*
145591      ** Reset the PRNG back to its uninitialized state.  The next call
145592      ** to sqlite3_randomness() will reseed the PRNG using a single call
145593      ** to the xRandomness method of the default VFS.
145594      */
145595      case SQLITE_TESTCTRL_PRNG_RESET: {
145596        sqlite3_randomness(0,0);
145597        break;
145598      }
145599  
145600      /*
145601      **  sqlite3_test_control(BITVEC_TEST, size, program)
145602      **
145603      ** Run a test against a Bitvec object of size.  The program argument
145604      ** is an array of integers that defines the test.  Return -1 on a
145605      ** memory allocation error, 0 on success, or non-zero for an error.
145606      ** See the sqlite3BitvecBuiltinTest() for additional information.
145607      */
145608      case SQLITE_TESTCTRL_BITVEC_TEST: {
145609        int sz = va_arg(ap, int);
145610        int *aProg = va_arg(ap, int*);
145611        rc = sqlite3BitvecBuiltinTest(sz, aProg);
145612        break;
145613      }
145614  
145615      /*
145616      **  sqlite3_test_control(FAULT_INSTALL, xCallback)
145617      **
145618      ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
145619      ** if xCallback is not NULL.
145620      **
145621      ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
145622      ** is called immediately after installing the new callback and the return
145623      ** value from sqlite3FaultSim(0) becomes the return from
145624      ** sqlite3_test_control().
145625      */
145626      case SQLITE_TESTCTRL_FAULT_INSTALL: {
145627        /* MSVC is picky about pulling func ptrs from va lists.
145628        ** http://support.microsoft.com/kb/47961
145629        ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
145630        */
145631        typedef int(*TESTCALLBACKFUNC_t)(int);
145632        sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
145633        rc = sqlite3FaultSim(0);
145634        break;
145635      }
145636  
145637      /*
145638      **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
145639      **
145640      ** Register hooks to call to indicate which malloc() failures 
145641      ** are benign.
145642      */
145643      case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
145644        typedef void (*void_function)(void);
145645        void_function xBenignBegin;
145646        void_function xBenignEnd;
145647        xBenignBegin = va_arg(ap, void_function);
145648        xBenignEnd = va_arg(ap, void_function);
145649        sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
145650        break;
145651      }
145652  
145653      /*
145654      **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
145655      **
145656      ** Set the PENDING byte to the value in the argument, if X>0.
145657      ** Make no changes if X==0.  Return the value of the pending byte
145658      ** as it existing before this routine was called.
145659      **
145660      ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
145661      ** an incompatible database file format.  Changing the PENDING byte
145662      ** while any database connection is open results in undefined and
145663      ** deleterious behavior.
145664      */
145665      case SQLITE_TESTCTRL_PENDING_BYTE: {
145666        rc = PENDING_BYTE;
145667  #ifndef SQLITE_OMIT_WSD
145668        {
145669          unsigned int newVal = va_arg(ap, unsigned int);
145670          if( newVal ) sqlite3PendingByte = newVal;
145671        }
145672  #endif
145673        break;
145674      }
145675  
145676      /*
145677      **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
145678      **
145679      ** This action provides a run-time test to see whether or not
145680      ** assert() was enabled at compile-time.  If X is true and assert()
145681      ** is enabled, then the return value is true.  If X is true and
145682      ** assert() is disabled, then the return value is zero.  If X is
145683      ** false and assert() is enabled, then the assertion fires and the
145684      ** process aborts.  If X is false and assert() is disabled, then the
145685      ** return value is zero.
145686      */
145687      case SQLITE_TESTCTRL_ASSERT: {
145688        volatile int x = 0;
145689        assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
145690        rc = x;
145691        break;
145692      }
145693  
145694  
145695      /*
145696      **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
145697      **
145698      ** This action provides a run-time test to see how the ALWAYS and
145699      ** NEVER macros were defined at compile-time.
145700      **
145701      ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
145702      **
145703      ** The recommended test is X==2.  If the return value is 2, that means
145704      ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
145705      ** default setting.  If the return value is 1, then ALWAYS() is either
145706      ** hard-coded to true or else it asserts if its argument is false.
145707      ** The first behavior (hard-coded to true) is the case if
145708      ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
145709      ** behavior (assert if the argument to ALWAYS() is false) is the case if
145710      ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
145711      **
145712      ** The run-time test procedure might look something like this:
145713      **
145714      **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
145715      **      // ALWAYS() and NEVER() are no-op pass-through macros
145716      **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
145717      **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
145718      **    }else{
145719      **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
145720      **    }
145721      */
145722      case SQLITE_TESTCTRL_ALWAYS: {
145723        int x = va_arg(ap,int);
145724        rc = x ? ALWAYS(x) : 0;
145725        break;
145726      }
145727  
145728      /*
145729      **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
145730      **
145731      ** The integer returned reveals the byte-order of the computer on which
145732      ** SQLite is running:
145733      **
145734      **       1     big-endian,    determined at run-time
145735      **      10     little-endian, determined at run-time
145736      **  432101     big-endian,    determined at compile-time
145737      **  123410     little-endian, determined at compile-time
145738      */ 
145739      case SQLITE_TESTCTRL_BYTEORDER: {
145740        rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
145741        break;
145742      }
145743  
145744      /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
145745      **
145746      ** Set the nReserve size to N for the main database on the database
145747      ** connection db.
145748      */
145749      case SQLITE_TESTCTRL_RESERVE: {
145750        sqlite3 *db = va_arg(ap, sqlite3*);
145751        int x = va_arg(ap,int);
145752        sqlite3_mutex_enter(db->mutex);
145753        sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
145754        sqlite3_mutex_leave(db->mutex);
145755        break;
145756      }
145757  
145758      /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
145759      **
145760      ** Enable or disable various optimizations for testing purposes.  The 
145761      ** argument N is a bitmask of optimizations to be disabled.  For normal
145762      ** operation N should be 0.  The idea is that a test program (like the
145763      ** SQL Logic Test or SLT test module) can run the same SQL multiple times
145764      ** with various optimizations disabled to verify that the same answer
145765      ** is obtained in every case.
145766      */
145767      case SQLITE_TESTCTRL_OPTIMIZATIONS: {
145768        sqlite3 *db = va_arg(ap, sqlite3*);
145769        db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
145770        break;
145771      }
145772  
145773  #ifdef SQLITE_N_KEYWORD
145774      /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
145775      **
145776      ** If zWord is a keyword recognized by the parser, then return the
145777      ** number of keywords.  Or if zWord is not a keyword, return 0.
145778      ** 
145779      ** This test feature is only available in the amalgamation since
145780      ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
145781      ** is built using separate source files.
145782      */
145783      case SQLITE_TESTCTRL_ISKEYWORD: {
145784        const char *zWord = va_arg(ap, const char*);
145785        int n = sqlite3Strlen30(zWord);
145786        rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
145787        break;
145788      }
145789  #endif 
145790  
145791      /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
145792      **
145793      ** If parameter onoff is non-zero, configure the wrappers so that all
145794      ** subsequent calls to localtime() and variants fail. If onoff is zero,
145795      ** undo this setting.
145796      */
145797      case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
145798        sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
145799        break;
145800      }
145801  
145802      /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
145803      **
145804      ** Set or clear a flag that indicates that the database file is always well-
145805      ** formed and never corrupt.  This flag is clear by default, indicating that
145806      ** database files might have arbitrary corruption.  Setting the flag during
145807      ** testing causes certain assert() statements in the code to be activated
145808      ** that demonstrat invariants on well-formed database files.
145809      */
145810      case SQLITE_TESTCTRL_NEVER_CORRUPT: {
145811        sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
145812        break;
145813      }
145814  
145815      /* Set the threshold at which OP_Once counters reset back to zero.
145816      ** By default this is 0x7ffffffe (over 2 billion), but that value is
145817      ** too big to test in a reasonable amount of time, so this control is
145818      ** provided to set a small and easily reachable reset value.
145819      */
145820      case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
145821        sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
145822        break;
145823      }
145824  
145825      /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
145826      **
145827      ** Set the VDBE coverage callback function to xCallback with context 
145828      ** pointer ptr.
145829      */
145830      case SQLITE_TESTCTRL_VDBE_COVERAGE: {
145831  #ifdef SQLITE_VDBE_COVERAGE
145832        typedef void (*branch_callback)(void*,int,u8,u8);
145833        sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
145834        sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
145835  #endif
145836        break;
145837      }
145838  
145839      /*   sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
145840      case SQLITE_TESTCTRL_SORTER_MMAP: {
145841        sqlite3 *db = va_arg(ap, sqlite3*);
145842        db->nMaxSorterMmap = va_arg(ap, int);
145843        break;
145844      }
145845  
145846      /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
145847      **
145848      ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
145849      ** not.
145850      */
145851      case SQLITE_TESTCTRL_ISINIT: {
145852        if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
145853        break;
145854      }
145855  
145856      /*  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
145857      **
145858      ** This test control is used to create imposter tables.  "db" is a pointer
145859      ** to the database connection.  dbName is the database name (ex: "main" or
145860      ** "temp") which will receive the imposter.  "onOff" turns imposter mode on
145861      ** or off.  "tnum" is the root page of the b-tree to which the imposter
145862      ** table should connect.
145863      **
145864      ** Enable imposter mode only when the schema has already been parsed.  Then
145865      ** run a single CREATE TABLE statement to construct the imposter table in
145866      ** the parsed schema.  Then turn imposter mode back off again.
145867      **
145868      ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
145869      ** the schema to be reparsed the next time it is needed.  This has the
145870      ** effect of erasing all imposter tables.
145871      */
145872      case SQLITE_TESTCTRL_IMPOSTER: {
145873        sqlite3 *db = va_arg(ap, sqlite3*);
145874        sqlite3_mutex_enter(db->mutex);
145875        db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
145876        db->init.busy = db->init.imposterTable = va_arg(ap,int);
145877        db->init.newTnum = va_arg(ap,int);
145878        if( db->init.busy==0 && db->init.newTnum>0 ){
145879          sqlite3ResetAllSchemasOfConnection(db);
145880        }
145881        sqlite3_mutex_leave(db->mutex);
145882        break;
145883      }
145884    }
145885    va_end(ap);
145886  #endif /* SQLITE_UNTESTABLE */
145887    return rc;
145888  }
145889  
145890  /*
145891  ** This is a utility routine, useful to VFS implementations, that checks
145892  ** to see if a database file was a URI that contained a specific query 
145893  ** parameter, and if so obtains the value of the query parameter.
145894  **
145895  ** The zFilename argument is the filename pointer passed into the xOpen()
145896  ** method of a VFS implementation.  The zParam argument is the name of the
145897  ** query parameter we seek.  This routine returns the value of the zParam
145898  ** parameter if it exists.  If the parameter does not exist, this routine
145899  ** returns a NULL pointer.
145900  */
145901  SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
145902    if( zFilename==0 || zParam==0 ) return 0;
145903    zFilename += sqlite3Strlen30(zFilename) + 1;
145904    while( zFilename[0] ){
145905      int x = strcmp(zFilename, zParam);
145906      zFilename += sqlite3Strlen30(zFilename) + 1;
145907      if( x==0 ) return zFilename;
145908      zFilename += sqlite3Strlen30(zFilename) + 1;
145909    }
145910    return 0;
145911  }
145912  
145913  /*
145914  ** Return a boolean value for a query parameter.
145915  */
145916  SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
145917    const char *z = sqlite3_uri_parameter(zFilename, zParam);
145918    bDflt = bDflt!=0;
145919    return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
145920  }
145921  
145922  /*
145923  ** Return a 64-bit integer value for a query parameter.
145924  */
145925  SQLITE_API sqlite3_int64 sqlite3_uri_int64(
145926    const char *zFilename,    /* Filename as passed to xOpen */
145927    const char *zParam,       /* URI parameter sought */
145928    sqlite3_int64 bDflt       /* return if parameter is missing */
145929  ){
145930    const char *z = sqlite3_uri_parameter(zFilename, zParam);
145931    sqlite3_int64 v;
145932    if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
145933      bDflt = v;
145934    }
145935    return bDflt;
145936  }
145937  
145938  /*
145939  ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
145940  */
145941  SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
145942    int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
145943    return iDb<0 ? 0 : db->aDb[iDb].pBt;
145944  }
145945  
145946  /*
145947  ** Return the filename of the database associated with a database
145948  ** connection.
145949  */
145950  SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
145951    Btree *pBt;
145952  #ifdef SQLITE_ENABLE_API_ARMOR
145953    if( !sqlite3SafetyCheckOk(db) ){
145954      (void)SQLITE_MISUSE_BKPT;
145955      return 0;
145956    }
145957  #endif
145958    pBt = sqlite3DbNameToBtree(db, zDbName);
145959    return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
145960  }
145961  
145962  /*
145963  ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
145964  ** no such database exists.
145965  */
145966  SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
145967    Btree *pBt;
145968  #ifdef SQLITE_ENABLE_API_ARMOR
145969    if( !sqlite3SafetyCheckOk(db) ){
145970      (void)SQLITE_MISUSE_BKPT;
145971      return -1;
145972    }
145973  #endif
145974    pBt = sqlite3DbNameToBtree(db, zDbName);
145975    return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
145976  }
145977  
145978  #ifdef SQLITE_ENABLE_SNAPSHOT
145979  /*
145980  ** Obtain a snapshot handle for the snapshot of database zDb currently 
145981  ** being read by handle db.
145982  */
145983  SQLITE_API int sqlite3_snapshot_get(
145984    sqlite3 *db, 
145985    const char *zDb,
145986    sqlite3_snapshot **ppSnapshot
145987  ){
145988    int rc = SQLITE_ERROR;
145989  #ifndef SQLITE_OMIT_WAL
145990  
145991  #ifdef SQLITE_ENABLE_API_ARMOR
145992    if( !sqlite3SafetyCheckOk(db) ){
145993      return SQLITE_MISUSE_BKPT;
145994    }
145995  #endif
145996    sqlite3_mutex_enter(db->mutex);
145997  
145998    if( db->autoCommit==0 ){
145999      int iDb = sqlite3FindDbName(db, zDb);
146000      if( iDb==0 || iDb>1 ){
146001        Btree *pBt = db->aDb[iDb].pBt;
146002        if( 0==sqlite3BtreeIsInTrans(pBt) ){
146003          rc = sqlite3BtreeBeginTrans(pBt, 0);
146004          if( rc==SQLITE_OK ){
146005            rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
146006          }
146007        }
146008      }
146009    }
146010  
146011    sqlite3_mutex_leave(db->mutex);
146012  #endif   /* SQLITE_OMIT_WAL */
146013    return rc;
146014  }
146015  
146016  /*
146017  ** Open a read-transaction on the snapshot idendified by pSnapshot.
146018  */
146019  SQLITE_API int sqlite3_snapshot_open(
146020    sqlite3 *db, 
146021    const char *zDb, 
146022    sqlite3_snapshot *pSnapshot
146023  ){
146024    int rc = SQLITE_ERROR;
146025  #ifndef SQLITE_OMIT_WAL
146026  
146027  #ifdef SQLITE_ENABLE_API_ARMOR
146028    if( !sqlite3SafetyCheckOk(db) ){
146029      return SQLITE_MISUSE_BKPT;
146030    }
146031  #endif
146032    sqlite3_mutex_enter(db->mutex);
146033    if( db->autoCommit==0 ){
146034      int iDb;
146035      iDb = sqlite3FindDbName(db, zDb);
146036      if( iDb==0 || iDb>1 ){
146037        Btree *pBt = db->aDb[iDb].pBt;
146038        if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
146039          rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
146040          if( rc==SQLITE_OK ){
146041            rc = sqlite3BtreeBeginTrans(pBt, 0);
146042            sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
146043          }
146044        }
146045      }
146046    }
146047  
146048    sqlite3_mutex_leave(db->mutex);
146049  #endif   /* SQLITE_OMIT_WAL */
146050    return rc;
146051  }
146052  
146053  /*
146054  ** Recover as many snapshots as possible from the wal file associated with
146055  ** schema zDb of database db.
146056  */
146057  SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
146058    int rc = SQLITE_ERROR;
146059    int iDb;
146060  #ifndef SQLITE_OMIT_WAL
146061  
146062  #ifdef SQLITE_ENABLE_API_ARMOR
146063    if( !sqlite3SafetyCheckOk(db) ){
146064      return SQLITE_MISUSE_BKPT;
146065    }
146066  #endif
146067  
146068    sqlite3_mutex_enter(db->mutex);
146069    iDb = sqlite3FindDbName(db, zDb);
146070    if( iDb==0 || iDb>1 ){
146071      Btree *pBt = db->aDb[iDb].pBt;
146072      if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
146073        rc = sqlite3BtreeBeginTrans(pBt, 0);
146074        if( rc==SQLITE_OK ){
146075          rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
146076          sqlite3BtreeCommit(pBt);
146077        }
146078      }
146079    }
146080    sqlite3_mutex_leave(db->mutex);
146081  #endif   /* SQLITE_OMIT_WAL */
146082    return rc;
146083  }
146084  
146085  /*
146086  ** Free a snapshot handle obtained from sqlite3_snapshot_get().
146087  */
146088  SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
146089    sqlite3_free(pSnapshot);
146090  }
146091  #endif /* SQLITE_ENABLE_SNAPSHOT */
146092  
146093  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
146094  /*
146095  ** Given the name of a compile-time option, return true if that option
146096  ** was used and false if not.
146097  **
146098  ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
146099  ** is not required for a match.
146100  */
146101  SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
146102    int i, n;
146103    int nOpt;
146104    const char **azCompileOpt;
146105   
146106  #if SQLITE_ENABLE_API_ARMOR
146107    if( zOptName==0 ){
146108      (void)SQLITE_MISUSE_BKPT;
146109      return 0;
146110    }
146111  #endif
146112  
146113    azCompileOpt = sqlite3CompileOptions(&nOpt);
146114  
146115    if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
146116    n = sqlite3Strlen30(zOptName);
146117  
146118    /* Since nOpt is normally in single digits, a linear search is 
146119    ** adequate. No need for a binary search. */
146120    for(i=0; i<nOpt; i++){
146121      if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
146122       && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
146123      ){
146124        return 1;
146125      }
146126    }
146127    return 0;
146128  }
146129  
146130  /*
146131  ** Return the N-th compile-time option string.  If N is out of range,
146132  ** return a NULL pointer.
146133  */
146134  SQLITE_API const char *sqlite3_compileoption_get(int N){
146135    int nOpt;
146136    const char **azCompileOpt;
146137    azCompileOpt = sqlite3CompileOptions(&nOpt);
146138    if( N>=0 && N<nOpt ){
146139      return azCompileOpt[N];
146140    }
146141    return 0;
146142  }
146143  #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
146144  
146145  /************** End of main.c ************************************************/
146146  /************** Begin file notify.c ******************************************/
146147  /*
146148  ** 2009 March 3
146149  **
146150  ** The author disclaims copyright to this source code.  In place of
146151  ** a legal notice, here is a blessing:
146152  **
146153  **    May you do good and not evil.
146154  **    May you find forgiveness for yourself and forgive others.
146155  **    May you share freely, never taking more than you give.
146156  **
146157  *************************************************************************
146158  **
146159  ** This file contains the implementation of the sqlite3_unlock_notify()
146160  ** API method and its associated functionality.
146161  */
146162  /* #include "sqliteInt.h" */
146163  /* #include "btreeInt.h" */
146164  
146165  /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
146166  #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
146167  
146168  /*
146169  ** Public interfaces:
146170  **
146171  **   sqlite3ConnectionBlocked()
146172  **   sqlite3ConnectionUnlocked()
146173  **   sqlite3ConnectionClosed()
146174  **   sqlite3_unlock_notify()
146175  */
146176  
146177  #define assertMutexHeld() \
146178    assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
146179  
146180  /*
146181  ** Head of a linked list of all sqlite3 objects created by this process
146182  ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
146183  ** is not NULL. This variable may only accessed while the STATIC_MASTER
146184  ** mutex is held.
146185  */
146186  static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
146187  
146188  #ifndef NDEBUG
146189  /*
146190  ** This function is a complex assert() that verifies the following 
146191  ** properties of the blocked connections list:
146192  **
146193  **   1) Each entry in the list has a non-NULL value for either 
146194  **      pUnlockConnection or pBlockingConnection, or both.
146195  **
146196  **   2) All entries in the list that share a common value for 
146197  **      xUnlockNotify are grouped together.
146198  **
146199  **   3) If the argument db is not NULL, then none of the entries in the
146200  **      blocked connections list have pUnlockConnection or pBlockingConnection
146201  **      set to db. This is used when closing connection db.
146202  */
146203  static void checkListProperties(sqlite3 *db){
146204    sqlite3 *p;
146205    for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
146206      int seen = 0;
146207      sqlite3 *p2;
146208  
146209      /* Verify property (1) */
146210      assert( p->pUnlockConnection || p->pBlockingConnection );
146211  
146212      /* Verify property (2) */
146213      for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
146214        if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
146215        assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
146216        assert( db==0 || p->pUnlockConnection!=db );
146217        assert( db==0 || p->pBlockingConnection!=db );
146218      }
146219    }
146220  }
146221  #else
146222  # define checkListProperties(x)
146223  #endif
146224  
146225  /*
146226  ** Remove connection db from the blocked connections list. If connection
146227  ** db is not currently a part of the list, this function is a no-op.
146228  */
146229  static void removeFromBlockedList(sqlite3 *db){
146230    sqlite3 **pp;
146231    assertMutexHeld();
146232    for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
146233      if( *pp==db ){
146234        *pp = (*pp)->pNextBlocked;
146235        break;
146236      }
146237    }
146238  }
146239  
146240  /*
146241  ** Add connection db to the blocked connections list. It is assumed
146242  ** that it is not already a part of the list.
146243  */
146244  static void addToBlockedList(sqlite3 *db){
146245    sqlite3 **pp;
146246    assertMutexHeld();
146247    for(
146248      pp=&sqlite3BlockedList; 
146249      *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
146250      pp=&(*pp)->pNextBlocked
146251    );
146252    db->pNextBlocked = *pp;
146253    *pp = db;
146254  }
146255  
146256  /*
146257  ** Obtain the STATIC_MASTER mutex.
146258  */
146259  static void enterMutex(void){
146260    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
146261    checkListProperties(0);
146262  }
146263  
146264  /*
146265  ** Release the STATIC_MASTER mutex.
146266  */
146267  static void leaveMutex(void){
146268    assertMutexHeld();
146269    checkListProperties(0);
146270    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
146271  }
146272  
146273  /*
146274  ** Register an unlock-notify callback.
146275  **
146276  ** This is called after connection "db" has attempted some operation
146277  ** but has received an SQLITE_LOCKED error because another connection
146278  ** (call it pOther) in the same process was busy using the same shared
146279  ** cache.  pOther is found by looking at db->pBlockingConnection.
146280  **
146281  ** If there is no blocking connection, the callback is invoked immediately,
146282  ** before this routine returns.
146283  **
146284  ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
146285  ** a deadlock.
146286  **
146287  ** Otherwise, make arrangements to invoke xNotify when pOther drops
146288  ** its locks.
146289  **
146290  ** Each call to this routine overrides any prior callbacks registered
146291  ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
146292  ** cancelled.
146293  */
146294  SQLITE_API int sqlite3_unlock_notify(
146295    sqlite3 *db,
146296    void (*xNotify)(void **, int),
146297    void *pArg
146298  ){
146299    int rc = SQLITE_OK;
146300  
146301    sqlite3_mutex_enter(db->mutex);
146302    enterMutex();
146303  
146304    if( xNotify==0 ){
146305      removeFromBlockedList(db);
146306      db->pBlockingConnection = 0;
146307      db->pUnlockConnection = 0;
146308      db->xUnlockNotify = 0;
146309      db->pUnlockArg = 0;
146310    }else if( 0==db->pBlockingConnection ){
146311      /* The blocking transaction has been concluded. Or there never was a 
146312      ** blocking transaction. In either case, invoke the notify callback
146313      ** immediately. 
146314      */
146315      xNotify(&pArg, 1);
146316    }else{
146317      sqlite3 *p;
146318  
146319      for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
146320      if( p ){
146321        rc = SQLITE_LOCKED;              /* Deadlock detected. */
146322      }else{
146323        db->pUnlockConnection = db->pBlockingConnection;
146324        db->xUnlockNotify = xNotify;
146325        db->pUnlockArg = pArg;
146326        removeFromBlockedList(db);
146327        addToBlockedList(db);
146328      }
146329    }
146330  
146331    leaveMutex();
146332    assert( !db->mallocFailed );
146333    sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
146334    sqlite3_mutex_leave(db->mutex);
146335    return rc;
146336  }
146337  
146338  /*
146339  ** This function is called while stepping or preparing a statement 
146340  ** associated with connection db. The operation will return SQLITE_LOCKED
146341  ** to the user because it requires a lock that will not be available
146342  ** until connection pBlocker concludes its current transaction.
146343  */
146344  SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
146345    enterMutex();
146346    if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
146347      addToBlockedList(db);
146348    }
146349    db->pBlockingConnection = pBlocker;
146350    leaveMutex();
146351  }
146352  
146353  /*
146354  ** This function is called when
146355  ** the transaction opened by database db has just finished. Locks held 
146356  ** by database connection db have been released.
146357  **
146358  ** This function loops through each entry in the blocked connections
146359  ** list and does the following:
146360  **
146361  **   1) If the sqlite3.pBlockingConnection member of a list entry is
146362  **      set to db, then set pBlockingConnection=0.
146363  **
146364  **   2) If the sqlite3.pUnlockConnection member of a list entry is
146365  **      set to db, then invoke the configured unlock-notify callback and
146366  **      set pUnlockConnection=0.
146367  **
146368  **   3) If the two steps above mean that pBlockingConnection==0 and
146369  **      pUnlockConnection==0, remove the entry from the blocked connections
146370  **      list.
146371  */
146372  SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
146373    void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
146374    int nArg = 0;                            /* Number of entries in aArg[] */
146375    sqlite3 **pp;                            /* Iterator variable */
146376    void **aArg;               /* Arguments to the unlock callback */
146377    void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
146378    void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
146379  
146380    aArg = aStatic;
146381    enterMutex();         /* Enter STATIC_MASTER mutex */
146382  
146383    /* This loop runs once for each entry in the blocked-connections list. */
146384    for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
146385      sqlite3 *p = *pp;
146386  
146387      /* Step 1. */
146388      if( p->pBlockingConnection==db ){
146389        p->pBlockingConnection = 0;
146390      }
146391  
146392      /* Step 2. */
146393      if( p->pUnlockConnection==db ){
146394        assert( p->xUnlockNotify );
146395        if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
146396          xUnlockNotify(aArg, nArg);
146397          nArg = 0;
146398        }
146399  
146400        sqlite3BeginBenignMalloc();
146401        assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
146402        assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
146403        if( (!aDyn && nArg==(int)ArraySize(aStatic))
146404         || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
146405        ){
146406          /* The aArg[] array needs to grow. */
146407          void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
146408          if( pNew ){
146409            memcpy(pNew, aArg, nArg*sizeof(void *));
146410            sqlite3_free(aDyn);
146411            aDyn = aArg = pNew;
146412          }else{
146413            /* This occurs when the array of context pointers that need to
146414            ** be passed to the unlock-notify callback is larger than the
146415            ** aStatic[] array allocated on the stack and the attempt to 
146416            ** allocate a larger array from the heap has failed.
146417            **
146418            ** This is a difficult situation to handle. Returning an error
146419            ** code to the caller is insufficient, as even if an error code
146420            ** is returned the transaction on connection db will still be
146421            ** closed and the unlock-notify callbacks on blocked connections
146422            ** will go unissued. This might cause the application to wait
146423            ** indefinitely for an unlock-notify callback that will never 
146424            ** arrive.
146425            **
146426            ** Instead, invoke the unlock-notify callback with the context
146427            ** array already accumulated. We can then clear the array and
146428            ** begin accumulating any further context pointers without 
146429            ** requiring any dynamic allocation. This is sub-optimal because
146430            ** it means that instead of one callback with a large array of
146431            ** context pointers the application will receive two or more
146432            ** callbacks with smaller arrays of context pointers, which will
146433            ** reduce the applications ability to prioritize multiple 
146434            ** connections. But it is the best that can be done under the
146435            ** circumstances.
146436            */
146437            xUnlockNotify(aArg, nArg);
146438            nArg = 0;
146439          }
146440        }
146441        sqlite3EndBenignMalloc();
146442  
146443        aArg[nArg++] = p->pUnlockArg;
146444        xUnlockNotify = p->xUnlockNotify;
146445        p->pUnlockConnection = 0;
146446        p->xUnlockNotify = 0;
146447        p->pUnlockArg = 0;
146448      }
146449  
146450      /* Step 3. */
146451      if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
146452        /* Remove connection p from the blocked connections list. */
146453        *pp = p->pNextBlocked;
146454        p->pNextBlocked = 0;
146455      }else{
146456        pp = &p->pNextBlocked;
146457      }
146458    }
146459  
146460    if( nArg!=0 ){
146461      xUnlockNotify(aArg, nArg);
146462    }
146463    sqlite3_free(aDyn);
146464    leaveMutex();         /* Leave STATIC_MASTER mutex */
146465  }
146466  
146467  /*
146468  ** This is called when the database connection passed as an argument is 
146469  ** being closed. The connection is removed from the blocked list.
146470  */
146471  SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
146472    sqlite3ConnectionUnlocked(db);
146473    enterMutex();
146474    removeFromBlockedList(db);
146475    checkListProperties(db);
146476    leaveMutex();
146477  }
146478  #endif
146479  
146480  /************** End of notify.c **********************************************/
146481  /************** Begin file fts3.c ********************************************/
146482  /*
146483  ** 2006 Oct 10
146484  **
146485  ** The author disclaims copyright to this source code.  In place of
146486  ** a legal notice, here is a blessing:
146487  **
146488  **    May you do good and not evil.
146489  **    May you find forgiveness for yourself and forgive others.
146490  **    May you share freely, never taking more than you give.
146491  **
146492  ******************************************************************************
146493  **
146494  ** This is an SQLite module implementing full-text search.
146495  */
146496  
146497  /*
146498  ** The code in this file is only compiled if:
146499  **
146500  **     * The FTS3 module is being built as an extension
146501  **       (in which case SQLITE_CORE is not defined), or
146502  **
146503  **     * The FTS3 module is being built into the core of
146504  **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
146505  */
146506  
146507  /* The full-text index is stored in a series of b+tree (-like)
146508  ** structures called segments which map terms to doclists.  The
146509  ** structures are like b+trees in layout, but are constructed from the
146510  ** bottom up in optimal fashion and are not updatable.  Since trees
146511  ** are built from the bottom up, things will be described from the
146512  ** bottom up.
146513  **
146514  **
146515  **** Varints ****
146516  ** The basic unit of encoding is a variable-length integer called a
146517  ** varint.  We encode variable-length integers in little-endian order
146518  ** using seven bits * per byte as follows:
146519  **
146520  ** KEY:
146521  **         A = 0xxxxxxx    7 bits of data and one flag bit
146522  **         B = 1xxxxxxx    7 bits of data and one flag bit
146523  **
146524  **  7 bits - A
146525  ** 14 bits - BA
146526  ** 21 bits - BBA
146527  ** and so on.
146528  **
146529  ** This is similar in concept to how sqlite encodes "varints" but
146530  ** the encoding is not the same.  SQLite varints are big-endian
146531  ** are are limited to 9 bytes in length whereas FTS3 varints are
146532  ** little-endian and can be up to 10 bytes in length (in theory).
146533  **
146534  ** Example encodings:
146535  **
146536  **     1:    0x01
146537  **   127:    0x7f
146538  **   128:    0x81 0x00
146539  **
146540  **
146541  **** Document lists ****
146542  ** A doclist (document list) holds a docid-sorted list of hits for a
146543  ** given term.  Doclists hold docids and associated token positions.
146544  ** A docid is the unique integer identifier for a single document.
146545  ** A position is the index of a word within the document.  The first 
146546  ** word of the document has a position of 0.
146547  **
146548  ** FTS3 used to optionally store character offsets using a compile-time
146549  ** option.  But that functionality is no longer supported.
146550  **
146551  ** A doclist is stored like this:
146552  **
146553  ** array {
146554  **   varint docid;          (delta from previous doclist)
146555  **   array {                (position list for column 0)
146556  **     varint position;     (2 more than the delta from previous position)
146557  **   }
146558  **   array {
146559  **     varint POS_COLUMN;   (marks start of position list for new column)
146560  **     varint column;       (index of new column)
146561  **     array {
146562  **       varint position;   (2 more than the delta from previous position)
146563  **     }
146564  **   }
146565  **   varint POS_END;        (marks end of positions for this document.
146566  ** }
146567  **
146568  ** Here, array { X } means zero or more occurrences of X, adjacent in
146569  ** memory.  A "position" is an index of a token in the token stream
146570  ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
146571  ** in the same logical place as the position element, and act as sentinals
146572  ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
146573  ** The positions numbers are not stored literally but rather as two more
146574  ** than the difference from the prior position, or the just the position plus
146575  ** 2 for the first position.  Example:
146576  **
146577  **   label:       A B C D E  F  G H   I  J K
146578  **   value:     123 5 9 1 1 14 35 0 234 72 0
146579  **
146580  ** The 123 value is the first docid.  For column zero in this document
146581  ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
146582  ** at D signals the start of a new column; the 1 at E indicates that the
146583  ** new column is column number 1.  There are two positions at 12 and 45
146584  ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
146585  ** 234 at I is the delta to next docid (357).  It has one position 70
146586  ** (72-2) and then terminates with the 0 at K.
146587  **
146588  ** A "position-list" is the list of positions for multiple columns for
146589  ** a single docid.  A "column-list" is the set of positions for a single
146590  ** column.  Hence, a position-list consists of one or more column-lists,
146591  ** a document record consists of a docid followed by a position-list and
146592  ** a doclist consists of one or more document records.
146593  **
146594  ** A bare doclist omits the position information, becoming an 
146595  ** array of varint-encoded docids.
146596  **
146597  **** Segment leaf nodes ****
146598  ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
146599  ** nodes are written using LeafWriter, and read using LeafReader (to
146600  ** iterate through a single leaf node's data) and LeavesReader (to
146601  ** iterate through a segment's entire leaf layer).  Leaf nodes have
146602  ** the format:
146603  **
146604  ** varint iHeight;             (height from leaf level, always 0)
146605  ** varint nTerm;               (length of first term)
146606  ** char pTerm[nTerm];          (content of first term)
146607  ** varint nDoclist;            (length of term's associated doclist)
146608  ** char pDoclist[nDoclist];    (content of doclist)
146609  ** array {
146610  **                             (further terms are delta-encoded)
146611  **   varint nPrefix;           (length of prefix shared with previous term)
146612  **   varint nSuffix;           (length of unshared suffix)
146613  **   char pTermSuffix[nSuffix];(unshared suffix of next term)
146614  **   varint nDoclist;          (length of term's associated doclist)
146615  **   char pDoclist[nDoclist];  (content of doclist)
146616  ** }
146617  **
146618  ** Here, array { X } means zero or more occurrences of X, adjacent in
146619  ** memory.
146620  **
146621  ** Leaf nodes are broken into blocks which are stored contiguously in
146622  ** the %_segments table in sorted order.  This means that when the end
146623  ** of a node is reached, the next term is in the node with the next
146624  ** greater node id.
146625  **
146626  ** New data is spilled to a new leaf node when the current node
146627  ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
146628  ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
146629  ** node (a leaf node with a single term and doclist).  The goal of
146630  ** these settings is to pack together groups of small doclists while
146631  ** making it efficient to directly access large doclists.  The
146632  ** assumption is that large doclists represent terms which are more
146633  ** likely to be query targets.
146634  **
146635  ** TODO(shess) It may be useful for blocking decisions to be more
146636  ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
146637  ** node rather than splitting into 2k and .5k nodes.  My intuition is
146638  ** that this might extend through 2x or 4x the pagesize.
146639  **
146640  **
146641  **** Segment interior nodes ****
146642  ** Segment interior nodes store blockids for subtree nodes and terms
146643  ** to describe what data is stored by the each subtree.  Interior
146644  ** nodes are written using InteriorWriter, and read using
146645  ** InteriorReader.  InteriorWriters are created as needed when
146646  ** SegmentWriter creates new leaf nodes, or when an interior node
146647  ** itself grows too big and must be split.  The format of interior
146648  ** nodes:
146649  **
146650  ** varint iHeight;           (height from leaf level, always >0)
146651  ** varint iBlockid;          (block id of node's leftmost subtree)
146652  ** optional {
146653  **   varint nTerm;           (length of first term)
146654  **   char pTerm[nTerm];      (content of first term)
146655  **   array {
146656  **                                (further terms are delta-encoded)
146657  **     varint nPrefix;            (length of shared prefix with previous term)
146658  **     varint nSuffix;            (length of unshared suffix)
146659  **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
146660  **   }
146661  ** }
146662  **
146663  ** Here, optional { X } means an optional element, while array { X }
146664  ** means zero or more occurrences of X, adjacent in memory.
146665  **
146666  ** An interior node encodes n terms separating n+1 subtrees.  The
146667  ** subtree blocks are contiguous, so only the first subtree's blockid
146668  ** is encoded.  The subtree at iBlockid will contain all terms less
146669  ** than the first term encoded (or all terms if no term is encoded).
146670  ** Otherwise, for terms greater than or equal to pTerm[i] but less
146671  ** than pTerm[i+1], the subtree for that term will be rooted at
146672  ** iBlockid+i.  Interior nodes only store enough term data to
146673  ** distinguish adjacent children (if the rightmost term of the left
146674  ** child is "something", and the leftmost term of the right child is
146675  ** "wicked", only "w" is stored).
146676  **
146677  ** New data is spilled to a new interior node at the same height when
146678  ** the current node exceeds INTERIOR_MAX bytes (default 2048).
146679  ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
146680  ** interior nodes and making the tree too skinny.  The interior nodes
146681  ** at a given height are naturally tracked by interior nodes at
146682  ** height+1, and so on.
146683  **
146684  **
146685  **** Segment directory ****
146686  ** The segment directory in table %_segdir stores meta-information for
146687  ** merging and deleting segments, and also the root node of the
146688  ** segment's tree.
146689  **
146690  ** The root node is the top node of the segment's tree after encoding
146691  ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
146692  ** This could be either a leaf node or an interior node.  If the top
146693  ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
146694  ** and a new root interior node is generated (which should always fit
146695  ** within ROOT_MAX because it only needs space for 2 varints, the
146696  ** height and the blockid of the previous root).
146697  **
146698  ** The meta-information in the segment directory is:
146699  **   level               - segment level (see below)
146700  **   idx                 - index within level
146701  **                       - (level,idx uniquely identify a segment)
146702  **   start_block         - first leaf node
146703  **   leaves_end_block    - last leaf node
146704  **   end_block           - last block (including interior nodes)
146705  **   root                - contents of root node
146706  **
146707  ** If the root node is a leaf node, then start_block,
146708  ** leaves_end_block, and end_block are all 0.
146709  **
146710  **
146711  **** Segment merging ****
146712  ** To amortize update costs, segments are grouped into levels and
146713  ** merged in batches.  Each increase in level represents exponentially
146714  ** more documents.
146715  **
146716  ** New documents (actually, document updates) are tokenized and
146717  ** written individually (using LeafWriter) to a level 0 segment, with
146718  ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
146719  ** level 0 segments are merged into a single level 1 segment.  Level 1
146720  ** is populated like level 0, and eventually MERGE_COUNT level 1
146721  ** segments are merged to a single level 2 segment (representing
146722  ** MERGE_COUNT^2 updates), and so on.
146723  **
146724  ** A segment merge traverses all segments at a given level in
146725  ** parallel, performing a straightforward sorted merge.  Since segment
146726  ** leaf nodes are written in to the %_segments table in order, this
146727  ** merge traverses the underlying sqlite disk structures efficiently.
146728  ** After the merge, all segment blocks from the merged level are
146729  ** deleted.
146730  **
146731  ** MERGE_COUNT controls how often we merge segments.  16 seems to be
146732  ** somewhat of a sweet spot for insertion performance.  32 and 64 show
146733  ** very similar performance numbers to 16 on insertion, though they're
146734  ** a tiny bit slower (perhaps due to more overhead in merge-time
146735  ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
146736  ** 16, 2 about 66% slower than 16.
146737  **
146738  ** At query time, high MERGE_COUNT increases the number of segments
146739  ** which need to be scanned and merged.  For instance, with 100k docs
146740  ** inserted:
146741  **
146742  **    MERGE_COUNT   segments
146743  **       16           25
146744  **        8           12
146745  **        4           10
146746  **        2            6
146747  **
146748  ** This appears to have only a moderate impact on queries for very
146749  ** frequent terms (which are somewhat dominated by segment merge
146750  ** costs), and infrequent and non-existent terms still seem to be fast
146751  ** even with many segments.
146752  **
146753  ** TODO(shess) That said, it would be nice to have a better query-side
146754  ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
146755  ** optimizations to things like doclist merging will swing the sweet
146756  ** spot around.
146757  **
146758  **
146759  **
146760  **** Handling of deletions and updates ****
146761  ** Since we're using a segmented structure, with no docid-oriented
146762  ** index into the term index, we clearly cannot simply update the term
146763  ** index when a document is deleted or updated.  For deletions, we
146764  ** write an empty doclist (varint(docid) varint(POS_END)), for updates
146765  ** we simply write the new doclist.  Segment merges overwrite older
146766  ** data for a particular docid with newer data, so deletes or updates
146767  ** will eventually overtake the earlier data and knock it out.  The
146768  ** query logic likewise merges doclists so that newer data knocks out
146769  ** older data.
146770  */
146771  
146772  /************** Include fts3Int.h in the middle of fts3.c ********************/
146773  /************** Begin file fts3Int.h *****************************************/
146774  /*
146775  ** 2009 Nov 12
146776  **
146777  ** The author disclaims copyright to this source code.  In place of
146778  ** a legal notice, here is a blessing:
146779  **
146780  **    May you do good and not evil.
146781  **    May you find forgiveness for yourself and forgive others.
146782  **    May you share freely, never taking more than you give.
146783  **
146784  ******************************************************************************
146785  **
146786  */
146787  #ifndef _FTSINT_H
146788  #define _FTSINT_H
146789  
146790  #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
146791  # define NDEBUG 1
146792  #endif
146793  
146794  /* FTS3/FTS4 require virtual tables */
146795  #ifdef SQLITE_OMIT_VIRTUALTABLE
146796  # undef SQLITE_ENABLE_FTS3
146797  # undef SQLITE_ENABLE_FTS4
146798  #endif
146799  
146800  /*
146801  ** FTS4 is really an extension for FTS3.  It is enabled using the
146802  ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
146803  ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
146804  */
146805  #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
146806  # define SQLITE_ENABLE_FTS3
146807  #endif
146808  
146809  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
146810  
146811  /* If not building as part of the core, include sqlite3ext.h. */
146812  #ifndef SQLITE_CORE
146813  /* # include "sqlite3ext.h"  */
146814  SQLITE_EXTENSION_INIT3
146815  #endif
146816  
146817  /* #include "sqlite3.h" */
146818  /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
146819  /************** Begin file fts3_tokenizer.h **********************************/
146820  /*
146821  ** 2006 July 10
146822  **
146823  ** The author disclaims copyright to this source code.
146824  **
146825  *************************************************************************
146826  ** Defines the interface to tokenizers used by fulltext-search.  There
146827  ** are three basic components:
146828  **
146829  ** sqlite3_tokenizer_module is a singleton defining the tokenizer
146830  ** interface functions.  This is essentially the class structure for
146831  ** tokenizers.
146832  **
146833  ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
146834  ** including customization information defined at creation time.
146835  **
146836  ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
146837  ** tokens from a particular input.
146838  */
146839  #ifndef _FTS3_TOKENIZER_H_
146840  #define _FTS3_TOKENIZER_H_
146841  
146842  /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
146843  ** If tokenizers are to be allowed to call sqlite3_*() functions, then
146844  ** we will need a way to register the API consistently.
146845  */
146846  /* #include "sqlite3.h" */
146847  
146848  /*
146849  ** Structures used by the tokenizer interface. When a new tokenizer
146850  ** implementation is registered, the caller provides a pointer to
146851  ** an sqlite3_tokenizer_module containing pointers to the callback
146852  ** functions that make up an implementation.
146853  **
146854  ** When an fts3 table is created, it passes any arguments passed to
146855  ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
146856  ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
146857  ** implementation. The xCreate() function in turn returns an 
146858  ** sqlite3_tokenizer structure representing the specific tokenizer to
146859  ** be used for the fts3 table (customized by the tokenizer clause arguments).
146860  **
146861  ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
146862  ** method is called. It returns an sqlite3_tokenizer_cursor object
146863  ** that may be used to tokenize a specific input buffer based on
146864  ** the tokenization rules supplied by a specific sqlite3_tokenizer
146865  ** object.
146866  */
146867  typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
146868  typedef struct sqlite3_tokenizer sqlite3_tokenizer;
146869  typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
146870  
146871  struct sqlite3_tokenizer_module {
146872  
146873    /*
146874    ** Structure version. Should always be set to 0 or 1.
146875    */
146876    int iVersion;
146877  
146878    /*
146879    ** Create a new tokenizer. The values in the argv[] array are the
146880    ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
146881    ** TABLE statement that created the fts3 table. For example, if
146882    ** the following SQL is executed:
146883    **
146884    **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
146885    **
146886    ** then argc is set to 2, and the argv[] array contains pointers
146887    ** to the strings "arg1" and "arg2".
146888    **
146889    ** This method should return either SQLITE_OK (0), or an SQLite error 
146890    ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
146891    ** to point at the newly created tokenizer structure. The generic
146892    ** sqlite3_tokenizer.pModule variable should not be initialized by
146893    ** this callback. The caller will do so.
146894    */
146895    int (*xCreate)(
146896      int argc,                           /* Size of argv array */
146897      const char *const*argv,             /* Tokenizer argument strings */
146898      sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
146899    );
146900  
146901    /*
146902    ** Destroy an existing tokenizer. The fts3 module calls this method
146903    ** exactly once for each successful call to xCreate().
146904    */
146905    int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
146906  
146907    /*
146908    ** Create a tokenizer cursor to tokenize an input buffer. The caller
146909    ** is responsible for ensuring that the input buffer remains valid
146910    ** until the cursor is closed (using the xClose() method). 
146911    */
146912    int (*xOpen)(
146913      sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
146914      const char *pInput, int nBytes,      /* Input buffer */
146915      sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
146916    );
146917  
146918    /*
146919    ** Destroy an existing tokenizer cursor. The fts3 module calls this 
146920    ** method exactly once for each successful call to xOpen().
146921    */
146922    int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
146923  
146924    /*
146925    ** Retrieve the next token from the tokenizer cursor pCursor. This
146926    ** method should either return SQLITE_OK and set the values of the
146927    ** "OUT" variables identified below, or SQLITE_DONE to indicate that
146928    ** the end of the buffer has been reached, or an SQLite error code.
146929    **
146930    ** *ppToken should be set to point at a buffer containing the 
146931    ** normalized version of the token (i.e. after any case-folding and/or
146932    ** stemming has been performed). *pnBytes should be set to the length
146933    ** of this buffer in bytes. The input text that generated the token is
146934    ** identified by the byte offsets returned in *piStartOffset and
146935    ** *piEndOffset. *piStartOffset should be set to the index of the first
146936    ** byte of the token in the input buffer. *piEndOffset should be set
146937    ** to the index of the first byte just past the end of the token in
146938    ** the input buffer.
146939    **
146940    ** The buffer *ppToken is set to point at is managed by the tokenizer
146941    ** implementation. It is only required to be valid until the next call
146942    ** to xNext() or xClose(). 
146943    */
146944    /* TODO(shess) current implementation requires pInput to be
146945    ** nul-terminated.  This should either be fixed, or pInput/nBytes
146946    ** should be converted to zInput.
146947    */
146948    int (*xNext)(
146949      sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
146950      const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
146951      int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
146952      int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
146953      int *piPosition      /* OUT: Number of tokens returned before this one */
146954    );
146955  
146956    /***********************************************************************
146957    ** Methods below this point are only available if iVersion>=1.
146958    */
146959  
146960    /* 
146961    ** Configure the language id of a tokenizer cursor.
146962    */
146963    int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
146964  };
146965  
146966  struct sqlite3_tokenizer {
146967    const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
146968    /* Tokenizer implementations will typically add additional fields */
146969  };
146970  
146971  struct sqlite3_tokenizer_cursor {
146972    sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
146973    /* Tokenizer implementations will typically add additional fields */
146974  };
146975  
146976  int fts3_global_term_cnt(int iTerm, int iCol);
146977  int fts3_term_cnt(int iTerm, int iCol);
146978  
146979  
146980  #endif /* _FTS3_TOKENIZER_H_ */
146981  
146982  /************** End of fts3_tokenizer.h **************************************/
146983  /************** Continuing where we left off in fts3Int.h ********************/
146984  /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
146985  /************** Begin file fts3_hash.h ***************************************/
146986  /*
146987  ** 2001 September 22
146988  **
146989  ** The author disclaims copyright to this source code.  In place of
146990  ** a legal notice, here is a blessing:
146991  **
146992  **    May you do good and not evil.
146993  **    May you find forgiveness for yourself and forgive others.
146994  **    May you share freely, never taking more than you give.
146995  **
146996  *************************************************************************
146997  ** This is the header file for the generic hash-table implementation
146998  ** used in SQLite.  We've modified it slightly to serve as a standalone
146999  ** hash table implementation for the full-text indexing module.
147000  **
147001  */
147002  #ifndef _FTS3_HASH_H_
147003  #define _FTS3_HASH_H_
147004  
147005  /* Forward declarations of structures. */
147006  typedef struct Fts3Hash Fts3Hash;
147007  typedef struct Fts3HashElem Fts3HashElem;
147008  
147009  /* A complete hash table is an instance of the following structure.
147010  ** The internals of this structure are intended to be opaque -- client
147011  ** code should not attempt to access or modify the fields of this structure
147012  ** directly.  Change this structure only by using the routines below.
147013  ** However, many of the "procedures" and "functions" for modifying and
147014  ** accessing this structure are really macros, so we can't really make
147015  ** this structure opaque.
147016  */
147017  struct Fts3Hash {
147018    char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
147019    char copyKey;           /* True if copy of key made on insert */
147020    int count;              /* Number of entries in this table */
147021    Fts3HashElem *first;    /* The first element of the array */
147022    int htsize;             /* Number of buckets in the hash table */
147023    struct _fts3ht {        /* the hash table */
147024      int count;               /* Number of entries with this hash */
147025      Fts3HashElem *chain;     /* Pointer to first entry with this hash */
147026    } *ht;
147027  };
147028  
147029  /* Each element in the hash table is an instance of the following 
147030  ** structure.  All elements are stored on a single doubly-linked list.
147031  **
147032  ** Again, this structure is intended to be opaque, but it can't really
147033  ** be opaque because it is used by macros.
147034  */
147035  struct Fts3HashElem {
147036    Fts3HashElem *next, *prev; /* Next and previous elements in the table */
147037    void *data;                /* Data associated with this element */
147038    void *pKey; int nKey;      /* Key associated with this element */
147039  };
147040  
147041  /*
147042  ** There are 2 different modes of operation for a hash table:
147043  **
147044  **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
147045  **                           (including the null-terminator, if any).  Case
147046  **                           is respected in comparisons.
147047  **
147048  **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
147049  **                           memcmp() is used to compare keys.
147050  **
147051  ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
147052  */
147053  #define FTS3_HASH_STRING    1
147054  #define FTS3_HASH_BINARY    2
147055  
147056  /*
147057  ** Access routines.  To delete, insert a NULL pointer.
147058  */
147059  SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
147060  SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
147061  SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
147062  SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
147063  SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
147064  
147065  /*
147066  ** Shorthand for the functions above
147067  */
147068  #define fts3HashInit     sqlite3Fts3HashInit
147069  #define fts3HashInsert   sqlite3Fts3HashInsert
147070  #define fts3HashFind     sqlite3Fts3HashFind
147071  #define fts3HashClear    sqlite3Fts3HashClear
147072  #define fts3HashFindElem sqlite3Fts3HashFindElem
147073  
147074  /*
147075  ** Macros for looping over all elements of a hash table.  The idiom is
147076  ** like this:
147077  **
147078  **   Fts3Hash h;
147079  **   Fts3HashElem *p;
147080  **   ...
147081  **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
147082  **     SomeStructure *pData = fts3HashData(p);
147083  **     // do something with pData
147084  **   }
147085  */
147086  #define fts3HashFirst(H)  ((H)->first)
147087  #define fts3HashNext(E)   ((E)->next)
147088  #define fts3HashData(E)   ((E)->data)
147089  #define fts3HashKey(E)    ((E)->pKey)
147090  #define fts3HashKeysize(E) ((E)->nKey)
147091  
147092  /*
147093  ** Number of entries in a hash table
147094  */
147095  #define fts3HashCount(H)  ((H)->count)
147096  
147097  #endif /* _FTS3_HASH_H_ */
147098  
147099  /************** End of fts3_hash.h *******************************************/
147100  /************** Continuing where we left off in fts3Int.h ********************/
147101  
147102  /*
147103  ** This constant determines the maximum depth of an FTS expression tree
147104  ** that the library will create and use. FTS uses recursion to perform 
147105  ** various operations on the query tree, so the disadvantage of a large
147106  ** limit is that it may allow very large queries to use large amounts
147107  ** of stack space (perhaps causing a stack overflow).
147108  */
147109  #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
147110  # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
147111  #endif
147112  
147113  
147114  /*
147115  ** This constant controls how often segments are merged. Once there are
147116  ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
147117  ** segment of level N+1.
147118  */
147119  #define FTS3_MERGE_COUNT 16
147120  
147121  /*
147122  ** This is the maximum amount of data (in bytes) to store in the 
147123  ** Fts3Table.pendingTerms hash table. Normally, the hash table is
147124  ** populated as documents are inserted/updated/deleted in a transaction
147125  ** and used to create a new segment when the transaction is committed.
147126  ** However if this limit is reached midway through a transaction, a new 
147127  ** segment is created and the hash table cleared immediately.
147128  */
147129  #define FTS3_MAX_PENDING_DATA (1*1024*1024)
147130  
147131  /*
147132  ** Macro to return the number of elements in an array. SQLite has a
147133  ** similar macro called ArraySize(). Use a different name to avoid
147134  ** a collision when building an amalgamation with built-in FTS3.
147135  */
147136  #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
147137  
147138  
147139  #ifndef MIN
147140  # define MIN(x,y) ((x)<(y)?(x):(y))
147141  #endif
147142  #ifndef MAX
147143  # define MAX(x,y) ((x)>(y)?(x):(y))
147144  #endif
147145  
147146  /*
147147  ** Maximum length of a varint encoded integer. The varint format is different
147148  ** from that used by SQLite, so the maximum length is 10, not 9.
147149  */
147150  #define FTS3_VARINT_MAX 10
147151  
147152  /*
147153  ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
147154  ** in the document set and zero or more prefix indexes. All indexes are stored
147155  ** as one or more b+-trees in the %_segments and %_segdir tables. 
147156  **
147157  ** It is possible to determine which index a b+-tree belongs to based on the
147158  ** value stored in the "%_segdir.level" column. Given this value L, the index
147159  ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
147160  ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
147161  ** between 1024 and 2047 to index 1, and so on.
147162  **
147163  ** It is considered impossible for an index to use more than 1024 levels. In 
147164  ** theory though this may happen, but only after at least 
147165  ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
147166  */
147167  #define FTS3_SEGDIR_MAXLEVEL      1024
147168  #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
147169  
147170  /*
147171  ** The testcase() macro is only used by the amalgamation.  If undefined,
147172  ** make it a no-op.
147173  */
147174  #ifndef testcase
147175  # define testcase(X)
147176  #endif
147177  
147178  /*
147179  ** Terminator values for position-lists and column-lists.
147180  */
147181  #define POS_COLUMN  (1)     /* Column-list terminator */
147182  #define POS_END     (0)     /* Position-list terminator */ 
147183  
147184  /*
147185  ** This section provides definitions to allow the
147186  ** FTS3 extension to be compiled outside of the 
147187  ** amalgamation.
147188  */
147189  #ifndef SQLITE_AMALGAMATION
147190  /*
147191  ** Macros indicating that conditional expressions are always true or
147192  ** false.
147193  */
147194  #ifdef SQLITE_COVERAGE_TEST
147195  # define ALWAYS(x) (1)
147196  # define NEVER(X)  (0)
147197  #elif defined(SQLITE_DEBUG)
147198  # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
147199  # define NEVER(x) sqlite3Fts3Never((x)!=0)
147200  SQLITE_PRIVATE int sqlite3Fts3Always(int b);
147201  SQLITE_PRIVATE int sqlite3Fts3Never(int b);
147202  #else
147203  # define ALWAYS(x) (x)
147204  # define NEVER(x)  (x)
147205  #endif
147206  
147207  /*
147208  ** Internal types used by SQLite.
147209  */
147210  typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
147211  typedef short int i16;            /* 2-byte (or larger) signed integer */
147212  typedef unsigned int u32;         /* 4-byte unsigned integer */
147213  typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
147214  typedef sqlite3_int64 i64;        /* 8-byte signed integer */
147215  
147216  /*
147217  ** Macro used to suppress compiler warnings for unused parameters.
147218  */
147219  #define UNUSED_PARAMETER(x) (void)(x)
147220  
147221  /*
147222  ** Activate assert() only if SQLITE_TEST is enabled.
147223  */
147224  #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
147225  # define NDEBUG 1
147226  #endif
147227  
147228  /*
147229  ** The TESTONLY macro is used to enclose variable declarations or
147230  ** other bits of code that are needed to support the arguments
147231  ** within testcase() and assert() macros.
147232  */
147233  #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
147234  # define TESTONLY(X)  X
147235  #else
147236  # define TESTONLY(X)
147237  #endif
147238  
147239  #endif /* SQLITE_AMALGAMATION */
147240  
147241  #ifdef SQLITE_DEBUG
147242  SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
147243  # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
147244  #else
147245  # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
147246  #endif
147247  
147248  typedef struct Fts3Table Fts3Table;
147249  typedef struct Fts3Cursor Fts3Cursor;
147250  typedef struct Fts3Expr Fts3Expr;
147251  typedef struct Fts3Phrase Fts3Phrase;
147252  typedef struct Fts3PhraseToken Fts3PhraseToken;
147253  
147254  typedef struct Fts3Doclist Fts3Doclist;
147255  typedef struct Fts3SegFilter Fts3SegFilter;
147256  typedef struct Fts3DeferredToken Fts3DeferredToken;
147257  typedef struct Fts3SegReader Fts3SegReader;
147258  typedef struct Fts3MultiSegReader Fts3MultiSegReader;
147259  
147260  typedef struct MatchinfoBuffer MatchinfoBuffer;
147261  
147262  /*
147263  ** A connection to a fulltext index is an instance of the following
147264  ** structure. The xCreate and xConnect methods create an instance
147265  ** of this structure and xDestroy and xDisconnect free that instance.
147266  ** All other methods receive a pointer to the structure as one of their
147267  ** arguments.
147268  */
147269  struct Fts3Table {
147270    sqlite3_vtab base;              /* Base class used by SQLite core */
147271    sqlite3 *db;                    /* The database connection */
147272    const char *zDb;                /* logical database name */
147273    const char *zName;              /* virtual table name */
147274    int nColumn;                    /* number of named columns in virtual table */
147275    char **azColumn;                /* column names.  malloced */
147276    u8 *abNotindexed;               /* True for 'notindexed' columns */
147277    sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
147278    char *zContentTbl;              /* content=xxx option, or NULL */
147279    char *zLanguageid;              /* languageid=xxx option, or NULL */
147280    int nAutoincrmerge;             /* Value configured by 'automerge' */
147281    u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
147282  
147283    /* Precompiled statements used by the implementation. Each of these 
147284    ** statements is run and reset within a single virtual table API call. 
147285    */
147286    sqlite3_stmt *aStmt[40];
147287    sqlite3_stmt *pSeekStmt;        /* Cache for fts3CursorSeekStmt() */
147288  
147289    char *zReadExprlist;
147290    char *zWriteExprlist;
147291  
147292    int nNodeSize;                  /* Soft limit for node size */
147293    u8 bFts4;                       /* True for FTS4, false for FTS3 */
147294    u8 bHasStat;                    /* True if %_stat table exists (2==unknown) */
147295    u8 bHasDocsize;                 /* True if %_docsize table exists */
147296    u8 bDescIdx;                    /* True if doclists are in reverse order */
147297    u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
147298    int nPgsz;                      /* Page size for host database */
147299    char *zSegmentsTbl;             /* Name of %_segments table */
147300    sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
147301  
147302    /* 
147303    ** The following array of hash tables is used to buffer pending index 
147304    ** updates during transactions. All pending updates buffered at any one
147305    ** time must share a common language-id (see the FTS4 langid= feature).
147306    ** The current language id is stored in variable iPrevLangid.
147307    **
147308    ** A single FTS4 table may have multiple full-text indexes. For each index
147309    ** there is an entry in the aIndex[] array. Index 0 is an index of all the
147310    ** terms that appear in the document set. Each subsequent index in aIndex[]
147311    ** is an index of prefixes of a specific length.
147312    **
147313    ** Variable nPendingData contains an estimate the memory consumed by the 
147314    ** pending data structures, including hash table overhead, but not including
147315    ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
147316    ** tables are flushed to disk. Variable iPrevDocid is the docid of the most 
147317    ** recently inserted record.
147318    */
147319    int nIndex;                     /* Size of aIndex[] */
147320    struct Fts3Index {
147321      int nPrefix;                  /* Prefix length (0 for main terms index) */
147322      Fts3Hash hPending;            /* Pending terms table for this index */
147323    } *aIndex;
147324    int nMaxPendingData;            /* Max pending data before flush to disk */
147325    int nPendingData;               /* Current bytes of pending data */
147326    sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
147327    int iPrevLangid;                /* Langid of recently inserted document */
147328    int bPrevDelete;                /* True if last operation was a delete */
147329  
147330  #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
147331    /* State variables used for validating that the transaction control
147332    ** methods of the virtual table are called at appropriate times.  These
147333    ** values do not contribute to FTS functionality; they are used for
147334    ** verifying the operation of the SQLite core.
147335    */
147336    int inTransaction;     /* True after xBegin but before xCommit/xRollback */
147337    int mxSavepoint;       /* Largest valid xSavepoint integer */
147338  #endif
147339  
147340  #ifdef SQLITE_TEST
147341    /* True to disable the incremental doclist optimization. This is controled
147342    ** by special insert command 'test-no-incr-doclist'.  */
147343    int bNoIncrDoclist;
147344  #endif
147345  };
147346  
147347  /*
147348  ** When the core wants to read from the virtual table, it creates a
147349  ** virtual table cursor (an instance of the following structure) using
147350  ** the xOpen method. Cursors are destroyed using the xClose method.
147351  */
147352  struct Fts3Cursor {
147353    sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
147354    i16 eSearch;                    /* Search strategy (see below) */
147355    u8 isEof;                       /* True if at End Of Results */
147356    u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
147357    u8 bSeekStmt;                   /* True if pStmt is a seek */
147358    sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
147359    Fts3Expr *pExpr;                /* Parsed MATCH query string */
147360    int iLangid;                    /* Language being queried for */
147361    int nPhrase;                    /* Number of matchable phrases in query */
147362    Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
147363    sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
147364    char *pNextId;                  /* Pointer into the body of aDoclist */
147365    char *aDoclist;                 /* List of docids for full-text queries */
147366    int nDoclist;                   /* Size of buffer at aDoclist */
147367    u8 bDesc;                       /* True to sort in descending order */
147368    int eEvalmode;                  /* An FTS3_EVAL_XX constant */
147369    int nRowAvg;                    /* Average size of database rows, in pages */
147370    sqlite3_int64 nDoc;             /* Documents in table */
147371    i64 iMinDocid;                  /* Minimum docid to return */
147372    i64 iMaxDocid;                  /* Maximum docid to return */
147373    int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
147374    MatchinfoBuffer *pMIBuffer;     /* Buffer for matchinfo data */
147375  };
147376  
147377  #define FTS3_EVAL_FILTER    0
147378  #define FTS3_EVAL_NEXT      1
147379  #define FTS3_EVAL_MATCHINFO 2
147380  
147381  /*
147382  ** The Fts3Cursor.eSearch member is always set to one of the following.
147383  ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
147384  ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
147385  ** of the column to be searched.  For example, in
147386  **
147387  **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
147388  **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
147389  ** 
147390  ** Because the LHS of the MATCH operator is 2nd column "b",
147391  ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
147392  ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
147393  ** indicating that all columns should be searched,
147394  ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
147395  */
147396  #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
147397  #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
147398  #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
147399  
147400  /*
147401  ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
147402  ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
147403  ** above. The upper 16-bits contain a combination of the following
147404  ** bits, used to describe extra constraints on full-text searches.
147405  */
147406  #define FTS3_HAVE_LANGID    0x00010000      /* languageid=? */
147407  #define FTS3_HAVE_DOCID_GE  0x00020000      /* docid>=? */
147408  #define FTS3_HAVE_DOCID_LE  0x00040000      /* docid<=? */
147409  
147410  struct Fts3Doclist {
147411    char *aAll;                    /* Array containing doclist (or NULL) */
147412    int nAll;                      /* Size of a[] in bytes */
147413    char *pNextDocid;              /* Pointer to next docid */
147414  
147415    sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
147416    int bFreeList;                 /* True if pList should be sqlite3_free()d */
147417    char *pList;                   /* Pointer to position list following iDocid */
147418    int nList;                     /* Length of position list */
147419  };
147420  
147421  /*
147422  ** A "phrase" is a sequence of one or more tokens that must match in
147423  ** sequence.  A single token is the base case and the most common case.
147424  ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
147425  ** nToken will be the number of tokens in the string.
147426  */
147427  struct Fts3PhraseToken {
147428    char *z;                        /* Text of the token */
147429    int n;                          /* Number of bytes in buffer z */
147430    int isPrefix;                   /* True if token ends with a "*" character */
147431    int bFirst;                     /* True if token must appear at position 0 */
147432  
147433    /* Variables above this point are populated when the expression is
147434    ** parsed (by code in fts3_expr.c). Below this point the variables are
147435    ** used when evaluating the expression. */
147436    Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
147437    Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
147438  };
147439  
147440  struct Fts3Phrase {
147441    /* Cache of doclist for this phrase. */
147442    Fts3Doclist doclist;
147443    int bIncr;                 /* True if doclist is loaded incrementally */
147444    int iDoclistToken;
147445  
147446    /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
147447    ** OR condition.  */
147448    char *pOrPoslist;
147449    i64 iOrDocid;
147450  
147451    /* Variables below this point are populated by fts3_expr.c when parsing 
147452    ** a MATCH expression. Everything above is part of the evaluation phase. 
147453    */
147454    int nToken;                /* Number of tokens in the phrase */
147455    int iColumn;               /* Index of column this phrase must match */
147456    Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
147457  };
147458  
147459  /*
147460  ** A tree of these objects forms the RHS of a MATCH operator.
147461  **
147462  ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist 
147463  ** points to a malloced buffer, size nDoclist bytes, containing the results 
147464  ** of this phrase query in FTS3 doclist format. As usual, the initial 
147465  ** "Length" field found in doclists stored on disk is omitted from this 
147466  ** buffer.
147467  **
147468  ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
147469  ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
147470  ** where nCol is the number of columns in the queried FTS table. The array
147471  ** is populated as follows:
147472  **
147473  **   aMI[iCol*3 + 0] = Undefined
147474  **   aMI[iCol*3 + 1] = Number of occurrences
147475  **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
147476  **
147477  ** The aMI array is allocated using sqlite3_malloc(). It should be freed 
147478  ** when the expression node is.
147479  */
147480  struct Fts3Expr {
147481    int eType;                 /* One of the FTSQUERY_XXX values defined below */
147482    int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
147483    Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
147484    Fts3Expr *pLeft;           /* Left operand */
147485    Fts3Expr *pRight;          /* Right operand */
147486    Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
147487  
147488    /* The following are used by the fts3_eval.c module. */
147489    sqlite3_int64 iDocid;      /* Current docid */
147490    u8 bEof;                   /* True this expression is at EOF already */
147491    u8 bStart;                 /* True if iDocid is valid */
147492    u8 bDeferred;              /* True if this expression is entirely deferred */
147493  
147494    /* The following are used by the fts3_snippet.c module. */
147495    int iPhrase;               /* Index of this phrase in matchinfo() results */
147496    u32 *aMI;                  /* See above */
147497  };
147498  
147499  /*
147500  ** Candidate values for Fts3Query.eType. Note that the order of the first
147501  ** four values is in order of precedence when parsing expressions. For 
147502  ** example, the following:
147503  **
147504  **   "a OR b AND c NOT d NEAR e"
147505  **
147506  ** is equivalent to:
147507  **
147508  **   "a OR (b AND (c NOT (d NEAR e)))"
147509  */
147510  #define FTSQUERY_NEAR   1
147511  #define FTSQUERY_NOT    2
147512  #define FTSQUERY_AND    3
147513  #define FTSQUERY_OR     4
147514  #define FTSQUERY_PHRASE 5
147515  
147516  
147517  /* fts3_write.c */
147518  SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
147519  SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
147520  SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
147521  SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
147522  SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
147523    sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
147524  SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
147525    Fts3Table*,int,const char*,int,int,Fts3SegReader**);
147526  SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
147527  SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
147528  SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
147529  
147530  SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
147531  SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
147532  
147533  #ifndef SQLITE_DISABLE_FTS4_DEFERRED
147534  SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
147535  SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
147536  SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
147537  SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
147538  SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
147539  #else
147540  # define sqlite3Fts3FreeDeferredTokens(x)
147541  # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
147542  # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
147543  # define sqlite3Fts3FreeDeferredDoclists(x)
147544  # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
147545  #endif
147546  
147547  SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
147548  SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
147549  
147550  /* Special values interpreted by sqlite3SegReaderCursor() */
147551  #define FTS3_SEGCURSOR_PENDING        -1
147552  #define FTS3_SEGCURSOR_ALL            -2
147553  
147554  SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
147555  SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
147556  SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
147557  
147558  SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *, 
147559      int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
147560  
147561  /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
147562  #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
147563  #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
147564  #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
147565  #define FTS3_SEGMENT_PREFIX        0x00000008
147566  #define FTS3_SEGMENT_SCAN          0x00000010
147567  #define FTS3_SEGMENT_FIRST         0x00000020
147568  
147569  /* Type passed as 4th argument to SegmentReaderIterate() */
147570  struct Fts3SegFilter {
147571    const char *zTerm;
147572    int nTerm;
147573    int iCol;
147574    int flags;
147575  };
147576  
147577  struct Fts3MultiSegReader {
147578    /* Used internally by sqlite3Fts3SegReaderXXX() calls */
147579    Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
147580    int nSegment;                   /* Size of apSegment array */
147581    int nAdvance;                   /* How many seg-readers to advance */
147582    Fts3SegFilter *pFilter;         /* Pointer to filter object */
147583    char *aBuffer;                  /* Buffer to merge doclists in */
147584    int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
147585  
147586    int iColFilter;                 /* If >=0, filter for this column */
147587    int bRestart;
147588  
147589    /* Used by fts3.c only. */
147590    int nCost;                      /* Cost of running iterator */
147591    int bLookup;                    /* True if a lookup of a single entry. */
147592  
147593    /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
147594    char *zTerm;                    /* Pointer to term buffer */
147595    int nTerm;                      /* Size of zTerm in bytes */
147596    char *aDoclist;                 /* Pointer to doclist buffer */
147597    int nDoclist;                   /* Size of aDoclist[] in bytes */
147598  };
147599  
147600  SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
147601  
147602  #define fts3GetVarint32(p, piVal) (                                           \
147603    (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
147604  )
147605  
147606  /* fts3.c */
147607  SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
147608  SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
147609  SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
147610  SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
147611  SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
147612  SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
147613  SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
147614  SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
147615  SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
147616  SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
147617  SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
147618  
147619  /* fts3_tokenizer.c */
147620  SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
147621  SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
147622  SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, 
147623      sqlite3_tokenizer **, char **
147624  );
147625  SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
147626  
147627  /* fts3_snippet.c */
147628  SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
147629  SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
147630    const char *, const char *, int, int
147631  );
147632  SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
147633  SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
147634  
147635  /* fts3_expr.c */
147636  SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
147637    char **, int, int, int, const char *, int, Fts3Expr **, char **
147638  );
147639  SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
147640  #ifdef SQLITE_TEST
147641  SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
147642  SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
147643  #endif
147644  
147645  SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
147646    sqlite3_tokenizer_cursor **
147647  );
147648  
147649  /* fts3_aux.c */
147650  SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
147651  
147652  SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
147653  
147654  SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
147655      Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
147656  SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
147657      Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
147658  SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **); 
147659  SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
147660  SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
147661  
147662  /* fts3_tokenize_vtab.c */
147663  SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
147664  
147665  /* fts3_unicode2.c (functions generated by parsing unicode text files) */
147666  #ifndef SQLITE_DISABLE_FTS3_UNICODE
147667  SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
147668  SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
147669  SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
147670  #endif
147671  
147672  #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
147673  #endif /* _FTSINT_H */
147674  
147675  /************** End of fts3Int.h *********************************************/
147676  /************** Continuing where we left off in fts3.c ***********************/
147677  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
147678  
147679  #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
147680  # define SQLITE_CORE 1
147681  #endif
147682  
147683  /* #include <assert.h> */
147684  /* #include <stdlib.h> */
147685  /* #include <stddef.h> */
147686  /* #include <stdio.h> */
147687  /* #include <string.h> */
147688  /* #include <stdarg.h> */
147689  
147690  /* #include "fts3.h" */
147691  #ifndef SQLITE_CORE 
147692  /* # include "sqlite3ext.h" */
147693    SQLITE_EXTENSION_INIT1
147694  #endif
147695  
147696  static int fts3EvalNext(Fts3Cursor *pCsr);
147697  static int fts3EvalStart(Fts3Cursor *pCsr);
147698  static int fts3TermSegReaderCursor(
147699      Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
147700  
147701  #ifndef SQLITE_AMALGAMATION
147702  # if defined(SQLITE_DEBUG)
147703  SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
147704  SQLITE_PRIVATE int sqlite3Fts3Never(int b)  { assert( !b ); return b; }
147705  # endif
147706  #endif
147707  
147708  /* 
147709  ** Write a 64-bit variable-length integer to memory starting at p[0].
147710  ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
147711  ** The number of bytes written is returned.
147712  */
147713  SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
147714    unsigned char *q = (unsigned char *) p;
147715    sqlite_uint64 vu = v;
147716    do{
147717      *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
147718      vu >>= 7;
147719    }while( vu!=0 );
147720    q[-1] &= 0x7f;  /* turn off high bit in final byte */
147721    assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
147722    return (int) (q - (unsigned char *)p);
147723  }
147724  
147725  #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
147726    v = (v & mask1) | ( (*ptr++) << shift );                    \
147727    if( (v & mask2)==0 ){ var = v; return ret; }
147728  #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
147729    v = (*ptr++);                                               \
147730    if( (v & mask2)==0 ){ var = v; return ret; }
147731  
147732  /* 
147733  ** Read a 64-bit variable-length integer from memory starting at p[0].
147734  ** Return the number of bytes read, or 0 on error.
147735  ** The value is stored in *v.
147736  */
147737  SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
147738    const unsigned char *p = (const unsigned char*)pBuf;
147739    const unsigned char *pStart = p;
147740    u32 a;
147741    u64 b;
147742    int shift;
147743  
147744    GETVARINT_INIT(a, p, 0,  0x00,     0x80, *v, 1);
147745    GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *v, 2);
147746    GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *v, 3);
147747    GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
147748    b = (a & 0x0FFFFFFF );
147749  
147750    for(shift=28; shift<=63; shift+=7){
147751      u64 c = *p++;
147752      b += (c&0x7F) << shift;
147753      if( (c & 0x80)==0 ) break;
147754    }
147755    *v = b;
147756    return (int)(p - pStart);
147757  }
147758  
147759  /*
147760  ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to 
147761  ** a non-negative 32-bit integer before it is returned.
147762  */
147763  SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
147764    u32 a;
147765  
147766  #ifndef fts3GetVarint32
147767    GETVARINT_INIT(a, p, 0,  0x00,     0x80, *pi, 1);
147768  #else
147769    a = (*p++);
147770    assert( a & 0x80 );
147771  #endif
147772  
147773    GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *pi, 2);
147774    GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *pi, 3);
147775    GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
147776    a = (a & 0x0FFFFFFF );
147777    *pi = (int)(a | ((u32)(*p & 0x07) << 28));
147778    assert( 0==(a & 0x80000000) );
147779    assert( *pi>=0 );
147780    return 5;
147781  }
147782  
147783  /*
147784  ** Return the number of bytes required to encode v as a varint
147785  */
147786  SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
147787    int i = 0;
147788    do{
147789      i++;
147790      v >>= 7;
147791    }while( v!=0 );
147792    return i;
147793  }
147794  
147795  /*
147796  ** Convert an SQL-style quoted string into a normal string by removing
147797  ** the quote characters.  The conversion is done in-place.  If the
147798  ** input does not begin with a quote character, then this routine
147799  ** is a no-op.
147800  **
147801  ** Examples:
147802  **
147803  **     "abc"   becomes   abc
147804  **     'xyz'   becomes   xyz
147805  **     [pqr]   becomes   pqr
147806  **     `mno`   becomes   mno
147807  **
147808  */
147809  SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
147810    char quote;                     /* Quote character (if any ) */
147811  
147812    quote = z[0];
147813    if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
147814      int iIn = 1;                  /* Index of next byte to read from input */
147815      int iOut = 0;                 /* Index of next byte to write to output */
147816  
147817      /* If the first byte was a '[', then the close-quote character is a ']' */
147818      if( quote=='[' ) quote = ']';  
147819  
147820      while( z[iIn] ){
147821        if( z[iIn]==quote ){
147822          if( z[iIn+1]!=quote ) break;
147823          z[iOut++] = quote;
147824          iIn += 2;
147825        }else{
147826          z[iOut++] = z[iIn++];
147827        }
147828      }
147829      z[iOut] = '\0';
147830    }
147831  }
147832  
147833  /*
147834  ** Read a single varint from the doclist at *pp and advance *pp to point
147835  ** to the first byte past the end of the varint.  Add the value of the varint
147836  ** to *pVal.
147837  */
147838  static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
147839    sqlite3_int64 iVal;
147840    *pp += sqlite3Fts3GetVarint(*pp, &iVal);
147841    *pVal += iVal;
147842  }
147843  
147844  /*
147845  ** When this function is called, *pp points to the first byte following a
147846  ** varint that is part of a doclist (or position-list, or any other list
147847  ** of varints). This function moves *pp to point to the start of that varint,
147848  ** and sets *pVal by the varint value.
147849  **
147850  ** Argument pStart points to the first byte of the doclist that the
147851  ** varint is part of.
147852  */
147853  static void fts3GetReverseVarint(
147854    char **pp, 
147855    char *pStart, 
147856    sqlite3_int64 *pVal
147857  ){
147858    sqlite3_int64 iVal;
147859    char *p;
147860  
147861    /* Pointer p now points at the first byte past the varint we are 
147862    ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
147863    ** clear on character p[-1]. */
147864    for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
147865    p++;
147866    *pp = p;
147867  
147868    sqlite3Fts3GetVarint(p, &iVal);
147869    *pVal = iVal;
147870  }
147871  
147872  /*
147873  ** The xDisconnect() virtual table method.
147874  */
147875  static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
147876    Fts3Table *p = (Fts3Table *)pVtab;
147877    int i;
147878  
147879    assert( p->nPendingData==0 );
147880    assert( p->pSegments==0 );
147881  
147882    /* Free any prepared statements held */
147883    sqlite3_finalize(p->pSeekStmt);
147884    for(i=0; i<SizeofArray(p->aStmt); i++){
147885      sqlite3_finalize(p->aStmt[i]);
147886    }
147887    sqlite3_free(p->zSegmentsTbl);
147888    sqlite3_free(p->zReadExprlist);
147889    sqlite3_free(p->zWriteExprlist);
147890    sqlite3_free(p->zContentTbl);
147891    sqlite3_free(p->zLanguageid);
147892  
147893    /* Invoke the tokenizer destructor to free the tokenizer. */
147894    p->pTokenizer->pModule->xDestroy(p->pTokenizer);
147895  
147896    sqlite3_free(p);
147897    return SQLITE_OK;
147898  }
147899  
147900  /*
147901  ** Write an error message into *pzErr
147902  */
147903  SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
147904    va_list ap;
147905    sqlite3_free(*pzErr);
147906    va_start(ap, zFormat);
147907    *pzErr = sqlite3_vmprintf(zFormat, ap);
147908    va_end(ap);
147909  }
147910  
147911  /*
147912  ** Construct one or more SQL statements from the format string given
147913  ** and then evaluate those statements. The success code is written
147914  ** into *pRc.
147915  **
147916  ** If *pRc is initially non-zero then this routine is a no-op.
147917  */
147918  static void fts3DbExec(
147919    int *pRc,              /* Success code */
147920    sqlite3 *db,           /* Database in which to run SQL */
147921    const char *zFormat,   /* Format string for SQL */
147922    ...                    /* Arguments to the format string */
147923  ){
147924    va_list ap;
147925    char *zSql;
147926    if( *pRc ) return;
147927    va_start(ap, zFormat);
147928    zSql = sqlite3_vmprintf(zFormat, ap);
147929    va_end(ap);
147930    if( zSql==0 ){
147931      *pRc = SQLITE_NOMEM;
147932    }else{
147933      *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
147934      sqlite3_free(zSql);
147935    }
147936  }
147937  
147938  /*
147939  ** The xDestroy() virtual table method.
147940  */
147941  static int fts3DestroyMethod(sqlite3_vtab *pVtab){
147942    Fts3Table *p = (Fts3Table *)pVtab;
147943    int rc = SQLITE_OK;              /* Return code */
147944    const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
147945    sqlite3 *db = p->db;             /* Database handle */
147946  
147947    /* Drop the shadow tables */
147948    if( p->zContentTbl==0 ){
147949      fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
147950    }
147951    fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
147952    fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
147953    fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
147954    fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
147955  
147956    /* If everything has worked, invoke fts3DisconnectMethod() to free the
147957    ** memory associated with the Fts3Table structure and return SQLITE_OK.
147958    ** Otherwise, return an SQLite error code.
147959    */
147960    return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
147961  }
147962  
147963  
147964  /*
147965  ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
147966  ** passed as the first argument. This is done as part of the xConnect()
147967  ** and xCreate() methods.
147968  **
147969  ** If *pRc is non-zero when this function is called, it is a no-op. 
147970  ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
147971  ** before returning.
147972  */
147973  static void fts3DeclareVtab(int *pRc, Fts3Table *p){
147974    if( *pRc==SQLITE_OK ){
147975      int i;                        /* Iterator variable */
147976      int rc;                       /* Return code */
147977      char *zSql;                   /* SQL statement passed to declare_vtab() */
147978      char *zCols;                  /* List of user defined columns */
147979      const char *zLanguageid;
147980  
147981      zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
147982      sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
147983  
147984      /* Create a list of user columns for the virtual table */
147985      zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
147986      for(i=1; zCols && i<p->nColumn; i++){
147987        zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
147988      }
147989  
147990      /* Create the whole "CREATE TABLE" statement to pass to SQLite */
147991      zSql = sqlite3_mprintf(
147992          "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)", 
147993          zCols, p->zName, zLanguageid
147994      );
147995      if( !zCols || !zSql ){
147996        rc = SQLITE_NOMEM;
147997      }else{
147998        rc = sqlite3_declare_vtab(p->db, zSql);
147999      }
148000  
148001      sqlite3_free(zSql);
148002      sqlite3_free(zCols);
148003      *pRc = rc;
148004    }
148005  }
148006  
148007  /*
148008  ** Create the %_stat table if it does not already exist.
148009  */
148010  SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
148011    fts3DbExec(pRc, p->db, 
148012        "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
148013            "(id INTEGER PRIMARY KEY, value BLOB);",
148014        p->zDb, p->zName
148015    );
148016    if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
148017  }
148018  
148019  /*
148020  ** Create the backing store tables (%_content, %_segments and %_segdir)
148021  ** required by the FTS3 table passed as the only argument. This is done
148022  ** as part of the vtab xCreate() method.
148023  **
148024  ** If the p->bHasDocsize boolean is true (indicating that this is an
148025  ** FTS4 table, not an FTS3 table) then also create the %_docsize and
148026  ** %_stat tables required by FTS4.
148027  */
148028  static int fts3CreateTables(Fts3Table *p){
148029    int rc = SQLITE_OK;             /* Return code */
148030    int i;                          /* Iterator variable */
148031    sqlite3 *db = p->db;            /* The database connection */
148032  
148033    if( p->zContentTbl==0 ){
148034      const char *zLanguageid = p->zLanguageid;
148035      char *zContentCols;           /* Columns of %_content table */
148036  
148037      /* Create a list of user columns for the content table */
148038      zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
148039      for(i=0; zContentCols && i<p->nColumn; i++){
148040        char *z = p->azColumn[i];
148041        zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
148042      }
148043      if( zLanguageid && zContentCols ){
148044        zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
148045      }
148046      if( zContentCols==0 ) rc = SQLITE_NOMEM;
148047    
148048      /* Create the content table */
148049      fts3DbExec(&rc, db, 
148050         "CREATE TABLE %Q.'%q_content'(%s)",
148051         p->zDb, p->zName, zContentCols
148052      );
148053      sqlite3_free(zContentCols);
148054    }
148055  
148056    /* Create other tables */
148057    fts3DbExec(&rc, db, 
148058        "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
148059        p->zDb, p->zName
148060    );
148061    fts3DbExec(&rc, db, 
148062        "CREATE TABLE %Q.'%q_segdir'("
148063          "level INTEGER,"
148064          "idx INTEGER,"
148065          "start_block INTEGER,"
148066          "leaves_end_block INTEGER,"
148067          "end_block INTEGER,"
148068          "root BLOB,"
148069          "PRIMARY KEY(level, idx)"
148070        ");",
148071        p->zDb, p->zName
148072    );
148073    if( p->bHasDocsize ){
148074      fts3DbExec(&rc, db, 
148075          "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
148076          p->zDb, p->zName
148077      );
148078    }
148079    assert( p->bHasStat==p->bFts4 );
148080    if( p->bHasStat ){
148081      sqlite3Fts3CreateStatTable(&rc, p);
148082    }
148083    return rc;
148084  }
148085  
148086  /*
148087  ** Store the current database page-size in bytes in p->nPgsz.
148088  **
148089  ** If *pRc is non-zero when this function is called, it is a no-op. 
148090  ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
148091  ** before returning.
148092  */
148093  static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
148094    if( *pRc==SQLITE_OK ){
148095      int rc;                       /* Return code */
148096      char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
148097      sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
148098    
148099      zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
148100      if( !zSql ){
148101        rc = SQLITE_NOMEM;
148102      }else{
148103        rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
148104        if( rc==SQLITE_OK ){
148105          sqlite3_step(pStmt);
148106          p->nPgsz = sqlite3_column_int(pStmt, 0);
148107          rc = sqlite3_finalize(pStmt);
148108        }else if( rc==SQLITE_AUTH ){
148109          p->nPgsz = 1024;
148110          rc = SQLITE_OK;
148111        }
148112      }
148113      assert( p->nPgsz>0 || rc!=SQLITE_OK );
148114      sqlite3_free(zSql);
148115      *pRc = rc;
148116    }
148117  }
148118  
148119  /*
148120  ** "Special" FTS4 arguments are column specifications of the following form:
148121  **
148122  **   <key> = <value>
148123  **
148124  ** There may not be whitespace surrounding the "=" character. The <value> 
148125  ** term may be quoted, but the <key> may not.
148126  */
148127  static int fts3IsSpecialColumn(
148128    const char *z, 
148129    int *pnKey,
148130    char **pzValue
148131  ){
148132    char *zValue;
148133    const char *zCsr = z;
148134  
148135    while( *zCsr!='=' ){
148136      if( *zCsr=='\0' ) return 0;
148137      zCsr++;
148138    }
148139  
148140    *pnKey = (int)(zCsr-z);
148141    zValue = sqlite3_mprintf("%s", &zCsr[1]);
148142    if( zValue ){
148143      sqlite3Fts3Dequote(zValue);
148144    }
148145    *pzValue = zValue;
148146    return 1;
148147  }
148148  
148149  /*
148150  ** Append the output of a printf() style formatting to an existing string.
148151  */
148152  static void fts3Appendf(
148153    int *pRc,                       /* IN/OUT: Error code */
148154    char **pz,                      /* IN/OUT: Pointer to string buffer */
148155    const char *zFormat,            /* Printf format string to append */
148156    ...                             /* Arguments for printf format string */
148157  ){
148158    if( *pRc==SQLITE_OK ){
148159      va_list ap;
148160      char *z;
148161      va_start(ap, zFormat);
148162      z = sqlite3_vmprintf(zFormat, ap);
148163      va_end(ap);
148164      if( z && *pz ){
148165        char *z2 = sqlite3_mprintf("%s%s", *pz, z);
148166        sqlite3_free(z);
148167        z = z2;
148168      }
148169      if( z==0 ) *pRc = SQLITE_NOMEM;
148170      sqlite3_free(*pz);
148171      *pz = z;
148172    }
148173  }
148174  
148175  /*
148176  ** Return a copy of input string zInput enclosed in double-quotes (") and
148177  ** with all double quote characters escaped. For example:
148178  **
148179  **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
148180  **
148181  ** The pointer returned points to memory obtained from sqlite3_malloc(). It
148182  ** is the callers responsibility to call sqlite3_free() to release this
148183  ** memory.
148184  */
148185  static char *fts3QuoteId(char const *zInput){
148186    int nRet;
148187    char *zRet;
148188    nRet = 2 + (int)strlen(zInput)*2 + 1;
148189    zRet = sqlite3_malloc(nRet);
148190    if( zRet ){
148191      int i;
148192      char *z = zRet;
148193      *(z++) = '"';
148194      for(i=0; zInput[i]; i++){
148195        if( zInput[i]=='"' ) *(z++) = '"';
148196        *(z++) = zInput[i];
148197      }
148198      *(z++) = '"';
148199      *(z++) = '\0';
148200    }
148201    return zRet;
148202  }
148203  
148204  /*
148205  ** Return a list of comma separated SQL expressions and a FROM clause that 
148206  ** could be used in a SELECT statement such as the following:
148207  **
148208  **     SELECT <list of expressions> FROM %_content AS x ...
148209  **
148210  ** to return the docid, followed by each column of text data in order
148211  ** from left to write. If parameter zFunc is not NULL, then instead of
148212  ** being returned directly each column of text data is passed to an SQL
148213  ** function named zFunc first. For example, if zFunc is "unzip" and the
148214  ** table has the three user-defined columns "a", "b", and "c", the following
148215  ** string is returned:
148216  **
148217  **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
148218  **
148219  ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
148220  ** is the responsibility of the caller to eventually free it.
148221  **
148222  ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
148223  ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
148224  ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
148225  ** no error occurs, *pRc is left unmodified.
148226  */
148227  static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
148228    char *zRet = 0;
148229    char *zFree = 0;
148230    char *zFunction;
148231    int i;
148232  
148233    if( p->zContentTbl==0 ){
148234      if( !zFunc ){
148235        zFunction = "";
148236      }else{
148237        zFree = zFunction = fts3QuoteId(zFunc);
148238      }
148239      fts3Appendf(pRc, &zRet, "docid");
148240      for(i=0; i<p->nColumn; i++){
148241        fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
148242      }
148243      if( p->zLanguageid ){
148244        fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
148245      }
148246      sqlite3_free(zFree);
148247    }else{
148248      fts3Appendf(pRc, &zRet, "rowid");
148249      for(i=0; i<p->nColumn; i++){
148250        fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
148251      }
148252      if( p->zLanguageid ){
148253        fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
148254      }
148255    }
148256    fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x", 
148257        p->zDb,
148258        (p->zContentTbl ? p->zContentTbl : p->zName),
148259        (p->zContentTbl ? "" : "_content")
148260    );
148261    return zRet;
148262  }
148263  
148264  /*
148265  ** Return a list of N comma separated question marks, where N is the number
148266  ** of columns in the %_content table (one for the docid plus one for each
148267  ** user-defined text column).
148268  **
148269  ** If argument zFunc is not NULL, then all but the first question mark
148270  ** is preceded by zFunc and an open bracket, and followed by a closed
148271  ** bracket. For example, if zFunc is "zip" and the FTS3 table has three 
148272  ** user-defined text columns, the following string is returned:
148273  **
148274  **     "?, zip(?), zip(?), zip(?)"
148275  **
148276  ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
148277  ** is the responsibility of the caller to eventually free it.
148278  **
148279  ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
148280  ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
148281  ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
148282  ** no error occurs, *pRc is left unmodified.
148283  */
148284  static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
148285    char *zRet = 0;
148286    char *zFree = 0;
148287    char *zFunction;
148288    int i;
148289  
148290    if( !zFunc ){
148291      zFunction = "";
148292    }else{
148293      zFree = zFunction = fts3QuoteId(zFunc);
148294    }
148295    fts3Appendf(pRc, &zRet, "?");
148296    for(i=0; i<p->nColumn; i++){
148297      fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
148298    }
148299    if( p->zLanguageid ){
148300      fts3Appendf(pRc, &zRet, ", ?");
148301    }
148302    sqlite3_free(zFree);
148303    return zRet;
148304  }
148305  
148306  /*
148307  ** This function interprets the string at (*pp) as a non-negative integer
148308  ** value. It reads the integer and sets *pnOut to the value read, then 
148309  ** sets *pp to point to the byte immediately following the last byte of
148310  ** the integer value.
148311  **
148312  ** Only decimal digits ('0'..'9') may be part of an integer value. 
148313  **
148314  ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
148315  ** the output value undefined. Otherwise SQLITE_OK is returned.
148316  **
148317  ** This function is used when parsing the "prefix=" FTS4 parameter.
148318  */
148319  static int fts3GobbleInt(const char **pp, int *pnOut){
148320    const int MAX_NPREFIX = 10000000;
148321    const char *p;                  /* Iterator pointer */
148322    int nInt = 0;                   /* Output value */
148323  
148324    for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
148325      nInt = nInt * 10 + (p[0] - '0');
148326      if( nInt>MAX_NPREFIX ){
148327        nInt = 0;
148328        break;
148329      }
148330    }
148331    if( p==*pp ) return SQLITE_ERROR;
148332    *pnOut = nInt;
148333    *pp = p;
148334    return SQLITE_OK;
148335  }
148336  
148337  /*
148338  ** This function is called to allocate an array of Fts3Index structures
148339  ** representing the indexes maintained by the current FTS table. FTS tables
148340  ** always maintain the main "terms" index, but may also maintain one or
148341  ** more "prefix" indexes, depending on the value of the "prefix=" parameter
148342  ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
148343  **
148344  ** Argument zParam is passed the value of the "prefix=" option if one was
148345  ** specified, or NULL otherwise.
148346  **
148347  ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
148348  ** the allocated array. *pnIndex is set to the number of elements in the
148349  ** array. If an error does occur, an SQLite error code is returned.
148350  **
148351  ** Regardless of whether or not an error is returned, it is the responsibility
148352  ** of the caller to call sqlite3_free() on the output array to free it.
148353  */
148354  static int fts3PrefixParameter(
148355    const char *zParam,             /* ABC in prefix=ABC parameter to parse */
148356    int *pnIndex,                   /* OUT: size of *apIndex[] array */
148357    struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
148358  ){
148359    struct Fts3Index *aIndex;       /* Allocated array */
148360    int nIndex = 1;                 /* Number of entries in array */
148361  
148362    if( zParam && zParam[0] ){
148363      const char *p;
148364      nIndex++;
148365      for(p=zParam; *p; p++){
148366        if( *p==',' ) nIndex++;
148367      }
148368    }
148369  
148370    aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
148371    *apIndex = aIndex;
148372    if( !aIndex ){
148373      return SQLITE_NOMEM;
148374    }
148375  
148376    memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
148377    if( zParam ){
148378      const char *p = zParam;
148379      int i;
148380      for(i=1; i<nIndex; i++){
148381        int nPrefix = 0;
148382        if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
148383        assert( nPrefix>=0 );
148384        if( nPrefix==0 ){
148385          nIndex--;
148386          i--;
148387        }else{
148388          aIndex[i].nPrefix = nPrefix;
148389        }
148390        p++;
148391      }
148392    }
148393  
148394    *pnIndex = nIndex;
148395    return SQLITE_OK;
148396  }
148397  
148398  /*
148399  ** This function is called when initializing an FTS4 table that uses the
148400  ** content=xxx option. It determines the number of and names of the columns
148401  ** of the new FTS4 table.
148402  **
148403  ** The third argument passed to this function is the value passed to the
148404  ** config=xxx option (i.e. "xxx"). This function queries the database for
148405  ** a table of that name. If found, the output variables are populated
148406  ** as follows:
148407  **
148408  **   *pnCol:   Set to the number of columns table xxx has,
148409  **
148410  **   *pnStr:   Set to the total amount of space required to store a copy
148411  **             of each columns name, including the nul-terminator.
148412  **
148413  **   *pazCol:  Set to point to an array of *pnCol strings. Each string is
148414  **             the name of the corresponding column in table xxx. The array
148415  **             and its contents are allocated using a single allocation. It
148416  **             is the responsibility of the caller to free this allocation
148417  **             by eventually passing the *pazCol value to sqlite3_free().
148418  **
148419  ** If the table cannot be found, an error code is returned and the output
148420  ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
148421  ** returned (and the output variables are undefined).
148422  */
148423  static int fts3ContentColumns(
148424    sqlite3 *db,                    /* Database handle */
148425    const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
148426    const char *zTbl,               /* Name of content table */
148427    const char ***pazCol,           /* OUT: Malloc'd array of column names */
148428    int *pnCol,                     /* OUT: Size of array *pazCol */
148429    int *pnStr,                     /* OUT: Bytes of string content */
148430    char **pzErr                    /* OUT: error message */
148431  ){
148432    int rc = SQLITE_OK;             /* Return code */
148433    char *zSql;                     /* "SELECT *" statement on zTbl */  
148434    sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
148435  
148436    zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
148437    if( !zSql ){
148438      rc = SQLITE_NOMEM;
148439    }else{
148440      rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
148441      if( rc!=SQLITE_OK ){
148442        sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
148443      }
148444    }
148445    sqlite3_free(zSql);
148446  
148447    if( rc==SQLITE_OK ){
148448      const char **azCol;           /* Output array */
148449      int nStr = 0;                 /* Size of all column names (incl. 0x00) */
148450      int nCol;                     /* Number of table columns */
148451      int i;                        /* Used to iterate through columns */
148452  
148453      /* Loop through the returned columns. Set nStr to the number of bytes of
148454      ** space required to store a copy of each column name, including the
148455      ** nul-terminator byte.  */
148456      nCol = sqlite3_column_count(pStmt);
148457      for(i=0; i<nCol; i++){
148458        const char *zCol = sqlite3_column_name(pStmt, i);
148459        nStr += (int)strlen(zCol) + 1;
148460      }
148461  
148462      /* Allocate and populate the array to return. */
148463      azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
148464      if( azCol==0 ){
148465        rc = SQLITE_NOMEM;
148466      }else{
148467        char *p = (char *)&azCol[nCol];
148468        for(i=0; i<nCol; i++){
148469          const char *zCol = sqlite3_column_name(pStmt, i);
148470          int n = (int)strlen(zCol)+1;
148471          memcpy(p, zCol, n);
148472          azCol[i] = p;
148473          p += n;
148474        }
148475      }
148476      sqlite3_finalize(pStmt);
148477  
148478      /* Set the output variables. */
148479      *pnCol = nCol;
148480      *pnStr = nStr;
148481      *pazCol = azCol;
148482    }
148483  
148484    return rc;
148485  }
148486  
148487  /*
148488  ** This function is the implementation of both the xConnect and xCreate
148489  ** methods of the FTS3 virtual table.
148490  **
148491  ** The argv[] array contains the following:
148492  **
148493  **   argv[0]   -> module name  ("fts3" or "fts4")
148494  **   argv[1]   -> database name
148495  **   argv[2]   -> table name
148496  **   argv[...] -> "column name" and other module argument fields.
148497  */
148498  static int fts3InitVtab(
148499    int isCreate,                   /* True for xCreate, false for xConnect */
148500    sqlite3 *db,                    /* The SQLite database connection */
148501    void *pAux,                     /* Hash table containing tokenizers */
148502    int argc,                       /* Number of elements in argv array */
148503    const char * const *argv,       /* xCreate/xConnect argument array */
148504    sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
148505    char **pzErr                    /* Write any error message here */
148506  ){
148507    Fts3Hash *pHash = (Fts3Hash *)pAux;
148508    Fts3Table *p = 0;               /* Pointer to allocated vtab */
148509    int rc = SQLITE_OK;             /* Return code */
148510    int i;                          /* Iterator variable */
148511    int nByte;                      /* Size of allocation used for *p */
148512    int iCol;                       /* Column index */
148513    int nString = 0;                /* Bytes required to hold all column names */
148514    int nCol = 0;                   /* Number of columns in the FTS table */
148515    char *zCsr;                     /* Space for holding column names */
148516    int nDb;                        /* Bytes required to hold database name */
148517    int nName;                      /* Bytes required to hold table name */
148518    int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
148519    const char **aCol;              /* Array of column names */
148520    sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
148521  
148522    int nIndex = 0;                 /* Size of aIndex[] array */
148523    struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
148524  
148525    /* The results of parsing supported FTS4 key=value options: */
148526    int bNoDocsize = 0;             /* True to omit %_docsize table */
148527    int bDescIdx = 0;               /* True to store descending indexes */
148528    char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
148529    char *zCompress = 0;            /* compress=? parameter (or NULL) */
148530    char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
148531    char *zContent = 0;             /* content=? parameter (or NULL) */
148532    char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
148533    char **azNotindexed = 0;        /* The set of notindexed= columns */
148534    int nNotindexed = 0;            /* Size of azNotindexed[] array */
148535  
148536    assert( strlen(argv[0])==4 );
148537    assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
148538         || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
148539    );
148540  
148541    nDb = (int)strlen(argv[1]) + 1;
148542    nName = (int)strlen(argv[2]) + 1;
148543  
148544    nByte = sizeof(const char *) * (argc-2);
148545    aCol = (const char **)sqlite3_malloc(nByte);
148546    if( aCol ){
148547      memset((void*)aCol, 0, nByte);
148548      azNotindexed = (char **)sqlite3_malloc(nByte);
148549    }
148550    if( azNotindexed ){
148551      memset(azNotindexed, 0, nByte);
148552    }
148553    if( !aCol || !azNotindexed ){
148554      rc = SQLITE_NOMEM;
148555      goto fts3_init_out;
148556    }
148557  
148558    /* Loop through all of the arguments passed by the user to the FTS3/4
148559    ** module (i.e. all the column names and special arguments). This loop
148560    ** does the following:
148561    **
148562    **   + Figures out the number of columns the FTSX table will have, and
148563    **     the number of bytes of space that must be allocated to store copies
148564    **     of the column names.
148565    **
148566    **   + If there is a tokenizer specification included in the arguments,
148567    **     initializes the tokenizer pTokenizer.
148568    */
148569    for(i=3; rc==SQLITE_OK && i<argc; i++){
148570      char const *z = argv[i];
148571      int nKey;
148572      char *zVal;
148573  
148574      /* Check if this is a tokenizer specification */
148575      if( !pTokenizer 
148576       && strlen(z)>8
148577       && 0==sqlite3_strnicmp(z, "tokenize", 8) 
148578       && 0==sqlite3Fts3IsIdChar(z[8])
148579      ){
148580        rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
148581      }
148582  
148583      /* Check if it is an FTS4 special argument. */
148584      else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
148585        struct Fts4Option {
148586          const char *zOpt;
148587          int nOpt;
148588        } aFts4Opt[] = {
148589          { "matchinfo",   9 },     /* 0 -> MATCHINFO */
148590          { "prefix",      6 },     /* 1 -> PREFIX */
148591          { "compress",    8 },     /* 2 -> COMPRESS */
148592          { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
148593          { "order",       5 },     /* 4 -> ORDER */
148594          { "content",     7 },     /* 5 -> CONTENT */
148595          { "languageid", 10 },     /* 6 -> LANGUAGEID */
148596          { "notindexed", 10 }      /* 7 -> NOTINDEXED */
148597        };
148598  
148599        int iOpt;
148600        if( !zVal ){
148601          rc = SQLITE_NOMEM;
148602        }else{
148603          for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
148604            struct Fts4Option *pOp = &aFts4Opt[iOpt];
148605            if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
148606              break;
148607            }
148608          }
148609          switch( iOpt ){
148610            case 0:               /* MATCHINFO */
148611              if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
148612                sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
148613                rc = SQLITE_ERROR;
148614              }
148615              bNoDocsize = 1;
148616              break;
148617  
148618            case 1:               /* PREFIX */
148619              sqlite3_free(zPrefix);
148620              zPrefix = zVal;
148621              zVal = 0;
148622              break;
148623  
148624            case 2:               /* COMPRESS */
148625              sqlite3_free(zCompress);
148626              zCompress = zVal;
148627              zVal = 0;
148628              break;
148629  
148630            case 3:               /* UNCOMPRESS */
148631              sqlite3_free(zUncompress);
148632              zUncompress = zVal;
148633              zVal = 0;
148634              break;
148635  
148636            case 4:               /* ORDER */
148637              if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3)) 
148638               && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4)) 
148639              ){
148640                sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
148641                rc = SQLITE_ERROR;
148642              }
148643              bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
148644              break;
148645  
148646            case 5:              /* CONTENT */
148647              sqlite3_free(zContent);
148648              zContent = zVal;
148649              zVal = 0;
148650              break;
148651  
148652            case 6:              /* LANGUAGEID */
148653              assert( iOpt==6 );
148654              sqlite3_free(zLanguageid);
148655              zLanguageid = zVal;
148656              zVal = 0;
148657              break;
148658  
148659            case 7:              /* NOTINDEXED */
148660              azNotindexed[nNotindexed++] = zVal;
148661              zVal = 0;
148662              break;
148663  
148664            default:
148665              assert( iOpt==SizeofArray(aFts4Opt) );
148666              sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
148667              rc = SQLITE_ERROR;
148668              break;
148669          }
148670          sqlite3_free(zVal);
148671        }
148672      }
148673  
148674      /* Otherwise, the argument is a column name. */
148675      else {
148676        nString += (int)(strlen(z) + 1);
148677        aCol[nCol++] = z;
148678      }
148679    }
148680  
148681    /* If a content=xxx option was specified, the following:
148682    **
148683    **   1. Ignore any compress= and uncompress= options.
148684    **
148685    **   2. If no column names were specified as part of the CREATE VIRTUAL
148686    **      TABLE statement, use all columns from the content table.
148687    */
148688    if( rc==SQLITE_OK && zContent ){
148689      sqlite3_free(zCompress); 
148690      sqlite3_free(zUncompress); 
148691      zCompress = 0;
148692      zUncompress = 0;
148693      if( nCol==0 ){
148694        sqlite3_free((void*)aCol); 
148695        aCol = 0;
148696        rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
148697  
148698        /* If a languageid= option was specified, remove the language id
148699        ** column from the aCol[] array. */ 
148700        if( rc==SQLITE_OK && zLanguageid ){
148701          int j;
148702          for(j=0; j<nCol; j++){
148703            if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
148704              int k;
148705              for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
148706              nCol--;
148707              break;
148708            }
148709          }
148710        }
148711      }
148712    }
148713    if( rc!=SQLITE_OK ) goto fts3_init_out;
148714  
148715    if( nCol==0 ){
148716      assert( nString==0 );
148717      aCol[0] = "content";
148718      nString = 8;
148719      nCol = 1;
148720    }
148721  
148722    if( pTokenizer==0 ){
148723      rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
148724      if( rc!=SQLITE_OK ) goto fts3_init_out;
148725    }
148726    assert( pTokenizer );
148727  
148728    rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
148729    if( rc==SQLITE_ERROR ){
148730      assert( zPrefix );
148731      sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
148732    }
148733    if( rc!=SQLITE_OK ) goto fts3_init_out;
148734  
148735    /* Allocate and populate the Fts3Table structure. */
148736    nByte = sizeof(Fts3Table) +                  /* Fts3Table */
148737            nCol * sizeof(char *) +              /* azColumn */
148738            nIndex * sizeof(struct Fts3Index) +  /* aIndex */
148739            nCol * sizeof(u8) +                  /* abNotindexed */
148740            nName +                              /* zName */
148741            nDb +                                /* zDb */
148742            nString;                             /* Space for azColumn strings */
148743    p = (Fts3Table*)sqlite3_malloc(nByte);
148744    if( p==0 ){
148745      rc = SQLITE_NOMEM;
148746      goto fts3_init_out;
148747    }
148748    memset(p, 0, nByte);
148749    p->db = db;
148750    p->nColumn = nCol;
148751    p->nPendingData = 0;
148752    p->azColumn = (char **)&p[1];
148753    p->pTokenizer = pTokenizer;
148754    p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
148755    p->bHasDocsize = (isFts4 && bNoDocsize==0);
148756    p->bHasStat = (u8)isFts4;
148757    p->bFts4 = (u8)isFts4;
148758    p->bDescIdx = (u8)bDescIdx;
148759    p->nAutoincrmerge = 0xff;   /* 0xff means setting unknown */
148760    p->zContentTbl = zContent;
148761    p->zLanguageid = zLanguageid;
148762    zContent = 0;
148763    zLanguageid = 0;
148764    TESTONLY( p->inTransaction = -1 );
148765    TESTONLY( p->mxSavepoint = -1 );
148766  
148767    p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
148768    memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
148769    p->nIndex = nIndex;
148770    for(i=0; i<nIndex; i++){
148771      fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
148772    }
148773    p->abNotindexed = (u8 *)&p->aIndex[nIndex];
148774  
148775    /* Fill in the zName and zDb fields of the vtab structure. */
148776    zCsr = (char *)&p->abNotindexed[nCol];
148777    p->zName = zCsr;
148778    memcpy(zCsr, argv[2], nName);
148779    zCsr += nName;
148780    p->zDb = zCsr;
148781    memcpy(zCsr, argv[1], nDb);
148782    zCsr += nDb;
148783  
148784    /* Fill in the azColumn array */
148785    for(iCol=0; iCol<nCol; iCol++){
148786      char *z; 
148787      int n = 0;
148788      z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
148789      if( n>0 ){
148790        memcpy(zCsr, z, n);
148791      }
148792      zCsr[n] = '\0';
148793      sqlite3Fts3Dequote(zCsr);
148794      p->azColumn[iCol] = zCsr;
148795      zCsr += n+1;
148796      assert( zCsr <= &((char *)p)[nByte] );
148797    }
148798  
148799    /* Fill in the abNotindexed array */
148800    for(iCol=0; iCol<nCol; iCol++){
148801      int n = (int)strlen(p->azColumn[iCol]);
148802      for(i=0; i<nNotindexed; i++){
148803        char *zNot = azNotindexed[i];
148804        if( zNot && n==(int)strlen(zNot)
148805         && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n) 
148806        ){
148807          p->abNotindexed[iCol] = 1;
148808          sqlite3_free(zNot);
148809          azNotindexed[i] = 0;
148810        }
148811      }
148812    }
148813    for(i=0; i<nNotindexed; i++){
148814      if( azNotindexed[i] ){
148815        sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
148816        rc = SQLITE_ERROR;
148817      }
148818    }
148819  
148820    if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
148821      char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
148822      rc = SQLITE_ERROR;
148823      sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
148824    }
148825    p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
148826    p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
148827    if( rc!=SQLITE_OK ) goto fts3_init_out;
148828  
148829    /* If this is an xCreate call, create the underlying tables in the 
148830    ** database. TODO: For xConnect(), it could verify that said tables exist.
148831    */
148832    if( isCreate ){
148833      rc = fts3CreateTables(p);
148834    }
148835  
148836    /* Check to see if a legacy fts3 table has been "upgraded" by the
148837    ** addition of a %_stat table so that it can use incremental merge.
148838    */
148839    if( !isFts4 && !isCreate ){
148840      p->bHasStat = 2;
148841    }
148842  
148843    /* Figure out the page-size for the database. This is required in order to
148844    ** estimate the cost of loading large doclists from the database.  */
148845    fts3DatabasePageSize(&rc, p);
148846    p->nNodeSize = p->nPgsz-35;
148847  
148848    /* Declare the table schema to SQLite. */
148849    fts3DeclareVtab(&rc, p);
148850  
148851  fts3_init_out:
148852    sqlite3_free(zPrefix);
148853    sqlite3_free(aIndex);
148854    sqlite3_free(zCompress);
148855    sqlite3_free(zUncompress);
148856    sqlite3_free(zContent);
148857    sqlite3_free(zLanguageid);
148858    for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
148859    sqlite3_free((void *)aCol);
148860    sqlite3_free((void *)azNotindexed);
148861    if( rc!=SQLITE_OK ){
148862      if( p ){
148863        fts3DisconnectMethod((sqlite3_vtab *)p);
148864      }else if( pTokenizer ){
148865        pTokenizer->pModule->xDestroy(pTokenizer);
148866      }
148867    }else{
148868      assert( p->pSegments==0 );
148869      *ppVTab = &p->base;
148870    }
148871    return rc;
148872  }
148873  
148874  /*
148875  ** The xConnect() and xCreate() methods for the virtual table. All the
148876  ** work is done in function fts3InitVtab().
148877  */
148878  static int fts3ConnectMethod(
148879    sqlite3 *db,                    /* Database connection */
148880    void *pAux,                     /* Pointer to tokenizer hash table */
148881    int argc,                       /* Number of elements in argv array */
148882    const char * const *argv,       /* xCreate/xConnect argument array */
148883    sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
148884    char **pzErr                    /* OUT: sqlite3_malloc'd error message */
148885  ){
148886    return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
148887  }
148888  static int fts3CreateMethod(
148889    sqlite3 *db,                    /* Database connection */
148890    void *pAux,                     /* Pointer to tokenizer hash table */
148891    int argc,                       /* Number of elements in argv array */
148892    const char * const *argv,       /* xCreate/xConnect argument array */
148893    sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
148894    char **pzErr                    /* OUT: sqlite3_malloc'd error message */
148895  ){
148896    return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
148897  }
148898  
148899  /*
148900  ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
148901  ** extension is currently being used by a version of SQLite too old to
148902  ** support estimatedRows. In that case this function is a no-op.
148903  */
148904  static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
148905  #if SQLITE_VERSION_NUMBER>=3008002
148906    if( sqlite3_libversion_number()>=3008002 ){
148907      pIdxInfo->estimatedRows = nRow;
148908    }
148909  #endif
148910  }
148911  
148912  /*
148913  ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
148914  ** extension is currently being used by a version of SQLite too old to
148915  ** support index-info flags. In that case this function is a no-op.
148916  */
148917  static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
148918  #if SQLITE_VERSION_NUMBER>=3008012
148919    if( sqlite3_libversion_number()>=3008012 ){
148920      pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
148921    }
148922  #endif
148923  }
148924  
148925  /* 
148926  ** Implementation of the xBestIndex method for FTS3 tables. There
148927  ** are three possible strategies, in order of preference:
148928  **
148929  **   1. Direct lookup by rowid or docid. 
148930  **   2. Full-text search using a MATCH operator on a non-docid column.
148931  **   3. Linear scan of %_content table.
148932  */
148933  static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
148934    Fts3Table *p = (Fts3Table *)pVTab;
148935    int i;                          /* Iterator variable */
148936    int iCons = -1;                 /* Index of constraint to use */
148937  
148938    int iLangidCons = -1;           /* Index of langid=x constraint, if present */
148939    int iDocidGe = -1;              /* Index of docid>=x constraint, if present */
148940    int iDocidLe = -1;              /* Index of docid<=x constraint, if present */
148941    int iIdx;
148942  
148943    /* By default use a full table scan. This is an expensive option,
148944    ** so search through the constraints to see if a more efficient 
148945    ** strategy is possible.
148946    */
148947    pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
148948    pInfo->estimatedCost = 5000000;
148949    for(i=0; i<pInfo->nConstraint; i++){
148950      int bDocid;                 /* True if this constraint is on docid */
148951      struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
148952      if( pCons->usable==0 ){
148953        if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
148954          /* There exists an unusable MATCH constraint. This means that if
148955          ** the planner does elect to use the results of this call as part
148956          ** of the overall query plan the user will see an "unable to use
148957          ** function MATCH in the requested context" error. To discourage
148958          ** this, return a very high cost here.  */
148959          pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
148960          pInfo->estimatedCost = 1e50;
148961          fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
148962          return SQLITE_OK;
148963        }
148964        continue;
148965      }
148966  
148967      bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
148968  
148969      /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
148970      if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
148971        pInfo->idxNum = FTS3_DOCID_SEARCH;
148972        pInfo->estimatedCost = 1.0;
148973        iCons = i;
148974      }
148975  
148976      /* A MATCH constraint. Use a full-text search.
148977      **
148978      ** If there is more than one MATCH constraint available, use the first
148979      ** one encountered. If there is both a MATCH constraint and a direct
148980      ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
148981      ** though the rowid/docid lookup is faster than a MATCH query, selecting
148982      ** it would lead to an "unable to use function MATCH in the requested 
148983      ** context" error.
148984      */
148985      if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 
148986       && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
148987      ){
148988        pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
148989        pInfo->estimatedCost = 2.0;
148990        iCons = i;
148991      }
148992  
148993      /* Equality constraint on the langid column */
148994      if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
148995       && pCons->iColumn==p->nColumn + 2
148996      ){
148997        iLangidCons = i;
148998      }
148999  
149000      if( bDocid ){
149001        switch( pCons->op ){
149002          case SQLITE_INDEX_CONSTRAINT_GE:
149003          case SQLITE_INDEX_CONSTRAINT_GT:
149004            iDocidGe = i;
149005            break;
149006  
149007          case SQLITE_INDEX_CONSTRAINT_LE:
149008          case SQLITE_INDEX_CONSTRAINT_LT:
149009            iDocidLe = i;
149010            break;
149011        }
149012      }
149013    }
149014  
149015    /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
149016    if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
149017  
149018    iIdx = 1;
149019    if( iCons>=0 ){
149020      pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
149021      pInfo->aConstraintUsage[iCons].omit = 1;
149022    } 
149023    if( iLangidCons>=0 ){
149024      pInfo->idxNum |= FTS3_HAVE_LANGID;
149025      pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
149026    } 
149027    if( iDocidGe>=0 ){
149028      pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
149029      pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
149030    } 
149031    if( iDocidLe>=0 ){
149032      pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
149033      pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
149034    } 
149035  
149036    /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
149037    ** docid) order. Both ascending and descending are possible. 
149038    */
149039    if( pInfo->nOrderBy==1 ){
149040      struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
149041      if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
149042        if( pOrder->desc ){
149043          pInfo->idxStr = "DESC";
149044        }else{
149045          pInfo->idxStr = "ASC";
149046        }
149047        pInfo->orderByConsumed = 1;
149048      }
149049    }
149050  
149051    assert( p->pSegments==0 );
149052    return SQLITE_OK;
149053  }
149054  
149055  /*
149056  ** Implementation of xOpen method.
149057  */
149058  static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
149059    sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
149060  
149061    UNUSED_PARAMETER(pVTab);
149062  
149063    /* Allocate a buffer large enough for an Fts3Cursor structure. If the
149064    ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 
149065    ** if the allocation fails, return SQLITE_NOMEM.
149066    */
149067    *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
149068    if( !pCsr ){
149069      return SQLITE_NOMEM;
149070    }
149071    memset(pCsr, 0, sizeof(Fts3Cursor));
149072    return SQLITE_OK;
149073  }
149074  
149075  /*
149076  ** Finalize the statement handle at pCsr->pStmt.
149077  **
149078  ** Or, if that statement handle is one created by fts3CursorSeekStmt(),
149079  ** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement
149080  ** pointer there instead of finalizing it.
149081  */
149082  static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){
149083    if( pCsr->bSeekStmt ){
149084      Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
149085      if( p->pSeekStmt==0 ){
149086        p->pSeekStmt = pCsr->pStmt;
149087        sqlite3_reset(pCsr->pStmt);
149088        pCsr->pStmt = 0;
149089      }
149090      pCsr->bSeekStmt = 0;
149091    }
149092    sqlite3_finalize(pCsr->pStmt);
149093  }
149094  
149095  /*
149096  ** Free all resources currently held by the cursor passed as the only
149097  ** argument.
149098  */
149099  static void fts3ClearCursor(Fts3Cursor *pCsr){
149100    fts3CursorFinalizeStmt(pCsr);
149101    sqlite3Fts3FreeDeferredTokens(pCsr);
149102    sqlite3_free(pCsr->aDoclist);
149103    sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
149104    sqlite3Fts3ExprFree(pCsr->pExpr);
149105    memset(&(&pCsr->base)[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
149106  }
149107  
149108  /*
149109  ** Close the cursor.  For additional information see the documentation
149110  ** on the xClose method of the virtual table interface.
149111  */
149112  static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
149113    Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
149114    assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
149115    fts3ClearCursor(pCsr);
149116    assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
149117    sqlite3_free(pCsr);
149118    return SQLITE_OK;
149119  }
149120  
149121  /*
149122  ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
149123  ** compose and prepare an SQL statement of the form:
149124  **
149125  **    "SELECT <columns> FROM %_content WHERE rowid = ?"
149126  **
149127  ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
149128  ** it. If an error occurs, return an SQLite error code.
149129  */
149130  static int fts3CursorSeekStmt(Fts3Cursor *pCsr){
149131    int rc = SQLITE_OK;
149132    if( pCsr->pStmt==0 ){
149133      Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
149134      char *zSql;
149135      if( p->pSeekStmt ){
149136        pCsr->pStmt = p->pSeekStmt;
149137        p->pSeekStmt = 0;
149138      }else{
149139        zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
149140        if( !zSql ) return SQLITE_NOMEM;
149141        rc = sqlite3_prepare_v3(p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
149142        sqlite3_free(zSql);
149143      }
149144      if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1;
149145    }
149146    return rc;
149147  }
149148  
149149  /*
149150  ** Position the pCsr->pStmt statement so that it is on the row
149151  ** of the %_content table that contains the last match.  Return
149152  ** SQLITE_OK on success.  
149153  */
149154  static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
149155    int rc = SQLITE_OK;
149156    if( pCsr->isRequireSeek ){
149157      rc = fts3CursorSeekStmt(pCsr);
149158      if( rc==SQLITE_OK ){
149159        sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
149160        pCsr->isRequireSeek = 0;
149161        if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
149162          return SQLITE_OK;
149163        }else{
149164          rc = sqlite3_reset(pCsr->pStmt);
149165          if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
149166            /* If no row was found and no error has occurred, then the %_content
149167            ** table is missing a row that is present in the full-text index.
149168            ** The data structures are corrupt.  */
149169            rc = FTS_CORRUPT_VTAB;
149170            pCsr->isEof = 1;
149171          }
149172        }
149173      }
149174    }
149175  
149176    if( rc!=SQLITE_OK && pContext ){
149177      sqlite3_result_error_code(pContext, rc);
149178    }
149179    return rc;
149180  }
149181  
149182  /*
149183  ** This function is used to process a single interior node when searching
149184  ** a b-tree for a term or term prefix. The node data is passed to this 
149185  ** function via the zNode/nNode parameters. The term to search for is
149186  ** passed in zTerm/nTerm.
149187  **
149188  ** If piFirst is not NULL, then this function sets *piFirst to the blockid
149189  ** of the child node that heads the sub-tree that may contain the term.
149190  **
149191  ** If piLast is not NULL, then *piLast is set to the right-most child node
149192  ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
149193  ** a prefix.
149194  **
149195  ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
149196  */
149197  static int fts3ScanInteriorNode(
149198    const char *zTerm,              /* Term to select leaves for */
149199    int nTerm,                      /* Size of term zTerm in bytes */
149200    const char *zNode,              /* Buffer containing segment interior node */
149201    int nNode,                      /* Size of buffer at zNode */
149202    sqlite3_int64 *piFirst,         /* OUT: Selected child node */
149203    sqlite3_int64 *piLast           /* OUT: Selected child node */
149204  ){
149205    int rc = SQLITE_OK;             /* Return code */
149206    const char *zCsr = zNode;       /* Cursor to iterate through node */
149207    const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
149208    char *zBuffer = 0;              /* Buffer to load terms into */
149209    int nAlloc = 0;                 /* Size of allocated buffer */
149210    int isFirstTerm = 1;            /* True when processing first term on page */
149211    sqlite3_int64 iChild;           /* Block id of child node to descend to */
149212  
149213    /* Skip over the 'height' varint that occurs at the start of every 
149214    ** interior node. Then load the blockid of the left-child of the b-tree
149215    ** node into variable iChild.  
149216    **
149217    ** Even if the data structure on disk is corrupted, this (reading two
149218    ** varints from the buffer) does not risk an overread. If zNode is a
149219    ** root node, then the buffer comes from a SELECT statement. SQLite does
149220    ** not make this guarantee explicitly, but in practice there are always
149221    ** either more than 20 bytes of allocated space following the nNode bytes of
149222    ** contents, or two zero bytes. Or, if the node is read from the %_segments
149223    ** table, then there are always 20 bytes of zeroed padding following the
149224    ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
149225    */
149226    zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
149227    zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
149228    if( zCsr>zEnd ){
149229      return FTS_CORRUPT_VTAB;
149230    }
149231    
149232    while( zCsr<zEnd && (piFirst || piLast) ){
149233      int cmp;                      /* memcmp() result */
149234      int nSuffix;                  /* Size of term suffix */
149235      int nPrefix = 0;              /* Size of term prefix */
149236      int nBuffer;                  /* Total term size */
149237    
149238      /* Load the next term on the node into zBuffer. Use realloc() to expand
149239      ** the size of zBuffer if required.  */
149240      if( !isFirstTerm ){
149241        zCsr += fts3GetVarint32(zCsr, &nPrefix);
149242      }
149243      isFirstTerm = 0;
149244      zCsr += fts3GetVarint32(zCsr, &nSuffix);
149245      
149246      assert( nPrefix>=0 && nSuffix>=0 );
149247      if( &zCsr[nSuffix]>zEnd ){
149248        rc = FTS_CORRUPT_VTAB;
149249        goto finish_scan;
149250      }
149251      if( nPrefix+nSuffix>nAlloc ){
149252        char *zNew;
149253        nAlloc = (nPrefix+nSuffix) * 2;
149254        zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
149255        if( !zNew ){
149256          rc = SQLITE_NOMEM;
149257          goto finish_scan;
149258        }
149259        zBuffer = zNew;
149260      }
149261      assert( zBuffer );
149262      memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
149263      nBuffer = nPrefix + nSuffix;
149264      zCsr += nSuffix;
149265  
149266      /* Compare the term we are searching for with the term just loaded from
149267      ** the interior node. If the specified term is greater than or equal
149268      ** to the term from the interior node, then all terms on the sub-tree 
149269      ** headed by node iChild are smaller than zTerm. No need to search 
149270      ** iChild.
149271      **
149272      ** If the interior node term is larger than the specified term, then
149273      ** the tree headed by iChild may contain the specified term.
149274      */
149275      cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
149276      if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
149277        *piFirst = iChild;
149278        piFirst = 0;
149279      }
149280  
149281      if( piLast && cmp<0 ){
149282        *piLast = iChild;
149283        piLast = 0;
149284      }
149285  
149286      iChild++;
149287    };
149288  
149289    if( piFirst ) *piFirst = iChild;
149290    if( piLast ) *piLast = iChild;
149291  
149292   finish_scan:
149293    sqlite3_free(zBuffer);
149294    return rc;
149295  }
149296  
149297  
149298  /*
149299  ** The buffer pointed to by argument zNode (size nNode bytes) contains an
149300  ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
149301  ** contains a term. This function searches the sub-tree headed by the zNode
149302  ** node for the range of leaf nodes that may contain the specified term
149303  ** or terms for which the specified term is a prefix.
149304  **
149305  ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the 
149306  ** left-most leaf node in the tree that may contain the specified term.
149307  ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
149308  ** right-most leaf node that may contain a term for which the specified
149309  ** term is a prefix.
149310  **
149311  ** It is possible that the range of returned leaf nodes does not contain 
149312  ** the specified term or any terms for which it is a prefix. However, if the 
149313  ** segment does contain any such terms, they are stored within the identified
149314  ** range. Because this function only inspects interior segment nodes (and
149315  ** never loads leaf nodes into memory), it is not possible to be sure.
149316  **
149317  ** If an error occurs, an error code other than SQLITE_OK is returned.
149318  */ 
149319  static int fts3SelectLeaf(
149320    Fts3Table *p,                   /* Virtual table handle */
149321    const char *zTerm,              /* Term to select leaves for */
149322    int nTerm,                      /* Size of term zTerm in bytes */
149323    const char *zNode,              /* Buffer containing segment interior node */
149324    int nNode,                      /* Size of buffer at zNode */
149325    sqlite3_int64 *piLeaf,          /* Selected leaf node */
149326    sqlite3_int64 *piLeaf2          /* Selected leaf node */
149327  ){
149328    int rc = SQLITE_OK;             /* Return code */
149329    int iHeight;                    /* Height of this node in tree */
149330  
149331    assert( piLeaf || piLeaf2 );
149332  
149333    fts3GetVarint32(zNode, &iHeight);
149334    rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
149335    assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
149336  
149337    if( rc==SQLITE_OK && iHeight>1 ){
149338      char *zBlob = 0;              /* Blob read from %_segments table */
149339      int nBlob = 0;                /* Size of zBlob in bytes */
149340  
149341      if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
149342        rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
149343        if( rc==SQLITE_OK ){
149344          rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
149345        }
149346        sqlite3_free(zBlob);
149347        piLeaf = 0;
149348        zBlob = 0;
149349      }
149350  
149351      if( rc==SQLITE_OK ){
149352        rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
149353      }
149354      if( rc==SQLITE_OK ){
149355        rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
149356      }
149357      sqlite3_free(zBlob);
149358    }
149359  
149360    return rc;
149361  }
149362  
149363  /*
149364  ** This function is used to create delta-encoded serialized lists of FTS3 
149365  ** varints. Each call to this function appends a single varint to a list.
149366  */
149367  static void fts3PutDeltaVarint(
149368    char **pp,                      /* IN/OUT: Output pointer */
149369    sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
149370    sqlite3_int64 iVal              /* Write this value to the list */
149371  ){
149372    assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
149373    *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
149374    *piPrev = iVal;
149375  }
149376  
149377  /*
149378  ** When this function is called, *ppPoslist is assumed to point to the 
149379  ** start of a position-list. After it returns, *ppPoslist points to the
149380  ** first byte after the position-list.
149381  **
149382  ** A position list is list of positions (delta encoded) and columns for 
149383  ** a single document record of a doclist.  So, in other words, this
149384  ** routine advances *ppPoslist so that it points to the next docid in
149385  ** the doclist, or to the first byte past the end of the doclist.
149386  **
149387  ** If pp is not NULL, then the contents of the position list are copied
149388  ** to *pp. *pp is set to point to the first byte past the last byte copied
149389  ** before this function returns.
149390  */
149391  static void fts3PoslistCopy(char **pp, char **ppPoslist){
149392    char *pEnd = *ppPoslist;
149393    char c = 0;
149394  
149395    /* The end of a position list is marked by a zero encoded as an FTS3 
149396    ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
149397    ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
149398    ** of some other, multi-byte, value.
149399    **
149400    ** The following while-loop moves pEnd to point to the first byte that is not 
149401    ** immediately preceded by a byte with the 0x80 bit set. Then increments
149402    ** pEnd once more so that it points to the byte immediately following the
149403    ** last byte in the position-list.
149404    */
149405    while( *pEnd | c ){
149406      c = *pEnd++ & 0x80;
149407      testcase( c!=0 && (*pEnd)==0 );
149408    }
149409    pEnd++;  /* Advance past the POS_END terminator byte */
149410  
149411    if( pp ){
149412      int n = (int)(pEnd - *ppPoslist);
149413      char *p = *pp;
149414      memcpy(p, *ppPoslist, n);
149415      p += n;
149416      *pp = p;
149417    }
149418    *ppPoslist = pEnd;
149419  }
149420  
149421  /*
149422  ** When this function is called, *ppPoslist is assumed to point to the 
149423  ** start of a column-list. After it returns, *ppPoslist points to the
149424  ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
149425  **
149426  ** A column-list is list of delta-encoded positions for a single column
149427  ** within a single document within a doclist.
149428  **
149429  ** The column-list is terminated either by a POS_COLUMN varint (1) or
149430  ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
149431  ** the POS_COLUMN or POS_END that terminates the column-list.
149432  **
149433  ** If pp is not NULL, then the contents of the column-list are copied
149434  ** to *pp. *pp is set to point to the first byte past the last byte copied
149435  ** before this function returns.  The POS_COLUMN or POS_END terminator
149436  ** is not copied into *pp.
149437  */
149438  static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
149439    char *pEnd = *ppPoslist;
149440    char c = 0;
149441  
149442    /* A column-list is terminated by either a 0x01 or 0x00 byte that is
149443    ** not part of a multi-byte varint.
149444    */
149445    while( 0xFE & (*pEnd | c) ){
149446      c = *pEnd++ & 0x80;
149447      testcase( c!=0 && ((*pEnd)&0xfe)==0 );
149448    }
149449    if( pp ){
149450      int n = (int)(pEnd - *ppPoslist);
149451      char *p = *pp;
149452      memcpy(p, *ppPoslist, n);
149453      p += n;
149454      *pp = p;
149455    }
149456    *ppPoslist = pEnd;
149457  }
149458  
149459  /*
149460  ** Value used to signify the end of an position-list. This is safe because
149461  ** it is not possible to have a document with 2^31 terms.
149462  */
149463  #define POSITION_LIST_END 0x7fffffff
149464  
149465  /*
149466  ** This function is used to help parse position-lists. When this function is
149467  ** called, *pp may point to the start of the next varint in the position-list
149468  ** being parsed, or it may point to 1 byte past the end of the position-list
149469  ** (in which case **pp will be a terminator bytes POS_END (0) or
149470  ** (1)).
149471  **
149472  ** If *pp points past the end of the current position-list, set *pi to 
149473  ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
149474  ** increment the current value of *pi by the value read, and set *pp to
149475  ** point to the next value before returning.
149476  **
149477  ** Before calling this routine *pi must be initialized to the value of
149478  ** the previous position, or zero if we are reading the first position
149479  ** in the position-list.  Because positions are delta-encoded, the value
149480  ** of the previous position is needed in order to compute the value of
149481  ** the next position.
149482  */
149483  static void fts3ReadNextPos(
149484    char **pp,                    /* IN/OUT: Pointer into position-list buffer */
149485    sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
149486  ){
149487    if( (**pp)&0xFE ){
149488      fts3GetDeltaVarint(pp, pi);
149489      *pi -= 2;
149490    }else{
149491      *pi = POSITION_LIST_END;
149492    }
149493  }
149494  
149495  /*
149496  ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
149497  ** the value of iCol encoded as a varint to *pp.   This will start a new
149498  ** column list.
149499  **
149500  ** Set *pp to point to the byte just after the last byte written before 
149501  ** returning (do not modify it if iCol==0). Return the total number of bytes
149502  ** written (0 if iCol==0).
149503  */
149504  static int fts3PutColNumber(char **pp, int iCol){
149505    int n = 0;                      /* Number of bytes written */
149506    if( iCol ){
149507      char *p = *pp;                /* Output pointer */
149508      n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
149509      *p = 0x01;
149510      *pp = &p[n];
149511    }
149512    return n;
149513  }
149514  
149515  /*
149516  ** Compute the union of two position lists.  The output written
149517  ** into *pp contains all positions of both *pp1 and *pp2 in sorted
149518  ** order and with any duplicates removed.  All pointers are
149519  ** updated appropriately.   The caller is responsible for insuring
149520  ** that there is enough space in *pp to hold the complete output.
149521  */
149522  static void fts3PoslistMerge(
149523    char **pp,                      /* Output buffer */
149524    char **pp1,                     /* Left input list */
149525    char **pp2                      /* Right input list */
149526  ){
149527    char *p = *pp;
149528    char *p1 = *pp1;
149529    char *p2 = *pp2;
149530  
149531    while( *p1 || *p2 ){
149532      int iCol1;         /* The current column index in pp1 */
149533      int iCol2;         /* The current column index in pp2 */
149534  
149535      if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
149536      else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
149537      else iCol1 = 0;
149538  
149539      if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
149540      else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
149541      else iCol2 = 0;
149542  
149543      if( iCol1==iCol2 ){
149544        sqlite3_int64 i1 = 0;       /* Last position from pp1 */
149545        sqlite3_int64 i2 = 0;       /* Last position from pp2 */
149546        sqlite3_int64 iPrev = 0;
149547        int n = fts3PutColNumber(&p, iCol1);
149548        p1 += n;
149549        p2 += n;
149550  
149551        /* At this point, both p1 and p2 point to the start of column-lists
149552        ** for the same column (the column with index iCol1 and iCol2).
149553        ** A column-list is a list of non-negative delta-encoded varints, each 
149554        ** incremented by 2 before being stored. Each list is terminated by a
149555        ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
149556        ** and writes the results to buffer p. p is left pointing to the byte
149557        ** after the list written. No terminator (POS_END or POS_COLUMN) is
149558        ** written to the output.
149559        */
149560        fts3GetDeltaVarint(&p1, &i1);
149561        fts3GetDeltaVarint(&p2, &i2);
149562        do {
149563          fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
149564          iPrev -= 2;
149565          if( i1==i2 ){
149566            fts3ReadNextPos(&p1, &i1);
149567            fts3ReadNextPos(&p2, &i2);
149568          }else if( i1<i2 ){
149569            fts3ReadNextPos(&p1, &i1);
149570          }else{
149571            fts3ReadNextPos(&p2, &i2);
149572          }
149573        }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
149574      }else if( iCol1<iCol2 ){
149575        p1 += fts3PutColNumber(&p, iCol1);
149576        fts3ColumnlistCopy(&p, &p1);
149577      }else{
149578        p2 += fts3PutColNumber(&p, iCol2);
149579        fts3ColumnlistCopy(&p, &p2);
149580      }
149581    }
149582  
149583    *p++ = POS_END;
149584    *pp = p;
149585    *pp1 = p1 + 1;
149586    *pp2 = p2 + 1;
149587  }
149588  
149589  /*
149590  ** This function is used to merge two position lists into one. When it is
149591  ** called, *pp1 and *pp2 must both point to position lists. A position-list is
149592  ** the part of a doclist that follows each document id. For example, if a row
149593  ** contains:
149594  **
149595  **     'a b c'|'x y z'|'a b b a'
149596  **
149597  ** Then the position list for this row for token 'b' would consist of:
149598  **
149599  **     0x02 0x01 0x02 0x03 0x03 0x00
149600  **
149601  ** When this function returns, both *pp1 and *pp2 are left pointing to the
149602  ** byte following the 0x00 terminator of their respective position lists.
149603  **
149604  ** If isSaveLeft is 0, an entry is added to the output position list for 
149605  ** each position in *pp2 for which there exists one or more positions in
149606  ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
149607  ** when the *pp1 token appears before the *pp2 token, but not more than nToken
149608  ** slots before it.
149609  **
149610  ** e.g. nToken==1 searches for adjacent positions.
149611  */
149612  static int fts3PoslistPhraseMerge(
149613    char **pp,                      /* IN/OUT: Preallocated output buffer */
149614    int nToken,                     /* Maximum difference in token positions */
149615    int isSaveLeft,                 /* Save the left position */
149616    int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
149617    char **pp1,                     /* IN/OUT: Left input list */
149618    char **pp2                      /* IN/OUT: Right input list */
149619  ){
149620    char *p = *pp;
149621    char *p1 = *pp1;
149622    char *p2 = *pp2;
149623    int iCol1 = 0;
149624    int iCol2 = 0;
149625  
149626    /* Never set both isSaveLeft and isExact for the same invocation. */
149627    assert( isSaveLeft==0 || isExact==0 );
149628  
149629    assert( p!=0 && *p1!=0 && *p2!=0 );
149630    if( *p1==POS_COLUMN ){ 
149631      p1++;
149632      p1 += fts3GetVarint32(p1, &iCol1);
149633    }
149634    if( *p2==POS_COLUMN ){ 
149635      p2++;
149636      p2 += fts3GetVarint32(p2, &iCol2);
149637    }
149638  
149639    while( 1 ){
149640      if( iCol1==iCol2 ){
149641        char *pSave = p;
149642        sqlite3_int64 iPrev = 0;
149643        sqlite3_int64 iPos1 = 0;
149644        sqlite3_int64 iPos2 = 0;
149645  
149646        if( iCol1 ){
149647          *p++ = POS_COLUMN;
149648          p += sqlite3Fts3PutVarint(p, iCol1);
149649        }
149650  
149651        assert( *p1!=POS_END && *p1!=POS_COLUMN );
149652        assert( *p2!=POS_END && *p2!=POS_COLUMN );
149653        fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
149654        fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
149655  
149656        while( 1 ){
149657          if( iPos2==iPos1+nToken 
149658           || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) 
149659          ){
149660            sqlite3_int64 iSave;
149661            iSave = isSaveLeft ? iPos1 : iPos2;
149662            fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
149663            pSave = 0;
149664            assert( p );
149665          }
149666          if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
149667            if( (*p2&0xFE)==0 ) break;
149668            fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
149669          }else{
149670            if( (*p1&0xFE)==0 ) break;
149671            fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
149672          }
149673        }
149674  
149675        if( pSave ){
149676          assert( pp && p );
149677          p = pSave;
149678        }
149679  
149680        fts3ColumnlistCopy(0, &p1);
149681        fts3ColumnlistCopy(0, &p2);
149682        assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
149683        if( 0==*p1 || 0==*p2 ) break;
149684  
149685        p1++;
149686        p1 += fts3GetVarint32(p1, &iCol1);
149687        p2++;
149688        p2 += fts3GetVarint32(p2, &iCol2);
149689      }
149690  
149691      /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
149692      ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
149693      ** end of the position list, or the 0x01 that precedes the next 
149694      ** column-number in the position list. 
149695      */
149696      else if( iCol1<iCol2 ){
149697        fts3ColumnlistCopy(0, &p1);
149698        if( 0==*p1 ) break;
149699        p1++;
149700        p1 += fts3GetVarint32(p1, &iCol1);
149701      }else{
149702        fts3ColumnlistCopy(0, &p2);
149703        if( 0==*p2 ) break;
149704        p2++;
149705        p2 += fts3GetVarint32(p2, &iCol2);
149706      }
149707    }
149708  
149709    fts3PoslistCopy(0, &p2);
149710    fts3PoslistCopy(0, &p1);
149711    *pp1 = p1;
149712    *pp2 = p2;
149713    if( *pp==p ){
149714      return 0;
149715    }
149716    *p++ = 0x00;
149717    *pp = p;
149718    return 1;
149719  }
149720  
149721  /*
149722  ** Merge two position-lists as required by the NEAR operator. The argument
149723  ** position lists correspond to the left and right phrases of an expression 
149724  ** like:
149725  **
149726  **     "phrase 1" NEAR "phrase number 2"
149727  **
149728  ** Position list *pp1 corresponds to the left-hand side of the NEAR 
149729  ** expression and *pp2 to the right. As usual, the indexes in the position 
149730  ** lists are the offsets of the last token in each phrase (tokens "1" and "2" 
149731  ** in the example above).
149732  **
149733  ** The output position list - written to *pp - is a copy of *pp2 with those
149734  ** entries that are not sufficiently NEAR entries in *pp1 removed.
149735  */
149736  static int fts3PoslistNearMerge(
149737    char **pp,                      /* Output buffer */
149738    char *aTmp,                     /* Temporary buffer space */
149739    int nRight,                     /* Maximum difference in token positions */
149740    int nLeft,                      /* Maximum difference in token positions */
149741    char **pp1,                     /* IN/OUT: Left input list */
149742    char **pp2                      /* IN/OUT: Right input list */
149743  ){
149744    char *p1 = *pp1;
149745    char *p2 = *pp2;
149746  
149747    char *pTmp1 = aTmp;
149748    char *pTmp2;
149749    char *aTmp2;
149750    int res = 1;
149751  
149752    fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
149753    aTmp2 = pTmp2 = pTmp1;
149754    *pp1 = p1;
149755    *pp2 = p2;
149756    fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
149757    if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
149758      fts3PoslistMerge(pp, &aTmp, &aTmp2);
149759    }else if( pTmp1!=aTmp ){
149760      fts3PoslistCopy(pp, &aTmp);
149761    }else if( pTmp2!=aTmp2 ){
149762      fts3PoslistCopy(pp, &aTmp2);
149763    }else{
149764      res = 0;
149765    }
149766  
149767    return res;
149768  }
149769  
149770  /* 
149771  ** An instance of this function is used to merge together the (potentially
149772  ** large number of) doclists for each term that matches a prefix query.
149773  ** See function fts3TermSelectMerge() for details.
149774  */
149775  typedef struct TermSelect TermSelect;
149776  struct TermSelect {
149777    char *aaOutput[16];             /* Malloc'd output buffers */
149778    int anOutput[16];               /* Size each output buffer in bytes */
149779  };
149780  
149781  /*
149782  ** This function is used to read a single varint from a buffer. Parameter
149783  ** pEnd points 1 byte past the end of the buffer. When this function is
149784  ** called, if *pp points to pEnd or greater, then the end of the buffer
149785  ** has been reached. In this case *pp is set to 0 and the function returns.
149786  **
149787  ** If *pp does not point to or past pEnd, then a single varint is read
149788  ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
149789  **
149790  ** If bDescIdx is false, the value read is added to *pVal before returning.
149791  ** If it is true, the value read is subtracted from *pVal before this 
149792  ** function returns.
149793  */
149794  static void fts3GetDeltaVarint3(
149795    char **pp,                      /* IN/OUT: Point to read varint from */
149796    char *pEnd,                     /* End of buffer */
149797    int bDescIdx,                   /* True if docids are descending */
149798    sqlite3_int64 *pVal             /* IN/OUT: Integer value */
149799  ){
149800    if( *pp>=pEnd ){
149801      *pp = 0;
149802    }else{
149803      sqlite3_int64 iVal;
149804      *pp += sqlite3Fts3GetVarint(*pp, &iVal);
149805      if( bDescIdx ){
149806        *pVal -= iVal;
149807      }else{
149808        *pVal += iVal;
149809      }
149810    }
149811  }
149812  
149813  /*
149814  ** This function is used to write a single varint to a buffer. The varint
149815  ** is written to *pp. Before returning, *pp is set to point 1 byte past the
149816  ** end of the value written.
149817  **
149818  ** If *pbFirst is zero when this function is called, the value written to
149819  ** the buffer is that of parameter iVal. 
149820  **
149821  ** If *pbFirst is non-zero when this function is called, then the value 
149822  ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
149823  ** (if bDescIdx is non-zero).
149824  **
149825  ** Before returning, this function always sets *pbFirst to 1 and *piPrev
149826  ** to the value of parameter iVal.
149827  */
149828  static void fts3PutDeltaVarint3(
149829    char **pp,                      /* IN/OUT: Output pointer */
149830    int bDescIdx,                   /* True for descending docids */
149831    sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
149832    int *pbFirst,                   /* IN/OUT: True after first int written */
149833    sqlite3_int64 iVal              /* Write this value to the list */
149834  ){
149835    sqlite3_int64 iWrite;
149836    if( bDescIdx==0 || *pbFirst==0 ){
149837      iWrite = iVal - *piPrev;
149838    }else{
149839      iWrite = *piPrev - iVal;
149840    }
149841    assert( *pbFirst || *piPrev==0 );
149842    assert( *pbFirst==0 || iWrite>0 );
149843    *pp += sqlite3Fts3PutVarint(*pp, iWrite);
149844    *piPrev = iVal;
149845    *pbFirst = 1;
149846  }
149847  
149848  
149849  /*
149850  ** This macro is used by various functions that merge doclists. The two
149851  ** arguments are 64-bit docid values. If the value of the stack variable
149852  ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2). 
149853  ** Otherwise, (i2-i1).
149854  **
149855  ** Using this makes it easier to write code that can merge doclists that are
149856  ** sorted in either ascending or descending order.
149857  */
149858  #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
149859  
149860  /*
149861  ** This function does an "OR" merge of two doclists (output contains all
149862  ** positions contained in either argument doclist). If the docids in the 
149863  ** input doclists are sorted in ascending order, parameter bDescDoclist
149864  ** should be false. If they are sorted in ascending order, it should be
149865  ** passed a non-zero value.
149866  **
149867  ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
149868  ** containing the output doclist and SQLITE_OK is returned. In this case
149869  ** *pnOut is set to the number of bytes in the output doclist.
149870  **
149871  ** If an error occurs, an SQLite error code is returned. The output values
149872  ** are undefined in this case.
149873  */
149874  static int fts3DoclistOrMerge(
149875    int bDescDoclist,               /* True if arguments are desc */
149876    char *a1, int n1,               /* First doclist */
149877    char *a2, int n2,               /* Second doclist */
149878    char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
149879  ){
149880    sqlite3_int64 i1 = 0;
149881    sqlite3_int64 i2 = 0;
149882    sqlite3_int64 iPrev = 0;
149883    char *pEnd1 = &a1[n1];
149884    char *pEnd2 = &a2[n2];
149885    char *p1 = a1;
149886    char *p2 = a2;
149887    char *p;
149888    char *aOut;
149889    int bFirstOut = 0;
149890  
149891    *paOut = 0;
149892    *pnOut = 0;
149893  
149894    /* Allocate space for the output. Both the input and output doclists
149895    ** are delta encoded. If they are in ascending order (bDescDoclist==0),
149896    ** then the first docid in each list is simply encoded as a varint. For
149897    ** each subsequent docid, the varint stored is the difference between the
149898    ** current and previous docid (a positive number - since the list is in
149899    ** ascending order).
149900    **
149901    ** The first docid written to the output is therefore encoded using the 
149902    ** same number of bytes as it is in whichever of the input lists it is
149903    ** read from. And each subsequent docid read from the same input list 
149904    ** consumes either the same or less bytes as it did in the input (since
149905    ** the difference between it and the previous value in the output must
149906    ** be a positive value less than or equal to the delta value read from 
149907    ** the input list). The same argument applies to all but the first docid
149908    ** read from the 'other' list. And to the contents of all position lists
149909    ** that will be copied and merged from the input to the output.
149910    **
149911    ** However, if the first docid copied to the output is a negative number,
149912    ** then the encoding of the first docid from the 'other' input list may
149913    ** be larger in the output than it was in the input (since the delta value
149914    ** may be a larger positive integer than the actual docid).
149915    **
149916    ** The space required to store the output is therefore the sum of the
149917    ** sizes of the two inputs, plus enough space for exactly one of the input
149918    ** docids to grow. 
149919    **
149920    ** A symetric argument may be made if the doclists are in descending 
149921    ** order.
149922    */
149923    aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
149924    if( !aOut ) return SQLITE_NOMEM;
149925  
149926    p = aOut;
149927    fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
149928    fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
149929    while( p1 || p2 ){
149930      sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
149931  
149932      if( p2 && p1 && iDiff==0 ){
149933        fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
149934        fts3PoslistMerge(&p, &p1, &p2);
149935        fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
149936        fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
149937      }else if( !p2 || (p1 && iDiff<0) ){
149938        fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
149939        fts3PoslistCopy(&p, &p1);
149940        fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
149941      }else{
149942        fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
149943        fts3PoslistCopy(&p, &p2);
149944        fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
149945      }
149946    }
149947  
149948    *paOut = aOut;
149949    *pnOut = (int)(p-aOut);
149950    assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
149951    return SQLITE_OK;
149952  }
149953  
149954  /*
149955  ** This function does a "phrase" merge of two doclists. In a phrase merge,
149956  ** the output contains a copy of each position from the right-hand input
149957  ** doclist for which there is a position in the left-hand input doclist
149958  ** exactly nDist tokens before it.
149959  **
149960  ** If the docids in the input doclists are sorted in ascending order,
149961  ** parameter bDescDoclist should be false. If they are sorted in ascending 
149962  ** order, it should be passed a non-zero value.
149963  **
149964  ** The right-hand input doclist is overwritten by this function.
149965  */
149966  static int fts3DoclistPhraseMerge(
149967    int bDescDoclist,               /* True if arguments are desc */
149968    int nDist,                      /* Distance from left to right (1=adjacent) */
149969    char *aLeft, int nLeft,         /* Left doclist */
149970    char **paRight, int *pnRight    /* IN/OUT: Right/output doclist */
149971  ){
149972    sqlite3_int64 i1 = 0;
149973    sqlite3_int64 i2 = 0;
149974    sqlite3_int64 iPrev = 0;
149975    char *aRight = *paRight;
149976    char *pEnd1 = &aLeft[nLeft];
149977    char *pEnd2 = &aRight[*pnRight];
149978    char *p1 = aLeft;
149979    char *p2 = aRight;
149980    char *p;
149981    int bFirstOut = 0;
149982    char *aOut;
149983  
149984    assert( nDist>0 );
149985    if( bDescDoclist ){
149986      aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
149987      if( aOut==0 ) return SQLITE_NOMEM;
149988    }else{
149989      aOut = aRight;
149990    }
149991    p = aOut;
149992  
149993    fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
149994    fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
149995  
149996    while( p1 && p2 ){
149997      sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
149998      if( iDiff==0 ){
149999        char *pSave = p;
150000        sqlite3_int64 iPrevSave = iPrev;
150001        int bFirstOutSave = bFirstOut;
150002  
150003        fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
150004        if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
150005          p = pSave;
150006          iPrev = iPrevSave;
150007          bFirstOut = bFirstOutSave;
150008        }
150009        fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
150010        fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
150011      }else if( iDiff<0 ){
150012        fts3PoslistCopy(0, &p1);
150013        fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
150014      }else{
150015        fts3PoslistCopy(0, &p2);
150016        fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
150017      }
150018    }
150019  
150020    *pnRight = (int)(p - aOut);
150021    if( bDescDoclist ){
150022      sqlite3_free(aRight);
150023      *paRight = aOut;
150024    }
150025  
150026    return SQLITE_OK;
150027  }
150028  
150029  /*
150030  ** Argument pList points to a position list nList bytes in size. This
150031  ** function checks to see if the position list contains any entries for
150032  ** a token in position 0 (of any column). If so, it writes argument iDelta
150033  ** to the output buffer pOut, followed by a position list consisting only
150034  ** of the entries from pList at position 0, and terminated by an 0x00 byte.
150035  ** The value returned is the number of bytes written to pOut (if any).
150036  */
150037  SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
150038    sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
150039    char *pList,                    /* Position list (no 0x00 term) */
150040    int nList,                      /* Size of pList in bytes */
150041    char *pOut                      /* Write output here */
150042  ){
150043    int nOut = 0;
150044    int bWritten = 0;               /* True once iDelta has been written */
150045    char *p = pList;
150046    char *pEnd = &pList[nList];
150047  
150048    if( *p!=0x01 ){
150049      if( *p==0x02 ){
150050        nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
150051        pOut[nOut++] = 0x02;
150052        bWritten = 1;
150053      }
150054      fts3ColumnlistCopy(0, &p);
150055    }
150056  
150057    while( p<pEnd ){
150058      sqlite3_int64 iCol;
150059      p++;
150060      p += sqlite3Fts3GetVarint(p, &iCol);
150061      if( *p==0x02 ){
150062        if( bWritten==0 ){
150063          nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
150064          bWritten = 1;
150065        }
150066        pOut[nOut++] = 0x01;
150067        nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
150068        pOut[nOut++] = 0x02;
150069      }
150070      fts3ColumnlistCopy(0, &p);
150071    }
150072    if( bWritten ){
150073      pOut[nOut++] = 0x00;
150074    }
150075  
150076    return nOut;
150077  }
150078  
150079  
150080  /*
150081  ** Merge all doclists in the TermSelect.aaOutput[] array into a single
150082  ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
150083  ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
150084  **
150085  ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
150086  ** the responsibility of the caller to free any doclists left in the
150087  ** TermSelect.aaOutput[] array.
150088  */
150089  static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
150090    char *aOut = 0;
150091    int nOut = 0;
150092    int i;
150093  
150094    /* Loop through the doclists in the aaOutput[] array. Merge them all
150095    ** into a single doclist.
150096    */
150097    for(i=0; i<SizeofArray(pTS->aaOutput); i++){
150098      if( pTS->aaOutput[i] ){
150099        if( !aOut ){
150100          aOut = pTS->aaOutput[i];
150101          nOut = pTS->anOutput[i];
150102          pTS->aaOutput[i] = 0;
150103        }else{
150104          int nNew;
150105          char *aNew;
150106  
150107          int rc = fts3DoclistOrMerge(p->bDescIdx, 
150108              pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
150109          );
150110          if( rc!=SQLITE_OK ){
150111            sqlite3_free(aOut);
150112            return rc;
150113          }
150114  
150115          sqlite3_free(pTS->aaOutput[i]);
150116          sqlite3_free(aOut);
150117          pTS->aaOutput[i] = 0;
150118          aOut = aNew;
150119          nOut = nNew;
150120        }
150121      }
150122    }
150123  
150124    pTS->aaOutput[0] = aOut;
150125    pTS->anOutput[0] = nOut;
150126    return SQLITE_OK;
150127  }
150128  
150129  /*
150130  ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
150131  ** as the first argument. The merge is an "OR" merge (see function
150132  ** fts3DoclistOrMerge() for details).
150133  **
150134  ** This function is called with the doclist for each term that matches
150135  ** a queried prefix. It merges all these doclists into one, the doclist
150136  ** for the specified prefix. Since there can be a very large number of
150137  ** doclists to merge, the merging is done pair-wise using the TermSelect
150138  ** object.
150139  **
150140  ** This function returns SQLITE_OK if the merge is successful, or an
150141  ** SQLite error code (SQLITE_NOMEM) if an error occurs.
150142  */
150143  static int fts3TermSelectMerge(
150144    Fts3Table *p,                   /* FTS table handle */
150145    TermSelect *pTS,                /* TermSelect object to merge into */
150146    char *aDoclist,                 /* Pointer to doclist */
150147    int nDoclist                    /* Size of aDoclist in bytes */
150148  ){
150149    if( pTS->aaOutput[0]==0 ){
150150      /* If this is the first term selected, copy the doclist to the output
150151      ** buffer using memcpy(). 
150152      **
150153      ** Add FTS3_VARINT_MAX bytes of unused space to the end of the 
150154      ** allocation. This is so as to ensure that the buffer is big enough
150155      ** to hold the current doclist AND'd with any other doclist. If the
150156      ** doclists are stored in order=ASC order, this padding would not be
150157      ** required (since the size of [doclistA AND doclistB] is always less
150158      ** than or equal to the size of [doclistA] in that case). But this is
150159      ** not true for order=DESC. For example, a doclist containing (1, -1) 
150160      ** may be smaller than (-1), as in the first example the -1 may be stored
150161      ** as a single-byte delta, whereas in the second it must be stored as a
150162      ** FTS3_VARINT_MAX byte varint.
150163      **
150164      ** Similar padding is added in the fts3DoclistOrMerge() function.
150165      */
150166      pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
150167      pTS->anOutput[0] = nDoclist;
150168      if( pTS->aaOutput[0] ){
150169        memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
150170      }else{
150171        return SQLITE_NOMEM;
150172      }
150173    }else{
150174      char *aMerge = aDoclist;
150175      int nMerge = nDoclist;
150176      int iOut;
150177  
150178      for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
150179        if( pTS->aaOutput[iOut]==0 ){
150180          assert( iOut>0 );
150181          pTS->aaOutput[iOut] = aMerge;
150182          pTS->anOutput[iOut] = nMerge;
150183          break;
150184        }else{
150185          char *aNew;
150186          int nNew;
150187  
150188          int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, 
150189              pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
150190          );
150191          if( rc!=SQLITE_OK ){
150192            if( aMerge!=aDoclist ) sqlite3_free(aMerge);
150193            return rc;
150194          }
150195  
150196          if( aMerge!=aDoclist ) sqlite3_free(aMerge);
150197          sqlite3_free(pTS->aaOutput[iOut]);
150198          pTS->aaOutput[iOut] = 0;
150199    
150200          aMerge = aNew;
150201          nMerge = nNew;
150202          if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
150203            pTS->aaOutput[iOut] = aMerge;
150204            pTS->anOutput[iOut] = nMerge;
150205          }
150206        }
150207      }
150208    }
150209    return SQLITE_OK;
150210  }
150211  
150212  /*
150213  ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
150214  */
150215  static int fts3SegReaderCursorAppend(
150216    Fts3MultiSegReader *pCsr, 
150217    Fts3SegReader *pNew
150218  ){
150219    if( (pCsr->nSegment%16)==0 ){
150220      Fts3SegReader **apNew;
150221      int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
150222      apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
150223      if( !apNew ){
150224        sqlite3Fts3SegReaderFree(pNew);
150225        return SQLITE_NOMEM;
150226      }
150227      pCsr->apSegment = apNew;
150228    }
150229    pCsr->apSegment[pCsr->nSegment++] = pNew;
150230    return SQLITE_OK;
150231  }
150232  
150233  /*
150234  ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
150235  ** 8th argument.
150236  **
150237  ** This function returns SQLITE_OK if successful, or an SQLite error code
150238  ** otherwise.
150239  */
150240  static int fts3SegReaderCursor(
150241    Fts3Table *p,                   /* FTS3 table handle */
150242    int iLangid,                    /* Language id */
150243    int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
150244    int iLevel,                     /* Level of segments to scan */
150245    const char *zTerm,              /* Term to query for */
150246    int nTerm,                      /* Size of zTerm in bytes */
150247    int isPrefix,                   /* True for a prefix search */
150248    int isScan,                     /* True to scan from zTerm to EOF */
150249    Fts3MultiSegReader *pCsr        /* Cursor object to populate */
150250  ){
150251    int rc = SQLITE_OK;             /* Error code */
150252    sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
150253    int rc2;                        /* Result of sqlite3_reset() */
150254  
150255    /* If iLevel is less than 0 and this is not a scan, include a seg-reader 
150256    ** for the pending-terms. If this is a scan, then this call must be being
150257    ** made by an fts4aux module, not an FTS table. In this case calling
150258    ** Fts3SegReaderPending might segfault, as the data structures used by 
150259    ** fts4aux are not completely populated. So it's easiest to filter these
150260    ** calls out here.  */
150261    if( iLevel<0 && p->aIndex ){
150262      Fts3SegReader *pSeg = 0;
150263      rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
150264      if( rc==SQLITE_OK && pSeg ){
150265        rc = fts3SegReaderCursorAppend(pCsr, pSeg);
150266      }
150267    }
150268  
150269    if( iLevel!=FTS3_SEGCURSOR_PENDING ){
150270      if( rc==SQLITE_OK ){
150271        rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
150272      }
150273  
150274      while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
150275        Fts3SegReader *pSeg = 0;
150276  
150277        /* Read the values returned by the SELECT into local variables. */
150278        sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
150279        sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
150280        sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
150281        int nRoot = sqlite3_column_bytes(pStmt, 4);
150282        char const *zRoot = sqlite3_column_blob(pStmt, 4);
150283  
150284        /* If zTerm is not NULL, and this segment is not stored entirely on its
150285        ** root node, the range of leaves scanned can be reduced. Do this. */
150286        if( iStartBlock && zTerm ){
150287          sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
150288          rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
150289          if( rc!=SQLITE_OK ) goto finished;
150290          if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
150291        }
150292   
150293        rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1, 
150294            (isPrefix==0 && isScan==0),
150295            iStartBlock, iLeavesEndBlock, 
150296            iEndBlock, zRoot, nRoot, &pSeg
150297        );
150298        if( rc!=SQLITE_OK ) goto finished;
150299        rc = fts3SegReaderCursorAppend(pCsr, pSeg);
150300      }
150301    }
150302  
150303   finished:
150304    rc2 = sqlite3_reset(pStmt);
150305    if( rc==SQLITE_DONE ) rc = rc2;
150306  
150307    return rc;
150308  }
150309  
150310  /*
150311  ** Set up a cursor object for iterating through a full-text index or a 
150312  ** single level therein.
150313  */
150314  SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
150315    Fts3Table *p,                   /* FTS3 table handle */
150316    int iLangid,                    /* Language-id to search */
150317    int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
150318    int iLevel,                     /* Level of segments to scan */
150319    const char *zTerm,              /* Term to query for */
150320    int nTerm,                      /* Size of zTerm in bytes */
150321    int isPrefix,                   /* True for a prefix search */
150322    int isScan,                     /* True to scan from zTerm to EOF */
150323    Fts3MultiSegReader *pCsr       /* Cursor object to populate */
150324  ){
150325    assert( iIndex>=0 && iIndex<p->nIndex );
150326    assert( iLevel==FTS3_SEGCURSOR_ALL
150327        ||  iLevel==FTS3_SEGCURSOR_PENDING 
150328        ||  iLevel>=0
150329    );
150330    assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
150331    assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
150332    assert( isPrefix==0 || isScan==0 );
150333  
150334    memset(pCsr, 0, sizeof(Fts3MultiSegReader));
150335    return fts3SegReaderCursor(
150336        p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
150337    );
150338  }
150339  
150340  /*
150341  ** In addition to its current configuration, have the Fts3MultiSegReader
150342  ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
150343  **
150344  ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
150345  */
150346  static int fts3SegReaderCursorAddZero(
150347    Fts3Table *p,                   /* FTS virtual table handle */
150348    int iLangid,
150349    const char *zTerm,              /* Term to scan doclist of */
150350    int nTerm,                      /* Number of bytes in zTerm */
150351    Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
150352  ){
150353    return fts3SegReaderCursor(p, 
150354        iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
150355    );
150356  }
150357  
150358  /*
150359  ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
150360  ** if isPrefix is true, to scan the doclist for all terms for which 
150361  ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
150362  ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
150363  ** an SQLite error code.
150364  **
150365  ** It is the responsibility of the caller to free this object by eventually
150366  ** passing it to fts3SegReaderCursorFree() 
150367  **
150368  ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
150369  ** Output parameter *ppSegcsr is set to 0 if an error occurs.
150370  */
150371  static int fts3TermSegReaderCursor(
150372    Fts3Cursor *pCsr,               /* Virtual table cursor handle */
150373    const char *zTerm,              /* Term to query for */
150374    int nTerm,                      /* Size of zTerm in bytes */
150375    int isPrefix,                   /* True for a prefix search */
150376    Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
150377  ){
150378    Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
150379    int rc = SQLITE_NOMEM;          /* Return code */
150380  
150381    pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
150382    if( pSegcsr ){
150383      int i;
150384      int bFound = 0;               /* True once an index has been found */
150385      Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
150386  
150387      if( isPrefix ){
150388        for(i=1; bFound==0 && i<p->nIndex; i++){
150389          if( p->aIndex[i].nPrefix==nTerm ){
150390            bFound = 1;
150391            rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
150392                i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
150393            );
150394            pSegcsr->bLookup = 1;
150395          }
150396        }
150397  
150398        for(i=1; bFound==0 && i<p->nIndex; i++){
150399          if( p->aIndex[i].nPrefix==nTerm+1 ){
150400            bFound = 1;
150401            rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
150402                i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
150403            );
150404            if( rc==SQLITE_OK ){
150405              rc = fts3SegReaderCursorAddZero(
150406                  p, pCsr->iLangid, zTerm, nTerm, pSegcsr
150407              );
150408            }
150409          }
150410        }
150411      }
150412  
150413      if( bFound==0 ){
150414        rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
150415            0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
150416        );
150417        pSegcsr->bLookup = !isPrefix;
150418      }
150419    }
150420  
150421    *ppSegcsr = pSegcsr;
150422    return rc;
150423  }
150424  
150425  /*
150426  ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
150427  */
150428  static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
150429    sqlite3Fts3SegReaderFinish(pSegcsr);
150430    sqlite3_free(pSegcsr);
150431  }
150432  
150433  /*
150434  ** This function retrieves the doclist for the specified term (or term
150435  ** prefix) from the database.
150436  */
150437  static int fts3TermSelect(
150438    Fts3Table *p,                   /* Virtual table handle */
150439    Fts3PhraseToken *pTok,          /* Token to query for */
150440    int iColumn,                    /* Column to query (or -ve for all columns) */
150441    int *pnOut,                     /* OUT: Size of buffer at *ppOut */
150442    char **ppOut                    /* OUT: Malloced result buffer */
150443  ){
150444    int rc;                         /* Return code */
150445    Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
150446    TermSelect tsc;                 /* Object for pair-wise doclist merging */
150447    Fts3SegFilter filter;           /* Segment term filter configuration */
150448  
150449    pSegcsr = pTok->pSegcsr;
150450    memset(&tsc, 0, sizeof(TermSelect));
150451  
150452    filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
150453          | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
150454          | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
150455          | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
150456    filter.iCol = iColumn;
150457    filter.zTerm = pTok->z;
150458    filter.nTerm = pTok->n;
150459  
150460    rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
150461    while( SQLITE_OK==rc
150462        && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) 
150463    ){
150464      rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
150465    }
150466  
150467    if( rc==SQLITE_OK ){
150468      rc = fts3TermSelectFinishMerge(p, &tsc);
150469    }
150470    if( rc==SQLITE_OK ){
150471      *ppOut = tsc.aaOutput[0];
150472      *pnOut = tsc.anOutput[0];
150473    }else{
150474      int i;
150475      for(i=0; i<SizeofArray(tsc.aaOutput); i++){
150476        sqlite3_free(tsc.aaOutput[i]);
150477      }
150478    }
150479  
150480    fts3SegReaderCursorFree(pSegcsr);
150481    pTok->pSegcsr = 0;
150482    return rc;
150483  }
150484  
150485  /*
150486  ** This function counts the total number of docids in the doclist stored
150487  ** in buffer aList[], size nList bytes.
150488  **
150489  ** If the isPoslist argument is true, then it is assumed that the doclist
150490  ** contains a position-list following each docid. Otherwise, it is assumed
150491  ** that the doclist is simply a list of docids stored as delta encoded 
150492  ** varints.
150493  */
150494  static int fts3DoclistCountDocids(char *aList, int nList){
150495    int nDoc = 0;                   /* Return value */
150496    if( aList ){
150497      char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
150498      char *p = aList;              /* Cursor */
150499      while( p<aEnd ){
150500        nDoc++;
150501        while( (*p++)&0x80 );     /* Skip docid varint */
150502        fts3PoslistCopy(0, &p);   /* Skip over position list */
150503      }
150504    }
150505  
150506    return nDoc;
150507  }
150508  
150509  /*
150510  ** Advance the cursor to the next row in the %_content table that
150511  ** matches the search criteria.  For a MATCH search, this will be
150512  ** the next row that matches. For a full-table scan, this will be
150513  ** simply the next row in the %_content table.  For a docid lookup,
150514  ** this routine simply sets the EOF flag.
150515  **
150516  ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
150517  ** even if we reach end-of-file.  The fts3EofMethod() will be called
150518  ** subsequently to determine whether or not an EOF was hit.
150519  */
150520  static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
150521    int rc;
150522    Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
150523    if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
150524      if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
150525        pCsr->isEof = 1;
150526        rc = sqlite3_reset(pCsr->pStmt);
150527      }else{
150528        pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
150529        rc = SQLITE_OK;
150530      }
150531    }else{
150532      rc = fts3EvalNext((Fts3Cursor *)pCursor);
150533    }
150534    assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
150535    return rc;
150536  }
150537  
150538  /*
150539  ** The following are copied from sqliteInt.h.
150540  **
150541  ** Constants for the largest and smallest possible 64-bit signed integers.
150542  ** These macros are designed to work correctly on both 32-bit and 64-bit
150543  ** compilers.
150544  */
150545  #ifndef SQLITE_AMALGAMATION
150546  # define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
150547  # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
150548  #endif
150549  
150550  /*
150551  ** If the numeric type of argument pVal is "integer", then return it
150552  ** converted to a 64-bit signed integer. Otherwise, return a copy of
150553  ** the second parameter, iDefault.
150554  */
150555  static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
150556    if( pVal ){
150557      int eType = sqlite3_value_numeric_type(pVal);
150558      if( eType==SQLITE_INTEGER ){
150559        return sqlite3_value_int64(pVal);
150560      }
150561    }
150562    return iDefault;
150563  }
150564  
150565  /*
150566  ** This is the xFilter interface for the virtual table.  See
150567  ** the virtual table xFilter method documentation for additional
150568  ** information.
150569  **
150570  ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
150571  ** the %_content table.
150572  **
150573  ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
150574  ** in the %_content table.
150575  **
150576  ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
150577  ** column on the left-hand side of the MATCH operator is column
150578  ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
150579  ** side of the MATCH operator.
150580  */
150581  static int fts3FilterMethod(
150582    sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
150583    int idxNum,                     /* Strategy index */
150584    const char *idxStr,             /* Unused */
150585    int nVal,                       /* Number of elements in apVal */
150586    sqlite3_value **apVal           /* Arguments for the indexing scheme */
150587  ){
150588    int rc = SQLITE_OK;
150589    char *zSql;                     /* SQL statement used to access %_content */
150590    int eSearch;
150591    Fts3Table *p = (Fts3Table *)pCursor->pVtab;
150592    Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
150593  
150594    sqlite3_value *pCons = 0;       /* The MATCH or rowid constraint, if any */
150595    sqlite3_value *pLangid = 0;     /* The "langid = ?" constraint, if any */
150596    sqlite3_value *pDocidGe = 0;    /* The "docid >= ?" constraint, if any */
150597    sqlite3_value *pDocidLe = 0;    /* The "docid <= ?" constraint, if any */
150598    int iIdx;
150599  
150600    UNUSED_PARAMETER(idxStr);
150601    UNUSED_PARAMETER(nVal);
150602  
150603    eSearch = (idxNum & 0x0000FFFF);
150604    assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
150605    assert( p->pSegments==0 );
150606  
150607    /* Collect arguments into local variables */
150608    iIdx = 0;
150609    if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
150610    if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
150611    if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
150612    if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
150613    assert( iIdx==nVal );
150614  
150615    /* In case the cursor has been used before, clear it now. */
150616    fts3ClearCursor(pCsr);
150617  
150618    /* Set the lower and upper bounds on docids to return */
150619    pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
150620    pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
150621  
150622    if( idxStr ){
150623      pCsr->bDesc = (idxStr[0]=='D');
150624    }else{
150625      pCsr->bDesc = p->bDescIdx;
150626    }
150627    pCsr->eSearch = (i16)eSearch;
150628  
150629    if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
150630      int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
150631      const char *zQuery = (const char *)sqlite3_value_text(pCons);
150632  
150633      if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
150634        return SQLITE_NOMEM;
150635      }
150636  
150637      pCsr->iLangid = 0;
150638      if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
150639  
150640      assert( p->base.zErrMsg==0 );
150641      rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
150642          p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr, 
150643          &p->base.zErrMsg
150644      );
150645      if( rc!=SQLITE_OK ){
150646        return rc;
150647      }
150648  
150649      rc = fts3EvalStart(pCsr);
150650      sqlite3Fts3SegmentsClose(p);
150651      if( rc!=SQLITE_OK ) return rc;
150652      pCsr->pNextId = pCsr->aDoclist;
150653      pCsr->iPrevId = 0;
150654    }
150655  
150656    /* Compile a SELECT statement for this cursor. For a full-table-scan, the
150657    ** statement loops through all rows of the %_content table. For a
150658    ** full-text query or docid lookup, the statement retrieves a single
150659    ** row by docid.
150660    */
150661    if( eSearch==FTS3_FULLSCAN_SEARCH ){
150662      if( pDocidGe || pDocidLe ){
150663        zSql = sqlite3_mprintf(
150664            "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
150665            p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
150666            (pCsr->bDesc ? "DESC" : "ASC")
150667        );
150668      }else{
150669        zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s", 
150670            p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
150671        );
150672      }
150673      if( zSql ){
150674        rc = sqlite3_prepare_v3(p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
150675        sqlite3_free(zSql);
150676      }else{
150677        rc = SQLITE_NOMEM;
150678      }
150679    }else if( eSearch==FTS3_DOCID_SEARCH ){
150680      rc = fts3CursorSeekStmt(pCsr);
150681      if( rc==SQLITE_OK ){
150682        rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
150683      }
150684    }
150685    if( rc!=SQLITE_OK ) return rc;
150686  
150687    return fts3NextMethod(pCursor);
150688  }
150689  
150690  /* 
150691  ** This is the xEof method of the virtual table. SQLite calls this 
150692  ** routine to find out if it has reached the end of a result set.
150693  */
150694  static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
150695    Fts3Cursor *pCsr = (Fts3Cursor*)pCursor;
150696    if( pCsr->isEof ){
150697      fts3ClearCursor(pCsr);
150698      pCsr->isEof = 1;
150699    }
150700    return pCsr->isEof;
150701  }
150702  
150703  /* 
150704  ** This is the xRowid method. The SQLite core calls this routine to
150705  ** retrieve the rowid for the current row of the result set. fts3
150706  ** exposes %_content.docid as the rowid for the virtual table. The
150707  ** rowid should be written to *pRowid.
150708  */
150709  static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
150710    Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
150711    *pRowid = pCsr->iPrevId;
150712    return SQLITE_OK;
150713  }
150714  
150715  /* 
150716  ** This is the xColumn method, called by SQLite to request a value from
150717  ** the row that the supplied cursor currently points to.
150718  **
150719  ** If:
150720  **
150721  **   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
150722  **   (iCol == p->nColumn)   -> Magic column with the same name as the table.
150723  **   (iCol == p->nColumn+1) -> Docid column
150724  **   (iCol == p->nColumn+2) -> Langid column
150725  */
150726  static int fts3ColumnMethod(
150727    sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
150728    sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
150729    int iCol                        /* Index of column to read value from */
150730  ){
150731    int rc = SQLITE_OK;             /* Return Code */
150732    Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
150733    Fts3Table *p = (Fts3Table *)pCursor->pVtab;
150734  
150735    /* The column value supplied by SQLite must be in range. */
150736    assert( iCol>=0 && iCol<=p->nColumn+2 );
150737  
150738    switch( iCol-p->nColumn ){
150739      case 0:
150740        /* The special 'table-name' column */
150741        sqlite3_result_pointer(pCtx, pCsr, "fts3cursor", 0);
150742        break;
150743  
150744      case 1:
150745        /* The docid column */
150746        sqlite3_result_int64(pCtx, pCsr->iPrevId);
150747        break;
150748  
150749      case 2:
150750        if( pCsr->pExpr ){
150751          sqlite3_result_int64(pCtx, pCsr->iLangid);
150752          break;
150753        }else if( p->zLanguageid==0 ){
150754          sqlite3_result_int(pCtx, 0);
150755          break;
150756        }else{
150757          iCol = p->nColumn;
150758          /* fall-through */
150759        }
150760  
150761      default:
150762        /* A user column. Or, if this is a full-table scan, possibly the
150763        ** language-id column. Seek the cursor. */
150764        rc = fts3CursorSeek(0, pCsr);
150765        if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)-1>iCol ){
150766          sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
150767        }
150768        break;
150769    }
150770  
150771    assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
150772    return rc;
150773  }
150774  
150775  /* 
150776  ** This function is the implementation of the xUpdate callback used by 
150777  ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
150778  ** inserted, updated or deleted.
150779  */
150780  static int fts3UpdateMethod(
150781    sqlite3_vtab *pVtab,            /* Virtual table handle */
150782    int nArg,                       /* Size of argument array */
150783    sqlite3_value **apVal,          /* Array of arguments */
150784    sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
150785  ){
150786    return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
150787  }
150788  
150789  /*
150790  ** Implementation of xSync() method. Flush the contents of the pending-terms
150791  ** hash-table to the database.
150792  */
150793  static int fts3SyncMethod(sqlite3_vtab *pVtab){
150794  
150795    /* Following an incremental-merge operation, assuming that the input
150796    ** segments are not completely consumed (the usual case), they are updated
150797    ** in place to remove the entries that have already been merged. This
150798    ** involves updating the leaf block that contains the smallest unmerged
150799    ** entry and each block (if any) between the leaf and the root node. So
150800    ** if the height of the input segment b-trees is N, and input segments
150801    ** are merged eight at a time, updating the input segments at the end
150802    ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
150803    ** small - often between 0 and 2. So the overhead of the incremental
150804    ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
150805    ** dwarfing the actual productive work accomplished, the incremental merge
150806    ** is only attempted if it will write at least 64 leaf blocks. Hence
150807    ** nMinMerge.
150808    **
150809    ** Of course, updating the input segments also involves deleting a bunch
150810    ** of blocks from the segments table. But this is not considered overhead
150811    ** as it would also be required by a crisis-merge that used the same input 
150812    ** segments.
150813    */
150814    const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
150815  
150816    Fts3Table *p = (Fts3Table*)pVtab;
150817    int rc;
150818    i64 iLastRowid = sqlite3_last_insert_rowid(p->db);
150819  
150820    rc = sqlite3Fts3PendingTermsFlush(p);
150821    if( rc==SQLITE_OK 
150822     && p->nLeafAdd>(nMinMerge/16) 
150823     && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
150824    ){
150825      int mxLevel = 0;              /* Maximum relative level value in db */
150826      int A;                        /* Incr-merge parameter A */
150827  
150828      rc = sqlite3Fts3MaxLevel(p, &mxLevel);
150829      assert( rc==SQLITE_OK || mxLevel==0 );
150830      A = p->nLeafAdd * mxLevel;
150831      A += (A/2);
150832      if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
150833    }
150834    sqlite3Fts3SegmentsClose(p);
150835    sqlite3_set_last_insert_rowid(p->db, iLastRowid);
150836    return rc;
150837  }
150838  
150839  /*
150840  ** If it is currently unknown whether or not the FTS table has an %_stat
150841  ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
150842  ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
150843  ** if an error occurs.
150844  */
150845  static int fts3SetHasStat(Fts3Table *p){
150846    int rc = SQLITE_OK;
150847    if( p->bHasStat==2 ){
150848      char *zTbl = sqlite3_mprintf("%s_stat", p->zName);
150849      if( zTbl ){
150850        int res = sqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0);
150851        sqlite3_free(zTbl);
150852        p->bHasStat = (res==SQLITE_OK);
150853      }else{
150854        rc = SQLITE_NOMEM;
150855      }
150856    }
150857    return rc;
150858  }
150859  
150860  /*
150861  ** Implementation of xBegin() method. 
150862  */
150863  static int fts3BeginMethod(sqlite3_vtab *pVtab){
150864    Fts3Table *p = (Fts3Table*)pVtab;
150865    UNUSED_PARAMETER(pVtab);
150866    assert( p->pSegments==0 );
150867    assert( p->nPendingData==0 );
150868    assert( p->inTransaction!=1 );
150869    TESTONLY( p->inTransaction = 1 );
150870    TESTONLY( p->mxSavepoint = -1; );
150871    p->nLeafAdd = 0;
150872    return fts3SetHasStat(p);
150873  }
150874  
150875  /*
150876  ** Implementation of xCommit() method. This is a no-op. The contents of
150877  ** the pending-terms hash-table have already been flushed into the database
150878  ** by fts3SyncMethod().
150879  */
150880  static int fts3CommitMethod(sqlite3_vtab *pVtab){
150881    TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
150882    UNUSED_PARAMETER(pVtab);
150883    assert( p->nPendingData==0 );
150884    assert( p->inTransaction!=0 );
150885    assert( p->pSegments==0 );
150886    TESTONLY( p->inTransaction = 0 );
150887    TESTONLY( p->mxSavepoint = -1; );
150888    return SQLITE_OK;
150889  }
150890  
150891  /*
150892  ** Implementation of xRollback(). Discard the contents of the pending-terms
150893  ** hash-table. Any changes made to the database are reverted by SQLite.
150894  */
150895  static int fts3RollbackMethod(sqlite3_vtab *pVtab){
150896    Fts3Table *p = (Fts3Table*)pVtab;
150897    sqlite3Fts3PendingTermsClear(p);
150898    assert( p->inTransaction!=0 );
150899    TESTONLY( p->inTransaction = 0 );
150900    TESTONLY( p->mxSavepoint = -1; );
150901    return SQLITE_OK;
150902  }
150903  
150904  /*
150905  ** When called, *ppPoslist must point to the byte immediately following the
150906  ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
150907  ** moves *ppPoslist so that it instead points to the first byte of the
150908  ** same position list.
150909  */
150910  static void fts3ReversePoslist(char *pStart, char **ppPoslist){
150911    char *p = &(*ppPoslist)[-2];
150912    char c = 0;
150913  
150914    /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
150915    while( p>pStart && (c=*p--)==0 );
150916  
150917    /* Search backwards for a varint with value zero (the end of the previous 
150918    ** poslist). This is an 0x00 byte preceded by some byte that does not
150919    ** have the 0x80 bit set.  */
150920    while( p>pStart && (*p & 0x80) | c ){ 
150921      c = *p--; 
150922    }
150923    assert( p==pStart || c==0 );
150924  
150925    /* At this point p points to that preceding byte without the 0x80 bit
150926    ** set. So to find the start of the poslist, skip forward 2 bytes then
150927    ** over a varint. 
150928    **
150929    ** Normally. The other case is that p==pStart and the poslist to return
150930    ** is the first in the doclist. In this case do not skip forward 2 bytes.
150931    ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
150932    ** is required for cases where the first byte of a doclist and the
150933    ** doclist is empty. For example, if the first docid is 10, a doclist
150934    ** that begins with:
150935    **
150936    **   0x0A 0x00 <next docid delta varint>
150937    */
150938    if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
150939    while( *p++&0x80 );
150940    *ppPoslist = p;
150941  }
150942  
150943  /*
150944  ** Helper function used by the implementation of the overloaded snippet(),
150945  ** offsets() and optimize() SQL functions.
150946  **
150947  ** If the value passed as the third argument is a blob of size
150948  ** sizeof(Fts3Cursor*), then the blob contents are copied to the 
150949  ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
150950  ** message is written to context pContext and SQLITE_ERROR returned. The
150951  ** string passed via zFunc is used as part of the error message.
150952  */
150953  static int fts3FunctionArg(
150954    sqlite3_context *pContext,      /* SQL function call context */
150955    const char *zFunc,              /* Function name */
150956    sqlite3_value *pVal,            /* argv[0] passed to function */
150957    Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
150958  ){
150959    int rc;
150960    *ppCsr = (Fts3Cursor*)sqlite3_value_pointer(pVal, "fts3cursor");
150961    if( (*ppCsr)!=0 ){
150962      rc = SQLITE_OK;
150963    }else{
150964      char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
150965      sqlite3_result_error(pContext, zErr, -1);
150966      sqlite3_free(zErr);
150967      rc = SQLITE_ERROR;
150968    }
150969    return rc;
150970  }
150971  
150972  /*
150973  ** Implementation of the snippet() function for FTS3
150974  */
150975  static void fts3SnippetFunc(
150976    sqlite3_context *pContext,      /* SQLite function call context */
150977    int nVal,                       /* Size of apVal[] array */
150978    sqlite3_value **apVal           /* Array of arguments */
150979  ){
150980    Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
150981    const char *zStart = "<b>";
150982    const char *zEnd = "</b>";
150983    const char *zEllipsis = "<b>...</b>";
150984    int iCol = -1;
150985    int nToken = 15;                /* Default number of tokens in snippet */
150986  
150987    /* There must be at least one argument passed to this function (otherwise
150988    ** the non-overloaded version would have been called instead of this one).
150989    */
150990    assert( nVal>=1 );
150991  
150992    if( nVal>6 ){
150993      sqlite3_result_error(pContext, 
150994          "wrong number of arguments to function snippet()", -1);
150995      return;
150996    }
150997    if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
150998  
150999    switch( nVal ){
151000      case 6: nToken = sqlite3_value_int(apVal[5]);
151001      case 5: iCol = sqlite3_value_int(apVal[4]);
151002      case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
151003      case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
151004      case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
151005    }
151006    if( !zEllipsis || !zEnd || !zStart ){
151007      sqlite3_result_error_nomem(pContext);
151008    }else if( nToken==0 ){
151009      sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
151010    }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
151011      sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
151012    }
151013  }
151014  
151015  /*
151016  ** Implementation of the offsets() function for FTS3
151017  */
151018  static void fts3OffsetsFunc(
151019    sqlite3_context *pContext,      /* SQLite function call context */
151020    int nVal,                       /* Size of argument array */
151021    sqlite3_value **apVal           /* Array of arguments */
151022  ){
151023    Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
151024  
151025    UNUSED_PARAMETER(nVal);
151026  
151027    assert( nVal==1 );
151028    if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
151029    assert( pCsr );
151030    if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
151031      sqlite3Fts3Offsets(pContext, pCsr);
151032    }
151033  }
151034  
151035  /* 
151036  ** Implementation of the special optimize() function for FTS3. This 
151037  ** function merges all segments in the database to a single segment.
151038  ** Example usage is:
151039  **
151040  **   SELECT optimize(t) FROM t LIMIT 1;
151041  **
151042  ** where 't' is the name of an FTS3 table.
151043  */
151044  static void fts3OptimizeFunc(
151045    sqlite3_context *pContext,      /* SQLite function call context */
151046    int nVal,                       /* Size of argument array */
151047    sqlite3_value **apVal           /* Array of arguments */
151048  ){
151049    int rc;                         /* Return code */
151050    Fts3Table *p;                   /* Virtual table handle */
151051    Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
151052  
151053    UNUSED_PARAMETER(nVal);
151054  
151055    assert( nVal==1 );
151056    if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
151057    p = (Fts3Table *)pCursor->base.pVtab;
151058    assert( p );
151059  
151060    rc = sqlite3Fts3Optimize(p);
151061  
151062    switch( rc ){
151063      case SQLITE_OK:
151064        sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
151065        break;
151066      case SQLITE_DONE:
151067        sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
151068        break;
151069      default:
151070        sqlite3_result_error_code(pContext, rc);
151071        break;
151072    }
151073  }
151074  
151075  /*
151076  ** Implementation of the matchinfo() function for FTS3
151077  */
151078  static void fts3MatchinfoFunc(
151079    sqlite3_context *pContext,      /* SQLite function call context */
151080    int nVal,                       /* Size of argument array */
151081    sqlite3_value **apVal           /* Array of arguments */
151082  ){
151083    Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
151084    assert( nVal==1 || nVal==2 );
151085    if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
151086      const char *zArg = 0;
151087      if( nVal>1 ){
151088        zArg = (const char *)sqlite3_value_text(apVal[1]);
151089      }
151090      sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
151091    }
151092  }
151093  
151094  /*
151095  ** This routine implements the xFindFunction method for the FTS3
151096  ** virtual table.
151097  */
151098  static int fts3FindFunctionMethod(
151099    sqlite3_vtab *pVtab,            /* Virtual table handle */
151100    int nArg,                       /* Number of SQL function arguments */
151101    const char *zName,              /* Name of SQL function */
151102    void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
151103    void **ppArg                    /* Unused */
151104  ){
151105    struct Overloaded {
151106      const char *zName;
151107      void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
151108    } aOverload[] = {
151109      { "snippet", fts3SnippetFunc },
151110      { "offsets", fts3OffsetsFunc },
151111      { "optimize", fts3OptimizeFunc },
151112      { "matchinfo", fts3MatchinfoFunc },
151113    };
151114    int i;                          /* Iterator variable */
151115  
151116    UNUSED_PARAMETER(pVtab);
151117    UNUSED_PARAMETER(nArg);
151118    UNUSED_PARAMETER(ppArg);
151119  
151120    for(i=0; i<SizeofArray(aOverload); i++){
151121      if( strcmp(zName, aOverload[i].zName)==0 ){
151122        *pxFunc = aOverload[i].xFunc;
151123        return 1;
151124      }
151125    }
151126  
151127    /* No function of the specified name was found. Return 0. */
151128    return 0;
151129  }
151130  
151131  /*
151132  ** Implementation of FTS3 xRename method. Rename an fts3 table.
151133  */
151134  static int fts3RenameMethod(
151135    sqlite3_vtab *pVtab,            /* Virtual table handle */
151136    const char *zName               /* New name of table */
151137  ){
151138    Fts3Table *p = (Fts3Table *)pVtab;
151139    sqlite3 *db = p->db;            /* Database connection */
151140    int rc;                         /* Return Code */
151141  
151142    /* At this point it must be known if the %_stat table exists or not.
151143    ** So bHasStat may not be 2.  */
151144    rc = fts3SetHasStat(p);
151145    
151146    /* As it happens, the pending terms table is always empty here. This is
151147    ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction 
151148    ** always opens a savepoint transaction. And the xSavepoint() method 
151149    ** flushes the pending terms table. But leave the (no-op) call to
151150    ** PendingTermsFlush() in in case that changes.
151151    */
151152    assert( p->nPendingData==0 );
151153    if( rc==SQLITE_OK ){
151154      rc = sqlite3Fts3PendingTermsFlush(p);
151155    }
151156  
151157    if( p->zContentTbl==0 ){
151158      fts3DbExec(&rc, db,
151159        "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
151160        p->zDb, p->zName, zName
151161      );
151162    }
151163  
151164    if( p->bHasDocsize ){
151165      fts3DbExec(&rc, db,
151166        "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
151167        p->zDb, p->zName, zName
151168      );
151169    }
151170    if( p->bHasStat ){
151171      fts3DbExec(&rc, db,
151172        "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
151173        p->zDb, p->zName, zName
151174      );
151175    }
151176    fts3DbExec(&rc, db,
151177      "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
151178      p->zDb, p->zName, zName
151179    );
151180    fts3DbExec(&rc, db,
151181      "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
151182      p->zDb, p->zName, zName
151183    );
151184    return rc;
151185  }
151186  
151187  /*
151188  ** The xSavepoint() method.
151189  **
151190  ** Flush the contents of the pending-terms table to disk.
151191  */
151192  static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
151193    int rc = SQLITE_OK;
151194    UNUSED_PARAMETER(iSavepoint);
151195    assert( ((Fts3Table *)pVtab)->inTransaction );
151196    assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
151197    TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
151198    if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
151199      rc = fts3SyncMethod(pVtab);
151200    }
151201    return rc;
151202  }
151203  
151204  /*
151205  ** The xRelease() method.
151206  **
151207  ** This is a no-op.
151208  */
151209  static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
151210    TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
151211    UNUSED_PARAMETER(iSavepoint);
151212    UNUSED_PARAMETER(pVtab);
151213    assert( p->inTransaction );
151214    assert( p->mxSavepoint >= iSavepoint );
151215    TESTONLY( p->mxSavepoint = iSavepoint-1 );
151216    return SQLITE_OK;
151217  }
151218  
151219  /*
151220  ** The xRollbackTo() method.
151221  **
151222  ** Discard the contents of the pending terms table.
151223  */
151224  static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
151225    Fts3Table *p = (Fts3Table*)pVtab;
151226    UNUSED_PARAMETER(iSavepoint);
151227    assert( p->inTransaction );
151228    assert( p->mxSavepoint >= iSavepoint );
151229    TESTONLY( p->mxSavepoint = iSavepoint );
151230    sqlite3Fts3PendingTermsClear(p);
151231    return SQLITE_OK;
151232  }
151233  
151234  static const sqlite3_module fts3Module = {
151235    /* iVersion      */ 2,
151236    /* xCreate       */ fts3CreateMethod,
151237    /* xConnect      */ fts3ConnectMethod,
151238    /* xBestIndex    */ fts3BestIndexMethod,
151239    /* xDisconnect   */ fts3DisconnectMethod,
151240    /* xDestroy      */ fts3DestroyMethod,
151241    /* xOpen         */ fts3OpenMethod,
151242    /* xClose        */ fts3CloseMethod,
151243    /* xFilter       */ fts3FilterMethod,
151244    /* xNext         */ fts3NextMethod,
151245    /* xEof          */ fts3EofMethod,
151246    /* xColumn       */ fts3ColumnMethod,
151247    /* xRowid        */ fts3RowidMethod,
151248    /* xUpdate       */ fts3UpdateMethod,
151249    /* xBegin        */ fts3BeginMethod,
151250    /* xSync         */ fts3SyncMethod,
151251    /* xCommit       */ fts3CommitMethod,
151252    /* xRollback     */ fts3RollbackMethod,
151253    /* xFindFunction */ fts3FindFunctionMethod,
151254    /* xRename */       fts3RenameMethod,
151255    /* xSavepoint    */ fts3SavepointMethod,
151256    /* xRelease      */ fts3ReleaseMethod,
151257    /* xRollbackTo   */ fts3RollbackToMethod,
151258  };
151259  
151260  /*
151261  ** This function is registered as the module destructor (called when an
151262  ** FTS3 enabled database connection is closed). It frees the memory
151263  ** allocated for the tokenizer hash table.
151264  */
151265  static void hashDestroy(void *p){
151266    Fts3Hash *pHash = (Fts3Hash *)p;
151267    sqlite3Fts3HashClear(pHash);
151268    sqlite3_free(pHash);
151269  }
151270  
151271  /*
151272  ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are 
151273  ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
151274  ** respectively. The following three forward declarations are for functions
151275  ** declared in these files used to retrieve the respective implementations.
151276  **
151277  ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
151278  ** to by the argument to point to the "simple" tokenizer implementation.
151279  ** And so on.
151280  */
151281  SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
151282  SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
151283  #ifndef SQLITE_DISABLE_FTS3_UNICODE
151284  SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
151285  #endif
151286  #ifdef SQLITE_ENABLE_ICU
151287  SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
151288  #endif
151289  
151290  /*
151291  ** Initialize the fts3 extension. If this extension is built as part
151292  ** of the sqlite library, then this function is called directly by
151293  ** SQLite. If fts3 is built as a dynamically loadable extension, this
151294  ** function is called by the sqlite3_extension_init() entry point.
151295  */
151296  SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
151297    int rc = SQLITE_OK;
151298    Fts3Hash *pHash = 0;
151299    const sqlite3_tokenizer_module *pSimple = 0;
151300    const sqlite3_tokenizer_module *pPorter = 0;
151301  #ifndef SQLITE_DISABLE_FTS3_UNICODE
151302    const sqlite3_tokenizer_module *pUnicode = 0;
151303  #endif
151304  
151305  #ifdef SQLITE_ENABLE_ICU
151306    const sqlite3_tokenizer_module *pIcu = 0;
151307    sqlite3Fts3IcuTokenizerModule(&pIcu);
151308  #endif
151309  
151310  #ifndef SQLITE_DISABLE_FTS3_UNICODE
151311    sqlite3Fts3UnicodeTokenizer(&pUnicode);
151312  #endif
151313  
151314  #ifdef SQLITE_TEST
151315    rc = sqlite3Fts3InitTerm(db);
151316    if( rc!=SQLITE_OK ) return rc;
151317  #endif
151318  
151319    rc = sqlite3Fts3InitAux(db);
151320    if( rc!=SQLITE_OK ) return rc;
151321  
151322    sqlite3Fts3SimpleTokenizerModule(&pSimple);
151323    sqlite3Fts3PorterTokenizerModule(&pPorter);
151324  
151325    /* Allocate and initialize the hash-table used to store tokenizers. */
151326    pHash = sqlite3_malloc(sizeof(Fts3Hash));
151327    if( !pHash ){
151328      rc = SQLITE_NOMEM;
151329    }else{
151330      sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
151331    }
151332  
151333    /* Load the built-in tokenizers into the hash table */
151334    if( rc==SQLITE_OK ){
151335      if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
151336       || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
151337  
151338  #ifndef SQLITE_DISABLE_FTS3_UNICODE
151339       || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode) 
151340  #endif
151341  #ifdef SQLITE_ENABLE_ICU
151342       || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
151343  #endif
151344      ){
151345        rc = SQLITE_NOMEM;
151346      }
151347    }
151348  
151349  #ifdef SQLITE_TEST
151350    if( rc==SQLITE_OK ){
151351      rc = sqlite3Fts3ExprInitTestInterface(db);
151352    }
151353  #endif
151354  
151355    /* Create the virtual table wrapper around the hash-table and overload 
151356    ** the four scalar functions. If this is successful, register the
151357    ** module with sqlite.
151358    */
151359    if( SQLITE_OK==rc 
151360     && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
151361     && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
151362     && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
151363     && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
151364     && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
151365     && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
151366    ){
151367      rc = sqlite3_create_module_v2(
151368          db, "fts3", &fts3Module, (void *)pHash, hashDestroy
151369      );
151370      if( rc==SQLITE_OK ){
151371        rc = sqlite3_create_module_v2(
151372            db, "fts4", &fts3Module, (void *)pHash, 0
151373        );
151374      }
151375      if( rc==SQLITE_OK ){
151376        rc = sqlite3Fts3InitTok(db, (void *)pHash);
151377      }
151378      return rc;
151379    }
151380  
151381  
151382    /* An error has occurred. Delete the hash table and return the error code. */
151383    assert( rc!=SQLITE_OK );
151384    if( pHash ){
151385      sqlite3Fts3HashClear(pHash);
151386      sqlite3_free(pHash);
151387    }
151388    return rc;
151389  }
151390  
151391  /*
151392  ** Allocate an Fts3MultiSegReader for each token in the expression headed
151393  ** by pExpr. 
151394  **
151395  ** An Fts3SegReader object is a cursor that can seek or scan a range of
151396  ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
151397  ** Fts3SegReader objects internally to provide an interface to seek or scan
151398  ** within the union of all segments of a b-tree. Hence the name.
151399  **
151400  ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
151401  ** segment b-tree (if the term is not a prefix or it is a prefix for which
151402  ** there exists prefix b-tree of the right length) then it may be traversed
151403  ** and merged incrementally. Otherwise, it has to be merged into an in-memory 
151404  ** doclist and then traversed.
151405  */
151406  static void fts3EvalAllocateReaders(
151407    Fts3Cursor *pCsr,               /* FTS cursor handle */
151408    Fts3Expr *pExpr,                /* Allocate readers for this expression */
151409    int *pnToken,                   /* OUT: Total number of tokens in phrase. */
151410    int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
151411    int *pRc                        /* IN/OUT: Error code */
151412  ){
151413    if( pExpr && SQLITE_OK==*pRc ){
151414      if( pExpr->eType==FTSQUERY_PHRASE ){
151415        int i;
151416        int nToken = pExpr->pPhrase->nToken;
151417        *pnToken += nToken;
151418        for(i=0; i<nToken; i++){
151419          Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
151420          int rc = fts3TermSegReaderCursor(pCsr, 
151421              pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
151422          );
151423          if( rc!=SQLITE_OK ){
151424            *pRc = rc;
151425            return;
151426          }
151427        }
151428        assert( pExpr->pPhrase->iDoclistToken==0 );
151429        pExpr->pPhrase->iDoclistToken = -1;
151430      }else{
151431        *pnOr += (pExpr->eType==FTSQUERY_OR);
151432        fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
151433        fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
151434      }
151435    }
151436  }
151437  
151438  /*
151439  ** Arguments pList/nList contain the doclist for token iToken of phrase p.
151440  ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
151441  **
151442  ** This function assumes that pList points to a buffer allocated using
151443  ** sqlite3_malloc(). This function takes responsibility for eventually
151444  ** freeing the buffer.
151445  **
151446  ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
151447  */
151448  static int fts3EvalPhraseMergeToken(
151449    Fts3Table *pTab,                /* FTS Table pointer */
151450    Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
151451    int iToken,                     /* Token pList/nList corresponds to */
151452    char *pList,                    /* Pointer to doclist */
151453    int nList                       /* Number of bytes in pList */
151454  ){
151455    int rc = SQLITE_OK;
151456    assert( iToken!=p->iDoclistToken );
151457  
151458    if( pList==0 ){
151459      sqlite3_free(p->doclist.aAll);
151460      p->doclist.aAll = 0;
151461      p->doclist.nAll = 0;
151462    }
151463  
151464    else if( p->iDoclistToken<0 ){
151465      p->doclist.aAll = pList;
151466      p->doclist.nAll = nList;
151467    }
151468  
151469    else if( p->doclist.aAll==0 ){
151470      sqlite3_free(pList);
151471    }
151472  
151473    else {
151474      char *pLeft;
151475      char *pRight;
151476      int nLeft;
151477      int nRight;
151478      int nDiff;
151479  
151480      if( p->iDoclistToken<iToken ){
151481        pLeft = p->doclist.aAll;
151482        nLeft = p->doclist.nAll;
151483        pRight = pList;
151484        nRight = nList;
151485        nDiff = iToken - p->iDoclistToken;
151486      }else{
151487        pRight = p->doclist.aAll;
151488        nRight = p->doclist.nAll;
151489        pLeft = pList;
151490        nLeft = nList;
151491        nDiff = p->iDoclistToken - iToken;
151492      }
151493  
151494      rc = fts3DoclistPhraseMerge(
151495          pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
151496      );
151497      sqlite3_free(pLeft);
151498      p->doclist.aAll = pRight;
151499      p->doclist.nAll = nRight;
151500    }
151501  
151502    if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
151503    return rc;
151504  }
151505  
151506  /*
151507  ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
151508  ** does not take deferred tokens into account.
151509  **
151510  ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
151511  */
151512  static int fts3EvalPhraseLoad(
151513    Fts3Cursor *pCsr,               /* FTS Cursor handle */
151514    Fts3Phrase *p                   /* Phrase object */
151515  ){
151516    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
151517    int iToken;
151518    int rc = SQLITE_OK;
151519  
151520    for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
151521      Fts3PhraseToken *pToken = &p->aToken[iToken];
151522      assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
151523  
151524      if( pToken->pSegcsr ){
151525        int nThis = 0;
151526        char *pThis = 0;
151527        rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
151528        if( rc==SQLITE_OK ){
151529          rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
151530        }
151531      }
151532      assert( pToken->pSegcsr==0 );
151533    }
151534  
151535    return rc;
151536  }
151537  
151538  /*
151539  ** This function is called on each phrase after the position lists for
151540  ** any deferred tokens have been loaded into memory. It updates the phrases
151541  ** current position list to include only those positions that are really
151542  ** instances of the phrase (after considering deferred tokens). If this
151543  ** means that the phrase does not appear in the current row, doclist.pList
151544  ** and doclist.nList are both zeroed.
151545  **
151546  ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
151547  */
151548  static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
151549    int iToken;                     /* Used to iterate through phrase tokens */
151550    char *aPoslist = 0;             /* Position list for deferred tokens */
151551    int nPoslist = 0;               /* Number of bytes in aPoslist */
151552    int iPrev = -1;                 /* Token number of previous deferred token */
151553  
151554    assert( pPhrase->doclist.bFreeList==0 );
151555  
151556    for(iToken=0; iToken<pPhrase->nToken; iToken++){
151557      Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
151558      Fts3DeferredToken *pDeferred = pToken->pDeferred;
151559  
151560      if( pDeferred ){
151561        char *pList;
151562        int nList;
151563        int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
151564        if( rc!=SQLITE_OK ) return rc;
151565  
151566        if( pList==0 ){
151567          sqlite3_free(aPoslist);
151568          pPhrase->doclist.pList = 0;
151569          pPhrase->doclist.nList = 0;
151570          return SQLITE_OK;
151571  
151572        }else if( aPoslist==0 ){
151573          aPoslist = pList;
151574          nPoslist = nList;
151575  
151576        }else{
151577          char *aOut = pList;
151578          char *p1 = aPoslist;
151579          char *p2 = aOut;
151580  
151581          assert( iPrev>=0 );
151582          fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
151583          sqlite3_free(aPoslist);
151584          aPoslist = pList;
151585          nPoslist = (int)(aOut - aPoslist);
151586          if( nPoslist==0 ){
151587            sqlite3_free(aPoslist);
151588            pPhrase->doclist.pList = 0;
151589            pPhrase->doclist.nList = 0;
151590            return SQLITE_OK;
151591          }
151592        }
151593        iPrev = iToken;
151594      }
151595    }
151596  
151597    if( iPrev>=0 ){
151598      int nMaxUndeferred = pPhrase->iDoclistToken;
151599      if( nMaxUndeferred<0 ){
151600        pPhrase->doclist.pList = aPoslist;
151601        pPhrase->doclist.nList = nPoslist;
151602        pPhrase->doclist.iDocid = pCsr->iPrevId;
151603        pPhrase->doclist.bFreeList = 1;
151604      }else{
151605        int nDistance;
151606        char *p1;
151607        char *p2;
151608        char *aOut;
151609  
151610        if( nMaxUndeferred>iPrev ){
151611          p1 = aPoslist;
151612          p2 = pPhrase->doclist.pList;
151613          nDistance = nMaxUndeferred - iPrev;
151614        }else{
151615          p1 = pPhrase->doclist.pList;
151616          p2 = aPoslist;
151617          nDistance = iPrev - nMaxUndeferred;
151618        }
151619  
151620        aOut = (char *)sqlite3_malloc(nPoslist+8);
151621        if( !aOut ){
151622          sqlite3_free(aPoslist);
151623          return SQLITE_NOMEM;
151624        }
151625        
151626        pPhrase->doclist.pList = aOut;
151627        if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
151628          pPhrase->doclist.bFreeList = 1;
151629          pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
151630        }else{
151631          sqlite3_free(aOut);
151632          pPhrase->doclist.pList = 0;
151633          pPhrase->doclist.nList = 0;
151634        }
151635        sqlite3_free(aPoslist);
151636      }
151637    }
151638  
151639    return SQLITE_OK;
151640  }
151641  
151642  /*
151643  ** Maximum number of tokens a phrase may have to be considered for the
151644  ** incremental doclists strategy.
151645  */
151646  #define MAX_INCR_PHRASE_TOKENS 4
151647  
151648  /*
151649  ** This function is called for each Fts3Phrase in a full-text query 
151650  ** expression to initialize the mechanism for returning rows. Once this
151651  ** function has been called successfully on an Fts3Phrase, it may be
151652  ** used with fts3EvalPhraseNext() to iterate through the matching docids.
151653  **
151654  ** If parameter bOptOk is true, then the phrase may (or may not) use the
151655  ** incremental loading strategy. Otherwise, the entire doclist is loaded into
151656  ** memory within this call.
151657  **
151658  ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
151659  */
151660  static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
151661    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
151662    int rc = SQLITE_OK;             /* Error code */
151663    int i;
151664  
151665    /* Determine if doclists may be loaded from disk incrementally. This is
151666    ** possible if the bOptOk argument is true, the FTS doclists will be
151667    ** scanned in forward order, and the phrase consists of 
151668    ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
151669    ** tokens or prefix tokens that cannot use a prefix-index.  */
151670    int bHaveIncr = 0;
151671    int bIncrOk = (bOptOk 
151672     && pCsr->bDesc==pTab->bDescIdx 
151673     && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
151674  #ifdef SQLITE_TEST
151675     && pTab->bNoIncrDoclist==0
151676  #endif
151677    );
151678    for(i=0; bIncrOk==1 && i<p->nToken; i++){
151679      Fts3PhraseToken *pToken = &p->aToken[i];
151680      if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
151681        bIncrOk = 0;
151682      }
151683      if( pToken->pSegcsr ) bHaveIncr = 1;
151684    }
151685  
151686    if( bIncrOk && bHaveIncr ){
151687      /* Use the incremental approach. */
151688      int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
151689      for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
151690        Fts3PhraseToken *pToken = &p->aToken[i];
151691        Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
151692        if( pSegcsr ){
151693          rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
151694        }
151695      }
151696      p->bIncr = 1;
151697    }else{
151698      /* Load the full doclist for the phrase into memory. */
151699      rc = fts3EvalPhraseLoad(pCsr, p);
151700      p->bIncr = 0;
151701    }
151702  
151703    assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
151704    return rc;
151705  }
151706  
151707  /*
151708  ** This function is used to iterate backwards (from the end to start) 
151709  ** through doclists. It is used by this module to iterate through phrase
151710  ** doclists in reverse and by the fts3_write.c module to iterate through
151711  ** pending-terms lists when writing to databases with "order=desc".
151712  **
151713  ** The doclist may be sorted in ascending (parameter bDescIdx==0) or 
151714  ** descending (parameter bDescIdx==1) order of docid. Regardless, this
151715  ** function iterates from the end of the doclist to the beginning.
151716  */
151717  SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
151718    int bDescIdx,                   /* True if the doclist is desc */
151719    char *aDoclist,                 /* Pointer to entire doclist */
151720    int nDoclist,                   /* Length of aDoclist in bytes */
151721    char **ppIter,                  /* IN/OUT: Iterator pointer */
151722    sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
151723    int *pnList,                    /* OUT: List length pointer */
151724    u8 *pbEof                       /* OUT: End-of-file flag */
151725  ){
151726    char *p = *ppIter;
151727  
151728    assert( nDoclist>0 );
151729    assert( *pbEof==0 );
151730    assert( p || *piDocid==0 );
151731    assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
151732  
151733    if( p==0 ){
151734      sqlite3_int64 iDocid = 0;
151735      char *pNext = 0;
151736      char *pDocid = aDoclist;
151737      char *pEnd = &aDoclist[nDoclist];
151738      int iMul = 1;
151739  
151740      while( pDocid<pEnd ){
151741        sqlite3_int64 iDelta;
151742        pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
151743        iDocid += (iMul * iDelta);
151744        pNext = pDocid;
151745        fts3PoslistCopy(0, &pDocid);
151746        while( pDocid<pEnd && *pDocid==0 ) pDocid++;
151747        iMul = (bDescIdx ? -1 : 1);
151748      }
151749  
151750      *pnList = (int)(pEnd - pNext);
151751      *ppIter = pNext;
151752      *piDocid = iDocid;
151753    }else{
151754      int iMul = (bDescIdx ? -1 : 1);
151755      sqlite3_int64 iDelta;
151756      fts3GetReverseVarint(&p, aDoclist, &iDelta);
151757      *piDocid -= (iMul * iDelta);
151758  
151759      if( p==aDoclist ){
151760        *pbEof = 1;
151761      }else{
151762        char *pSave = p;
151763        fts3ReversePoslist(aDoclist, &p);
151764        *pnList = (int)(pSave - p);
151765      }
151766      *ppIter = p;
151767    }
151768  }
151769  
151770  /*
151771  ** Iterate forwards through a doclist.
151772  */
151773  SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
151774    int bDescIdx,                   /* True if the doclist is desc */
151775    char *aDoclist,                 /* Pointer to entire doclist */
151776    int nDoclist,                   /* Length of aDoclist in bytes */
151777    char **ppIter,                  /* IN/OUT: Iterator pointer */
151778    sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
151779    u8 *pbEof                       /* OUT: End-of-file flag */
151780  ){
151781    char *p = *ppIter;
151782  
151783    assert( nDoclist>0 );
151784    assert( *pbEof==0 );
151785    assert( p || *piDocid==0 );
151786    assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
151787  
151788    if( p==0 ){
151789      p = aDoclist;
151790      p += sqlite3Fts3GetVarint(p, piDocid);
151791    }else{
151792      fts3PoslistCopy(0, &p);
151793      while( p<&aDoclist[nDoclist] && *p==0 ) p++; 
151794      if( p>=&aDoclist[nDoclist] ){
151795        *pbEof = 1;
151796      }else{
151797        sqlite3_int64 iVar;
151798        p += sqlite3Fts3GetVarint(p, &iVar);
151799        *piDocid += ((bDescIdx ? -1 : 1) * iVar);
151800      }
151801    }
151802  
151803    *ppIter = p;
151804  }
151805  
151806  /*
151807  ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
151808  ** to true if EOF is reached.
151809  */
151810  static void fts3EvalDlPhraseNext(
151811    Fts3Table *pTab,
151812    Fts3Doclist *pDL,
151813    u8 *pbEof
151814  ){
151815    char *pIter;                            /* Used to iterate through aAll */
151816    char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
151817   
151818    if( pDL->pNextDocid ){
151819      pIter = pDL->pNextDocid;
151820    }else{
151821      pIter = pDL->aAll;
151822    }
151823  
151824    if( pIter>=pEnd ){
151825      /* We have already reached the end of this doclist. EOF. */
151826      *pbEof = 1;
151827    }else{
151828      sqlite3_int64 iDelta;
151829      pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
151830      if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
151831        pDL->iDocid += iDelta;
151832      }else{
151833        pDL->iDocid -= iDelta;
151834      }
151835      pDL->pList = pIter;
151836      fts3PoslistCopy(0, &pIter);
151837      pDL->nList = (int)(pIter - pDL->pList);
151838  
151839      /* pIter now points just past the 0x00 that terminates the position-
151840      ** list for document pDL->iDocid. However, if this position-list was
151841      ** edited in place by fts3EvalNearTrim(), then pIter may not actually
151842      ** point to the start of the next docid value. The following line deals
151843      ** with this case by advancing pIter past the zero-padding added by
151844      ** fts3EvalNearTrim().  */
151845      while( pIter<pEnd && *pIter==0 ) pIter++;
151846  
151847      pDL->pNextDocid = pIter;
151848      assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
151849      *pbEof = 0;
151850    }
151851  }
151852  
151853  /*
151854  ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
151855  */
151856  typedef struct TokenDoclist TokenDoclist;
151857  struct TokenDoclist {
151858    int bIgnore;
151859    sqlite3_int64 iDocid;
151860    char *pList;
151861    int nList;
151862  };
151863  
151864  /*
151865  ** Token pToken is an incrementally loaded token that is part of a 
151866  ** multi-token phrase. Advance it to the next matching document in the
151867  ** database and populate output variable *p with the details of the new
151868  ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
151869  **
151870  ** If an error occurs, return an SQLite error code. Otherwise, return 
151871  ** SQLITE_OK.
151872  */
151873  static int incrPhraseTokenNext(
151874    Fts3Table *pTab,                /* Virtual table handle */
151875    Fts3Phrase *pPhrase,            /* Phrase to advance token of */
151876    int iToken,                     /* Specific token to advance */
151877    TokenDoclist *p,                /* OUT: Docid and doclist for new entry */
151878    u8 *pbEof                       /* OUT: True if iterator is at EOF */
151879  ){
151880    int rc = SQLITE_OK;
151881  
151882    if( pPhrase->iDoclistToken==iToken ){
151883      assert( p->bIgnore==0 );
151884      assert( pPhrase->aToken[iToken].pSegcsr==0 );
151885      fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
151886      p->pList = pPhrase->doclist.pList;
151887      p->nList = pPhrase->doclist.nList;
151888      p->iDocid = pPhrase->doclist.iDocid;
151889    }else{
151890      Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
151891      assert( pToken->pDeferred==0 );
151892      assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
151893      if( pToken->pSegcsr ){
151894        assert( p->bIgnore==0 );
151895        rc = sqlite3Fts3MsrIncrNext(
151896            pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
151897        );
151898        if( p->pList==0 ) *pbEof = 1;
151899      }else{
151900        p->bIgnore = 1;
151901      }
151902    }
151903  
151904    return rc;
151905  }
151906  
151907  
151908  /*
151909  ** The phrase iterator passed as the second argument:
151910  **
151911  **   * features at least one token that uses an incremental doclist, and 
151912  **
151913  **   * does not contain any deferred tokens.
151914  **
151915  ** Advance it to the next matching documnent in the database and populate
151916  ** the Fts3Doclist.pList and nList fields. 
151917  **
151918  ** If there is no "next" entry and no error occurs, then *pbEof is set to
151919  ** 1 before returning. Otherwise, if no error occurs and the iterator is
151920  ** successfully advanced, *pbEof is set to 0.
151921  **
151922  ** If an error occurs, return an SQLite error code. Otherwise, return 
151923  ** SQLITE_OK.
151924  */
151925  static int fts3EvalIncrPhraseNext(
151926    Fts3Cursor *pCsr,               /* FTS Cursor handle */
151927    Fts3Phrase *p,                  /* Phrase object to advance to next docid */
151928    u8 *pbEof                       /* OUT: Set to 1 if EOF */
151929  ){
151930    int rc = SQLITE_OK;
151931    Fts3Doclist *pDL = &p->doclist;
151932    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
151933    u8 bEof = 0;
151934  
151935    /* This is only called if it is guaranteed that the phrase has at least
151936    ** one incremental token. In which case the bIncr flag is set. */
151937    assert( p->bIncr==1 );
151938  
151939    if( p->nToken==1 ){
151940      rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, 
151941          &pDL->iDocid, &pDL->pList, &pDL->nList
151942      );
151943      if( pDL->pList==0 ) bEof = 1;
151944    }else{
151945      int bDescDoclist = pCsr->bDesc;
151946      struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
151947  
151948      memset(a, 0, sizeof(a));
151949      assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
151950      assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
151951  
151952      while( bEof==0 ){
151953        int bMaxSet = 0;
151954        sqlite3_int64 iMax = 0;     /* Largest docid for all iterators */
151955        int i;                      /* Used to iterate through tokens */
151956  
151957        /* Advance the iterator for each token in the phrase once. */
151958        for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
151959          rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
151960          if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
151961            iMax = a[i].iDocid;
151962            bMaxSet = 1;
151963          }
151964        }
151965        assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
151966        assert( rc!=SQLITE_OK || bMaxSet );
151967  
151968        /* Keep advancing iterators until they all point to the same document */
151969        for(i=0; i<p->nToken; i++){
151970          while( rc==SQLITE_OK && bEof==0 
151971              && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0 
151972          ){
151973            rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
151974            if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
151975              iMax = a[i].iDocid;
151976              i = 0;
151977            }
151978          }
151979        }
151980  
151981        /* Check if the current entries really are a phrase match */
151982        if( bEof==0 ){
151983          int nList = 0;
151984          int nByte = a[p->nToken-1].nList;
151985          char *aDoclist = sqlite3_malloc(nByte+1);
151986          if( !aDoclist ) return SQLITE_NOMEM;
151987          memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
151988  
151989          for(i=0; i<(p->nToken-1); i++){
151990            if( a[i].bIgnore==0 ){
151991              char *pL = a[i].pList;
151992              char *pR = aDoclist;
151993              char *pOut = aDoclist;
151994              int nDist = p->nToken-1-i;
151995              int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
151996              if( res==0 ) break;
151997              nList = (int)(pOut - aDoclist);
151998            }
151999          }
152000          if( i==(p->nToken-1) ){
152001            pDL->iDocid = iMax;
152002            pDL->pList = aDoclist;
152003            pDL->nList = nList;
152004            pDL->bFreeList = 1;
152005            break;
152006          }
152007          sqlite3_free(aDoclist);
152008        }
152009      }
152010    }
152011  
152012    *pbEof = bEof;
152013    return rc;
152014  }
152015  
152016  /*
152017  ** Attempt to move the phrase iterator to point to the next matching docid. 
152018  ** If an error occurs, return an SQLite error code. Otherwise, return 
152019  ** SQLITE_OK.
152020  **
152021  ** If there is no "next" entry and no error occurs, then *pbEof is set to
152022  ** 1 before returning. Otherwise, if no error occurs and the iterator is
152023  ** successfully advanced, *pbEof is set to 0.
152024  */
152025  static int fts3EvalPhraseNext(
152026    Fts3Cursor *pCsr,               /* FTS Cursor handle */
152027    Fts3Phrase *p,                  /* Phrase object to advance to next docid */
152028    u8 *pbEof                       /* OUT: Set to 1 if EOF */
152029  ){
152030    int rc = SQLITE_OK;
152031    Fts3Doclist *pDL = &p->doclist;
152032    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
152033  
152034    if( p->bIncr ){
152035      rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
152036    }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
152037      sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, 
152038          &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
152039      );
152040      pDL->pList = pDL->pNextDocid;
152041    }else{
152042      fts3EvalDlPhraseNext(pTab, pDL, pbEof);
152043    }
152044  
152045    return rc;
152046  }
152047  
152048  /*
152049  **
152050  ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
152051  ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
152052  ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
152053  ** expressions for which all descendent tokens are deferred.
152054  **
152055  ** If parameter bOptOk is zero, then it is guaranteed that the
152056  ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
152057  ** each phrase in the expression (subject to deferred token processing).
152058  ** Or, if bOptOk is non-zero, then one or more tokens within the expression
152059  ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
152060  **
152061  ** If an error occurs within this function, *pRc is set to an SQLite error
152062  ** code before returning.
152063  */
152064  static void fts3EvalStartReaders(
152065    Fts3Cursor *pCsr,               /* FTS Cursor handle */
152066    Fts3Expr *pExpr,                /* Expression to initialize phrases in */
152067    int *pRc                        /* IN/OUT: Error code */
152068  ){
152069    if( pExpr && SQLITE_OK==*pRc ){
152070      if( pExpr->eType==FTSQUERY_PHRASE ){
152071        int nToken = pExpr->pPhrase->nToken;
152072        if( nToken ){
152073          int i;
152074          for(i=0; i<nToken; i++){
152075            if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
152076          }
152077          pExpr->bDeferred = (i==nToken);
152078        }
152079        *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
152080      }else{
152081        fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
152082        fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
152083        pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
152084      }
152085    }
152086  }
152087  
152088  /*
152089  ** An array of the following structures is assembled as part of the process
152090  ** of selecting tokens to defer before the query starts executing (as part
152091  ** of the xFilter() method). There is one element in the array for each
152092  ** token in the FTS expression.
152093  **
152094  ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
152095  ** to phrases that are connected only by AND and NEAR operators (not OR or
152096  ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
152097  ** separately. The root of a tokens AND/NEAR cluster is stored in 
152098  ** Fts3TokenAndCost.pRoot.
152099  */
152100  typedef struct Fts3TokenAndCost Fts3TokenAndCost;
152101  struct Fts3TokenAndCost {
152102    Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
152103    int iToken;                     /* Position of token in phrase */
152104    Fts3PhraseToken *pToken;        /* The token itself */
152105    Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
152106    int nOvfl;                      /* Number of overflow pages to load doclist */
152107    int iCol;                       /* The column the token must match */
152108  };
152109  
152110  /*
152111  ** This function is used to populate an allocated Fts3TokenAndCost array.
152112  **
152113  ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
152114  ** Otherwise, if an error occurs during execution, *pRc is set to an
152115  ** SQLite error code.
152116  */
152117  static void fts3EvalTokenCosts(
152118    Fts3Cursor *pCsr,               /* FTS Cursor handle */
152119    Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
152120    Fts3Expr *pExpr,                /* Expression to consider */
152121    Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
152122    Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
152123    int *pRc                        /* IN/OUT: Error code */
152124  ){
152125    if( *pRc==SQLITE_OK ){
152126      if( pExpr->eType==FTSQUERY_PHRASE ){
152127        Fts3Phrase *pPhrase = pExpr->pPhrase;
152128        int i;
152129        for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
152130          Fts3TokenAndCost *pTC = (*ppTC)++;
152131          pTC->pPhrase = pPhrase;
152132          pTC->iToken = i;
152133          pTC->pRoot = pRoot;
152134          pTC->pToken = &pPhrase->aToken[i];
152135          pTC->iCol = pPhrase->iColumn;
152136          *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
152137        }
152138      }else if( pExpr->eType!=FTSQUERY_NOT ){
152139        assert( pExpr->eType==FTSQUERY_OR
152140             || pExpr->eType==FTSQUERY_AND
152141             || pExpr->eType==FTSQUERY_NEAR
152142        );
152143        assert( pExpr->pLeft && pExpr->pRight );
152144        if( pExpr->eType==FTSQUERY_OR ){
152145          pRoot = pExpr->pLeft;
152146          **ppOr = pRoot;
152147          (*ppOr)++;
152148        }
152149        fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
152150        if( pExpr->eType==FTSQUERY_OR ){
152151          pRoot = pExpr->pRight;
152152          **ppOr = pRoot;
152153          (*ppOr)++;
152154        }
152155        fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
152156      }
152157    }
152158  }
152159  
152160  /*
152161  ** Determine the average document (row) size in pages. If successful,
152162  ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
152163  ** an SQLite error code.
152164  **
152165  ** The average document size in pages is calculated by first calculating 
152166  ** determining the average size in bytes, B. If B is less than the amount
152167  ** of data that will fit on a single leaf page of an intkey table in
152168  ** this database, then the average docsize is 1. Otherwise, it is 1 plus
152169  ** the number of overflow pages consumed by a record B bytes in size.
152170  */
152171  static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
152172    int rc = SQLITE_OK;
152173    if( pCsr->nRowAvg==0 ){
152174      /* The average document size, which is required to calculate the cost
152175      ** of each doclist, has not yet been determined. Read the required 
152176      ** data from the %_stat table to calculate it.
152177      **
152178      ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 
152179      ** varints, where nCol is the number of columns in the FTS3 table.
152180      ** The first varint is the number of documents currently stored in
152181      ** the table. The following nCol varints contain the total amount of
152182      ** data stored in all rows of each column of the table, from left
152183      ** to right.
152184      */
152185      Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
152186      sqlite3_stmt *pStmt;
152187      sqlite3_int64 nDoc = 0;
152188      sqlite3_int64 nByte = 0;
152189      const char *pEnd;
152190      const char *a;
152191  
152192      rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
152193      if( rc!=SQLITE_OK ) return rc;
152194      a = sqlite3_column_blob(pStmt, 0);
152195      assert( a );
152196  
152197      pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
152198      a += sqlite3Fts3GetVarint(a, &nDoc);
152199      while( a<pEnd ){
152200        a += sqlite3Fts3GetVarint(a, &nByte);
152201      }
152202      if( nDoc==0 || nByte==0 ){
152203        sqlite3_reset(pStmt);
152204        return FTS_CORRUPT_VTAB;
152205      }
152206  
152207      pCsr->nDoc = nDoc;
152208      pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
152209      assert( pCsr->nRowAvg>0 ); 
152210      rc = sqlite3_reset(pStmt);
152211    }
152212  
152213    *pnPage = pCsr->nRowAvg;
152214    return rc;
152215  }
152216  
152217  /*
152218  ** This function is called to select the tokens (if any) that will be 
152219  ** deferred. The array aTC[] has already been populated when this is
152220  ** called.
152221  **
152222  ** This function is called once for each AND/NEAR cluster in the 
152223  ** expression. Each invocation determines which tokens to defer within
152224  ** the cluster with root node pRoot. See comments above the definition
152225  ** of struct Fts3TokenAndCost for more details.
152226  **
152227  ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
152228  ** called on each token to defer. Otherwise, an SQLite error code is
152229  ** returned.
152230  */
152231  static int fts3EvalSelectDeferred(
152232    Fts3Cursor *pCsr,               /* FTS Cursor handle */
152233    Fts3Expr *pRoot,                /* Consider tokens with this root node */
152234    Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
152235    int nTC                         /* Number of entries in aTC[] */
152236  ){
152237    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
152238    int nDocSize = 0;               /* Number of pages per doc loaded */
152239    int rc = SQLITE_OK;             /* Return code */
152240    int ii;                         /* Iterator variable for various purposes */
152241    int nOvfl = 0;                  /* Total overflow pages used by doclists */
152242    int nToken = 0;                 /* Total number of tokens in cluster */
152243  
152244    int nMinEst = 0;                /* The minimum count for any phrase so far. */
152245    int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
152246  
152247    /* Tokens are never deferred for FTS tables created using the content=xxx
152248    ** option. The reason being that it is not guaranteed that the content
152249    ** table actually contains the same data as the index. To prevent this from
152250    ** causing any problems, the deferred token optimization is completely
152251    ** disabled for content=xxx tables. */
152252    if( pTab->zContentTbl ){
152253      return SQLITE_OK;
152254    }
152255  
152256    /* Count the tokens in this AND/NEAR cluster. If none of the doclists
152257    ** associated with the tokens spill onto overflow pages, or if there is
152258    ** only 1 token, exit early. No tokens to defer in this case. */
152259    for(ii=0; ii<nTC; ii++){
152260      if( aTC[ii].pRoot==pRoot ){
152261        nOvfl += aTC[ii].nOvfl;
152262        nToken++;
152263      }
152264    }
152265    if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
152266  
152267    /* Obtain the average docsize (in pages). */
152268    rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
152269    assert( rc!=SQLITE_OK || nDocSize>0 );
152270  
152271  
152272    /* Iterate through all tokens in this AND/NEAR cluster, in ascending order 
152273    ** of the number of overflow pages that will be loaded by the pager layer 
152274    ** to retrieve the entire doclist for the token from the full-text index.
152275    ** Load the doclists for tokens that are either:
152276    **
152277    **   a. The cheapest token in the entire query (i.e. the one visited by the
152278    **      first iteration of this loop), or
152279    **
152280    **   b. Part of a multi-token phrase.
152281    **
152282    ** After each token doclist is loaded, merge it with the others from the
152283    ** same phrase and count the number of documents that the merged doclist
152284    ** contains. Set variable "nMinEst" to the smallest number of documents in 
152285    ** any phrase doclist for which 1 or more token doclists have been loaded.
152286    ** Let nOther be the number of other phrases for which it is certain that
152287    ** one or more tokens will not be deferred.
152288    **
152289    ** Then, for each token, defer it if loading the doclist would result in
152290    ** loading N or more overflow pages into memory, where N is computed as:
152291    **
152292    **    (nMinEst + 4^nOther - 1) / (4^nOther)
152293    */
152294    for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
152295      int iTC;                      /* Used to iterate through aTC[] array. */
152296      Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
152297  
152298      /* Set pTC to point to the cheapest remaining token. */
152299      for(iTC=0; iTC<nTC; iTC++){
152300        if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot 
152301         && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl) 
152302        ){
152303          pTC = &aTC[iTC];
152304        }
152305      }
152306      assert( pTC );
152307  
152308      if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
152309        /* The number of overflow pages to load for this (and therefore all
152310        ** subsequent) tokens is greater than the estimated number of pages 
152311        ** that will be loaded if all subsequent tokens are deferred.
152312        */
152313        Fts3PhraseToken *pToken = pTC->pToken;
152314        rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
152315        fts3SegReaderCursorFree(pToken->pSegcsr);
152316        pToken->pSegcsr = 0;
152317      }else{
152318        /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
152319        ** for-loop. Except, limit the value to 2^24 to prevent it from 
152320        ** overflowing the 32-bit integer it is stored in. */
152321        if( ii<12 ) nLoad4 = nLoad4*4;
152322  
152323        if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
152324          /* Either this is the cheapest token in the entire query, or it is
152325          ** part of a multi-token phrase. Either way, the entire doclist will
152326          ** (eventually) be loaded into memory. It may as well be now. */
152327          Fts3PhraseToken *pToken = pTC->pToken;
152328          int nList = 0;
152329          char *pList = 0;
152330          rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
152331          assert( rc==SQLITE_OK || pList==0 );
152332          if( rc==SQLITE_OK ){
152333            rc = fts3EvalPhraseMergeToken(
152334                pTab, pTC->pPhrase, pTC->iToken,pList,nList
152335            );
152336          }
152337          if( rc==SQLITE_OK ){
152338            int nCount;
152339            nCount = fts3DoclistCountDocids(
152340                pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
152341            );
152342            if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
152343          }
152344        }
152345      }
152346      pTC->pToken = 0;
152347    }
152348  
152349    return rc;
152350  }
152351  
152352  /*
152353  ** This function is called from within the xFilter method. It initializes
152354  ** the full-text query currently stored in pCsr->pExpr. To iterate through
152355  ** the results of a query, the caller does:
152356  **
152357  **    fts3EvalStart(pCsr);
152358  **    while( 1 ){
152359  **      fts3EvalNext(pCsr);
152360  **      if( pCsr->bEof ) break;
152361  **      ... return row pCsr->iPrevId to the caller ...
152362  **    }
152363  */
152364  static int fts3EvalStart(Fts3Cursor *pCsr){
152365    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
152366    int rc = SQLITE_OK;
152367    int nToken = 0;
152368    int nOr = 0;
152369  
152370    /* Allocate a MultiSegReader for each token in the expression. */
152371    fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
152372  
152373    /* Determine which, if any, tokens in the expression should be deferred. */
152374  #ifndef SQLITE_DISABLE_FTS4_DEFERRED
152375    if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
152376      Fts3TokenAndCost *aTC;
152377      Fts3Expr **apOr;
152378      aTC = (Fts3TokenAndCost *)sqlite3_malloc(
152379          sizeof(Fts3TokenAndCost) * nToken
152380        + sizeof(Fts3Expr *) * nOr * 2
152381      );
152382      apOr = (Fts3Expr **)&aTC[nToken];
152383  
152384      if( !aTC ){
152385        rc = SQLITE_NOMEM;
152386      }else{
152387        int ii;
152388        Fts3TokenAndCost *pTC = aTC;
152389        Fts3Expr **ppOr = apOr;
152390  
152391        fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
152392        nToken = (int)(pTC-aTC);
152393        nOr = (int)(ppOr-apOr);
152394  
152395        if( rc==SQLITE_OK ){
152396          rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
152397          for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
152398            rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
152399          }
152400        }
152401  
152402        sqlite3_free(aTC);
152403      }
152404    }
152405  #endif
152406  
152407    fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
152408    return rc;
152409  }
152410  
152411  /*
152412  ** Invalidate the current position list for phrase pPhrase.
152413  */
152414  static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
152415    if( pPhrase->doclist.bFreeList ){
152416      sqlite3_free(pPhrase->doclist.pList);
152417    }
152418    pPhrase->doclist.pList = 0;
152419    pPhrase->doclist.nList = 0;
152420    pPhrase->doclist.bFreeList = 0;
152421  }
152422  
152423  /*
152424  ** This function is called to edit the position list associated with
152425  ** the phrase object passed as the fifth argument according to a NEAR
152426  ** condition. For example:
152427  **
152428  **     abc NEAR/5 "def ghi"
152429  **
152430  ** Parameter nNear is passed the NEAR distance of the expression (5 in
152431  ** the example above). When this function is called, *paPoslist points to
152432  ** the position list, and *pnToken is the number of phrase tokens in, the
152433  ** phrase on the other side of the NEAR operator to pPhrase. For example,
152434  ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
152435  ** the position list associated with phrase "abc".
152436  **
152437  ** All positions in the pPhrase position list that are not sufficiently
152438  ** close to a position in the *paPoslist position list are removed. If this
152439  ** leaves 0 positions, zero is returned. Otherwise, non-zero.
152440  **
152441  ** Before returning, *paPoslist is set to point to the position lsit 
152442  ** associated with pPhrase. And *pnToken is set to the number of tokens in
152443  ** pPhrase.
152444  */
152445  static int fts3EvalNearTrim(
152446    int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
152447    char *aTmp,                     /* Temporary space to use */
152448    char **paPoslist,               /* IN/OUT: Position list */
152449    int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
152450    Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
152451  ){
152452    int nParam1 = nNear + pPhrase->nToken;
152453    int nParam2 = nNear + *pnToken;
152454    int nNew;
152455    char *p2; 
152456    char *pOut; 
152457    int res;
152458  
152459    assert( pPhrase->doclist.pList );
152460  
152461    p2 = pOut = pPhrase->doclist.pList;
152462    res = fts3PoslistNearMerge(
152463      &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
152464    );
152465    if( res ){
152466      nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
152467      assert( pPhrase->doclist.pList[nNew]=='\0' );
152468      assert( nNew<=pPhrase->doclist.nList && nNew>0 );
152469      memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
152470      pPhrase->doclist.nList = nNew;
152471      *paPoslist = pPhrase->doclist.pList;
152472      *pnToken = pPhrase->nToken;
152473    }
152474  
152475    return res;
152476  }
152477  
152478  /*
152479  ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
152480  ** Otherwise, it advances the expression passed as the second argument to
152481  ** point to the next matching row in the database. Expressions iterate through
152482  ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
152483  ** or descending if it is non-zero.
152484  **
152485  ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
152486  ** successful, the following variables in pExpr are set:
152487  **
152488  **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
152489  **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
152490  **
152491  ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
152492  ** at EOF, then the following variables are populated with the position list
152493  ** for the phrase for the visited row:
152494  **
152495  **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
152496  **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
152497  **
152498  ** It says above that this function advances the expression to the next
152499  ** matching row. This is usually true, but there are the following exceptions:
152500  **
152501  **   1. Deferred tokens are not taken into account. If a phrase consists
152502  **      entirely of deferred tokens, it is assumed to match every row in
152503  **      the db. In this case the position-list is not populated at all. 
152504  **
152505  **      Or, if a phrase contains one or more deferred tokens and one or
152506  **      more non-deferred tokens, then the expression is advanced to the 
152507  **      next possible match, considering only non-deferred tokens. In other
152508  **      words, if the phrase is "A B C", and "B" is deferred, the expression
152509  **      is advanced to the next row that contains an instance of "A * C", 
152510  **      where "*" may match any single token. The position list in this case
152511  **      is populated as for "A * C" before returning.
152512  **
152513  **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is 
152514  **      advanced to point to the next row that matches "x AND y".
152515  ** 
152516  ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
152517  ** really a match, taking into account deferred tokens and NEAR operators.
152518  */
152519  static void fts3EvalNextRow(
152520    Fts3Cursor *pCsr,               /* FTS Cursor handle */
152521    Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
152522    int *pRc                        /* IN/OUT: Error code */
152523  ){
152524    if( *pRc==SQLITE_OK ){
152525      int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
152526      assert( pExpr->bEof==0 );
152527      pExpr->bStart = 1;
152528  
152529      switch( pExpr->eType ){
152530        case FTSQUERY_NEAR:
152531        case FTSQUERY_AND: {
152532          Fts3Expr *pLeft = pExpr->pLeft;
152533          Fts3Expr *pRight = pExpr->pRight;
152534          assert( !pLeft->bDeferred || !pRight->bDeferred );
152535  
152536          if( pLeft->bDeferred ){
152537            /* LHS is entirely deferred. So we assume it matches every row.
152538            ** Advance the RHS iterator to find the next row visited. */
152539            fts3EvalNextRow(pCsr, pRight, pRc);
152540            pExpr->iDocid = pRight->iDocid;
152541            pExpr->bEof = pRight->bEof;
152542          }else if( pRight->bDeferred ){
152543            /* RHS is entirely deferred. So we assume it matches every row.
152544            ** Advance the LHS iterator to find the next row visited. */
152545            fts3EvalNextRow(pCsr, pLeft, pRc);
152546            pExpr->iDocid = pLeft->iDocid;
152547            pExpr->bEof = pLeft->bEof;
152548          }else{
152549            /* Neither the RHS or LHS are deferred. */
152550            fts3EvalNextRow(pCsr, pLeft, pRc);
152551            fts3EvalNextRow(pCsr, pRight, pRc);
152552            while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
152553              sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
152554              if( iDiff==0 ) break;
152555              if( iDiff<0 ){
152556                fts3EvalNextRow(pCsr, pLeft, pRc);
152557              }else{
152558                fts3EvalNextRow(pCsr, pRight, pRc);
152559              }
152560            }
152561            pExpr->iDocid = pLeft->iDocid;
152562            pExpr->bEof = (pLeft->bEof || pRight->bEof);
152563            if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
152564              assert( pRight->eType==FTSQUERY_PHRASE );
152565              if( pRight->pPhrase->doclist.aAll ){
152566                Fts3Doclist *pDl = &pRight->pPhrase->doclist;
152567                while( *pRc==SQLITE_OK && pRight->bEof==0 ){
152568                  memset(pDl->pList, 0, pDl->nList);
152569                  fts3EvalNextRow(pCsr, pRight, pRc);
152570                }
152571              }
152572              if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
152573                Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
152574                while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
152575                  memset(pDl->pList, 0, pDl->nList);
152576                  fts3EvalNextRow(pCsr, pLeft, pRc);
152577                }
152578              }
152579            }
152580          }
152581          break;
152582        }
152583    
152584        case FTSQUERY_OR: {
152585          Fts3Expr *pLeft = pExpr->pLeft;
152586          Fts3Expr *pRight = pExpr->pRight;
152587          sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
152588  
152589          assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
152590          assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
152591  
152592          if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
152593            fts3EvalNextRow(pCsr, pLeft, pRc);
152594          }else if( pLeft->bEof || iCmp>0 ){
152595            fts3EvalNextRow(pCsr, pRight, pRc);
152596          }else{
152597            fts3EvalNextRow(pCsr, pLeft, pRc);
152598            fts3EvalNextRow(pCsr, pRight, pRc);
152599          }
152600  
152601          pExpr->bEof = (pLeft->bEof && pRight->bEof);
152602          iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
152603          if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
152604            pExpr->iDocid = pLeft->iDocid;
152605          }else{
152606            pExpr->iDocid = pRight->iDocid;
152607          }
152608  
152609          break;
152610        }
152611  
152612        case FTSQUERY_NOT: {
152613          Fts3Expr *pLeft = pExpr->pLeft;
152614          Fts3Expr *pRight = pExpr->pRight;
152615  
152616          if( pRight->bStart==0 ){
152617            fts3EvalNextRow(pCsr, pRight, pRc);
152618            assert( *pRc!=SQLITE_OK || pRight->bStart );
152619          }
152620  
152621          fts3EvalNextRow(pCsr, pLeft, pRc);
152622          if( pLeft->bEof==0 ){
152623            while( !*pRc 
152624                && !pRight->bEof 
152625                && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 
152626            ){
152627              fts3EvalNextRow(pCsr, pRight, pRc);
152628            }
152629          }
152630          pExpr->iDocid = pLeft->iDocid;
152631          pExpr->bEof = pLeft->bEof;
152632          break;
152633        }
152634  
152635        default: {
152636          Fts3Phrase *pPhrase = pExpr->pPhrase;
152637          fts3EvalInvalidatePoslist(pPhrase);
152638          *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
152639          pExpr->iDocid = pPhrase->doclist.iDocid;
152640          break;
152641        }
152642      }
152643    }
152644  }
152645  
152646  /*
152647  ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
152648  ** cluster, then this function returns 1 immediately.
152649  **
152650  ** Otherwise, it checks if the current row really does match the NEAR 
152651  ** expression, using the data currently stored in the position lists 
152652  ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression. 
152653  **
152654  ** If the current row is a match, the position list associated with each
152655  ** phrase in the NEAR expression is edited in place to contain only those
152656  ** phrase instances sufficiently close to their peers to satisfy all NEAR
152657  ** constraints. In this case it returns 1. If the NEAR expression does not 
152658  ** match the current row, 0 is returned. The position lists may or may not
152659  ** be edited if 0 is returned.
152660  */
152661  static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
152662    int res = 1;
152663  
152664    /* The following block runs if pExpr is the root of a NEAR query.
152665    ** For example, the query:
152666    **
152667    **         "w" NEAR "x" NEAR "y" NEAR "z"
152668    **
152669    ** which is represented in tree form as:
152670    **
152671    **                               |
152672    **                          +--NEAR--+      <-- root of NEAR query
152673    **                          |        |
152674    **                     +--NEAR--+   "z"
152675    **                     |        |
152676    **                +--NEAR--+   "y"
152677    **                |        |
152678    **               "w"      "x"
152679    **
152680    ** The right-hand child of a NEAR node is always a phrase. The 
152681    ** left-hand child may be either a phrase or a NEAR node. There are
152682    ** no exceptions to this - it's the way the parser in fts3_expr.c works.
152683    */
152684    if( *pRc==SQLITE_OK 
152685     && pExpr->eType==FTSQUERY_NEAR 
152686     && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
152687    ){
152688      Fts3Expr *p; 
152689      int nTmp = 0;                 /* Bytes of temp space */
152690      char *aTmp;                   /* Temp space for PoslistNearMerge() */
152691  
152692      /* Allocate temporary working space. */
152693      for(p=pExpr; p->pLeft; p=p->pLeft){
152694        assert( p->pRight->pPhrase->doclist.nList>0 );
152695        nTmp += p->pRight->pPhrase->doclist.nList;
152696      }
152697      nTmp += p->pPhrase->doclist.nList;
152698      aTmp = sqlite3_malloc(nTmp*2);
152699      if( !aTmp ){
152700        *pRc = SQLITE_NOMEM;
152701        res = 0;
152702      }else{
152703        char *aPoslist = p->pPhrase->doclist.pList;
152704        int nToken = p->pPhrase->nToken;
152705  
152706        for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
152707          Fts3Phrase *pPhrase = p->pRight->pPhrase;
152708          int nNear = p->nNear;
152709          res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
152710        }
152711  
152712        aPoslist = pExpr->pRight->pPhrase->doclist.pList;
152713        nToken = pExpr->pRight->pPhrase->nToken;
152714        for(p=pExpr->pLeft; p && res; p=p->pLeft){
152715          int nNear;
152716          Fts3Phrase *pPhrase;
152717          assert( p->pParent && p->pParent->pLeft==p );
152718          nNear = p->pParent->nNear;
152719          pPhrase = (
152720              p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
152721          );
152722          res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
152723        }
152724      }
152725  
152726      sqlite3_free(aTmp);
152727    }
152728  
152729    return res;
152730  }
152731  
152732  /*
152733  ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
152734  ** Assuming no error occurs or has occurred, It returns non-zero if the
152735  ** expression passed as the second argument matches the row that pCsr 
152736  ** currently points to, or zero if it does not.
152737  **
152738  ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
152739  ** If an error occurs during execution of this function, *pRc is set to 
152740  ** the appropriate SQLite error code. In this case the returned value is 
152741  ** undefined.
152742  */
152743  static int fts3EvalTestExpr(
152744    Fts3Cursor *pCsr,               /* FTS cursor handle */
152745    Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
152746    int *pRc                        /* IN/OUT: Error code */
152747  ){
152748    int bHit = 1;                   /* Return value */
152749    if( *pRc==SQLITE_OK ){
152750      switch( pExpr->eType ){
152751        case FTSQUERY_NEAR:
152752        case FTSQUERY_AND:
152753          bHit = (
152754              fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
152755           && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
152756           && fts3EvalNearTest(pExpr, pRc)
152757          );
152758  
152759          /* If the NEAR expression does not match any rows, zero the doclist for 
152760          ** all phrases involved in the NEAR. This is because the snippet(),
152761          ** offsets() and matchinfo() functions are not supposed to recognize 
152762          ** any instances of phrases that are part of unmatched NEAR queries. 
152763          ** For example if this expression:
152764          **
152765          **    ... MATCH 'a OR (b NEAR c)'
152766          **
152767          ** is matched against a row containing:
152768          **
152769          **        'a b d e'
152770          **
152771          ** then any snippet() should ony highlight the "a" term, not the "b"
152772          ** (as "b" is part of a non-matching NEAR clause).
152773          */
152774          if( bHit==0 
152775           && pExpr->eType==FTSQUERY_NEAR 
152776           && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
152777          ){
152778            Fts3Expr *p;
152779            for(p=pExpr; p->pPhrase==0; p=p->pLeft){
152780              if( p->pRight->iDocid==pCsr->iPrevId ){
152781                fts3EvalInvalidatePoslist(p->pRight->pPhrase);
152782              }
152783            }
152784            if( p->iDocid==pCsr->iPrevId ){
152785              fts3EvalInvalidatePoslist(p->pPhrase);
152786            }
152787          }
152788  
152789          break;
152790  
152791        case FTSQUERY_OR: {
152792          int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
152793          int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
152794          bHit = bHit1 || bHit2;
152795          break;
152796        }
152797  
152798        case FTSQUERY_NOT:
152799          bHit = (
152800              fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
152801           && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
152802          );
152803          break;
152804  
152805        default: {
152806  #ifndef SQLITE_DISABLE_FTS4_DEFERRED
152807          if( pCsr->pDeferred 
152808           && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
152809          ){
152810            Fts3Phrase *pPhrase = pExpr->pPhrase;
152811            assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
152812            if( pExpr->bDeferred ){
152813              fts3EvalInvalidatePoslist(pPhrase);
152814            }
152815            *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
152816            bHit = (pPhrase->doclist.pList!=0);
152817            pExpr->iDocid = pCsr->iPrevId;
152818          }else
152819  #endif
152820          {
152821            bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
152822          }
152823          break;
152824        }
152825      }
152826    }
152827    return bHit;
152828  }
152829  
152830  /*
152831  ** This function is called as the second part of each xNext operation when
152832  ** iterating through the results of a full-text query. At this point the
152833  ** cursor points to a row that matches the query expression, with the
152834  ** following caveats:
152835  **
152836  **   * Up until this point, "NEAR" operators in the expression have been
152837  **     treated as "AND".
152838  **
152839  **   * Deferred tokens have not yet been considered.
152840  **
152841  ** If *pRc is not SQLITE_OK when this function is called, it immediately
152842  ** returns 0. Otherwise, it tests whether or not after considering NEAR
152843  ** operators and deferred tokens the current row is still a match for the
152844  ** expression. It returns 1 if both of the following are true:
152845  **
152846  **   1. *pRc is SQLITE_OK when this function returns, and
152847  **
152848  **   2. After scanning the current FTS table row for the deferred tokens,
152849  **      it is determined that the row does *not* match the query.
152850  **
152851  ** Or, if no error occurs and it seems the current row does match the FTS
152852  ** query, return 0.
152853  */
152854  SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
152855    int rc = *pRc;
152856    int bMiss = 0;
152857    if( rc==SQLITE_OK ){
152858  
152859      /* If there are one or more deferred tokens, load the current row into
152860      ** memory and scan it to determine the position list for each deferred
152861      ** token. Then, see if this row is really a match, considering deferred
152862      ** tokens and NEAR operators (neither of which were taken into account
152863      ** earlier, by fts3EvalNextRow()). 
152864      */
152865      if( pCsr->pDeferred ){
152866        rc = fts3CursorSeek(0, pCsr);
152867        if( rc==SQLITE_OK ){
152868          rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
152869        }
152870      }
152871      bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
152872  
152873      /* Free the position-lists accumulated for each deferred token above. */
152874      sqlite3Fts3FreeDeferredDoclists(pCsr);
152875      *pRc = rc;
152876    }
152877    return (rc==SQLITE_OK && bMiss);
152878  }
152879  
152880  /*
152881  ** Advance to the next document that matches the FTS expression in
152882  ** Fts3Cursor.pExpr.
152883  */
152884  static int fts3EvalNext(Fts3Cursor *pCsr){
152885    int rc = SQLITE_OK;             /* Return Code */
152886    Fts3Expr *pExpr = pCsr->pExpr;
152887    assert( pCsr->isEof==0 );
152888    if( pExpr==0 ){
152889      pCsr->isEof = 1;
152890    }else{
152891      do {
152892        if( pCsr->isRequireSeek==0 ){
152893          sqlite3_reset(pCsr->pStmt);
152894        }
152895        assert( sqlite3_data_count(pCsr->pStmt)==0 );
152896        fts3EvalNextRow(pCsr, pExpr, &rc);
152897        pCsr->isEof = pExpr->bEof;
152898        pCsr->isRequireSeek = 1;
152899        pCsr->isMatchinfoNeeded = 1;
152900        pCsr->iPrevId = pExpr->iDocid;
152901      }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
152902    }
152903  
152904    /* Check if the cursor is past the end of the docid range specified
152905    ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag.  */
152906    if( rc==SQLITE_OK && (
152907          (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
152908       || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
152909    )){
152910      pCsr->isEof = 1;
152911    }
152912  
152913    return rc;
152914  }
152915  
152916  /*
152917  ** Restart interation for expression pExpr so that the next call to
152918  ** fts3EvalNext() visits the first row. Do not allow incremental 
152919  ** loading or merging of phrase doclists for this iteration.
152920  **
152921  ** If *pRc is other than SQLITE_OK when this function is called, it is
152922  ** a no-op. If an error occurs within this function, *pRc is set to an
152923  ** SQLite error code before returning.
152924  */
152925  static void fts3EvalRestart(
152926    Fts3Cursor *pCsr,
152927    Fts3Expr *pExpr,
152928    int *pRc
152929  ){
152930    if( pExpr && *pRc==SQLITE_OK ){
152931      Fts3Phrase *pPhrase = pExpr->pPhrase;
152932  
152933      if( pPhrase ){
152934        fts3EvalInvalidatePoslist(pPhrase);
152935        if( pPhrase->bIncr ){
152936          int i;
152937          for(i=0; i<pPhrase->nToken; i++){
152938            Fts3PhraseToken *pToken = &pPhrase->aToken[i];
152939            assert( pToken->pDeferred==0 );
152940            if( pToken->pSegcsr ){
152941              sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
152942            }
152943          }
152944          *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
152945        }
152946        pPhrase->doclist.pNextDocid = 0;
152947        pPhrase->doclist.iDocid = 0;
152948        pPhrase->pOrPoslist = 0;
152949      }
152950  
152951      pExpr->iDocid = 0;
152952      pExpr->bEof = 0;
152953      pExpr->bStart = 0;
152954  
152955      fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
152956      fts3EvalRestart(pCsr, pExpr->pRight, pRc);
152957    }
152958  }
152959  
152960  /*
152961  ** After allocating the Fts3Expr.aMI[] array for each phrase in the 
152962  ** expression rooted at pExpr, the cursor iterates through all rows matched
152963  ** by pExpr, calling this function for each row. This function increments
152964  ** the values in Fts3Expr.aMI[] according to the position-list currently
152965  ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase 
152966  ** expression nodes.
152967  */
152968  static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
152969    if( pExpr ){
152970      Fts3Phrase *pPhrase = pExpr->pPhrase;
152971      if( pPhrase && pPhrase->doclist.pList ){
152972        int iCol = 0;
152973        char *p = pPhrase->doclist.pList;
152974  
152975        assert( *p );
152976        while( 1 ){
152977          u8 c = 0;
152978          int iCnt = 0;
152979          while( 0xFE & (*p | c) ){
152980            if( (c&0x80)==0 ) iCnt++;
152981            c = *p++ & 0x80;
152982          }
152983  
152984          /* aMI[iCol*3 + 1] = Number of occurrences
152985          ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
152986          */
152987          pExpr->aMI[iCol*3 + 1] += iCnt;
152988          pExpr->aMI[iCol*3 + 2] += (iCnt>0);
152989          if( *p==0x00 ) break;
152990          p++;
152991          p += fts3GetVarint32(p, &iCol);
152992        }
152993      }
152994  
152995      fts3EvalUpdateCounts(pExpr->pLeft);
152996      fts3EvalUpdateCounts(pExpr->pRight);
152997    }
152998  }
152999  
153000  /*
153001  ** Expression pExpr must be of type FTSQUERY_PHRASE.
153002  **
153003  ** If it is not already allocated and populated, this function allocates and
153004  ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
153005  ** of a NEAR expression, then it also allocates and populates the same array
153006  ** for all other phrases that are part of the NEAR expression.
153007  **
153008  ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
153009  ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
153010  */
153011  static int fts3EvalGatherStats(
153012    Fts3Cursor *pCsr,               /* Cursor object */
153013    Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
153014  ){
153015    int rc = SQLITE_OK;             /* Return code */
153016  
153017    assert( pExpr->eType==FTSQUERY_PHRASE );
153018    if( pExpr->aMI==0 ){
153019      Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
153020      Fts3Expr *pRoot;                /* Root of NEAR expression */
153021      Fts3Expr *p;                    /* Iterator used for several purposes */
153022  
153023      sqlite3_int64 iPrevId = pCsr->iPrevId;
153024      sqlite3_int64 iDocid;
153025      u8 bEof;
153026  
153027      /* Find the root of the NEAR expression */
153028      pRoot = pExpr;
153029      while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
153030        pRoot = pRoot->pParent;
153031      }
153032      iDocid = pRoot->iDocid;
153033      bEof = pRoot->bEof;
153034      assert( pRoot->bStart );
153035  
153036      /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
153037      for(p=pRoot; p; p=p->pLeft){
153038        Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
153039        assert( pE->aMI==0 );
153040        pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
153041        if( !pE->aMI ) return SQLITE_NOMEM;
153042        memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
153043      }
153044  
153045      fts3EvalRestart(pCsr, pRoot, &rc);
153046  
153047      while( pCsr->isEof==0 && rc==SQLITE_OK ){
153048  
153049        do {
153050          /* Ensure the %_content statement is reset. */
153051          if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
153052          assert( sqlite3_data_count(pCsr->pStmt)==0 );
153053  
153054          /* Advance to the next document */
153055          fts3EvalNextRow(pCsr, pRoot, &rc);
153056          pCsr->isEof = pRoot->bEof;
153057          pCsr->isRequireSeek = 1;
153058          pCsr->isMatchinfoNeeded = 1;
153059          pCsr->iPrevId = pRoot->iDocid;
153060        }while( pCsr->isEof==0 
153061             && pRoot->eType==FTSQUERY_NEAR 
153062             && sqlite3Fts3EvalTestDeferred(pCsr, &rc) 
153063        );
153064  
153065        if( rc==SQLITE_OK && pCsr->isEof==0 ){
153066          fts3EvalUpdateCounts(pRoot);
153067        }
153068      }
153069  
153070      pCsr->isEof = 0;
153071      pCsr->iPrevId = iPrevId;
153072  
153073      if( bEof ){
153074        pRoot->bEof = bEof;
153075      }else{
153076        /* Caution: pRoot may iterate through docids in ascending or descending
153077        ** order. For this reason, even though it seems more defensive, the 
153078        ** do loop can not be written:
153079        **
153080        **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
153081        */
153082        fts3EvalRestart(pCsr, pRoot, &rc);
153083        do {
153084          fts3EvalNextRow(pCsr, pRoot, &rc);
153085          assert( pRoot->bEof==0 );
153086        }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
153087      }
153088    }
153089    return rc;
153090  }
153091  
153092  /*
153093  ** This function is used by the matchinfo() module to query a phrase 
153094  ** expression node for the following information:
153095  **
153096  **   1. The total number of occurrences of the phrase in each column of 
153097  **      the FTS table (considering all rows), and
153098  **
153099  **   2. For each column, the number of rows in the table for which the
153100  **      column contains at least one instance of the phrase.
153101  **
153102  ** If no error occurs, SQLITE_OK is returned and the values for each column
153103  ** written into the array aiOut as follows:
153104  **
153105  **   aiOut[iCol*3 + 1] = Number of occurrences
153106  **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
153107  **
153108  ** Caveats:
153109  **
153110  **   * If a phrase consists entirely of deferred tokens, then all output 
153111  **     values are set to the number of documents in the table. In other
153112  **     words we assume that very common tokens occur exactly once in each 
153113  **     column of each row of the table.
153114  **
153115  **   * If a phrase contains some deferred tokens (and some non-deferred 
153116  **     tokens), count the potential occurrence identified by considering
153117  **     the non-deferred tokens instead of actual phrase occurrences.
153118  **
153119  **   * If the phrase is part of a NEAR expression, then only phrase instances
153120  **     that meet the NEAR constraint are included in the counts.
153121  */
153122  SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
153123    Fts3Cursor *pCsr,               /* FTS cursor handle */
153124    Fts3Expr *pExpr,                /* Phrase expression */
153125    u32 *aiOut                      /* Array to write results into (see above) */
153126  ){
153127    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
153128    int rc = SQLITE_OK;
153129    int iCol;
153130  
153131    if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
153132      assert( pCsr->nDoc>0 );
153133      for(iCol=0; iCol<pTab->nColumn; iCol++){
153134        aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
153135        aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
153136      }
153137    }else{
153138      rc = fts3EvalGatherStats(pCsr, pExpr);
153139      if( rc==SQLITE_OK ){
153140        assert( pExpr->aMI );
153141        for(iCol=0; iCol<pTab->nColumn; iCol++){
153142          aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
153143          aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
153144        }
153145      }
153146    }
153147  
153148    return rc;
153149  }
153150  
153151  /*
153152  ** The expression pExpr passed as the second argument to this function
153153  ** must be of type FTSQUERY_PHRASE. 
153154  **
153155  ** The returned value is either NULL or a pointer to a buffer containing
153156  ** a position-list indicating the occurrences of the phrase in column iCol
153157  ** of the current row. 
153158  **
153159  ** More specifically, the returned buffer contains 1 varint for each 
153160  ** occurrence of the phrase in the column, stored using the normal (delta+2) 
153161  ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
153162  ** if the requested column contains "a b X c d X X" and the position-list
153163  ** for 'X' is requested, the buffer returned may contain:
153164  **
153165  **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
153166  **
153167  ** This function works regardless of whether or not the phrase is deferred,
153168  ** incremental, or neither.
153169  */
153170  SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
153171    Fts3Cursor *pCsr,               /* FTS3 cursor object */
153172    Fts3Expr *pExpr,                /* Phrase to return doclist for */
153173    int iCol,                       /* Column to return position list for */
153174    char **ppOut                    /* OUT: Pointer to position list */
153175  ){
153176    Fts3Phrase *pPhrase = pExpr->pPhrase;
153177    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
153178    char *pIter;
153179    int iThis;
153180    sqlite3_int64 iDocid;
153181  
153182    /* If this phrase is applies specifically to some column other than 
153183    ** column iCol, return a NULL pointer.  */
153184    *ppOut = 0;
153185    assert( iCol>=0 && iCol<pTab->nColumn );
153186    if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
153187      return SQLITE_OK;
153188    }
153189  
153190    iDocid = pExpr->iDocid;
153191    pIter = pPhrase->doclist.pList;
153192    if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
153193      int rc = SQLITE_OK;
153194      int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
153195      int bOr = 0;
153196      u8 bTreeEof = 0;
153197      Fts3Expr *p;                  /* Used to iterate from pExpr to root */
153198      Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */
153199      int bMatch;
153200  
153201      /* Check if this phrase descends from an OR expression node. If not, 
153202      ** return NULL. Otherwise, the entry that corresponds to docid 
153203      ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
153204      ** tree that the node is part of has been marked as EOF, but the node
153205      ** itself is not EOF, then it may point to an earlier entry. */
153206      pNear = pExpr;
153207      for(p=pExpr->pParent; p; p=p->pParent){
153208        if( p->eType==FTSQUERY_OR ) bOr = 1;
153209        if( p->eType==FTSQUERY_NEAR ) pNear = p;
153210        if( p->bEof ) bTreeEof = 1;
153211      }
153212      if( bOr==0 ) return SQLITE_OK;
153213  
153214      /* This is the descendent of an OR node. In this case we cannot use
153215      ** an incremental phrase. Load the entire doclist for the phrase
153216      ** into memory in this case.  */
153217      if( pPhrase->bIncr ){
153218        int bEofSave = pNear->bEof;
153219        fts3EvalRestart(pCsr, pNear, &rc);
153220        while( rc==SQLITE_OK && !pNear->bEof ){
153221          fts3EvalNextRow(pCsr, pNear, &rc);
153222          if( bEofSave==0 && pNear->iDocid==iDocid ) break;
153223        }
153224        assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
153225      }
153226      if( bTreeEof ){
153227        while( rc==SQLITE_OK && !pNear->bEof ){
153228          fts3EvalNextRow(pCsr, pNear, &rc);
153229        }
153230      }
153231      if( rc!=SQLITE_OK ) return rc;
153232  
153233      bMatch = 1;
153234      for(p=pNear; p; p=p->pLeft){
153235        u8 bEof = 0;
153236        Fts3Expr *pTest = p;
153237        Fts3Phrase *pPh;
153238        assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
153239        if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
153240        assert( pTest->eType==FTSQUERY_PHRASE );
153241        pPh = pTest->pPhrase;
153242  
153243        pIter = pPh->pOrPoslist;
153244        iDocid = pPh->iOrDocid;
153245        if( pCsr->bDesc==bDescDoclist ){
153246          bEof = !pPh->doclist.nAll ||
153247            (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
153248          while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
153249            sqlite3Fts3DoclistNext(
153250                bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll, 
153251                &pIter, &iDocid, &bEof
153252            );
153253          }
153254        }else{
153255          bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
153256          while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
153257            int dummy;
153258            sqlite3Fts3DoclistPrev(
153259                bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll, 
153260                &pIter, &iDocid, &dummy, &bEof
153261                );
153262          }
153263        }
153264        pPh->pOrPoslist = pIter;
153265        pPh->iOrDocid = iDocid;
153266        if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
153267      }
153268  
153269      if( bMatch ){
153270        pIter = pPhrase->pOrPoslist;
153271      }else{
153272        pIter = 0;
153273      }
153274    }
153275    if( pIter==0 ) return SQLITE_OK;
153276  
153277    if( *pIter==0x01 ){
153278      pIter++;
153279      pIter += fts3GetVarint32(pIter, &iThis);
153280    }else{
153281      iThis = 0;
153282    }
153283    while( iThis<iCol ){
153284      fts3ColumnlistCopy(0, &pIter);
153285      if( *pIter==0x00 ) return SQLITE_OK;
153286      pIter++;
153287      pIter += fts3GetVarint32(pIter, &iThis);
153288    }
153289    if( *pIter==0x00 ){
153290      pIter = 0;
153291    }
153292  
153293    *ppOut = ((iCol==iThis)?pIter:0);
153294    return SQLITE_OK;
153295  }
153296  
153297  /*
153298  ** Free all components of the Fts3Phrase structure that were allocated by
153299  ** the eval module. Specifically, this means to free:
153300  **
153301  **   * the contents of pPhrase->doclist, and
153302  **   * any Fts3MultiSegReader objects held by phrase tokens.
153303  */
153304  SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
153305    if( pPhrase ){
153306      int i;
153307      sqlite3_free(pPhrase->doclist.aAll);
153308      fts3EvalInvalidatePoslist(pPhrase);
153309      memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
153310      for(i=0; i<pPhrase->nToken; i++){
153311        fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
153312        pPhrase->aToken[i].pSegcsr = 0;
153313      }
153314    }
153315  }
153316  
153317  
153318  /*
153319  ** Return SQLITE_CORRUPT_VTAB.
153320  */
153321  #ifdef SQLITE_DEBUG
153322  SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
153323    return SQLITE_CORRUPT_VTAB;
153324  }
153325  #endif
153326  
153327  #if !SQLITE_CORE
153328  /*
153329  ** Initialize API pointer table, if required.
153330  */
153331  #ifdef _WIN32
153332  __declspec(dllexport)
153333  #endif
153334  SQLITE_API int sqlite3_fts3_init(
153335    sqlite3 *db, 
153336    char **pzErrMsg,
153337    const sqlite3_api_routines *pApi
153338  ){
153339    SQLITE_EXTENSION_INIT2(pApi)
153340    return sqlite3Fts3Init(db);
153341  }
153342  #endif
153343  
153344  #endif
153345  
153346  /************** End of fts3.c ************************************************/
153347  /************** Begin file fts3_aux.c ****************************************/
153348  /*
153349  ** 2011 Jan 27
153350  **
153351  ** The author disclaims copyright to this source code.  In place of
153352  ** a legal notice, here is a blessing:
153353  **
153354  **    May you do good and not evil.
153355  **    May you find forgiveness for yourself and forgive others.
153356  **    May you share freely, never taking more than you give.
153357  **
153358  ******************************************************************************
153359  **
153360  */
153361  /* #include "fts3Int.h" */
153362  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
153363  
153364  /* #include <string.h> */
153365  /* #include <assert.h> */
153366  
153367  typedef struct Fts3auxTable Fts3auxTable;
153368  typedef struct Fts3auxCursor Fts3auxCursor;
153369  
153370  struct Fts3auxTable {
153371    sqlite3_vtab base;              /* Base class used by SQLite core */
153372    Fts3Table *pFts3Tab;
153373  };
153374  
153375  struct Fts3auxCursor {
153376    sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
153377    Fts3MultiSegReader csr;        /* Must be right after "base" */
153378    Fts3SegFilter filter;
153379    char *zStop;
153380    int nStop;                      /* Byte-length of string zStop */
153381    int iLangid;                    /* Language id to query */
153382    int isEof;                      /* True if cursor is at EOF */
153383    sqlite3_int64 iRowid;           /* Current rowid */
153384  
153385    int iCol;                       /* Current value of 'col' column */
153386    int nStat;                      /* Size of aStat[] array */
153387    struct Fts3auxColstats {
153388      sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
153389      sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
153390    } *aStat;
153391  };
153392  
153393  /*
153394  ** Schema of the terms table.
153395  */
153396  #define FTS3_AUX_SCHEMA \
153397    "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
153398  
153399  /*
153400  ** This function does all the work for both the xConnect and xCreate methods.
153401  ** These tables have no persistent representation of their own, so xConnect
153402  ** and xCreate are identical operations.
153403  */
153404  static int fts3auxConnectMethod(
153405    sqlite3 *db,                    /* Database connection */
153406    void *pUnused,                  /* Unused */
153407    int argc,                       /* Number of elements in argv array */
153408    const char * const *argv,       /* xCreate/xConnect argument array */
153409    sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
153410    char **pzErr                    /* OUT: sqlite3_malloc'd error message */
153411  ){
153412    char const *zDb;                /* Name of database (e.g. "main") */
153413    char const *zFts3;              /* Name of fts3 table */
153414    int nDb;                        /* Result of strlen(zDb) */
153415    int nFts3;                      /* Result of strlen(zFts3) */
153416    int nByte;                      /* Bytes of space to allocate here */
153417    int rc;                         /* value returned by declare_vtab() */
153418    Fts3auxTable *p;                /* Virtual table object to return */
153419  
153420    UNUSED_PARAMETER(pUnused);
153421  
153422    /* The user should invoke this in one of two forms:
153423    **
153424    **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
153425    **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
153426    */
153427    if( argc!=4 && argc!=5 ) goto bad_args;
153428  
153429    zDb = argv[1]; 
153430    nDb = (int)strlen(zDb);
153431    if( argc==5 ){
153432      if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
153433        zDb = argv[3]; 
153434        nDb = (int)strlen(zDb);
153435        zFts3 = argv[4];
153436      }else{
153437        goto bad_args;
153438      }
153439    }else{
153440      zFts3 = argv[3];
153441    }
153442    nFts3 = (int)strlen(zFts3);
153443  
153444    rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
153445    if( rc!=SQLITE_OK ) return rc;
153446  
153447    nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
153448    p = (Fts3auxTable *)sqlite3_malloc(nByte);
153449    if( !p ) return SQLITE_NOMEM;
153450    memset(p, 0, nByte);
153451  
153452    p->pFts3Tab = (Fts3Table *)&p[1];
153453    p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
153454    p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
153455    p->pFts3Tab->db = db;
153456    p->pFts3Tab->nIndex = 1;
153457  
153458    memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
153459    memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
153460    sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
153461  
153462    *ppVtab = (sqlite3_vtab *)p;
153463    return SQLITE_OK;
153464  
153465   bad_args:
153466    sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
153467    return SQLITE_ERROR;
153468  }
153469  
153470  /*
153471  ** This function does the work for both the xDisconnect and xDestroy methods.
153472  ** These tables have no persistent representation of their own, so xDisconnect
153473  ** and xDestroy are identical operations.
153474  */
153475  static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
153476    Fts3auxTable *p = (Fts3auxTable *)pVtab;
153477    Fts3Table *pFts3 = p->pFts3Tab;
153478    int i;
153479  
153480    /* Free any prepared statements held */
153481    for(i=0; i<SizeofArray(pFts3->aStmt); i++){
153482      sqlite3_finalize(pFts3->aStmt[i]);
153483    }
153484    sqlite3_free(pFts3->zSegmentsTbl);
153485    sqlite3_free(p);
153486    return SQLITE_OK;
153487  }
153488  
153489  #define FTS4AUX_EQ_CONSTRAINT 1
153490  #define FTS4AUX_GE_CONSTRAINT 2
153491  #define FTS4AUX_LE_CONSTRAINT 4
153492  
153493  /*
153494  ** xBestIndex - Analyze a WHERE and ORDER BY clause.
153495  */
153496  static int fts3auxBestIndexMethod(
153497    sqlite3_vtab *pVTab, 
153498    sqlite3_index_info *pInfo
153499  ){
153500    int i;
153501    int iEq = -1;
153502    int iGe = -1;
153503    int iLe = -1;
153504    int iLangid = -1;
153505    int iNext = 1;                  /* Next free argvIndex value */
153506  
153507    UNUSED_PARAMETER(pVTab);
153508  
153509    /* This vtab delivers always results in "ORDER BY term ASC" order. */
153510    if( pInfo->nOrderBy==1 
153511     && pInfo->aOrderBy[0].iColumn==0 
153512     && pInfo->aOrderBy[0].desc==0
153513    ){
153514      pInfo->orderByConsumed = 1;
153515    }
153516  
153517    /* Search for equality and range constraints on the "term" column. 
153518    ** And equality constraints on the hidden "languageid" column. */
153519    for(i=0; i<pInfo->nConstraint; i++){
153520      if( pInfo->aConstraint[i].usable ){
153521        int op = pInfo->aConstraint[i].op;
153522        int iCol = pInfo->aConstraint[i].iColumn;
153523  
153524        if( iCol==0 ){
153525          if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
153526          if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
153527          if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
153528          if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
153529          if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
153530        }
153531        if( iCol==4 ){
153532          if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
153533        }
153534      }
153535    }
153536  
153537    if( iEq>=0 ){
153538      pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
153539      pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
153540      pInfo->estimatedCost = 5;
153541    }else{
153542      pInfo->idxNum = 0;
153543      pInfo->estimatedCost = 20000;
153544      if( iGe>=0 ){
153545        pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
153546        pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
153547        pInfo->estimatedCost /= 2;
153548      }
153549      if( iLe>=0 ){
153550        pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
153551        pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
153552        pInfo->estimatedCost /= 2;
153553      }
153554    }
153555    if( iLangid>=0 ){
153556      pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
153557      pInfo->estimatedCost--;
153558    }
153559  
153560    return SQLITE_OK;
153561  }
153562  
153563  /*
153564  ** xOpen - Open a cursor.
153565  */
153566  static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
153567    Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
153568  
153569    UNUSED_PARAMETER(pVTab);
153570  
153571    pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
153572    if( !pCsr ) return SQLITE_NOMEM;
153573    memset(pCsr, 0, sizeof(Fts3auxCursor));
153574  
153575    *ppCsr = (sqlite3_vtab_cursor *)pCsr;
153576    return SQLITE_OK;
153577  }
153578  
153579  /*
153580  ** xClose - Close a cursor.
153581  */
153582  static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
153583    Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
153584    Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
153585  
153586    sqlite3Fts3SegmentsClose(pFts3);
153587    sqlite3Fts3SegReaderFinish(&pCsr->csr);
153588    sqlite3_free((void *)pCsr->filter.zTerm);
153589    sqlite3_free(pCsr->zStop);
153590    sqlite3_free(pCsr->aStat);
153591    sqlite3_free(pCsr);
153592    return SQLITE_OK;
153593  }
153594  
153595  static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
153596    if( nSize>pCsr->nStat ){
153597      struct Fts3auxColstats *aNew;
153598      aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat, 
153599          sizeof(struct Fts3auxColstats) * nSize
153600      );
153601      if( aNew==0 ) return SQLITE_NOMEM;
153602      memset(&aNew[pCsr->nStat], 0, 
153603          sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
153604      );
153605      pCsr->aStat = aNew;
153606      pCsr->nStat = nSize;
153607    }
153608    return SQLITE_OK;
153609  }
153610  
153611  /*
153612  ** xNext - Advance the cursor to the next row, if any.
153613  */
153614  static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
153615    Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
153616    Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
153617    int rc;
153618  
153619    /* Increment our pretend rowid value. */
153620    pCsr->iRowid++;
153621  
153622    for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
153623      if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
153624    }
153625  
153626    rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
153627    if( rc==SQLITE_ROW ){
153628      int i = 0;
153629      int nDoclist = pCsr->csr.nDoclist;
153630      char *aDoclist = pCsr->csr.aDoclist;
153631      int iCol;
153632  
153633      int eState = 0;
153634  
153635      if( pCsr->zStop ){
153636        int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
153637        int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
153638        if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
153639          pCsr->isEof = 1;
153640          return SQLITE_OK;
153641        }
153642      }
153643  
153644      if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
153645      memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
153646      iCol = 0;
153647  
153648      while( i<nDoclist ){
153649        sqlite3_int64 v = 0;
153650  
153651        i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
153652        switch( eState ){
153653          /* State 0. In this state the integer just read was a docid. */
153654          case 0:
153655            pCsr->aStat[0].nDoc++;
153656            eState = 1;
153657            iCol = 0;
153658            break;
153659  
153660          /* State 1. In this state we are expecting either a 1, indicating
153661          ** that the following integer will be a column number, or the
153662          ** start of a position list for column 0.  
153663          ** 
153664          ** The only difference between state 1 and state 2 is that if the
153665          ** integer encountered in state 1 is not 0 or 1, then we need to
153666          ** increment the column 0 "nDoc" count for this term.
153667          */
153668          case 1:
153669            assert( iCol==0 );
153670            if( v>1 ){
153671              pCsr->aStat[1].nDoc++;
153672            }
153673            eState = 2;
153674            /* fall through */
153675  
153676          case 2:
153677            if( v==0 ){       /* 0x00. Next integer will be a docid. */
153678              eState = 0;
153679            }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
153680              eState = 3;
153681            }else{            /* 2 or greater. A position. */
153682              pCsr->aStat[iCol+1].nOcc++;
153683              pCsr->aStat[0].nOcc++;
153684            }
153685            break;
153686  
153687          /* State 3. The integer just read is a column number. */
153688          default: assert( eState==3 );
153689            iCol = (int)v;
153690            if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
153691            pCsr->aStat[iCol+1].nDoc++;
153692            eState = 2;
153693            break;
153694        }
153695      }
153696  
153697      pCsr->iCol = 0;
153698      rc = SQLITE_OK;
153699    }else{
153700      pCsr->isEof = 1;
153701    }
153702    return rc;
153703  }
153704  
153705  /*
153706  ** xFilter - Initialize a cursor to point at the start of its data.
153707  */
153708  static int fts3auxFilterMethod(
153709    sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
153710    int idxNum,                     /* Strategy index */
153711    const char *idxStr,             /* Unused */
153712    int nVal,                       /* Number of elements in apVal */
153713    sqlite3_value **apVal           /* Arguments for the indexing scheme */
153714  ){
153715    Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
153716    Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
153717    int rc;
153718    int isScan = 0;
153719    int iLangVal = 0;               /* Language id to query */
153720  
153721    int iEq = -1;                   /* Index of term=? value in apVal */
153722    int iGe = -1;                   /* Index of term>=? value in apVal */
153723    int iLe = -1;                   /* Index of term<=? value in apVal */
153724    int iLangid = -1;               /* Index of languageid=? value in apVal */
153725    int iNext = 0;
153726  
153727    UNUSED_PARAMETER(nVal);
153728    UNUSED_PARAMETER(idxStr);
153729  
153730    assert( idxStr==0 );
153731    assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
153732         || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
153733         || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
153734    );
153735  
153736    if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
153737      iEq = iNext++;
153738    }else{
153739      isScan = 1;
153740      if( idxNum & FTS4AUX_GE_CONSTRAINT ){
153741        iGe = iNext++;
153742      }
153743      if( idxNum & FTS4AUX_LE_CONSTRAINT ){
153744        iLe = iNext++;
153745      }
153746    }
153747    if( iNext<nVal ){
153748      iLangid = iNext++;
153749    }
153750  
153751    /* In case this cursor is being reused, close and zero it. */
153752    testcase(pCsr->filter.zTerm);
153753    sqlite3Fts3SegReaderFinish(&pCsr->csr);
153754    sqlite3_free((void *)pCsr->filter.zTerm);
153755    sqlite3_free(pCsr->aStat);
153756    memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
153757  
153758    pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
153759    if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
153760  
153761    if( iEq>=0 || iGe>=0 ){
153762      const unsigned char *zStr = sqlite3_value_text(apVal[0]);
153763      assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
153764      if( zStr ){
153765        pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
153766        pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
153767        if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
153768      }
153769    }
153770  
153771    if( iLe>=0 ){
153772      pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
153773      pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
153774      if( pCsr->zStop==0 ) return SQLITE_NOMEM;
153775    }
153776    
153777    if( iLangid>=0 ){
153778      iLangVal = sqlite3_value_int(apVal[iLangid]);
153779  
153780      /* If the user specified a negative value for the languageid, use zero
153781      ** instead. This works, as the "languageid=?" constraint will also
153782      ** be tested by the VDBE layer. The test will always be false (since
153783      ** this module will not return a row with a negative languageid), and
153784      ** so the overall query will return zero rows.  */
153785      if( iLangVal<0 ) iLangVal = 0;
153786    }
153787    pCsr->iLangid = iLangVal;
153788  
153789    rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
153790        pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
153791    );
153792    if( rc==SQLITE_OK ){
153793      rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
153794    }
153795  
153796    if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
153797    return rc;
153798  }
153799  
153800  /*
153801  ** xEof - Return true if the cursor is at EOF, or false otherwise.
153802  */
153803  static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
153804    Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
153805    return pCsr->isEof;
153806  }
153807  
153808  /*
153809  ** xColumn - Return a column value.
153810  */
153811  static int fts3auxColumnMethod(
153812    sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
153813    sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
153814    int iCol                        /* Index of column to read value from */
153815  ){
153816    Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
153817  
153818    assert( p->isEof==0 );
153819    switch( iCol ){
153820      case 0: /* term */
153821        sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
153822        break;
153823  
153824      case 1: /* col */
153825        if( p->iCol ){
153826          sqlite3_result_int(pCtx, p->iCol-1);
153827        }else{
153828          sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
153829        }
153830        break;
153831  
153832      case 2: /* documents */
153833        sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
153834        break;
153835  
153836      case 3: /* occurrences */
153837        sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
153838        break;
153839  
153840      default: /* languageid */
153841        assert( iCol==4 );
153842        sqlite3_result_int(pCtx, p->iLangid);
153843        break;
153844    }
153845  
153846    return SQLITE_OK;
153847  }
153848  
153849  /*
153850  ** xRowid - Return the current rowid for the cursor.
153851  */
153852  static int fts3auxRowidMethod(
153853    sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
153854    sqlite_int64 *pRowid            /* OUT: Rowid value */
153855  ){
153856    Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
153857    *pRowid = pCsr->iRowid;
153858    return SQLITE_OK;
153859  }
153860  
153861  /*
153862  ** Register the fts3aux module with database connection db. Return SQLITE_OK
153863  ** if successful or an error code if sqlite3_create_module() fails.
153864  */
153865  SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
153866    static const sqlite3_module fts3aux_module = {
153867       0,                           /* iVersion      */
153868       fts3auxConnectMethod,        /* xCreate       */
153869       fts3auxConnectMethod,        /* xConnect      */
153870       fts3auxBestIndexMethod,      /* xBestIndex    */
153871       fts3auxDisconnectMethod,     /* xDisconnect   */
153872       fts3auxDisconnectMethod,     /* xDestroy      */
153873       fts3auxOpenMethod,           /* xOpen         */
153874       fts3auxCloseMethod,          /* xClose        */
153875       fts3auxFilterMethod,         /* xFilter       */
153876       fts3auxNextMethod,           /* xNext         */
153877       fts3auxEofMethod,            /* xEof          */
153878       fts3auxColumnMethod,         /* xColumn       */
153879       fts3auxRowidMethod,          /* xRowid        */
153880       0,                           /* xUpdate       */
153881       0,                           /* xBegin        */
153882       0,                           /* xSync         */
153883       0,                           /* xCommit       */
153884       0,                           /* xRollback     */
153885       0,                           /* xFindFunction */
153886       0,                           /* xRename       */
153887       0,                           /* xSavepoint    */
153888       0,                           /* xRelease      */
153889       0                            /* xRollbackTo   */
153890    };
153891    int rc;                         /* Return code */
153892  
153893    rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
153894    return rc;
153895  }
153896  
153897  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
153898  
153899  /************** End of fts3_aux.c ********************************************/
153900  /************** Begin file fts3_expr.c ***************************************/
153901  /*
153902  ** 2008 Nov 28
153903  **
153904  ** The author disclaims copyright to this source code.  In place of
153905  ** a legal notice, here is a blessing:
153906  **
153907  **    May you do good and not evil.
153908  **    May you find forgiveness for yourself and forgive others.
153909  **    May you share freely, never taking more than you give.
153910  **
153911  ******************************************************************************
153912  **
153913  ** This module contains code that implements a parser for fts3 query strings
153914  ** (the right-hand argument to the MATCH operator). Because the supported 
153915  ** syntax is relatively simple, the whole tokenizer/parser system is
153916  ** hand-coded. 
153917  */
153918  /* #include "fts3Int.h" */
153919  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
153920  
153921  /*
153922  ** By default, this module parses the legacy syntax that has been 
153923  ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
153924  ** is defined, then it uses the new syntax. The differences between
153925  ** the new and the old syntaxes are:
153926  **
153927  **  a) The new syntax supports parenthesis. The old does not.
153928  **
153929  **  b) The new syntax supports the AND and NOT operators. The old does not.
153930  **
153931  **  c) The old syntax supports the "-" token qualifier. This is not 
153932  **     supported by the new syntax (it is replaced by the NOT operator).
153933  **
153934  **  d) When using the old syntax, the OR operator has a greater precedence
153935  **     than an implicit AND. When using the new, both implicity and explicit
153936  **     AND operators have a higher precedence than OR.
153937  **
153938  ** If compiled with SQLITE_TEST defined, then this module exports the
153939  ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
153940  ** to zero causes the module to use the old syntax. If it is set to 
153941  ** non-zero the new syntax is activated. This is so both syntaxes can
153942  ** be tested using a single build of testfixture.
153943  **
153944  ** The following describes the syntax supported by the fts3 MATCH
153945  ** operator in a similar format to that used by the lemon parser
153946  ** generator. This module does not use actually lemon, it uses a
153947  ** custom parser.
153948  **
153949  **   query ::= andexpr (OR andexpr)*.
153950  **
153951  **   andexpr ::= notexpr (AND? notexpr)*.
153952  **
153953  **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
153954  **   notexpr ::= LP query RP.
153955  **
153956  **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
153957  **
153958  **   distance_opt ::= .
153959  **   distance_opt ::= / INTEGER.
153960  **
153961  **   phrase ::= TOKEN.
153962  **   phrase ::= COLUMN:TOKEN.
153963  **   phrase ::= "TOKEN TOKEN TOKEN...".
153964  */
153965  
153966  #ifdef SQLITE_TEST
153967  SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
153968  #else
153969  # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
153970  #  define sqlite3_fts3_enable_parentheses 1
153971  # else
153972  #  define sqlite3_fts3_enable_parentheses 0
153973  # endif
153974  #endif
153975  
153976  /*
153977  ** Default span for NEAR operators.
153978  */
153979  #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
153980  
153981  /* #include <string.h> */
153982  /* #include <assert.h> */
153983  
153984  /*
153985  ** isNot:
153986  **   This variable is used by function getNextNode(). When getNextNode() is
153987  **   called, it sets ParseContext.isNot to true if the 'next node' is a 
153988  **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
153989  **   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
153990  **   zero.
153991  */
153992  typedef struct ParseContext ParseContext;
153993  struct ParseContext {
153994    sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
153995    int iLangid;                        /* Language id used with tokenizer */
153996    const char **azCol;                 /* Array of column names for fts3 table */
153997    int bFts4;                          /* True to allow FTS4-only syntax */
153998    int nCol;                           /* Number of entries in azCol[] */
153999    int iDefaultCol;                    /* Default column to query */
154000    int isNot;                          /* True if getNextNode() sees a unary - */
154001    sqlite3_context *pCtx;              /* Write error message here */
154002    int nNest;                          /* Number of nested brackets */
154003  };
154004  
154005  /*
154006  ** This function is equivalent to the standard isspace() function. 
154007  **
154008  ** The standard isspace() can be awkward to use safely, because although it
154009  ** is defined to accept an argument of type int, its behavior when passed
154010  ** an integer that falls outside of the range of the unsigned char type
154011  ** is undefined (and sometimes, "undefined" means segfault). This wrapper
154012  ** is defined to accept an argument of type char, and always returns 0 for
154013  ** any values that fall outside of the range of the unsigned char type (i.e.
154014  ** negative values).
154015  */
154016  static int fts3isspace(char c){
154017    return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
154018  }
154019  
154020  /*
154021  ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
154022  ** zero the memory before returning a pointer to it. If unsuccessful, 
154023  ** return NULL.
154024  */
154025  static void *fts3MallocZero(int nByte){
154026    void *pRet = sqlite3_malloc(nByte);
154027    if( pRet ) memset(pRet, 0, nByte);
154028    return pRet;
154029  }
154030  
154031  SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
154032    sqlite3_tokenizer *pTokenizer,
154033    int iLangid,
154034    const char *z,
154035    int n,
154036    sqlite3_tokenizer_cursor **ppCsr
154037  ){
154038    sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
154039    sqlite3_tokenizer_cursor *pCsr = 0;
154040    int rc;
154041  
154042    rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
154043    assert( rc==SQLITE_OK || pCsr==0 );
154044    if( rc==SQLITE_OK ){
154045      pCsr->pTokenizer = pTokenizer;
154046      if( pModule->iVersion>=1 ){
154047        rc = pModule->xLanguageid(pCsr, iLangid);
154048        if( rc!=SQLITE_OK ){
154049          pModule->xClose(pCsr);
154050          pCsr = 0;
154051        }
154052      }
154053    }
154054    *ppCsr = pCsr;
154055    return rc;
154056  }
154057  
154058  /*
154059  ** Function getNextNode(), which is called by fts3ExprParse(), may itself
154060  ** call fts3ExprParse(). So this forward declaration is required.
154061  */
154062  static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
154063  
154064  /*
154065  ** Extract the next token from buffer z (length n) using the tokenizer
154066  ** and other information (column names etc.) in pParse. Create an Fts3Expr
154067  ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
154068  ** single token and set *ppExpr to point to it. If the end of the buffer is
154069  ** reached before a token is found, set *ppExpr to zero. It is the
154070  ** responsibility of the caller to eventually deallocate the allocated 
154071  ** Fts3Expr structure (if any) by passing it to sqlite3_free().
154072  **
154073  ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
154074  ** fails.
154075  */
154076  static int getNextToken(
154077    ParseContext *pParse,                   /* fts3 query parse context */
154078    int iCol,                               /* Value for Fts3Phrase.iColumn */
154079    const char *z, int n,                   /* Input string */
154080    Fts3Expr **ppExpr,                      /* OUT: expression */
154081    int *pnConsumed                         /* OUT: Number of bytes consumed */
154082  ){
154083    sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
154084    sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
154085    int rc;
154086    sqlite3_tokenizer_cursor *pCursor;
154087    Fts3Expr *pRet = 0;
154088    int i = 0;
154089  
154090    /* Set variable i to the maximum number of bytes of input to tokenize. */
154091    for(i=0; i<n; i++){
154092      if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
154093      if( z[i]=='"' ) break;
154094    }
154095  
154096    *pnConsumed = i;
154097    rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
154098    if( rc==SQLITE_OK ){
154099      const char *zToken;
154100      int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
154101      int nByte;                               /* total space to allocate */
154102  
154103      rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
154104      if( rc==SQLITE_OK ){
154105        nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
154106        pRet = (Fts3Expr *)fts3MallocZero(nByte);
154107        if( !pRet ){
154108          rc = SQLITE_NOMEM;
154109        }else{
154110          pRet->eType = FTSQUERY_PHRASE;
154111          pRet->pPhrase = (Fts3Phrase *)&pRet[1];
154112          pRet->pPhrase->nToken = 1;
154113          pRet->pPhrase->iColumn = iCol;
154114          pRet->pPhrase->aToken[0].n = nToken;
154115          pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
154116          memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
154117  
154118          if( iEnd<n && z[iEnd]=='*' ){
154119            pRet->pPhrase->aToken[0].isPrefix = 1;
154120            iEnd++;
154121          }
154122  
154123          while( 1 ){
154124            if( !sqlite3_fts3_enable_parentheses 
154125             && iStart>0 && z[iStart-1]=='-' 
154126            ){
154127              pParse->isNot = 1;
154128              iStart--;
154129            }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
154130              pRet->pPhrase->aToken[0].bFirst = 1;
154131              iStart--;
154132            }else{
154133              break;
154134            }
154135          }
154136  
154137        }
154138        *pnConsumed = iEnd;
154139      }else if( i && rc==SQLITE_DONE ){
154140        rc = SQLITE_OK;
154141      }
154142  
154143      pModule->xClose(pCursor);
154144    }
154145    
154146    *ppExpr = pRet;
154147    return rc;
154148  }
154149  
154150  
154151  /*
154152  ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
154153  ** then free the old allocation.
154154  */
154155  static void *fts3ReallocOrFree(void *pOrig, int nNew){
154156    void *pRet = sqlite3_realloc(pOrig, nNew);
154157    if( !pRet ){
154158      sqlite3_free(pOrig);
154159    }
154160    return pRet;
154161  }
154162  
154163  /*
154164  ** Buffer zInput, length nInput, contains the contents of a quoted string
154165  ** that appeared as part of an fts3 query expression. Neither quote character
154166  ** is included in the buffer. This function attempts to tokenize the entire
154167  ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
154168  ** containing the results.
154169  **
154170  ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
154171  ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
154172  ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
154173  ** to 0.
154174  */
154175  static int getNextString(
154176    ParseContext *pParse,                   /* fts3 query parse context */
154177    const char *zInput, int nInput,         /* Input string */
154178    Fts3Expr **ppExpr                       /* OUT: expression */
154179  ){
154180    sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
154181    sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
154182    int rc;
154183    Fts3Expr *p = 0;
154184    sqlite3_tokenizer_cursor *pCursor = 0;
154185    char *zTemp = 0;
154186    int nTemp = 0;
154187  
154188    const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
154189    int nToken = 0;
154190  
154191    /* The final Fts3Expr data structure, including the Fts3Phrase,
154192    ** Fts3PhraseToken structures token buffers are all stored as a single 
154193    ** allocation so that the expression can be freed with a single call to
154194    ** sqlite3_free(). Setting this up requires a two pass approach.
154195    **
154196    ** The first pass, in the block below, uses a tokenizer cursor to iterate
154197    ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
154198    ** to assemble data in two dynamic buffers:
154199    **
154200    **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
154201    **             structure, followed by the array of Fts3PhraseToken 
154202    **             structures. This pass only populates the Fts3PhraseToken array.
154203    **
154204    **   Buffer zTemp: Contains copies of all tokens.
154205    **
154206    ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
154207    ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
154208    ** structures.
154209    */
154210    rc = sqlite3Fts3OpenTokenizer(
154211        pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
154212    if( rc==SQLITE_OK ){
154213      int ii;
154214      for(ii=0; rc==SQLITE_OK; ii++){
154215        const char *zByte;
154216        int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
154217        rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
154218        if( rc==SQLITE_OK ){
154219          Fts3PhraseToken *pToken;
154220  
154221          p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
154222          if( !p ) goto no_mem;
154223  
154224          zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
154225          if( !zTemp ) goto no_mem;
154226  
154227          assert( nToken==ii );
154228          pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
154229          memset(pToken, 0, sizeof(Fts3PhraseToken));
154230  
154231          memcpy(&zTemp[nTemp], zByte, nByte);
154232          nTemp += nByte;
154233  
154234          pToken->n = nByte;
154235          pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
154236          pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
154237          nToken = ii+1;
154238        }
154239      }
154240  
154241      pModule->xClose(pCursor);
154242      pCursor = 0;
154243    }
154244  
154245    if( rc==SQLITE_DONE ){
154246      int jj;
154247      char *zBuf = 0;
154248  
154249      p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
154250      if( !p ) goto no_mem;
154251      memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
154252      p->eType = FTSQUERY_PHRASE;
154253      p->pPhrase = (Fts3Phrase *)&p[1];
154254      p->pPhrase->iColumn = pParse->iDefaultCol;
154255      p->pPhrase->nToken = nToken;
154256  
154257      zBuf = (char *)&p->pPhrase->aToken[nToken];
154258      if( zTemp ){
154259        memcpy(zBuf, zTemp, nTemp);
154260        sqlite3_free(zTemp);
154261      }else{
154262        assert( nTemp==0 );
154263      }
154264  
154265      for(jj=0; jj<p->pPhrase->nToken; jj++){
154266        p->pPhrase->aToken[jj].z = zBuf;
154267        zBuf += p->pPhrase->aToken[jj].n;
154268      }
154269      rc = SQLITE_OK;
154270    }
154271  
154272    *ppExpr = p;
154273    return rc;
154274  no_mem:
154275  
154276    if( pCursor ){
154277      pModule->xClose(pCursor);
154278    }
154279    sqlite3_free(zTemp);
154280    sqlite3_free(p);
154281    *ppExpr = 0;
154282    return SQLITE_NOMEM;
154283  }
154284  
154285  /*
154286  ** The output variable *ppExpr is populated with an allocated Fts3Expr 
154287  ** structure, or set to 0 if the end of the input buffer is reached.
154288  **
154289  ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
154290  ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
154291  ** If SQLITE_ERROR is returned, pContext is populated with an error message.
154292  */
154293  static int getNextNode(
154294    ParseContext *pParse,                   /* fts3 query parse context */
154295    const char *z, int n,                   /* Input string */
154296    Fts3Expr **ppExpr,                      /* OUT: expression */
154297    int *pnConsumed                         /* OUT: Number of bytes consumed */
154298  ){
154299    static const struct Fts3Keyword {
154300      char *z;                              /* Keyword text */
154301      unsigned char n;                      /* Length of the keyword */
154302      unsigned char parenOnly;              /* Only valid in paren mode */
154303      unsigned char eType;                  /* Keyword code */
154304    } aKeyword[] = {
154305      { "OR" ,  2, 0, FTSQUERY_OR   },
154306      { "AND",  3, 1, FTSQUERY_AND  },
154307      { "NOT",  3, 1, FTSQUERY_NOT  },
154308      { "NEAR", 4, 0, FTSQUERY_NEAR }
154309    };
154310    int ii;
154311    int iCol;
154312    int iColLen;
154313    int rc;
154314    Fts3Expr *pRet = 0;
154315  
154316    const char *zInput = z;
154317    int nInput = n;
154318  
154319    pParse->isNot = 0;
154320  
154321    /* Skip over any whitespace before checking for a keyword, an open or
154322    ** close bracket, or a quoted string. 
154323    */
154324    while( nInput>0 && fts3isspace(*zInput) ){
154325      nInput--;
154326      zInput++;
154327    }
154328    if( nInput==0 ){
154329      return SQLITE_DONE;
154330    }
154331  
154332    /* See if we are dealing with a keyword. */
154333    for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
154334      const struct Fts3Keyword *pKey = &aKeyword[ii];
154335  
154336      if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
154337        continue;
154338      }
154339  
154340      if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
154341        int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
154342        int nKey = pKey->n;
154343        char cNext;
154344  
154345        /* If this is a "NEAR" keyword, check for an explicit nearness. */
154346        if( pKey->eType==FTSQUERY_NEAR ){
154347          assert( nKey==4 );
154348          if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
154349            nNear = 0;
154350            for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
154351              nNear = nNear * 10 + (zInput[nKey] - '0');
154352            }
154353          }
154354        }
154355  
154356        /* At this point this is probably a keyword. But for that to be true,
154357        ** the next byte must contain either whitespace, an open or close
154358        ** parenthesis, a quote character, or EOF. 
154359        */
154360        cNext = zInput[nKey];
154361        if( fts3isspace(cNext) 
154362         || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
154363        ){
154364          pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
154365          if( !pRet ){
154366            return SQLITE_NOMEM;
154367          }
154368          pRet->eType = pKey->eType;
154369          pRet->nNear = nNear;
154370          *ppExpr = pRet;
154371          *pnConsumed = (int)((zInput - z) + nKey);
154372          return SQLITE_OK;
154373        }
154374  
154375        /* Turns out that wasn't a keyword after all. This happens if the
154376        ** user has supplied a token such as "ORacle". Continue.
154377        */
154378      }
154379    }
154380  
154381    /* See if we are dealing with a quoted phrase. If this is the case, then
154382    ** search for the closing quote and pass the whole string to getNextString()
154383    ** for processing. This is easy to do, as fts3 has no syntax for escaping
154384    ** a quote character embedded in a string.
154385    */
154386    if( *zInput=='"' ){
154387      for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
154388      *pnConsumed = (int)((zInput - z) + ii + 1);
154389      if( ii==nInput ){
154390        return SQLITE_ERROR;
154391      }
154392      return getNextString(pParse, &zInput[1], ii-1, ppExpr);
154393    }
154394  
154395    if( sqlite3_fts3_enable_parentheses ){
154396      if( *zInput=='(' ){
154397        int nConsumed = 0;
154398        pParse->nNest++;
154399        rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
154400        if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
154401        *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
154402        return rc;
154403      }else if( *zInput==')' ){
154404        pParse->nNest--;
154405        *pnConsumed = (int)((zInput - z) + 1);
154406        *ppExpr = 0;
154407        return SQLITE_DONE;
154408      }
154409    }
154410  
154411    /* If control flows to this point, this must be a regular token, or 
154412    ** the end of the input. Read a regular token using the sqlite3_tokenizer
154413    ** interface. Before doing so, figure out if there is an explicit
154414    ** column specifier for the token. 
154415    **
154416    ** TODO: Strangely, it is not possible to associate a column specifier
154417    ** with a quoted phrase, only with a single token. Not sure if this was
154418    ** an implementation artifact or an intentional decision when fts3 was
154419    ** first implemented. Whichever it was, this module duplicates the 
154420    ** limitation.
154421    */
154422    iCol = pParse->iDefaultCol;
154423    iColLen = 0;
154424    for(ii=0; ii<pParse->nCol; ii++){
154425      const char *zStr = pParse->azCol[ii];
154426      int nStr = (int)strlen(zStr);
154427      if( nInput>nStr && zInput[nStr]==':' 
154428       && sqlite3_strnicmp(zStr, zInput, nStr)==0 
154429      ){
154430        iCol = ii;
154431        iColLen = (int)((zInput - z) + nStr + 1);
154432        break;
154433      }
154434    }
154435    rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
154436    *pnConsumed += iColLen;
154437    return rc;
154438  }
154439  
154440  /*
154441  ** The argument is an Fts3Expr structure for a binary operator (any type
154442  ** except an FTSQUERY_PHRASE). Return an integer value representing the
154443  ** precedence of the operator. Lower values have a higher precedence (i.e.
154444  ** group more tightly). For example, in the C language, the == operator
154445  ** groups more tightly than ||, and would therefore have a higher precedence.
154446  **
154447  ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
154448  ** is defined), the order of the operators in precedence from highest to
154449  ** lowest is:
154450  **
154451  **   NEAR
154452  **   NOT
154453  **   AND (including implicit ANDs)
154454  **   OR
154455  **
154456  ** Note that when using the old query syntax, the OR operator has a higher
154457  ** precedence than the AND operator.
154458  */
154459  static int opPrecedence(Fts3Expr *p){
154460    assert( p->eType!=FTSQUERY_PHRASE );
154461    if( sqlite3_fts3_enable_parentheses ){
154462      return p->eType;
154463    }else if( p->eType==FTSQUERY_NEAR ){
154464      return 1;
154465    }else if( p->eType==FTSQUERY_OR ){
154466      return 2;
154467    }
154468    assert( p->eType==FTSQUERY_AND );
154469    return 3;
154470  }
154471  
154472  /*
154473  ** Argument ppHead contains a pointer to the current head of a query 
154474  ** expression tree being parsed. pPrev is the expression node most recently
154475  ** inserted into the tree. This function adds pNew, which is always a binary
154476  ** operator node, into the expression tree based on the relative precedence
154477  ** of pNew and the existing nodes of the tree. This may result in the head
154478  ** of the tree changing, in which case *ppHead is set to the new root node.
154479  */
154480  static void insertBinaryOperator(
154481    Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
154482    Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
154483    Fts3Expr *pNew           /* New binary node to insert into expression tree */
154484  ){
154485    Fts3Expr *pSplit = pPrev;
154486    while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
154487      pSplit = pSplit->pParent;
154488    }
154489  
154490    if( pSplit->pParent ){
154491      assert( pSplit->pParent->pRight==pSplit );
154492      pSplit->pParent->pRight = pNew;
154493      pNew->pParent = pSplit->pParent;
154494    }else{
154495      *ppHead = pNew;
154496    }
154497    pNew->pLeft = pSplit;
154498    pSplit->pParent = pNew;
154499  }
154500  
154501  /*
154502  ** Parse the fts3 query expression found in buffer z, length n. This function
154503  ** returns either when the end of the buffer is reached or an unmatched 
154504  ** closing bracket - ')' - is encountered.
154505  **
154506  ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
154507  ** parsed form of the expression and *pnConsumed is set to the number of
154508  ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
154509  ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
154510  */
154511  static int fts3ExprParse(
154512    ParseContext *pParse,                   /* fts3 query parse context */
154513    const char *z, int n,                   /* Text of MATCH query */
154514    Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
154515    int *pnConsumed                         /* OUT: Number of bytes consumed */
154516  ){
154517    Fts3Expr *pRet = 0;
154518    Fts3Expr *pPrev = 0;
154519    Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
154520    int nIn = n;
154521    const char *zIn = z;
154522    int rc = SQLITE_OK;
154523    int isRequirePhrase = 1;
154524  
154525    while( rc==SQLITE_OK ){
154526      Fts3Expr *p = 0;
154527      int nByte = 0;
154528  
154529      rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
154530      assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
154531      if( rc==SQLITE_OK ){
154532        if( p ){
154533          int isPhrase;
154534  
154535          if( !sqlite3_fts3_enable_parentheses 
154536              && p->eType==FTSQUERY_PHRASE && pParse->isNot 
154537          ){
154538            /* Create an implicit NOT operator. */
154539            Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
154540            if( !pNot ){
154541              sqlite3Fts3ExprFree(p);
154542              rc = SQLITE_NOMEM;
154543              goto exprparse_out;
154544            }
154545            pNot->eType = FTSQUERY_NOT;
154546            pNot->pRight = p;
154547            p->pParent = pNot;
154548            if( pNotBranch ){
154549              pNot->pLeft = pNotBranch;
154550              pNotBranch->pParent = pNot;
154551            }
154552            pNotBranch = pNot;
154553            p = pPrev;
154554          }else{
154555            int eType = p->eType;
154556            isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
154557  
154558            /* The isRequirePhrase variable is set to true if a phrase or
154559            ** an expression contained in parenthesis is required. If a
154560            ** binary operator (AND, OR, NOT or NEAR) is encounted when
154561            ** isRequirePhrase is set, this is a syntax error.
154562            */
154563            if( !isPhrase && isRequirePhrase ){
154564              sqlite3Fts3ExprFree(p);
154565              rc = SQLITE_ERROR;
154566              goto exprparse_out;
154567            }
154568  
154569            if( isPhrase && !isRequirePhrase ){
154570              /* Insert an implicit AND operator. */
154571              Fts3Expr *pAnd;
154572              assert( pRet && pPrev );
154573              pAnd = fts3MallocZero(sizeof(Fts3Expr));
154574              if( !pAnd ){
154575                sqlite3Fts3ExprFree(p);
154576                rc = SQLITE_NOMEM;
154577                goto exprparse_out;
154578              }
154579              pAnd->eType = FTSQUERY_AND;
154580              insertBinaryOperator(&pRet, pPrev, pAnd);
154581              pPrev = pAnd;
154582            }
154583  
154584            /* This test catches attempts to make either operand of a NEAR
154585             ** operator something other than a phrase. For example, either of
154586             ** the following:
154587             **
154588             **    (bracketed expression) NEAR phrase
154589             **    phrase NEAR (bracketed expression)
154590             **
154591             ** Return an error in either case.
154592             */
154593            if( pPrev && (
154594              (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
154595           || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
154596            )){
154597              sqlite3Fts3ExprFree(p);
154598              rc = SQLITE_ERROR;
154599              goto exprparse_out;
154600            }
154601  
154602            if( isPhrase ){
154603              if( pRet ){
154604                assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
154605                pPrev->pRight = p;
154606                p->pParent = pPrev;
154607              }else{
154608                pRet = p;
154609              }
154610            }else{
154611              insertBinaryOperator(&pRet, pPrev, p);
154612            }
154613            isRequirePhrase = !isPhrase;
154614          }
154615          pPrev = p;
154616        }
154617        assert( nByte>0 );
154618      }
154619      assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
154620      nIn -= nByte;
154621      zIn += nByte;
154622    }
154623  
154624    if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
154625      rc = SQLITE_ERROR;
154626    }
154627  
154628    if( rc==SQLITE_DONE ){
154629      rc = SQLITE_OK;
154630      if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
154631        if( !pRet ){
154632          rc = SQLITE_ERROR;
154633        }else{
154634          Fts3Expr *pIter = pNotBranch;
154635          while( pIter->pLeft ){
154636            pIter = pIter->pLeft;
154637          }
154638          pIter->pLeft = pRet;
154639          pRet->pParent = pIter;
154640          pRet = pNotBranch;
154641        }
154642      }
154643    }
154644    *pnConsumed = n - nIn;
154645  
154646  exprparse_out:
154647    if( rc!=SQLITE_OK ){
154648      sqlite3Fts3ExprFree(pRet);
154649      sqlite3Fts3ExprFree(pNotBranch);
154650      pRet = 0;
154651    }
154652    *ppExpr = pRet;
154653    return rc;
154654  }
154655  
154656  /*
154657  ** Return SQLITE_ERROR if the maximum depth of the expression tree passed 
154658  ** as the only argument is more than nMaxDepth.
154659  */
154660  static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
154661    int rc = SQLITE_OK;
154662    if( p ){
154663      if( nMaxDepth<0 ){ 
154664        rc = SQLITE_TOOBIG;
154665      }else{
154666        rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
154667        if( rc==SQLITE_OK ){
154668          rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
154669        }
154670      }
154671    }
154672    return rc;
154673  }
154674  
154675  /*
154676  ** This function attempts to transform the expression tree at (*pp) to
154677  ** an equivalent but more balanced form. The tree is modified in place.
154678  ** If successful, SQLITE_OK is returned and (*pp) set to point to the 
154679  ** new root expression node. 
154680  **
154681  ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
154682  **
154683  ** Otherwise, if an error occurs, an SQLite error code is returned and 
154684  ** expression (*pp) freed.
154685  */
154686  static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
154687    int rc = SQLITE_OK;             /* Return code */
154688    Fts3Expr *pRoot = *pp;          /* Initial root node */
154689    Fts3Expr *pFree = 0;            /* List of free nodes. Linked by pParent. */
154690    int eType = pRoot->eType;       /* Type of node in this tree */
154691  
154692    if( nMaxDepth==0 ){
154693      rc = SQLITE_ERROR;
154694    }
154695  
154696    if( rc==SQLITE_OK ){
154697      if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
154698        Fts3Expr **apLeaf;
154699        apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
154700        if( 0==apLeaf ){
154701          rc = SQLITE_NOMEM;
154702        }else{
154703          memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
154704        }
154705  
154706        if( rc==SQLITE_OK ){
154707          int i;
154708          Fts3Expr *p;
154709  
154710          /* Set $p to point to the left-most leaf in the tree of eType nodes. */
154711          for(p=pRoot; p->eType==eType; p=p->pLeft){
154712            assert( p->pParent==0 || p->pParent->pLeft==p );
154713            assert( p->pLeft && p->pRight );
154714          }
154715  
154716          /* This loop runs once for each leaf in the tree of eType nodes. */
154717          while( 1 ){
154718            int iLvl;
154719            Fts3Expr *pParent = p->pParent;     /* Current parent of p */
154720  
154721            assert( pParent==0 || pParent->pLeft==p );
154722            p->pParent = 0;
154723            if( pParent ){
154724              pParent->pLeft = 0;
154725            }else{
154726              pRoot = 0;
154727            }
154728            rc = fts3ExprBalance(&p, nMaxDepth-1);
154729            if( rc!=SQLITE_OK ) break;
154730  
154731            for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
154732              if( apLeaf[iLvl]==0 ){
154733                apLeaf[iLvl] = p;
154734                p = 0;
154735              }else{
154736                assert( pFree );
154737                pFree->pLeft = apLeaf[iLvl];
154738                pFree->pRight = p;
154739                pFree->pLeft->pParent = pFree;
154740                pFree->pRight->pParent = pFree;
154741  
154742                p = pFree;
154743                pFree = pFree->pParent;
154744                p->pParent = 0;
154745                apLeaf[iLvl] = 0;
154746              }
154747            }
154748            if( p ){
154749              sqlite3Fts3ExprFree(p);
154750              rc = SQLITE_TOOBIG;
154751              break;
154752            }
154753  
154754            /* If that was the last leaf node, break out of the loop */
154755            if( pParent==0 ) break;
154756  
154757            /* Set $p to point to the next leaf in the tree of eType nodes */
154758            for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
154759  
154760            /* Remove pParent from the original tree. */
154761            assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
154762            pParent->pRight->pParent = pParent->pParent;
154763            if( pParent->pParent ){
154764              pParent->pParent->pLeft = pParent->pRight;
154765            }else{
154766              assert( pParent==pRoot );
154767              pRoot = pParent->pRight;
154768            }
154769  
154770            /* Link pParent into the free node list. It will be used as an
154771            ** internal node of the new tree.  */
154772            pParent->pParent = pFree;
154773            pFree = pParent;
154774          }
154775  
154776          if( rc==SQLITE_OK ){
154777            p = 0;
154778            for(i=0; i<nMaxDepth; i++){
154779              if( apLeaf[i] ){
154780                if( p==0 ){
154781                  p = apLeaf[i];
154782                  p->pParent = 0;
154783                }else{
154784                  assert( pFree!=0 );
154785                  pFree->pRight = p;
154786                  pFree->pLeft = apLeaf[i];
154787                  pFree->pLeft->pParent = pFree;
154788                  pFree->pRight->pParent = pFree;
154789  
154790                  p = pFree;
154791                  pFree = pFree->pParent;
154792                  p->pParent = 0;
154793                }
154794              }
154795            }
154796            pRoot = p;
154797          }else{
154798            /* An error occurred. Delete the contents of the apLeaf[] array 
154799            ** and pFree list. Everything else is cleaned up by the call to
154800            ** sqlite3Fts3ExprFree(pRoot) below.  */
154801            Fts3Expr *pDel;
154802            for(i=0; i<nMaxDepth; i++){
154803              sqlite3Fts3ExprFree(apLeaf[i]);
154804            }
154805            while( (pDel=pFree)!=0 ){
154806              pFree = pDel->pParent;
154807              sqlite3_free(pDel);
154808            }
154809          }
154810  
154811          assert( pFree==0 );
154812          sqlite3_free( apLeaf );
154813        }
154814      }else if( eType==FTSQUERY_NOT ){
154815        Fts3Expr *pLeft = pRoot->pLeft;
154816        Fts3Expr *pRight = pRoot->pRight;
154817  
154818        pRoot->pLeft = 0;
154819        pRoot->pRight = 0;
154820        pLeft->pParent = 0;
154821        pRight->pParent = 0;
154822  
154823        rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
154824        if( rc==SQLITE_OK ){
154825          rc = fts3ExprBalance(&pRight, nMaxDepth-1);
154826        }
154827  
154828        if( rc!=SQLITE_OK ){
154829          sqlite3Fts3ExprFree(pRight);
154830          sqlite3Fts3ExprFree(pLeft);
154831        }else{
154832          assert( pLeft && pRight );
154833          pRoot->pLeft = pLeft;
154834          pLeft->pParent = pRoot;
154835          pRoot->pRight = pRight;
154836          pRight->pParent = pRoot;
154837        }
154838      }
154839    }
154840    
154841    if( rc!=SQLITE_OK ){
154842      sqlite3Fts3ExprFree(pRoot);
154843      pRoot = 0;
154844    }
154845    *pp = pRoot;
154846    return rc;
154847  }
154848  
154849  /*
154850  ** This function is similar to sqlite3Fts3ExprParse(), with the following
154851  ** differences:
154852  **
154853  **   1. It does not do expression rebalancing.
154854  **   2. It does not check that the expression does not exceed the 
154855  **      maximum allowable depth.
154856  **   3. Even if it fails, *ppExpr may still be set to point to an 
154857  **      expression tree. It should be deleted using sqlite3Fts3ExprFree()
154858  **      in this case.
154859  */
154860  static int fts3ExprParseUnbalanced(
154861    sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
154862    int iLangid,                        /* Language id for tokenizer */
154863    char **azCol,                       /* Array of column names for fts3 table */
154864    int bFts4,                          /* True to allow FTS4-only syntax */
154865    int nCol,                           /* Number of entries in azCol[] */
154866    int iDefaultCol,                    /* Default column to query */
154867    const char *z, int n,               /* Text of MATCH query */
154868    Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
154869  ){
154870    int nParsed;
154871    int rc;
154872    ParseContext sParse;
154873  
154874    memset(&sParse, 0, sizeof(ParseContext));
154875    sParse.pTokenizer = pTokenizer;
154876    sParse.iLangid = iLangid;
154877    sParse.azCol = (const char **)azCol;
154878    sParse.nCol = nCol;
154879    sParse.iDefaultCol = iDefaultCol;
154880    sParse.bFts4 = bFts4;
154881    if( z==0 ){
154882      *ppExpr = 0;
154883      return SQLITE_OK;
154884    }
154885    if( n<0 ){
154886      n = (int)strlen(z);
154887    }
154888    rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
154889    assert( rc==SQLITE_OK || *ppExpr==0 );
154890  
154891    /* Check for mismatched parenthesis */
154892    if( rc==SQLITE_OK && sParse.nNest ){
154893      rc = SQLITE_ERROR;
154894    }
154895    
154896    return rc;
154897  }
154898  
154899  /*
154900  ** Parameters z and n contain a pointer to and length of a buffer containing
154901  ** an fts3 query expression, respectively. This function attempts to parse the
154902  ** query expression and create a tree of Fts3Expr structures representing the
154903  ** parsed expression. If successful, *ppExpr is set to point to the head
154904  ** of the parsed expression tree and SQLITE_OK is returned. If an error
154905  ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
154906  ** error) is returned and *ppExpr is set to 0.
154907  **
154908  ** If parameter n is a negative number, then z is assumed to point to a
154909  ** nul-terminated string and the length is determined using strlen().
154910  **
154911  ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
154912  ** use to normalize query tokens while parsing the expression. The azCol[]
154913  ** array, which is assumed to contain nCol entries, should contain the names
154914  ** of each column in the target fts3 table, in order from left to right. 
154915  ** Column names must be nul-terminated strings.
154916  **
154917  ** The iDefaultCol parameter should be passed the index of the table column
154918  ** that appears on the left-hand-side of the MATCH operator (the default
154919  ** column to match against for tokens for which a column name is not explicitly
154920  ** specified as part of the query string), or -1 if tokens may by default
154921  ** match any table column.
154922  */
154923  SQLITE_PRIVATE int sqlite3Fts3ExprParse(
154924    sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
154925    int iLangid,                        /* Language id for tokenizer */
154926    char **azCol,                       /* Array of column names for fts3 table */
154927    int bFts4,                          /* True to allow FTS4-only syntax */
154928    int nCol,                           /* Number of entries in azCol[] */
154929    int iDefaultCol,                    /* Default column to query */
154930    const char *z, int n,               /* Text of MATCH query */
154931    Fts3Expr **ppExpr,                  /* OUT: Parsed query structure */
154932    char **pzErr                        /* OUT: Error message (sqlite3_malloc) */
154933  ){
154934    int rc = fts3ExprParseUnbalanced(
154935        pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
154936    );
154937    
154938    /* Rebalance the expression. And check that its depth does not exceed
154939    ** SQLITE_FTS3_MAX_EXPR_DEPTH.  */
154940    if( rc==SQLITE_OK && *ppExpr ){
154941      rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
154942      if( rc==SQLITE_OK ){
154943        rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
154944      }
154945    }
154946  
154947    if( rc!=SQLITE_OK ){
154948      sqlite3Fts3ExprFree(*ppExpr);
154949      *ppExpr = 0;
154950      if( rc==SQLITE_TOOBIG ){
154951        sqlite3Fts3ErrMsg(pzErr,
154952            "FTS expression tree is too large (maximum depth %d)", 
154953            SQLITE_FTS3_MAX_EXPR_DEPTH
154954        );
154955        rc = SQLITE_ERROR;
154956      }else if( rc==SQLITE_ERROR ){
154957        sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
154958      }
154959    }
154960  
154961    return rc;
154962  }
154963  
154964  /*
154965  ** Free a single node of an expression tree.
154966  */
154967  static void fts3FreeExprNode(Fts3Expr *p){
154968    assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
154969    sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
154970    sqlite3_free(p->aMI);
154971    sqlite3_free(p);
154972  }
154973  
154974  /*
154975  ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
154976  **
154977  ** This function would be simpler if it recursively called itself. But
154978  ** that would mean passing a sufficiently large expression to ExprParse()
154979  ** could cause a stack overflow.
154980  */
154981  SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
154982    Fts3Expr *p;
154983    assert( pDel==0 || pDel->pParent==0 );
154984    for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
154985      assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
154986    }
154987    while( p ){
154988      Fts3Expr *pParent = p->pParent;
154989      fts3FreeExprNode(p);
154990      if( pParent && p==pParent->pLeft && pParent->pRight ){
154991        p = pParent->pRight;
154992        while( p && (p->pLeft || p->pRight) ){
154993          assert( p==p->pParent->pRight || p==p->pParent->pLeft );
154994          p = (p->pLeft ? p->pLeft : p->pRight);
154995        }
154996      }else{
154997        p = pParent;
154998      }
154999    }
155000  }
155001  
155002  /****************************************************************************
155003  *****************************************************************************
155004  ** Everything after this point is just test code.
155005  */
155006  
155007  #ifdef SQLITE_TEST
155008  
155009  /* #include <stdio.h> */
155010  
155011  /*
155012  ** Function to query the hash-table of tokenizers (see README.tokenizers).
155013  */
155014  static int queryTestTokenizer(
155015    sqlite3 *db, 
155016    const char *zName,  
155017    const sqlite3_tokenizer_module **pp
155018  ){
155019    int rc;
155020    sqlite3_stmt *pStmt;
155021    const char zSql[] = "SELECT fts3_tokenizer(?)";
155022  
155023    *pp = 0;
155024    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
155025    if( rc!=SQLITE_OK ){
155026      return rc;
155027    }
155028  
155029    sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
155030    if( SQLITE_ROW==sqlite3_step(pStmt) ){
155031      if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
155032        memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
155033      }
155034    }
155035  
155036    return sqlite3_finalize(pStmt);
155037  }
155038  
155039  /*
155040  ** Return a pointer to a buffer containing a text representation of the
155041  ** expression passed as the first argument. The buffer is obtained from
155042  ** sqlite3_malloc(). It is the responsibility of the caller to use 
155043  ** sqlite3_free() to release the memory. If an OOM condition is encountered,
155044  ** NULL is returned.
155045  **
155046  ** If the second argument is not NULL, then its contents are prepended to 
155047  ** the returned expression text and then freed using sqlite3_free().
155048  */
155049  static char *exprToString(Fts3Expr *pExpr, char *zBuf){
155050    if( pExpr==0 ){
155051      return sqlite3_mprintf("");
155052    }
155053    switch( pExpr->eType ){
155054      case FTSQUERY_PHRASE: {
155055        Fts3Phrase *pPhrase = pExpr->pPhrase;
155056        int i;
155057        zBuf = sqlite3_mprintf(
155058            "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
155059        for(i=0; zBuf && i<pPhrase->nToken; i++){
155060          zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, 
155061              pPhrase->aToken[i].n, pPhrase->aToken[i].z,
155062              (pPhrase->aToken[i].isPrefix?"+":"")
155063          );
155064        }
155065        return zBuf;
155066      }
155067  
155068      case FTSQUERY_NEAR:
155069        zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
155070        break;
155071      case FTSQUERY_NOT:
155072        zBuf = sqlite3_mprintf("%zNOT ", zBuf);
155073        break;
155074      case FTSQUERY_AND:
155075        zBuf = sqlite3_mprintf("%zAND ", zBuf);
155076        break;
155077      case FTSQUERY_OR:
155078        zBuf = sqlite3_mprintf("%zOR ", zBuf);
155079        break;
155080    }
155081  
155082    if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
155083    if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
155084    if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
155085  
155086    if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
155087    if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
155088  
155089    return zBuf;
155090  }
155091  
155092  /*
155093  ** This is the implementation of a scalar SQL function used to test the 
155094  ** expression parser. It should be called as follows:
155095  **
155096  **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
155097  **
155098  ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
155099  ** to parse the query expression (see README.tokenizers). The second argument
155100  ** is the query expression to parse. Each subsequent argument is the name
155101  ** of a column of the fts3 table that the query expression may refer to.
155102  ** For example:
155103  **
155104  **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
155105  */
155106  static void fts3ExprTest(
155107    sqlite3_context *context,
155108    int argc,
155109    sqlite3_value **argv
155110  ){
155111    sqlite3_tokenizer_module const *pModule = 0;
155112    sqlite3_tokenizer *pTokenizer = 0;
155113    int rc;
155114    char **azCol = 0;
155115    const char *zExpr;
155116    int nExpr;
155117    int nCol;
155118    int ii;
155119    Fts3Expr *pExpr;
155120    char *zBuf = 0;
155121    sqlite3 *db = sqlite3_context_db_handle(context);
155122  
155123    if( argc<3 ){
155124      sqlite3_result_error(context, 
155125          "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
155126      );
155127      return;
155128    }
155129  
155130    rc = queryTestTokenizer(db,
155131                            (const char *)sqlite3_value_text(argv[0]), &pModule);
155132    if( rc==SQLITE_NOMEM ){
155133      sqlite3_result_error_nomem(context);
155134      goto exprtest_out;
155135    }else if( !pModule ){
155136      sqlite3_result_error(context, "No such tokenizer module", -1);
155137      goto exprtest_out;
155138    }
155139  
155140    rc = pModule->xCreate(0, 0, &pTokenizer);
155141    assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
155142    if( rc==SQLITE_NOMEM ){
155143      sqlite3_result_error_nomem(context);
155144      goto exprtest_out;
155145    }
155146    pTokenizer->pModule = pModule;
155147  
155148    zExpr = (const char *)sqlite3_value_text(argv[1]);
155149    nExpr = sqlite3_value_bytes(argv[1]);
155150    nCol = argc-2;
155151    azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
155152    if( !azCol ){
155153      sqlite3_result_error_nomem(context);
155154      goto exprtest_out;
155155    }
155156    for(ii=0; ii<nCol; ii++){
155157      azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
155158    }
155159  
155160    if( sqlite3_user_data(context) ){
155161      char *zDummy = 0;
155162      rc = sqlite3Fts3ExprParse(
155163          pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
155164      );
155165      assert( rc==SQLITE_OK || pExpr==0 );
155166      sqlite3_free(zDummy);
155167    }else{
155168      rc = fts3ExprParseUnbalanced(
155169          pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
155170      );
155171    }
155172  
155173    if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
155174      sqlite3Fts3ExprFree(pExpr);
155175      sqlite3_result_error(context, "Error parsing expression", -1);
155176    }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
155177      sqlite3_result_error_nomem(context);
155178    }else{
155179      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
155180      sqlite3_free(zBuf);
155181    }
155182  
155183    sqlite3Fts3ExprFree(pExpr);
155184  
155185  exprtest_out:
155186    if( pModule && pTokenizer ){
155187      rc = pModule->xDestroy(pTokenizer);
155188    }
155189    sqlite3_free(azCol);
155190  }
155191  
155192  /*
155193  ** Register the query expression parser test function fts3_exprtest() 
155194  ** with database connection db. 
155195  */
155196  SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
155197    int rc = sqlite3_create_function(
155198        db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
155199    );
155200    if( rc==SQLITE_OK ){
155201      rc = sqlite3_create_function(db, "fts3_exprtest_rebalance", 
155202          -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
155203      );
155204    }
155205    return rc;
155206  }
155207  
155208  #endif
155209  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
155210  
155211  /************** End of fts3_expr.c *******************************************/
155212  /************** Begin file fts3_hash.c ***************************************/
155213  /*
155214  ** 2001 September 22
155215  **
155216  ** The author disclaims copyright to this source code.  In place of
155217  ** a legal notice, here is a blessing:
155218  **
155219  **    May you do good and not evil.
155220  **    May you find forgiveness for yourself and forgive others.
155221  **    May you share freely, never taking more than you give.
155222  **
155223  *************************************************************************
155224  ** This is the implementation of generic hash-tables used in SQLite.
155225  ** We've modified it slightly to serve as a standalone hash table
155226  ** implementation for the full-text indexing module.
155227  */
155228  
155229  /*
155230  ** The code in this file is only compiled if:
155231  **
155232  **     * The FTS3 module is being built as an extension
155233  **       (in which case SQLITE_CORE is not defined), or
155234  **
155235  **     * The FTS3 module is being built into the core of
155236  **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
155237  */
155238  /* #include "fts3Int.h" */
155239  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
155240  
155241  /* #include <assert.h> */
155242  /* #include <stdlib.h> */
155243  /* #include <string.h> */
155244  
155245  /* #include "fts3_hash.h" */
155246  
155247  /*
155248  ** Malloc and Free functions
155249  */
155250  static void *fts3HashMalloc(int n){
155251    void *p = sqlite3_malloc(n);
155252    if( p ){
155253      memset(p, 0, n);
155254    }
155255    return p;
155256  }
155257  static void fts3HashFree(void *p){
155258    sqlite3_free(p);
155259  }
155260  
155261  /* Turn bulk memory into a hash table object by initializing the
155262  ** fields of the Hash structure.
155263  **
155264  ** "pNew" is a pointer to the hash table that is to be initialized.
155265  ** keyClass is one of the constants 
155266  ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
155267  ** determines what kind of key the hash table will use.  "copyKey" is
155268  ** true if the hash table should make its own private copy of keys and
155269  ** false if it should just use the supplied pointer.
155270  */
155271  SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
155272    assert( pNew!=0 );
155273    assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
155274    pNew->keyClass = keyClass;
155275    pNew->copyKey = copyKey;
155276    pNew->first = 0;
155277    pNew->count = 0;
155278    pNew->htsize = 0;
155279    pNew->ht = 0;
155280  }
155281  
155282  /* Remove all entries from a hash table.  Reclaim all memory.
155283  ** Call this routine to delete a hash table or to reset a hash table
155284  ** to the empty state.
155285  */
155286  SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
155287    Fts3HashElem *elem;         /* For looping over all elements of the table */
155288  
155289    assert( pH!=0 );
155290    elem = pH->first;
155291    pH->first = 0;
155292    fts3HashFree(pH->ht);
155293    pH->ht = 0;
155294    pH->htsize = 0;
155295    while( elem ){
155296      Fts3HashElem *next_elem = elem->next;
155297      if( pH->copyKey && elem->pKey ){
155298        fts3HashFree(elem->pKey);
155299      }
155300      fts3HashFree(elem);
155301      elem = next_elem;
155302    }
155303    pH->count = 0;
155304  }
155305  
155306  /*
155307  ** Hash and comparison functions when the mode is FTS3_HASH_STRING
155308  */
155309  static int fts3StrHash(const void *pKey, int nKey){
155310    const char *z = (const char *)pKey;
155311    unsigned h = 0;
155312    if( nKey<=0 ) nKey = (int) strlen(z);
155313    while( nKey > 0  ){
155314      h = (h<<3) ^ h ^ *z++;
155315      nKey--;
155316    }
155317    return (int)(h & 0x7fffffff);
155318  }
155319  static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
155320    if( n1!=n2 ) return 1;
155321    return strncmp((const char*)pKey1,(const char*)pKey2,n1);
155322  }
155323  
155324  /*
155325  ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
155326  */
155327  static int fts3BinHash(const void *pKey, int nKey){
155328    int h = 0;
155329    const char *z = (const char *)pKey;
155330    while( nKey-- > 0 ){
155331      h = (h<<3) ^ h ^ *(z++);
155332    }
155333    return h & 0x7fffffff;
155334  }
155335  static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
155336    if( n1!=n2 ) return 1;
155337    return memcmp(pKey1,pKey2,n1);
155338  }
155339  
155340  /*
155341  ** Return a pointer to the appropriate hash function given the key class.
155342  **
155343  ** The C syntax in this function definition may be unfamilar to some 
155344  ** programmers, so we provide the following additional explanation:
155345  **
155346  ** The name of the function is "ftsHashFunction".  The function takes a
155347  ** single parameter "keyClass".  The return value of ftsHashFunction()
155348  ** is a pointer to another function.  Specifically, the return value
155349  ** of ftsHashFunction() is a pointer to a function that takes two parameters
155350  ** with types "const void*" and "int" and returns an "int".
155351  */
155352  static int (*ftsHashFunction(int keyClass))(const void*,int){
155353    if( keyClass==FTS3_HASH_STRING ){
155354      return &fts3StrHash;
155355    }else{
155356      assert( keyClass==FTS3_HASH_BINARY );
155357      return &fts3BinHash;
155358    }
155359  }
155360  
155361  /*
155362  ** Return a pointer to the appropriate hash function given the key class.
155363  **
155364  ** For help in interpreted the obscure C code in the function definition,
155365  ** see the header comment on the previous function.
155366  */
155367  static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
155368    if( keyClass==FTS3_HASH_STRING ){
155369      return &fts3StrCompare;
155370    }else{
155371      assert( keyClass==FTS3_HASH_BINARY );
155372      return &fts3BinCompare;
155373    }
155374  }
155375  
155376  /* Link an element into the hash table
155377  */
155378  static void fts3HashInsertElement(
155379    Fts3Hash *pH,            /* The complete hash table */
155380    struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
155381    Fts3HashElem *pNew       /* The element to be inserted */
155382  ){
155383    Fts3HashElem *pHead;     /* First element already in pEntry */
155384    pHead = pEntry->chain;
155385    if( pHead ){
155386      pNew->next = pHead;
155387      pNew->prev = pHead->prev;
155388      if( pHead->prev ){ pHead->prev->next = pNew; }
155389      else             { pH->first = pNew; }
155390      pHead->prev = pNew;
155391    }else{
155392      pNew->next = pH->first;
155393      if( pH->first ){ pH->first->prev = pNew; }
155394      pNew->prev = 0;
155395      pH->first = pNew;
155396    }
155397    pEntry->count++;
155398    pEntry->chain = pNew;
155399  }
155400  
155401  
155402  /* Resize the hash table so that it cantains "new_size" buckets.
155403  ** "new_size" must be a power of 2.  The hash table might fail 
155404  ** to resize if sqliteMalloc() fails.
155405  **
155406  ** Return non-zero if a memory allocation error occurs.
155407  */
155408  static int fts3Rehash(Fts3Hash *pH, int new_size){
155409    struct _fts3ht *new_ht;          /* The new hash table */
155410    Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
155411    int (*xHash)(const void*,int);   /* The hash function */
155412  
155413    assert( (new_size & (new_size-1))==0 );
155414    new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
155415    if( new_ht==0 ) return 1;
155416    fts3HashFree(pH->ht);
155417    pH->ht = new_ht;
155418    pH->htsize = new_size;
155419    xHash = ftsHashFunction(pH->keyClass);
155420    for(elem=pH->first, pH->first=0; elem; elem = next_elem){
155421      int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
155422      next_elem = elem->next;
155423      fts3HashInsertElement(pH, &new_ht[h], elem);
155424    }
155425    return 0;
155426  }
155427  
155428  /* This function (for internal use only) locates an element in an
155429  ** hash table that matches the given key.  The hash for this key has
155430  ** already been computed and is passed as the 4th parameter.
155431  */
155432  static Fts3HashElem *fts3FindElementByHash(
155433    const Fts3Hash *pH, /* The pH to be searched */
155434    const void *pKey,   /* The key we are searching for */
155435    int nKey,
155436    int h               /* The hash for this key. */
155437  ){
155438    Fts3HashElem *elem;            /* Used to loop thru the element list */
155439    int count;                     /* Number of elements left to test */
155440    int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
155441  
155442    if( pH->ht ){
155443      struct _fts3ht *pEntry = &pH->ht[h];
155444      elem = pEntry->chain;
155445      count = pEntry->count;
155446      xCompare = ftsCompareFunction(pH->keyClass);
155447      while( count-- && elem ){
155448        if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
155449          return elem;
155450        }
155451        elem = elem->next;
155452      }
155453    }
155454    return 0;
155455  }
155456  
155457  /* Remove a single entry from the hash table given a pointer to that
155458  ** element and a hash on the element's key.
155459  */
155460  static void fts3RemoveElementByHash(
155461    Fts3Hash *pH,         /* The pH containing "elem" */
155462    Fts3HashElem* elem,   /* The element to be removed from the pH */
155463    int h                 /* Hash value for the element */
155464  ){
155465    struct _fts3ht *pEntry;
155466    if( elem->prev ){
155467      elem->prev->next = elem->next; 
155468    }else{
155469      pH->first = elem->next;
155470    }
155471    if( elem->next ){
155472      elem->next->prev = elem->prev;
155473    }
155474    pEntry = &pH->ht[h];
155475    if( pEntry->chain==elem ){
155476      pEntry->chain = elem->next;
155477    }
155478    pEntry->count--;
155479    if( pEntry->count<=0 ){
155480      pEntry->chain = 0;
155481    }
155482    if( pH->copyKey && elem->pKey ){
155483      fts3HashFree(elem->pKey);
155484    }
155485    fts3HashFree( elem );
155486    pH->count--;
155487    if( pH->count<=0 ){
155488      assert( pH->first==0 );
155489      assert( pH->count==0 );
155490      fts3HashClear(pH);
155491    }
155492  }
155493  
155494  SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
155495    const Fts3Hash *pH, 
155496    const void *pKey, 
155497    int nKey
155498  ){
155499    int h;                          /* A hash on key */
155500    int (*xHash)(const void*,int);  /* The hash function */
155501  
155502    if( pH==0 || pH->ht==0 ) return 0;
155503    xHash = ftsHashFunction(pH->keyClass);
155504    assert( xHash!=0 );
155505    h = (*xHash)(pKey,nKey);
155506    assert( (pH->htsize & (pH->htsize-1))==0 );
155507    return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
155508  }
155509  
155510  /* 
155511  ** Attempt to locate an element of the hash table pH with a key
155512  ** that matches pKey,nKey.  Return the data for this element if it is
155513  ** found, or NULL if there is no match.
155514  */
155515  SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
155516    Fts3HashElem *pElem;            /* The element that matches key (if any) */
155517  
155518    pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
155519    return pElem ? pElem->data : 0;
155520  }
155521  
155522  /* Insert an element into the hash table pH.  The key is pKey,nKey
155523  ** and the data is "data".
155524  **
155525  ** If no element exists with a matching key, then a new
155526  ** element is created.  A copy of the key is made if the copyKey
155527  ** flag is set.  NULL is returned.
155528  **
155529  ** If another element already exists with the same key, then the
155530  ** new data replaces the old data and the old data is returned.
155531  ** The key is not copied in this instance.  If a malloc fails, then
155532  ** the new data is returned and the hash table is unchanged.
155533  **
155534  ** If the "data" parameter to this function is NULL, then the
155535  ** element corresponding to "key" is removed from the hash table.
155536  */
155537  SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
155538    Fts3Hash *pH,        /* The hash table to insert into */
155539    const void *pKey,    /* The key */
155540    int nKey,            /* Number of bytes in the key */
155541    void *data           /* The data */
155542  ){
155543    int hraw;                 /* Raw hash value of the key */
155544    int h;                    /* the hash of the key modulo hash table size */
155545    Fts3HashElem *elem;       /* Used to loop thru the element list */
155546    Fts3HashElem *new_elem;   /* New element added to the pH */
155547    int (*xHash)(const void*,int);  /* The hash function */
155548  
155549    assert( pH!=0 );
155550    xHash = ftsHashFunction(pH->keyClass);
155551    assert( xHash!=0 );
155552    hraw = (*xHash)(pKey, nKey);
155553    assert( (pH->htsize & (pH->htsize-1))==0 );
155554    h = hraw & (pH->htsize-1);
155555    elem = fts3FindElementByHash(pH,pKey,nKey,h);
155556    if( elem ){
155557      void *old_data = elem->data;
155558      if( data==0 ){
155559        fts3RemoveElementByHash(pH,elem,h);
155560      }else{
155561        elem->data = data;
155562      }
155563      return old_data;
155564    }
155565    if( data==0 ) return 0;
155566    if( (pH->htsize==0 && fts3Rehash(pH,8))
155567     || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
155568    ){
155569      pH->count = 0;
155570      return data;
155571    }
155572    assert( pH->htsize>0 );
155573    new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
155574    if( new_elem==0 ) return data;
155575    if( pH->copyKey && pKey!=0 ){
155576      new_elem->pKey = fts3HashMalloc( nKey );
155577      if( new_elem->pKey==0 ){
155578        fts3HashFree(new_elem);
155579        return data;
155580      }
155581      memcpy((void*)new_elem->pKey, pKey, nKey);
155582    }else{
155583      new_elem->pKey = (void*)pKey;
155584    }
155585    new_elem->nKey = nKey;
155586    pH->count++;
155587    assert( pH->htsize>0 );
155588    assert( (pH->htsize & (pH->htsize-1))==0 );
155589    h = hraw & (pH->htsize-1);
155590    fts3HashInsertElement(pH, &pH->ht[h], new_elem);
155591    new_elem->data = data;
155592    return 0;
155593  }
155594  
155595  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
155596  
155597  /************** End of fts3_hash.c *******************************************/
155598  /************** Begin file fts3_porter.c *************************************/
155599  /*
155600  ** 2006 September 30
155601  **
155602  ** The author disclaims copyright to this source code.  In place of
155603  ** a legal notice, here is a blessing:
155604  **
155605  **    May you do good and not evil.
155606  **    May you find forgiveness for yourself and forgive others.
155607  **    May you share freely, never taking more than you give.
155608  **
155609  *************************************************************************
155610  ** Implementation of the full-text-search tokenizer that implements
155611  ** a Porter stemmer.
155612  */
155613  
155614  /*
155615  ** The code in this file is only compiled if:
155616  **
155617  **     * The FTS3 module is being built as an extension
155618  **       (in which case SQLITE_CORE is not defined), or
155619  **
155620  **     * The FTS3 module is being built into the core of
155621  **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
155622  */
155623  /* #include "fts3Int.h" */
155624  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
155625  
155626  /* #include <assert.h> */
155627  /* #include <stdlib.h> */
155628  /* #include <stdio.h> */
155629  /* #include <string.h> */
155630  
155631  /* #include "fts3_tokenizer.h" */
155632  
155633  /*
155634  ** Class derived from sqlite3_tokenizer
155635  */
155636  typedef struct porter_tokenizer {
155637    sqlite3_tokenizer base;      /* Base class */
155638  } porter_tokenizer;
155639  
155640  /*
155641  ** Class derived from sqlite3_tokenizer_cursor
155642  */
155643  typedef struct porter_tokenizer_cursor {
155644    sqlite3_tokenizer_cursor base;
155645    const char *zInput;          /* input we are tokenizing */
155646    int nInput;                  /* size of the input */
155647    int iOffset;                 /* current position in zInput */
155648    int iToken;                  /* index of next token to be returned */
155649    char *zToken;                /* storage for current token */
155650    int nAllocated;              /* space allocated to zToken buffer */
155651  } porter_tokenizer_cursor;
155652  
155653  
155654  /*
155655  ** Create a new tokenizer instance.
155656  */
155657  static int porterCreate(
155658    int argc, const char * const *argv,
155659    sqlite3_tokenizer **ppTokenizer
155660  ){
155661    porter_tokenizer *t;
155662  
155663    UNUSED_PARAMETER(argc);
155664    UNUSED_PARAMETER(argv);
155665  
155666    t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
155667    if( t==NULL ) return SQLITE_NOMEM;
155668    memset(t, 0, sizeof(*t));
155669    *ppTokenizer = &t->base;
155670    return SQLITE_OK;
155671  }
155672  
155673  /*
155674  ** Destroy a tokenizer
155675  */
155676  static int porterDestroy(sqlite3_tokenizer *pTokenizer){
155677    sqlite3_free(pTokenizer);
155678    return SQLITE_OK;
155679  }
155680  
155681  /*
155682  ** Prepare to begin tokenizing a particular string.  The input
155683  ** string to be tokenized is zInput[0..nInput-1].  A cursor
155684  ** used to incrementally tokenize this string is returned in 
155685  ** *ppCursor.
155686  */
155687  static int porterOpen(
155688    sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
155689    const char *zInput, int nInput,        /* String to be tokenized */
155690    sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
155691  ){
155692    porter_tokenizer_cursor *c;
155693  
155694    UNUSED_PARAMETER(pTokenizer);
155695  
155696    c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
155697    if( c==NULL ) return SQLITE_NOMEM;
155698  
155699    c->zInput = zInput;
155700    if( zInput==0 ){
155701      c->nInput = 0;
155702    }else if( nInput<0 ){
155703      c->nInput = (int)strlen(zInput);
155704    }else{
155705      c->nInput = nInput;
155706    }
155707    c->iOffset = 0;                 /* start tokenizing at the beginning */
155708    c->iToken = 0;
155709    c->zToken = NULL;               /* no space allocated, yet. */
155710    c->nAllocated = 0;
155711  
155712    *ppCursor = &c->base;
155713    return SQLITE_OK;
155714  }
155715  
155716  /*
155717  ** Close a tokenization cursor previously opened by a call to
155718  ** porterOpen() above.
155719  */
155720  static int porterClose(sqlite3_tokenizer_cursor *pCursor){
155721    porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
155722    sqlite3_free(c->zToken);
155723    sqlite3_free(c);
155724    return SQLITE_OK;
155725  }
155726  /*
155727  ** Vowel or consonant
155728  */
155729  static const char cType[] = {
155730     0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
155731     1, 1, 1, 2, 1
155732  };
155733  
155734  /*
155735  ** isConsonant() and isVowel() determine if their first character in
155736  ** the string they point to is a consonant or a vowel, according
155737  ** to Porter ruls.  
155738  **
155739  ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
155740  ** 'Y' is a consonant unless it follows another consonant,
155741  ** in which case it is a vowel.
155742  **
155743  ** In these routine, the letters are in reverse order.  So the 'y' rule
155744  ** is that 'y' is a consonant unless it is followed by another
155745  ** consonent.
155746  */
155747  static int isVowel(const char*);
155748  static int isConsonant(const char *z){
155749    int j;
155750    char x = *z;
155751    if( x==0 ) return 0;
155752    assert( x>='a' && x<='z' );
155753    j = cType[x-'a'];
155754    if( j<2 ) return j;
155755    return z[1]==0 || isVowel(z + 1);
155756  }
155757  static int isVowel(const char *z){
155758    int j;
155759    char x = *z;
155760    if( x==0 ) return 0;
155761    assert( x>='a' && x<='z' );
155762    j = cType[x-'a'];
155763    if( j<2 ) return 1-j;
155764    return isConsonant(z + 1);
155765  }
155766  
155767  /*
155768  ** Let any sequence of one or more vowels be represented by V and let
155769  ** C be sequence of one or more consonants.  Then every word can be
155770  ** represented as:
155771  **
155772  **           [C] (VC){m} [V]
155773  **
155774  ** In prose:  A word is an optional consonant followed by zero or
155775  ** vowel-consonant pairs followed by an optional vowel.  "m" is the
155776  ** number of vowel consonant pairs.  This routine computes the value
155777  ** of m for the first i bytes of a word.
155778  **
155779  ** Return true if the m-value for z is 1 or more.  In other words,
155780  ** return true if z contains at least one vowel that is followed
155781  ** by a consonant.
155782  **
155783  ** In this routine z[] is in reverse order.  So we are really looking
155784  ** for an instance of a consonant followed by a vowel.
155785  */
155786  static int m_gt_0(const char *z){
155787    while( isVowel(z) ){ z++; }
155788    if( *z==0 ) return 0;
155789    while( isConsonant(z) ){ z++; }
155790    return *z!=0;
155791  }
155792  
155793  /* Like mgt0 above except we are looking for a value of m which is
155794  ** exactly 1
155795  */
155796  static int m_eq_1(const char *z){
155797    while( isVowel(z) ){ z++; }
155798    if( *z==0 ) return 0;
155799    while( isConsonant(z) ){ z++; }
155800    if( *z==0 ) return 0;
155801    while( isVowel(z) ){ z++; }
155802    if( *z==0 ) return 1;
155803    while( isConsonant(z) ){ z++; }
155804    return *z==0;
155805  }
155806  
155807  /* Like mgt0 above except we are looking for a value of m>1 instead
155808  ** or m>0
155809  */
155810  static int m_gt_1(const char *z){
155811    while( isVowel(z) ){ z++; }
155812    if( *z==0 ) return 0;
155813    while( isConsonant(z) ){ z++; }
155814    if( *z==0 ) return 0;
155815    while( isVowel(z) ){ z++; }
155816    if( *z==0 ) return 0;
155817    while( isConsonant(z) ){ z++; }
155818    return *z!=0;
155819  }
155820  
155821  /*
155822  ** Return TRUE if there is a vowel anywhere within z[0..n-1]
155823  */
155824  static int hasVowel(const char *z){
155825    while( isConsonant(z) ){ z++; }
155826    return *z!=0;
155827  }
155828  
155829  /*
155830  ** Return TRUE if the word ends in a double consonant.
155831  **
155832  ** The text is reversed here. So we are really looking at
155833  ** the first two characters of z[].
155834  */
155835  static int doubleConsonant(const char *z){
155836    return isConsonant(z) && z[0]==z[1];
155837  }
155838  
155839  /*
155840  ** Return TRUE if the word ends with three letters which
155841  ** are consonant-vowel-consonent and where the final consonant
155842  ** is not 'w', 'x', or 'y'.
155843  **
155844  ** The word is reversed here.  So we are really checking the
155845  ** first three letters and the first one cannot be in [wxy].
155846  */
155847  static int star_oh(const char *z){
155848    return
155849      isConsonant(z) &&
155850      z[0]!='w' && z[0]!='x' && z[0]!='y' &&
155851      isVowel(z+1) &&
155852      isConsonant(z+2);
155853  }
155854  
155855  /*
155856  ** If the word ends with zFrom and xCond() is true for the stem
155857  ** of the word that preceeds the zFrom ending, then change the 
155858  ** ending to zTo.
155859  **
155860  ** The input word *pz and zFrom are both in reverse order.  zTo
155861  ** is in normal order. 
155862  **
155863  ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
155864  ** match.  Not that TRUE is returned even if xCond() fails and
155865  ** no substitution occurs.
155866  */
155867  static int stem(
155868    char **pz,             /* The word being stemmed (Reversed) */
155869    const char *zFrom,     /* If the ending matches this... (Reversed) */
155870    const char *zTo,       /* ... change the ending to this (not reversed) */
155871    int (*xCond)(const char*)   /* Condition that must be true */
155872  ){
155873    char *z = *pz;
155874    while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
155875    if( *zFrom!=0 ) return 0;
155876    if( xCond && !xCond(z) ) return 1;
155877    while( *zTo ){
155878      *(--z) = *(zTo++);
155879    }
155880    *pz = z;
155881    return 1;
155882  }
155883  
155884  /*
155885  ** This is the fallback stemmer used when the porter stemmer is
155886  ** inappropriate.  The input word is copied into the output with
155887  ** US-ASCII case folding.  If the input word is too long (more
155888  ** than 20 bytes if it contains no digits or more than 6 bytes if
155889  ** it contains digits) then word is truncated to 20 or 6 bytes
155890  ** by taking 10 or 3 bytes from the beginning and end.
155891  */
155892  static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
155893    int i, mx, j;
155894    int hasDigit = 0;
155895    for(i=0; i<nIn; i++){
155896      char c = zIn[i];
155897      if( c>='A' && c<='Z' ){
155898        zOut[i] = c - 'A' + 'a';
155899      }else{
155900        if( c>='0' && c<='9' ) hasDigit = 1;
155901        zOut[i] = c;
155902      }
155903    }
155904    mx = hasDigit ? 3 : 10;
155905    if( nIn>mx*2 ){
155906      for(j=mx, i=nIn-mx; i<nIn; i++, j++){
155907        zOut[j] = zOut[i];
155908      }
155909      i = j;
155910    }
155911    zOut[i] = 0;
155912    *pnOut = i;
155913  }
155914  
155915  
155916  /*
155917  ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
155918  ** zOut is at least big enough to hold nIn bytes.  Write the actual
155919  ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
155920  **
155921  ** Any upper-case characters in the US-ASCII character set ([A-Z])
155922  ** are converted to lower case.  Upper-case UTF characters are
155923  ** unchanged.
155924  **
155925  ** Words that are longer than about 20 bytes are stemmed by retaining
155926  ** a few bytes from the beginning and the end of the word.  If the
155927  ** word contains digits, 3 bytes are taken from the beginning and
155928  ** 3 bytes from the end.  For long words without digits, 10 bytes
155929  ** are taken from each end.  US-ASCII case folding still applies.
155930  ** 
155931  ** If the input word contains not digits but does characters not 
155932  ** in [a-zA-Z] then no stemming is attempted and this routine just 
155933  ** copies the input into the input into the output with US-ASCII
155934  ** case folding.
155935  **
155936  ** Stemming never increases the length of the word.  So there is
155937  ** no chance of overflowing the zOut buffer.
155938  */
155939  static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
155940    int i, j;
155941    char zReverse[28];
155942    char *z, *z2;
155943    if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
155944      /* The word is too big or too small for the porter stemmer.
155945      ** Fallback to the copy stemmer */
155946      copy_stemmer(zIn, nIn, zOut, pnOut);
155947      return;
155948    }
155949    for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
155950      char c = zIn[i];
155951      if( c>='A' && c<='Z' ){
155952        zReverse[j] = c + 'a' - 'A';
155953      }else if( c>='a' && c<='z' ){
155954        zReverse[j] = c;
155955      }else{
155956        /* The use of a character not in [a-zA-Z] means that we fallback
155957        ** to the copy stemmer */
155958        copy_stemmer(zIn, nIn, zOut, pnOut);
155959        return;
155960      }
155961    }
155962    memset(&zReverse[sizeof(zReverse)-5], 0, 5);
155963    z = &zReverse[j+1];
155964  
155965  
155966    /* Step 1a */
155967    if( z[0]=='s' ){
155968      if(
155969       !stem(&z, "sess", "ss", 0) &&
155970       !stem(&z, "sei", "i", 0)  &&
155971       !stem(&z, "ss", "ss", 0)
155972      ){
155973        z++;
155974      }
155975    }
155976  
155977    /* Step 1b */  
155978    z2 = z;
155979    if( stem(&z, "dee", "ee", m_gt_0) ){
155980      /* Do nothing.  The work was all in the test */
155981    }else if( 
155982       (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
155983        && z!=z2
155984    ){
155985       if( stem(&z, "ta", "ate", 0) ||
155986           stem(&z, "lb", "ble", 0) ||
155987           stem(&z, "zi", "ize", 0) ){
155988         /* Do nothing.  The work was all in the test */
155989       }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
155990         z++;
155991       }else if( m_eq_1(z) && star_oh(z) ){
155992         *(--z) = 'e';
155993       }
155994    }
155995  
155996    /* Step 1c */
155997    if( z[0]=='y' && hasVowel(z+1) ){
155998      z[0] = 'i';
155999    }
156000  
156001    /* Step 2 */
156002    switch( z[1] ){
156003     case 'a':
156004       if( !stem(&z, "lanoita", "ate", m_gt_0) ){
156005         stem(&z, "lanoit", "tion", m_gt_0);
156006       }
156007       break;
156008     case 'c':
156009       if( !stem(&z, "icne", "ence", m_gt_0) ){
156010         stem(&z, "icna", "ance", m_gt_0);
156011       }
156012       break;
156013     case 'e':
156014       stem(&z, "rezi", "ize", m_gt_0);
156015       break;
156016     case 'g':
156017       stem(&z, "igol", "log", m_gt_0);
156018       break;
156019     case 'l':
156020       if( !stem(&z, "ilb", "ble", m_gt_0) 
156021        && !stem(&z, "illa", "al", m_gt_0)
156022        && !stem(&z, "iltne", "ent", m_gt_0)
156023        && !stem(&z, "ile", "e", m_gt_0)
156024       ){
156025         stem(&z, "ilsuo", "ous", m_gt_0);
156026       }
156027       break;
156028     case 'o':
156029       if( !stem(&z, "noitazi", "ize", m_gt_0)
156030        && !stem(&z, "noita", "ate", m_gt_0)
156031       ){
156032         stem(&z, "rota", "ate", m_gt_0);
156033       }
156034       break;
156035     case 's':
156036       if( !stem(&z, "msila", "al", m_gt_0)
156037        && !stem(&z, "ssenevi", "ive", m_gt_0)
156038        && !stem(&z, "ssenluf", "ful", m_gt_0)
156039       ){
156040         stem(&z, "ssensuo", "ous", m_gt_0);
156041       }
156042       break;
156043     case 't':
156044       if( !stem(&z, "itila", "al", m_gt_0)
156045        && !stem(&z, "itivi", "ive", m_gt_0)
156046       ){
156047         stem(&z, "itilib", "ble", m_gt_0);
156048       }
156049       break;
156050    }
156051  
156052    /* Step 3 */
156053    switch( z[0] ){
156054     case 'e':
156055       if( !stem(&z, "etaci", "ic", m_gt_0)
156056        && !stem(&z, "evita", "", m_gt_0)
156057       ){
156058         stem(&z, "ezila", "al", m_gt_0);
156059       }
156060       break;
156061     case 'i':
156062       stem(&z, "itici", "ic", m_gt_0);
156063       break;
156064     case 'l':
156065       if( !stem(&z, "laci", "ic", m_gt_0) ){
156066         stem(&z, "luf", "", m_gt_0);
156067       }
156068       break;
156069     case 's':
156070       stem(&z, "ssen", "", m_gt_0);
156071       break;
156072    }
156073  
156074    /* Step 4 */
156075    switch( z[1] ){
156076     case 'a':
156077       if( z[0]=='l' && m_gt_1(z+2) ){
156078         z += 2;
156079       }
156080       break;
156081     case 'c':
156082       if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
156083         z += 4;
156084       }
156085       break;
156086     case 'e':
156087       if( z[0]=='r' && m_gt_1(z+2) ){
156088         z += 2;
156089       }
156090       break;
156091     case 'i':
156092       if( z[0]=='c' && m_gt_1(z+2) ){
156093         z += 2;
156094       }
156095       break;
156096     case 'l':
156097       if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
156098         z += 4;
156099       }
156100       break;
156101     case 'n':
156102       if( z[0]=='t' ){
156103         if( z[2]=='a' ){
156104           if( m_gt_1(z+3) ){
156105             z += 3;
156106           }
156107         }else if( z[2]=='e' ){
156108           if( !stem(&z, "tneme", "", m_gt_1)
156109            && !stem(&z, "tnem", "", m_gt_1)
156110           ){
156111             stem(&z, "tne", "", m_gt_1);
156112           }
156113         }
156114       }
156115       break;
156116     case 'o':
156117       if( z[0]=='u' ){
156118         if( m_gt_1(z+2) ){
156119           z += 2;
156120         }
156121       }else if( z[3]=='s' || z[3]=='t' ){
156122         stem(&z, "noi", "", m_gt_1);
156123       }
156124       break;
156125     case 's':
156126       if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
156127         z += 3;
156128       }
156129       break;
156130     case 't':
156131       if( !stem(&z, "eta", "", m_gt_1) ){
156132         stem(&z, "iti", "", m_gt_1);
156133       }
156134       break;
156135     case 'u':
156136       if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
156137         z += 3;
156138       }
156139       break;
156140     case 'v':
156141     case 'z':
156142       if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
156143         z += 3;
156144       }
156145       break;
156146    }
156147  
156148    /* Step 5a */
156149    if( z[0]=='e' ){
156150      if( m_gt_1(z+1) ){
156151        z++;
156152      }else if( m_eq_1(z+1) && !star_oh(z+1) ){
156153        z++;
156154      }
156155    }
156156  
156157    /* Step 5b */
156158    if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
156159      z++;
156160    }
156161  
156162    /* z[] is now the stemmed word in reverse order.  Flip it back
156163    ** around into forward order and return.
156164    */
156165    *pnOut = i = (int)strlen(z);
156166    zOut[i] = 0;
156167    while( *z ){
156168      zOut[--i] = *(z++);
156169    }
156170  }
156171  
156172  /*
156173  ** Characters that can be part of a token.  We assume any character
156174  ** whose value is greater than 0x80 (any UTF character) can be
156175  ** part of a token.  In other words, delimiters all must have
156176  ** values of 0x7f or lower.
156177  */
156178  static const char porterIdChar[] = {
156179  /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
156180      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
156181      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
156182      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
156183      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
156184      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
156185  };
156186  #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
156187  
156188  /*
156189  ** Extract the next token from a tokenization cursor.  The cursor must
156190  ** have been opened by a prior call to porterOpen().
156191  */
156192  static int porterNext(
156193    sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
156194    const char **pzToken,               /* OUT: *pzToken is the token text */
156195    int *pnBytes,                       /* OUT: Number of bytes in token */
156196    int *piStartOffset,                 /* OUT: Starting offset of token */
156197    int *piEndOffset,                   /* OUT: Ending offset of token */
156198    int *piPosition                     /* OUT: Position integer of token */
156199  ){
156200    porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
156201    const char *z = c->zInput;
156202  
156203    while( c->iOffset<c->nInput ){
156204      int iStartOffset, ch;
156205  
156206      /* Scan past delimiter characters */
156207      while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
156208        c->iOffset++;
156209      }
156210  
156211      /* Count non-delimiter characters. */
156212      iStartOffset = c->iOffset;
156213      while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
156214        c->iOffset++;
156215      }
156216  
156217      if( c->iOffset>iStartOffset ){
156218        int n = c->iOffset-iStartOffset;
156219        if( n>c->nAllocated ){
156220          char *pNew;
156221          c->nAllocated = n+20;
156222          pNew = sqlite3_realloc(c->zToken, c->nAllocated);
156223          if( !pNew ) return SQLITE_NOMEM;
156224          c->zToken = pNew;
156225        }
156226        porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
156227        *pzToken = c->zToken;
156228        *piStartOffset = iStartOffset;
156229        *piEndOffset = c->iOffset;
156230        *piPosition = c->iToken++;
156231        return SQLITE_OK;
156232      }
156233    }
156234    return SQLITE_DONE;
156235  }
156236  
156237  /*
156238  ** The set of routines that implement the porter-stemmer tokenizer
156239  */
156240  static const sqlite3_tokenizer_module porterTokenizerModule = {
156241    0,
156242    porterCreate,
156243    porterDestroy,
156244    porterOpen,
156245    porterClose,
156246    porterNext,
156247    0
156248  };
156249  
156250  /*
156251  ** Allocate a new porter tokenizer.  Return a pointer to the new
156252  ** tokenizer in *ppModule
156253  */
156254  SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
156255    sqlite3_tokenizer_module const**ppModule
156256  ){
156257    *ppModule = &porterTokenizerModule;
156258  }
156259  
156260  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
156261  
156262  /************** End of fts3_porter.c *****************************************/
156263  /************** Begin file fts3_tokenizer.c **********************************/
156264  /*
156265  ** 2007 June 22
156266  **
156267  ** The author disclaims copyright to this source code.  In place of
156268  ** a legal notice, here is a blessing:
156269  **
156270  **    May you do good and not evil.
156271  **    May you find forgiveness for yourself and forgive others.
156272  **    May you share freely, never taking more than you give.
156273  **
156274  ******************************************************************************
156275  **
156276  ** This is part of an SQLite module implementing full-text search.
156277  ** This particular file implements the generic tokenizer interface.
156278  */
156279  
156280  /*
156281  ** The code in this file is only compiled if:
156282  **
156283  **     * The FTS3 module is being built as an extension
156284  **       (in which case SQLITE_CORE is not defined), or
156285  **
156286  **     * The FTS3 module is being built into the core of
156287  **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
156288  */
156289  /* #include "fts3Int.h" */
156290  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
156291  
156292  /* #include <assert.h> */
156293  /* #include <string.h> */
156294  
156295  /*
156296  ** Return true if the two-argument version of fts3_tokenizer()
156297  ** has been activated via a prior call to sqlite3_db_config(db,
156298  ** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
156299  */
156300  static int fts3TokenizerEnabled(sqlite3_context *context){
156301    sqlite3 *db = sqlite3_context_db_handle(context);
156302    int isEnabled = 0;
156303    sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
156304    return isEnabled;
156305  }
156306  
156307  /*
156308  ** Implementation of the SQL scalar function for accessing the underlying 
156309  ** hash table. This function may be called as follows:
156310  **
156311  **   SELECT <function-name>(<key-name>);
156312  **   SELECT <function-name>(<key-name>, <pointer>);
156313  **
156314  ** where <function-name> is the name passed as the second argument
156315  ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
156316  **
156317  ** If the <pointer> argument is specified, it must be a blob value
156318  ** containing a pointer to be stored as the hash data corresponding
156319  ** to the string <key-name>. If <pointer> is not specified, then
156320  ** the string <key-name> must already exist in the has table. Otherwise,
156321  ** an error is returned.
156322  **
156323  ** Whether or not the <pointer> argument is specified, the value returned
156324  ** is a blob containing the pointer stored as the hash data corresponding
156325  ** to string <key-name> (after the hash-table is updated, if applicable).
156326  */
156327  static void fts3TokenizerFunc(
156328    sqlite3_context *context,
156329    int argc,
156330    sqlite3_value **argv
156331  ){
156332    Fts3Hash *pHash;
156333    void *pPtr = 0;
156334    const unsigned char *zName;
156335    int nName;
156336  
156337    assert( argc==1 || argc==2 );
156338  
156339    pHash = (Fts3Hash *)sqlite3_user_data(context);
156340  
156341    zName = sqlite3_value_text(argv[0]);
156342    nName = sqlite3_value_bytes(argv[0])+1;
156343  
156344    if( argc==2 ){
156345      if( fts3TokenizerEnabled(context) ){
156346        void *pOld;
156347        int n = sqlite3_value_bytes(argv[1]);
156348        if( zName==0 || n!=sizeof(pPtr) ){
156349          sqlite3_result_error(context, "argument type mismatch", -1);
156350          return;
156351        }
156352        pPtr = *(void **)sqlite3_value_blob(argv[1]);
156353        pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
156354        if( pOld==pPtr ){
156355          sqlite3_result_error(context, "out of memory", -1);
156356        }
156357      }else{
156358        sqlite3_result_error(context, "fts3tokenize disabled", -1);
156359        return;
156360      }
156361    }else{
156362      if( zName ){
156363        pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
156364      }
156365      if( !pPtr ){
156366        char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
156367        sqlite3_result_error(context, zErr, -1);
156368        sqlite3_free(zErr);
156369        return;
156370      }
156371    }
156372    sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
156373  }
156374  
156375  SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
156376    static const char isFtsIdChar[] = {
156377        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
156378        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
156379        0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
156380        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
156381        0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
156382        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
156383        0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
156384        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
156385    };
156386    return (c&0x80 || isFtsIdChar[(int)(c)]);
156387  }
156388  
156389  SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
156390    const char *z1;
156391    const char *z2 = 0;
156392  
156393    /* Find the start of the next token. */
156394    z1 = zStr;
156395    while( z2==0 ){
156396      char c = *z1;
156397      switch( c ){
156398        case '\0': return 0;        /* No more tokens here */
156399        case '\'':
156400        case '"':
156401        case '`': {
156402          z2 = z1;
156403          while( *++z2 && (*z2!=c || *++z2==c) );
156404          break;
156405        }
156406        case '[':
156407          z2 = &z1[1];
156408          while( *z2 && z2[0]!=']' ) z2++;
156409          if( *z2 ) z2++;
156410          break;
156411  
156412        default:
156413          if( sqlite3Fts3IsIdChar(*z1) ){
156414            z2 = &z1[1];
156415            while( sqlite3Fts3IsIdChar(*z2) ) z2++;
156416          }else{
156417            z1++;
156418          }
156419      }
156420    }
156421  
156422    *pn = (int)(z2-z1);
156423    return z1;
156424  }
156425  
156426  SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
156427    Fts3Hash *pHash,                /* Tokenizer hash table */
156428    const char *zArg,               /* Tokenizer name */
156429    sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
156430    char **pzErr                    /* OUT: Set to malloced error message */
156431  ){
156432    int rc;
156433    char *z = (char *)zArg;
156434    int n = 0;
156435    char *zCopy;
156436    char *zEnd;                     /* Pointer to nul-term of zCopy */
156437    sqlite3_tokenizer_module *m;
156438  
156439    zCopy = sqlite3_mprintf("%s", zArg);
156440    if( !zCopy ) return SQLITE_NOMEM;
156441    zEnd = &zCopy[strlen(zCopy)];
156442  
156443    z = (char *)sqlite3Fts3NextToken(zCopy, &n);
156444    if( z==0 ){
156445      assert( n==0 );
156446      z = zCopy;
156447    }
156448    z[n] = '\0';
156449    sqlite3Fts3Dequote(z);
156450  
156451    m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
156452    if( !m ){
156453      sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
156454      rc = SQLITE_ERROR;
156455    }else{
156456      char const **aArg = 0;
156457      int iArg = 0;
156458      z = &z[n+1];
156459      while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
156460        int nNew = sizeof(char *)*(iArg+1);
156461        char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
156462        if( !aNew ){
156463          sqlite3_free(zCopy);
156464          sqlite3_free((void *)aArg);
156465          return SQLITE_NOMEM;
156466        }
156467        aArg = aNew;
156468        aArg[iArg++] = z;
156469        z[n] = '\0';
156470        sqlite3Fts3Dequote(z);
156471        z = &z[n+1];
156472      }
156473      rc = m->xCreate(iArg, aArg, ppTok);
156474      assert( rc!=SQLITE_OK || *ppTok );
156475      if( rc!=SQLITE_OK ){
156476        sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
156477      }else{
156478        (*ppTok)->pModule = m; 
156479      }
156480      sqlite3_free((void *)aArg);
156481    }
156482  
156483    sqlite3_free(zCopy);
156484    return rc;
156485  }
156486  
156487  
156488  #ifdef SQLITE_TEST
156489  
156490  #if defined(INCLUDE_SQLITE_TCL_H)
156491  #  include "sqlite_tcl.h"
156492  #else
156493  #  include "tcl.h"
156494  #endif
156495  /* #include <string.h> */
156496  
156497  /*
156498  ** Implementation of a special SQL scalar function for testing tokenizers 
156499  ** designed to be used in concert with the Tcl testing framework. This
156500  ** function must be called with two or more arguments:
156501  **
156502  **   SELECT <function-name>(<key-name>, ..., <input-string>);
156503  **
156504  ** where <function-name> is the name passed as the second argument
156505  ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
156506  ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
156507  **
156508  ** The return value is a string that may be interpreted as a Tcl
156509  ** list. For each token in the <input-string>, three elements are
156510  ** added to the returned list. The first is the token position, the 
156511  ** second is the token text (folded, stemmed, etc.) and the third is the
156512  ** substring of <input-string> associated with the token. For example, 
156513  ** using the built-in "simple" tokenizer:
156514  **
156515  **   SELECT fts_tokenizer_test('simple', 'I don't see how');
156516  **
156517  ** will return the string:
156518  **
156519  **   "{0 i I 1 dont don't 2 see see 3 how how}"
156520  **   
156521  */
156522  static void testFunc(
156523    sqlite3_context *context,
156524    int argc,
156525    sqlite3_value **argv
156526  ){
156527    Fts3Hash *pHash;
156528    sqlite3_tokenizer_module *p;
156529    sqlite3_tokenizer *pTokenizer = 0;
156530    sqlite3_tokenizer_cursor *pCsr = 0;
156531  
156532    const char *zErr = 0;
156533  
156534    const char *zName;
156535    int nName;
156536    const char *zInput;
156537    int nInput;
156538  
156539    const char *azArg[64];
156540  
156541    const char *zToken;
156542    int nToken = 0;
156543    int iStart = 0;
156544    int iEnd = 0;
156545    int iPos = 0;
156546    int i;
156547  
156548    Tcl_Obj *pRet;
156549  
156550    if( argc<2 ){
156551      sqlite3_result_error(context, "insufficient arguments", -1);
156552      return;
156553    }
156554  
156555    nName = sqlite3_value_bytes(argv[0]);
156556    zName = (const char *)sqlite3_value_text(argv[0]);
156557    nInput = sqlite3_value_bytes(argv[argc-1]);
156558    zInput = (const char *)sqlite3_value_text(argv[argc-1]);
156559  
156560    pHash = (Fts3Hash *)sqlite3_user_data(context);
156561    p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
156562  
156563    if( !p ){
156564      char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
156565      sqlite3_result_error(context, zErr2, -1);
156566      sqlite3_free(zErr2);
156567      return;
156568    }
156569  
156570    pRet = Tcl_NewObj();
156571    Tcl_IncrRefCount(pRet);
156572  
156573    for(i=1; i<argc-1; i++){
156574      azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
156575    }
156576  
156577    if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
156578      zErr = "error in xCreate()";
156579      goto finish;
156580    }
156581    pTokenizer->pModule = p;
156582    if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
156583      zErr = "error in xOpen()";
156584      goto finish;
156585    }
156586  
156587    while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
156588      Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
156589      Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
156590      zToken = &zInput[iStart];
156591      nToken = iEnd-iStart;
156592      Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
156593    }
156594  
156595    if( SQLITE_OK!=p->xClose(pCsr) ){
156596      zErr = "error in xClose()";
156597      goto finish;
156598    }
156599    if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
156600      zErr = "error in xDestroy()";
156601      goto finish;
156602    }
156603  
156604  finish:
156605    if( zErr ){
156606      sqlite3_result_error(context, zErr, -1);
156607    }else{
156608      sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
156609    }
156610    Tcl_DecrRefCount(pRet);
156611  }
156612  
156613  static
156614  int registerTokenizer(
156615    sqlite3 *db, 
156616    char *zName, 
156617    const sqlite3_tokenizer_module *p
156618  ){
156619    int rc;
156620    sqlite3_stmt *pStmt;
156621    const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
156622  
156623    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
156624    if( rc!=SQLITE_OK ){
156625      return rc;
156626    }
156627  
156628    sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
156629    sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
156630    sqlite3_step(pStmt);
156631  
156632    return sqlite3_finalize(pStmt);
156633  }
156634  
156635  
156636  static
156637  int queryTokenizer(
156638    sqlite3 *db, 
156639    char *zName,  
156640    const sqlite3_tokenizer_module **pp
156641  ){
156642    int rc;
156643    sqlite3_stmt *pStmt;
156644    const char zSql[] = "SELECT fts3_tokenizer(?)";
156645  
156646    *pp = 0;
156647    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
156648    if( rc!=SQLITE_OK ){
156649      return rc;
156650    }
156651  
156652    sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
156653    if( SQLITE_ROW==sqlite3_step(pStmt) ){
156654      if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
156655        memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
156656      }
156657    }
156658  
156659    return sqlite3_finalize(pStmt);
156660  }
156661  
156662  SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
156663  
156664  /*
156665  ** Implementation of the scalar function fts3_tokenizer_internal_test().
156666  ** This function is used for testing only, it is not included in the
156667  ** build unless SQLITE_TEST is defined.
156668  **
156669  ** The purpose of this is to test that the fts3_tokenizer() function
156670  ** can be used as designed by the C-code in the queryTokenizer and
156671  ** registerTokenizer() functions above. These two functions are repeated
156672  ** in the README.tokenizer file as an example, so it is important to
156673  ** test them.
156674  **
156675  ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
156676  ** function with no arguments. An assert() will fail if a problem is
156677  ** detected. i.e.:
156678  **
156679  **     SELECT fts3_tokenizer_internal_test();
156680  **
156681  */
156682  static void intTestFunc(
156683    sqlite3_context *context,
156684    int argc,
156685    sqlite3_value **argv
156686  ){
156687    int rc;
156688    const sqlite3_tokenizer_module *p1;
156689    const sqlite3_tokenizer_module *p2;
156690    sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
156691  
156692    UNUSED_PARAMETER(argc);
156693    UNUSED_PARAMETER(argv);
156694  
156695    /* Test the query function */
156696    sqlite3Fts3SimpleTokenizerModule(&p1);
156697    rc = queryTokenizer(db, "simple", &p2);
156698    assert( rc==SQLITE_OK );
156699    assert( p1==p2 );
156700    rc = queryTokenizer(db, "nosuchtokenizer", &p2);
156701    assert( rc==SQLITE_ERROR );
156702    assert( p2==0 );
156703    assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
156704  
156705    /* Test the storage function */
156706    if( fts3TokenizerEnabled(context) ){
156707      rc = registerTokenizer(db, "nosuchtokenizer", p1);
156708      assert( rc==SQLITE_OK );
156709      rc = queryTokenizer(db, "nosuchtokenizer", &p2);
156710      assert( rc==SQLITE_OK );
156711      assert( p2==p1 );
156712    }
156713  
156714    sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
156715  }
156716  
156717  #endif
156718  
156719  /*
156720  ** Set up SQL objects in database db used to access the contents of
156721  ** the hash table pointed to by argument pHash. The hash table must
156722  ** been initialized to use string keys, and to take a private copy 
156723  ** of the key when a value is inserted. i.e. by a call similar to:
156724  **
156725  **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
156726  **
156727  ** This function adds a scalar function (see header comment above
156728  ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
156729  ** defined at compilation time, a temporary virtual table (see header 
156730  ** comment above struct HashTableVtab) to the database schema. Both 
156731  ** provide read/write access to the contents of *pHash.
156732  **
156733  ** The third argument to this function, zName, is used as the name
156734  ** of both the scalar and, if created, the virtual table.
156735  */
156736  SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
156737    sqlite3 *db, 
156738    Fts3Hash *pHash, 
156739    const char *zName
156740  ){
156741    int rc = SQLITE_OK;
156742    void *p = (void *)pHash;
156743    const int any = SQLITE_ANY;
156744  
156745  #ifdef SQLITE_TEST
156746    char *zTest = 0;
156747    char *zTest2 = 0;
156748    void *pdb = (void *)db;
156749    zTest = sqlite3_mprintf("%s_test", zName);
156750    zTest2 = sqlite3_mprintf("%s_internal_test", zName);
156751    if( !zTest || !zTest2 ){
156752      rc = SQLITE_NOMEM;
156753    }
156754  #endif
156755  
156756    if( SQLITE_OK==rc ){
156757      rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
156758    }
156759    if( SQLITE_OK==rc ){
156760      rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
156761    }
156762  #ifdef SQLITE_TEST
156763    if( SQLITE_OK==rc ){
156764      rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
156765    }
156766    if( SQLITE_OK==rc ){
156767      rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
156768    }
156769  #endif
156770  
156771  #ifdef SQLITE_TEST
156772    sqlite3_free(zTest);
156773    sqlite3_free(zTest2);
156774  #endif
156775  
156776    return rc;
156777  }
156778  
156779  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
156780  
156781  /************** End of fts3_tokenizer.c **************************************/
156782  /************** Begin file fts3_tokenizer1.c *********************************/
156783  /*
156784  ** 2006 Oct 10
156785  **
156786  ** The author disclaims copyright to this source code.  In place of
156787  ** a legal notice, here is a blessing:
156788  **
156789  **    May you do good and not evil.
156790  **    May you find forgiveness for yourself and forgive others.
156791  **    May you share freely, never taking more than you give.
156792  **
156793  ******************************************************************************
156794  **
156795  ** Implementation of the "simple" full-text-search tokenizer.
156796  */
156797  
156798  /*
156799  ** The code in this file is only compiled if:
156800  **
156801  **     * The FTS3 module is being built as an extension
156802  **       (in which case SQLITE_CORE is not defined), or
156803  **
156804  **     * The FTS3 module is being built into the core of
156805  **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
156806  */
156807  /* #include "fts3Int.h" */
156808  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
156809  
156810  /* #include <assert.h> */
156811  /* #include <stdlib.h> */
156812  /* #include <stdio.h> */
156813  /* #include <string.h> */
156814  
156815  /* #include "fts3_tokenizer.h" */
156816  
156817  typedef struct simple_tokenizer {
156818    sqlite3_tokenizer base;
156819    char delim[128];             /* flag ASCII delimiters */
156820  } simple_tokenizer;
156821  
156822  typedef struct simple_tokenizer_cursor {
156823    sqlite3_tokenizer_cursor base;
156824    const char *pInput;          /* input we are tokenizing */
156825    int nBytes;                  /* size of the input */
156826    int iOffset;                 /* current position in pInput */
156827    int iToken;                  /* index of next token to be returned */
156828    char *pToken;                /* storage for current token */
156829    int nTokenAllocated;         /* space allocated to zToken buffer */
156830  } simple_tokenizer_cursor;
156831  
156832  
156833  static int simpleDelim(simple_tokenizer *t, unsigned char c){
156834    return c<0x80 && t->delim[c];
156835  }
156836  static int fts3_isalnum(int x){
156837    return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
156838  }
156839  
156840  /*
156841  ** Create a new tokenizer instance.
156842  */
156843  static int simpleCreate(
156844    int argc, const char * const *argv,
156845    sqlite3_tokenizer **ppTokenizer
156846  ){
156847    simple_tokenizer *t;
156848  
156849    t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
156850    if( t==NULL ) return SQLITE_NOMEM;
156851    memset(t, 0, sizeof(*t));
156852  
156853    /* TODO(shess) Delimiters need to remain the same from run to run,
156854    ** else we need to reindex.  One solution would be a meta-table to
156855    ** track such information in the database, then we'd only want this
156856    ** information on the initial create.
156857    */
156858    if( argc>1 ){
156859      int i, n = (int)strlen(argv[1]);
156860      for(i=0; i<n; i++){
156861        unsigned char ch = argv[1][i];
156862        /* We explicitly don't support UTF-8 delimiters for now. */
156863        if( ch>=0x80 ){
156864          sqlite3_free(t);
156865          return SQLITE_ERROR;
156866        }
156867        t->delim[ch] = 1;
156868      }
156869    } else {
156870      /* Mark non-alphanumeric ASCII characters as delimiters */
156871      int i;
156872      for(i=1; i<0x80; i++){
156873        t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
156874      }
156875    }
156876  
156877    *ppTokenizer = &t->base;
156878    return SQLITE_OK;
156879  }
156880  
156881  /*
156882  ** Destroy a tokenizer
156883  */
156884  static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
156885    sqlite3_free(pTokenizer);
156886    return SQLITE_OK;
156887  }
156888  
156889  /*
156890  ** Prepare to begin tokenizing a particular string.  The input
156891  ** string to be tokenized is pInput[0..nBytes-1].  A cursor
156892  ** used to incrementally tokenize this string is returned in 
156893  ** *ppCursor.
156894  */
156895  static int simpleOpen(
156896    sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
156897    const char *pInput, int nBytes,        /* String to be tokenized */
156898    sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
156899  ){
156900    simple_tokenizer_cursor *c;
156901  
156902    UNUSED_PARAMETER(pTokenizer);
156903  
156904    c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
156905    if( c==NULL ) return SQLITE_NOMEM;
156906  
156907    c->pInput = pInput;
156908    if( pInput==0 ){
156909      c->nBytes = 0;
156910    }else if( nBytes<0 ){
156911      c->nBytes = (int)strlen(pInput);
156912    }else{
156913      c->nBytes = nBytes;
156914    }
156915    c->iOffset = 0;                 /* start tokenizing at the beginning */
156916    c->iToken = 0;
156917    c->pToken = NULL;               /* no space allocated, yet. */
156918    c->nTokenAllocated = 0;
156919  
156920    *ppCursor = &c->base;
156921    return SQLITE_OK;
156922  }
156923  
156924  /*
156925  ** Close a tokenization cursor previously opened by a call to
156926  ** simpleOpen() above.
156927  */
156928  static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
156929    simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
156930    sqlite3_free(c->pToken);
156931    sqlite3_free(c);
156932    return SQLITE_OK;
156933  }
156934  
156935  /*
156936  ** Extract the next token from a tokenization cursor.  The cursor must
156937  ** have been opened by a prior call to simpleOpen().
156938  */
156939  static int simpleNext(
156940    sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
156941    const char **ppToken,               /* OUT: *ppToken is the token text */
156942    int *pnBytes,                       /* OUT: Number of bytes in token */
156943    int *piStartOffset,                 /* OUT: Starting offset of token */
156944    int *piEndOffset,                   /* OUT: Ending offset of token */
156945    int *piPosition                     /* OUT: Position integer of token */
156946  ){
156947    simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
156948    simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
156949    unsigned char *p = (unsigned char *)c->pInput;
156950  
156951    while( c->iOffset<c->nBytes ){
156952      int iStartOffset;
156953  
156954      /* Scan past delimiter characters */
156955      while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
156956        c->iOffset++;
156957      }
156958  
156959      /* Count non-delimiter characters. */
156960      iStartOffset = c->iOffset;
156961      while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
156962        c->iOffset++;
156963      }
156964  
156965      if( c->iOffset>iStartOffset ){
156966        int i, n = c->iOffset-iStartOffset;
156967        if( n>c->nTokenAllocated ){
156968          char *pNew;
156969          c->nTokenAllocated = n+20;
156970          pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
156971          if( !pNew ) return SQLITE_NOMEM;
156972          c->pToken = pNew;
156973        }
156974        for(i=0; i<n; i++){
156975          /* TODO(shess) This needs expansion to handle UTF-8
156976          ** case-insensitivity.
156977          */
156978          unsigned char ch = p[iStartOffset+i];
156979          c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
156980        }
156981        *ppToken = c->pToken;
156982        *pnBytes = n;
156983        *piStartOffset = iStartOffset;
156984        *piEndOffset = c->iOffset;
156985        *piPosition = c->iToken++;
156986  
156987        return SQLITE_OK;
156988      }
156989    }
156990    return SQLITE_DONE;
156991  }
156992  
156993  /*
156994  ** The set of routines that implement the simple tokenizer
156995  */
156996  static const sqlite3_tokenizer_module simpleTokenizerModule = {
156997    0,
156998    simpleCreate,
156999    simpleDestroy,
157000    simpleOpen,
157001    simpleClose,
157002    simpleNext,
157003    0,
157004  };
157005  
157006  /*
157007  ** Allocate a new simple tokenizer.  Return a pointer to the new
157008  ** tokenizer in *ppModule
157009  */
157010  SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
157011    sqlite3_tokenizer_module const**ppModule
157012  ){
157013    *ppModule = &simpleTokenizerModule;
157014  }
157015  
157016  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
157017  
157018  /************** End of fts3_tokenizer1.c *************************************/
157019  /************** Begin file fts3_tokenize_vtab.c ******************************/
157020  /*
157021  ** 2013 Apr 22
157022  **
157023  ** The author disclaims copyright to this source code.  In place of
157024  ** a legal notice, here is a blessing:
157025  **
157026  **    May you do good and not evil.
157027  **    May you find forgiveness for yourself and forgive others.
157028  **    May you share freely, never taking more than you give.
157029  **
157030  ******************************************************************************
157031  **
157032  ** This file contains code for the "fts3tokenize" virtual table module.
157033  ** An fts3tokenize virtual table is created as follows:
157034  **
157035  **   CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
157036  **       <tokenizer-name>, <arg-1>, ...
157037  **   );
157038  **
157039  ** The table created has the following schema:
157040  **
157041  **   CREATE TABLE <tbl>(input, token, start, end, position)
157042  **
157043  ** When queried, the query must include a WHERE clause of type:
157044  **
157045  **   input = <string>
157046  **
157047  ** The virtual table module tokenizes this <string>, using the FTS3 
157048  ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE 
157049  ** statement and returns one row for each token in the result. With
157050  ** fields set as follows:
157051  **
157052  **   input:   Always set to a copy of <string>
157053  **   token:   A token from the input.
157054  **   start:   Byte offset of the token within the input <string>.
157055  **   end:     Byte offset of the byte immediately following the end of the
157056  **            token within the input string.
157057  **   pos:     Token offset of token within input.
157058  **
157059  */
157060  /* #include "fts3Int.h" */
157061  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
157062  
157063  /* #include <string.h> */
157064  /* #include <assert.h> */
157065  
157066  typedef struct Fts3tokTable Fts3tokTable;
157067  typedef struct Fts3tokCursor Fts3tokCursor;
157068  
157069  /*
157070  ** Virtual table structure.
157071  */
157072  struct Fts3tokTable {
157073    sqlite3_vtab base;              /* Base class used by SQLite core */
157074    const sqlite3_tokenizer_module *pMod;
157075    sqlite3_tokenizer *pTok;
157076  };
157077  
157078  /*
157079  ** Virtual table cursor structure.
157080  */
157081  struct Fts3tokCursor {
157082    sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
157083    char *zInput;                   /* Input string */
157084    sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
157085    int iRowid;                     /* Current 'rowid' value */
157086    const char *zToken;             /* Current 'token' value */
157087    int nToken;                     /* Size of zToken in bytes */
157088    int iStart;                     /* Current 'start' value */
157089    int iEnd;                       /* Current 'end' value */
157090    int iPos;                       /* Current 'pos' value */
157091  };
157092  
157093  /*
157094  ** Query FTS for the tokenizer implementation named zName.
157095  */
157096  static int fts3tokQueryTokenizer(
157097    Fts3Hash *pHash,
157098    const char *zName,
157099    const sqlite3_tokenizer_module **pp,
157100    char **pzErr
157101  ){
157102    sqlite3_tokenizer_module *p;
157103    int nName = (int)strlen(zName);
157104  
157105    p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
157106    if( !p ){
157107      sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
157108      return SQLITE_ERROR;
157109    }
157110  
157111    *pp = p;
157112    return SQLITE_OK;
157113  }
157114  
157115  /*
157116  ** The second argument, argv[], is an array of pointers to nul-terminated
157117  ** strings. This function makes a copy of the array and strings into a 
157118  ** single block of memory. It then dequotes any of the strings that appear
157119  ** to be quoted.
157120  **
157121  ** If successful, output parameter *pazDequote is set to point at the
157122  ** array of dequoted strings and SQLITE_OK is returned. The caller is
157123  ** responsible for eventually calling sqlite3_free() to free the array
157124  ** in this case. Or, if an error occurs, an SQLite error code is returned.
157125  ** The final value of *pazDequote is undefined in this case.
157126  */
157127  static int fts3tokDequoteArray(
157128    int argc,                       /* Number of elements in argv[] */
157129    const char * const *argv,       /* Input array */
157130    char ***pazDequote              /* Output array */
157131  ){
157132    int rc = SQLITE_OK;             /* Return code */
157133    if( argc==0 ){
157134      *pazDequote = 0;
157135    }else{
157136      int i;
157137      int nByte = 0;
157138      char **azDequote;
157139  
157140      for(i=0; i<argc; i++){
157141        nByte += (int)(strlen(argv[i]) + 1);
157142      }
157143  
157144      *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
157145      if( azDequote==0 ){
157146        rc = SQLITE_NOMEM;
157147      }else{
157148        char *pSpace = (char *)&azDequote[argc];
157149        for(i=0; i<argc; i++){
157150          int n = (int)strlen(argv[i]);
157151          azDequote[i] = pSpace;
157152          memcpy(pSpace, argv[i], n+1);
157153          sqlite3Fts3Dequote(pSpace);
157154          pSpace += (n+1);
157155        }
157156      }
157157    }
157158  
157159    return rc;
157160  }
157161  
157162  /*
157163  ** Schema of the tokenizer table.
157164  */
157165  #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
157166  
157167  /*
157168  ** This function does all the work for both the xConnect and xCreate methods.
157169  ** These tables have no persistent representation of their own, so xConnect
157170  ** and xCreate are identical operations.
157171  **
157172  **   argv[0]: module name
157173  **   argv[1]: database name 
157174  **   argv[2]: table name
157175  **   argv[3]: first argument (tokenizer name)
157176  */
157177  static int fts3tokConnectMethod(
157178    sqlite3 *db,                    /* Database connection */
157179    void *pHash,                    /* Hash table of tokenizers */
157180    int argc,                       /* Number of elements in argv array */
157181    const char * const *argv,       /* xCreate/xConnect argument array */
157182    sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
157183    char **pzErr                    /* OUT: sqlite3_malloc'd error message */
157184  ){
157185    Fts3tokTable *pTab = 0;
157186    const sqlite3_tokenizer_module *pMod = 0;
157187    sqlite3_tokenizer *pTok = 0;
157188    int rc;
157189    char **azDequote = 0;
157190    int nDequote;
157191  
157192    rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
157193    if( rc!=SQLITE_OK ) return rc;
157194  
157195    nDequote = argc-3;
157196    rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
157197  
157198    if( rc==SQLITE_OK ){
157199      const char *zModule;
157200      if( nDequote<1 ){
157201        zModule = "simple";
157202      }else{
157203        zModule = azDequote[0];
157204      }
157205      rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
157206    }
157207  
157208    assert( (rc==SQLITE_OK)==(pMod!=0) );
157209    if( rc==SQLITE_OK ){
157210      const char * const *azArg = (const char * const *)&azDequote[1];
157211      rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
157212    }
157213  
157214    if( rc==SQLITE_OK ){
157215      pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
157216      if( pTab==0 ){
157217        rc = SQLITE_NOMEM;
157218      }
157219    }
157220  
157221    if( rc==SQLITE_OK ){
157222      memset(pTab, 0, sizeof(Fts3tokTable));
157223      pTab->pMod = pMod;
157224      pTab->pTok = pTok;
157225      *ppVtab = &pTab->base;
157226    }else{
157227      if( pTok ){
157228        pMod->xDestroy(pTok);
157229      }
157230    }
157231  
157232    sqlite3_free(azDequote);
157233    return rc;
157234  }
157235  
157236  /*
157237  ** This function does the work for both the xDisconnect and xDestroy methods.
157238  ** These tables have no persistent representation of their own, so xDisconnect
157239  ** and xDestroy are identical operations.
157240  */
157241  static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
157242    Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
157243  
157244    pTab->pMod->xDestroy(pTab->pTok);
157245    sqlite3_free(pTab);
157246    return SQLITE_OK;
157247  }
157248  
157249  /*
157250  ** xBestIndex - Analyze a WHERE and ORDER BY clause.
157251  */
157252  static int fts3tokBestIndexMethod(
157253    sqlite3_vtab *pVTab, 
157254    sqlite3_index_info *pInfo
157255  ){
157256    int i;
157257    UNUSED_PARAMETER(pVTab);
157258  
157259    for(i=0; i<pInfo->nConstraint; i++){
157260      if( pInfo->aConstraint[i].usable 
157261       && pInfo->aConstraint[i].iColumn==0 
157262       && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ 
157263      ){
157264        pInfo->idxNum = 1;
157265        pInfo->aConstraintUsage[i].argvIndex = 1;
157266        pInfo->aConstraintUsage[i].omit = 1;
157267        pInfo->estimatedCost = 1;
157268        return SQLITE_OK;
157269      }
157270    }
157271  
157272    pInfo->idxNum = 0;
157273    assert( pInfo->estimatedCost>1000000.0 );
157274  
157275    return SQLITE_OK;
157276  }
157277  
157278  /*
157279  ** xOpen - Open a cursor.
157280  */
157281  static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
157282    Fts3tokCursor *pCsr;
157283    UNUSED_PARAMETER(pVTab);
157284  
157285    pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
157286    if( pCsr==0 ){
157287      return SQLITE_NOMEM;
157288    }
157289    memset(pCsr, 0, sizeof(Fts3tokCursor));
157290  
157291    *ppCsr = (sqlite3_vtab_cursor *)pCsr;
157292    return SQLITE_OK;
157293  }
157294  
157295  /*
157296  ** Reset the tokenizer cursor passed as the only argument. As if it had
157297  ** just been returned by fts3tokOpenMethod().
157298  */
157299  static void fts3tokResetCursor(Fts3tokCursor *pCsr){
157300    if( pCsr->pCsr ){
157301      Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
157302      pTab->pMod->xClose(pCsr->pCsr);
157303      pCsr->pCsr = 0;
157304    }
157305    sqlite3_free(pCsr->zInput);
157306    pCsr->zInput = 0;
157307    pCsr->zToken = 0;
157308    pCsr->nToken = 0;
157309    pCsr->iStart = 0;
157310    pCsr->iEnd = 0;
157311    pCsr->iPos = 0;
157312    pCsr->iRowid = 0;
157313  }
157314  
157315  /*
157316  ** xClose - Close a cursor.
157317  */
157318  static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
157319    Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
157320  
157321    fts3tokResetCursor(pCsr);
157322    sqlite3_free(pCsr);
157323    return SQLITE_OK;
157324  }
157325  
157326  /*
157327  ** xNext - Advance the cursor to the next row, if any.
157328  */
157329  static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
157330    Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
157331    Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
157332    int rc;                         /* Return code */
157333  
157334    pCsr->iRowid++;
157335    rc = pTab->pMod->xNext(pCsr->pCsr,
157336        &pCsr->zToken, &pCsr->nToken,
157337        &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
157338    );
157339  
157340    if( rc!=SQLITE_OK ){
157341      fts3tokResetCursor(pCsr);
157342      if( rc==SQLITE_DONE ) rc = SQLITE_OK;
157343    }
157344  
157345    return rc;
157346  }
157347  
157348  /*
157349  ** xFilter - Initialize a cursor to point at the start of its data.
157350  */
157351  static int fts3tokFilterMethod(
157352    sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
157353    int idxNum,                     /* Strategy index */
157354    const char *idxStr,             /* Unused */
157355    int nVal,                       /* Number of elements in apVal */
157356    sqlite3_value **apVal           /* Arguments for the indexing scheme */
157357  ){
157358    int rc = SQLITE_ERROR;
157359    Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
157360    Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
157361    UNUSED_PARAMETER(idxStr);
157362    UNUSED_PARAMETER(nVal);
157363  
157364    fts3tokResetCursor(pCsr);
157365    if( idxNum==1 ){
157366      const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
157367      int nByte = sqlite3_value_bytes(apVal[0]);
157368      pCsr->zInput = sqlite3_malloc(nByte+1);
157369      if( pCsr->zInput==0 ){
157370        rc = SQLITE_NOMEM;
157371      }else{
157372        memcpy(pCsr->zInput, zByte, nByte);
157373        pCsr->zInput[nByte] = 0;
157374        rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
157375        if( rc==SQLITE_OK ){
157376          pCsr->pCsr->pTokenizer = pTab->pTok;
157377        }
157378      }
157379    }
157380  
157381    if( rc!=SQLITE_OK ) return rc;
157382    return fts3tokNextMethod(pCursor);
157383  }
157384  
157385  /*
157386  ** xEof - Return true if the cursor is at EOF, or false otherwise.
157387  */
157388  static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
157389    Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
157390    return (pCsr->zToken==0);
157391  }
157392  
157393  /*
157394  ** xColumn - Return a column value.
157395  */
157396  static int fts3tokColumnMethod(
157397    sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
157398    sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
157399    int iCol                        /* Index of column to read value from */
157400  ){
157401    Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
157402  
157403    /* CREATE TABLE x(input, token, start, end, position) */
157404    switch( iCol ){
157405      case 0:
157406        sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
157407        break;
157408      case 1:
157409        sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
157410        break;
157411      case 2:
157412        sqlite3_result_int(pCtx, pCsr->iStart);
157413        break;
157414      case 3:
157415        sqlite3_result_int(pCtx, pCsr->iEnd);
157416        break;
157417      default:
157418        assert( iCol==4 );
157419        sqlite3_result_int(pCtx, pCsr->iPos);
157420        break;
157421    }
157422    return SQLITE_OK;
157423  }
157424  
157425  /*
157426  ** xRowid - Return the current rowid for the cursor.
157427  */
157428  static int fts3tokRowidMethod(
157429    sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
157430    sqlite_int64 *pRowid            /* OUT: Rowid value */
157431  ){
157432    Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
157433    *pRowid = (sqlite3_int64)pCsr->iRowid;
157434    return SQLITE_OK;
157435  }
157436  
157437  /*
157438  ** Register the fts3tok module with database connection db. Return SQLITE_OK
157439  ** if successful or an error code if sqlite3_create_module() fails.
157440  */
157441  SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
157442    static const sqlite3_module fts3tok_module = {
157443       0,                           /* iVersion      */
157444       fts3tokConnectMethod,        /* xCreate       */
157445       fts3tokConnectMethod,        /* xConnect      */
157446       fts3tokBestIndexMethod,      /* xBestIndex    */
157447       fts3tokDisconnectMethod,     /* xDisconnect   */
157448       fts3tokDisconnectMethod,     /* xDestroy      */
157449       fts3tokOpenMethod,           /* xOpen         */
157450       fts3tokCloseMethod,          /* xClose        */
157451       fts3tokFilterMethod,         /* xFilter       */
157452       fts3tokNextMethod,           /* xNext         */
157453       fts3tokEofMethod,            /* xEof          */
157454       fts3tokColumnMethod,         /* xColumn       */
157455       fts3tokRowidMethod,          /* xRowid        */
157456       0,                           /* xUpdate       */
157457       0,                           /* xBegin        */
157458       0,                           /* xSync         */
157459       0,                           /* xCommit       */
157460       0,                           /* xRollback     */
157461       0,                           /* xFindFunction */
157462       0,                           /* xRename       */
157463       0,                           /* xSavepoint    */
157464       0,                           /* xRelease      */
157465       0                            /* xRollbackTo   */
157466    };
157467    int rc;                         /* Return code */
157468  
157469    rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
157470    return rc;
157471  }
157472  
157473  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
157474  
157475  /************** End of fts3_tokenize_vtab.c **********************************/
157476  /************** Begin file fts3_write.c **************************************/
157477  /*
157478  ** 2009 Oct 23
157479  **
157480  ** The author disclaims copyright to this source code.  In place of
157481  ** a legal notice, here is a blessing:
157482  **
157483  **    May you do good and not evil.
157484  **    May you find forgiveness for yourself and forgive others.
157485  **    May you share freely, never taking more than you give.
157486  **
157487  ******************************************************************************
157488  **
157489  ** This file is part of the SQLite FTS3 extension module. Specifically,
157490  ** this file contains code to insert, update and delete rows from FTS3
157491  ** tables. It also contains code to merge FTS3 b-tree segments. Some
157492  ** of the sub-routines used to merge segments are also used by the query 
157493  ** code in fts3.c.
157494  */
157495  
157496  /* #include "fts3Int.h" */
157497  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
157498  
157499  /* #include <string.h> */
157500  /* #include <assert.h> */
157501  /* #include <stdlib.h> */
157502  
157503  
157504  #define FTS_MAX_APPENDABLE_HEIGHT 16
157505  
157506  /*
157507  ** When full-text index nodes are loaded from disk, the buffer that they
157508  ** are loaded into has the following number of bytes of padding at the end 
157509  ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
157510  ** of 920 bytes is allocated for it.
157511  **
157512  ** This means that if we have a pointer into a buffer containing node data,
157513  ** it is always safe to read up to two varints from it without risking an
157514  ** overread, even if the node data is corrupted.
157515  */
157516  #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
157517  
157518  /*
157519  ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
157520  ** memory incrementally instead of all at once. This can be a big performance
157521  ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
157522  ** method before retrieving all query results (as may happen, for example,
157523  ** if a query has a LIMIT clause).
157524  **
157525  ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD 
157526  ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
157527  ** The code is written so that the hard lower-limit for each of these values 
157528  ** is 1. Clearly such small values would be inefficient, but can be useful 
157529  ** for testing purposes.
157530  **
157531  ** If this module is built with SQLITE_TEST defined, these constants may
157532  ** be overridden at runtime for testing purposes. File fts3_test.c contains
157533  ** a Tcl interface to read and write the values.
157534  */
157535  #ifdef SQLITE_TEST
157536  int test_fts3_node_chunksize = (4*1024);
157537  int test_fts3_node_chunk_threshold = (4*1024)*4;
157538  # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
157539  # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
157540  #else
157541  # define FTS3_NODE_CHUNKSIZE (4*1024) 
157542  # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
157543  #endif
157544  
157545  /*
157546  ** The two values that may be meaningfully bound to the :1 parameter in
157547  ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
157548  */
157549  #define FTS_STAT_DOCTOTAL      0
157550  #define FTS_STAT_INCRMERGEHINT 1
157551  #define FTS_STAT_AUTOINCRMERGE 2
157552  
157553  /*
157554  ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
157555  ** and incremental merge operation that takes place. This is used for 
157556  ** debugging FTS only, it should not usually be turned on in production
157557  ** systems.
157558  */
157559  #ifdef FTS3_LOG_MERGES
157560  static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
157561    sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
157562  }
157563  #else
157564  #define fts3LogMerge(x, y)
157565  #endif
157566  
157567  
157568  typedef struct PendingList PendingList;
157569  typedef struct SegmentNode SegmentNode;
157570  typedef struct SegmentWriter SegmentWriter;
157571  
157572  /*
157573  ** An instance of the following data structure is used to build doclists
157574  ** incrementally. See function fts3PendingListAppend() for details.
157575  */
157576  struct PendingList {
157577    int nData;
157578    char *aData;
157579    int nSpace;
157580    sqlite3_int64 iLastDocid;
157581    sqlite3_int64 iLastCol;
157582    sqlite3_int64 iLastPos;
157583  };
157584  
157585  
157586  /*
157587  ** Each cursor has a (possibly empty) linked list of the following objects.
157588  */
157589  struct Fts3DeferredToken {
157590    Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
157591    int iCol;                       /* Column token must occur in */
157592    Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
157593    PendingList *pList;             /* Doclist is assembled here */
157594  };
157595  
157596  /*
157597  ** An instance of this structure is used to iterate through the terms on
157598  ** a contiguous set of segment b-tree leaf nodes. Although the details of
157599  ** this structure are only manipulated by code in this file, opaque handles
157600  ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
157601  ** terms when querying the full-text index. See functions:
157602  **
157603  **   sqlite3Fts3SegReaderNew()
157604  **   sqlite3Fts3SegReaderFree()
157605  **   sqlite3Fts3SegReaderIterate()
157606  **
157607  ** Methods used to manipulate Fts3SegReader structures:
157608  **
157609  **   fts3SegReaderNext()
157610  **   fts3SegReaderFirstDocid()
157611  **   fts3SegReaderNextDocid()
157612  */
157613  struct Fts3SegReader {
157614    int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
157615    u8 bLookup;                     /* True for a lookup only */
157616    u8 rootOnly;                    /* True for a root-only reader */
157617  
157618    sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
157619    sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
157620    sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
157621    sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
157622  
157623    char *aNode;                    /* Pointer to node data (or NULL) */
157624    int nNode;                      /* Size of buffer at aNode (or 0) */
157625    int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
157626    sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
157627  
157628    Fts3HashElem **ppNextElem;
157629  
157630    /* Variables set by fts3SegReaderNext(). These may be read directly
157631    ** by the caller. They are valid from the time SegmentReaderNew() returns
157632    ** until SegmentReaderNext() returns something other than SQLITE_OK
157633    ** (i.e. SQLITE_DONE).
157634    */
157635    int nTerm;                      /* Number of bytes in current term */
157636    char *zTerm;                    /* Pointer to current term */
157637    int nTermAlloc;                 /* Allocated size of zTerm buffer */
157638    char *aDoclist;                 /* Pointer to doclist of current entry */
157639    int nDoclist;                   /* Size of doclist in current entry */
157640  
157641    /* The following variables are used by fts3SegReaderNextDocid() to iterate 
157642    ** through the current doclist (aDoclist/nDoclist).
157643    */
157644    char *pOffsetList;
157645    int nOffsetList;                /* For descending pending seg-readers only */
157646    sqlite3_int64 iDocid;
157647  };
157648  
157649  #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
157650  #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
157651  
157652  /*
157653  ** An instance of this structure is used to create a segment b-tree in the
157654  ** database. The internal details of this type are only accessed by the
157655  ** following functions:
157656  **
157657  **   fts3SegWriterAdd()
157658  **   fts3SegWriterFlush()
157659  **   fts3SegWriterFree()
157660  */
157661  struct SegmentWriter {
157662    SegmentNode *pTree;             /* Pointer to interior tree structure */
157663    sqlite3_int64 iFirst;           /* First slot in %_segments written */
157664    sqlite3_int64 iFree;            /* Next free slot in %_segments */
157665    char *zTerm;                    /* Pointer to previous term buffer */
157666    int nTerm;                      /* Number of bytes in zTerm */
157667    int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
157668    char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
157669    int nSize;                      /* Size of allocation at aData */
157670    int nData;                      /* Bytes of data in aData */
157671    char *aData;                    /* Pointer to block from malloc() */
157672    i64 nLeafData;                  /* Number of bytes of leaf data written */
157673  };
157674  
157675  /*
157676  ** Type SegmentNode is used by the following three functions to create
157677  ** the interior part of the segment b+-tree structures (everything except
157678  ** the leaf nodes). These functions and type are only ever used by code
157679  ** within the fts3SegWriterXXX() family of functions described above.
157680  **
157681  **   fts3NodeAddTerm()
157682  **   fts3NodeWrite()
157683  **   fts3NodeFree()
157684  **
157685  ** When a b+tree is written to the database (either as a result of a merge
157686  ** or the pending-terms table being flushed), leaves are written into the 
157687  ** database file as soon as they are completely populated. The interior of
157688  ** the tree is assembled in memory and written out only once all leaves have
157689  ** been populated and stored. This is Ok, as the b+-tree fanout is usually
157690  ** very large, meaning that the interior of the tree consumes relatively 
157691  ** little memory.
157692  */
157693  struct SegmentNode {
157694    SegmentNode *pParent;           /* Parent node (or NULL for root node) */
157695    SegmentNode *pRight;            /* Pointer to right-sibling */
157696    SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
157697    int nEntry;                     /* Number of terms written to node so far */
157698    char *zTerm;                    /* Pointer to previous term buffer */
157699    int nTerm;                      /* Number of bytes in zTerm */
157700    int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
157701    char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
157702    int nData;                      /* Bytes of valid data so far */
157703    char *aData;                    /* Node data */
157704  };
157705  
157706  /*
157707  ** Valid values for the second argument to fts3SqlStmt().
157708  */
157709  #define SQL_DELETE_CONTENT             0
157710  #define SQL_IS_EMPTY                   1
157711  #define SQL_DELETE_ALL_CONTENT         2 
157712  #define SQL_DELETE_ALL_SEGMENTS        3
157713  #define SQL_DELETE_ALL_SEGDIR          4
157714  #define SQL_DELETE_ALL_DOCSIZE         5
157715  #define SQL_DELETE_ALL_STAT            6
157716  #define SQL_SELECT_CONTENT_BY_ROWID    7
157717  #define SQL_NEXT_SEGMENT_INDEX         8
157718  #define SQL_INSERT_SEGMENTS            9
157719  #define SQL_NEXT_SEGMENTS_ID          10
157720  #define SQL_INSERT_SEGDIR             11
157721  #define SQL_SELECT_LEVEL              12
157722  #define SQL_SELECT_LEVEL_RANGE        13
157723  #define SQL_SELECT_LEVEL_COUNT        14
157724  #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
157725  #define SQL_DELETE_SEGDIR_LEVEL       16
157726  #define SQL_DELETE_SEGMENTS_RANGE     17
157727  #define SQL_CONTENT_INSERT            18
157728  #define SQL_DELETE_DOCSIZE            19
157729  #define SQL_REPLACE_DOCSIZE           20
157730  #define SQL_SELECT_DOCSIZE            21
157731  #define SQL_SELECT_STAT               22
157732  #define SQL_REPLACE_STAT              23
157733  
157734  #define SQL_SELECT_ALL_PREFIX_LEVEL   24
157735  #define SQL_DELETE_ALL_TERMS_SEGDIR   25
157736  #define SQL_DELETE_SEGDIR_RANGE       26
157737  #define SQL_SELECT_ALL_LANGID         27
157738  #define SQL_FIND_MERGE_LEVEL          28
157739  #define SQL_MAX_LEAF_NODE_ESTIMATE    29
157740  #define SQL_DELETE_SEGDIR_ENTRY       30
157741  #define SQL_SHIFT_SEGDIR_ENTRY        31
157742  #define SQL_SELECT_SEGDIR             32
157743  #define SQL_CHOMP_SEGDIR              33
157744  #define SQL_SEGMENT_IS_APPENDABLE     34
157745  #define SQL_SELECT_INDEXES            35
157746  #define SQL_SELECT_MXLEVEL            36
157747  
157748  #define SQL_SELECT_LEVEL_RANGE2       37
157749  #define SQL_UPDATE_LEVEL_IDX          38
157750  #define SQL_UPDATE_LEVEL              39
157751  
157752  /*
157753  ** This function is used to obtain an SQLite prepared statement handle
157754  ** for the statement identified by the second argument. If successful,
157755  ** *pp is set to the requested statement handle and SQLITE_OK returned.
157756  ** Otherwise, an SQLite error code is returned and *pp is set to 0.
157757  **
157758  ** If argument apVal is not NULL, then it must point to an array with
157759  ** at least as many entries as the requested statement has bound 
157760  ** parameters. The values are bound to the statements parameters before
157761  ** returning.
157762  */
157763  static int fts3SqlStmt(
157764    Fts3Table *p,                   /* Virtual table handle */
157765    int eStmt,                      /* One of the SQL_XXX constants above */
157766    sqlite3_stmt **pp,              /* OUT: Statement handle */
157767    sqlite3_value **apVal           /* Values to bind to statement */
157768  ){
157769    const char *azSql[] = {
157770  /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
157771  /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
157772  /* 2  */  "DELETE FROM %Q.'%q_content'",
157773  /* 3  */  "DELETE FROM %Q.'%q_segments'",
157774  /* 4  */  "DELETE FROM %Q.'%q_segdir'",
157775  /* 5  */  "DELETE FROM %Q.'%q_docsize'",
157776  /* 6  */  "DELETE FROM %Q.'%q_stat'",
157777  /* 7  */  "SELECT %s WHERE rowid=?",
157778  /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
157779  /* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
157780  /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
157781  /* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
157782  
157783            /* Return segments in order from oldest to newest.*/ 
157784  /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
157785              "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
157786  /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
157787              "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
157788              "ORDER BY level DESC, idx ASC",
157789  
157790  /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
157791  /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
157792  
157793  /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
157794  /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
157795  /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
157796  /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
157797  /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
157798  /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
157799  /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
157800  /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
157801  /* 24 */  "",
157802  /* 25 */  "",
157803  
157804  /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
157805  /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
157806  
157807  /* This statement is used to determine which level to read the input from
157808  ** when performing an incremental merge. It returns the absolute level number
157809  ** of the oldest level in the db that contains at least ? segments. Or,
157810  ** if no level in the FTS index contains more than ? segments, the statement
157811  ** returns zero rows.  */
157812  /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
157813           "  GROUP BY level HAVING cnt>=?"
157814           "  ORDER BY (level %% 1024) ASC LIMIT 1",
157815  
157816  /* Estimate the upper limit on the number of leaf nodes in a new segment
157817  ** created by merging the oldest :2 segments from absolute level :1. See 
157818  ** function sqlite3Fts3Incrmerge() for details.  */
157819  /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
157820           "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
157821  
157822  /* SQL_DELETE_SEGDIR_ENTRY
157823  **   Delete the %_segdir entry on absolute level :1 with index :2.  */
157824  /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
157825  
157826  /* SQL_SHIFT_SEGDIR_ENTRY
157827  **   Modify the idx value for the segment with idx=:3 on absolute level :2
157828  **   to :1.  */
157829  /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
157830  
157831  /* SQL_SELECT_SEGDIR
157832  **   Read a single entry from the %_segdir table. The entry from absolute 
157833  **   level :1 with index value :2.  */
157834  /* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
157835              "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
157836  
157837  /* SQL_CHOMP_SEGDIR
157838  **   Update the start_block (:1) and root (:2) fields of the %_segdir
157839  **   entry located on absolute level :3 with index :4.  */
157840  /* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
157841              "WHERE level = ? AND idx = ?",
157842  
157843  /* SQL_SEGMENT_IS_APPENDABLE
157844  **   Return a single row if the segment with end_block=? is appendable. Or
157845  **   no rows otherwise.  */
157846  /* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
157847  
157848  /* SQL_SELECT_INDEXES
157849  **   Return the list of valid segment indexes for absolute level ?  */
157850  /* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
157851  
157852  /* SQL_SELECT_MXLEVEL
157853  **   Return the largest relative level in the FTS index or indexes.  */
157854  /* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
157855  
157856            /* Return segments in order from oldest to newest.*/ 
157857  /* 37 */  "SELECT level, idx, end_block "
157858              "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
157859              "ORDER BY level DESC, idx ASC",
157860  
157861            /* Update statements used while promoting segments */
157862  /* 38 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
157863              "WHERE level=? AND idx=?",
157864  /* 39 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
157865  
157866    };
157867    int rc = SQLITE_OK;
157868    sqlite3_stmt *pStmt;
157869  
157870    assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
157871    assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
157872    
157873    pStmt = p->aStmt[eStmt];
157874    if( !pStmt ){
157875      char *zSql;
157876      if( eStmt==SQL_CONTENT_INSERT ){
157877        zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
157878      }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
157879        zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
157880      }else{
157881        zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
157882      }
157883      if( !zSql ){
157884        rc = SQLITE_NOMEM;
157885      }else{
157886        rc = sqlite3_prepare_v3(p->db, zSql, -1, SQLITE_PREPARE_PERSISTENT,
157887                                &pStmt, NULL);
157888        sqlite3_free(zSql);
157889        assert( rc==SQLITE_OK || pStmt==0 );
157890        p->aStmt[eStmt] = pStmt;
157891      }
157892    }
157893    if( apVal ){
157894      int i;
157895      int nParam = sqlite3_bind_parameter_count(pStmt);
157896      for(i=0; rc==SQLITE_OK && i<nParam; i++){
157897        rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
157898      }
157899    }
157900    *pp = pStmt;
157901    return rc;
157902  }
157903  
157904  
157905  static int fts3SelectDocsize(
157906    Fts3Table *pTab,                /* FTS3 table handle */
157907    sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
157908    sqlite3_stmt **ppStmt           /* OUT: Statement handle */
157909  ){
157910    sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
157911    int rc;                         /* Return code */
157912  
157913    rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
157914    if( rc==SQLITE_OK ){
157915      sqlite3_bind_int64(pStmt, 1, iDocid);
157916      rc = sqlite3_step(pStmt);
157917      if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
157918        rc = sqlite3_reset(pStmt);
157919        if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
157920        pStmt = 0;
157921      }else{
157922        rc = SQLITE_OK;
157923      }
157924    }
157925  
157926    *ppStmt = pStmt;
157927    return rc;
157928  }
157929  
157930  SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
157931    Fts3Table *pTab,                /* Fts3 table handle */
157932    sqlite3_stmt **ppStmt           /* OUT: Statement handle */
157933  ){
157934    sqlite3_stmt *pStmt = 0;
157935    int rc;
157936    rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
157937    if( rc==SQLITE_OK ){
157938      sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
157939      if( sqlite3_step(pStmt)!=SQLITE_ROW
157940       || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
157941      ){
157942        rc = sqlite3_reset(pStmt);
157943        if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
157944        pStmt = 0;
157945      }
157946    }
157947    *ppStmt = pStmt;
157948    return rc;
157949  }
157950  
157951  SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
157952    Fts3Table *pTab,                /* Fts3 table handle */
157953    sqlite3_int64 iDocid,           /* Docid to read size data for */
157954    sqlite3_stmt **ppStmt           /* OUT: Statement handle */
157955  ){
157956    return fts3SelectDocsize(pTab, iDocid, ppStmt);
157957  }
157958  
157959  /*
157960  ** Similar to fts3SqlStmt(). Except, after binding the parameters in
157961  ** array apVal[] to the SQL statement identified by eStmt, the statement
157962  ** is executed.
157963  **
157964  ** Returns SQLITE_OK if the statement is successfully executed, or an
157965  ** SQLite error code otherwise.
157966  */
157967  static void fts3SqlExec(
157968    int *pRC,                /* Result code */
157969    Fts3Table *p,            /* The FTS3 table */
157970    int eStmt,               /* Index of statement to evaluate */
157971    sqlite3_value **apVal    /* Parameters to bind */
157972  ){
157973    sqlite3_stmt *pStmt;
157974    int rc;
157975    if( *pRC ) return;
157976    rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
157977    if( rc==SQLITE_OK ){
157978      sqlite3_step(pStmt);
157979      rc = sqlite3_reset(pStmt);
157980    }
157981    *pRC = rc;
157982  }
157983  
157984  
157985  /*
157986  ** This function ensures that the caller has obtained an exclusive 
157987  ** shared-cache table-lock on the %_segdir table. This is required before 
157988  ** writing data to the fts3 table. If this lock is not acquired first, then
157989  ** the caller may end up attempting to take this lock as part of committing
157990  ** a transaction, causing SQLite to return SQLITE_LOCKED or 
157991  ** LOCKED_SHAREDCACHEto a COMMIT command.
157992  **
157993  ** It is best to avoid this because if FTS3 returns any error when 
157994  ** committing a transaction, the whole transaction will be rolled back. 
157995  ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. 
157996  ** It can still happen if the user locks the underlying tables directly 
157997  ** instead of accessing them via FTS.
157998  */
157999  static int fts3Writelock(Fts3Table *p){
158000    int rc = SQLITE_OK;
158001    
158002    if( p->nPendingData==0 ){
158003      sqlite3_stmt *pStmt;
158004      rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
158005      if( rc==SQLITE_OK ){
158006        sqlite3_bind_null(pStmt, 1);
158007        sqlite3_step(pStmt);
158008        rc = sqlite3_reset(pStmt);
158009      }
158010    }
158011  
158012    return rc;
158013  }
158014  
158015  /*
158016  ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
158017  ** Within each language id, a separate index is maintained to store the
158018  ** document terms, and each configured prefix size (configured the FTS 
158019  ** "prefix=" option). And each index consists of multiple levels ("relative
158020  ** levels").
158021  **
158022  ** All three of these values (the language id, the specific index and the
158023  ** level within the index) are encoded in 64-bit integer values stored
158024  ** in the %_segdir table on disk. This function is used to convert three
158025  ** separate component values into the single 64-bit integer value that
158026  ** can be used to query the %_segdir table.
158027  **
158028  ** Specifically, each language-id/index combination is allocated 1024 
158029  ** 64-bit integer level values ("absolute levels"). The main terms index
158030  ** for language-id 0 is allocate values 0-1023. The first prefix index
158031  ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
158032  ** Language 1 indexes are allocated immediately following language 0.
158033  **
158034  ** So, for a system with nPrefix prefix indexes configured, the block of
158035  ** absolute levels that corresponds to language-id iLangid and index 
158036  ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
158037  */
158038  static sqlite3_int64 getAbsoluteLevel(
158039    Fts3Table *p,                   /* FTS3 table handle */
158040    int iLangid,                    /* Language id */
158041    int iIndex,                     /* Index in p->aIndex[] */
158042    int iLevel                      /* Level of segments */
158043  ){
158044    sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
158045    assert( iLangid>=0 );
158046    assert( p->nIndex>0 );
158047    assert( iIndex>=0 && iIndex<p->nIndex );
158048  
158049    iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
158050    return iBase + iLevel;
158051  }
158052  
158053  /*
158054  ** Set *ppStmt to a statement handle that may be used to iterate through
158055  ** all rows in the %_segdir table, from oldest to newest. If successful,
158056  ** return SQLITE_OK. If an error occurs while preparing the statement, 
158057  ** return an SQLite error code.
158058  **
158059  ** There is only ever one instance of this SQL statement compiled for
158060  ** each FTS3 table.
158061  **
158062  ** The statement returns the following columns from the %_segdir table:
158063  **
158064  **   0: idx
158065  **   1: start_block
158066  **   2: leaves_end_block
158067  **   3: end_block
158068  **   4: root
158069  */
158070  SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
158071    Fts3Table *p,                   /* FTS3 table */
158072    int iLangid,                    /* Language being queried */
158073    int iIndex,                     /* Index for p->aIndex[] */
158074    int iLevel,                     /* Level to select (relative level) */
158075    sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
158076  ){
158077    int rc;
158078    sqlite3_stmt *pStmt = 0;
158079  
158080    assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
158081    assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
158082    assert( iIndex>=0 && iIndex<p->nIndex );
158083  
158084    if( iLevel<0 ){
158085      /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
158086      rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
158087      if( rc==SQLITE_OK ){ 
158088        sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
158089        sqlite3_bind_int64(pStmt, 2, 
158090            getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
158091        );
158092      }
158093    }else{
158094      /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
158095      rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
158096      if( rc==SQLITE_OK ){ 
158097        sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
158098      }
158099    }
158100    *ppStmt = pStmt;
158101    return rc;
158102  }
158103  
158104  
158105  /*
158106  ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
158107  ** if successful, or an SQLite error code otherwise.
158108  **
158109  ** This function also serves to allocate the PendingList structure itself.
158110  ** For example, to create a new PendingList structure containing two
158111  ** varints:
158112  **
158113  **   PendingList *p = 0;
158114  **   fts3PendingListAppendVarint(&p, 1);
158115  **   fts3PendingListAppendVarint(&p, 2);
158116  */
158117  static int fts3PendingListAppendVarint(
158118    PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
158119    sqlite3_int64 i                 /* Value to append to data */
158120  ){
158121    PendingList *p = *pp;
158122  
158123    /* Allocate or grow the PendingList as required. */
158124    if( !p ){
158125      p = sqlite3_malloc(sizeof(*p) + 100);
158126      if( !p ){
158127        return SQLITE_NOMEM;
158128      }
158129      p->nSpace = 100;
158130      p->aData = (char *)&p[1];
158131      p->nData = 0;
158132    }
158133    else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
158134      int nNew = p->nSpace * 2;
158135      p = sqlite3_realloc(p, sizeof(*p) + nNew);
158136      if( !p ){
158137        sqlite3_free(*pp);
158138        *pp = 0;
158139        return SQLITE_NOMEM;
158140      }
158141      p->nSpace = nNew;
158142      p->aData = (char *)&p[1];
158143    }
158144  
158145    /* Append the new serialized varint to the end of the list. */
158146    p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
158147    p->aData[p->nData] = '\0';
158148    *pp = p;
158149    return SQLITE_OK;
158150  }
158151  
158152  /*
158153  ** Add a docid/column/position entry to a PendingList structure. Non-zero
158154  ** is returned if the structure is sqlite3_realloced as part of adding
158155  ** the entry. Otherwise, zero.
158156  **
158157  ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
158158  ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
158159  ** it is set to SQLITE_OK.
158160  */
158161  static int fts3PendingListAppend(
158162    PendingList **pp,               /* IN/OUT: PendingList structure */
158163    sqlite3_int64 iDocid,           /* Docid for entry to add */
158164    sqlite3_int64 iCol,             /* Column for entry to add */
158165    sqlite3_int64 iPos,             /* Position of term for entry to add */
158166    int *pRc                        /* OUT: Return code */
158167  ){
158168    PendingList *p = *pp;
158169    int rc = SQLITE_OK;
158170  
158171    assert( !p || p->iLastDocid<=iDocid );
158172  
158173    if( !p || p->iLastDocid!=iDocid ){
158174      sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
158175      if( p ){
158176        assert( p->nData<p->nSpace );
158177        assert( p->aData[p->nData]==0 );
158178        p->nData++;
158179      }
158180      if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
158181        goto pendinglistappend_out;
158182      }
158183      p->iLastCol = -1;
158184      p->iLastPos = 0;
158185      p->iLastDocid = iDocid;
158186    }
158187    if( iCol>0 && p->iLastCol!=iCol ){
158188      if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
158189       || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
158190      ){
158191        goto pendinglistappend_out;
158192      }
158193      p->iLastCol = iCol;
158194      p->iLastPos = 0;
158195    }
158196    if( iCol>=0 ){
158197      assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
158198      rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
158199      if( rc==SQLITE_OK ){
158200        p->iLastPos = iPos;
158201      }
158202    }
158203  
158204   pendinglistappend_out:
158205    *pRc = rc;
158206    if( p!=*pp ){
158207      *pp = p;
158208      return 1;
158209    }
158210    return 0;
158211  }
158212  
158213  /*
158214  ** Free a PendingList object allocated by fts3PendingListAppend().
158215  */
158216  static void fts3PendingListDelete(PendingList *pList){
158217    sqlite3_free(pList);
158218  }
158219  
158220  /*
158221  ** Add an entry to one of the pending-terms hash tables.
158222  */
158223  static int fts3PendingTermsAddOne(
158224    Fts3Table *p,
158225    int iCol,
158226    int iPos,
158227    Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
158228    const char *zToken,
158229    int nToken
158230  ){
158231    PendingList *pList;
158232    int rc = SQLITE_OK;
158233  
158234    pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
158235    if( pList ){
158236      p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
158237    }
158238    if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
158239      if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
158240        /* Malloc failed while inserting the new entry. This can only 
158241        ** happen if there was no previous entry for this token.
158242        */
158243        assert( 0==fts3HashFind(pHash, zToken, nToken) );
158244        sqlite3_free(pList);
158245        rc = SQLITE_NOMEM;
158246      }
158247    }
158248    if( rc==SQLITE_OK ){
158249      p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
158250    }
158251    return rc;
158252  }
158253  
158254  /*
158255  ** Tokenize the nul-terminated string zText and add all tokens to the
158256  ** pending-terms hash-table. The docid used is that currently stored in
158257  ** p->iPrevDocid, and the column is specified by argument iCol.
158258  **
158259  ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
158260  */
158261  static int fts3PendingTermsAdd(
158262    Fts3Table *p,                   /* Table into which text will be inserted */
158263    int iLangid,                    /* Language id to use */
158264    const char *zText,              /* Text of document to be inserted */
158265    int iCol,                       /* Column into which text is being inserted */
158266    u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
158267  ){
158268    int rc;
158269    int iStart = 0;
158270    int iEnd = 0;
158271    int iPos = 0;
158272    int nWord = 0;
158273  
158274    char const *zToken;
158275    int nToken = 0;
158276  
158277    sqlite3_tokenizer *pTokenizer = p->pTokenizer;
158278    sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
158279    sqlite3_tokenizer_cursor *pCsr;
158280    int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
158281        const char**,int*,int*,int*,int*);
158282  
158283    assert( pTokenizer && pModule );
158284  
158285    /* If the user has inserted a NULL value, this function may be called with
158286    ** zText==0. In this case, add zero token entries to the hash table and 
158287    ** return early. */
158288    if( zText==0 ){
158289      *pnWord = 0;
158290      return SQLITE_OK;
158291    }
158292  
158293    rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
158294    if( rc!=SQLITE_OK ){
158295      return rc;
158296    }
158297  
158298    xNext = pModule->xNext;
158299    while( SQLITE_OK==rc
158300        && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
158301    ){
158302      int i;
158303      if( iPos>=nWord ) nWord = iPos+1;
158304  
158305      /* Positions cannot be negative; we use -1 as a terminator internally.
158306      ** Tokens must have a non-zero length.
158307      */
158308      if( iPos<0 || !zToken || nToken<=0 ){
158309        rc = SQLITE_ERROR;
158310        break;
158311      }
158312  
158313      /* Add the term to the terms index */
158314      rc = fts3PendingTermsAddOne(
158315          p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
158316      );
158317      
158318      /* Add the term to each of the prefix indexes that it is not too 
158319      ** short for. */
158320      for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
158321        struct Fts3Index *pIndex = &p->aIndex[i];
158322        if( nToken<pIndex->nPrefix ) continue;
158323        rc = fts3PendingTermsAddOne(
158324            p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
158325        );
158326      }
158327    }
158328  
158329    pModule->xClose(pCsr);
158330    *pnWord += nWord;
158331    return (rc==SQLITE_DONE ? SQLITE_OK : rc);
158332  }
158333  
158334  /* 
158335  ** Calling this function indicates that subsequent calls to 
158336  ** fts3PendingTermsAdd() are to add term/position-list pairs for the
158337  ** contents of the document with docid iDocid.
158338  */
158339  static int fts3PendingTermsDocid(
158340    Fts3Table *p,                   /* Full-text table handle */
158341    int bDelete,                    /* True if this op is a delete */
158342    int iLangid,                    /* Language id of row being written */
158343    sqlite_int64 iDocid             /* Docid of row being written */
158344  ){
158345    assert( iLangid>=0 );
158346    assert( bDelete==1 || bDelete==0 );
158347  
158348    /* TODO(shess) Explore whether partially flushing the buffer on
158349    ** forced-flush would provide better performance.  I suspect that if
158350    ** we ordered the doclists by size and flushed the largest until the
158351    ** buffer was half empty, that would let the less frequent terms
158352    ** generate longer doclists.
158353    */
158354    if( iDocid<p->iPrevDocid 
158355     || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
158356     || p->iPrevLangid!=iLangid
158357     || p->nPendingData>p->nMaxPendingData 
158358    ){
158359      int rc = sqlite3Fts3PendingTermsFlush(p);
158360      if( rc!=SQLITE_OK ) return rc;
158361    }
158362    p->iPrevDocid = iDocid;
158363    p->iPrevLangid = iLangid;
158364    p->bPrevDelete = bDelete;
158365    return SQLITE_OK;
158366  }
158367  
158368  /*
158369  ** Discard the contents of the pending-terms hash tables. 
158370  */
158371  SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
158372    int i;
158373    for(i=0; i<p->nIndex; i++){
158374      Fts3HashElem *pElem;
158375      Fts3Hash *pHash = &p->aIndex[i].hPending;
158376      for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
158377        PendingList *pList = (PendingList *)fts3HashData(pElem);
158378        fts3PendingListDelete(pList);
158379      }
158380      fts3HashClear(pHash);
158381    }
158382    p->nPendingData = 0;
158383  }
158384  
158385  /*
158386  ** This function is called by the xUpdate() method as part of an INSERT
158387  ** operation. It adds entries for each term in the new record to the
158388  ** pendingTerms hash table.
158389  **
158390  ** Argument apVal is the same as the similarly named argument passed to
158391  ** fts3InsertData(). Parameter iDocid is the docid of the new row.
158392  */
158393  static int fts3InsertTerms(
158394    Fts3Table *p, 
158395    int iLangid, 
158396    sqlite3_value **apVal, 
158397    u32 *aSz
158398  ){
158399    int i;                          /* Iterator variable */
158400    for(i=2; i<p->nColumn+2; i++){
158401      int iCol = i-2;
158402      if( p->abNotindexed[iCol]==0 ){
158403        const char *zText = (const char *)sqlite3_value_text(apVal[i]);
158404        int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
158405        if( rc!=SQLITE_OK ){
158406          return rc;
158407        }
158408        aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
158409      }
158410    }
158411    return SQLITE_OK;
158412  }
158413  
158414  /*
158415  ** This function is called by the xUpdate() method for an INSERT operation.
158416  ** The apVal parameter is passed a copy of the apVal argument passed by
158417  ** SQLite to the xUpdate() method. i.e:
158418  **
158419  **   apVal[0]                Not used for INSERT.
158420  **   apVal[1]                rowid
158421  **   apVal[2]                Left-most user-defined column
158422  **   ...
158423  **   apVal[p->nColumn+1]     Right-most user-defined column
158424  **   apVal[p->nColumn+2]     Hidden column with same name as table
158425  **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
158426  **   apVal[p->nColumn+4]     Hidden languageid column
158427  */
158428  static int fts3InsertData(
158429    Fts3Table *p,                   /* Full-text table */
158430    sqlite3_value **apVal,          /* Array of values to insert */
158431    sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
158432  ){
158433    int rc;                         /* Return code */
158434    sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
158435  
158436    if( p->zContentTbl ){
158437      sqlite3_value *pRowid = apVal[p->nColumn+3];
158438      if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
158439        pRowid = apVal[1];
158440      }
158441      if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
158442        return SQLITE_CONSTRAINT;
158443      }
158444      *piDocid = sqlite3_value_int64(pRowid);
158445      return SQLITE_OK;
158446    }
158447  
158448    /* Locate the statement handle used to insert data into the %_content
158449    ** table. The SQL for this statement is:
158450    **
158451    **   INSERT INTO %_content VALUES(?, ?, ?, ...)
158452    **
158453    ** The statement features N '?' variables, where N is the number of user
158454    ** defined columns in the FTS3 table, plus one for the docid field.
158455    */
158456    rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
158457    if( rc==SQLITE_OK && p->zLanguageid ){
158458      rc = sqlite3_bind_int(
158459          pContentInsert, p->nColumn+2, 
158460          sqlite3_value_int(apVal[p->nColumn+4])
158461      );
158462    }
158463    if( rc!=SQLITE_OK ) return rc;
158464  
158465    /* There is a quirk here. The users INSERT statement may have specified
158466    ** a value for the "rowid" field, for the "docid" field, or for both.
158467    ** Which is a problem, since "rowid" and "docid" are aliases for the
158468    ** same value. For example:
158469    **
158470    **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
158471    **
158472    ** In FTS3, this is an error. It is an error to specify non-NULL values
158473    ** for both docid and some other rowid alias.
158474    */
158475    if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
158476      if( SQLITE_NULL==sqlite3_value_type(apVal[0])
158477       && SQLITE_NULL!=sqlite3_value_type(apVal[1])
158478      ){
158479        /* A rowid/docid conflict. */
158480        return SQLITE_ERROR;
158481      }
158482      rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
158483      if( rc!=SQLITE_OK ) return rc;
158484    }
158485  
158486    /* Execute the statement to insert the record. Set *piDocid to the 
158487    ** new docid value. 
158488    */
158489    sqlite3_step(pContentInsert);
158490    rc = sqlite3_reset(pContentInsert);
158491  
158492    *piDocid = sqlite3_last_insert_rowid(p->db);
158493    return rc;
158494  }
158495  
158496  
158497  
158498  /*
158499  ** Remove all data from the FTS3 table. Clear the hash table containing
158500  ** pending terms.
158501  */
158502  static int fts3DeleteAll(Fts3Table *p, int bContent){
158503    int rc = SQLITE_OK;             /* Return code */
158504  
158505    /* Discard the contents of the pending-terms hash table. */
158506    sqlite3Fts3PendingTermsClear(p);
158507  
158508    /* Delete everything from the shadow tables. Except, leave %_content as
158509    ** is if bContent is false.  */
158510    assert( p->zContentTbl==0 || bContent==0 );
158511    if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
158512    fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
158513    fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
158514    if( p->bHasDocsize ){
158515      fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
158516    }
158517    if( p->bHasStat ){
158518      fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
158519    }
158520    return rc;
158521  }
158522  
158523  /*
158524  **
158525  */
158526  static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
158527    int iLangid = 0;
158528    if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
158529    return iLangid;
158530  }
158531  
158532  /*
158533  ** The first element in the apVal[] array is assumed to contain the docid
158534  ** (an integer) of a row about to be deleted. Remove all terms from the
158535  ** full-text index.
158536  */
158537  static void fts3DeleteTerms( 
158538    int *pRC,               /* Result code */
158539    Fts3Table *p,           /* The FTS table to delete from */
158540    sqlite3_value *pRowid,  /* The docid to be deleted */
158541    u32 *aSz,               /* Sizes of deleted document written here */
158542    int *pbFound            /* OUT: Set to true if row really does exist */
158543  ){
158544    int rc;
158545    sqlite3_stmt *pSelect;
158546  
158547    assert( *pbFound==0 );
158548    if( *pRC ) return;
158549    rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
158550    if( rc==SQLITE_OK ){
158551      if( SQLITE_ROW==sqlite3_step(pSelect) ){
158552        int i;
158553        int iLangid = langidFromSelect(p, pSelect);
158554        i64 iDocid = sqlite3_column_int64(pSelect, 0);
158555        rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
158556        for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
158557          int iCol = i-1;
158558          if( p->abNotindexed[iCol]==0 ){
158559            const char *zText = (const char *)sqlite3_column_text(pSelect, i);
158560            rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
158561            aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
158562          }
158563        }
158564        if( rc!=SQLITE_OK ){
158565          sqlite3_reset(pSelect);
158566          *pRC = rc;
158567          return;
158568        }
158569        *pbFound = 1;
158570      }
158571      rc = sqlite3_reset(pSelect);
158572    }else{
158573      sqlite3_reset(pSelect);
158574    }
158575    *pRC = rc;
158576  }
158577  
158578  /*
158579  ** Forward declaration to account for the circular dependency between
158580  ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
158581  */
158582  static int fts3SegmentMerge(Fts3Table *, int, int, int);
158583  
158584  /* 
158585  ** This function allocates a new level iLevel index in the segdir table.
158586  ** Usually, indexes are allocated within a level sequentially starting
158587  ** with 0, so the allocated index is one greater than the value returned
158588  ** by:
158589  **
158590  **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
158591  **
158592  ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
158593  ** level, they are merged into a single level (iLevel+1) segment and the 
158594  ** allocated index is 0.
158595  **
158596  ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
158597  ** returned. Otherwise, an SQLite error code is returned.
158598  */
158599  static int fts3AllocateSegdirIdx(
158600    Fts3Table *p, 
158601    int iLangid,                    /* Language id */
158602    int iIndex,                     /* Index for p->aIndex */
158603    int iLevel, 
158604    int *piIdx
158605  ){
158606    int rc;                         /* Return Code */
158607    sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
158608    int iNext = 0;                  /* Result of query pNextIdx */
158609  
158610    assert( iLangid>=0 );
158611    assert( p->nIndex>=1 );
158612  
158613    /* Set variable iNext to the next available segdir index at level iLevel. */
158614    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
158615    if( rc==SQLITE_OK ){
158616      sqlite3_bind_int64(
158617          pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
158618      );
158619      if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
158620        iNext = sqlite3_column_int(pNextIdx, 0);
158621      }
158622      rc = sqlite3_reset(pNextIdx);
158623    }
158624  
158625    if( rc==SQLITE_OK ){
158626      /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
158627      ** full, merge all segments in level iLevel into a single iLevel+1
158628      ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
158629      ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
158630      */
158631      if( iNext>=FTS3_MERGE_COUNT ){
158632        fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
158633        rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
158634        *piIdx = 0;
158635      }else{
158636        *piIdx = iNext;
158637      }
158638    }
158639  
158640    return rc;
158641  }
158642  
158643  /*
158644  ** The %_segments table is declared as follows:
158645  **
158646  **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
158647  **
158648  ** This function reads data from a single row of the %_segments table. The
158649  ** specific row is identified by the iBlockid parameter. If paBlob is not
158650  ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
158651  ** with the contents of the blob stored in the "block" column of the 
158652  ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
158653  ** to the size of the blob in bytes before returning.
158654  **
158655  ** If an error occurs, or the table does not contain the specified row,
158656  ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
158657  ** paBlob is non-NULL, then it is the responsibility of the caller to
158658  ** eventually free the returned buffer.
158659  **
158660  ** This function may leave an open sqlite3_blob* handle in the
158661  ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
158662  ** to this function. The handle may be closed by calling the
158663  ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
158664  ** performance improvement, but the blob handle should always be closed
158665  ** before control is returned to the user (to prevent a lock being held
158666  ** on the database file for longer than necessary). Thus, any virtual table
158667  ** method (xFilter etc.) that may directly or indirectly call this function
158668  ** must call sqlite3Fts3SegmentsClose() before returning.
158669  */
158670  SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
158671    Fts3Table *p,                   /* FTS3 table handle */
158672    sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
158673    char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
158674    int *pnBlob,                    /* OUT: Size of blob data */
158675    int *pnLoad                     /* OUT: Bytes actually loaded */
158676  ){
158677    int rc;                         /* Return code */
158678  
158679    /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
158680    assert( pnBlob );
158681  
158682    if( p->pSegments ){
158683      rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
158684    }else{
158685      if( 0==p->zSegmentsTbl ){
158686        p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
158687        if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
158688      }
158689      rc = sqlite3_blob_open(
158690         p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
158691      );
158692    }
158693  
158694    if( rc==SQLITE_OK ){
158695      int nByte = sqlite3_blob_bytes(p->pSegments);
158696      *pnBlob = nByte;
158697      if( paBlob ){
158698        char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
158699        if( !aByte ){
158700          rc = SQLITE_NOMEM;
158701        }else{
158702          if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
158703            nByte = FTS3_NODE_CHUNKSIZE;
158704            *pnLoad = nByte;
158705          }
158706          rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
158707          memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
158708          if( rc!=SQLITE_OK ){
158709            sqlite3_free(aByte);
158710            aByte = 0;
158711          }
158712        }
158713        *paBlob = aByte;
158714      }
158715    }
158716  
158717    return rc;
158718  }
158719  
158720  /*
158721  ** Close the blob handle at p->pSegments, if it is open. See comments above
158722  ** the sqlite3Fts3ReadBlock() function for details.
158723  */
158724  SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
158725    sqlite3_blob_close(p->pSegments);
158726    p->pSegments = 0;
158727  }
158728      
158729  static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
158730    int nRead;                      /* Number of bytes to read */
158731    int rc;                         /* Return code */
158732  
158733    nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
158734    rc = sqlite3_blob_read(
158735        pReader->pBlob, 
158736        &pReader->aNode[pReader->nPopulate],
158737        nRead,
158738        pReader->nPopulate
158739    );
158740  
158741    if( rc==SQLITE_OK ){
158742      pReader->nPopulate += nRead;
158743      memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
158744      if( pReader->nPopulate==pReader->nNode ){
158745        sqlite3_blob_close(pReader->pBlob);
158746        pReader->pBlob = 0;
158747        pReader->nPopulate = 0;
158748      }
158749    }
158750    return rc;
158751  }
158752  
158753  static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
158754    int rc = SQLITE_OK;
158755    assert( !pReader->pBlob 
158756         || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
158757    );
158758    while( pReader->pBlob && rc==SQLITE_OK 
158759       &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
158760    ){
158761      rc = fts3SegReaderIncrRead(pReader);
158762    }
158763    return rc;
158764  }
158765  
158766  /*
158767  ** Set an Fts3SegReader cursor to point at EOF.
158768  */
158769  static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
158770    if( !fts3SegReaderIsRootOnly(pSeg) ){
158771      sqlite3_free(pSeg->aNode);
158772      sqlite3_blob_close(pSeg->pBlob);
158773      pSeg->pBlob = 0;
158774    }
158775    pSeg->aNode = 0;
158776  }
158777  
158778  /*
158779  ** Move the iterator passed as the first argument to the next term in the
158780  ** segment. If successful, SQLITE_OK is returned. If there is no next term,
158781  ** SQLITE_DONE. Otherwise, an SQLite error code.
158782  */
158783  static int fts3SegReaderNext(
158784    Fts3Table *p, 
158785    Fts3SegReader *pReader,
158786    int bIncr
158787  ){
158788    int rc;                         /* Return code of various sub-routines */
158789    char *pNext;                    /* Cursor variable */
158790    int nPrefix;                    /* Number of bytes in term prefix */
158791    int nSuffix;                    /* Number of bytes in term suffix */
158792  
158793    if( !pReader->aDoclist ){
158794      pNext = pReader->aNode;
158795    }else{
158796      pNext = &pReader->aDoclist[pReader->nDoclist];
158797    }
158798  
158799    if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
158800  
158801      if( fts3SegReaderIsPending(pReader) ){
158802        Fts3HashElem *pElem = *(pReader->ppNextElem);
158803        sqlite3_free(pReader->aNode);
158804        pReader->aNode = 0;
158805        if( pElem ){
158806          char *aCopy;
158807          PendingList *pList = (PendingList *)fts3HashData(pElem);
158808          int nCopy = pList->nData+1;
158809          pReader->zTerm = (char *)fts3HashKey(pElem);
158810          pReader->nTerm = fts3HashKeysize(pElem);
158811          aCopy = (char*)sqlite3_malloc(nCopy);
158812          if( !aCopy ) return SQLITE_NOMEM;
158813          memcpy(aCopy, pList->aData, nCopy);
158814          pReader->nNode = pReader->nDoclist = nCopy;
158815          pReader->aNode = pReader->aDoclist = aCopy;
158816          pReader->ppNextElem++;
158817          assert( pReader->aNode );
158818        }
158819        return SQLITE_OK;
158820      }
158821  
158822      fts3SegReaderSetEof(pReader);
158823  
158824      /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf 
158825      ** blocks have already been traversed.  */
158826      assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
158827      if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
158828        return SQLITE_OK;
158829      }
158830  
158831      rc = sqlite3Fts3ReadBlock(
158832          p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, 
158833          (bIncr ? &pReader->nPopulate : 0)
158834      );
158835      if( rc!=SQLITE_OK ) return rc;
158836      assert( pReader->pBlob==0 );
158837      if( bIncr && pReader->nPopulate<pReader->nNode ){
158838        pReader->pBlob = p->pSegments;
158839        p->pSegments = 0;
158840      }
158841      pNext = pReader->aNode;
158842    }
158843  
158844    assert( !fts3SegReaderIsPending(pReader) );
158845  
158846    rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
158847    if( rc!=SQLITE_OK ) return rc;
158848    
158849    /* Because of the FTS3_NODE_PADDING bytes of padding, the following is 
158850    ** safe (no risk of overread) even if the node data is corrupted. */
158851    pNext += fts3GetVarint32(pNext, &nPrefix);
158852    pNext += fts3GetVarint32(pNext, &nSuffix);
158853    if( nPrefix<0 || nSuffix<=0 
158854     || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] 
158855    ){
158856      return FTS_CORRUPT_VTAB;
158857    }
158858  
158859    if( nPrefix+nSuffix>pReader->nTermAlloc ){
158860      int nNew = (nPrefix+nSuffix)*2;
158861      char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
158862      if( !zNew ){
158863        return SQLITE_NOMEM;
158864      }
158865      pReader->zTerm = zNew;
158866      pReader->nTermAlloc = nNew;
158867    }
158868  
158869    rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
158870    if( rc!=SQLITE_OK ) return rc;
158871  
158872    memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
158873    pReader->nTerm = nPrefix+nSuffix;
158874    pNext += nSuffix;
158875    pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
158876    pReader->aDoclist = pNext;
158877    pReader->pOffsetList = 0;
158878  
158879    /* Check that the doclist does not appear to extend past the end of the
158880    ** b-tree node. And that the final byte of the doclist is 0x00. If either 
158881    ** of these statements is untrue, then the data structure is corrupt.
158882    */
158883    if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] 
158884     || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
158885    ){
158886      return FTS_CORRUPT_VTAB;
158887    }
158888    return SQLITE_OK;
158889  }
158890  
158891  /*
158892  ** Set the SegReader to point to the first docid in the doclist associated
158893  ** with the current term.
158894  */
158895  static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
158896    int rc = SQLITE_OK;
158897    assert( pReader->aDoclist );
158898    assert( !pReader->pOffsetList );
158899    if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
158900      u8 bEof = 0;
158901      pReader->iDocid = 0;
158902      pReader->nOffsetList = 0;
158903      sqlite3Fts3DoclistPrev(0,
158904          pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, 
158905          &pReader->iDocid, &pReader->nOffsetList, &bEof
158906      );
158907    }else{
158908      rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
158909      if( rc==SQLITE_OK ){
158910        int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
158911        pReader->pOffsetList = &pReader->aDoclist[n];
158912      }
158913    }
158914    return rc;
158915  }
158916  
158917  /*
158918  ** Advance the SegReader to point to the next docid in the doclist
158919  ** associated with the current term.
158920  ** 
158921  ** If arguments ppOffsetList and pnOffsetList are not NULL, then 
158922  ** *ppOffsetList is set to point to the first column-offset list
158923  ** in the doclist entry (i.e. immediately past the docid varint).
158924  ** *pnOffsetList is set to the length of the set of column-offset
158925  ** lists, not including the nul-terminator byte. For example:
158926  */
158927  static int fts3SegReaderNextDocid(
158928    Fts3Table *pTab,
158929    Fts3SegReader *pReader,         /* Reader to advance to next docid */
158930    char **ppOffsetList,            /* OUT: Pointer to current position-list */
158931    int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
158932  ){
158933    int rc = SQLITE_OK;
158934    char *p = pReader->pOffsetList;
158935    char c = 0;
158936  
158937    assert( p );
158938  
158939    if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
158940      /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
158941      ** Pending-terms doclists are always built up in ascending order, so
158942      ** we have to iterate through them backwards here. */
158943      u8 bEof = 0;
158944      if( ppOffsetList ){
158945        *ppOffsetList = pReader->pOffsetList;
158946        *pnOffsetList = pReader->nOffsetList - 1;
158947      }
158948      sqlite3Fts3DoclistPrev(0,
158949          pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
158950          &pReader->nOffsetList, &bEof
158951      );
158952      if( bEof ){
158953        pReader->pOffsetList = 0;
158954      }else{
158955        pReader->pOffsetList = p;
158956      }
158957    }else{
158958      char *pEnd = &pReader->aDoclist[pReader->nDoclist];
158959  
158960      /* Pointer p currently points at the first byte of an offset list. The
158961      ** following block advances it to point one byte past the end of
158962      ** the same offset list. */
158963      while( 1 ){
158964    
158965        /* The following line of code (and the "p++" below the while() loop) is
158966        ** normally all that is required to move pointer p to the desired 
158967        ** position. The exception is if this node is being loaded from disk
158968        ** incrementally and pointer "p" now points to the first byte past
158969        ** the populated part of pReader->aNode[].
158970        */
158971        while( *p | c ) c = *p++ & 0x80;
158972        assert( *p==0 );
158973    
158974        if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
158975        rc = fts3SegReaderIncrRead(pReader);
158976        if( rc!=SQLITE_OK ) return rc;
158977      }
158978      p++;
158979    
158980      /* If required, populate the output variables with a pointer to and the
158981      ** size of the previous offset-list.
158982      */
158983      if( ppOffsetList ){
158984        *ppOffsetList = pReader->pOffsetList;
158985        *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
158986      }
158987  
158988      /* List may have been edited in place by fts3EvalNearTrim() */
158989      while( p<pEnd && *p==0 ) p++;
158990    
158991      /* If there are no more entries in the doclist, set pOffsetList to
158992      ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
158993      ** Fts3SegReader.pOffsetList to point to the next offset list before
158994      ** returning.
158995      */
158996      if( p>=pEnd ){
158997        pReader->pOffsetList = 0;
158998      }else{
158999        rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
159000        if( rc==SQLITE_OK ){
159001          sqlite3_int64 iDelta;
159002          pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
159003          if( pTab->bDescIdx ){
159004            pReader->iDocid -= iDelta;
159005          }else{
159006            pReader->iDocid += iDelta;
159007          }
159008        }
159009      }
159010    }
159011  
159012    return SQLITE_OK;
159013  }
159014  
159015  
159016  SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
159017    Fts3Cursor *pCsr, 
159018    Fts3MultiSegReader *pMsr,
159019    int *pnOvfl
159020  ){
159021    Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
159022    int nOvfl = 0;
159023    int ii;
159024    int rc = SQLITE_OK;
159025    int pgsz = p->nPgsz;
159026  
159027    assert( p->bFts4 );
159028    assert( pgsz>0 );
159029  
159030    for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
159031      Fts3SegReader *pReader = pMsr->apSegment[ii];
159032      if( !fts3SegReaderIsPending(pReader) 
159033       && !fts3SegReaderIsRootOnly(pReader) 
159034      ){
159035        sqlite3_int64 jj;
159036        for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
159037          int nBlob;
159038          rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
159039          if( rc!=SQLITE_OK ) break;
159040          if( (nBlob+35)>pgsz ){
159041            nOvfl += (nBlob + 34)/pgsz;
159042          }
159043        }
159044      }
159045    }
159046    *pnOvfl = nOvfl;
159047    return rc;
159048  }
159049  
159050  /*
159051  ** Free all allocations associated with the iterator passed as the 
159052  ** second argument.
159053  */
159054  SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
159055    if( pReader ){
159056      if( !fts3SegReaderIsPending(pReader) ){
159057        sqlite3_free(pReader->zTerm);
159058      }
159059      if( !fts3SegReaderIsRootOnly(pReader) ){
159060        sqlite3_free(pReader->aNode);
159061      }
159062      sqlite3_blob_close(pReader->pBlob);
159063    }
159064    sqlite3_free(pReader);
159065  }
159066  
159067  /*
159068  ** Allocate a new SegReader object.
159069  */
159070  SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
159071    int iAge,                       /* Segment "age". */
159072    int bLookup,                    /* True for a lookup only */
159073    sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
159074    sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
159075    sqlite3_int64 iEndBlock,        /* Final block of segment */
159076    const char *zRoot,              /* Buffer containing root node */
159077    int nRoot,                      /* Size of buffer containing root node */
159078    Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
159079  ){
159080    Fts3SegReader *pReader;         /* Newly allocated SegReader object */
159081    int nExtra = 0;                 /* Bytes to allocate segment root node */
159082  
159083    assert( iStartLeaf<=iEndLeaf );
159084    if( iStartLeaf==0 ){
159085      nExtra = nRoot + FTS3_NODE_PADDING;
159086    }
159087  
159088    pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
159089    if( !pReader ){
159090      return SQLITE_NOMEM;
159091    }
159092    memset(pReader, 0, sizeof(Fts3SegReader));
159093    pReader->iIdx = iAge;
159094    pReader->bLookup = bLookup!=0;
159095    pReader->iStartBlock = iStartLeaf;
159096    pReader->iLeafEndBlock = iEndLeaf;
159097    pReader->iEndBlock = iEndBlock;
159098  
159099    if( nExtra ){
159100      /* The entire segment is stored in the root node. */
159101      pReader->aNode = (char *)&pReader[1];
159102      pReader->rootOnly = 1;
159103      pReader->nNode = nRoot;
159104      memcpy(pReader->aNode, zRoot, nRoot);
159105      memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
159106    }else{
159107      pReader->iCurrentBlock = iStartLeaf-1;
159108    }
159109    *ppReader = pReader;
159110    return SQLITE_OK;
159111  }
159112  
159113  /*
159114  ** This is a comparison function used as a qsort() callback when sorting
159115  ** an array of pending terms by term. This occurs as part of flushing
159116  ** the contents of the pending-terms hash table to the database.
159117  */
159118  static int SQLITE_CDECL fts3CompareElemByTerm(
159119    const void *lhs,
159120    const void *rhs
159121  ){
159122    char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
159123    char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
159124    int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
159125    int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
159126  
159127    int n = (n1<n2 ? n1 : n2);
159128    int c = memcmp(z1, z2, n);
159129    if( c==0 ){
159130      c = n1 - n2;
159131    }
159132    return c;
159133  }
159134  
159135  /*
159136  ** This function is used to allocate an Fts3SegReader that iterates through
159137  ** a subset of the terms stored in the Fts3Table.pendingTerms array.
159138  **
159139  ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
159140  ** through each term in the pending-terms table. Or, if isPrefixIter is
159141  ** non-zero, it iterates through each term and its prefixes. For example, if
159142  ** the pending terms hash table contains the terms "sqlite", "mysql" and
159143  ** "firebird", then the iterator visits the following 'terms' (in the order
159144  ** shown):
159145  **
159146  **   f fi fir fire fireb firebi firebir firebird
159147  **   m my mys mysq mysql
159148  **   s sq sql sqli sqlit sqlite
159149  **
159150  ** Whereas if isPrefixIter is zero, the terms visited are:
159151  **
159152  **   firebird mysql sqlite
159153  */
159154  SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
159155    Fts3Table *p,                   /* Virtual table handle */
159156    int iIndex,                     /* Index for p->aIndex */
159157    const char *zTerm,              /* Term to search for */
159158    int nTerm,                      /* Size of buffer zTerm */
159159    int bPrefix,                    /* True for a prefix iterator */
159160    Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
159161  ){
159162    Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
159163    Fts3HashElem *pE;               /* Iterator variable */
159164    Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
159165    int nElem = 0;                  /* Size of array at aElem */
159166    int rc = SQLITE_OK;             /* Return Code */
159167    Fts3Hash *pHash;
159168  
159169    pHash = &p->aIndex[iIndex].hPending;
159170    if( bPrefix ){
159171      int nAlloc = 0;               /* Size of allocated array at aElem */
159172  
159173      for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
159174        char *zKey = (char *)fts3HashKey(pE);
159175        int nKey = fts3HashKeysize(pE);
159176        if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
159177          if( nElem==nAlloc ){
159178            Fts3HashElem **aElem2;
159179            nAlloc += 16;
159180            aElem2 = (Fts3HashElem **)sqlite3_realloc(
159181                aElem, nAlloc*sizeof(Fts3HashElem *)
159182            );
159183            if( !aElem2 ){
159184              rc = SQLITE_NOMEM;
159185              nElem = 0;
159186              break;
159187            }
159188            aElem = aElem2;
159189          }
159190  
159191          aElem[nElem++] = pE;
159192        }
159193      }
159194  
159195      /* If more than one term matches the prefix, sort the Fts3HashElem
159196      ** objects in term order using qsort(). This uses the same comparison
159197      ** callback as is used when flushing terms to disk.
159198      */
159199      if( nElem>1 ){
159200        qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
159201      }
159202  
159203    }else{
159204      /* The query is a simple term lookup that matches at most one term in
159205      ** the index. All that is required is a straight hash-lookup. 
159206      **
159207      ** Because the stack address of pE may be accessed via the aElem pointer
159208      ** below, the "Fts3HashElem *pE" must be declared so that it is valid
159209      ** within this entire function, not just this "else{...}" block.
159210      */
159211      pE = fts3HashFindElem(pHash, zTerm, nTerm);
159212      if( pE ){
159213        aElem = &pE;
159214        nElem = 1;
159215      }
159216    }
159217  
159218    if( nElem>0 ){
159219      int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
159220      pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
159221      if( !pReader ){
159222        rc = SQLITE_NOMEM;
159223      }else{
159224        memset(pReader, 0, nByte);
159225        pReader->iIdx = 0x7FFFFFFF;
159226        pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
159227        memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
159228      }
159229    }
159230  
159231    if( bPrefix ){
159232      sqlite3_free(aElem);
159233    }
159234    *ppReader = pReader;
159235    return rc;
159236  }
159237  
159238  /*
159239  ** Compare the entries pointed to by two Fts3SegReader structures. 
159240  ** Comparison is as follows:
159241  **
159242  **   1) EOF is greater than not EOF.
159243  **
159244  **   2) The current terms (if any) are compared using memcmp(). If one
159245  **      term is a prefix of another, the longer term is considered the
159246  **      larger.
159247  **
159248  **   3) By segment age. An older segment is considered larger.
159249  */
159250  static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
159251    int rc;
159252    if( pLhs->aNode && pRhs->aNode ){
159253      int rc2 = pLhs->nTerm - pRhs->nTerm;
159254      if( rc2<0 ){
159255        rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
159256      }else{
159257        rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
159258      }
159259      if( rc==0 ){
159260        rc = rc2;
159261      }
159262    }else{
159263      rc = (pLhs->aNode==0) - (pRhs->aNode==0);
159264    }
159265    if( rc==0 ){
159266      rc = pRhs->iIdx - pLhs->iIdx;
159267    }
159268    assert( rc!=0 );
159269    return rc;
159270  }
159271  
159272  /*
159273  ** A different comparison function for SegReader structures. In this
159274  ** version, it is assumed that each SegReader points to an entry in
159275  ** a doclist for identical terms. Comparison is made as follows:
159276  **
159277  **   1) EOF (end of doclist in this case) is greater than not EOF.
159278  **
159279  **   2) By current docid.
159280  **
159281  **   3) By segment age. An older segment is considered larger.
159282  */
159283  static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
159284    int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
159285    if( rc==0 ){
159286      if( pLhs->iDocid==pRhs->iDocid ){
159287        rc = pRhs->iIdx - pLhs->iIdx;
159288      }else{
159289        rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
159290      }
159291    }
159292    assert( pLhs->aNode && pRhs->aNode );
159293    return rc;
159294  }
159295  static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
159296    int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
159297    if( rc==0 ){
159298      if( pLhs->iDocid==pRhs->iDocid ){
159299        rc = pRhs->iIdx - pLhs->iIdx;
159300      }else{
159301        rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
159302      }
159303    }
159304    assert( pLhs->aNode && pRhs->aNode );
159305    return rc;
159306  }
159307  
159308  /*
159309  ** Compare the term that the Fts3SegReader object passed as the first argument
159310  ** points to with the term specified by arguments zTerm and nTerm. 
159311  **
159312  ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
159313  ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
159314  ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
159315  */
159316  static int fts3SegReaderTermCmp(
159317    Fts3SegReader *pSeg,            /* Segment reader object */
159318    const char *zTerm,              /* Term to compare to */
159319    int nTerm                       /* Size of term zTerm in bytes */
159320  ){
159321    int res = 0;
159322    if( pSeg->aNode ){
159323      if( pSeg->nTerm>nTerm ){
159324        res = memcmp(pSeg->zTerm, zTerm, nTerm);
159325      }else{
159326        res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
159327      }
159328      if( res==0 ){
159329        res = pSeg->nTerm-nTerm;
159330      }
159331    }
159332    return res;
159333  }
159334  
159335  /*
159336  ** Argument apSegment is an array of nSegment elements. It is known that
159337  ** the final (nSegment-nSuspect) members are already in sorted order
159338  ** (according to the comparison function provided). This function shuffles
159339  ** the array around until all entries are in sorted order.
159340  */
159341  static void fts3SegReaderSort(
159342    Fts3SegReader **apSegment,                     /* Array to sort entries of */
159343    int nSegment,                                  /* Size of apSegment array */
159344    int nSuspect,                                  /* Unsorted entry count */
159345    int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
159346  ){
159347    int i;                          /* Iterator variable */
159348  
159349    assert( nSuspect<=nSegment );
159350  
159351    if( nSuspect==nSegment ) nSuspect--;
159352    for(i=nSuspect-1; i>=0; i--){
159353      int j;
159354      for(j=i; j<(nSegment-1); j++){
159355        Fts3SegReader *pTmp;
159356        if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
159357        pTmp = apSegment[j+1];
159358        apSegment[j+1] = apSegment[j];
159359        apSegment[j] = pTmp;
159360      }
159361    }
159362  
159363  #ifndef NDEBUG
159364    /* Check that the list really is sorted now. */
159365    for(i=0; i<(nSuspect-1); i++){
159366      assert( xCmp(apSegment[i], apSegment[i+1])<0 );
159367    }
159368  #endif
159369  }
159370  
159371  /* 
159372  ** Insert a record into the %_segments table.
159373  */
159374  static int fts3WriteSegment(
159375    Fts3Table *p,                   /* Virtual table handle */
159376    sqlite3_int64 iBlock,           /* Block id for new block */
159377    char *z,                        /* Pointer to buffer containing block data */
159378    int n                           /* Size of buffer z in bytes */
159379  ){
159380    sqlite3_stmt *pStmt;
159381    int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
159382    if( rc==SQLITE_OK ){
159383      sqlite3_bind_int64(pStmt, 1, iBlock);
159384      sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
159385      sqlite3_step(pStmt);
159386      rc = sqlite3_reset(pStmt);
159387    }
159388    return rc;
159389  }
159390  
159391  /*
159392  ** Find the largest relative level number in the table. If successful, set
159393  ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
159394  ** set *pnMax to zero and return an SQLite error code.
159395  */
159396  SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
159397    int rc;
159398    int mxLevel = 0;
159399    sqlite3_stmt *pStmt = 0;
159400  
159401    rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
159402    if( rc==SQLITE_OK ){
159403      if( SQLITE_ROW==sqlite3_step(pStmt) ){
159404        mxLevel = sqlite3_column_int(pStmt, 0);
159405      }
159406      rc = sqlite3_reset(pStmt);
159407    }
159408    *pnMax = mxLevel;
159409    return rc;
159410  }
159411  
159412  /* 
159413  ** Insert a record into the %_segdir table.
159414  */
159415  static int fts3WriteSegdir(
159416    Fts3Table *p,                   /* Virtual table handle */
159417    sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
159418    int iIdx,                       /* Value for "idx" field */
159419    sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
159420    sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
159421    sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
159422    sqlite3_int64 nLeafData,        /* Bytes of leaf data in segment */
159423    char *zRoot,                    /* Blob value for "root" field */
159424    int nRoot                       /* Number of bytes in buffer zRoot */
159425  ){
159426    sqlite3_stmt *pStmt;
159427    int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
159428    if( rc==SQLITE_OK ){
159429      sqlite3_bind_int64(pStmt, 1, iLevel);
159430      sqlite3_bind_int(pStmt, 2, iIdx);
159431      sqlite3_bind_int64(pStmt, 3, iStartBlock);
159432      sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
159433      if( nLeafData==0 ){
159434        sqlite3_bind_int64(pStmt, 5, iEndBlock);
159435      }else{
159436        char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
159437        if( !zEnd ) return SQLITE_NOMEM;
159438        sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
159439      }
159440      sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
159441      sqlite3_step(pStmt);
159442      rc = sqlite3_reset(pStmt);
159443    }
159444    return rc;
159445  }
159446  
159447  /*
159448  ** Return the size of the common prefix (if any) shared by zPrev and
159449  ** zNext, in bytes. For example, 
159450  **
159451  **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
159452  **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
159453  **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
159454  */
159455  static int fts3PrefixCompress(
159456    const char *zPrev,              /* Buffer containing previous term */
159457    int nPrev,                      /* Size of buffer zPrev in bytes */
159458    const char *zNext,              /* Buffer containing next term */
159459    int nNext                       /* Size of buffer zNext in bytes */
159460  ){
159461    int n;
159462    UNUSED_PARAMETER(nNext);
159463    for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
159464    return n;
159465  }
159466  
159467  /*
159468  ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
159469  ** (according to memcmp) than the previous term.
159470  */
159471  static int fts3NodeAddTerm(
159472    Fts3Table *p,                   /* Virtual table handle */
159473    SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
159474    int isCopyTerm,                 /* True if zTerm/nTerm is transient */
159475    const char *zTerm,              /* Pointer to buffer containing term */
159476    int nTerm                       /* Size of term in bytes */
159477  ){
159478    SegmentNode *pTree = *ppTree;
159479    int rc;
159480    SegmentNode *pNew;
159481  
159482    /* First try to append the term to the current node. Return early if 
159483    ** this is possible.
159484    */
159485    if( pTree ){
159486      int nData = pTree->nData;     /* Current size of node in bytes */
159487      int nReq = nData;             /* Required space after adding zTerm */
159488      int nPrefix;                  /* Number of bytes of prefix compression */
159489      int nSuffix;                  /* Suffix length */
159490  
159491      nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
159492      nSuffix = nTerm-nPrefix;
159493  
159494      nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
159495      if( nReq<=p->nNodeSize || !pTree->zTerm ){
159496  
159497        if( nReq>p->nNodeSize ){
159498          /* An unusual case: this is the first term to be added to the node
159499          ** and the static node buffer (p->nNodeSize bytes) is not large
159500          ** enough. Use a separately malloced buffer instead This wastes
159501          ** p->nNodeSize bytes, but since this scenario only comes about when
159502          ** the database contain two terms that share a prefix of almost 2KB, 
159503          ** this is not expected to be a serious problem. 
159504          */
159505          assert( pTree->aData==(char *)&pTree[1] );
159506          pTree->aData = (char *)sqlite3_malloc(nReq);
159507          if( !pTree->aData ){
159508            return SQLITE_NOMEM;
159509          }
159510        }
159511  
159512        if( pTree->zTerm ){
159513          /* There is no prefix-length field for first term in a node */
159514          nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
159515        }
159516  
159517        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
159518        memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
159519        pTree->nData = nData + nSuffix;
159520        pTree->nEntry++;
159521  
159522        if( isCopyTerm ){
159523          if( pTree->nMalloc<nTerm ){
159524            char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
159525            if( !zNew ){
159526              return SQLITE_NOMEM;
159527            }
159528            pTree->nMalloc = nTerm*2;
159529            pTree->zMalloc = zNew;
159530          }
159531          pTree->zTerm = pTree->zMalloc;
159532          memcpy(pTree->zTerm, zTerm, nTerm);
159533          pTree->nTerm = nTerm;
159534        }else{
159535          pTree->zTerm = (char *)zTerm;
159536          pTree->nTerm = nTerm;
159537        }
159538        return SQLITE_OK;
159539      }
159540    }
159541  
159542    /* If control flows to here, it was not possible to append zTerm to the
159543    ** current node. Create a new node (a right-sibling of the current node).
159544    ** If this is the first node in the tree, the term is added to it.
159545    **
159546    ** Otherwise, the term is not added to the new node, it is left empty for
159547    ** now. Instead, the term is inserted into the parent of pTree. If pTree 
159548    ** has no parent, one is created here.
159549    */
159550    pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
159551    if( !pNew ){
159552      return SQLITE_NOMEM;
159553    }
159554    memset(pNew, 0, sizeof(SegmentNode));
159555    pNew->nData = 1 + FTS3_VARINT_MAX;
159556    pNew->aData = (char *)&pNew[1];
159557  
159558    if( pTree ){
159559      SegmentNode *pParent = pTree->pParent;
159560      rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
159561      if( pTree->pParent==0 ){
159562        pTree->pParent = pParent;
159563      }
159564      pTree->pRight = pNew;
159565      pNew->pLeftmost = pTree->pLeftmost;
159566      pNew->pParent = pParent;
159567      pNew->zMalloc = pTree->zMalloc;
159568      pNew->nMalloc = pTree->nMalloc;
159569      pTree->zMalloc = 0;
159570    }else{
159571      pNew->pLeftmost = pNew;
159572      rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
159573    }
159574  
159575    *ppTree = pNew;
159576    return rc;
159577  }
159578  
159579  /*
159580  ** Helper function for fts3NodeWrite().
159581  */
159582  static int fts3TreeFinishNode(
159583    SegmentNode *pTree, 
159584    int iHeight, 
159585    sqlite3_int64 iLeftChild
159586  ){
159587    int nStart;
159588    assert( iHeight>=1 && iHeight<128 );
159589    nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
159590    pTree->aData[nStart] = (char)iHeight;
159591    sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
159592    return nStart;
159593  }
159594  
159595  /*
159596  ** Write the buffer for the segment node pTree and all of its peers to the
159597  ** database. Then call this function recursively to write the parent of 
159598  ** pTree and its peers to the database. 
159599  **
159600  ** Except, if pTree is a root node, do not write it to the database. Instead,
159601  ** set output variables *paRoot and *pnRoot to contain the root node.
159602  **
159603  ** If successful, SQLITE_OK is returned and output variable *piLast is
159604  ** set to the largest blockid written to the database (or zero if no
159605  ** blocks were written to the db). Otherwise, an SQLite error code is 
159606  ** returned.
159607  */
159608  static int fts3NodeWrite(
159609    Fts3Table *p,                   /* Virtual table handle */
159610    SegmentNode *pTree,             /* SegmentNode handle */
159611    int iHeight,                    /* Height of this node in tree */
159612    sqlite3_int64 iLeaf,            /* Block id of first leaf node */
159613    sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
159614    sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
159615    char **paRoot,                  /* OUT: Data for root node */
159616    int *pnRoot                     /* OUT: Size of root node in bytes */
159617  ){
159618    int rc = SQLITE_OK;
159619  
159620    if( !pTree->pParent ){
159621      /* Root node of the tree. */
159622      int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
159623      *piLast = iFree-1;
159624      *pnRoot = pTree->nData - nStart;
159625      *paRoot = &pTree->aData[nStart];
159626    }else{
159627      SegmentNode *pIter;
159628      sqlite3_int64 iNextFree = iFree;
159629      sqlite3_int64 iNextLeaf = iLeaf;
159630      for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
159631        int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
159632        int nWrite = pIter->nData - nStart;
159633    
159634        rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
159635        iNextFree++;
159636        iNextLeaf += (pIter->nEntry+1);
159637      }
159638      if( rc==SQLITE_OK ){
159639        assert( iNextLeaf==iFree );
159640        rc = fts3NodeWrite(
159641            p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
159642        );
159643      }
159644    }
159645  
159646    return rc;
159647  }
159648  
159649  /*
159650  ** Free all memory allocations associated with the tree pTree.
159651  */
159652  static void fts3NodeFree(SegmentNode *pTree){
159653    if( pTree ){
159654      SegmentNode *p = pTree->pLeftmost;
159655      fts3NodeFree(p->pParent);
159656      while( p ){
159657        SegmentNode *pRight = p->pRight;
159658        if( p->aData!=(char *)&p[1] ){
159659          sqlite3_free(p->aData);
159660        }
159661        assert( pRight==0 || p->zMalloc==0 );
159662        sqlite3_free(p->zMalloc);
159663        sqlite3_free(p);
159664        p = pRight;
159665      }
159666    }
159667  }
159668  
159669  /*
159670  ** Add a term to the segment being constructed by the SegmentWriter object
159671  ** *ppWriter. When adding the first term to a segment, *ppWriter should
159672  ** be passed NULL. This function will allocate a new SegmentWriter object
159673  ** and return it via the input/output variable *ppWriter in this case.
159674  **
159675  ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
159676  */
159677  static int fts3SegWriterAdd(
159678    Fts3Table *p,                   /* Virtual table handle */
159679    SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
159680    int isCopyTerm,                 /* True if buffer zTerm must be copied */
159681    const char *zTerm,              /* Pointer to buffer containing term */
159682    int nTerm,                      /* Size of term in bytes */
159683    const char *aDoclist,           /* Pointer to buffer containing doclist */
159684    int nDoclist                    /* Size of doclist in bytes */
159685  ){
159686    int nPrefix;                    /* Size of term prefix in bytes */
159687    int nSuffix;                    /* Size of term suffix in bytes */
159688    int nReq;                       /* Number of bytes required on leaf page */
159689    int nData;
159690    SegmentWriter *pWriter = *ppWriter;
159691  
159692    if( !pWriter ){
159693      int rc;
159694      sqlite3_stmt *pStmt;
159695  
159696      /* Allocate the SegmentWriter structure */
159697      pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
159698      if( !pWriter ) return SQLITE_NOMEM;
159699      memset(pWriter, 0, sizeof(SegmentWriter));
159700      *ppWriter = pWriter;
159701  
159702      /* Allocate a buffer in which to accumulate data */
159703      pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
159704      if( !pWriter->aData ) return SQLITE_NOMEM;
159705      pWriter->nSize = p->nNodeSize;
159706  
159707      /* Find the next free blockid in the %_segments table */
159708      rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
159709      if( rc!=SQLITE_OK ) return rc;
159710      if( SQLITE_ROW==sqlite3_step(pStmt) ){
159711        pWriter->iFree = sqlite3_column_int64(pStmt, 0);
159712        pWriter->iFirst = pWriter->iFree;
159713      }
159714      rc = sqlite3_reset(pStmt);
159715      if( rc!=SQLITE_OK ) return rc;
159716    }
159717    nData = pWriter->nData;
159718  
159719    nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
159720    nSuffix = nTerm-nPrefix;
159721  
159722    /* Figure out how many bytes are required by this new entry */
159723    nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
159724      sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
159725      nSuffix +                               /* Term suffix */
159726      sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
159727      nDoclist;                               /* Doclist data */
159728  
159729    if( nData>0 && nData+nReq>p->nNodeSize ){
159730      int rc;
159731  
159732      /* The current leaf node is full. Write it out to the database. */
159733      rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
159734      if( rc!=SQLITE_OK ) return rc;
159735      p->nLeafAdd++;
159736  
159737      /* Add the current term to the interior node tree. The term added to
159738      ** the interior tree must:
159739      **
159740      **   a) be greater than the largest term on the leaf node just written
159741      **      to the database (still available in pWriter->zTerm), and
159742      **
159743      **   b) be less than or equal to the term about to be added to the new
159744      **      leaf node (zTerm/nTerm).
159745      **
159746      ** In other words, it must be the prefix of zTerm 1 byte longer than
159747      ** the common prefix (if any) of zTerm and pWriter->zTerm.
159748      */
159749      assert( nPrefix<nTerm );
159750      rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
159751      if( rc!=SQLITE_OK ) return rc;
159752  
159753      nData = 0;
159754      pWriter->nTerm = 0;
159755  
159756      nPrefix = 0;
159757      nSuffix = nTerm;
159758      nReq = 1 +                              /* varint containing prefix size */
159759        sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
159760        nTerm +                               /* Term suffix */
159761        sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
159762        nDoclist;                             /* Doclist data */
159763    }
159764  
159765    /* Increase the total number of bytes written to account for the new entry. */
159766    pWriter->nLeafData += nReq;
159767  
159768    /* If the buffer currently allocated is too small for this entry, realloc
159769    ** the buffer to make it large enough.
159770    */
159771    if( nReq>pWriter->nSize ){
159772      char *aNew = sqlite3_realloc(pWriter->aData, nReq);
159773      if( !aNew ) return SQLITE_NOMEM;
159774      pWriter->aData = aNew;
159775      pWriter->nSize = nReq;
159776    }
159777    assert( nData+nReq<=pWriter->nSize );
159778  
159779    /* Append the prefix-compressed term and doclist to the buffer. */
159780    nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
159781    nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
159782    memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
159783    nData += nSuffix;
159784    nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
159785    memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
159786    pWriter->nData = nData + nDoclist;
159787  
159788    /* Save the current term so that it can be used to prefix-compress the next.
159789    ** If the isCopyTerm parameter is true, then the buffer pointed to by
159790    ** zTerm is transient, so take a copy of the term data. Otherwise, just
159791    ** store a copy of the pointer.
159792    */
159793    if( isCopyTerm ){
159794      if( nTerm>pWriter->nMalloc ){
159795        char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
159796        if( !zNew ){
159797          return SQLITE_NOMEM;
159798        }
159799        pWriter->nMalloc = nTerm*2;
159800        pWriter->zMalloc = zNew;
159801        pWriter->zTerm = zNew;
159802      }
159803      assert( pWriter->zTerm==pWriter->zMalloc );
159804      memcpy(pWriter->zTerm, zTerm, nTerm);
159805    }else{
159806      pWriter->zTerm = (char *)zTerm;
159807    }
159808    pWriter->nTerm = nTerm;
159809  
159810    return SQLITE_OK;
159811  }
159812  
159813  /*
159814  ** Flush all data associated with the SegmentWriter object pWriter to the
159815  ** database. This function must be called after all terms have been added
159816  ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
159817  ** returned. Otherwise, an SQLite error code.
159818  */
159819  static int fts3SegWriterFlush(
159820    Fts3Table *p,                   /* Virtual table handle */
159821    SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
159822    sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
159823    int iIdx                        /* Value for 'idx' column of %_segdir */
159824  ){
159825    int rc;                         /* Return code */
159826    if( pWriter->pTree ){
159827      sqlite3_int64 iLast = 0;      /* Largest block id written to database */
159828      sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
159829      char *zRoot = NULL;           /* Pointer to buffer containing root node */
159830      int nRoot = 0;                /* Size of buffer zRoot */
159831  
159832      iLastLeaf = pWriter->iFree;
159833      rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
159834      if( rc==SQLITE_OK ){
159835        rc = fts3NodeWrite(p, pWriter->pTree, 1,
159836            pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
159837      }
159838      if( rc==SQLITE_OK ){
159839        rc = fts3WriteSegdir(p, iLevel, iIdx, 
159840            pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
159841      }
159842    }else{
159843      /* The entire tree fits on the root node. Write it to the segdir table. */
159844      rc = fts3WriteSegdir(p, iLevel, iIdx, 
159845          0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
159846    }
159847    p->nLeafAdd++;
159848    return rc;
159849  }
159850  
159851  /*
159852  ** Release all memory held by the SegmentWriter object passed as the 
159853  ** first argument.
159854  */
159855  static void fts3SegWriterFree(SegmentWriter *pWriter){
159856    if( pWriter ){
159857      sqlite3_free(pWriter->aData);
159858      sqlite3_free(pWriter->zMalloc);
159859      fts3NodeFree(pWriter->pTree);
159860      sqlite3_free(pWriter);
159861    }
159862  }
159863  
159864  /*
159865  ** The first value in the apVal[] array is assumed to contain an integer.
159866  ** This function tests if there exist any documents with docid values that
159867  ** are different from that integer. i.e. if deleting the document with docid
159868  ** pRowid would mean the FTS3 table were empty.
159869  **
159870  ** If successful, *pisEmpty is set to true if the table is empty except for
159871  ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
159872  ** error occurs, an SQLite error code is returned.
159873  */
159874  static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
159875    sqlite3_stmt *pStmt;
159876    int rc;
159877    if( p->zContentTbl ){
159878      /* If using the content=xxx option, assume the table is never empty */
159879      *pisEmpty = 0;
159880      rc = SQLITE_OK;
159881    }else{
159882      rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
159883      if( rc==SQLITE_OK ){
159884        if( SQLITE_ROW==sqlite3_step(pStmt) ){
159885          *pisEmpty = sqlite3_column_int(pStmt, 0);
159886        }
159887        rc = sqlite3_reset(pStmt);
159888      }
159889    }
159890    return rc;
159891  }
159892  
159893  /*
159894  ** Set *pnMax to the largest segment level in the database for the index
159895  ** iIndex.
159896  **
159897  ** Segment levels are stored in the 'level' column of the %_segdir table.
159898  **
159899  ** Return SQLITE_OK if successful, or an SQLite error code if not.
159900  */
159901  static int fts3SegmentMaxLevel(
159902    Fts3Table *p, 
159903    int iLangid,
159904    int iIndex, 
159905    sqlite3_int64 *pnMax
159906  ){
159907    sqlite3_stmt *pStmt;
159908    int rc;
159909    assert( iIndex>=0 && iIndex<p->nIndex );
159910  
159911    /* Set pStmt to the compiled version of:
159912    **
159913    **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
159914    **
159915    ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
159916    */
159917    rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
159918    if( rc!=SQLITE_OK ) return rc;
159919    sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
159920    sqlite3_bind_int64(pStmt, 2, 
159921        getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
159922    );
159923    if( SQLITE_ROW==sqlite3_step(pStmt) ){
159924      *pnMax = sqlite3_column_int64(pStmt, 0);
159925    }
159926    return sqlite3_reset(pStmt);
159927  }
159928  
159929  /*
159930  ** iAbsLevel is an absolute level that may be assumed to exist within
159931  ** the database. This function checks if it is the largest level number
159932  ** within its index. Assuming no error occurs, *pbMax is set to 1 if
159933  ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
159934  ** is returned. If an error occurs, an error code is returned and the
159935  ** final value of *pbMax is undefined.
159936  */
159937  static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
159938  
159939    /* Set pStmt to the compiled version of:
159940    **
159941    **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
159942    **
159943    ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
159944    */
159945    sqlite3_stmt *pStmt;
159946    int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
159947    if( rc!=SQLITE_OK ) return rc;
159948    sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
159949    sqlite3_bind_int64(pStmt, 2, 
159950        ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
159951    );
159952  
159953    *pbMax = 0;
159954    if( SQLITE_ROW==sqlite3_step(pStmt) ){
159955      *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
159956    }
159957    return sqlite3_reset(pStmt);
159958  }
159959  
159960  /*
159961  ** Delete all entries in the %_segments table associated with the segment
159962  ** opened with seg-reader pSeg. This function does not affect the contents
159963  ** of the %_segdir table.
159964  */
159965  static int fts3DeleteSegment(
159966    Fts3Table *p,                   /* FTS table handle */
159967    Fts3SegReader *pSeg             /* Segment to delete */
159968  ){
159969    int rc = SQLITE_OK;             /* Return code */
159970    if( pSeg->iStartBlock ){
159971      sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
159972      rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
159973      if( rc==SQLITE_OK ){
159974        sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
159975        sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
159976        sqlite3_step(pDelete);
159977        rc = sqlite3_reset(pDelete);
159978      }
159979    }
159980    return rc;
159981  }
159982  
159983  /*
159984  ** This function is used after merging multiple segments into a single large
159985  ** segment to delete the old, now redundant, segment b-trees. Specifically,
159986  ** it:
159987  ** 
159988  **   1) Deletes all %_segments entries for the segments associated with 
159989  **      each of the SegReader objects in the array passed as the third 
159990  **      argument, and
159991  **
159992  **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
159993  **      entries regardless of level if (iLevel<0).
159994  **
159995  ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
159996  */
159997  static int fts3DeleteSegdir(
159998    Fts3Table *p,                   /* Virtual table handle */
159999    int iLangid,                    /* Language id */
160000    int iIndex,                     /* Index for p->aIndex */
160001    int iLevel,                     /* Level of %_segdir entries to delete */
160002    Fts3SegReader **apSegment,      /* Array of SegReader objects */
160003    int nReader                     /* Size of array apSegment */
160004  ){
160005    int rc = SQLITE_OK;             /* Return Code */
160006    int i;                          /* Iterator variable */
160007    sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
160008  
160009    for(i=0; rc==SQLITE_OK && i<nReader; i++){
160010      rc = fts3DeleteSegment(p, apSegment[i]);
160011    }
160012    if( rc!=SQLITE_OK ){
160013      return rc;
160014    }
160015  
160016    assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
160017    if( iLevel==FTS3_SEGCURSOR_ALL ){
160018      rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
160019      if( rc==SQLITE_OK ){
160020        sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
160021        sqlite3_bind_int64(pDelete, 2, 
160022            getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
160023        );
160024      }
160025    }else{
160026      rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
160027      if( rc==SQLITE_OK ){
160028        sqlite3_bind_int64(
160029            pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
160030        );
160031      }
160032    }
160033  
160034    if( rc==SQLITE_OK ){
160035      sqlite3_step(pDelete);
160036      rc = sqlite3_reset(pDelete);
160037    }
160038  
160039    return rc;
160040  }
160041  
160042  /*
160043  ** When this function is called, buffer *ppList (size *pnList bytes) contains 
160044  ** a position list that may (or may not) feature multiple columns. This
160045  ** function adjusts the pointer *ppList and the length *pnList so that they
160046  ** identify the subset of the position list that corresponds to column iCol.
160047  **
160048  ** If there are no entries in the input position list for column iCol, then
160049  ** *pnList is set to zero before returning.
160050  **
160051  ** If parameter bZero is non-zero, then any part of the input list following
160052  ** the end of the output list is zeroed before returning.
160053  */
160054  static void fts3ColumnFilter(
160055    int iCol,                       /* Column to filter on */
160056    int bZero,                      /* Zero out anything following *ppList */
160057    char **ppList,                  /* IN/OUT: Pointer to position list */
160058    int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
160059  ){
160060    char *pList = *ppList;
160061    int nList = *pnList;
160062    char *pEnd = &pList[nList];
160063    int iCurrent = 0;
160064    char *p = pList;
160065  
160066    assert( iCol>=0 );
160067    while( 1 ){
160068      char c = 0;
160069      while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
160070    
160071      if( iCol==iCurrent ){
160072        nList = (int)(p - pList);
160073        break;
160074      }
160075  
160076      nList -= (int)(p - pList);
160077      pList = p;
160078      if( nList==0 ){
160079        break;
160080      }
160081      p = &pList[1];
160082      p += fts3GetVarint32(p, &iCurrent);
160083    }
160084  
160085    if( bZero && &pList[nList]!=pEnd ){
160086      memset(&pList[nList], 0, pEnd - &pList[nList]);
160087    }
160088    *ppList = pList;
160089    *pnList = nList;
160090  }
160091  
160092  /*
160093  ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
160094  ** existing data). Grow the buffer if required.
160095  **
160096  ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
160097  ** trying to resize the buffer, return SQLITE_NOMEM.
160098  */
160099  static int fts3MsrBufferData(
160100    Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
160101    char *pList,
160102    int nList
160103  ){
160104    if( nList>pMsr->nBuffer ){
160105      char *pNew;
160106      pMsr->nBuffer = nList*2;
160107      pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
160108      if( !pNew ) return SQLITE_NOMEM;
160109      pMsr->aBuffer = pNew;
160110    }
160111  
160112    memcpy(pMsr->aBuffer, pList, nList);
160113    return SQLITE_OK;
160114  }
160115  
160116  SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
160117    Fts3Table *p,                   /* Virtual table handle */
160118    Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
160119    sqlite3_int64 *piDocid,         /* OUT: Docid value */
160120    char **paPoslist,               /* OUT: Pointer to position list */
160121    int *pnPoslist                  /* OUT: Size of position list in bytes */
160122  ){
160123    int nMerge = pMsr->nAdvance;
160124    Fts3SegReader **apSegment = pMsr->apSegment;
160125    int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
160126      p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
160127    );
160128  
160129    if( nMerge==0 ){
160130      *paPoslist = 0;
160131      return SQLITE_OK;
160132    }
160133  
160134    while( 1 ){
160135      Fts3SegReader *pSeg;
160136      pSeg = pMsr->apSegment[0];
160137  
160138      if( pSeg->pOffsetList==0 ){
160139        *paPoslist = 0;
160140        break;
160141      }else{
160142        int rc;
160143        char *pList;
160144        int nList;
160145        int j;
160146        sqlite3_int64 iDocid = apSegment[0]->iDocid;
160147  
160148        rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
160149        j = 1;
160150        while( rc==SQLITE_OK 
160151          && j<nMerge
160152          && apSegment[j]->pOffsetList
160153          && apSegment[j]->iDocid==iDocid
160154        ){
160155          rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
160156          j++;
160157        }
160158        if( rc!=SQLITE_OK ) return rc;
160159        fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
160160  
160161        if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
160162          rc = fts3MsrBufferData(pMsr, pList, nList+1);
160163          if( rc!=SQLITE_OK ) return rc;
160164          assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
160165          pList = pMsr->aBuffer;
160166        }
160167  
160168        if( pMsr->iColFilter>=0 ){
160169          fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
160170        }
160171  
160172        if( nList>0 ){
160173          *paPoslist = pList;
160174          *piDocid = iDocid;
160175          *pnPoslist = nList;
160176          break;
160177        }
160178      }
160179    }
160180  
160181    return SQLITE_OK;
160182  }
160183  
160184  static int fts3SegReaderStart(
160185    Fts3Table *p,                   /* Virtual table handle */
160186    Fts3MultiSegReader *pCsr,       /* Cursor object */
160187    const char *zTerm,              /* Term searched for (or NULL) */
160188    int nTerm                       /* Length of zTerm in bytes */
160189  ){
160190    int i;
160191    int nSeg = pCsr->nSegment;
160192  
160193    /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
160194    ** for, then advance each segment iterator until it points to a term of
160195    ** equal or greater value than the specified term. This prevents many
160196    ** unnecessary merge/sort operations for the case where single segment
160197    ** b-tree leaf nodes contain more than one term.
160198    */
160199    for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
160200      int res = 0;
160201      Fts3SegReader *pSeg = pCsr->apSegment[i];
160202      do {
160203        int rc = fts3SegReaderNext(p, pSeg, 0);
160204        if( rc!=SQLITE_OK ) return rc;
160205      }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
160206  
160207      if( pSeg->bLookup && res!=0 ){
160208        fts3SegReaderSetEof(pSeg);
160209      }
160210    }
160211    fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
160212  
160213    return SQLITE_OK;
160214  }
160215  
160216  SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
160217    Fts3Table *p,                   /* Virtual table handle */
160218    Fts3MultiSegReader *pCsr,       /* Cursor object */
160219    Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
160220  ){
160221    pCsr->pFilter = pFilter;
160222    return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
160223  }
160224  
160225  SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
160226    Fts3Table *p,                   /* Virtual table handle */
160227    Fts3MultiSegReader *pCsr,       /* Cursor object */
160228    int iCol,                       /* Column to match on. */
160229    const char *zTerm,              /* Term to iterate through a doclist for */
160230    int nTerm                       /* Number of bytes in zTerm */
160231  ){
160232    int i;
160233    int rc;
160234    int nSegment = pCsr->nSegment;
160235    int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
160236      p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
160237    );
160238  
160239    assert( pCsr->pFilter==0 );
160240    assert( zTerm && nTerm>0 );
160241  
160242    /* Advance each segment iterator until it points to the term zTerm/nTerm. */
160243    rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
160244    if( rc!=SQLITE_OK ) return rc;
160245  
160246    /* Determine how many of the segments actually point to zTerm/nTerm. */
160247    for(i=0; i<nSegment; i++){
160248      Fts3SegReader *pSeg = pCsr->apSegment[i];
160249      if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
160250        break;
160251      }
160252    }
160253    pCsr->nAdvance = i;
160254  
160255    /* Advance each of the segments to point to the first docid. */
160256    for(i=0; i<pCsr->nAdvance; i++){
160257      rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
160258      if( rc!=SQLITE_OK ) return rc;
160259    }
160260    fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
160261  
160262    assert( iCol<0 || iCol<p->nColumn );
160263    pCsr->iColFilter = iCol;
160264  
160265    return SQLITE_OK;
160266  }
160267  
160268  /*
160269  ** This function is called on a MultiSegReader that has been started using
160270  ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
160271  ** have been made. Calling this function puts the MultiSegReader in such
160272  ** a state that if the next two calls are:
160273  **
160274  **   sqlite3Fts3SegReaderStart()
160275  **   sqlite3Fts3SegReaderStep()
160276  **
160277  ** then the entire doclist for the term is available in 
160278  ** MultiSegReader.aDoclist/nDoclist.
160279  */
160280  SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
160281    int i;                          /* Used to iterate through segment-readers */
160282  
160283    assert( pCsr->zTerm==0 );
160284    assert( pCsr->nTerm==0 );
160285    assert( pCsr->aDoclist==0 );
160286    assert( pCsr->nDoclist==0 );
160287  
160288    pCsr->nAdvance = 0;
160289    pCsr->bRestart = 1;
160290    for(i=0; i<pCsr->nSegment; i++){
160291      pCsr->apSegment[i]->pOffsetList = 0;
160292      pCsr->apSegment[i]->nOffsetList = 0;
160293      pCsr->apSegment[i]->iDocid = 0;
160294    }
160295  
160296    return SQLITE_OK;
160297  }
160298  
160299  
160300  SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
160301    Fts3Table *p,                   /* Virtual table handle */
160302    Fts3MultiSegReader *pCsr        /* Cursor object */
160303  ){
160304    int rc = SQLITE_OK;
160305  
160306    int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
160307    int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
160308    int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
160309    int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
160310    int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
160311    int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
160312  
160313    Fts3SegReader **apSegment = pCsr->apSegment;
160314    int nSegment = pCsr->nSegment;
160315    Fts3SegFilter *pFilter = pCsr->pFilter;
160316    int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
160317      p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
160318    );
160319  
160320    if( pCsr->nSegment==0 ) return SQLITE_OK;
160321  
160322    do {
160323      int nMerge;
160324      int i;
160325    
160326      /* Advance the first pCsr->nAdvance entries in the apSegment[] array
160327      ** forward. Then sort the list in order of current term again.  
160328      */
160329      for(i=0; i<pCsr->nAdvance; i++){
160330        Fts3SegReader *pSeg = apSegment[i];
160331        if( pSeg->bLookup ){
160332          fts3SegReaderSetEof(pSeg);
160333        }else{
160334          rc = fts3SegReaderNext(p, pSeg, 0);
160335        }
160336        if( rc!=SQLITE_OK ) return rc;
160337      }
160338      fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
160339      pCsr->nAdvance = 0;
160340  
160341      /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
160342      assert( rc==SQLITE_OK );
160343      if( apSegment[0]->aNode==0 ) break;
160344  
160345      pCsr->nTerm = apSegment[0]->nTerm;
160346      pCsr->zTerm = apSegment[0]->zTerm;
160347  
160348      /* If this is a prefix-search, and if the term that apSegment[0] points
160349      ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
160350      ** required callbacks have been made. In this case exit early.
160351      **
160352      ** Similarly, if this is a search for an exact match, and the first term
160353      ** of segment apSegment[0] is not a match, exit early.
160354      */
160355      if( pFilter->zTerm && !isScan ){
160356        if( pCsr->nTerm<pFilter->nTerm 
160357         || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
160358         || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) 
160359        ){
160360          break;
160361        }
160362      }
160363  
160364      nMerge = 1;
160365      while( nMerge<nSegment 
160366          && apSegment[nMerge]->aNode
160367          && apSegment[nMerge]->nTerm==pCsr->nTerm 
160368          && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
160369      ){
160370        nMerge++;
160371      }
160372  
160373      assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
160374      if( nMerge==1 
160375       && !isIgnoreEmpty 
160376       && !isFirst 
160377       && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
160378      ){
160379        pCsr->nDoclist = apSegment[0]->nDoclist;
160380        if( fts3SegReaderIsPending(apSegment[0]) ){
160381          rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
160382          pCsr->aDoclist = pCsr->aBuffer;
160383        }else{
160384          pCsr->aDoclist = apSegment[0]->aDoclist;
160385        }
160386        if( rc==SQLITE_OK ) rc = SQLITE_ROW;
160387      }else{
160388        int nDoclist = 0;           /* Size of doclist */
160389        sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
160390  
160391        /* The current term of the first nMerge entries in the array
160392        ** of Fts3SegReader objects is the same. The doclists must be merged
160393        ** and a single term returned with the merged doclist.
160394        */
160395        for(i=0; i<nMerge; i++){
160396          fts3SegReaderFirstDocid(p, apSegment[i]);
160397        }
160398        fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
160399        while( apSegment[0]->pOffsetList ){
160400          int j;                    /* Number of segments that share a docid */
160401          char *pList = 0;
160402          int nList = 0;
160403          int nByte;
160404          sqlite3_int64 iDocid = apSegment[0]->iDocid;
160405          fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
160406          j = 1;
160407          while( j<nMerge
160408              && apSegment[j]->pOffsetList
160409              && apSegment[j]->iDocid==iDocid
160410          ){
160411            fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
160412            j++;
160413          }
160414  
160415          if( isColFilter ){
160416            fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
160417          }
160418  
160419          if( !isIgnoreEmpty || nList>0 ){
160420  
160421            /* Calculate the 'docid' delta value to write into the merged 
160422            ** doclist. */
160423            sqlite3_int64 iDelta;
160424            if( p->bDescIdx && nDoclist>0 ){
160425              iDelta = iPrev - iDocid;
160426            }else{
160427              iDelta = iDocid - iPrev;
160428            }
160429            assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
160430            assert( nDoclist>0 || iDelta==iDocid );
160431  
160432            nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
160433            if( nDoclist+nByte>pCsr->nBuffer ){
160434              char *aNew;
160435              pCsr->nBuffer = (nDoclist+nByte)*2;
160436              aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
160437              if( !aNew ){
160438                return SQLITE_NOMEM;
160439              }
160440              pCsr->aBuffer = aNew;
160441            }
160442  
160443            if( isFirst ){
160444              char *a = &pCsr->aBuffer[nDoclist];
160445              int nWrite;
160446             
160447              nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
160448              if( nWrite ){
160449                iPrev = iDocid;
160450                nDoclist += nWrite;
160451              }
160452            }else{
160453              nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
160454              iPrev = iDocid;
160455              if( isRequirePos ){
160456                memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
160457                nDoclist += nList;
160458                pCsr->aBuffer[nDoclist++] = '\0';
160459              }
160460            }
160461          }
160462  
160463          fts3SegReaderSort(apSegment, nMerge, j, xCmp);
160464        }
160465        if( nDoclist>0 ){
160466          pCsr->aDoclist = pCsr->aBuffer;
160467          pCsr->nDoclist = nDoclist;
160468          rc = SQLITE_ROW;
160469        }
160470      }
160471      pCsr->nAdvance = nMerge;
160472    }while( rc==SQLITE_OK );
160473  
160474    return rc;
160475  }
160476  
160477  
160478  SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
160479    Fts3MultiSegReader *pCsr       /* Cursor object */
160480  ){
160481    if( pCsr ){
160482      int i;
160483      for(i=0; i<pCsr->nSegment; i++){
160484        sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
160485      }
160486      sqlite3_free(pCsr->apSegment);
160487      sqlite3_free(pCsr->aBuffer);
160488  
160489      pCsr->nSegment = 0;
160490      pCsr->apSegment = 0;
160491      pCsr->aBuffer = 0;
160492    }
160493  }
160494  
160495  /*
160496  ** Decode the "end_block" field, selected by column iCol of the SELECT 
160497  ** statement passed as the first argument. 
160498  **
160499  ** The "end_block" field may contain either an integer, or a text field
160500  ** containing the text representation of two non-negative integers separated 
160501  ** by one or more space (0x20) characters. In the first case, set *piEndBlock 
160502  ** to the integer value and *pnByte to zero before returning. In the second, 
160503  ** set *piEndBlock to the first value and *pnByte to the second.
160504  */
160505  static void fts3ReadEndBlockField(
160506    sqlite3_stmt *pStmt, 
160507    int iCol, 
160508    i64 *piEndBlock,
160509    i64 *pnByte
160510  ){
160511    const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
160512    if( zText ){
160513      int i;
160514      int iMul = 1;
160515      i64 iVal = 0;
160516      for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
160517        iVal = iVal*10 + (zText[i] - '0');
160518      }
160519      *piEndBlock = iVal;
160520      while( zText[i]==' ' ) i++;
160521      iVal = 0;
160522      if( zText[i]=='-' ){
160523        i++;
160524        iMul = -1;
160525      }
160526      for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
160527        iVal = iVal*10 + (zText[i] - '0');
160528      }
160529      *pnByte = (iVal * (i64)iMul);
160530    }
160531  }
160532  
160533  
160534  /*
160535  ** A segment of size nByte bytes has just been written to absolute level
160536  ** iAbsLevel. Promote any segments that should be promoted as a result.
160537  */
160538  static int fts3PromoteSegments(
160539    Fts3Table *p,                   /* FTS table handle */
160540    sqlite3_int64 iAbsLevel,        /* Absolute level just updated */
160541    sqlite3_int64 nByte             /* Size of new segment at iAbsLevel */
160542  ){
160543    int rc = SQLITE_OK;
160544    sqlite3_stmt *pRange;
160545  
160546    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
160547  
160548    if( rc==SQLITE_OK ){
160549      int bOk = 0;
160550      i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
160551      i64 nLimit = (nByte*3)/2;
160552  
160553      /* Loop through all entries in the %_segdir table corresponding to 
160554      ** segments in this index on levels greater than iAbsLevel. If there is
160555      ** at least one such segment, and it is possible to determine that all 
160556      ** such segments are smaller than nLimit bytes in size, they will be 
160557      ** promoted to level iAbsLevel.  */
160558      sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
160559      sqlite3_bind_int64(pRange, 2, iLast);
160560      while( SQLITE_ROW==sqlite3_step(pRange) ){
160561        i64 nSize = 0, dummy;
160562        fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
160563        if( nSize<=0 || nSize>nLimit ){
160564          /* If nSize==0, then the %_segdir.end_block field does not not 
160565          ** contain a size value. This happens if it was written by an
160566          ** old version of FTS. In this case it is not possible to determine
160567          ** the size of the segment, and so segment promotion does not
160568          ** take place.  */
160569          bOk = 0;
160570          break;
160571        }
160572        bOk = 1;
160573      }
160574      rc = sqlite3_reset(pRange);
160575  
160576      if( bOk ){
160577        int iIdx = 0;
160578        sqlite3_stmt *pUpdate1 = 0;
160579        sqlite3_stmt *pUpdate2 = 0;
160580  
160581        if( rc==SQLITE_OK ){
160582          rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
160583        }
160584        if( rc==SQLITE_OK ){
160585          rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
160586        }
160587  
160588        if( rc==SQLITE_OK ){
160589  
160590          /* Loop through all %_segdir entries for segments in this index with
160591          ** levels equal to or greater than iAbsLevel. As each entry is visited,
160592          ** updated it to set (level = -1) and (idx = N), where N is 0 for the
160593          ** oldest segment in the range, 1 for the next oldest, and so on.
160594          **
160595          ** In other words, move all segments being promoted to level -1,
160596          ** setting the "idx" fields as appropriate to keep them in the same
160597          ** order. The contents of level -1 (which is never used, except
160598          ** transiently here), will be moved back to level iAbsLevel below.  */
160599          sqlite3_bind_int64(pRange, 1, iAbsLevel);
160600          while( SQLITE_ROW==sqlite3_step(pRange) ){
160601            sqlite3_bind_int(pUpdate1, 1, iIdx++);
160602            sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
160603            sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
160604            sqlite3_step(pUpdate1);
160605            rc = sqlite3_reset(pUpdate1);
160606            if( rc!=SQLITE_OK ){
160607              sqlite3_reset(pRange);
160608              break;
160609            }
160610          }
160611        }
160612        if( rc==SQLITE_OK ){
160613          rc = sqlite3_reset(pRange);
160614        }
160615  
160616        /* Move level -1 to level iAbsLevel */
160617        if( rc==SQLITE_OK ){
160618          sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
160619          sqlite3_step(pUpdate2);
160620          rc = sqlite3_reset(pUpdate2);
160621        }
160622      }
160623    }
160624  
160625  
160626    return rc;
160627  }
160628  
160629  /*
160630  ** Merge all level iLevel segments in the database into a single 
160631  ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
160632  ** single segment with a level equal to the numerically largest level 
160633  ** currently present in the database.
160634  **
160635  ** If this function is called with iLevel<0, but there is only one
160636  ** segment in the database, SQLITE_DONE is returned immediately. 
160637  ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, 
160638  ** an SQLite error code is returned.
160639  */
160640  static int fts3SegmentMerge(
160641    Fts3Table *p, 
160642    int iLangid,                    /* Language id to merge */
160643    int iIndex,                     /* Index in p->aIndex[] to merge */
160644    int iLevel                      /* Level to merge */
160645  ){
160646    int rc;                         /* Return code */
160647    int iIdx = 0;                   /* Index of new segment */
160648    sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
160649    SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
160650    Fts3SegFilter filter;           /* Segment term filter condition */
160651    Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
160652    int bIgnoreEmpty = 0;           /* True to ignore empty segments */
160653    i64 iMaxLevel = 0;              /* Max level number for this index/langid */
160654  
160655    assert( iLevel==FTS3_SEGCURSOR_ALL
160656         || iLevel==FTS3_SEGCURSOR_PENDING
160657         || iLevel>=0
160658    );
160659    assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
160660    assert( iIndex>=0 && iIndex<p->nIndex );
160661  
160662    rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
160663    if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
160664  
160665    if( iLevel!=FTS3_SEGCURSOR_PENDING ){
160666      rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
160667      if( rc!=SQLITE_OK ) goto finished;
160668    }
160669  
160670    if( iLevel==FTS3_SEGCURSOR_ALL ){
160671      /* This call is to merge all segments in the database to a single
160672      ** segment. The level of the new segment is equal to the numerically
160673      ** greatest segment level currently present in the database for this
160674      ** index. The idx of the new segment is always 0.  */
160675      if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
160676        rc = SQLITE_DONE;
160677        goto finished;
160678      }
160679      iNewLevel = iMaxLevel;
160680      bIgnoreEmpty = 1;
160681  
160682    }else{
160683      /* This call is to merge all segments at level iLevel. find the next
160684      ** available segment index at level iLevel+1. The call to
160685      ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
160686      ** a single iLevel+2 segment if necessary.  */
160687      assert( FTS3_SEGCURSOR_PENDING==-1 );
160688      iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
160689      rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
160690      bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
160691    }
160692    if( rc!=SQLITE_OK ) goto finished;
160693  
160694    assert( csr.nSegment>0 );
160695    assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
160696    assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
160697  
160698    memset(&filter, 0, sizeof(Fts3SegFilter));
160699    filter.flags = FTS3_SEGMENT_REQUIRE_POS;
160700    filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
160701  
160702    rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
160703    while( SQLITE_OK==rc ){
160704      rc = sqlite3Fts3SegReaderStep(p, &csr);
160705      if( rc!=SQLITE_ROW ) break;
160706      rc = fts3SegWriterAdd(p, &pWriter, 1, 
160707          csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
160708    }
160709    if( rc!=SQLITE_OK ) goto finished;
160710    assert( pWriter || bIgnoreEmpty );
160711  
160712    if( iLevel!=FTS3_SEGCURSOR_PENDING ){
160713      rc = fts3DeleteSegdir(
160714          p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
160715      );
160716      if( rc!=SQLITE_OK ) goto finished;
160717    }
160718    if( pWriter ){
160719      rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
160720      if( rc==SQLITE_OK ){
160721        if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
160722          rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
160723        }
160724      }
160725    }
160726  
160727   finished:
160728    fts3SegWriterFree(pWriter);
160729    sqlite3Fts3SegReaderFinish(&csr);
160730    return rc;
160731  }
160732  
160733  
160734  /* 
160735  ** Flush the contents of pendingTerms to level 0 segments. 
160736  */
160737  SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
160738    int rc = SQLITE_OK;
160739    int i;
160740          
160741    for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
160742      rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
160743      if( rc==SQLITE_DONE ) rc = SQLITE_OK;
160744    }
160745    sqlite3Fts3PendingTermsClear(p);
160746  
160747    /* Determine the auto-incr-merge setting if unknown.  If enabled,
160748    ** estimate the number of leaf blocks of content to be written
160749    */
160750    if( rc==SQLITE_OK && p->bHasStat
160751     && p->nAutoincrmerge==0xff && p->nLeafAdd>0
160752    ){
160753      sqlite3_stmt *pStmt = 0;
160754      rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
160755      if( rc==SQLITE_OK ){
160756        sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
160757        rc = sqlite3_step(pStmt);
160758        if( rc==SQLITE_ROW ){
160759          p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
160760          if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
160761        }else if( rc==SQLITE_DONE ){
160762          p->nAutoincrmerge = 0;
160763        }
160764        rc = sqlite3_reset(pStmt);
160765      }
160766    }
160767    return rc;
160768  }
160769  
160770  /*
160771  ** Encode N integers as varints into a blob.
160772  */
160773  static void fts3EncodeIntArray(
160774    int N,             /* The number of integers to encode */
160775    u32 *a,            /* The integer values */
160776    char *zBuf,        /* Write the BLOB here */
160777    int *pNBuf         /* Write number of bytes if zBuf[] used here */
160778  ){
160779    int i, j;
160780    for(i=j=0; i<N; i++){
160781      j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
160782    }
160783    *pNBuf = j;
160784  }
160785  
160786  /*
160787  ** Decode a blob of varints into N integers
160788  */
160789  static void fts3DecodeIntArray(
160790    int N,             /* The number of integers to decode */
160791    u32 *a,            /* Write the integer values */
160792    const char *zBuf,  /* The BLOB containing the varints */
160793    int nBuf           /* size of the BLOB */
160794  ){
160795    int i, j;
160796    UNUSED_PARAMETER(nBuf);
160797    for(i=j=0; i<N; i++){
160798      sqlite3_int64 x;
160799      j += sqlite3Fts3GetVarint(&zBuf[j], &x);
160800      assert(j<=nBuf);
160801      a[i] = (u32)(x & 0xffffffff);
160802    }
160803  }
160804  
160805  /*
160806  ** Insert the sizes (in tokens) for each column of the document
160807  ** with docid equal to p->iPrevDocid.  The sizes are encoded as
160808  ** a blob of varints.
160809  */
160810  static void fts3InsertDocsize(
160811    int *pRC,                       /* Result code */
160812    Fts3Table *p,                   /* Table into which to insert */
160813    u32 *aSz                        /* Sizes of each column, in tokens */
160814  ){
160815    char *pBlob;             /* The BLOB encoding of the document size */
160816    int nBlob;               /* Number of bytes in the BLOB */
160817    sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
160818    int rc;                  /* Result code from subfunctions */
160819  
160820    if( *pRC ) return;
160821    pBlob = sqlite3_malloc( 10*p->nColumn );
160822    if( pBlob==0 ){
160823      *pRC = SQLITE_NOMEM;
160824      return;
160825    }
160826    fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
160827    rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
160828    if( rc ){
160829      sqlite3_free(pBlob);
160830      *pRC = rc;
160831      return;
160832    }
160833    sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
160834    sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
160835    sqlite3_step(pStmt);
160836    *pRC = sqlite3_reset(pStmt);
160837  }
160838  
160839  /*
160840  ** Record 0 of the %_stat table contains a blob consisting of N varints,
160841  ** where N is the number of user defined columns in the fts3 table plus
160842  ** two. If nCol is the number of user defined columns, then values of the 
160843  ** varints are set as follows:
160844  **
160845  **   Varint 0:       Total number of rows in the table.
160846  **
160847  **   Varint 1..nCol: For each column, the total number of tokens stored in
160848  **                   the column for all rows of the table.
160849  **
160850  **   Varint 1+nCol:  The total size, in bytes, of all text values in all
160851  **                   columns of all rows of the table.
160852  **
160853  */
160854  static void fts3UpdateDocTotals(
160855    int *pRC,                       /* The result code */
160856    Fts3Table *p,                   /* Table being updated */
160857    u32 *aSzIns,                    /* Size increases */
160858    u32 *aSzDel,                    /* Size decreases */
160859    int nChng                       /* Change in the number of documents */
160860  ){
160861    char *pBlob;             /* Storage for BLOB written into %_stat */
160862    int nBlob;               /* Size of BLOB written into %_stat */
160863    u32 *a;                  /* Array of integers that becomes the BLOB */
160864    sqlite3_stmt *pStmt;     /* Statement for reading and writing */
160865    int i;                   /* Loop counter */
160866    int rc;                  /* Result code from subfunctions */
160867  
160868    const int nStat = p->nColumn+2;
160869  
160870    if( *pRC ) return;
160871    a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
160872    if( a==0 ){
160873      *pRC = SQLITE_NOMEM;
160874      return;
160875    }
160876    pBlob = (char*)&a[nStat];
160877    rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
160878    if( rc ){
160879      sqlite3_free(a);
160880      *pRC = rc;
160881      return;
160882    }
160883    sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
160884    if( sqlite3_step(pStmt)==SQLITE_ROW ){
160885      fts3DecodeIntArray(nStat, a,
160886           sqlite3_column_blob(pStmt, 0),
160887           sqlite3_column_bytes(pStmt, 0));
160888    }else{
160889      memset(a, 0, sizeof(u32)*(nStat) );
160890    }
160891    rc = sqlite3_reset(pStmt);
160892    if( rc!=SQLITE_OK ){
160893      sqlite3_free(a);
160894      *pRC = rc;
160895      return;
160896    }
160897    if( nChng<0 && a[0]<(u32)(-nChng) ){
160898      a[0] = 0;
160899    }else{
160900      a[0] += nChng;
160901    }
160902    for(i=0; i<p->nColumn+1; i++){
160903      u32 x = a[i+1];
160904      if( x+aSzIns[i] < aSzDel[i] ){
160905        x = 0;
160906      }else{
160907        x = x + aSzIns[i] - aSzDel[i];
160908      }
160909      a[i+1] = x;
160910    }
160911    fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
160912    rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
160913    if( rc ){
160914      sqlite3_free(a);
160915      *pRC = rc;
160916      return;
160917    }
160918    sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
160919    sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
160920    sqlite3_step(pStmt);
160921    *pRC = sqlite3_reset(pStmt);
160922    sqlite3_free(a);
160923  }
160924  
160925  /*
160926  ** Merge the entire database so that there is one segment for each 
160927  ** iIndex/iLangid combination.
160928  */
160929  static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
160930    int bSeenDone = 0;
160931    int rc;
160932    sqlite3_stmt *pAllLangid = 0;
160933  
160934    rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
160935    if( rc==SQLITE_OK ){
160936      int rc2;
160937      sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
160938      sqlite3_bind_int(pAllLangid, 2, p->nIndex);
160939      while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
160940        int i;
160941        int iLangid = sqlite3_column_int(pAllLangid, 0);
160942        for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
160943          rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
160944          if( rc==SQLITE_DONE ){
160945            bSeenDone = 1;
160946            rc = SQLITE_OK;
160947          }
160948        }
160949      }
160950      rc2 = sqlite3_reset(pAllLangid);
160951      if( rc==SQLITE_OK ) rc = rc2;
160952    }
160953  
160954    sqlite3Fts3SegmentsClose(p);
160955    sqlite3Fts3PendingTermsClear(p);
160956  
160957    return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
160958  }
160959  
160960  /*
160961  ** This function is called when the user executes the following statement:
160962  **
160963  **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
160964  **
160965  ** The entire FTS index is discarded and rebuilt. If the table is one 
160966  ** created using the content=xxx option, then the new index is based on
160967  ** the current contents of the xxx table. Otherwise, it is rebuilt based
160968  ** on the contents of the %_content table.
160969  */
160970  static int fts3DoRebuild(Fts3Table *p){
160971    int rc;                         /* Return Code */
160972  
160973    rc = fts3DeleteAll(p, 0);
160974    if( rc==SQLITE_OK ){
160975      u32 *aSz = 0;
160976      u32 *aSzIns = 0;
160977      u32 *aSzDel = 0;
160978      sqlite3_stmt *pStmt = 0;
160979      int nEntry = 0;
160980  
160981      /* Compose and prepare an SQL statement to loop through the content table */
160982      char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
160983      if( !zSql ){
160984        rc = SQLITE_NOMEM;
160985      }else{
160986        rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
160987        sqlite3_free(zSql);
160988      }
160989  
160990      if( rc==SQLITE_OK ){
160991        int nByte = sizeof(u32) * (p->nColumn+1)*3;
160992        aSz = (u32 *)sqlite3_malloc(nByte);
160993        if( aSz==0 ){
160994          rc = SQLITE_NOMEM;
160995        }else{
160996          memset(aSz, 0, nByte);
160997          aSzIns = &aSz[p->nColumn+1];
160998          aSzDel = &aSzIns[p->nColumn+1];
160999        }
161000      }
161001  
161002      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
161003        int iCol;
161004        int iLangid = langidFromSelect(p, pStmt);
161005        rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
161006        memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
161007        for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
161008          if( p->abNotindexed[iCol]==0 ){
161009            const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
161010            rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
161011            aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
161012          }
161013        }
161014        if( p->bHasDocsize ){
161015          fts3InsertDocsize(&rc, p, aSz);
161016        }
161017        if( rc!=SQLITE_OK ){
161018          sqlite3_finalize(pStmt);
161019          pStmt = 0;
161020        }else{
161021          nEntry++;
161022          for(iCol=0; iCol<=p->nColumn; iCol++){
161023            aSzIns[iCol] += aSz[iCol];
161024          }
161025        }
161026      }
161027      if( p->bFts4 ){
161028        fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
161029      }
161030      sqlite3_free(aSz);
161031  
161032      if( pStmt ){
161033        int rc2 = sqlite3_finalize(pStmt);
161034        if( rc==SQLITE_OK ){
161035          rc = rc2;
161036        }
161037      }
161038    }
161039  
161040    return rc;
161041  }
161042  
161043  
161044  /*
161045  ** This function opens a cursor used to read the input data for an 
161046  ** incremental merge operation. Specifically, it opens a cursor to scan
161047  ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute 
161048  ** level iAbsLevel.
161049  */
161050  static int fts3IncrmergeCsr(
161051    Fts3Table *p,                   /* FTS3 table handle */
161052    sqlite3_int64 iAbsLevel,        /* Absolute level to open */
161053    int nSeg,                       /* Number of segments to merge */
161054    Fts3MultiSegReader *pCsr        /* Cursor object to populate */
161055  ){
161056    int rc;                         /* Return Code */
161057    sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */  
161058    int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
161059  
161060    /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
161061    memset(pCsr, 0, sizeof(*pCsr));
161062    nByte = sizeof(Fts3SegReader *) * nSeg;
161063    pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
161064  
161065    if( pCsr->apSegment==0 ){
161066      rc = SQLITE_NOMEM;
161067    }else{
161068      memset(pCsr->apSegment, 0, nByte);
161069      rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
161070    }
161071    if( rc==SQLITE_OK ){
161072      int i;
161073      int rc2;
161074      sqlite3_bind_int64(pStmt, 1, iAbsLevel);
161075      assert( pCsr->nSegment==0 );
161076      for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
161077        rc = sqlite3Fts3SegReaderNew(i, 0,
161078            sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
161079            sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
161080            sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
161081            sqlite3_column_blob(pStmt, 4),         /* segdir.root */
161082            sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
161083            &pCsr->apSegment[i]
161084        );
161085        pCsr->nSegment++;
161086      }
161087      rc2 = sqlite3_reset(pStmt);
161088      if( rc==SQLITE_OK ) rc = rc2;
161089    }
161090  
161091    return rc;
161092  }
161093  
161094  typedef struct IncrmergeWriter IncrmergeWriter;
161095  typedef struct NodeWriter NodeWriter;
161096  typedef struct Blob Blob;
161097  typedef struct NodeReader NodeReader;
161098  
161099  /*
161100  ** An instance of the following structure is used as a dynamic buffer
161101  ** to build up nodes or other blobs of data in.
161102  **
161103  ** The function blobGrowBuffer() is used to extend the allocation.
161104  */
161105  struct Blob {
161106    char *a;                        /* Pointer to allocation */
161107    int n;                          /* Number of valid bytes of data in a[] */
161108    int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
161109  };
161110  
161111  /*
161112  ** This structure is used to build up buffers containing segment b-tree 
161113  ** nodes (blocks).
161114  */
161115  struct NodeWriter {
161116    sqlite3_int64 iBlock;           /* Current block id */
161117    Blob key;                       /* Last key written to the current block */
161118    Blob block;                     /* Current block image */
161119  };
161120  
161121  /*
161122  ** An object of this type contains the state required to create or append
161123  ** to an appendable b-tree segment.
161124  */
161125  struct IncrmergeWriter {
161126    int nLeafEst;                   /* Space allocated for leaf blocks */
161127    int nWork;                      /* Number of leaf pages flushed */
161128    sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
161129    int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
161130    sqlite3_int64 iStart;           /* Block number of first allocated block */
161131    sqlite3_int64 iEnd;             /* Block number of last allocated block */
161132    sqlite3_int64 nLeafData;        /* Bytes of leaf page data so far */
161133    u8 bNoLeafData;                 /* If true, store 0 for segment size */
161134    NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
161135  };
161136  
161137  /*
161138  ** An object of the following type is used to read data from a single
161139  ** FTS segment node. See the following functions:
161140  **
161141  **     nodeReaderInit()
161142  **     nodeReaderNext()
161143  **     nodeReaderRelease()
161144  */
161145  struct NodeReader {
161146    const char *aNode;
161147    int nNode;
161148    int iOff;                       /* Current offset within aNode[] */
161149  
161150    /* Output variables. Containing the current node entry. */
161151    sqlite3_int64 iChild;           /* Pointer to child node */
161152    Blob term;                      /* Current term */
161153    const char *aDoclist;           /* Pointer to doclist */
161154    int nDoclist;                   /* Size of doclist in bytes */
161155  };
161156  
161157  /*
161158  ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
161159  ** Otherwise, if the allocation at pBlob->a is not already at least nMin
161160  ** bytes in size, extend (realloc) it to be so.
161161  **
161162  ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
161163  ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
161164  ** to reflect the new size of the pBlob->a[] buffer.
161165  */
161166  static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
161167    if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
161168      int nAlloc = nMin;
161169      char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
161170      if( a ){
161171        pBlob->nAlloc = nAlloc;
161172        pBlob->a = a;
161173      }else{
161174        *pRc = SQLITE_NOMEM;
161175      }
161176    }
161177  }
161178  
161179  /*
161180  ** Attempt to advance the node-reader object passed as the first argument to
161181  ** the next entry on the node. 
161182  **
161183  ** Return an error code if an error occurs (SQLITE_NOMEM is possible). 
161184  ** Otherwise return SQLITE_OK. If there is no next entry on the node
161185  ** (e.g. because the current entry is the last) set NodeReader->aNode to
161186  ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output 
161187  ** variables for the new entry.
161188  */
161189  static int nodeReaderNext(NodeReader *p){
161190    int bFirst = (p->term.n==0);    /* True for first term on the node */
161191    int nPrefix = 0;                /* Bytes to copy from previous term */
161192    int nSuffix = 0;                /* Bytes to append to the prefix */
161193    int rc = SQLITE_OK;             /* Return code */
161194  
161195    assert( p->aNode );
161196    if( p->iChild && bFirst==0 ) p->iChild++;
161197    if( p->iOff>=p->nNode ){
161198      /* EOF */
161199      p->aNode = 0;
161200    }else{
161201      if( bFirst==0 ){
161202        p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
161203      }
161204      p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
161205  
161206      blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
161207      if( rc==SQLITE_OK ){
161208        memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
161209        p->term.n = nPrefix+nSuffix;
161210        p->iOff += nSuffix;
161211        if( p->iChild==0 ){
161212          p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
161213          p->aDoclist = &p->aNode[p->iOff];
161214          p->iOff += p->nDoclist;
161215        }
161216      }
161217    }
161218  
161219    assert( p->iOff<=p->nNode );
161220  
161221    return rc;
161222  }
161223  
161224  /*
161225  ** Release all dynamic resources held by node-reader object *p.
161226  */
161227  static void nodeReaderRelease(NodeReader *p){
161228    sqlite3_free(p->term.a);
161229  }
161230  
161231  /*
161232  ** Initialize a node-reader object to read the node in buffer aNode/nNode.
161233  **
161234  ** If successful, SQLITE_OK is returned and the NodeReader object set to 
161235  ** point to the first entry on the node (if any). Otherwise, an SQLite
161236  ** error code is returned.
161237  */
161238  static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
161239    memset(p, 0, sizeof(NodeReader));
161240    p->aNode = aNode;
161241    p->nNode = nNode;
161242  
161243    /* Figure out if this is a leaf or an internal node. */
161244    if( p->aNode[0] ){
161245      /* An internal node. */
161246      p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
161247    }else{
161248      p->iOff = 1;
161249    }
161250  
161251    return nodeReaderNext(p);
161252  }
161253  
161254  /*
161255  ** This function is called while writing an FTS segment each time a leaf o
161256  ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
161257  ** to be greater than the largest key on the node just written, but smaller
161258  ** than or equal to the first key that will be written to the next leaf
161259  ** node.
161260  **
161261  ** The block id of the leaf node just written to disk may be found in
161262  ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
161263  */
161264  static int fts3IncrmergePush(
161265    Fts3Table *p,                   /* Fts3 table handle */
161266    IncrmergeWriter *pWriter,       /* Writer object */
161267    const char *zTerm,              /* Term to write to internal node */
161268    int nTerm                       /* Bytes at zTerm */
161269  ){
161270    sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
161271    int iLayer;
161272  
161273    assert( nTerm>0 );
161274    for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
161275      sqlite3_int64 iNextPtr = 0;
161276      NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
161277      int rc = SQLITE_OK;
161278      int nPrefix;
161279      int nSuffix;
161280      int nSpace;
161281  
161282      /* Figure out how much space the key will consume if it is written to
161283      ** the current node of layer iLayer. Due to the prefix compression, 
161284      ** the space required changes depending on which node the key is to
161285      ** be added to.  */
161286      nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
161287      nSuffix = nTerm - nPrefix;
161288      nSpace  = sqlite3Fts3VarintLen(nPrefix);
161289      nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
161290  
161291      if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){ 
161292        /* If the current node of layer iLayer contains zero keys, or if adding
161293        ** the key to it will not cause it to grow to larger than nNodeSize 
161294        ** bytes in size, write the key here.  */
161295  
161296        Blob *pBlk = &pNode->block;
161297        if( pBlk->n==0 ){
161298          blobGrowBuffer(pBlk, p->nNodeSize, &rc);
161299          if( rc==SQLITE_OK ){
161300            pBlk->a[0] = (char)iLayer;
161301            pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
161302          }
161303        }
161304        blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
161305        blobGrowBuffer(&pNode->key, nTerm, &rc);
161306  
161307        if( rc==SQLITE_OK ){
161308          if( pNode->key.n ){
161309            pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
161310          }
161311          pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
161312          memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
161313          pBlk->n += nSuffix;
161314  
161315          memcpy(pNode->key.a, zTerm, nTerm);
161316          pNode->key.n = nTerm;
161317        }
161318      }else{
161319        /* Otherwise, flush the current node of layer iLayer to disk.
161320        ** Then allocate a new, empty sibling node. The key will be written
161321        ** into the parent of this node. */
161322        rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
161323  
161324        assert( pNode->block.nAlloc>=p->nNodeSize );
161325        pNode->block.a[0] = (char)iLayer;
161326        pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
161327  
161328        iNextPtr = pNode->iBlock;
161329        pNode->iBlock++;
161330        pNode->key.n = 0;
161331      }
161332  
161333      if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
161334      iPtr = iNextPtr;
161335    }
161336  
161337    assert( 0 );
161338    return 0;
161339  }
161340  
161341  /*
161342  ** Append a term and (optionally) doclist to the FTS segment node currently
161343  ** stored in blob *pNode. The node need not contain any terms, but the
161344  ** header must be written before this function is called.
161345  **
161346  ** A node header is a single 0x00 byte for a leaf node, or a height varint
161347  ** followed by the left-hand-child varint for an internal node.
161348  **
161349  ** The term to be appended is passed via arguments zTerm/nTerm. For a 
161350  ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
161351  ** node, both aDoclist and nDoclist must be passed 0.
161352  **
161353  ** If the size of the value in blob pPrev is zero, then this is the first
161354  ** term written to the node. Otherwise, pPrev contains a copy of the 
161355  ** previous term. Before this function returns, it is updated to contain a
161356  ** copy of zTerm/nTerm.
161357  **
161358  ** It is assumed that the buffer associated with pNode is already large
161359  ** enough to accommodate the new entry. The buffer associated with pPrev
161360  ** is extended by this function if requrired.
161361  **
161362  ** If an error (i.e. OOM condition) occurs, an SQLite error code is
161363  ** returned. Otherwise, SQLITE_OK.
161364  */
161365  static int fts3AppendToNode(
161366    Blob *pNode,                    /* Current node image to append to */
161367    Blob *pPrev,                    /* Buffer containing previous term written */
161368    const char *zTerm,              /* New term to write */
161369    int nTerm,                      /* Size of zTerm in bytes */
161370    const char *aDoclist,           /* Doclist (or NULL) to write */
161371    int nDoclist                    /* Size of aDoclist in bytes */ 
161372  ){
161373    int rc = SQLITE_OK;             /* Return code */
161374    int bFirst = (pPrev->n==0);     /* True if this is the first term written */
161375    int nPrefix;                    /* Size of term prefix in bytes */
161376    int nSuffix;                    /* Size of term suffix in bytes */
161377  
161378    /* Node must have already been started. There must be a doclist for a
161379    ** leaf node, and there must not be a doclist for an internal node.  */
161380    assert( pNode->n>0 );
161381    assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
161382  
161383    blobGrowBuffer(pPrev, nTerm, &rc);
161384    if( rc!=SQLITE_OK ) return rc;
161385  
161386    nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
161387    nSuffix = nTerm - nPrefix;
161388    memcpy(pPrev->a, zTerm, nTerm);
161389    pPrev->n = nTerm;
161390  
161391    if( bFirst==0 ){
161392      pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
161393    }
161394    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
161395    memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
161396    pNode->n += nSuffix;
161397  
161398    if( aDoclist ){
161399      pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
161400      memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
161401      pNode->n += nDoclist;
161402    }
161403  
161404    assert( pNode->n<=pNode->nAlloc );
161405  
161406    return SQLITE_OK;
161407  }
161408  
161409  /*
161410  ** Append the current term and doclist pointed to by cursor pCsr to the
161411  ** appendable b-tree segment opened for writing by pWriter.
161412  **
161413  ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
161414  */
161415  static int fts3IncrmergeAppend(
161416    Fts3Table *p,                   /* Fts3 table handle */
161417    IncrmergeWriter *pWriter,       /* Writer object */
161418    Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
161419  ){
161420    const char *zTerm = pCsr->zTerm;
161421    int nTerm = pCsr->nTerm;
161422    const char *aDoclist = pCsr->aDoclist;
161423    int nDoclist = pCsr->nDoclist;
161424    int rc = SQLITE_OK;           /* Return code */
161425    int nSpace;                   /* Total space in bytes required on leaf */
161426    int nPrefix;                  /* Size of prefix shared with previous term */
161427    int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
161428    NodeWriter *pLeaf;            /* Object used to write leaf nodes */
161429  
161430    pLeaf = &pWriter->aNodeWriter[0];
161431    nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
161432    nSuffix = nTerm - nPrefix;
161433  
161434    nSpace  = sqlite3Fts3VarintLen(nPrefix);
161435    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
161436    nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
161437  
161438    /* If the current block is not empty, and if adding this term/doclist
161439    ** to the current block would make it larger than Fts3Table.nNodeSize
161440    ** bytes, write this block out to the database. */
161441    if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
161442      rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
161443      pWriter->nWork++;
161444  
161445      /* Add the current term to the parent node. The term added to the 
161446      ** parent must:
161447      **
161448      **   a) be greater than the largest term on the leaf node just written
161449      **      to the database (still available in pLeaf->key), and
161450      **
161451      **   b) be less than or equal to the term about to be added to the new
161452      **      leaf node (zTerm/nTerm).
161453      **
161454      ** In other words, it must be the prefix of zTerm 1 byte longer than
161455      ** the common prefix (if any) of zTerm and pWriter->zTerm.
161456      */
161457      if( rc==SQLITE_OK ){
161458        rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
161459      }
161460  
161461      /* Advance to the next output block */
161462      pLeaf->iBlock++;
161463      pLeaf->key.n = 0;
161464      pLeaf->block.n = 0;
161465  
161466      nSuffix = nTerm;
161467      nSpace  = 1;
161468      nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
161469      nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
161470    }
161471  
161472    pWriter->nLeafData += nSpace;
161473    blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
161474    if( rc==SQLITE_OK ){
161475      if( pLeaf->block.n==0 ){
161476        pLeaf->block.n = 1;
161477        pLeaf->block.a[0] = '\0';
161478      }
161479      rc = fts3AppendToNode(
161480          &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
161481      );
161482    }
161483  
161484    return rc;
161485  }
161486  
161487  /*
161488  ** This function is called to release all dynamic resources held by the
161489  ** merge-writer object pWriter, and if no error has occurred, to flush
161490  ** all outstanding node buffers held by pWriter to disk.
161491  **
161492  ** If *pRc is not SQLITE_OK when this function is called, then no attempt
161493  ** is made to write any data to disk. Instead, this function serves only
161494  ** to release outstanding resources.
161495  **
161496  ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
161497  ** flushing buffers to disk, *pRc is set to an SQLite error code before
161498  ** returning.
161499  */
161500  static void fts3IncrmergeRelease(
161501    Fts3Table *p,                   /* FTS3 table handle */
161502    IncrmergeWriter *pWriter,       /* Merge-writer object */
161503    int *pRc                        /* IN/OUT: Error code */
161504  ){
161505    int i;                          /* Used to iterate through non-root layers */
161506    int iRoot;                      /* Index of root in pWriter->aNodeWriter */
161507    NodeWriter *pRoot;              /* NodeWriter for root node */
161508    int rc = *pRc;                  /* Error code */
161509  
161510    /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment 
161511    ** root node. If the segment fits entirely on a single leaf node, iRoot
161512    ** will be set to 0. If the root node is the parent of the leaves, iRoot
161513    ** will be 1. And so on.  */
161514    for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
161515      NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
161516      if( pNode->block.n>0 ) break;
161517      assert( *pRc || pNode->block.nAlloc==0 );
161518      assert( *pRc || pNode->key.nAlloc==0 );
161519      sqlite3_free(pNode->block.a);
161520      sqlite3_free(pNode->key.a);
161521    }
161522  
161523    /* Empty output segment. This is a no-op. */
161524    if( iRoot<0 ) return;
161525  
161526    /* The entire output segment fits on a single node. Normally, this means
161527    ** the node would be stored as a blob in the "root" column of the %_segdir
161528    ** table. However, this is not permitted in this case. The problem is that 
161529    ** space has already been reserved in the %_segments table, and so the 
161530    ** start_block and end_block fields of the %_segdir table must be populated. 
161531    ** And, by design or by accident, released versions of FTS cannot handle 
161532    ** segments that fit entirely on the root node with start_block!=0.
161533    **
161534    ** Instead, create a synthetic root node that contains nothing but a 
161535    ** pointer to the single content node. So that the segment consists of a
161536    ** single leaf and a single interior (root) node.
161537    **
161538    ** Todo: Better might be to defer allocating space in the %_segments 
161539    ** table until we are sure it is needed.
161540    */
161541    if( iRoot==0 ){
161542      Blob *pBlock = &pWriter->aNodeWriter[1].block;
161543      blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
161544      if( rc==SQLITE_OK ){
161545        pBlock->a[0] = 0x01;
161546        pBlock->n = 1 + sqlite3Fts3PutVarint(
161547            &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
161548        );
161549      }
161550      iRoot = 1;
161551    }
161552    pRoot = &pWriter->aNodeWriter[iRoot];
161553  
161554    /* Flush all currently outstanding nodes to disk. */
161555    for(i=0; i<iRoot; i++){
161556      NodeWriter *pNode = &pWriter->aNodeWriter[i];
161557      if( pNode->block.n>0 && rc==SQLITE_OK ){
161558        rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
161559      }
161560      sqlite3_free(pNode->block.a);
161561      sqlite3_free(pNode->key.a);
161562    }
161563  
161564    /* Write the %_segdir record. */
161565    if( rc==SQLITE_OK ){
161566      rc = fts3WriteSegdir(p, 
161567          pWriter->iAbsLevel+1,               /* level */
161568          pWriter->iIdx,                      /* idx */
161569          pWriter->iStart,                    /* start_block */
161570          pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
161571          pWriter->iEnd,                      /* end_block */
161572          (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0),   /* end_block */
161573          pRoot->block.a, pRoot->block.n      /* root */
161574      );
161575    }
161576    sqlite3_free(pRoot->block.a);
161577    sqlite3_free(pRoot->key.a);
161578  
161579    *pRc = rc;
161580  }
161581  
161582  /*
161583  ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
161584  ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
161585  ** the other, it is considered to be smaller than the other.
161586  **
161587  ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
161588  ** if it is greater.
161589  */
161590  static int fts3TermCmp(
161591    const char *zLhs, int nLhs,     /* LHS of comparison */
161592    const char *zRhs, int nRhs      /* RHS of comparison */
161593  ){
161594    int nCmp = MIN(nLhs, nRhs);
161595    int res;
161596  
161597    res = memcmp(zLhs, zRhs, nCmp);
161598    if( res==0 ) res = nLhs - nRhs;
161599  
161600    return res;
161601  }
161602  
161603  
161604  /*
161605  ** Query to see if the entry in the %_segments table with blockid iEnd is 
161606  ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
161607  ** returning. Otherwise, set *pbRes to 0. 
161608  **
161609  ** Or, if an error occurs while querying the database, return an SQLite 
161610  ** error code. The final value of *pbRes is undefined in this case.
161611  **
161612  ** This is used to test if a segment is an "appendable" segment. If it
161613  ** is, then a NULL entry has been inserted into the %_segments table
161614  ** with blockid %_segdir.end_block.
161615  */
161616  static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
161617    int bRes = 0;                   /* Result to set *pbRes to */
161618    sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
161619    int rc;                         /* Return code */
161620  
161621    rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
161622    if( rc==SQLITE_OK ){
161623      sqlite3_bind_int64(pCheck, 1, iEnd);
161624      if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
161625      rc = sqlite3_reset(pCheck);
161626    }
161627    
161628    *pbRes = bRes;
161629    return rc;
161630  }
161631  
161632  /*
161633  ** This function is called when initializing an incremental-merge operation.
161634  ** It checks if the existing segment with index value iIdx at absolute level 
161635  ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
161636  ** merge-writer object *pWriter is initialized to write to it.
161637  **
161638  ** An existing segment can be appended to by an incremental merge if:
161639  **
161640  **   * It was initially created as an appendable segment (with all required
161641  **     space pre-allocated), and
161642  **
161643  **   * The first key read from the input (arguments zKey and nKey) is 
161644  **     greater than the largest key currently stored in the potential
161645  **     output segment.
161646  */
161647  static int fts3IncrmergeLoad(
161648    Fts3Table *p,                   /* Fts3 table handle */
161649    sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
161650    int iIdx,                       /* Index of candidate output segment */
161651    const char *zKey,               /* First key to write */
161652    int nKey,                       /* Number of bytes in nKey */
161653    IncrmergeWriter *pWriter        /* Populate this object */
161654  ){
161655    int rc;                         /* Return code */
161656    sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
161657  
161658    rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
161659    if( rc==SQLITE_OK ){
161660      sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
161661      sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
161662      sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
161663      const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
161664      int nRoot = 0;                /* Size of aRoot[] in bytes */
161665      int rc2;                      /* Return code from sqlite3_reset() */
161666      int bAppendable = 0;          /* Set to true if segment is appendable */
161667  
161668      /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
161669      sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
161670      sqlite3_bind_int(pSelect, 2, iIdx);
161671      if( sqlite3_step(pSelect)==SQLITE_ROW ){
161672        iStart = sqlite3_column_int64(pSelect, 1);
161673        iLeafEnd = sqlite3_column_int64(pSelect, 2);
161674        fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
161675        if( pWriter->nLeafData<0 ){
161676          pWriter->nLeafData = pWriter->nLeafData * -1;
161677        }
161678        pWriter->bNoLeafData = (pWriter->nLeafData==0);
161679        nRoot = sqlite3_column_bytes(pSelect, 4);
161680        aRoot = sqlite3_column_blob(pSelect, 4);
161681      }else{
161682        return sqlite3_reset(pSelect);
161683      }
161684  
161685      /* Check for the zero-length marker in the %_segments table */
161686      rc = fts3IsAppendable(p, iEnd, &bAppendable);
161687  
161688      /* Check that zKey/nKey is larger than the largest key the candidate */
161689      if( rc==SQLITE_OK && bAppendable ){
161690        char *aLeaf = 0;
161691        int nLeaf = 0;
161692  
161693        rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
161694        if( rc==SQLITE_OK ){
161695          NodeReader reader;
161696          for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
161697              rc==SQLITE_OK && reader.aNode;
161698              rc = nodeReaderNext(&reader)
161699          ){
161700            assert( reader.aNode );
161701          }
161702          if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
161703            bAppendable = 0;
161704          }
161705          nodeReaderRelease(&reader);
161706        }
161707        sqlite3_free(aLeaf);
161708      }
161709  
161710      if( rc==SQLITE_OK && bAppendable ){
161711        /* It is possible to append to this segment. Set up the IncrmergeWriter
161712        ** object to do so.  */
161713        int i;
161714        int nHeight = (int)aRoot[0];
161715        NodeWriter *pNode;
161716  
161717        pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
161718        pWriter->iStart = iStart;
161719        pWriter->iEnd = iEnd;
161720        pWriter->iAbsLevel = iAbsLevel;
161721        pWriter->iIdx = iIdx;
161722  
161723        for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
161724          pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
161725        }
161726  
161727        pNode = &pWriter->aNodeWriter[nHeight];
161728        pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
161729        blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
161730        if( rc==SQLITE_OK ){
161731          memcpy(pNode->block.a, aRoot, nRoot);
161732          pNode->block.n = nRoot;
161733        }
161734  
161735        for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
161736          NodeReader reader;
161737          pNode = &pWriter->aNodeWriter[i];
161738  
161739          rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
161740          while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
161741          blobGrowBuffer(&pNode->key, reader.term.n, &rc);
161742          if( rc==SQLITE_OK ){
161743            memcpy(pNode->key.a, reader.term.a, reader.term.n);
161744            pNode->key.n = reader.term.n;
161745            if( i>0 ){
161746              char *aBlock = 0;
161747              int nBlock = 0;
161748              pNode = &pWriter->aNodeWriter[i-1];
161749              pNode->iBlock = reader.iChild;
161750              rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
161751              blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
161752              if( rc==SQLITE_OK ){
161753                memcpy(pNode->block.a, aBlock, nBlock);
161754                pNode->block.n = nBlock;
161755              }
161756              sqlite3_free(aBlock);
161757            }
161758          }
161759          nodeReaderRelease(&reader);
161760        }
161761      }
161762  
161763      rc2 = sqlite3_reset(pSelect);
161764      if( rc==SQLITE_OK ) rc = rc2;
161765    }
161766  
161767    return rc;
161768  }
161769  
161770  /*
161771  ** Determine the largest segment index value that exists within absolute
161772  ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
161773  ** one before returning SQLITE_OK. Or, if there are no segments at all 
161774  ** within level iAbsLevel, set *piIdx to zero.
161775  **
161776  ** If an error occurs, return an SQLite error code. The final value of
161777  ** *piIdx is undefined in this case.
161778  */
161779  static int fts3IncrmergeOutputIdx( 
161780    Fts3Table *p,                   /* FTS Table handle */
161781    sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
161782    int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
161783  ){
161784    int rc;
161785    sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
161786  
161787    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
161788    if( rc==SQLITE_OK ){
161789      sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
161790      sqlite3_step(pOutputIdx);
161791      *piIdx = sqlite3_column_int(pOutputIdx, 0);
161792      rc = sqlite3_reset(pOutputIdx);
161793    }
161794  
161795    return rc;
161796  }
161797  
161798  /* 
161799  ** Allocate an appendable output segment on absolute level iAbsLevel+1
161800  ** with idx value iIdx.
161801  **
161802  ** In the %_segdir table, a segment is defined by the values in three
161803  ** columns:
161804  **
161805  **     start_block
161806  **     leaves_end_block
161807  **     end_block
161808  **
161809  ** When an appendable segment is allocated, it is estimated that the
161810  ** maximum number of leaf blocks that may be required is the sum of the
161811  ** number of leaf blocks consumed by the input segments, plus the number
161812  ** of input segments, multiplied by two. This value is stored in stack 
161813  ** variable nLeafEst.
161814  **
161815  ** A total of 16*nLeafEst blocks are allocated when an appendable segment
161816  ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
161817  ** array of leaf nodes starts at the first block allocated. The array
161818  ** of interior nodes that are parents of the leaf nodes start at block
161819  ** (start_block + (1 + end_block - start_block) / 16). And so on.
161820  **
161821  ** In the actual code below, the value "16" is replaced with the 
161822  ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
161823  */
161824  static int fts3IncrmergeWriter( 
161825    Fts3Table *p,                   /* Fts3 table handle */
161826    sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
161827    int iIdx,                       /* Index of new output segment */
161828    Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
161829    IncrmergeWriter *pWriter        /* Populate this object */
161830  ){
161831    int rc;                         /* Return Code */
161832    int i;                          /* Iterator variable */
161833    int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
161834    sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
161835    sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
161836  
161837    /* Calculate nLeafEst. */
161838    rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
161839    if( rc==SQLITE_OK ){
161840      sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
161841      sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
161842      if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
161843        nLeafEst = sqlite3_column_int(pLeafEst, 0);
161844      }
161845      rc = sqlite3_reset(pLeafEst);
161846    }
161847    if( rc!=SQLITE_OK ) return rc;
161848  
161849    /* Calculate the first block to use in the output segment */
161850    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
161851    if( rc==SQLITE_OK ){
161852      if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
161853        pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
161854        pWriter->iEnd = pWriter->iStart - 1;
161855        pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
161856      }
161857      rc = sqlite3_reset(pFirstBlock);
161858    }
161859    if( rc!=SQLITE_OK ) return rc;
161860  
161861    /* Insert the marker in the %_segments table to make sure nobody tries
161862    ** to steal the space just allocated. This is also used to identify 
161863    ** appendable segments.  */
161864    rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
161865    if( rc!=SQLITE_OK ) return rc;
161866  
161867    pWriter->iAbsLevel = iAbsLevel;
161868    pWriter->nLeafEst = nLeafEst;
161869    pWriter->iIdx = iIdx;
161870  
161871    /* Set up the array of NodeWriter objects */
161872    for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
161873      pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
161874    }
161875    return SQLITE_OK;
161876  }
161877  
161878  /*
161879  ** Remove an entry from the %_segdir table. This involves running the 
161880  ** following two statements:
161881  **
161882  **   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
161883  **   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
161884  **
161885  ** The DELETE statement removes the specific %_segdir level. The UPDATE 
161886  ** statement ensures that the remaining segments have contiguously allocated
161887  ** idx values.
161888  */
161889  static int fts3RemoveSegdirEntry(
161890    Fts3Table *p,                   /* FTS3 table handle */
161891    sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
161892    int iIdx                        /* Index of %_segdir entry to delete */
161893  ){
161894    int rc;                         /* Return code */
161895    sqlite3_stmt *pDelete = 0;      /* DELETE statement */
161896  
161897    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
161898    if( rc==SQLITE_OK ){
161899      sqlite3_bind_int64(pDelete, 1, iAbsLevel);
161900      sqlite3_bind_int(pDelete, 2, iIdx);
161901      sqlite3_step(pDelete);
161902      rc = sqlite3_reset(pDelete);
161903    }
161904  
161905    return rc;
161906  }
161907  
161908  /*
161909  ** One or more segments have just been removed from absolute level iAbsLevel.
161910  ** Update the 'idx' values of the remaining segments in the level so that
161911  ** the idx values are a contiguous sequence starting from 0.
161912  */
161913  static int fts3RepackSegdirLevel(
161914    Fts3Table *p,                   /* FTS3 table handle */
161915    sqlite3_int64 iAbsLevel         /* Absolute level to repack */
161916  ){
161917    int rc;                         /* Return code */
161918    int *aIdx = 0;                  /* Array of remaining idx values */
161919    int nIdx = 0;                   /* Valid entries in aIdx[] */
161920    int nAlloc = 0;                 /* Allocated size of aIdx[] */
161921    int i;                          /* Iterator variable */
161922    sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
161923    sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
161924  
161925    rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
161926    if( rc==SQLITE_OK ){
161927      int rc2;
161928      sqlite3_bind_int64(pSelect, 1, iAbsLevel);
161929      while( SQLITE_ROW==sqlite3_step(pSelect) ){
161930        if( nIdx>=nAlloc ){
161931          int *aNew;
161932          nAlloc += 16;
161933          aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
161934          if( !aNew ){
161935            rc = SQLITE_NOMEM;
161936            break;
161937          }
161938          aIdx = aNew;
161939        }
161940        aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
161941      }
161942      rc2 = sqlite3_reset(pSelect);
161943      if( rc==SQLITE_OK ) rc = rc2;
161944    }
161945  
161946    if( rc==SQLITE_OK ){
161947      rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
161948    }
161949    if( rc==SQLITE_OK ){
161950      sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
161951    }
161952  
161953    assert( p->bIgnoreSavepoint==0 );
161954    p->bIgnoreSavepoint = 1;
161955    for(i=0; rc==SQLITE_OK && i<nIdx; i++){
161956      if( aIdx[i]!=i ){
161957        sqlite3_bind_int(pUpdate, 3, aIdx[i]);
161958        sqlite3_bind_int(pUpdate, 1, i);
161959        sqlite3_step(pUpdate);
161960        rc = sqlite3_reset(pUpdate);
161961      }
161962    }
161963    p->bIgnoreSavepoint = 0;
161964  
161965    sqlite3_free(aIdx);
161966    return rc;
161967  }
161968  
161969  static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
161970    pNode->a[0] = (char)iHeight;
161971    if( iChild ){
161972      assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
161973      pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
161974    }else{
161975      assert( pNode->nAlloc>=1 );
161976      pNode->n = 1;
161977    }
161978  }
161979  
161980  /*
161981  ** The first two arguments are a pointer to and the size of a segment b-tree
161982  ** node. The node may be a leaf or an internal node.
161983  **
161984  ** This function creates a new node image in blob object *pNew by copying
161985  ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
161986  ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
161987  */
161988  static int fts3TruncateNode(
161989    const char *aNode,              /* Current node image */
161990    int nNode,                      /* Size of aNode in bytes */
161991    Blob *pNew,                     /* OUT: Write new node image here */
161992    const char *zTerm,              /* Omit all terms smaller than this */
161993    int nTerm,                      /* Size of zTerm in bytes */
161994    sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
161995  ){
161996    NodeReader reader;              /* Reader object */
161997    Blob prev = {0, 0, 0};          /* Previous term written to new node */
161998    int rc = SQLITE_OK;             /* Return code */
161999    int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
162000  
162001    /* Allocate required output space */
162002    blobGrowBuffer(pNew, nNode, &rc);
162003    if( rc!=SQLITE_OK ) return rc;
162004    pNew->n = 0;
162005  
162006    /* Populate new node buffer */
162007    for(rc = nodeReaderInit(&reader, aNode, nNode); 
162008        rc==SQLITE_OK && reader.aNode; 
162009        rc = nodeReaderNext(&reader)
162010    ){
162011      if( pNew->n==0 ){
162012        int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
162013        if( res<0 || (bLeaf==0 && res==0) ) continue;
162014        fts3StartNode(pNew, (int)aNode[0], reader.iChild);
162015        *piBlock = reader.iChild;
162016      }
162017      rc = fts3AppendToNode(
162018          pNew, &prev, reader.term.a, reader.term.n,
162019          reader.aDoclist, reader.nDoclist
162020      );
162021      if( rc!=SQLITE_OK ) break;
162022    }
162023    if( pNew->n==0 ){
162024      fts3StartNode(pNew, (int)aNode[0], reader.iChild);
162025      *piBlock = reader.iChild;
162026    }
162027    assert( pNew->n<=pNew->nAlloc );
162028  
162029    nodeReaderRelease(&reader);
162030    sqlite3_free(prev.a);
162031    return rc;
162032  }
162033  
162034  /*
162035  ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute 
162036  ** level iAbsLevel. This may involve deleting entries from the %_segments
162037  ** table, and modifying existing entries in both the %_segments and %_segdir
162038  ** tables.
162039  **
162040  ** SQLITE_OK is returned if the segment is updated successfully. Or an
162041  ** SQLite error code otherwise.
162042  */
162043  static int fts3TruncateSegment(
162044    Fts3Table *p,                   /* FTS3 table handle */
162045    sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
162046    int iIdx,                       /* Index within level of segment to modify */
162047    const char *zTerm,              /* Remove terms smaller than this */
162048    int nTerm                      /* Number of bytes in buffer zTerm */
162049  ){
162050    int rc = SQLITE_OK;             /* Return code */
162051    Blob root = {0,0,0};            /* New root page image */
162052    Blob block = {0,0,0};           /* Buffer used for any other block */
162053    sqlite3_int64 iBlock = 0;       /* Block id */
162054    sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
162055    sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
162056    sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
162057  
162058    rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
162059    if( rc==SQLITE_OK ){
162060      int rc2;                      /* sqlite3_reset() return code */
162061      sqlite3_bind_int64(pFetch, 1, iAbsLevel);
162062      sqlite3_bind_int(pFetch, 2, iIdx);
162063      if( SQLITE_ROW==sqlite3_step(pFetch) ){
162064        const char *aRoot = sqlite3_column_blob(pFetch, 4);
162065        int nRoot = sqlite3_column_bytes(pFetch, 4);
162066        iOldStart = sqlite3_column_int64(pFetch, 1);
162067        rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
162068      }
162069      rc2 = sqlite3_reset(pFetch);
162070      if( rc==SQLITE_OK ) rc = rc2;
162071    }
162072  
162073    while( rc==SQLITE_OK && iBlock ){
162074      char *aBlock = 0;
162075      int nBlock = 0;
162076      iNewStart = iBlock;
162077  
162078      rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
162079      if( rc==SQLITE_OK ){
162080        rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
162081      }
162082      if( rc==SQLITE_OK ){
162083        rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
162084      }
162085      sqlite3_free(aBlock);
162086    }
162087  
162088    /* Variable iNewStart now contains the first valid leaf node. */
162089    if( rc==SQLITE_OK && iNewStart ){
162090      sqlite3_stmt *pDel = 0;
162091      rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
162092      if( rc==SQLITE_OK ){
162093        sqlite3_bind_int64(pDel, 1, iOldStart);
162094        sqlite3_bind_int64(pDel, 2, iNewStart-1);
162095        sqlite3_step(pDel);
162096        rc = sqlite3_reset(pDel);
162097      }
162098    }
162099  
162100    if( rc==SQLITE_OK ){
162101      sqlite3_stmt *pChomp = 0;
162102      rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
162103      if( rc==SQLITE_OK ){
162104        sqlite3_bind_int64(pChomp, 1, iNewStart);
162105        sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
162106        sqlite3_bind_int64(pChomp, 3, iAbsLevel);
162107        sqlite3_bind_int(pChomp, 4, iIdx);
162108        sqlite3_step(pChomp);
162109        rc = sqlite3_reset(pChomp);
162110      }
162111    }
162112  
162113    sqlite3_free(root.a);
162114    sqlite3_free(block.a);
162115    return rc;
162116  }
162117  
162118  /*
162119  ** This function is called after an incrmental-merge operation has run to
162120  ** merge (or partially merge) two or more segments from absolute level
162121  ** iAbsLevel.
162122  **
162123  ** Each input segment is either removed from the db completely (if all of
162124  ** its data was copied to the output segment by the incrmerge operation)
162125  ** or modified in place so that it no longer contains those entries that
162126  ** have been duplicated in the output segment.
162127  */
162128  static int fts3IncrmergeChomp(
162129    Fts3Table *p,                   /* FTS table handle */
162130    sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
162131    Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
162132    int *pnRem                      /* Number of segments not deleted */
162133  ){
162134    int i;
162135    int nRem = 0;
162136    int rc = SQLITE_OK;
162137  
162138    for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
162139      Fts3SegReader *pSeg = 0;
162140      int j;
162141  
162142      /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
162143      ** somewhere in the pCsr->apSegment[] array.  */
162144      for(j=0; ALWAYS(j<pCsr->nSegment); j++){
162145        pSeg = pCsr->apSegment[j];
162146        if( pSeg->iIdx==i ) break;
162147      }
162148      assert( j<pCsr->nSegment && pSeg->iIdx==i );
162149  
162150      if( pSeg->aNode==0 ){
162151        /* Seg-reader is at EOF. Remove the entire input segment. */
162152        rc = fts3DeleteSegment(p, pSeg);
162153        if( rc==SQLITE_OK ){
162154          rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
162155        }
162156        *pnRem = 0;
162157      }else{
162158        /* The incremental merge did not copy all the data from this 
162159        ** segment to the upper level. The segment is modified in place
162160        ** so that it contains no keys smaller than zTerm/nTerm. */ 
162161        const char *zTerm = pSeg->zTerm;
162162        int nTerm = pSeg->nTerm;
162163        rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
162164        nRem++;
162165      }
162166    }
162167  
162168    if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
162169      rc = fts3RepackSegdirLevel(p, iAbsLevel);
162170    }
162171  
162172    *pnRem = nRem;
162173    return rc;
162174  }
162175  
162176  /*
162177  ** Store an incr-merge hint in the database.
162178  */
162179  static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
162180    sqlite3_stmt *pReplace = 0;
162181    int rc;                         /* Return code */
162182  
162183    rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
162184    if( rc==SQLITE_OK ){
162185      sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
162186      sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
162187      sqlite3_step(pReplace);
162188      rc = sqlite3_reset(pReplace);
162189    }
162190  
162191    return rc;
162192  }
162193  
162194  /*
162195  ** Load an incr-merge hint from the database. The incr-merge hint, if one 
162196  ** exists, is stored in the rowid==1 row of the %_stat table.
162197  **
162198  ** If successful, populate blob *pHint with the value read from the %_stat
162199  ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
162200  ** SQLite error code.
162201  */
162202  static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
162203    sqlite3_stmt *pSelect = 0;
162204    int rc;
162205  
162206    pHint->n = 0;
162207    rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
162208    if( rc==SQLITE_OK ){
162209      int rc2;
162210      sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
162211      if( SQLITE_ROW==sqlite3_step(pSelect) ){
162212        const char *aHint = sqlite3_column_blob(pSelect, 0);
162213        int nHint = sqlite3_column_bytes(pSelect, 0);
162214        if( aHint ){
162215          blobGrowBuffer(pHint, nHint, &rc);
162216          if( rc==SQLITE_OK ){
162217            memcpy(pHint->a, aHint, nHint);
162218            pHint->n = nHint;
162219          }
162220        }
162221      }
162222      rc2 = sqlite3_reset(pSelect);
162223      if( rc==SQLITE_OK ) rc = rc2;
162224    }
162225  
162226    return rc;
162227  }
162228  
162229  /*
162230  ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
162231  ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
162232  ** consists of two varints, the absolute level number of the input segments 
162233  ** and the number of input segments.
162234  **
162235  ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
162236  ** set *pRc to an SQLite error code before returning.
162237  */
162238  static void fts3IncrmergeHintPush(
162239    Blob *pHint,                    /* Hint blob to append to */
162240    i64 iAbsLevel,                  /* First varint to store in hint */
162241    int nInput,                     /* Second varint to store in hint */
162242    int *pRc                        /* IN/OUT: Error code */
162243  ){
162244    blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
162245    if( *pRc==SQLITE_OK ){
162246      pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
162247      pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
162248    }
162249  }
162250  
162251  /*
162252  ** Read the last entry (most recently pushed) from the hint blob *pHint
162253  ** and then remove the entry. Write the two values read to *piAbsLevel and 
162254  ** *pnInput before returning.
162255  **
162256  ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
162257  ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
162258  */
162259  static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
162260    const int nHint = pHint->n;
162261    int i;
162262  
162263    i = pHint->n-2;
162264    while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
162265    while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
162266  
162267    pHint->n = i;
162268    i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
162269    i += fts3GetVarint32(&pHint->a[i], pnInput);
162270    if( i!=nHint ) return FTS_CORRUPT_VTAB;
162271  
162272    return SQLITE_OK;
162273  }
162274  
162275  
162276  /*
162277  ** Attempt an incremental merge that writes nMerge leaf blocks.
162278  **
162279  ** Incremental merges happen nMin segments at a time. The segments 
162280  ** to be merged are the nMin oldest segments (the ones with the smallest 
162281  ** values for the _segdir.idx field) in the highest level that contains 
162282  ** at least nMin segments. Multiple merges might occur in an attempt to 
162283  ** write the quota of nMerge leaf blocks.
162284  */
162285  SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
162286    int rc;                         /* Return code */
162287    int nRem = nMerge;              /* Number of leaf pages yet to  be written */
162288    Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
162289    Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
162290    IncrmergeWriter *pWriter;       /* Writer object */
162291    int nSeg = 0;                   /* Number of input segments */
162292    sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
162293    Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
162294    int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
162295  
162296    /* Allocate space for the cursor, filter and writer objects */
162297    const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
162298    pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
162299    if( !pWriter ) return SQLITE_NOMEM;
162300    pFilter = (Fts3SegFilter *)&pWriter[1];
162301    pCsr = (Fts3MultiSegReader *)&pFilter[1];
162302  
162303    rc = fts3IncrmergeHintLoad(p, &hint);
162304    while( rc==SQLITE_OK && nRem>0 ){
162305      const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
162306      sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
162307      int bUseHint = 0;             /* True if attempting to append */
162308      int iIdx = 0;                 /* Largest idx in level (iAbsLevel+1) */
162309  
162310      /* Search the %_segdir table for the absolute level with the smallest
162311      ** relative level number that contains at least nMin segments, if any.
162312      ** If one is found, set iAbsLevel to the absolute level number and
162313      ** nSeg to nMin. If no level with at least nMin segments can be found, 
162314      ** set nSeg to -1.
162315      */
162316      rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
162317      sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
162318      if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
162319        iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
162320        nSeg = sqlite3_column_int(pFindLevel, 1);
162321        assert( nSeg>=2 );
162322      }else{
162323        nSeg = -1;
162324      }
162325      rc = sqlite3_reset(pFindLevel);
162326  
162327      /* If the hint read from the %_stat table is not empty, check if the
162328      ** last entry in it specifies a relative level smaller than or equal
162329      ** to the level identified by the block above (if any). If so, this 
162330      ** iteration of the loop will work on merging at the hinted level.
162331      */
162332      if( rc==SQLITE_OK && hint.n ){
162333        int nHint = hint.n;
162334        sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
162335        int nHintSeg = 0;                     /* Hint number of segments */
162336  
162337        rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
162338        if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
162339          iAbsLevel = iHintAbsLevel;
162340          nSeg = nHintSeg;
162341          bUseHint = 1;
162342          bDirtyHint = 1;
162343        }else{
162344          /* This undoes the effect of the HintPop() above - so that no entry
162345          ** is removed from the hint blob.  */
162346          hint.n = nHint;
162347        }
162348      }
162349  
162350      /* If nSeg is less that zero, then there is no level with at least
162351      ** nMin segments and no hint in the %_stat table. No work to do.
162352      ** Exit early in this case.  */
162353      if( nSeg<0 ) break;
162354  
162355      /* Open a cursor to iterate through the contents of the oldest nSeg 
162356      ** indexes of absolute level iAbsLevel. If this cursor is opened using 
162357      ** the 'hint' parameters, it is possible that there are less than nSeg
162358      ** segments available in level iAbsLevel. In this case, no work is
162359      ** done on iAbsLevel - fall through to the next iteration of the loop 
162360      ** to start work on some other level.  */
162361      memset(pWriter, 0, nAlloc);
162362      pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
162363  
162364      if( rc==SQLITE_OK ){
162365        rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
162366        assert( bUseHint==1 || bUseHint==0 );
162367        if( iIdx==0 || (bUseHint && iIdx==1) ){
162368          int bIgnore = 0;
162369          rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
162370          if( bIgnore ){
162371            pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
162372          }
162373        }
162374      }
162375  
162376      if( rc==SQLITE_OK ){
162377        rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
162378      }
162379      if( SQLITE_OK==rc && pCsr->nSegment==nSeg
162380       && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
162381       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
162382      ){
162383        if( bUseHint && iIdx>0 ){
162384          const char *zKey = pCsr->zTerm;
162385          int nKey = pCsr->nTerm;
162386          rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
162387        }else{
162388          rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
162389        }
162390  
162391        if( rc==SQLITE_OK && pWriter->nLeafEst ){
162392          fts3LogMerge(nSeg, iAbsLevel);
162393          do {
162394            rc = fts3IncrmergeAppend(p, pWriter, pCsr);
162395            if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
162396            if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
162397          }while( rc==SQLITE_ROW );
162398  
162399          /* Update or delete the input segments */
162400          if( rc==SQLITE_OK ){
162401            nRem -= (1 + pWriter->nWork);
162402            rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
162403            if( nSeg!=0 ){
162404              bDirtyHint = 1;
162405              fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
162406            }
162407          }
162408        }
162409  
162410        if( nSeg!=0 ){
162411          pWriter->nLeafData = pWriter->nLeafData * -1;
162412        }
162413        fts3IncrmergeRelease(p, pWriter, &rc);
162414        if( nSeg==0 && pWriter->bNoLeafData==0 ){
162415          fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
162416        }
162417      }
162418  
162419      sqlite3Fts3SegReaderFinish(pCsr);
162420    }
162421  
162422    /* Write the hint values into the %_stat table for the next incr-merger */
162423    if( bDirtyHint && rc==SQLITE_OK ){
162424      rc = fts3IncrmergeHintStore(p, &hint);
162425    }
162426  
162427    sqlite3_free(pWriter);
162428    sqlite3_free(hint.a);
162429    return rc;
162430  }
162431  
162432  /*
162433  ** Convert the text beginning at *pz into an integer and return
162434  ** its value.  Advance *pz to point to the first character past
162435  ** the integer.
162436  **
162437  ** This function used for parameters to merge= and incrmerge=
162438  ** commands. 
162439  */
162440  static int fts3Getint(const char **pz){
162441    const char *z = *pz;
162442    int i = 0;
162443    while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0';
162444    *pz = z;
162445    return i;
162446  }
162447  
162448  /*
162449  ** Process statements of the form:
162450  **
162451  **    INSERT INTO table(table) VALUES('merge=A,B');
162452  **
162453  ** A and B are integers that decode to be the number of leaf pages
162454  ** written for the merge, and the minimum number of segments on a level
162455  ** before it will be selected for a merge, respectively.
162456  */
162457  static int fts3DoIncrmerge(
162458    Fts3Table *p,                   /* FTS3 table handle */
162459    const char *zParam              /* Nul-terminated string containing "A,B" */
162460  ){
162461    int rc;
162462    int nMin = (FTS3_MERGE_COUNT / 2);
162463    int nMerge = 0;
162464    const char *z = zParam;
162465  
162466    /* Read the first integer value */
162467    nMerge = fts3Getint(&z);
162468  
162469    /* If the first integer value is followed by a ',',  read the second
162470    ** integer value. */
162471    if( z[0]==',' && z[1]!='\0' ){
162472      z++;
162473      nMin = fts3Getint(&z);
162474    }
162475  
162476    if( z[0]!='\0' || nMin<2 ){
162477      rc = SQLITE_ERROR;
162478    }else{
162479      rc = SQLITE_OK;
162480      if( !p->bHasStat ){
162481        assert( p->bFts4==0 );
162482        sqlite3Fts3CreateStatTable(&rc, p);
162483      }
162484      if( rc==SQLITE_OK ){
162485        rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
162486      }
162487      sqlite3Fts3SegmentsClose(p);
162488    }
162489    return rc;
162490  }
162491  
162492  /*
162493  ** Process statements of the form:
162494  **
162495  **    INSERT INTO table(table) VALUES('automerge=X');
162496  **
162497  ** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
162498  ** turn it on.  The setting is persistent.
162499  */
162500  static int fts3DoAutoincrmerge(
162501    Fts3Table *p,                   /* FTS3 table handle */
162502    const char *zParam              /* Nul-terminated string containing boolean */
162503  ){
162504    int rc = SQLITE_OK;
162505    sqlite3_stmt *pStmt = 0;
162506    p->nAutoincrmerge = fts3Getint(&zParam);
162507    if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
162508      p->nAutoincrmerge = 8;
162509    }
162510    if( !p->bHasStat ){
162511      assert( p->bFts4==0 );
162512      sqlite3Fts3CreateStatTable(&rc, p);
162513      if( rc ) return rc;
162514    }
162515    rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
162516    if( rc ) return rc;
162517    sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
162518    sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
162519    sqlite3_step(pStmt);
162520    rc = sqlite3_reset(pStmt);
162521    return rc;
162522  }
162523  
162524  /*
162525  ** Return a 64-bit checksum for the FTS index entry specified by the
162526  ** arguments to this function.
162527  */
162528  static u64 fts3ChecksumEntry(
162529    const char *zTerm,              /* Pointer to buffer containing term */
162530    int nTerm,                      /* Size of zTerm in bytes */
162531    int iLangid,                    /* Language id for current row */
162532    int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
162533    i64 iDocid,                     /* Docid for current row. */
162534    int iCol,                       /* Column number */
162535    int iPos                        /* Position */
162536  ){
162537    int i;
162538    u64 ret = (u64)iDocid;
162539  
162540    ret += (ret<<3) + iLangid;
162541    ret += (ret<<3) + iIndex;
162542    ret += (ret<<3) + iCol;
162543    ret += (ret<<3) + iPos;
162544    for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
162545  
162546    return ret;
162547  }
162548  
162549  /*
162550  ** Return a checksum of all entries in the FTS index that correspond to
162551  ** language id iLangid. The checksum is calculated by XORing the checksums
162552  ** of each individual entry (see fts3ChecksumEntry()) together.
162553  **
162554  ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
162555  ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
162556  ** return value is undefined in this case.
162557  */
162558  static u64 fts3ChecksumIndex(
162559    Fts3Table *p,                   /* FTS3 table handle */
162560    int iLangid,                    /* Language id to return cksum for */
162561    int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
162562    int *pRc                        /* OUT: Return code */
162563  ){
162564    Fts3SegFilter filter;
162565    Fts3MultiSegReader csr;
162566    int rc;
162567    u64 cksum = 0;
162568  
162569    assert( *pRc==SQLITE_OK );
162570  
162571    memset(&filter, 0, sizeof(filter));
162572    memset(&csr, 0, sizeof(csr));
162573    filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
162574    filter.flags |= FTS3_SEGMENT_SCAN;
162575  
162576    rc = sqlite3Fts3SegReaderCursor(
162577        p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
162578    );
162579    if( rc==SQLITE_OK ){
162580      rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
162581    }
162582  
162583    if( rc==SQLITE_OK ){
162584      while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
162585        char *pCsr = csr.aDoclist;
162586        char *pEnd = &pCsr[csr.nDoclist];
162587  
162588        i64 iDocid = 0;
162589        i64 iCol = 0;
162590        i64 iPos = 0;
162591  
162592        pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
162593        while( pCsr<pEnd ){
162594          i64 iVal = 0;
162595          pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
162596          if( pCsr<pEnd ){
162597            if( iVal==0 || iVal==1 ){
162598              iCol = 0;
162599              iPos = 0;
162600              if( iVal ){
162601                pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
162602              }else{
162603                pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
162604                iDocid += iVal;
162605              }
162606            }else{
162607              iPos += (iVal - 2);
162608              cksum = cksum ^ fts3ChecksumEntry(
162609                  csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
162610                  (int)iCol, (int)iPos
162611              );
162612            }
162613          }
162614        }
162615      }
162616    }
162617    sqlite3Fts3SegReaderFinish(&csr);
162618  
162619    *pRc = rc;
162620    return cksum;
162621  }
162622  
162623  /*
162624  ** Check if the contents of the FTS index match the current contents of the
162625  ** content table. If no error occurs and the contents do match, set *pbOk
162626  ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
162627  ** to false before returning.
162628  **
162629  ** If an error occurs (e.g. an OOM or IO error), return an SQLite error 
162630  ** code. The final value of *pbOk is undefined in this case.
162631  */
162632  static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
162633    int rc = SQLITE_OK;             /* Return code */
162634    u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
162635    u64 cksum2 = 0;                 /* Checksum based on %_content contents */
162636    sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
162637  
162638    /* This block calculates the checksum according to the FTS index. */
162639    rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
162640    if( rc==SQLITE_OK ){
162641      int rc2;
162642      sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
162643      sqlite3_bind_int(pAllLangid, 2, p->nIndex);
162644      while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
162645        int iLangid = sqlite3_column_int(pAllLangid, 0);
162646        int i;
162647        for(i=0; i<p->nIndex; i++){
162648          cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
162649        }
162650      }
162651      rc2 = sqlite3_reset(pAllLangid);
162652      if( rc==SQLITE_OK ) rc = rc2;
162653    }
162654  
162655    /* This block calculates the checksum according to the %_content table */
162656    if( rc==SQLITE_OK ){
162657      sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
162658      sqlite3_stmt *pStmt = 0;
162659      char *zSql;
162660     
162661      zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
162662      if( !zSql ){
162663        rc = SQLITE_NOMEM;
162664      }else{
162665        rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
162666        sqlite3_free(zSql);
162667      }
162668  
162669      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
162670        i64 iDocid = sqlite3_column_int64(pStmt, 0);
162671        int iLang = langidFromSelect(p, pStmt);
162672        int iCol;
162673  
162674        for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
162675          if( p->abNotindexed[iCol]==0 ){
162676            const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
162677            int nText = sqlite3_column_bytes(pStmt, iCol+1);
162678            sqlite3_tokenizer_cursor *pT = 0;
162679  
162680            rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
162681            while( rc==SQLITE_OK ){
162682              char const *zToken;       /* Buffer containing token */
162683              int nToken = 0;           /* Number of bytes in token */
162684              int iDum1 = 0, iDum2 = 0; /* Dummy variables */
162685              int iPos = 0;             /* Position of token in zText */
162686  
162687              rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
162688              if( rc==SQLITE_OK ){
162689                int i;
162690                cksum2 = cksum2 ^ fts3ChecksumEntry(
162691                    zToken, nToken, iLang, 0, iDocid, iCol, iPos
162692                );
162693                for(i=1; i<p->nIndex; i++){
162694                  if( p->aIndex[i].nPrefix<=nToken ){
162695                    cksum2 = cksum2 ^ fts3ChecksumEntry(
162696                        zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
162697                    );
162698                  }
162699                }
162700              }
162701            }
162702            if( pT ) pModule->xClose(pT);
162703            if( rc==SQLITE_DONE ) rc = SQLITE_OK;
162704          }
162705        }
162706      }
162707  
162708      sqlite3_finalize(pStmt);
162709    }
162710  
162711    *pbOk = (cksum1==cksum2);
162712    return rc;
162713  }
162714  
162715  /*
162716  ** Run the integrity-check. If no error occurs and the current contents of
162717  ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
162718  ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
162719  **
162720  ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite 
162721  ** error code.
162722  **
162723  ** The integrity-check works as follows. For each token and indexed token
162724  ** prefix in the document set, a 64-bit checksum is calculated (by code
162725  ** in fts3ChecksumEntry()) based on the following:
162726  **
162727  **     + The index number (0 for the main index, 1 for the first prefix
162728  **       index etc.),
162729  **     + The token (or token prefix) text itself, 
162730  **     + The language-id of the row it appears in,
162731  **     + The docid of the row it appears in,
162732  **     + The column it appears in, and
162733  **     + The tokens position within that column.
162734  **
162735  ** The checksums for all entries in the index are XORed together to create
162736  ** a single checksum for the entire index.
162737  **
162738  ** The integrity-check code calculates the same checksum in two ways:
162739  **
162740  **     1. By scanning the contents of the FTS index, and 
162741  **     2. By scanning and tokenizing the content table.
162742  **
162743  ** If the two checksums are identical, the integrity-check is deemed to have
162744  ** passed.
162745  */
162746  static int fts3DoIntegrityCheck(
162747    Fts3Table *p                    /* FTS3 table handle */
162748  ){
162749    int rc;
162750    int bOk = 0;
162751    rc = fts3IntegrityCheck(p, &bOk);
162752    if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
162753    return rc;
162754  }
162755  
162756  /*
162757  ** Handle a 'special' INSERT of the form:
162758  **
162759  **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
162760  **
162761  ** Argument pVal contains the result of <expr>. Currently the only 
162762  ** meaningful value to insert is the text 'optimize'.
162763  */
162764  static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
162765    int rc;                         /* Return Code */
162766    const char *zVal = (const char *)sqlite3_value_text(pVal);
162767    int nVal = sqlite3_value_bytes(pVal);
162768  
162769    if( !zVal ){
162770      return SQLITE_NOMEM;
162771    }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
162772      rc = fts3DoOptimize(p, 0);
162773    }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
162774      rc = fts3DoRebuild(p);
162775    }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
162776      rc = fts3DoIntegrityCheck(p);
162777    }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
162778      rc = fts3DoIncrmerge(p, &zVal[6]);
162779    }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
162780      rc = fts3DoAutoincrmerge(p, &zVal[10]);
162781  #ifdef SQLITE_TEST
162782    }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
162783      p->nNodeSize = atoi(&zVal[9]);
162784      rc = SQLITE_OK;
162785    }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
162786      p->nMaxPendingData = atoi(&zVal[11]);
162787      rc = SQLITE_OK;
162788    }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
162789      p->bNoIncrDoclist = atoi(&zVal[21]);
162790      rc = SQLITE_OK;
162791  #endif
162792    }else{
162793      rc = SQLITE_ERROR;
162794    }
162795  
162796    return rc;
162797  }
162798  
162799  #ifndef SQLITE_DISABLE_FTS4_DEFERRED
162800  /*
162801  ** Delete all cached deferred doclists. Deferred doclists are cached
162802  ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
162803  */
162804  SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
162805    Fts3DeferredToken *pDef;
162806    for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
162807      fts3PendingListDelete(pDef->pList);
162808      pDef->pList = 0;
162809    }
162810  }
162811  
162812  /*
162813  ** Free all entries in the pCsr->pDeffered list. Entries are added to 
162814  ** this list using sqlite3Fts3DeferToken().
162815  */
162816  SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
162817    Fts3DeferredToken *pDef;
162818    Fts3DeferredToken *pNext;
162819    for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
162820      pNext = pDef->pNext;
162821      fts3PendingListDelete(pDef->pList);
162822      sqlite3_free(pDef);
162823    }
162824    pCsr->pDeferred = 0;
162825  }
162826  
162827  /*
162828  ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
162829  ** based on the row that pCsr currently points to.
162830  **
162831  ** A deferred-doclist is like any other doclist with position information
162832  ** included, except that it only contains entries for a single row of the
162833  ** table, not for all rows.
162834  */
162835  SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
162836    int rc = SQLITE_OK;             /* Return code */
162837    if( pCsr->pDeferred ){
162838      int i;                        /* Used to iterate through table columns */
162839      sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
162840      Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
162841    
162842      Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
162843      sqlite3_tokenizer *pT = p->pTokenizer;
162844      sqlite3_tokenizer_module const *pModule = pT->pModule;
162845     
162846      assert( pCsr->isRequireSeek==0 );
162847      iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
162848    
162849      for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
162850        if( p->abNotindexed[i]==0 ){
162851          const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
162852          sqlite3_tokenizer_cursor *pTC = 0;
162853  
162854          rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
162855          while( rc==SQLITE_OK ){
162856            char const *zToken;       /* Buffer containing token */
162857            int nToken = 0;           /* Number of bytes in token */
162858            int iDum1 = 0, iDum2 = 0; /* Dummy variables */
162859            int iPos = 0;             /* Position of token in zText */
162860  
162861            rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
162862            for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
162863              Fts3PhraseToken *pPT = pDef->pToken;
162864              if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
162865                  && (pPT->bFirst==0 || iPos==0)
162866                  && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
162867                  && (0==memcmp(zToken, pPT->z, pPT->n))
162868                ){
162869                fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
162870              }
162871            }
162872          }
162873          if( pTC ) pModule->xClose(pTC);
162874          if( rc==SQLITE_DONE ) rc = SQLITE_OK;
162875        }
162876      }
162877  
162878      for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
162879        if( pDef->pList ){
162880          rc = fts3PendingListAppendVarint(&pDef->pList, 0);
162881        }
162882      }
162883    }
162884  
162885    return rc;
162886  }
162887  
162888  SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
162889    Fts3DeferredToken *p, 
162890    char **ppData, 
162891    int *pnData
162892  ){
162893    char *pRet;
162894    int nSkip;
162895    sqlite3_int64 dummy;
162896  
162897    *ppData = 0;
162898    *pnData = 0;
162899  
162900    if( p->pList==0 ){
162901      return SQLITE_OK;
162902    }
162903  
162904    pRet = (char *)sqlite3_malloc(p->pList->nData);
162905    if( !pRet ) return SQLITE_NOMEM;
162906  
162907    nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
162908    *pnData = p->pList->nData - nSkip;
162909    *ppData = pRet;
162910    
162911    memcpy(pRet, &p->pList->aData[nSkip], *pnData);
162912    return SQLITE_OK;
162913  }
162914  
162915  /*
162916  ** Add an entry for token pToken to the pCsr->pDeferred list.
162917  */
162918  SQLITE_PRIVATE int sqlite3Fts3DeferToken(
162919    Fts3Cursor *pCsr,               /* Fts3 table cursor */
162920    Fts3PhraseToken *pToken,        /* Token to defer */
162921    int iCol                        /* Column that token must appear in (or -1) */
162922  ){
162923    Fts3DeferredToken *pDeferred;
162924    pDeferred = sqlite3_malloc(sizeof(*pDeferred));
162925    if( !pDeferred ){
162926      return SQLITE_NOMEM;
162927    }
162928    memset(pDeferred, 0, sizeof(*pDeferred));
162929    pDeferred->pToken = pToken;
162930    pDeferred->pNext = pCsr->pDeferred; 
162931    pDeferred->iCol = iCol;
162932    pCsr->pDeferred = pDeferred;
162933  
162934    assert( pToken->pDeferred==0 );
162935    pToken->pDeferred = pDeferred;
162936  
162937    return SQLITE_OK;
162938  }
162939  #endif
162940  
162941  /*
162942  ** SQLite value pRowid contains the rowid of a row that may or may not be
162943  ** present in the FTS3 table. If it is, delete it and adjust the contents
162944  ** of subsiduary data structures accordingly.
162945  */
162946  static int fts3DeleteByRowid(
162947    Fts3Table *p, 
162948    sqlite3_value *pRowid, 
162949    int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
162950    u32 *aSzDel
162951  ){
162952    int rc = SQLITE_OK;             /* Return code */
162953    int bFound = 0;                 /* True if *pRowid really is in the table */
162954  
162955    fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
162956    if( bFound && rc==SQLITE_OK ){
162957      int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
162958      rc = fts3IsEmpty(p, pRowid, &isEmpty);
162959      if( rc==SQLITE_OK ){
162960        if( isEmpty ){
162961          /* Deleting this row means the whole table is empty. In this case
162962          ** delete the contents of all three tables and throw away any
162963          ** data in the pendingTerms hash table.  */
162964          rc = fts3DeleteAll(p, 1);
162965          *pnChng = 0;
162966          memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
162967        }else{
162968          *pnChng = *pnChng - 1;
162969          if( p->zContentTbl==0 ){
162970            fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
162971          }
162972          if( p->bHasDocsize ){
162973            fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
162974          }
162975        }
162976      }
162977    }
162978  
162979    return rc;
162980  }
162981  
162982  /*
162983  ** This function does the work for the xUpdate method of FTS3 virtual
162984  ** tables. The schema of the virtual table being:
162985  **
162986  **     CREATE TABLE <table name>( 
162987  **       <user columns>,
162988  **       <table name> HIDDEN, 
162989  **       docid HIDDEN, 
162990  **       <langid> HIDDEN
162991  **     );
162992  **
162993  ** 
162994  */
162995  SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
162996    sqlite3_vtab *pVtab,            /* FTS3 vtab object */
162997    int nArg,                       /* Size of argument array */
162998    sqlite3_value **apVal,          /* Array of arguments */
162999    sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
163000  ){
163001    Fts3Table *p = (Fts3Table *)pVtab;
163002    int rc = SQLITE_OK;             /* Return Code */
163003    int isRemove = 0;               /* True for an UPDATE or DELETE */
163004    u32 *aSzIns = 0;                /* Sizes of inserted documents */
163005    u32 *aSzDel = 0;                /* Sizes of deleted documents */
163006    int nChng = 0;                  /* Net change in number of documents */
163007    int bInsertDone = 0;
163008  
163009    /* At this point it must be known if the %_stat table exists or not.
163010    ** So bHasStat may not be 2.  */
163011    assert( p->bHasStat==0 || p->bHasStat==1 );
163012  
163013    assert( p->pSegments==0 );
163014    assert( 
163015        nArg==1                     /* DELETE operations */
163016     || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
163017    );
163018  
163019    /* Check for a "special" INSERT operation. One of the form:
163020    **
163021    **   INSERT INTO xyz(xyz) VALUES('command');
163022    */
163023    if( nArg>1 
163024     && sqlite3_value_type(apVal[0])==SQLITE_NULL 
163025     && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL 
163026    ){
163027      rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
163028      goto update_out;
163029    }
163030  
163031    if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
163032      rc = SQLITE_CONSTRAINT;
163033      goto update_out;
163034    }
163035  
163036    /* Allocate space to hold the change in document sizes */
163037    aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
163038    if( aSzDel==0 ){
163039      rc = SQLITE_NOMEM;
163040      goto update_out;
163041    }
163042    aSzIns = &aSzDel[p->nColumn+1];
163043    memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
163044  
163045    rc = fts3Writelock(p);
163046    if( rc!=SQLITE_OK ) goto update_out;
163047  
163048    /* If this is an INSERT operation, or an UPDATE that modifies the rowid
163049    ** value, then this operation requires constraint handling.
163050    **
163051    ** If the on-conflict mode is REPLACE, this means that the existing row
163052    ** should be deleted from the database before inserting the new row. Or,
163053    ** if the on-conflict mode is other than REPLACE, then this method must
163054    ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
163055    ** modify the database file.
163056    */
163057    if( nArg>1 && p->zContentTbl==0 ){
163058      /* Find the value object that holds the new rowid value. */
163059      sqlite3_value *pNewRowid = apVal[3+p->nColumn];
163060      if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
163061        pNewRowid = apVal[1];
163062      }
163063  
163064      if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && ( 
163065          sqlite3_value_type(apVal[0])==SQLITE_NULL
163066       || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
163067      )){
163068        /* The new rowid is not NULL (in this case the rowid will be
163069        ** automatically assigned and there is no chance of a conflict), and 
163070        ** the statement is either an INSERT or an UPDATE that modifies the
163071        ** rowid column. So if the conflict mode is REPLACE, then delete any
163072        ** existing row with rowid=pNewRowid. 
163073        **
163074        ** Or, if the conflict mode is not REPLACE, insert the new record into 
163075        ** the %_content table. If we hit the duplicate rowid constraint (or any
163076        ** other error) while doing so, return immediately.
163077        **
163078        ** This branch may also run if pNewRowid contains a value that cannot
163079        ** be losslessly converted to an integer. In this case, the eventual 
163080        ** call to fts3InsertData() (either just below or further on in this
163081        ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is 
163082        ** invoked, it will delete zero rows (since no row will have
163083        ** docid=$pNewRowid if $pNewRowid is not an integer value).
163084        */
163085        if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
163086          rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
163087        }else{
163088          rc = fts3InsertData(p, apVal, pRowid);
163089          bInsertDone = 1;
163090        }
163091      }
163092    }
163093    if( rc!=SQLITE_OK ){
163094      goto update_out;
163095    }
163096  
163097    /* If this is a DELETE or UPDATE operation, remove the old record. */
163098    if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
163099      assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
163100      rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
163101      isRemove = 1;
163102    }
163103    
163104    /* If this is an INSERT or UPDATE operation, insert the new record. */
163105    if( nArg>1 && rc==SQLITE_OK ){
163106      int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
163107      if( bInsertDone==0 ){
163108        rc = fts3InsertData(p, apVal, pRowid);
163109        if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
163110          rc = FTS_CORRUPT_VTAB;
163111        }
163112      }
163113      if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
163114        rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
163115      }
163116      if( rc==SQLITE_OK ){
163117        assert( p->iPrevDocid==*pRowid );
163118        rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
163119      }
163120      if( p->bHasDocsize ){
163121        fts3InsertDocsize(&rc, p, aSzIns);
163122      }
163123      nChng++;
163124    }
163125  
163126    if( p->bFts4 ){
163127      fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
163128    }
163129  
163130   update_out:
163131    sqlite3_free(aSzDel);
163132    sqlite3Fts3SegmentsClose(p);
163133    return rc;
163134  }
163135  
163136  /* 
163137  ** Flush any data in the pending-terms hash table to disk. If successful,
163138  ** merge all segments in the database (including the new segment, if 
163139  ** there was any data to flush) into a single segment. 
163140  */
163141  SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
163142    int rc;
163143    rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
163144    if( rc==SQLITE_OK ){
163145      rc = fts3DoOptimize(p, 1);
163146      if( rc==SQLITE_OK || rc==SQLITE_DONE ){
163147        int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
163148        if( rc2!=SQLITE_OK ) rc = rc2;
163149      }else{
163150        sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
163151        sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
163152      }
163153    }
163154    sqlite3Fts3SegmentsClose(p);
163155    return rc;
163156  }
163157  
163158  #endif
163159  
163160  /************** End of fts3_write.c ******************************************/
163161  /************** Begin file fts3_snippet.c ************************************/
163162  /*
163163  ** 2009 Oct 23
163164  **
163165  ** The author disclaims copyright to this source code.  In place of
163166  ** a legal notice, here is a blessing:
163167  **
163168  **    May you do good and not evil.
163169  **    May you find forgiveness for yourself and forgive others.
163170  **    May you share freely, never taking more than you give.
163171  **
163172  ******************************************************************************
163173  */
163174  
163175  /* #include "fts3Int.h" */
163176  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
163177  
163178  /* #include <string.h> */
163179  /* #include <assert.h> */
163180  
163181  /*
163182  ** Characters that may appear in the second argument to matchinfo().
163183  */
163184  #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
163185  #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
163186  #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
163187  #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
163188  #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
163189  #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
163190  #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
163191  #define FTS3_MATCHINFO_LHITS     'y'        /* nCol*nPhrase values */
163192  #define FTS3_MATCHINFO_LHITS_BM  'b'        /* nCol*nPhrase values */
163193  
163194  /*
163195  ** The default value for the second argument to matchinfo(). 
163196  */
163197  #define FTS3_MATCHINFO_DEFAULT   "pcx"
163198  
163199  
163200  /*
163201  ** Used as an fts3ExprIterate() context when loading phrase doclists to
163202  ** Fts3Expr.aDoclist[]/nDoclist.
163203  */
163204  typedef struct LoadDoclistCtx LoadDoclistCtx;
163205  struct LoadDoclistCtx {
163206    Fts3Cursor *pCsr;               /* FTS3 Cursor */
163207    int nPhrase;                    /* Number of phrases seen so far */
163208    int nToken;                     /* Number of tokens seen so far */
163209  };
163210  
163211  /*
163212  ** The following types are used as part of the implementation of the 
163213  ** fts3BestSnippet() routine.
163214  */
163215  typedef struct SnippetIter SnippetIter;
163216  typedef struct SnippetPhrase SnippetPhrase;
163217  typedef struct SnippetFragment SnippetFragment;
163218  
163219  struct SnippetIter {
163220    Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
163221    int iCol;                       /* Extract snippet from this column */
163222    int nSnippet;                   /* Requested snippet length (in tokens) */
163223    int nPhrase;                    /* Number of phrases in query */
163224    SnippetPhrase *aPhrase;         /* Array of size nPhrase */
163225    int iCurrent;                   /* First token of current snippet */
163226  };
163227  
163228  struct SnippetPhrase {
163229    int nToken;                     /* Number of tokens in phrase */
163230    char *pList;                    /* Pointer to start of phrase position list */
163231    int iHead;                      /* Next value in position list */
163232    char *pHead;                    /* Position list data following iHead */
163233    int iTail;                      /* Next value in trailing position list */
163234    char *pTail;                    /* Position list data following iTail */
163235  };
163236  
163237  struct SnippetFragment {
163238    int iCol;                       /* Column snippet is extracted from */
163239    int iPos;                       /* Index of first token in snippet */
163240    u64 covered;                    /* Mask of query phrases covered */
163241    u64 hlmask;                     /* Mask of snippet terms to highlight */
163242  };
163243  
163244  /*
163245  ** This type is used as an fts3ExprIterate() context object while 
163246  ** accumulating the data returned by the matchinfo() function.
163247  */
163248  typedef struct MatchInfo MatchInfo;
163249  struct MatchInfo {
163250    Fts3Cursor *pCursor;            /* FTS3 Cursor */
163251    int nCol;                       /* Number of columns in table */
163252    int nPhrase;                    /* Number of matchable phrases in query */
163253    sqlite3_int64 nDoc;             /* Number of docs in database */
163254    char flag;
163255    u32 *aMatchinfo;                /* Pre-allocated buffer */
163256  };
163257  
163258  /*
163259  ** An instance of this structure is used to manage a pair of buffers, each
163260  ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
163261  ** for details.
163262  */
163263  struct MatchinfoBuffer {
163264    u8 aRef[3];
163265    int nElem;
163266    int bGlobal;                    /* Set if global data is loaded */
163267    char *zMatchinfo;
163268    u32 aMatchinfo[1];
163269  };
163270  
163271  
163272  /*
163273  ** The snippet() and offsets() functions both return text values. An instance
163274  ** of the following structure is used to accumulate those values while the
163275  ** functions are running. See fts3StringAppend() for details.
163276  */
163277  typedef struct StrBuffer StrBuffer;
163278  struct StrBuffer {
163279    char *z;                        /* Pointer to buffer containing string */
163280    int n;                          /* Length of z in bytes (excl. nul-term) */
163281    int nAlloc;                     /* Allocated size of buffer z in bytes */
163282  };
163283  
163284  
163285  /*************************************************************************
163286  ** Start of MatchinfoBuffer code.
163287  */
163288  
163289  /*
163290  ** Allocate a two-slot MatchinfoBuffer object.
163291  */
163292  static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
163293    MatchinfoBuffer *pRet;
163294    int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
163295    int nStr = (int)strlen(zMatchinfo);
163296  
163297    pRet = sqlite3_malloc(nByte + nStr+1);
163298    if( pRet ){
163299      memset(pRet, 0, nByte);
163300      pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
163301      pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
163302      pRet->nElem = nElem;
163303      pRet->zMatchinfo = ((char*)pRet) + nByte;
163304      memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
163305      pRet->aRef[0] = 1;
163306    }
163307  
163308    return pRet;
163309  }
163310  
163311  static void fts3MIBufferFree(void *p){
163312    MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
163313  
163314    assert( (u32*)p==&pBuf->aMatchinfo[1] 
163315         || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2] 
163316    );
163317    if( (u32*)p==&pBuf->aMatchinfo[1] ){
163318      pBuf->aRef[1] = 0;
163319    }else{
163320      pBuf->aRef[2] = 0;
163321    }
163322  
163323    if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
163324      sqlite3_free(pBuf);
163325    }
163326  }
163327  
163328  static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
163329    void (*xRet)(void*) = 0;
163330    u32 *aOut = 0;
163331  
163332    if( p->aRef[1]==0 ){
163333      p->aRef[1] = 1;
163334      aOut = &p->aMatchinfo[1];
163335      xRet = fts3MIBufferFree;
163336    }
163337    else if( p->aRef[2]==0 ){
163338      p->aRef[2] = 1;
163339      aOut = &p->aMatchinfo[p->nElem+2];
163340      xRet = fts3MIBufferFree;
163341    }else{
163342      aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
163343      if( aOut ){
163344        xRet = sqlite3_free;
163345        if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
163346      }
163347    }
163348  
163349    *paOut = aOut;
163350    return xRet;
163351  }
163352  
163353  static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
163354    p->bGlobal = 1;
163355    memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
163356  }
163357  
163358  /*
163359  ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
163360  */
163361  SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
163362    if( p ){
163363      assert( p->aRef[0]==1 );
163364      p->aRef[0] = 0;
163365      if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
163366        sqlite3_free(p);
163367      }
163368    }
163369  }
163370  
163371  /* 
163372  ** End of MatchinfoBuffer code.
163373  *************************************************************************/
163374  
163375  
163376  /*
163377  ** This function is used to help iterate through a position-list. A position
163378  ** list is a list of unique integers, sorted from smallest to largest. Each
163379  ** element of the list is represented by an FTS3 varint that takes the value
163380  ** of the difference between the current element and the previous one plus
163381  ** two. For example, to store the position-list:
163382  **
163383  **     4 9 113
163384  **
163385  ** the three varints:
163386  **
163387  **     6 7 106
163388  **
163389  ** are encoded.
163390  **
163391  ** When this function is called, *pp points to the start of an element of
163392  ** the list. *piPos contains the value of the previous entry in the list.
163393  ** After it returns, *piPos contains the value of the next element of the
163394  ** list and *pp is advanced to the following varint.
163395  */
163396  static void fts3GetDeltaPosition(char **pp, int *piPos){
163397    int iVal;
163398    *pp += fts3GetVarint32(*pp, &iVal);
163399    *piPos += (iVal-2);
163400  }
163401  
163402  /*
163403  ** Helper function for fts3ExprIterate() (see below).
163404  */
163405  static int fts3ExprIterate2(
163406    Fts3Expr *pExpr,                /* Expression to iterate phrases of */
163407    int *piPhrase,                  /* Pointer to phrase counter */
163408    int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
163409    void *pCtx                      /* Second argument to pass to callback */
163410  ){
163411    int rc;                         /* Return code */
163412    int eType = pExpr->eType;     /* Type of expression node pExpr */
163413  
163414    if( eType!=FTSQUERY_PHRASE ){
163415      assert( pExpr->pLeft && pExpr->pRight );
163416      rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
163417      if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
163418        rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
163419      }
163420    }else{
163421      rc = x(pExpr, *piPhrase, pCtx);
163422      (*piPhrase)++;
163423    }
163424    return rc;
163425  }
163426  
163427  /*
163428  ** Iterate through all phrase nodes in an FTS3 query, except those that
163429  ** are part of a sub-tree that is the right-hand-side of a NOT operator.
163430  ** For each phrase node found, the supplied callback function is invoked.
163431  **
163432  ** If the callback function returns anything other than SQLITE_OK, 
163433  ** the iteration is abandoned and the error code returned immediately.
163434  ** Otherwise, SQLITE_OK is returned after a callback has been made for
163435  ** all eligible phrase nodes.
163436  */
163437  static int fts3ExprIterate(
163438    Fts3Expr *pExpr,                /* Expression to iterate phrases of */
163439    int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
163440    void *pCtx                      /* Second argument to pass to callback */
163441  ){
163442    int iPhrase = 0;                /* Variable used as the phrase counter */
163443    return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
163444  }
163445  
163446  
163447  /*
163448  ** This is an fts3ExprIterate() callback used while loading the doclists
163449  ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
163450  ** fts3ExprLoadDoclists().
163451  */
163452  static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
163453    int rc = SQLITE_OK;
163454    Fts3Phrase *pPhrase = pExpr->pPhrase;
163455    LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
163456  
163457    UNUSED_PARAMETER(iPhrase);
163458  
163459    p->nPhrase++;
163460    p->nToken += pPhrase->nToken;
163461  
163462    return rc;
163463  }
163464  
163465  /*
163466  ** Load the doclists for each phrase in the query associated with FTS3 cursor
163467  ** pCsr. 
163468  **
163469  ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
163470  ** phrases in the expression (all phrases except those directly or 
163471  ** indirectly descended from the right-hand-side of a NOT operator). If 
163472  ** pnToken is not NULL, then it is set to the number of tokens in all
163473  ** matchable phrases of the expression.
163474  */
163475  static int fts3ExprLoadDoclists(
163476    Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
163477    int *pnPhrase,                  /* OUT: Number of phrases in query */
163478    int *pnToken                    /* OUT: Number of tokens in query */
163479  ){
163480    int rc;                         /* Return Code */
163481    LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
163482    sCtx.pCsr = pCsr;
163483    rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
163484    if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
163485    if( pnToken ) *pnToken = sCtx.nToken;
163486    return rc;
163487  }
163488  
163489  static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
163490    (*(int *)ctx)++;
163491    pExpr->iPhrase = iPhrase;
163492    return SQLITE_OK;
163493  }
163494  static int fts3ExprPhraseCount(Fts3Expr *pExpr){
163495    int nPhrase = 0;
163496    (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
163497    return nPhrase;
163498  }
163499  
163500  /*
163501  ** Advance the position list iterator specified by the first two 
163502  ** arguments so that it points to the first element with a value greater
163503  ** than or equal to parameter iNext.
163504  */
163505  static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
163506    char *pIter = *ppIter;
163507    if( pIter ){
163508      int iIter = *piIter;
163509  
163510      while( iIter<iNext ){
163511        if( 0==(*pIter & 0xFE) ){
163512          iIter = -1;
163513          pIter = 0;
163514          break;
163515        }
163516        fts3GetDeltaPosition(&pIter, &iIter);
163517      }
163518  
163519      *piIter = iIter;
163520      *ppIter = pIter;
163521    }
163522  }
163523  
163524  /*
163525  ** Advance the snippet iterator to the next candidate snippet.
163526  */
163527  static int fts3SnippetNextCandidate(SnippetIter *pIter){
163528    int i;                          /* Loop counter */
163529  
163530    if( pIter->iCurrent<0 ){
163531      /* The SnippetIter object has just been initialized. The first snippet
163532      ** candidate always starts at offset 0 (even if this candidate has a
163533      ** score of 0.0).
163534      */
163535      pIter->iCurrent = 0;
163536  
163537      /* Advance the 'head' iterator of each phrase to the first offset that
163538      ** is greater than or equal to (iNext+nSnippet).
163539      */
163540      for(i=0; i<pIter->nPhrase; i++){
163541        SnippetPhrase *pPhrase = &pIter->aPhrase[i];
163542        fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
163543      }
163544    }else{
163545      int iStart;
163546      int iEnd = 0x7FFFFFFF;
163547  
163548      for(i=0; i<pIter->nPhrase; i++){
163549        SnippetPhrase *pPhrase = &pIter->aPhrase[i];
163550        if( pPhrase->pHead && pPhrase->iHead<iEnd ){
163551          iEnd = pPhrase->iHead;
163552        }
163553      }
163554      if( iEnd==0x7FFFFFFF ){
163555        return 1;
163556      }
163557  
163558      pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
163559      for(i=0; i<pIter->nPhrase; i++){
163560        SnippetPhrase *pPhrase = &pIter->aPhrase[i];
163561        fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
163562        fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
163563      }
163564    }
163565  
163566    return 0;
163567  }
163568  
163569  /*
163570  ** Retrieve information about the current candidate snippet of snippet 
163571  ** iterator pIter.
163572  */
163573  static void fts3SnippetDetails(
163574    SnippetIter *pIter,             /* Snippet iterator */
163575    u64 mCovered,                   /* Bitmask of phrases already covered */
163576    int *piToken,                   /* OUT: First token of proposed snippet */
163577    int *piScore,                   /* OUT: "Score" for this snippet */
163578    u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
163579    u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
163580  ){
163581    int iStart = pIter->iCurrent;   /* First token of snippet */
163582    int iScore = 0;                 /* Score of this snippet */
163583    int i;                          /* Loop counter */
163584    u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
163585    u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
163586  
163587    for(i=0; i<pIter->nPhrase; i++){
163588      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
163589      if( pPhrase->pTail ){
163590        char *pCsr = pPhrase->pTail;
163591        int iCsr = pPhrase->iTail;
163592  
163593        while( iCsr<(iStart+pIter->nSnippet) ){
163594          int j;
163595          u64 mPhrase = (u64)1 << i;
163596          u64 mPos = (u64)1 << (iCsr - iStart);
163597          assert( iCsr>=iStart );
163598          if( (mCover|mCovered)&mPhrase ){
163599            iScore++;
163600          }else{
163601            iScore += 1000;
163602          }
163603          mCover |= mPhrase;
163604  
163605          for(j=0; j<pPhrase->nToken; j++){
163606            mHighlight |= (mPos>>j);
163607          }
163608  
163609          if( 0==(*pCsr & 0x0FE) ) break;
163610          fts3GetDeltaPosition(&pCsr, &iCsr);
163611        }
163612      }
163613    }
163614  
163615    /* Set the output variables before returning. */
163616    *piToken = iStart;
163617    *piScore = iScore;
163618    *pmCover = mCover;
163619    *pmHighlight = mHighlight;
163620  }
163621  
163622  /*
163623  ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
163624  ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
163625  */
163626  static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
163627    SnippetIter *p = (SnippetIter *)ctx;
163628    SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
163629    char *pCsr;
163630    int rc;
163631  
163632    pPhrase->nToken = pExpr->pPhrase->nToken;
163633    rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
163634    assert( rc==SQLITE_OK || pCsr==0 );
163635    if( pCsr ){
163636      int iFirst = 0;
163637      pPhrase->pList = pCsr;
163638      fts3GetDeltaPosition(&pCsr, &iFirst);
163639      assert( iFirst>=0 );
163640      pPhrase->pHead = pCsr;
163641      pPhrase->pTail = pCsr;
163642      pPhrase->iHead = iFirst;
163643      pPhrase->iTail = iFirst;
163644    }else{
163645      assert( rc!=SQLITE_OK || (
163646         pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 
163647      ));
163648    }
163649  
163650    return rc;
163651  }
163652  
163653  /*
163654  ** Select the fragment of text consisting of nFragment contiguous tokens 
163655  ** from column iCol that represent the "best" snippet. The best snippet
163656  ** is the snippet with the highest score, where scores are calculated
163657  ** by adding:
163658  **
163659  **   (a) +1 point for each occurrence of a matchable phrase in the snippet.
163660  **
163661  **   (b) +1000 points for the first occurrence of each matchable phrase in 
163662  **       the snippet for which the corresponding mCovered bit is not set.
163663  **
163664  ** The selected snippet parameters are stored in structure *pFragment before
163665  ** returning. The score of the selected snippet is stored in *piScore
163666  ** before returning.
163667  */
163668  static int fts3BestSnippet(
163669    int nSnippet,                   /* Desired snippet length */
163670    Fts3Cursor *pCsr,               /* Cursor to create snippet for */
163671    int iCol,                       /* Index of column to create snippet from */
163672    u64 mCovered,                   /* Mask of phrases already covered */
163673    u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
163674    SnippetFragment *pFragment,     /* OUT: Best snippet found */
163675    int *piScore                    /* OUT: Score of snippet pFragment */
163676  ){
163677    int rc;                         /* Return Code */
163678    int nList;                      /* Number of phrases in expression */
163679    SnippetIter sIter;              /* Iterates through snippet candidates */
163680    int nByte;                      /* Number of bytes of space to allocate */
163681    int iBestScore = -1;            /* Best snippet score found so far */
163682    int i;                          /* Loop counter */
163683  
163684    memset(&sIter, 0, sizeof(sIter));
163685  
163686    /* Iterate through the phrases in the expression to count them. The same
163687    ** callback makes sure the doclists are loaded for each phrase.
163688    */
163689    rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
163690    if( rc!=SQLITE_OK ){
163691      return rc;
163692    }
163693  
163694    /* Now that it is known how many phrases there are, allocate and zero
163695    ** the required space using malloc().
163696    */
163697    nByte = sizeof(SnippetPhrase) * nList;
163698    sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
163699    if( !sIter.aPhrase ){
163700      return SQLITE_NOMEM;
163701    }
163702    memset(sIter.aPhrase, 0, nByte);
163703  
163704    /* Initialize the contents of the SnippetIter object. Then iterate through
163705    ** the set of phrases in the expression to populate the aPhrase[] array.
163706    */
163707    sIter.pCsr = pCsr;
163708    sIter.iCol = iCol;
163709    sIter.nSnippet = nSnippet;
163710    sIter.nPhrase = nList;
163711    sIter.iCurrent = -1;
163712    rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
163713    if( rc==SQLITE_OK ){
163714  
163715      /* Set the *pmSeen output variable. */
163716      for(i=0; i<nList; i++){
163717        if( sIter.aPhrase[i].pHead ){
163718          *pmSeen |= (u64)1 << i;
163719        }
163720      }
163721  
163722      /* Loop through all candidate snippets. Store the best snippet in 
163723       ** *pFragment. Store its associated 'score' in iBestScore.
163724       */
163725      pFragment->iCol = iCol;
163726      while( !fts3SnippetNextCandidate(&sIter) ){
163727        int iPos;
163728        int iScore;
163729        u64 mCover;
163730        u64 mHighlite;
163731        fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
163732        assert( iScore>=0 );
163733        if( iScore>iBestScore ){
163734          pFragment->iPos = iPos;
163735          pFragment->hlmask = mHighlite;
163736          pFragment->covered = mCover;
163737          iBestScore = iScore;
163738        }
163739      }
163740  
163741      *piScore = iBestScore;
163742    }
163743    sqlite3_free(sIter.aPhrase);
163744    return rc;
163745  }
163746  
163747  
163748  /*
163749  ** Append a string to the string-buffer passed as the first argument.
163750  **
163751  ** If nAppend is negative, then the length of the string zAppend is
163752  ** determined using strlen().
163753  */
163754  static int fts3StringAppend(
163755    StrBuffer *pStr,                /* Buffer to append to */
163756    const char *zAppend,            /* Pointer to data to append to buffer */
163757    int nAppend                     /* Size of zAppend in bytes (or -1) */
163758  ){
163759    if( nAppend<0 ){
163760      nAppend = (int)strlen(zAppend);
163761    }
163762  
163763    /* If there is insufficient space allocated at StrBuffer.z, use realloc()
163764    ** to grow the buffer until so that it is big enough to accomadate the
163765    ** appended data.
163766    */
163767    if( pStr->n+nAppend+1>=pStr->nAlloc ){
163768      int nAlloc = pStr->nAlloc+nAppend+100;
163769      char *zNew = sqlite3_realloc(pStr->z, nAlloc);
163770      if( !zNew ){
163771        return SQLITE_NOMEM;
163772      }
163773      pStr->z = zNew;
163774      pStr->nAlloc = nAlloc;
163775    }
163776    assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
163777  
163778    /* Append the data to the string buffer. */
163779    memcpy(&pStr->z[pStr->n], zAppend, nAppend);
163780    pStr->n += nAppend;
163781    pStr->z[pStr->n] = '\0';
163782  
163783    return SQLITE_OK;
163784  }
163785  
163786  /*
163787  ** The fts3BestSnippet() function often selects snippets that end with a
163788  ** query term. That is, the final term of the snippet is always a term
163789  ** that requires highlighting. For example, if 'X' is a highlighted term
163790  ** and '.' is a non-highlighted term, BestSnippet() may select:
163791  **
163792  **     ........X.....X
163793  **
163794  ** This function "shifts" the beginning of the snippet forward in the 
163795  ** document so that there are approximately the same number of 
163796  ** non-highlighted terms to the right of the final highlighted term as there
163797  ** are to the left of the first highlighted term. For example, to this:
163798  **
163799  **     ....X.....X....
163800  **
163801  ** This is done as part of extracting the snippet text, not when selecting
163802  ** the snippet. Snippet selection is done based on doclists only, so there
163803  ** is no way for fts3BestSnippet() to know whether or not the document 
163804  ** actually contains terms that follow the final highlighted term. 
163805  */
163806  static int fts3SnippetShift(
163807    Fts3Table *pTab,                /* FTS3 table snippet comes from */
163808    int iLangid,                    /* Language id to use in tokenizing */
163809    int nSnippet,                   /* Number of tokens desired for snippet */
163810    const char *zDoc,               /* Document text to extract snippet from */
163811    int nDoc,                       /* Size of buffer zDoc in bytes */
163812    int *piPos,                     /* IN/OUT: First token of snippet */
163813    u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
163814  ){
163815    u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
163816  
163817    if( hlmask ){
163818      int nLeft;                    /* Tokens to the left of first highlight */
163819      int nRight;                   /* Tokens to the right of last highlight */
163820      int nDesired;                 /* Ideal number of tokens to shift forward */
163821  
163822      for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
163823      for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
163824      nDesired = (nLeft-nRight)/2;
163825  
163826      /* Ideally, the start of the snippet should be pushed forward in the
163827      ** document nDesired tokens. This block checks if there are actually
163828      ** nDesired tokens to the right of the snippet. If so, *piPos and
163829      ** *pHlMask are updated to shift the snippet nDesired tokens to the
163830      ** right. Otherwise, the snippet is shifted by the number of tokens
163831      ** available.
163832      */
163833      if( nDesired>0 ){
163834        int nShift;                 /* Number of tokens to shift snippet by */
163835        int iCurrent = 0;           /* Token counter */
163836        int rc;                     /* Return Code */
163837        sqlite3_tokenizer_module *pMod;
163838        sqlite3_tokenizer_cursor *pC;
163839        pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
163840  
163841        /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
163842        ** or more tokens in zDoc/nDoc.
163843        */
163844        rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
163845        if( rc!=SQLITE_OK ){
163846          return rc;
163847        }
163848        while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
163849          const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
163850          rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
163851        }
163852        pMod->xClose(pC);
163853        if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
163854  
163855        nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
163856        assert( nShift<=nDesired );
163857        if( nShift>0 ){
163858          *piPos += nShift;
163859          *pHlmask = hlmask >> nShift;
163860        }
163861      }
163862    }
163863    return SQLITE_OK;
163864  }
163865  
163866  /*
163867  ** Extract the snippet text for fragment pFragment from cursor pCsr and
163868  ** append it to string buffer pOut.
163869  */
163870  static int fts3SnippetText(
163871    Fts3Cursor *pCsr,               /* FTS3 Cursor */
163872    SnippetFragment *pFragment,     /* Snippet to extract */
163873    int iFragment,                  /* Fragment number */
163874    int isLast,                     /* True for final fragment in snippet */
163875    int nSnippet,                   /* Number of tokens in extracted snippet */
163876    const char *zOpen,              /* String inserted before highlighted term */
163877    const char *zClose,             /* String inserted after highlighted term */
163878    const char *zEllipsis,          /* String inserted between snippets */
163879    StrBuffer *pOut                 /* Write output here */
163880  ){
163881    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
163882    int rc;                         /* Return code */
163883    const char *zDoc;               /* Document text to extract snippet from */
163884    int nDoc;                       /* Size of zDoc in bytes */
163885    int iCurrent = 0;               /* Current token number of document */
163886    int iEnd = 0;                   /* Byte offset of end of current token */
163887    int isShiftDone = 0;            /* True after snippet is shifted */
163888    int iPos = pFragment->iPos;     /* First token of snippet */
163889    u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
163890    int iCol = pFragment->iCol+1;   /* Query column to extract text from */
163891    sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
163892    sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
163893    
163894    zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
163895    if( zDoc==0 ){
163896      if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
163897        return SQLITE_NOMEM;
163898      }
163899      return SQLITE_OK;
163900    }
163901    nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
163902  
163903    /* Open a token cursor on the document. */
163904    pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
163905    rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
163906    if( rc!=SQLITE_OK ){
163907      return rc;
163908    }
163909  
163910    while( rc==SQLITE_OK ){
163911      const char *ZDUMMY;           /* Dummy argument used with tokenizer */
163912      int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
163913      int iBegin = 0;               /* Offset in zDoc of start of token */
163914      int iFin = 0;                 /* Offset in zDoc of end of token */
163915      int isHighlight = 0;          /* True for highlighted terms */
163916  
163917      /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
163918      ** in the FTS code the variable that the third argument to xNext points to
163919      ** is initialized to zero before the first (*but not necessarily
163920      ** subsequent*) call to xNext(). This is done for a particular application
163921      ** that needs to know whether or not the tokenizer is being used for
163922      ** snippet generation or for some other purpose.
163923      **
163924      ** Extreme care is required when writing code to depend on this
163925      ** initialization. It is not a documented part of the tokenizer interface.
163926      ** If a tokenizer is used directly by any code outside of FTS, this
163927      ** convention might not be respected.  */
163928      rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
163929      if( rc!=SQLITE_OK ){
163930        if( rc==SQLITE_DONE ){
163931          /* Special case - the last token of the snippet is also the last token
163932          ** of the column. Append any punctuation that occurred between the end
163933          ** of the previous token and the end of the document to the output. 
163934          ** Then break out of the loop. */
163935          rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
163936        }
163937        break;
163938      }
163939      if( iCurrent<iPos ){ continue; }
163940  
163941      if( !isShiftDone ){
163942        int n = nDoc - iBegin;
163943        rc = fts3SnippetShift(
163944            pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
163945        );
163946        isShiftDone = 1;
163947  
163948        /* Now that the shift has been done, check if the initial "..." are
163949        ** required. They are required if (a) this is not the first fragment,
163950        ** or (b) this fragment does not begin at position 0 of its column. 
163951        */
163952        if( rc==SQLITE_OK ){
163953          if( iPos>0 || iFragment>0 ){
163954            rc = fts3StringAppend(pOut, zEllipsis, -1);
163955          }else if( iBegin ){
163956            rc = fts3StringAppend(pOut, zDoc, iBegin);
163957          }
163958        }
163959        if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
163960      }
163961  
163962      if( iCurrent>=(iPos+nSnippet) ){
163963        if( isLast ){
163964          rc = fts3StringAppend(pOut, zEllipsis, -1);
163965        }
163966        break;
163967      }
163968  
163969      /* Set isHighlight to true if this term should be highlighted. */
163970      isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
163971  
163972      if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
163973      if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
163974      if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
163975      if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
163976  
163977      iEnd = iFin;
163978    }
163979  
163980    pMod->xClose(pC);
163981    return rc;
163982  }
163983  
163984  
163985  /*
163986  ** This function is used to count the entries in a column-list (a 
163987  ** delta-encoded list of term offsets within a single column of a single 
163988  ** row). When this function is called, *ppCollist should point to the
163989  ** beginning of the first varint in the column-list (the varint that
163990  ** contains the position of the first matching term in the column data).
163991  ** Before returning, *ppCollist is set to point to the first byte after
163992  ** the last varint in the column-list (either the 0x00 signifying the end
163993  ** of the position-list, or the 0x01 that precedes the column number of
163994  ** the next column in the position-list).
163995  **
163996  ** The number of elements in the column-list is returned.
163997  */
163998  static int fts3ColumnlistCount(char **ppCollist){
163999    char *pEnd = *ppCollist;
164000    char c = 0;
164001    int nEntry = 0;
164002  
164003    /* A column-list is terminated by either a 0x01 or 0x00. */
164004    while( 0xFE & (*pEnd | c) ){
164005      c = *pEnd++ & 0x80;
164006      if( !c ) nEntry++;
164007    }
164008  
164009    *ppCollist = pEnd;
164010    return nEntry;
164011  }
164012  
164013  /*
164014  ** This function gathers 'y' or 'b' data for a single phrase.
164015  */
164016  static void fts3ExprLHits(
164017    Fts3Expr *pExpr,                /* Phrase expression node */
164018    MatchInfo *p                    /* Matchinfo context */
164019  ){
164020    Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
164021    int iStart;
164022    Fts3Phrase *pPhrase = pExpr->pPhrase;
164023    char *pIter = pPhrase->doclist.pList;
164024    int iCol = 0;
164025  
164026    assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
164027    if( p->flag==FTS3_MATCHINFO_LHITS ){
164028      iStart = pExpr->iPhrase * p->nCol;
164029    }else{
164030      iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
164031    }
164032  
164033    while( 1 ){
164034      int nHit = fts3ColumnlistCount(&pIter);
164035      if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
164036        if( p->flag==FTS3_MATCHINFO_LHITS ){
164037          p->aMatchinfo[iStart + iCol] = (u32)nHit;
164038        }else if( nHit ){
164039          p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
164040        }
164041      }
164042      assert( *pIter==0x00 || *pIter==0x01 );
164043      if( *pIter!=0x01 ) break;
164044      pIter++;
164045      pIter += fts3GetVarint32(pIter, &iCol);
164046    }
164047  }
164048  
164049  /*
164050  ** Gather the results for matchinfo directives 'y' and 'b'.
164051  */
164052  static void fts3ExprLHitGather(
164053    Fts3Expr *pExpr,
164054    MatchInfo *p
164055  ){
164056    assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
164057    if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
164058      if( pExpr->pLeft ){
164059        fts3ExprLHitGather(pExpr->pLeft, p);
164060        fts3ExprLHitGather(pExpr->pRight, p);
164061      }else{
164062        fts3ExprLHits(pExpr, p);
164063      }
164064    }
164065  }
164066  
164067  /*
164068  ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
164069  ** for a single query. 
164070  **
164071  ** fts3ExprIterate() callback to load the 'global' elements of a
164072  ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements 
164073  ** of the matchinfo array that are constant for all rows returned by the 
164074  ** current query.
164075  **
164076  ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
164077  ** function populates Matchinfo.aMatchinfo[] as follows:
164078  **
164079  **   for(iCol=0; iCol<nCol; iCol++){
164080  **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
164081  **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
164082  **   }
164083  **
164084  ** where X is the number of matches for phrase iPhrase is column iCol of all
164085  ** rows of the table. Y is the number of rows for which column iCol contains
164086  ** at least one instance of phrase iPhrase.
164087  **
164088  ** If the phrase pExpr consists entirely of deferred tokens, then all X and
164089  ** Y values are set to nDoc, where nDoc is the number of documents in the 
164090  ** file system. This is done because the full-text index doclist is required
164091  ** to calculate these values properly, and the full-text index doclist is
164092  ** not available for deferred tokens.
164093  */
164094  static int fts3ExprGlobalHitsCb(
164095    Fts3Expr *pExpr,                /* Phrase expression node */
164096    int iPhrase,                    /* Phrase number (numbered from zero) */
164097    void *pCtx                      /* Pointer to MatchInfo structure */
164098  ){
164099    MatchInfo *p = (MatchInfo *)pCtx;
164100    return sqlite3Fts3EvalPhraseStats(
164101        p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
164102    );
164103  }
164104  
164105  /*
164106  ** fts3ExprIterate() callback used to collect the "local" part of the
164107  ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the 
164108  ** array that are different for each row returned by the query.
164109  */
164110  static int fts3ExprLocalHitsCb(
164111    Fts3Expr *pExpr,                /* Phrase expression node */
164112    int iPhrase,                    /* Phrase number */
164113    void *pCtx                      /* Pointer to MatchInfo structure */
164114  ){
164115    int rc = SQLITE_OK;
164116    MatchInfo *p = (MatchInfo *)pCtx;
164117    int iStart = iPhrase * p->nCol * 3;
164118    int i;
164119  
164120    for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
164121      char *pCsr;
164122      rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
164123      if( pCsr ){
164124        p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
164125      }else{
164126        p->aMatchinfo[iStart+i*3] = 0;
164127      }
164128    }
164129  
164130    return rc;
164131  }
164132  
164133  static int fts3MatchinfoCheck(
164134    Fts3Table *pTab, 
164135    char cArg,
164136    char **pzErr
164137  ){
164138    if( (cArg==FTS3_MATCHINFO_NPHRASE)
164139     || (cArg==FTS3_MATCHINFO_NCOL)
164140     || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
164141     || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
164142     || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
164143     || (cArg==FTS3_MATCHINFO_LCS)
164144     || (cArg==FTS3_MATCHINFO_HITS)
164145     || (cArg==FTS3_MATCHINFO_LHITS)
164146     || (cArg==FTS3_MATCHINFO_LHITS_BM)
164147    ){
164148      return SQLITE_OK;
164149    }
164150    sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
164151    return SQLITE_ERROR;
164152  }
164153  
164154  static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
164155    int nVal;                       /* Number of integers output by cArg */
164156  
164157    switch( cArg ){
164158      case FTS3_MATCHINFO_NDOC:
164159      case FTS3_MATCHINFO_NPHRASE: 
164160      case FTS3_MATCHINFO_NCOL: 
164161        nVal = 1;
164162        break;
164163  
164164      case FTS3_MATCHINFO_AVGLENGTH:
164165      case FTS3_MATCHINFO_LENGTH:
164166      case FTS3_MATCHINFO_LCS:
164167        nVal = pInfo->nCol;
164168        break;
164169  
164170      case FTS3_MATCHINFO_LHITS:
164171        nVal = pInfo->nCol * pInfo->nPhrase;
164172        break;
164173  
164174      case FTS3_MATCHINFO_LHITS_BM:
164175        nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
164176        break;
164177  
164178      default:
164179        assert( cArg==FTS3_MATCHINFO_HITS );
164180        nVal = pInfo->nCol * pInfo->nPhrase * 3;
164181        break;
164182    }
164183  
164184    return nVal;
164185  }
164186  
164187  static int fts3MatchinfoSelectDoctotal(
164188    Fts3Table *pTab,
164189    sqlite3_stmt **ppStmt,
164190    sqlite3_int64 *pnDoc,
164191    const char **paLen
164192  ){
164193    sqlite3_stmt *pStmt;
164194    const char *a;
164195    sqlite3_int64 nDoc;
164196  
164197    if( !*ppStmt ){
164198      int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
164199      if( rc!=SQLITE_OK ) return rc;
164200    }
164201    pStmt = *ppStmt;
164202    assert( sqlite3_data_count(pStmt)==1 );
164203  
164204    a = sqlite3_column_blob(pStmt, 0);
164205    a += sqlite3Fts3GetVarint(a, &nDoc);
164206    if( nDoc==0 ) return FTS_CORRUPT_VTAB;
164207    *pnDoc = (u32)nDoc;
164208  
164209    if( paLen ) *paLen = a;
164210    return SQLITE_OK;
164211  }
164212  
164213  /*
164214  ** An instance of the following structure is used to store state while 
164215  ** iterating through a multi-column position-list corresponding to the
164216  ** hits for a single phrase on a single row in order to calculate the
164217  ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
164218  */
164219  typedef struct LcsIterator LcsIterator;
164220  struct LcsIterator {
164221    Fts3Expr *pExpr;                /* Pointer to phrase expression */
164222    int iPosOffset;                 /* Tokens count up to end of this phrase */
164223    char *pRead;                    /* Cursor used to iterate through aDoclist */
164224    int iPos;                       /* Current position */
164225  };
164226  
164227  /* 
164228  ** If LcsIterator.iCol is set to the following value, the iterator has
164229  ** finished iterating through all offsets for all columns.
164230  */
164231  #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
164232  
164233  static int fts3MatchinfoLcsCb(
164234    Fts3Expr *pExpr,                /* Phrase expression node */
164235    int iPhrase,                    /* Phrase number (numbered from zero) */
164236    void *pCtx                      /* Pointer to MatchInfo structure */
164237  ){
164238    LcsIterator *aIter = (LcsIterator *)pCtx;
164239    aIter[iPhrase].pExpr = pExpr;
164240    return SQLITE_OK;
164241  }
164242  
164243  /*
164244  ** Advance the iterator passed as an argument to the next position. Return
164245  ** 1 if the iterator is at EOF or if it now points to the start of the
164246  ** position list for the next column.
164247  */
164248  static int fts3LcsIteratorAdvance(LcsIterator *pIter){
164249    char *pRead = pIter->pRead;
164250    sqlite3_int64 iRead;
164251    int rc = 0;
164252  
164253    pRead += sqlite3Fts3GetVarint(pRead, &iRead);
164254    if( iRead==0 || iRead==1 ){
164255      pRead = 0;
164256      rc = 1;
164257    }else{
164258      pIter->iPos += (int)(iRead-2);
164259    }
164260  
164261    pIter->pRead = pRead;
164262    return rc;
164263  }
164264    
164265  /*
164266  ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. 
164267  **
164268  ** If the call is successful, the longest-common-substring lengths for each
164269  ** column are written into the first nCol elements of the pInfo->aMatchinfo[] 
164270  ** array before returning. SQLITE_OK is returned in this case.
164271  **
164272  ** Otherwise, if an error occurs, an SQLite error code is returned and the
164273  ** data written to the first nCol elements of pInfo->aMatchinfo[] is 
164274  ** undefined.
164275  */
164276  static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
164277    LcsIterator *aIter;
164278    int i;
164279    int iCol;
164280    int nToken = 0;
164281  
164282    /* Allocate and populate the array of LcsIterator objects. The array
164283    ** contains one element for each matchable phrase in the query.
164284    **/
164285    aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
164286    if( !aIter ) return SQLITE_NOMEM;
164287    memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
164288    (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
164289  
164290    for(i=0; i<pInfo->nPhrase; i++){
164291      LcsIterator *pIter = &aIter[i];
164292      nToken -= pIter->pExpr->pPhrase->nToken;
164293      pIter->iPosOffset = nToken;
164294    }
164295  
164296    for(iCol=0; iCol<pInfo->nCol; iCol++){
164297      int nLcs = 0;                 /* LCS value for this column */
164298      int nLive = 0;                /* Number of iterators in aIter not at EOF */
164299  
164300      for(i=0; i<pInfo->nPhrase; i++){
164301        int rc;
164302        LcsIterator *pIt = &aIter[i];
164303        rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
164304        if( rc!=SQLITE_OK ) return rc;
164305        if( pIt->pRead ){
164306          pIt->iPos = pIt->iPosOffset;
164307          fts3LcsIteratorAdvance(&aIter[i]);
164308          nLive++;
164309        }
164310      }
164311  
164312      while( nLive>0 ){
164313        LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
164314        int nThisLcs = 0;           /* LCS for the current iterator positions */
164315  
164316        for(i=0; i<pInfo->nPhrase; i++){
164317          LcsIterator *pIter = &aIter[i];
164318          if( pIter->pRead==0 ){
164319            /* This iterator is already at EOF for this column. */
164320            nThisLcs = 0;
164321          }else{
164322            if( pAdv==0 || pIter->iPos<pAdv->iPos ){
164323              pAdv = pIter;
164324            }
164325            if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
164326              nThisLcs++;
164327            }else{
164328              nThisLcs = 1;
164329            }
164330            if( nThisLcs>nLcs ) nLcs = nThisLcs;
164331          }
164332        }
164333        if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
164334      }
164335  
164336      pInfo->aMatchinfo[iCol] = nLcs;
164337    }
164338  
164339    sqlite3_free(aIter);
164340    return SQLITE_OK;
164341  }
164342  
164343  /*
164344  ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
164345  ** be returned by the matchinfo() function. Argument zArg contains the 
164346  ** format string passed as the second argument to matchinfo (or the
164347  ** default value "pcx" if no second argument was specified). The format
164348  ** string has already been validated and the pInfo->aMatchinfo[] array
164349  ** is guaranteed to be large enough for the output.
164350  **
164351  ** If bGlobal is true, then populate all fields of the matchinfo() output.
164352  ** If it is false, then assume that those fields that do not change between
164353  ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
164354  ** have already been populated.
164355  **
164356  ** Return SQLITE_OK if successful, or an SQLite error code if an error 
164357  ** occurs. If a value other than SQLITE_OK is returned, the state the
164358  ** pInfo->aMatchinfo[] buffer is left in is undefined.
164359  */
164360  static int fts3MatchinfoValues(
164361    Fts3Cursor *pCsr,               /* FTS3 cursor object */
164362    int bGlobal,                    /* True to grab the global stats */
164363    MatchInfo *pInfo,               /* Matchinfo context object */
164364    const char *zArg                /* Matchinfo format string */
164365  ){
164366    int rc = SQLITE_OK;
164367    int i;
164368    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
164369    sqlite3_stmt *pSelect = 0;
164370  
164371    for(i=0; rc==SQLITE_OK && zArg[i]; i++){
164372      pInfo->flag = zArg[i];
164373      switch( zArg[i] ){
164374        case FTS3_MATCHINFO_NPHRASE:
164375          if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
164376          break;
164377  
164378        case FTS3_MATCHINFO_NCOL:
164379          if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
164380          break;
164381          
164382        case FTS3_MATCHINFO_NDOC:
164383          if( bGlobal ){
164384            sqlite3_int64 nDoc = 0;
164385            rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
164386            pInfo->aMatchinfo[0] = (u32)nDoc;
164387          }
164388          break;
164389  
164390        case FTS3_MATCHINFO_AVGLENGTH: 
164391          if( bGlobal ){
164392            sqlite3_int64 nDoc;     /* Number of rows in table */
164393            const char *a;          /* Aggregate column length array */
164394  
164395            rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
164396            if( rc==SQLITE_OK ){
164397              int iCol;
164398              for(iCol=0; iCol<pInfo->nCol; iCol++){
164399                u32 iVal;
164400                sqlite3_int64 nToken;
164401                a += sqlite3Fts3GetVarint(a, &nToken);
164402                iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
164403                pInfo->aMatchinfo[iCol] = iVal;
164404              }
164405            }
164406          }
164407          break;
164408  
164409        case FTS3_MATCHINFO_LENGTH: {
164410          sqlite3_stmt *pSelectDocsize = 0;
164411          rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
164412          if( rc==SQLITE_OK ){
164413            int iCol;
164414            const char *a = sqlite3_column_blob(pSelectDocsize, 0);
164415            for(iCol=0; iCol<pInfo->nCol; iCol++){
164416              sqlite3_int64 nToken;
164417              a += sqlite3Fts3GetVarint(a, &nToken);
164418              pInfo->aMatchinfo[iCol] = (u32)nToken;
164419            }
164420          }
164421          sqlite3_reset(pSelectDocsize);
164422          break;
164423        }
164424  
164425        case FTS3_MATCHINFO_LCS:
164426          rc = fts3ExprLoadDoclists(pCsr, 0, 0);
164427          if( rc==SQLITE_OK ){
164428            rc = fts3MatchinfoLcs(pCsr, pInfo);
164429          }
164430          break;
164431  
164432        case FTS3_MATCHINFO_LHITS_BM:
164433        case FTS3_MATCHINFO_LHITS: {
164434          int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
164435          memset(pInfo->aMatchinfo, 0, nZero);
164436          fts3ExprLHitGather(pCsr->pExpr, pInfo);
164437          break;
164438        }
164439  
164440        default: {
164441          Fts3Expr *pExpr;
164442          assert( zArg[i]==FTS3_MATCHINFO_HITS );
164443          pExpr = pCsr->pExpr;
164444          rc = fts3ExprLoadDoclists(pCsr, 0, 0);
164445          if( rc!=SQLITE_OK ) break;
164446          if( bGlobal ){
164447            if( pCsr->pDeferred ){
164448              rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
164449              if( rc!=SQLITE_OK ) break;
164450            }
164451            rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
164452            sqlite3Fts3EvalTestDeferred(pCsr, &rc);
164453            if( rc!=SQLITE_OK ) break;
164454          }
164455          (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
164456          break;
164457        }
164458      }
164459  
164460      pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
164461    }
164462  
164463    sqlite3_reset(pSelect);
164464    return rc;
164465  }
164466  
164467  
164468  /*
164469  ** Populate pCsr->aMatchinfo[] with data for the current row. The 
164470  ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
164471  */
164472  static void fts3GetMatchinfo(
164473    sqlite3_context *pCtx,        /* Return results here */
164474    Fts3Cursor *pCsr,               /* FTS3 Cursor object */
164475    const char *zArg                /* Second argument to matchinfo() function */
164476  ){
164477    MatchInfo sInfo;
164478    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
164479    int rc = SQLITE_OK;
164480    int bGlobal = 0;                /* Collect 'global' stats as well as local */
164481  
164482    u32 *aOut = 0;
164483    void (*xDestroyOut)(void*) = 0;
164484  
164485    memset(&sInfo, 0, sizeof(MatchInfo));
164486    sInfo.pCursor = pCsr;
164487    sInfo.nCol = pTab->nColumn;
164488  
164489    /* If there is cached matchinfo() data, but the format string for the 
164490    ** cache does not match the format string for this request, discard 
164491    ** the cached data. */
164492    if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
164493      sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
164494      pCsr->pMIBuffer = 0;
164495    }
164496  
164497    /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
164498    ** matchinfo function has been called for this query. In this case 
164499    ** allocate the array used to accumulate the matchinfo data and
164500    ** initialize those elements that are constant for every row.
164501    */
164502    if( pCsr->pMIBuffer==0 ){
164503      int nMatchinfo = 0;           /* Number of u32 elements in match-info */
164504      int i;                        /* Used to iterate through zArg */
164505  
164506      /* Determine the number of phrases in the query */
164507      pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
164508      sInfo.nPhrase = pCsr->nPhrase;
164509  
164510      /* Determine the number of integers in the buffer returned by this call. */
164511      for(i=0; zArg[i]; i++){
164512        char *zErr = 0;
164513        if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
164514          sqlite3_result_error(pCtx, zErr, -1);
164515          sqlite3_free(zErr);
164516          return;
164517        }
164518        nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
164519      }
164520  
164521      /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
164522      pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
164523      if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
164524  
164525      pCsr->isMatchinfoNeeded = 1;
164526      bGlobal = 1;
164527    }
164528  
164529    if( rc==SQLITE_OK ){
164530      xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
164531      if( xDestroyOut==0 ){
164532        rc = SQLITE_NOMEM;
164533      }
164534    }
164535  
164536    if( rc==SQLITE_OK ){
164537      sInfo.aMatchinfo = aOut;
164538      sInfo.nPhrase = pCsr->nPhrase;
164539      rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
164540      if( bGlobal ){
164541        fts3MIBufferSetGlobal(pCsr->pMIBuffer);
164542      }
164543    }
164544  
164545    if( rc!=SQLITE_OK ){
164546      sqlite3_result_error_code(pCtx, rc);
164547      if( xDestroyOut ) xDestroyOut(aOut);
164548    }else{
164549      int n = pCsr->pMIBuffer->nElem * sizeof(u32);
164550      sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
164551    }
164552  }
164553  
164554  /*
164555  ** Implementation of snippet() function.
164556  */
164557  SQLITE_PRIVATE void sqlite3Fts3Snippet(
164558    sqlite3_context *pCtx,          /* SQLite function call context */
164559    Fts3Cursor *pCsr,               /* Cursor object */
164560    const char *zStart,             /* Snippet start text - "<b>" */
164561    const char *zEnd,               /* Snippet end text - "</b>" */
164562    const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
164563    int iCol,                       /* Extract snippet from this column */
164564    int nToken                      /* Approximate number of tokens in snippet */
164565  ){
164566    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
164567    int rc = SQLITE_OK;
164568    int i;
164569    StrBuffer res = {0, 0, 0};
164570  
164571    /* The returned text includes up to four fragments of text extracted from
164572    ** the data in the current row. The first iteration of the for(...) loop
164573    ** below attempts to locate a single fragment of text nToken tokens in 
164574    ** size that contains at least one instance of all phrases in the query
164575    ** expression that appear in the current row. If such a fragment of text
164576    ** cannot be found, the second iteration of the loop attempts to locate
164577    ** a pair of fragments, and so on.
164578    */
164579    int nSnippet = 0;               /* Number of fragments in this snippet */
164580    SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
164581    int nFToken = -1;               /* Number of tokens in each fragment */
164582  
164583    if( !pCsr->pExpr ){
164584      sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
164585      return;
164586    }
164587  
164588    for(nSnippet=1; 1; nSnippet++){
164589  
164590      int iSnip;                    /* Loop counter 0..nSnippet-1 */
164591      u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
164592      u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
164593  
164594      if( nToken>=0 ){
164595        nFToken = (nToken+nSnippet-1) / nSnippet;
164596      }else{
164597        nFToken = -1 * nToken;
164598      }
164599  
164600      for(iSnip=0; iSnip<nSnippet; iSnip++){
164601        int iBestScore = -1;        /* Best score of columns checked so far */
164602        int iRead;                  /* Used to iterate through columns */
164603        SnippetFragment *pFragment = &aSnippet[iSnip];
164604  
164605        memset(pFragment, 0, sizeof(*pFragment));
164606  
164607        /* Loop through all columns of the table being considered for snippets.
164608        ** If the iCol argument to this function was negative, this means all
164609        ** columns of the FTS3 table. Otherwise, only column iCol is considered.
164610        */
164611        for(iRead=0; iRead<pTab->nColumn; iRead++){
164612          SnippetFragment sF = {0, 0, 0, 0};
164613          int iS = 0;
164614          if( iCol>=0 && iRead!=iCol ) continue;
164615  
164616          /* Find the best snippet of nFToken tokens in column iRead. */
164617          rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
164618          if( rc!=SQLITE_OK ){
164619            goto snippet_out;
164620          }
164621          if( iS>iBestScore ){
164622            *pFragment = sF;
164623            iBestScore = iS;
164624          }
164625        }
164626  
164627        mCovered |= pFragment->covered;
164628      }
164629  
164630      /* If all query phrases seen by fts3BestSnippet() are present in at least
164631      ** one of the nSnippet snippet fragments, break out of the loop.
164632      */
164633      assert( (mCovered&mSeen)==mCovered );
164634      if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
164635    }
164636  
164637    assert( nFToken>0 );
164638  
164639    for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
164640      rc = fts3SnippetText(pCsr, &aSnippet[i], 
164641          i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
164642      );
164643    }
164644  
164645   snippet_out:
164646    sqlite3Fts3SegmentsClose(pTab);
164647    if( rc!=SQLITE_OK ){
164648      sqlite3_result_error_code(pCtx, rc);
164649      sqlite3_free(res.z);
164650    }else{
164651      sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
164652    }
164653  }
164654  
164655  
164656  typedef struct TermOffset TermOffset;
164657  typedef struct TermOffsetCtx TermOffsetCtx;
164658  
164659  struct TermOffset {
164660    char *pList;                    /* Position-list */
164661    int iPos;                       /* Position just read from pList */
164662    int iOff;                       /* Offset of this term from read positions */
164663  };
164664  
164665  struct TermOffsetCtx {
164666    Fts3Cursor *pCsr;
164667    int iCol;                       /* Column of table to populate aTerm for */
164668    int iTerm;
164669    sqlite3_int64 iDocid;
164670    TermOffset *aTerm;
164671  };
164672  
164673  /*
164674  ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
164675  */
164676  static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
164677    TermOffsetCtx *p = (TermOffsetCtx *)ctx;
164678    int nTerm;                      /* Number of tokens in phrase */
164679    int iTerm;                      /* For looping through nTerm phrase terms */
164680    char *pList;                    /* Pointer to position list for phrase */
164681    int iPos = 0;                   /* First position in position-list */
164682    int rc;
164683  
164684    UNUSED_PARAMETER(iPhrase);
164685    rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
164686    nTerm = pExpr->pPhrase->nToken;
164687    if( pList ){
164688      fts3GetDeltaPosition(&pList, &iPos);
164689      assert( iPos>=0 );
164690    }
164691  
164692    for(iTerm=0; iTerm<nTerm; iTerm++){
164693      TermOffset *pT = &p->aTerm[p->iTerm++];
164694      pT->iOff = nTerm-iTerm-1;
164695      pT->pList = pList;
164696      pT->iPos = iPos;
164697    }
164698  
164699    return rc;
164700  }
164701  
164702  /*
164703  ** Implementation of offsets() function.
164704  */
164705  SQLITE_PRIVATE void sqlite3Fts3Offsets(
164706    sqlite3_context *pCtx,          /* SQLite function call context */
164707    Fts3Cursor *pCsr                /* Cursor object */
164708  ){
164709    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
164710    sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
164711    int rc;                         /* Return Code */
164712    int nToken;                     /* Number of tokens in query */
164713    int iCol;                       /* Column currently being processed */
164714    StrBuffer res = {0, 0, 0};      /* Result string */
164715    TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
164716  
164717    if( !pCsr->pExpr ){
164718      sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
164719      return;
164720    }
164721  
164722    memset(&sCtx, 0, sizeof(sCtx));
164723    assert( pCsr->isRequireSeek==0 );
164724  
164725    /* Count the number of terms in the query */
164726    rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
164727    if( rc!=SQLITE_OK ) goto offsets_out;
164728  
164729    /* Allocate the array of TermOffset iterators. */
164730    sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
164731    if( 0==sCtx.aTerm ){
164732      rc = SQLITE_NOMEM;
164733      goto offsets_out;
164734    }
164735    sCtx.iDocid = pCsr->iPrevId;
164736    sCtx.pCsr = pCsr;
164737  
164738    /* Loop through the table columns, appending offset information to 
164739    ** string-buffer res for each column.
164740    */
164741    for(iCol=0; iCol<pTab->nColumn; iCol++){
164742      sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
164743      const char *ZDUMMY;           /* Dummy argument used with xNext() */
164744      int NDUMMY = 0;               /* Dummy argument used with xNext() */
164745      int iStart = 0;
164746      int iEnd = 0;
164747      int iCurrent = 0;
164748      const char *zDoc;
164749      int nDoc;
164750  
164751      /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
164752      ** no way that this operation can fail, so the return code from
164753      ** fts3ExprIterate() can be discarded.
164754      */
164755      sCtx.iCol = iCol;
164756      sCtx.iTerm = 0;
164757      (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
164758  
164759      /* Retreive the text stored in column iCol. If an SQL NULL is stored 
164760      ** in column iCol, jump immediately to the next iteration of the loop.
164761      ** If an OOM occurs while retrieving the data (this can happen if SQLite
164762      ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM 
164763      ** to the caller. 
164764      */
164765      zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
164766      nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
164767      if( zDoc==0 ){
164768        if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
164769          continue;
164770        }
164771        rc = SQLITE_NOMEM;
164772        goto offsets_out;
164773      }
164774  
164775      /* Initialize a tokenizer iterator to iterate through column iCol. */
164776      rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
164777          zDoc, nDoc, &pC
164778      );
164779      if( rc!=SQLITE_OK ) goto offsets_out;
164780  
164781      rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
164782      while( rc==SQLITE_OK ){
164783        int i;                      /* Used to loop through terms */
164784        int iMinPos = 0x7FFFFFFF;   /* Position of next token */
164785        TermOffset *pTerm = 0;      /* TermOffset associated with next token */
164786  
164787        for(i=0; i<nToken; i++){
164788          TermOffset *pT = &sCtx.aTerm[i];
164789          if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
164790            iMinPos = pT->iPos-pT->iOff;
164791            pTerm = pT;
164792          }
164793        }
164794  
164795        if( !pTerm ){
164796          /* All offsets for this column have been gathered. */
164797          rc = SQLITE_DONE;
164798        }else{
164799          assert( iCurrent<=iMinPos );
164800          if( 0==(0xFE&*pTerm->pList) ){
164801            pTerm->pList = 0;
164802          }else{
164803            fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
164804          }
164805          while( rc==SQLITE_OK && iCurrent<iMinPos ){
164806            rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
164807          }
164808          if( rc==SQLITE_OK ){
164809            char aBuffer[64];
164810            sqlite3_snprintf(sizeof(aBuffer), aBuffer, 
164811                "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
164812            );
164813            rc = fts3StringAppend(&res, aBuffer, -1);
164814          }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
164815            rc = FTS_CORRUPT_VTAB;
164816          }
164817        }
164818      }
164819      if( rc==SQLITE_DONE ){
164820        rc = SQLITE_OK;
164821      }
164822  
164823      pMod->xClose(pC);
164824      if( rc!=SQLITE_OK ) goto offsets_out;
164825    }
164826  
164827   offsets_out:
164828    sqlite3_free(sCtx.aTerm);
164829    assert( rc!=SQLITE_DONE );
164830    sqlite3Fts3SegmentsClose(pTab);
164831    if( rc!=SQLITE_OK ){
164832      sqlite3_result_error_code(pCtx,  rc);
164833      sqlite3_free(res.z);
164834    }else{
164835      sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
164836    }
164837    return;
164838  }
164839  
164840  /*
164841  ** Implementation of matchinfo() function.
164842  */
164843  SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
164844    sqlite3_context *pContext,      /* Function call context */
164845    Fts3Cursor *pCsr,               /* FTS3 table cursor */
164846    const char *zArg                /* Second arg to matchinfo() function */
164847  ){
164848    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
164849    const char *zFormat;
164850  
164851    if( zArg ){
164852      zFormat = zArg;
164853    }else{
164854      zFormat = FTS3_MATCHINFO_DEFAULT;
164855    }
164856  
164857    if( !pCsr->pExpr ){
164858      sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
164859      return;
164860    }else{
164861      /* Retrieve matchinfo() data. */
164862      fts3GetMatchinfo(pContext, pCsr, zFormat);
164863      sqlite3Fts3SegmentsClose(pTab);
164864    }
164865  }
164866  
164867  #endif
164868  
164869  /************** End of fts3_snippet.c ****************************************/
164870  /************** Begin file fts3_unicode.c ************************************/
164871  /*
164872  ** 2012 May 24
164873  **
164874  ** The author disclaims copyright to this source code.  In place of
164875  ** a legal notice, here is a blessing:
164876  **
164877  **    May you do good and not evil.
164878  **    May you find forgiveness for yourself and forgive others.
164879  **    May you share freely, never taking more than you give.
164880  **
164881  ******************************************************************************
164882  **
164883  ** Implementation of the "unicode" full-text-search tokenizer.
164884  */
164885  
164886  #ifndef SQLITE_DISABLE_FTS3_UNICODE
164887  
164888  /* #include "fts3Int.h" */
164889  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
164890  
164891  /* #include <assert.h> */
164892  /* #include <stdlib.h> */
164893  /* #include <stdio.h> */
164894  /* #include <string.h> */
164895  
164896  /* #include "fts3_tokenizer.h" */
164897  
164898  /*
164899  ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
164900  ** from the sqlite3 source file utf.c. If this file is compiled as part
164901  ** of the amalgamation, they are not required.
164902  */
164903  #ifndef SQLITE_AMALGAMATION
164904  
164905  static const unsigned char sqlite3Utf8Trans1[] = {
164906    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
164907    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
164908    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
164909    0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
164910    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
164911    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
164912    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
164913    0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
164914  };
164915  
164916  #define READ_UTF8(zIn, zTerm, c)                           \
164917    c = *(zIn++);                                            \
164918    if( c>=0xc0 ){                                           \
164919      c = sqlite3Utf8Trans1[c-0xc0];                         \
164920      while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
164921        c = (c<<6) + (0x3f & *(zIn++));                      \
164922      }                                                      \
164923      if( c<0x80                                             \
164924          || (c&0xFFFFF800)==0xD800                          \
164925          || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
164926    }
164927  
164928  #define WRITE_UTF8(zOut, c) {                          \
164929    if( c<0x00080 ){                                     \
164930      *zOut++ = (u8)(c&0xFF);                            \
164931    }                                                    \
164932    else if( c<0x00800 ){                                \
164933      *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
164934      *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
164935    }                                                    \
164936    else if( c<0x10000 ){                                \
164937      *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
164938      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
164939      *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
164940    }else{                                               \
164941      *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
164942      *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
164943      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
164944      *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
164945    }                                                    \
164946  }
164947  
164948  #endif /* ifndef SQLITE_AMALGAMATION */
164949  
164950  typedef struct unicode_tokenizer unicode_tokenizer;
164951  typedef struct unicode_cursor unicode_cursor;
164952  
164953  struct unicode_tokenizer {
164954    sqlite3_tokenizer base;
164955    int bRemoveDiacritic;
164956    int nException;
164957    int *aiException;
164958  };
164959  
164960  struct unicode_cursor {
164961    sqlite3_tokenizer_cursor base;
164962    const unsigned char *aInput;    /* Input text being tokenized */
164963    int nInput;                     /* Size of aInput[] in bytes */
164964    int iOff;                       /* Current offset within aInput[] */
164965    int iToken;                     /* Index of next token to be returned */
164966    char *zToken;                   /* storage for current token */
164967    int nAlloc;                     /* space allocated at zToken */
164968  };
164969  
164970  
164971  /*
164972  ** Destroy a tokenizer allocated by unicodeCreate().
164973  */
164974  static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
164975    if( pTokenizer ){
164976      unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
164977      sqlite3_free(p->aiException);
164978      sqlite3_free(p);
164979    }
164980    return SQLITE_OK;
164981  }
164982  
164983  /*
164984  ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
164985  ** statement has specified that the tokenizer for this table shall consider
164986  ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
164987  ** token characters (if bAlnum==1).
164988  **
164989  ** For each codepoint in the zIn/nIn string, this function checks if the
164990  ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
164991  ** If so, no action is taken. Otherwise, the codepoint is added to the 
164992  ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
164993  ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
164994  ** codepoints in the aiException[] array.
164995  **
164996  ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
164997  ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
164998  ** It is not possible to change the behavior of the tokenizer with respect
164999  ** to these codepoints.
165000  */
165001  static int unicodeAddExceptions(
165002    unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
165003    int bAlnum,                     /* Replace Isalnum() return value with this */
165004    const char *zIn,                /* Array of characters to make exceptions */
165005    int nIn                         /* Length of z in bytes */
165006  ){
165007    const unsigned char *z = (const unsigned char *)zIn;
165008    const unsigned char *zTerm = &z[nIn];
165009    unsigned int iCode;
165010    int nEntry = 0;
165011  
165012    assert( bAlnum==0 || bAlnum==1 );
165013  
165014    while( z<zTerm ){
165015      READ_UTF8(z, zTerm, iCode);
165016      assert( (sqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 );
165017      if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum 
165018       && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0 
165019      ){
165020        nEntry++;
165021      }
165022    }
165023  
165024    if( nEntry ){
165025      int *aNew;                    /* New aiException[] array */
165026      int nNew;                     /* Number of valid entries in array aNew[] */
165027  
165028      aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
165029      if( aNew==0 ) return SQLITE_NOMEM;
165030      nNew = p->nException;
165031  
165032      z = (const unsigned char *)zIn;
165033      while( z<zTerm ){
165034        READ_UTF8(z, zTerm, iCode);
165035        if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum 
165036         && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
165037        ){
165038          int i, j;
165039          for(i=0; i<nNew && aNew[i]<(int)iCode; i++);
165040          for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
165041          aNew[i] = (int)iCode;
165042          nNew++;
165043        }
165044      }
165045      p->aiException = aNew;
165046      p->nException = nNew;
165047    }
165048  
165049    return SQLITE_OK;
165050  }
165051  
165052  /*
165053  ** Return true if the p->aiException[] array contains the value iCode.
165054  */
165055  static int unicodeIsException(unicode_tokenizer *p, int iCode){
165056    if( p->nException>0 ){
165057      int *a = p->aiException;
165058      int iLo = 0;
165059      int iHi = p->nException-1;
165060  
165061      while( iHi>=iLo ){
165062        int iTest = (iHi + iLo) / 2;
165063        if( iCode==a[iTest] ){
165064          return 1;
165065        }else if( iCode>a[iTest] ){
165066          iLo = iTest+1;
165067        }else{
165068          iHi = iTest-1;
165069        }
165070      }
165071    }
165072  
165073    return 0;
165074  }
165075  
165076  /*
165077  ** Return true if, for the purposes of tokenization, codepoint iCode is
165078  ** considered a token character (not a separator).
165079  */
165080  static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
165081    assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
165082    return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
165083  }
165084  
165085  /*
165086  ** Create a new tokenizer instance.
165087  */
165088  static int unicodeCreate(
165089    int nArg,                       /* Size of array argv[] */
165090    const char * const *azArg,      /* Tokenizer creation arguments */
165091    sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
165092  ){
165093    unicode_tokenizer *pNew;        /* New tokenizer object */
165094    int i;
165095    int rc = SQLITE_OK;
165096  
165097    pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
165098    if( pNew==NULL ) return SQLITE_NOMEM;
165099    memset(pNew, 0, sizeof(unicode_tokenizer));
165100    pNew->bRemoveDiacritic = 1;
165101  
165102    for(i=0; rc==SQLITE_OK && i<nArg; i++){
165103      const char *z = azArg[i];
165104      int n = (int)strlen(z);
165105  
165106      if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
165107        pNew->bRemoveDiacritic = 1;
165108      }
165109      else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
165110        pNew->bRemoveDiacritic = 0;
165111      }
165112      else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
165113        rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
165114      }
165115      else if( n>=11 && memcmp("separators=", z, 11)==0 ){
165116        rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
165117      }
165118      else{
165119        /* Unrecognized argument */
165120        rc  = SQLITE_ERROR;
165121      }
165122    }
165123  
165124    if( rc!=SQLITE_OK ){
165125      unicodeDestroy((sqlite3_tokenizer *)pNew);
165126      pNew = 0;
165127    }
165128    *pp = (sqlite3_tokenizer *)pNew;
165129    return rc;
165130  }
165131  
165132  /*
165133  ** Prepare to begin tokenizing a particular string.  The input
165134  ** string to be tokenized is pInput[0..nBytes-1].  A cursor
165135  ** used to incrementally tokenize this string is returned in 
165136  ** *ppCursor.
165137  */
165138  static int unicodeOpen(
165139    sqlite3_tokenizer *p,           /* The tokenizer */
165140    const char *aInput,             /* Input string */
165141    int nInput,                     /* Size of string aInput in bytes */
165142    sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
165143  ){
165144    unicode_cursor *pCsr;
165145  
165146    pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
165147    if( pCsr==0 ){
165148      return SQLITE_NOMEM;
165149    }
165150    memset(pCsr, 0, sizeof(unicode_cursor));
165151  
165152    pCsr->aInput = (const unsigned char *)aInput;
165153    if( aInput==0 ){
165154      pCsr->nInput = 0;
165155    }else if( nInput<0 ){
165156      pCsr->nInput = (int)strlen(aInput);
165157    }else{
165158      pCsr->nInput = nInput;
165159    }
165160  
165161    *pp = &pCsr->base;
165162    UNUSED_PARAMETER(p);
165163    return SQLITE_OK;
165164  }
165165  
165166  /*
165167  ** Close a tokenization cursor previously opened by a call to
165168  ** simpleOpen() above.
165169  */
165170  static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
165171    unicode_cursor *pCsr = (unicode_cursor *) pCursor;
165172    sqlite3_free(pCsr->zToken);
165173    sqlite3_free(pCsr);
165174    return SQLITE_OK;
165175  }
165176  
165177  /*
165178  ** Extract the next token from a tokenization cursor.  The cursor must
165179  ** have been opened by a prior call to simpleOpen().
165180  */
165181  static int unicodeNext(
165182    sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
165183    const char **paToken,           /* OUT: Token text */
165184    int *pnToken,                   /* OUT: Number of bytes at *paToken */
165185    int *piStart,                   /* OUT: Starting offset of token */
165186    int *piEnd,                     /* OUT: Ending offset of token */
165187    int *piPos                      /* OUT: Position integer of token */
165188  ){
165189    unicode_cursor *pCsr = (unicode_cursor *)pC;
165190    unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
165191    unsigned int iCode = 0;
165192    char *zOut;
165193    const unsigned char *z = &pCsr->aInput[pCsr->iOff];
165194    const unsigned char *zStart = z;
165195    const unsigned char *zEnd;
165196    const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
165197  
165198    /* Scan past any delimiter characters before the start of the next token.
165199    ** Return SQLITE_DONE early if this takes us all the way to the end of 
165200    ** the input.  */
165201    while( z<zTerm ){
165202      READ_UTF8(z, zTerm, iCode);
165203      if( unicodeIsAlnum(p, (int)iCode) ) break;
165204      zStart = z;
165205    }
165206    if( zStart>=zTerm ) return SQLITE_DONE;
165207  
165208    zOut = pCsr->zToken;
165209    do {
165210      int iOut;
165211  
165212      /* Grow the output buffer if required. */
165213      if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
165214        char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
165215        if( !zNew ) return SQLITE_NOMEM;
165216        zOut = &zNew[zOut - pCsr->zToken];
165217        pCsr->zToken = zNew;
165218        pCsr->nAlloc += 64;
165219      }
165220  
165221      /* Write the folded case of the last character read to the output */
165222      zEnd = z;
165223      iOut = sqlite3FtsUnicodeFold((int)iCode, p->bRemoveDiacritic);
165224      if( iOut ){
165225        WRITE_UTF8(zOut, iOut);
165226      }
165227  
165228      /* If the cursor is not at EOF, read the next character */
165229      if( z>=zTerm ) break;
165230      READ_UTF8(z, zTerm, iCode);
165231    }while( unicodeIsAlnum(p, (int)iCode) 
165232         || sqlite3FtsUnicodeIsdiacritic((int)iCode)
165233    );
165234  
165235    /* Set the output variables and return. */
165236    pCsr->iOff = (int)(z - pCsr->aInput);
165237    *paToken = pCsr->zToken;
165238    *pnToken = (int)(zOut - pCsr->zToken);
165239    *piStart = (int)(zStart - pCsr->aInput);
165240    *piEnd = (int)(zEnd - pCsr->aInput);
165241    *piPos = pCsr->iToken++;
165242    return SQLITE_OK;
165243  }
165244  
165245  /*
165246  ** Set *ppModule to a pointer to the sqlite3_tokenizer_module 
165247  ** structure for the unicode tokenizer.
165248  */
165249  SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
165250    static const sqlite3_tokenizer_module module = {
165251      0,
165252      unicodeCreate,
165253      unicodeDestroy,
165254      unicodeOpen,
165255      unicodeClose,
165256      unicodeNext,
165257      0,
165258    };
165259    *ppModule = &module;
165260  }
165261  
165262  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
165263  #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
165264  
165265  /************** End of fts3_unicode.c ****************************************/
165266  /************** Begin file fts3_unicode2.c ***********************************/
165267  /*
165268  ** 2012 May 25
165269  **
165270  ** The author disclaims copyright to this source code.  In place of
165271  ** a legal notice, here is a blessing:
165272  **
165273  **    May you do good and not evil.
165274  **    May you find forgiveness for yourself and forgive others.
165275  **    May you share freely, never taking more than you give.
165276  **
165277  ******************************************************************************
165278  */
165279  
165280  /*
165281  ** DO NOT EDIT THIS MACHINE GENERATED FILE.
165282  */
165283  
165284  #ifndef SQLITE_DISABLE_FTS3_UNICODE
165285  #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
165286  
165287  /* #include <assert.h> */
165288  
165289  /*
165290  ** Return true if the argument corresponds to a unicode codepoint
165291  ** classified as either a letter or a number. Otherwise false.
165292  **
165293  ** The results are undefined if the value passed to this function
165294  ** is less than zero.
165295  */
165296  SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
165297    /* Each unsigned integer in the following array corresponds to a contiguous
165298    ** range of unicode codepoints that are not either letters or numbers (i.e.
165299    ** codepoints for which this function should return 0).
165300    **
165301    ** The most significant 22 bits in each 32-bit value contain the first 
165302    ** codepoint in the range. The least significant 10 bits are used to store
165303    ** the size of the range (always at least 1). In other words, the value 
165304    ** ((C<<22) + N) represents a range of N codepoints starting with codepoint 
165305    ** C. It is not possible to represent a range larger than 1023 codepoints 
165306    ** using this format.
165307    */
165308    static const unsigned int aEntry[] = {
165309      0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
165310      0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
165311      0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
165312      0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
165313      0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
165314      0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
165315      0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
165316      0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
165317      0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
165318      0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
165319      0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
165320      0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
165321      0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
165322      0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
165323      0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
165324      0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
165325      0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
165326      0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
165327      0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
165328      0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
165329      0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
165330      0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
165331      0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
165332      0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
165333      0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
165334      0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
165335      0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
165336      0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
165337      0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
165338      0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
165339      0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
165340      0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
165341      0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
165342      0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
165343      0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
165344      0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
165345      0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
165346      0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
165347      0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
165348      0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
165349      0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
165350      0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
165351      0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
165352      0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
165353      0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
165354      0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
165355      0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
165356      0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
165357      0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
165358      0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
165359      0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
165360      0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
165361      0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
165362      0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
165363      0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
165364      0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
165365      0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
165366      0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
165367      0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
165368      0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
165369      0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
165370      0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
165371      0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
165372      0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
165373      0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
165374      0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
165375      0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
165376      0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
165377      0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
165378      0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
165379      0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
165380      0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
165381      0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
165382      0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
165383      0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
165384      0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
165385      0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
165386      0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
165387      0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
165388      0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
165389      0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
165390      0x380400F0,
165391    };
165392    static const unsigned int aAscii[4] = {
165393      0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
165394    };
165395  
165396    if( (unsigned int)c<128 ){
165397      return ( (aAscii[c >> 5] & ((unsigned int)1 << (c & 0x001F)))==0 );
165398    }else if( (unsigned int)c<(1<<22) ){
165399      unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
165400      int iRes = 0;
165401      int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
165402      int iLo = 0;
165403      while( iHi>=iLo ){
165404        int iTest = (iHi + iLo) / 2;
165405        if( key >= aEntry[iTest] ){
165406          iRes = iTest;
165407          iLo = iTest+1;
165408        }else{
165409          iHi = iTest-1;
165410        }
165411      }
165412      assert( aEntry[0]<key );
165413      assert( key>=aEntry[iRes] );
165414      return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
165415    }
165416    return 1;
165417  }
165418  
165419  
165420  /*
165421  ** If the argument is a codepoint corresponding to a lowercase letter
165422  ** in the ASCII range with a diacritic added, return the codepoint
165423  ** of the ASCII letter only. For example, if passed 235 - "LATIN
165424  ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
165425  ** E"). The resuls of passing a codepoint that corresponds to an
165426  ** uppercase letter are undefined.
165427  */
165428  static int remove_diacritic(int c){
165429    unsigned short aDia[] = {
165430          0,  1797,  1848,  1859,  1891,  1928,  1940,  1995, 
165431       2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286, 
165432       2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732, 
165433       2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336, 
165434       3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928, 
165435       3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234, 
165436       4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504, 
165437       6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529, 
165438      61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726, 
165439      61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122, 
165440      62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536, 
165441      62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730, 
165442      62924, 63050, 63082, 63274, 63390, 
165443    };
165444    char aChar[] = {
165445      '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',  
165446      'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',  
165447      's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',  
165448      'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',  
165449      'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0', 
165450      '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',  
165451      'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',  
165452      'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',  
165453      'e',  'i',  'o',  'u',  'y',  
165454    };
165455  
165456    unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
165457    int iRes = 0;
165458    int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
165459    int iLo = 0;
165460    while( iHi>=iLo ){
165461      int iTest = (iHi + iLo) / 2;
165462      if( key >= aDia[iTest] ){
165463        iRes = iTest;
165464        iLo = iTest+1;
165465      }else{
165466        iHi = iTest-1;
165467      }
165468    }
165469    assert( key>=aDia[iRes] );
165470    return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
165471  }
165472  
165473  
165474  /*
165475  ** Return true if the argument interpreted as a unicode codepoint
165476  ** is a diacritical modifier character.
165477  */
165478  SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
165479    unsigned int mask0 = 0x08029FDF;
165480    unsigned int mask1 = 0x000361F8;
165481    if( c<768 || c>817 ) return 0;
165482    return (c < 768+32) ?
165483        (mask0 & (1 << (c-768))) :
165484        (mask1 & (1 << (c-768-32)));
165485  }
165486  
165487  
165488  /*
165489  ** Interpret the argument as a unicode codepoint. If the codepoint
165490  ** is an upper case character that has a lower case equivalent,
165491  ** return the codepoint corresponding to the lower case version.
165492  ** Otherwise, return a copy of the argument.
165493  **
165494  ** The results are undefined if the value passed to this function
165495  ** is less than zero.
165496  */
165497  SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
165498    /* Each entry in the following array defines a rule for folding a range
165499    ** of codepoints to lower case. The rule applies to a range of nRange
165500    ** codepoints starting at codepoint iCode.
165501    **
165502    ** If the least significant bit in flags is clear, then the rule applies
165503    ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
165504    ** need to be folded). Or, if it is set, then the rule only applies to
165505    ** every second codepoint in the range, starting with codepoint C.
165506    **
165507    ** The 7 most significant bits in flags are an index into the aiOff[]
165508    ** array. If a specific codepoint C does require folding, then its lower
165509    ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
165510    **
165511    ** The contents of this array are generated by parsing the CaseFolding.txt
165512    ** file distributed as part of the "Unicode Character Database". See
165513    ** http://www.unicode.org for details.
165514    */
165515    static const struct TableEntry {
165516      unsigned short iCode;
165517      unsigned char flags;
165518      unsigned char nRange;
165519    } aEntry[] = {
165520      {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
165521      {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
165522      {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
165523      {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
165524      {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
165525      {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
165526      {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
165527      {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
165528      {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
165529      {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
165530      {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
165531      {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
165532      {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
165533      {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
165534      {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
165535      {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
165536      {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
165537      {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
165538      {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
165539      {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
165540      {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
165541      {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
165542      {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
165543      {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
165544      {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
165545      {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
165546      {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
165547      {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
165548      {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
165549      {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
165550      {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
165551      {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
165552      {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
165553      {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
165554      {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
165555      {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
165556      {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
165557      {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
165558      {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
165559      {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
165560      {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
165561      {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
165562      {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
165563      {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
165564      {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
165565      {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
165566      {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
165567      {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
165568      {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
165569      {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
165570      {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
165571      {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
165572      {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
165573      {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
165574      {65313, 14, 26},       
165575    };
165576    static const unsigned short aiOff[] = {
165577     1,     2,     8,     15,    16,    26,    28,    32,    
165578     37,    38,    40,    48,    63,    64,    69,    71,    
165579     79,    80,    116,   202,   203,   205,   206,   207,   
165580     209,   210,   211,   213,   214,   217,   218,   219,   
165581     775,   7264,  10792, 10795, 23228, 23256, 30204, 54721, 
165582     54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, 
165583     57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, 
165584     65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, 
165585     65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, 
165586     65514, 65521, 65527, 65528, 65529, 
165587    };
165588  
165589    int ret = c;
165590  
165591    assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
165592  
165593    if( c<128 ){
165594      if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
165595    }else if( c<65536 ){
165596      const struct TableEntry *p;
165597      int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
165598      int iLo = 0;
165599      int iRes = -1;
165600  
165601      assert( c>aEntry[0].iCode );
165602      while( iHi>=iLo ){
165603        int iTest = (iHi + iLo) / 2;
165604        int cmp = (c - aEntry[iTest].iCode);
165605        if( cmp>=0 ){
165606          iRes = iTest;
165607          iLo = iTest+1;
165608        }else{
165609          iHi = iTest-1;
165610        }
165611      }
165612  
165613      assert( iRes>=0 && c>=aEntry[iRes].iCode );
165614      p = &aEntry[iRes];
165615      if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
165616        ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
165617        assert( ret>0 );
165618      }
165619  
165620      if( bRemoveDiacritic ) ret = remove_diacritic(ret);
165621    }
165622    
165623    else if( c>=66560 && c<66600 ){
165624      ret = c + 40;
165625    }
165626  
165627    return ret;
165628  }
165629  #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
165630  #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
165631  
165632  /************** End of fts3_unicode2.c ***************************************/
165633  /************** Begin file rtree.c *******************************************/
165634  /*
165635  ** 2001 September 15
165636  **
165637  ** The author disclaims copyright to this source code.  In place of
165638  ** a legal notice, here is a blessing:
165639  **
165640  **    May you do good and not evil.
165641  **    May you find forgiveness for yourself and forgive others.
165642  **    May you share freely, never taking more than you give.
165643  **
165644  *************************************************************************
165645  ** This file contains code for implementations of the r-tree and r*-tree
165646  ** algorithms packaged as an SQLite virtual table module.
165647  */
165648  
165649  /*
165650  ** Database Format of R-Tree Tables
165651  ** --------------------------------
165652  **
165653  ** The data structure for a single virtual r-tree table is stored in three 
165654  ** native SQLite tables declared as follows. In each case, the '%' character
165655  ** in the table name is replaced with the user-supplied name of the r-tree
165656  ** table.
165657  **
165658  **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
165659  **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
165660  **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
165661  **
165662  ** The data for each node of the r-tree structure is stored in the %_node
165663  ** table. For each node that is not the root node of the r-tree, there is
165664  ** an entry in the %_parent table associating the node with its parent.
165665  ** And for each row of data in the table, there is an entry in the %_rowid
165666  ** table that maps from the entries rowid to the id of the node that it
165667  ** is stored on.
165668  **
165669  ** The root node of an r-tree always exists, even if the r-tree table is
165670  ** empty. The nodeno of the root node is always 1. All other nodes in the
165671  ** table must be the same size as the root node. The content of each node
165672  ** is formatted as follows:
165673  **
165674  **   1. If the node is the root node (node 1), then the first 2 bytes
165675  **      of the node contain the tree depth as a big-endian integer.
165676  **      For non-root nodes, the first 2 bytes are left unused.
165677  **
165678  **   2. The next 2 bytes contain the number of entries currently 
165679  **      stored in the node.
165680  **
165681  **   3. The remainder of the node contains the node entries. Each entry
165682  **      consists of a single 8-byte integer followed by an even number
165683  **      of 4-byte coordinates. For leaf nodes the integer is the rowid
165684  **      of a record. For internal nodes it is the node number of a
165685  **      child page.
165686  */
165687  
165688  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
165689  
165690  #ifndef SQLITE_CORE
165691  /*   #include "sqlite3ext.h" */
165692    SQLITE_EXTENSION_INIT1
165693  #else
165694  /*   #include "sqlite3.h" */
165695  #endif
165696  
165697  /* #include <string.h> */
165698  /* #include <assert.h> */
165699  /* #include <stdio.h> */
165700  
165701  #ifndef SQLITE_AMALGAMATION
165702  #include "sqlite3rtree.h"
165703  typedef sqlite3_int64 i64;
165704  typedef sqlite3_uint64 u64;
165705  typedef unsigned char u8;
165706  typedef unsigned short u16;
165707  typedef unsigned int u32;
165708  #endif
165709  
165710  /*  The following macro is used to suppress compiler warnings.
165711  */
165712  #ifndef UNUSED_PARAMETER
165713  # define UNUSED_PARAMETER(x) (void)(x)
165714  #endif
165715  
165716  typedef struct Rtree Rtree;
165717  typedef struct RtreeCursor RtreeCursor;
165718  typedef struct RtreeNode RtreeNode;
165719  typedef struct RtreeCell RtreeCell;
165720  typedef struct RtreeConstraint RtreeConstraint;
165721  typedef struct RtreeMatchArg RtreeMatchArg;
165722  typedef struct RtreeGeomCallback RtreeGeomCallback;
165723  typedef union RtreeCoord RtreeCoord;
165724  typedef struct RtreeSearchPoint RtreeSearchPoint;
165725  
165726  /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
165727  #define RTREE_MAX_DIMENSIONS 5
165728  
165729  /* Size of hash table Rtree.aHash. This hash table is not expected to
165730  ** ever contain very many entries, so a fixed number of buckets is 
165731  ** used.
165732  */
165733  #define HASHSIZE 97
165734  
165735  /* The xBestIndex method of this virtual table requires an estimate of
165736  ** the number of rows in the virtual table to calculate the costs of
165737  ** various strategies. If possible, this estimate is loaded from the
165738  ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
165739  ** Otherwise, if no sqlite_stat1 entry is available, use 
165740  ** RTREE_DEFAULT_ROWEST.
165741  */
165742  #define RTREE_DEFAULT_ROWEST 1048576
165743  #define RTREE_MIN_ROWEST         100
165744  
165745  /* 
165746  ** An rtree virtual-table object.
165747  */
165748  struct Rtree {
165749    sqlite3_vtab base;          /* Base class.  Must be first */
165750    sqlite3 *db;                /* Host database connection */
165751    int iNodeSize;              /* Size in bytes of each node in the node table */
165752    u8 nDim;                    /* Number of dimensions */
165753    u8 nDim2;                   /* Twice the number of dimensions */
165754    u8 eCoordType;              /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
165755    u8 nBytesPerCell;           /* Bytes consumed per cell */
165756    u8 inWrTrans;               /* True if inside write transaction */
165757    int iDepth;                 /* Current depth of the r-tree structure */
165758    char *zDb;                  /* Name of database containing r-tree table */
165759    char *zName;                /* Name of r-tree table */ 
165760    u32 nBusy;                  /* Current number of users of this structure */
165761    i64 nRowEst;                /* Estimated number of rows in this table */
165762    u32 nCursor;                /* Number of open cursors */
165763  
165764    /* List of nodes removed during a CondenseTree operation. List is
165765    ** linked together via the pointer normally used for hash chains -
165766    ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
165767    ** headed by the node (leaf nodes have RtreeNode.iNode==0).
165768    */
165769    RtreeNode *pDeleted;
165770    int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
165771  
165772    /* Blob I/O on xxx_node */
165773    sqlite3_blob *pNodeBlob;
165774  
165775    /* Statements to read/write/delete a record from xxx_node */
165776    sqlite3_stmt *pWriteNode;
165777    sqlite3_stmt *pDeleteNode;
165778  
165779    /* Statements to read/write/delete a record from xxx_rowid */
165780    sqlite3_stmt *pReadRowid;
165781    sqlite3_stmt *pWriteRowid;
165782    sqlite3_stmt *pDeleteRowid;
165783  
165784    /* Statements to read/write/delete a record from xxx_parent */
165785    sqlite3_stmt *pReadParent;
165786    sqlite3_stmt *pWriteParent;
165787    sqlite3_stmt *pDeleteParent;
165788  
165789    RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
165790  };
165791  
165792  /* Possible values for Rtree.eCoordType: */
165793  #define RTREE_COORD_REAL32 0
165794  #define RTREE_COORD_INT32  1
165795  
165796  /*
165797  ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
165798  ** only deal with integer coordinates.  No floating point operations
165799  ** will be done.
165800  */
165801  #ifdef SQLITE_RTREE_INT_ONLY
165802    typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
165803    typedef int RtreeValue;                  /* Low accuracy coordinate */
165804  # define RTREE_ZERO 0
165805  #else
165806    typedef double RtreeDValue;              /* High accuracy coordinate */
165807    typedef float RtreeValue;                /* Low accuracy coordinate */
165808  # define RTREE_ZERO 0.0
165809  #endif
165810  
165811  /*
165812  ** When doing a search of an r-tree, instances of the following structure
165813  ** record intermediate results from the tree walk.
165814  **
165815  ** The id is always a node-id.  For iLevel>=1 the id is the node-id of
165816  ** the node that the RtreeSearchPoint represents.  When iLevel==0, however,
165817  ** the id is of the parent node and the cell that RtreeSearchPoint
165818  ** represents is the iCell-th entry in the parent node.
165819  */
165820  struct RtreeSearchPoint {
165821    RtreeDValue rScore;    /* The score for this node.  Smallest goes first. */
165822    sqlite3_int64 id;      /* Node ID */
165823    u8 iLevel;             /* 0=entries.  1=leaf node.  2+ for higher */
165824    u8 eWithin;            /* PARTLY_WITHIN or FULLY_WITHIN */
165825    u8 iCell;              /* Cell index within the node */
165826  };
165827  
165828  /*
165829  ** The minimum number of cells allowed for a node is a third of the 
165830  ** maximum. In Gutman's notation:
165831  **
165832  **     m = M/3
165833  **
165834  ** If an R*-tree "Reinsert" operation is required, the same number of
165835  ** cells are removed from the overfull node and reinserted into the tree.
165836  */
165837  #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
165838  #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
165839  #define RTREE_MAXCELLS 51
165840  
165841  /*
165842  ** The smallest possible node-size is (512-64)==448 bytes. And the largest
165843  ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
165844  ** Therefore all non-root nodes must contain at least 3 entries. Since 
165845  ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
165846  ** 40 or less.
165847  */
165848  #define RTREE_MAX_DEPTH 40
165849  
165850  
165851  /*
165852  ** Number of entries in the cursor RtreeNode cache.  The first entry is
165853  ** used to cache the RtreeNode for RtreeCursor.sPoint.  The remaining
165854  ** entries cache the RtreeNode for the first elements of the priority queue.
165855  */
165856  #define RTREE_CACHE_SZ  5
165857  
165858  /* 
165859  ** An rtree cursor object.
165860  */
165861  struct RtreeCursor {
165862    sqlite3_vtab_cursor base;         /* Base class.  Must be first */
165863    u8 atEOF;                         /* True if at end of search */
165864    u8 bPoint;                        /* True if sPoint is valid */
165865    int iStrategy;                    /* Copy of idxNum search parameter */
165866    int nConstraint;                  /* Number of entries in aConstraint */
165867    RtreeConstraint *aConstraint;     /* Search constraints. */
165868    int nPointAlloc;                  /* Number of slots allocated for aPoint[] */
165869    int nPoint;                       /* Number of slots used in aPoint[] */
165870    int mxLevel;                      /* iLevel value for root of the tree */
165871    RtreeSearchPoint *aPoint;         /* Priority queue for search points */
165872    RtreeSearchPoint sPoint;          /* Cached next search point */
165873    RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
165874    u32 anQueue[RTREE_MAX_DEPTH+1];   /* Number of queued entries by iLevel */
165875  };
165876  
165877  /* Return the Rtree of a RtreeCursor */
165878  #define RTREE_OF_CURSOR(X)   ((Rtree*)((X)->base.pVtab))
165879  
165880  /*
165881  ** A coordinate can be either a floating point number or a integer.  All
165882  ** coordinates within a single R-Tree are always of the same time.
165883  */
165884  union RtreeCoord {
165885    RtreeValue f;      /* Floating point value */
165886    int i;             /* Integer value */
165887    u32 u;             /* Unsigned for byte-order conversions */
165888  };
165889  
165890  /*
165891  ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
165892  ** formatted as a RtreeDValue (double or int64). This macro assumes that local
165893  ** variable pRtree points to the Rtree structure associated with the
165894  ** RtreeCoord.
165895  */
165896  #ifdef SQLITE_RTREE_INT_ONLY
165897  # define DCOORD(coord) ((RtreeDValue)coord.i)
165898  #else
165899  # define DCOORD(coord) (                           \
165900      (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
165901        ((double)coord.f) :                           \
165902        ((double)coord.i)                             \
165903    )
165904  #endif
165905  
165906  /*
165907  ** A search constraint.
165908  */
165909  struct RtreeConstraint {
165910    int iCoord;                     /* Index of constrained coordinate */
165911    int op;                         /* Constraining operation */
165912    union {
165913      RtreeDValue rValue;             /* Constraint value. */
165914      int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
165915      int (*xQueryFunc)(sqlite3_rtree_query_info*);
165916    } u;
165917    sqlite3_rtree_query_info *pInfo;  /* xGeom and xQueryFunc argument */
165918  };
165919  
165920  /* Possible values for RtreeConstraint.op */
165921  #define RTREE_EQ    0x41  /* A */
165922  #define RTREE_LE    0x42  /* B */
165923  #define RTREE_LT    0x43  /* C */
165924  #define RTREE_GE    0x44  /* D */
165925  #define RTREE_GT    0x45  /* E */
165926  #define RTREE_MATCH 0x46  /* F: Old-style sqlite3_rtree_geometry_callback() */
165927  #define RTREE_QUERY 0x47  /* G: New-style sqlite3_rtree_query_callback() */
165928  
165929  
165930  /* 
165931  ** An rtree structure node.
165932  */
165933  struct RtreeNode {
165934    RtreeNode *pParent;         /* Parent node */
165935    i64 iNode;                  /* The node number */
165936    int nRef;                   /* Number of references to this node */
165937    int isDirty;                /* True if the node needs to be written to disk */
165938    u8 *zData;                  /* Content of the node, as should be on disk */
165939    RtreeNode *pNext;           /* Next node in this hash collision chain */
165940  };
165941  
165942  /* Return the number of cells in a node  */
165943  #define NCELL(pNode) readInt16(&(pNode)->zData[2])
165944  
165945  /* 
165946  ** A single cell from a node, deserialized
165947  */
165948  struct RtreeCell {
165949    i64 iRowid;                                 /* Node or entry ID */
165950    RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];  /* Bounding box coordinates */
165951  };
165952  
165953  
165954  /*
165955  ** This object becomes the sqlite3_user_data() for the SQL functions
165956  ** that are created by sqlite3_rtree_geometry_callback() and
165957  ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
165958  ** operators in order to constrain a search.
165959  **
165960  ** xGeom and xQueryFunc are the callback functions.  Exactly one of 
165961  ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
165962  ** SQL function was created using sqlite3_rtree_geometry_callback() or
165963  ** sqlite3_rtree_query_callback().
165964  ** 
165965  ** This object is deleted automatically by the destructor mechanism in
165966  ** sqlite3_create_function_v2().
165967  */
165968  struct RtreeGeomCallback {
165969    int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
165970    int (*xQueryFunc)(sqlite3_rtree_query_info*);
165971    void (*xDestructor)(void*);
165972    void *pContext;
165973  };
165974  
165975  /*
165976  ** An instance of this structure (in the form of a BLOB) is returned by
165977  ** the SQL functions that sqlite3_rtree_geometry_callback() and
165978  ** sqlite3_rtree_query_callback() create, and is read as the right-hand
165979  ** operand to the MATCH operator of an R-Tree.
165980  */
165981  struct RtreeMatchArg {
165982    u32 iSize;                  /* Size of this object */
165983    RtreeGeomCallback cb;       /* Info about the callback functions */
165984    int nParam;                 /* Number of parameters to the SQL function */
165985    sqlite3_value **apSqlParam; /* Original SQL parameter values */
165986    RtreeDValue aParam[1];      /* Values for parameters to the SQL function */
165987  };
165988  
165989  #ifndef MAX
165990  # define MAX(x,y) ((x) < (y) ? (y) : (x))
165991  #endif
165992  #ifndef MIN
165993  # define MIN(x,y) ((x) > (y) ? (y) : (x))
165994  #endif
165995  
165996  /* What version of GCC is being used.  0 means GCC is not being used .
165997  ** Note that the GCC_VERSION macro will also be set correctly when using
165998  ** clang, since clang works hard to be gcc compatible.  So the gcc
165999  ** optimizations will also work when compiling with clang.
166000  */
166001  #ifndef GCC_VERSION
166002  #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
166003  # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
166004  #else
166005  # define GCC_VERSION 0
166006  #endif
166007  #endif
166008  
166009  /* The testcase() macro should already be defined in the amalgamation.  If
166010  ** it is not, make it a no-op.
166011  */
166012  #ifndef SQLITE_AMALGAMATION
166013  # define testcase(X)
166014  #endif
166015  
166016  /*
166017  ** Macros to determine whether the machine is big or little endian,
166018  ** and whether or not that determination is run-time or compile-time.
166019  **
166020  ** For best performance, an attempt is made to guess at the byte-order
166021  ** using C-preprocessor macros.  If that is unsuccessful, or if
166022  ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
166023  ** at run-time.
166024  */
166025  #ifndef SQLITE_BYTEORDER
166026  #if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
166027      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
166028      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
166029      defined(__arm__)
166030  # define SQLITE_BYTEORDER    1234
166031  #elif defined(sparc)    || defined(__ppc__)
166032  # define SQLITE_BYTEORDER    4321
166033  #else
166034  # define SQLITE_BYTEORDER    0     /* 0 means "unknown at compile-time" */
166035  #endif
166036  #endif
166037  
166038  
166039  /* What version of MSVC is being used.  0 means MSVC is not being used */
166040  #ifndef MSVC_VERSION
166041  #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
166042  # define MSVC_VERSION _MSC_VER
166043  #else
166044  # define MSVC_VERSION 0
166045  #endif
166046  #endif
166047  
166048  /*
166049  ** Functions to deserialize a 16 bit integer, 32 bit real number and
166050  ** 64 bit integer. The deserialized value is returned.
166051  */
166052  static int readInt16(u8 *p){
166053    return (p[0]<<8) + p[1];
166054  }
166055  static void readCoord(u8 *p, RtreeCoord *pCoord){
166056    assert( ((((char*)p) - (char*)0)&3)==0 );  /* p is always 4-byte aligned */
166057  #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
166058    pCoord->u = _byteswap_ulong(*(u32*)p);
166059  #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
166060    pCoord->u = __builtin_bswap32(*(u32*)p);
166061  #elif SQLITE_BYTEORDER==4321
166062    pCoord->u = *(u32*)p;
166063  #else
166064    pCoord->u = (
166065      (((u32)p[0]) << 24) + 
166066      (((u32)p[1]) << 16) + 
166067      (((u32)p[2]) <<  8) + 
166068      (((u32)p[3]) <<  0)
166069    );
166070  #endif
166071  }
166072  static i64 readInt64(u8 *p){
166073  #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
166074    u64 x;
166075    memcpy(&x, p, 8);
166076    return (i64)_byteswap_uint64(x);
166077  #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
166078    u64 x;
166079    memcpy(&x, p, 8);
166080    return (i64)__builtin_bswap64(x);
166081  #elif SQLITE_BYTEORDER==4321
166082    i64 x;
166083    memcpy(&x, p, 8);
166084    return x;
166085  #else
166086    return (i64)(
166087      (((u64)p[0]) << 56) + 
166088      (((u64)p[1]) << 48) + 
166089      (((u64)p[2]) << 40) + 
166090      (((u64)p[3]) << 32) + 
166091      (((u64)p[4]) << 24) + 
166092      (((u64)p[5]) << 16) + 
166093      (((u64)p[6]) <<  8) + 
166094      (((u64)p[7]) <<  0)
166095    );
166096  #endif
166097  }
166098  
166099  /*
166100  ** Functions to serialize a 16 bit integer, 32 bit real number and
166101  ** 64 bit integer. The value returned is the number of bytes written
166102  ** to the argument buffer (always 2, 4 and 8 respectively).
166103  */
166104  static void writeInt16(u8 *p, int i){
166105    p[0] = (i>> 8)&0xFF;
166106    p[1] = (i>> 0)&0xFF;
166107  }
166108  static int writeCoord(u8 *p, RtreeCoord *pCoord){
166109    u32 i;
166110    assert( ((((char*)p) - (char*)0)&3)==0 );  /* p is always 4-byte aligned */
166111    assert( sizeof(RtreeCoord)==4 );
166112    assert( sizeof(u32)==4 );
166113  #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
166114    i = __builtin_bswap32(pCoord->u);
166115    memcpy(p, &i, 4);
166116  #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
166117    i = _byteswap_ulong(pCoord->u);
166118    memcpy(p, &i, 4);
166119  #elif SQLITE_BYTEORDER==4321
166120    i = pCoord->u;
166121    memcpy(p, &i, 4);
166122  #else
166123    i = pCoord->u;
166124    p[0] = (i>>24)&0xFF;
166125    p[1] = (i>>16)&0xFF;
166126    p[2] = (i>> 8)&0xFF;
166127    p[3] = (i>> 0)&0xFF;
166128  #endif
166129    return 4;
166130  }
166131  static int writeInt64(u8 *p, i64 i){
166132  #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
166133    i = (i64)__builtin_bswap64((u64)i);
166134    memcpy(p, &i, 8);
166135  #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
166136    i = (i64)_byteswap_uint64((u64)i);
166137    memcpy(p, &i, 8);
166138  #elif SQLITE_BYTEORDER==4321
166139    memcpy(p, &i, 8);
166140  #else
166141    p[0] = (i>>56)&0xFF;
166142    p[1] = (i>>48)&0xFF;
166143    p[2] = (i>>40)&0xFF;
166144    p[3] = (i>>32)&0xFF;
166145    p[4] = (i>>24)&0xFF;
166146    p[5] = (i>>16)&0xFF;
166147    p[6] = (i>> 8)&0xFF;
166148    p[7] = (i>> 0)&0xFF;
166149  #endif
166150    return 8;
166151  }
166152  
166153  /*
166154  ** Increment the reference count of node p.
166155  */
166156  static void nodeReference(RtreeNode *p){
166157    if( p ){
166158      p->nRef++;
166159    }
166160  }
166161  
166162  /*
166163  ** Clear the content of node p (set all bytes to 0x00).
166164  */
166165  static void nodeZero(Rtree *pRtree, RtreeNode *p){
166166    memset(&p->zData[2], 0, pRtree->iNodeSize-2);
166167    p->isDirty = 1;
166168  }
166169  
166170  /*
166171  ** Given a node number iNode, return the corresponding key to use
166172  ** in the Rtree.aHash table.
166173  */
166174  static int nodeHash(i64 iNode){
166175    return iNode % HASHSIZE;
166176  }
166177  
166178  /*
166179  ** Search the node hash table for node iNode. If found, return a pointer
166180  ** to it. Otherwise, return 0.
166181  */
166182  static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
166183    RtreeNode *p;
166184    for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
166185    return p;
166186  }
166187  
166188  /*
166189  ** Add node pNode to the node hash table.
166190  */
166191  static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
166192    int iHash;
166193    assert( pNode->pNext==0 );
166194    iHash = nodeHash(pNode->iNode);
166195    pNode->pNext = pRtree->aHash[iHash];
166196    pRtree->aHash[iHash] = pNode;
166197  }
166198  
166199  /*
166200  ** Remove node pNode from the node hash table.
166201  */
166202  static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
166203    RtreeNode **pp;
166204    if( pNode->iNode!=0 ){
166205      pp = &pRtree->aHash[nodeHash(pNode->iNode)];
166206      for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
166207      *pp = pNode->pNext;
166208      pNode->pNext = 0;
166209    }
166210  }
166211  
166212  /*
166213  ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
166214  ** indicating that node has not yet been assigned a node number. It is
166215  ** assigned a node number when nodeWrite() is called to write the
166216  ** node contents out to the database.
166217  */
166218  static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
166219    RtreeNode *pNode;
166220    pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
166221    if( pNode ){
166222      memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
166223      pNode->zData = (u8 *)&pNode[1];
166224      pNode->nRef = 1;
166225      pNode->pParent = pParent;
166226      pNode->isDirty = 1;
166227      nodeReference(pParent);
166228    }
166229    return pNode;
166230  }
166231  
166232  /*
166233  ** Clear the Rtree.pNodeBlob object
166234  */
166235  static void nodeBlobReset(Rtree *pRtree){
166236    if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){
166237      sqlite3_blob *pBlob = pRtree->pNodeBlob;
166238      pRtree->pNodeBlob = 0;
166239      sqlite3_blob_close(pBlob);
166240    }
166241  }
166242  
166243  /*
166244  ** Obtain a reference to an r-tree node.
166245  */
166246  static int nodeAcquire(
166247    Rtree *pRtree,             /* R-tree structure */
166248    i64 iNode,                 /* Node number to load */
166249    RtreeNode *pParent,        /* Either the parent node or NULL */
166250    RtreeNode **ppNode         /* OUT: Acquired node */
166251  ){
166252    int rc = SQLITE_OK;
166253    RtreeNode *pNode = 0;
166254  
166255    /* Check if the requested node is already in the hash table. If so,
166256    ** increase its reference count and return it.
166257    */
166258    if( (pNode = nodeHashLookup(pRtree, iNode)) ){
166259      assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
166260      if( pParent && !pNode->pParent ){
166261        nodeReference(pParent);
166262        pNode->pParent = pParent;
166263      }
166264      pNode->nRef++;
166265      *ppNode = pNode;
166266      return SQLITE_OK;
166267    }
166268  
166269    if( pRtree->pNodeBlob ){
166270      sqlite3_blob *pBlob = pRtree->pNodeBlob;
166271      pRtree->pNodeBlob = 0;
166272      rc = sqlite3_blob_reopen(pBlob, iNode);
166273      pRtree->pNodeBlob = pBlob;
166274      if( rc ){
166275        nodeBlobReset(pRtree);
166276        if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
166277      }
166278    }
166279    if( pRtree->pNodeBlob==0 ){
166280      char *zTab = sqlite3_mprintf("%s_node", pRtree->zName);
166281      if( zTab==0 ) return SQLITE_NOMEM;
166282      rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0,
166283                             &pRtree->pNodeBlob);
166284      sqlite3_free(zTab);
166285    }
166286    if( rc ){
166287      nodeBlobReset(pRtree);
166288      *ppNode = 0;
166289      /* If unable to open an sqlite3_blob on the desired row, that can only
166290      ** be because the shadow tables hold erroneous data. */
166291      if( rc==SQLITE_ERROR ) rc = SQLITE_CORRUPT_VTAB;
166292    }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
166293      pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
166294      if( !pNode ){
166295        rc = SQLITE_NOMEM;
166296      }else{
166297        pNode->pParent = pParent;
166298        pNode->zData = (u8 *)&pNode[1];
166299        pNode->nRef = 1;
166300        pNode->iNode = iNode;
166301        pNode->isDirty = 0;
166302        pNode->pNext = 0;
166303        rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
166304                               pRtree->iNodeSize, 0);
166305        nodeReference(pParent);
166306      }
166307    }
166308  
166309    /* If the root node was just loaded, set pRtree->iDepth to the height
166310    ** of the r-tree structure. A height of zero means all data is stored on
166311    ** the root node. A height of one means the children of the root node
166312    ** are the leaves, and so on. If the depth as specified on the root node
166313    ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
166314    */
166315    if( pNode && iNode==1 ){
166316      pRtree->iDepth = readInt16(pNode->zData);
166317      if( pRtree->iDepth>RTREE_MAX_DEPTH ){
166318        rc = SQLITE_CORRUPT_VTAB;
166319      }
166320    }
166321  
166322    /* If no error has occurred so far, check if the "number of entries"
166323    ** field on the node is too large. If so, set the return code to 
166324    ** SQLITE_CORRUPT_VTAB.
166325    */
166326    if( pNode && rc==SQLITE_OK ){
166327      if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
166328        rc = SQLITE_CORRUPT_VTAB;
166329      }
166330    }
166331  
166332    if( rc==SQLITE_OK ){
166333      if( pNode!=0 ){
166334        nodeHashInsert(pRtree, pNode);
166335      }else{
166336        rc = SQLITE_CORRUPT_VTAB;
166337      }
166338      *ppNode = pNode;
166339    }else{
166340      sqlite3_free(pNode);
166341      *ppNode = 0;
166342    }
166343  
166344    return rc;
166345  }
166346  
166347  /*
166348  ** Overwrite cell iCell of node pNode with the contents of pCell.
166349  */
166350  static void nodeOverwriteCell(
166351    Rtree *pRtree,             /* The overall R-Tree */
166352    RtreeNode *pNode,          /* The node into which the cell is to be written */
166353    RtreeCell *pCell,          /* The cell to write */
166354    int iCell                  /* Index into pNode into which pCell is written */
166355  ){
166356    int ii;
166357    u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
166358    p += writeInt64(p, pCell->iRowid);
166359    for(ii=0; ii<pRtree->nDim2; ii++){
166360      p += writeCoord(p, &pCell->aCoord[ii]);
166361    }
166362    pNode->isDirty = 1;
166363  }
166364  
166365  /*
166366  ** Remove the cell with index iCell from node pNode.
166367  */
166368  static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
166369    u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
166370    u8 *pSrc = &pDst[pRtree->nBytesPerCell];
166371    int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
166372    memmove(pDst, pSrc, nByte);
166373    writeInt16(&pNode->zData[2], NCELL(pNode)-1);
166374    pNode->isDirty = 1;
166375  }
166376  
166377  /*
166378  ** Insert the contents of cell pCell into node pNode. If the insert
166379  ** is successful, return SQLITE_OK.
166380  **
166381  ** If there is not enough free space in pNode, return SQLITE_FULL.
166382  */
166383  static int nodeInsertCell(
166384    Rtree *pRtree,                /* The overall R-Tree */
166385    RtreeNode *pNode,             /* Write new cell into this node */
166386    RtreeCell *pCell              /* The cell to be inserted */
166387  ){
166388    int nCell;                    /* Current number of cells in pNode */
166389    int nMaxCell;                 /* Maximum number of cells for pNode */
166390  
166391    nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
166392    nCell = NCELL(pNode);
166393  
166394    assert( nCell<=nMaxCell );
166395    if( nCell<nMaxCell ){
166396      nodeOverwriteCell(pRtree, pNode, pCell, nCell);
166397      writeInt16(&pNode->zData[2], nCell+1);
166398      pNode->isDirty = 1;
166399    }
166400  
166401    return (nCell==nMaxCell);
166402  }
166403  
166404  /*
166405  ** If the node is dirty, write it out to the database.
166406  */
166407  static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
166408    int rc = SQLITE_OK;
166409    if( pNode->isDirty ){
166410      sqlite3_stmt *p = pRtree->pWriteNode;
166411      if( pNode->iNode ){
166412        sqlite3_bind_int64(p, 1, pNode->iNode);
166413      }else{
166414        sqlite3_bind_null(p, 1);
166415      }
166416      sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
166417      sqlite3_step(p);
166418      pNode->isDirty = 0;
166419      rc = sqlite3_reset(p);
166420      if( pNode->iNode==0 && rc==SQLITE_OK ){
166421        pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
166422        nodeHashInsert(pRtree, pNode);
166423      }
166424    }
166425    return rc;
166426  }
166427  
166428  /*
166429  ** Release a reference to a node. If the node is dirty and the reference
166430  ** count drops to zero, the node data is written to the database.
166431  */
166432  static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
166433    int rc = SQLITE_OK;
166434    if( pNode ){
166435      assert( pNode->nRef>0 );
166436      pNode->nRef--;
166437      if( pNode->nRef==0 ){
166438        if( pNode->iNode==1 ){
166439          pRtree->iDepth = -1;
166440        }
166441        if( pNode->pParent ){
166442          rc = nodeRelease(pRtree, pNode->pParent);
166443        }
166444        if( rc==SQLITE_OK ){
166445          rc = nodeWrite(pRtree, pNode);
166446        }
166447        nodeHashDelete(pRtree, pNode);
166448        sqlite3_free(pNode);
166449      }
166450    }
166451    return rc;
166452  }
166453  
166454  /*
166455  ** Return the 64-bit integer value associated with cell iCell of
166456  ** node pNode. If pNode is a leaf node, this is a rowid. If it is
166457  ** an internal node, then the 64-bit integer is a child page number.
166458  */
166459  static i64 nodeGetRowid(
166460    Rtree *pRtree,       /* The overall R-Tree */
166461    RtreeNode *pNode,    /* The node from which to extract the ID */
166462    int iCell            /* The cell index from which to extract the ID */
166463  ){
166464    assert( iCell<NCELL(pNode) );
166465    return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
166466  }
166467  
166468  /*
166469  ** Return coordinate iCoord from cell iCell in node pNode.
166470  */
166471  static void nodeGetCoord(
166472    Rtree *pRtree,               /* The overall R-Tree */
166473    RtreeNode *pNode,            /* The node from which to extract a coordinate */
166474    int iCell,                   /* The index of the cell within the node */
166475    int iCoord,                  /* Which coordinate to extract */
166476    RtreeCoord *pCoord           /* OUT: Space to write result to */
166477  ){
166478    readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
166479  }
166480  
166481  /*
166482  ** Deserialize cell iCell of node pNode. Populate the structure pointed
166483  ** to by pCell with the results.
166484  */
166485  static void nodeGetCell(
166486    Rtree *pRtree,               /* The overall R-Tree */
166487    RtreeNode *pNode,            /* The node containing the cell to be read */
166488    int iCell,                   /* Index of the cell within the node */
166489    RtreeCell *pCell             /* OUT: Write the cell contents here */
166490  ){
166491    u8 *pData;
166492    RtreeCoord *pCoord;
166493    int ii = 0;
166494    pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
166495    pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
166496    pCoord = pCell->aCoord;
166497    do{
166498      readCoord(pData, &pCoord[ii]);
166499      readCoord(pData+4, &pCoord[ii+1]);
166500      pData += 8;
166501      ii += 2;
166502    }while( ii<pRtree->nDim2 );
166503  }
166504  
166505  
166506  /* Forward declaration for the function that does the work of
166507  ** the virtual table module xCreate() and xConnect() methods.
166508  */
166509  static int rtreeInit(
166510    sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
166511  );
166512  
166513  /* 
166514  ** Rtree virtual table module xCreate method.
166515  */
166516  static int rtreeCreate(
166517    sqlite3 *db,
166518    void *pAux,
166519    int argc, const char *const*argv,
166520    sqlite3_vtab **ppVtab,
166521    char **pzErr
166522  ){
166523    return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
166524  }
166525  
166526  /* 
166527  ** Rtree virtual table module xConnect method.
166528  */
166529  static int rtreeConnect(
166530    sqlite3 *db,
166531    void *pAux,
166532    int argc, const char *const*argv,
166533    sqlite3_vtab **ppVtab,
166534    char **pzErr
166535  ){
166536    return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
166537  }
166538  
166539  /*
166540  ** Increment the r-tree reference count.
166541  */
166542  static void rtreeReference(Rtree *pRtree){
166543    pRtree->nBusy++;
166544  }
166545  
166546  /*
166547  ** Decrement the r-tree reference count. When the reference count reaches
166548  ** zero the structure is deleted.
166549  */
166550  static void rtreeRelease(Rtree *pRtree){
166551    pRtree->nBusy--;
166552    if( pRtree->nBusy==0 ){
166553      pRtree->inWrTrans = 0;
166554      pRtree->nCursor = 0;
166555      nodeBlobReset(pRtree);
166556      sqlite3_finalize(pRtree->pWriteNode);
166557      sqlite3_finalize(pRtree->pDeleteNode);
166558      sqlite3_finalize(pRtree->pReadRowid);
166559      sqlite3_finalize(pRtree->pWriteRowid);
166560      sqlite3_finalize(pRtree->pDeleteRowid);
166561      sqlite3_finalize(pRtree->pReadParent);
166562      sqlite3_finalize(pRtree->pWriteParent);
166563      sqlite3_finalize(pRtree->pDeleteParent);
166564      sqlite3_free(pRtree);
166565    }
166566  }
166567  
166568  /* 
166569  ** Rtree virtual table module xDisconnect method.
166570  */
166571  static int rtreeDisconnect(sqlite3_vtab *pVtab){
166572    rtreeRelease((Rtree *)pVtab);
166573    return SQLITE_OK;
166574  }
166575  
166576  /* 
166577  ** Rtree virtual table module xDestroy method.
166578  */
166579  static int rtreeDestroy(sqlite3_vtab *pVtab){
166580    Rtree *pRtree = (Rtree *)pVtab;
166581    int rc;
166582    char *zCreate = sqlite3_mprintf(
166583      "DROP TABLE '%q'.'%q_node';"
166584      "DROP TABLE '%q'.'%q_rowid';"
166585      "DROP TABLE '%q'.'%q_parent';",
166586      pRtree->zDb, pRtree->zName, 
166587      pRtree->zDb, pRtree->zName,
166588      pRtree->zDb, pRtree->zName
166589    );
166590    if( !zCreate ){
166591      rc = SQLITE_NOMEM;
166592    }else{
166593      nodeBlobReset(pRtree);
166594      rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
166595      sqlite3_free(zCreate);
166596    }
166597    if( rc==SQLITE_OK ){
166598      rtreeRelease(pRtree);
166599    }
166600  
166601    return rc;
166602  }
166603  
166604  /* 
166605  ** Rtree virtual table module xOpen method.
166606  */
166607  static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
166608    int rc = SQLITE_NOMEM;
166609    Rtree *pRtree = (Rtree *)pVTab;
166610    RtreeCursor *pCsr;
166611  
166612    pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
166613    if( pCsr ){
166614      memset(pCsr, 0, sizeof(RtreeCursor));
166615      pCsr->base.pVtab = pVTab;
166616      rc = SQLITE_OK;
166617      pRtree->nCursor++;
166618    }
166619    *ppCursor = (sqlite3_vtab_cursor *)pCsr;
166620  
166621    return rc;
166622  }
166623  
166624  
166625  /*
166626  ** Free the RtreeCursor.aConstraint[] array and its contents.
166627  */
166628  static void freeCursorConstraints(RtreeCursor *pCsr){
166629    if( pCsr->aConstraint ){
166630      int i;                        /* Used to iterate through constraint array */
166631      for(i=0; i<pCsr->nConstraint; i++){
166632        sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
166633        if( pInfo ){
166634          if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
166635          sqlite3_free(pInfo);
166636        }
166637      }
166638      sqlite3_free(pCsr->aConstraint);
166639      pCsr->aConstraint = 0;
166640    }
166641  }
166642  
166643  /* 
166644  ** Rtree virtual table module xClose method.
166645  */
166646  static int rtreeClose(sqlite3_vtab_cursor *cur){
166647    Rtree *pRtree = (Rtree *)(cur->pVtab);
166648    int ii;
166649    RtreeCursor *pCsr = (RtreeCursor *)cur;
166650    assert( pRtree->nCursor>0 );
166651    freeCursorConstraints(pCsr);
166652    sqlite3_free(pCsr->aPoint);
166653    for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
166654    sqlite3_free(pCsr);
166655    pRtree->nCursor--;
166656    nodeBlobReset(pRtree);
166657    return SQLITE_OK;
166658  }
166659  
166660  /*
166661  ** Rtree virtual table module xEof method.
166662  **
166663  ** Return non-zero if the cursor does not currently point to a valid 
166664  ** record (i.e if the scan has finished), or zero otherwise.
166665  */
166666  static int rtreeEof(sqlite3_vtab_cursor *cur){
166667    RtreeCursor *pCsr = (RtreeCursor *)cur;
166668    return pCsr->atEOF;
166669  }
166670  
166671  /*
166672  ** Convert raw bits from the on-disk RTree record into a coordinate value.
166673  ** The on-disk format is big-endian and needs to be converted for little-
166674  ** endian platforms.  The on-disk record stores integer coordinates if
166675  ** eInt is true and it stores 32-bit floating point records if eInt is
166676  ** false.  a[] is the four bytes of the on-disk record to be decoded.
166677  ** Store the results in "r".
166678  **
166679  ** There are five versions of this macro.  The last one is generic.  The
166680  ** other four are various architectures-specific optimizations.
166681  */
166682  #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
166683  #define RTREE_DECODE_COORD(eInt, a, r) {                        \
166684      RtreeCoord c;    /* Coordinate decoded */                   \
166685      c.u = _byteswap_ulong(*(u32*)a);                            \
166686      r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
166687  }
166688  #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
166689  #define RTREE_DECODE_COORD(eInt, a, r) {                        \
166690      RtreeCoord c;    /* Coordinate decoded */                   \
166691      c.u = __builtin_bswap32(*(u32*)a);                          \
166692      r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
166693  }
166694  #elif SQLITE_BYTEORDER==1234
166695  #define RTREE_DECODE_COORD(eInt, a, r) {                        \
166696      RtreeCoord c;    /* Coordinate decoded */                   \
166697      memcpy(&c.u,a,4);                                           \
166698      c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)|                   \
166699            ((c.u&0xff)<<24)|((c.u&0xff00)<<8);                   \
166700      r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
166701  }
166702  #elif SQLITE_BYTEORDER==4321
166703  #define RTREE_DECODE_COORD(eInt, a, r) {                        \
166704      RtreeCoord c;    /* Coordinate decoded */                   \
166705      memcpy(&c.u,a,4);                                           \
166706      r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
166707  }
166708  #else
166709  #define RTREE_DECODE_COORD(eInt, a, r) {                        \
166710      RtreeCoord c;    /* Coordinate decoded */                   \
166711      c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16)                     \
166712             +((u32)a[2]<<8) + a[3];                              \
166713      r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
166714  }
166715  #endif
166716  
166717  /*
166718  ** Check the RTree node or entry given by pCellData and p against the MATCH
166719  ** constraint pConstraint.  
166720  */
166721  static int rtreeCallbackConstraint(
166722    RtreeConstraint *pConstraint,  /* The constraint to test */
166723    int eInt,                      /* True if RTree holding integer coordinates */
166724    u8 *pCellData,                 /* Raw cell content */
166725    RtreeSearchPoint *pSearch,     /* Container of this cell */
166726    sqlite3_rtree_dbl *prScore,    /* OUT: score for the cell */
166727    int *peWithin                  /* OUT: visibility of the cell */
166728  ){
166729    sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
166730    int nCoord = pInfo->nCoord;                           /* No. of coordinates */
166731    int rc;                                             /* Callback return code */
166732    RtreeCoord c;                                       /* Translator union */
166733    sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2];   /* Decoded coordinates */
166734  
166735    assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
166736    assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
166737  
166738    if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
166739      pInfo->iRowid = readInt64(pCellData);
166740    }
166741    pCellData += 8;
166742  #ifndef SQLITE_RTREE_INT_ONLY
166743    if( eInt==0 ){
166744      switch( nCoord ){
166745        case 10:  readCoord(pCellData+36, &c); aCoord[9] = c.f;
166746                  readCoord(pCellData+32, &c); aCoord[8] = c.f;
166747        case 8:   readCoord(pCellData+28, &c); aCoord[7] = c.f;
166748                  readCoord(pCellData+24, &c); aCoord[6] = c.f;
166749        case 6:   readCoord(pCellData+20, &c); aCoord[5] = c.f;
166750                  readCoord(pCellData+16, &c); aCoord[4] = c.f;
166751        case 4:   readCoord(pCellData+12, &c); aCoord[3] = c.f;
166752                  readCoord(pCellData+8,  &c); aCoord[2] = c.f;
166753        default:  readCoord(pCellData+4,  &c); aCoord[1] = c.f;
166754                  readCoord(pCellData,    &c); aCoord[0] = c.f;
166755      }
166756    }else
166757  #endif
166758    {
166759      switch( nCoord ){
166760        case 10:  readCoord(pCellData+36, &c); aCoord[9] = c.i;
166761                  readCoord(pCellData+32, &c); aCoord[8] = c.i;
166762        case 8:   readCoord(pCellData+28, &c); aCoord[7] = c.i;
166763                  readCoord(pCellData+24, &c); aCoord[6] = c.i;
166764        case 6:   readCoord(pCellData+20, &c); aCoord[5] = c.i;
166765                  readCoord(pCellData+16, &c); aCoord[4] = c.i;
166766        case 4:   readCoord(pCellData+12, &c); aCoord[3] = c.i;
166767                  readCoord(pCellData+8,  &c); aCoord[2] = c.i;
166768        default:  readCoord(pCellData+4,  &c); aCoord[1] = c.i;
166769                  readCoord(pCellData,    &c); aCoord[0] = c.i;
166770      }
166771    }
166772    if( pConstraint->op==RTREE_MATCH ){
166773      int eWithin = 0;
166774      rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
166775                                nCoord, aCoord, &eWithin);
166776      if( eWithin==0 ) *peWithin = NOT_WITHIN;
166777      *prScore = RTREE_ZERO;
166778    }else{
166779      pInfo->aCoord = aCoord;
166780      pInfo->iLevel = pSearch->iLevel - 1;
166781      pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
166782      pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
166783      rc = pConstraint->u.xQueryFunc(pInfo);
166784      if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
166785      if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
166786        *prScore = pInfo->rScore;
166787      }
166788    }
166789    return rc;
166790  }
166791  
166792  /* 
166793  ** Check the internal RTree node given by pCellData against constraint p.
166794  ** If this constraint cannot be satisfied by any child within the node,
166795  ** set *peWithin to NOT_WITHIN.
166796  */
166797  static void rtreeNonleafConstraint(
166798    RtreeConstraint *p,        /* The constraint to test */
166799    int eInt,                  /* True if RTree holds integer coordinates */
166800    u8 *pCellData,             /* Raw cell content as appears on disk */
166801    int *peWithin              /* Adjust downward, as appropriate */
166802  ){
166803    sqlite3_rtree_dbl val;     /* Coordinate value convert to a double */
166804  
166805    /* p->iCoord might point to either a lower or upper bound coordinate
166806    ** in a coordinate pair.  But make pCellData point to the lower bound.
166807    */
166808    pCellData += 8 + 4*(p->iCoord&0xfe);
166809  
166810    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
166811        || p->op==RTREE_GT || p->op==RTREE_EQ );
166812    assert( ((((char*)pCellData) - (char*)0)&3)==0 );  /* 4-byte aligned */
166813    switch( p->op ){
166814      case RTREE_LE:
166815      case RTREE_LT:
166816      case RTREE_EQ:
166817        RTREE_DECODE_COORD(eInt, pCellData, val);
166818        /* val now holds the lower bound of the coordinate pair */
166819        if( p->u.rValue>=val ) return;
166820        if( p->op!=RTREE_EQ ) break;  /* RTREE_LE and RTREE_LT end here */
166821        /* Fall through for the RTREE_EQ case */
166822  
166823      default: /* RTREE_GT or RTREE_GE,  or fallthrough of RTREE_EQ */
166824        pCellData += 4;
166825        RTREE_DECODE_COORD(eInt, pCellData, val);
166826        /* val now holds the upper bound of the coordinate pair */
166827        if( p->u.rValue<=val ) return;
166828    }
166829    *peWithin = NOT_WITHIN;
166830  }
166831  
166832  /*
166833  ** Check the leaf RTree cell given by pCellData against constraint p.
166834  ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
166835  ** If the constraint is satisfied, leave *peWithin unchanged.
166836  **
166837  ** The constraint is of the form:  xN op $val
166838  **
166839  ** The op is given by p->op.  The xN is p->iCoord-th coordinate in
166840  ** pCellData.  $val is given by p->u.rValue.
166841  */
166842  static void rtreeLeafConstraint(
166843    RtreeConstraint *p,        /* The constraint to test */
166844    int eInt,                  /* True if RTree holds integer coordinates */
166845    u8 *pCellData,             /* Raw cell content as appears on disk */
166846    int *peWithin              /* Adjust downward, as appropriate */
166847  ){
166848    RtreeDValue xN;      /* Coordinate value converted to a double */
166849  
166850    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
166851        || p->op==RTREE_GT || p->op==RTREE_EQ );
166852    pCellData += 8 + p->iCoord*4;
166853    assert( ((((char*)pCellData) - (char*)0)&3)==0 );  /* 4-byte aligned */
166854    RTREE_DECODE_COORD(eInt, pCellData, xN);
166855    switch( p->op ){
166856      case RTREE_LE: if( xN <= p->u.rValue ) return;  break;
166857      case RTREE_LT: if( xN <  p->u.rValue ) return;  break;
166858      case RTREE_GE: if( xN >= p->u.rValue ) return;  break;
166859      case RTREE_GT: if( xN >  p->u.rValue ) return;  break;
166860      default:       if( xN == p->u.rValue ) return;  break;
166861    }
166862    *peWithin = NOT_WITHIN;
166863  }
166864  
166865  /*
166866  ** One of the cells in node pNode is guaranteed to have a 64-bit 
166867  ** integer value equal to iRowid. Return the index of this cell.
166868  */
166869  static int nodeRowidIndex(
166870    Rtree *pRtree, 
166871    RtreeNode *pNode, 
166872    i64 iRowid,
166873    int *piIndex
166874  ){
166875    int ii;
166876    int nCell = NCELL(pNode);
166877    assert( nCell<200 );
166878    for(ii=0; ii<nCell; ii++){
166879      if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
166880        *piIndex = ii;
166881        return SQLITE_OK;
166882      }
166883    }
166884    return SQLITE_CORRUPT_VTAB;
166885  }
166886  
166887  /*
166888  ** Return the index of the cell containing a pointer to node pNode
166889  ** in its parent. If pNode is the root node, return -1.
166890  */
166891  static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
166892    RtreeNode *pParent = pNode->pParent;
166893    if( pParent ){
166894      return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
166895    }
166896    *piIndex = -1;
166897    return SQLITE_OK;
166898  }
166899  
166900  /*
166901  ** Compare two search points.  Return negative, zero, or positive if the first
166902  ** is less than, equal to, or greater than the second.
166903  **
166904  ** The rScore is the primary key.  Smaller rScore values come first.
166905  ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
166906  ** iLevel values coming first.  In this way, if rScore is the same for all
166907  ** SearchPoints, then iLevel becomes the deciding factor and the result
166908  ** is a depth-first search, which is the desired default behavior.
166909  */
166910  static int rtreeSearchPointCompare(
166911    const RtreeSearchPoint *pA,
166912    const RtreeSearchPoint *pB
166913  ){
166914    if( pA->rScore<pB->rScore ) return -1;
166915    if( pA->rScore>pB->rScore ) return +1;
166916    if( pA->iLevel<pB->iLevel ) return -1;
166917    if( pA->iLevel>pB->iLevel ) return +1;
166918    return 0;
166919  }
166920  
166921  /*
166922  ** Interchange two search points in a cursor.
166923  */
166924  static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
166925    RtreeSearchPoint t = p->aPoint[i];
166926    assert( i<j );
166927    p->aPoint[i] = p->aPoint[j];
166928    p->aPoint[j] = t;
166929    i++; j++;
166930    if( i<RTREE_CACHE_SZ ){
166931      if( j>=RTREE_CACHE_SZ ){
166932        nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
166933        p->aNode[i] = 0;
166934      }else{
166935        RtreeNode *pTemp = p->aNode[i];
166936        p->aNode[i] = p->aNode[j];
166937        p->aNode[j] = pTemp;
166938      }
166939    }
166940  }
166941  
166942  /*
166943  ** Return the search point with the lowest current score.
166944  */
166945  static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
166946    return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
166947  }
166948  
166949  /*
166950  ** Get the RtreeNode for the search point with the lowest score.
166951  */
166952  static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
166953    sqlite3_int64 id;
166954    int ii = 1 - pCur->bPoint;
166955    assert( ii==0 || ii==1 );
166956    assert( pCur->bPoint || pCur->nPoint );
166957    if( pCur->aNode[ii]==0 ){
166958      assert( pRC!=0 );
166959      id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
166960      *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
166961    }
166962    return pCur->aNode[ii];
166963  }
166964  
166965  /*
166966  ** Push a new element onto the priority queue
166967  */
166968  static RtreeSearchPoint *rtreeEnqueue(
166969    RtreeCursor *pCur,    /* The cursor */
166970    RtreeDValue rScore,   /* Score for the new search point */
166971    u8 iLevel             /* Level for the new search point */
166972  ){
166973    int i, j;
166974    RtreeSearchPoint *pNew;
166975    if( pCur->nPoint>=pCur->nPointAlloc ){
166976      int nNew = pCur->nPointAlloc*2 + 8;
166977      pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
166978      if( pNew==0 ) return 0;
166979      pCur->aPoint = pNew;
166980      pCur->nPointAlloc = nNew;
166981    }
166982    i = pCur->nPoint++;
166983    pNew = pCur->aPoint + i;
166984    pNew->rScore = rScore;
166985    pNew->iLevel = iLevel;
166986    assert( iLevel<=RTREE_MAX_DEPTH );
166987    while( i>0 ){
166988      RtreeSearchPoint *pParent;
166989      j = (i-1)/2;
166990      pParent = pCur->aPoint + j;
166991      if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
166992      rtreeSearchPointSwap(pCur, j, i);
166993      i = j;
166994      pNew = pParent;
166995    }
166996    return pNew;
166997  }
166998  
166999  /*
167000  ** Allocate a new RtreeSearchPoint and return a pointer to it.  Return
167001  ** NULL if malloc fails.
167002  */
167003  static RtreeSearchPoint *rtreeSearchPointNew(
167004    RtreeCursor *pCur,    /* The cursor */
167005    RtreeDValue rScore,   /* Score for the new search point */
167006    u8 iLevel             /* Level for the new search point */
167007  ){
167008    RtreeSearchPoint *pNew, *pFirst;
167009    pFirst = rtreeSearchPointFirst(pCur);
167010    pCur->anQueue[iLevel]++;
167011    if( pFirst==0
167012     || pFirst->rScore>rScore 
167013     || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
167014    ){
167015      if( pCur->bPoint ){
167016        int ii;
167017        pNew = rtreeEnqueue(pCur, rScore, iLevel);
167018        if( pNew==0 ) return 0;
167019        ii = (int)(pNew - pCur->aPoint) + 1;
167020        if( ii<RTREE_CACHE_SZ ){
167021          assert( pCur->aNode[ii]==0 );
167022          pCur->aNode[ii] = pCur->aNode[0];
167023         }else{
167024          nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
167025        }
167026        pCur->aNode[0] = 0;
167027        *pNew = pCur->sPoint;
167028      }
167029      pCur->sPoint.rScore = rScore;
167030      pCur->sPoint.iLevel = iLevel;
167031      pCur->bPoint = 1;
167032      return &pCur->sPoint;
167033    }else{
167034      return rtreeEnqueue(pCur, rScore, iLevel);
167035    }
167036  }
167037  
167038  #if 0
167039  /* Tracing routines for the RtreeSearchPoint queue */
167040  static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
167041    if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
167042    printf(" %d.%05lld.%02d %g %d",
167043      p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
167044    );
167045    idx++;
167046    if( idx<RTREE_CACHE_SZ ){
167047      printf(" %p\n", pCur->aNode[idx]);
167048    }else{
167049      printf("\n");
167050    }
167051  }
167052  static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
167053    int ii;
167054    printf("=== %9s ", zPrefix);
167055    if( pCur->bPoint ){
167056      tracePoint(&pCur->sPoint, -1, pCur);
167057    }
167058    for(ii=0; ii<pCur->nPoint; ii++){
167059      if( ii>0 || pCur->bPoint ) printf("              ");
167060      tracePoint(&pCur->aPoint[ii], ii, pCur);
167061    }
167062  }
167063  # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
167064  #else
167065  # define RTREE_QUEUE_TRACE(A,B)   /* no-op */
167066  #endif
167067  
167068  /* Remove the search point with the lowest current score.
167069  */
167070  static void rtreeSearchPointPop(RtreeCursor *p){
167071    int i, j, k, n;
167072    i = 1 - p->bPoint;
167073    assert( i==0 || i==1 );
167074    if( p->aNode[i] ){
167075      nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
167076      p->aNode[i] = 0;
167077    }
167078    if( p->bPoint ){
167079      p->anQueue[p->sPoint.iLevel]--;
167080      p->bPoint = 0;
167081    }else if( p->nPoint ){
167082      p->anQueue[p->aPoint[0].iLevel]--;
167083      n = --p->nPoint;
167084      p->aPoint[0] = p->aPoint[n];
167085      if( n<RTREE_CACHE_SZ-1 ){
167086        p->aNode[1] = p->aNode[n+1];
167087        p->aNode[n+1] = 0;
167088      }
167089      i = 0;
167090      while( (j = i*2+1)<n ){
167091        k = j+1;
167092        if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
167093          if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
167094            rtreeSearchPointSwap(p, i, k);
167095            i = k;
167096          }else{
167097            break;
167098          }
167099        }else{
167100          if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
167101            rtreeSearchPointSwap(p, i, j);
167102            i = j;
167103          }else{
167104            break;
167105          }
167106        }
167107      }
167108    }
167109  }
167110  
167111  
167112  /*
167113  ** Continue the search on cursor pCur until the front of the queue
167114  ** contains an entry suitable for returning as a result-set row,
167115  ** or until the RtreeSearchPoint queue is empty, indicating that the
167116  ** query has completed.
167117  */
167118  static int rtreeStepToLeaf(RtreeCursor *pCur){
167119    RtreeSearchPoint *p;
167120    Rtree *pRtree = RTREE_OF_CURSOR(pCur);
167121    RtreeNode *pNode;
167122    int eWithin;
167123    int rc = SQLITE_OK;
167124    int nCell;
167125    int nConstraint = pCur->nConstraint;
167126    int ii;
167127    int eInt;
167128    RtreeSearchPoint x;
167129  
167130    eInt = pRtree->eCoordType==RTREE_COORD_INT32;
167131    while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
167132      pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
167133      if( rc ) return rc;
167134      nCell = NCELL(pNode);
167135      assert( nCell<200 );
167136      while( p->iCell<nCell ){
167137        sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
167138        u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
167139        eWithin = FULLY_WITHIN;
167140        for(ii=0; ii<nConstraint; ii++){
167141          RtreeConstraint *pConstraint = pCur->aConstraint + ii;
167142          if( pConstraint->op>=RTREE_MATCH ){
167143            rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
167144                                         &rScore, &eWithin);
167145            if( rc ) return rc;
167146          }else if( p->iLevel==1 ){
167147            rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
167148          }else{
167149            rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
167150          }
167151          if( eWithin==NOT_WITHIN ) break;
167152        }
167153        p->iCell++;
167154        if( eWithin==NOT_WITHIN ) continue;
167155        x.iLevel = p->iLevel - 1;
167156        if( x.iLevel ){
167157          x.id = readInt64(pCellData);
167158          x.iCell = 0;
167159        }else{
167160          x.id = p->id;
167161          x.iCell = p->iCell - 1;
167162        }
167163        if( p->iCell>=nCell ){
167164          RTREE_QUEUE_TRACE(pCur, "POP-S:");
167165          rtreeSearchPointPop(pCur);
167166        }
167167        if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
167168        p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
167169        if( p==0 ) return SQLITE_NOMEM;
167170        p->eWithin = (u8)eWithin;
167171        p->id = x.id;
167172        p->iCell = x.iCell;
167173        RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
167174        break;
167175      }
167176      if( p->iCell>=nCell ){
167177        RTREE_QUEUE_TRACE(pCur, "POP-Se:");
167178        rtreeSearchPointPop(pCur);
167179      }
167180    }
167181    pCur->atEOF = p==0;
167182    return SQLITE_OK;
167183  }
167184  
167185  /* 
167186  ** Rtree virtual table module xNext method.
167187  */
167188  static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
167189    RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
167190    int rc = SQLITE_OK;
167191  
167192    /* Move to the next entry that matches the configured constraints. */
167193    RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
167194    rtreeSearchPointPop(pCsr);
167195    rc = rtreeStepToLeaf(pCsr);
167196    return rc;
167197  }
167198  
167199  /* 
167200  ** Rtree virtual table module xRowid method.
167201  */
167202  static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
167203    RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
167204    RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
167205    int rc = SQLITE_OK;
167206    RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
167207    if( rc==SQLITE_OK && p ){
167208      *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
167209    }
167210    return rc;
167211  }
167212  
167213  /* 
167214  ** Rtree virtual table module xColumn method.
167215  */
167216  static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
167217    Rtree *pRtree = (Rtree *)cur->pVtab;
167218    RtreeCursor *pCsr = (RtreeCursor *)cur;
167219    RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
167220    RtreeCoord c;
167221    int rc = SQLITE_OK;
167222    RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
167223  
167224    if( rc ) return rc;
167225    if( p==0 ) return SQLITE_OK;
167226    if( i==0 ){
167227      sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
167228    }else{
167229      nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
167230  #ifndef SQLITE_RTREE_INT_ONLY
167231      if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
167232        sqlite3_result_double(ctx, c.f);
167233      }else
167234  #endif
167235      {
167236        assert( pRtree->eCoordType==RTREE_COORD_INT32 );
167237        sqlite3_result_int(ctx, c.i);
167238      }
167239    }
167240    return SQLITE_OK;
167241  }
167242  
167243  /* 
167244  ** Use nodeAcquire() to obtain the leaf node containing the record with 
167245  ** rowid iRowid. If successful, set *ppLeaf to point to the node and
167246  ** return SQLITE_OK. If there is no such record in the table, set
167247  ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
167248  ** to zero and return an SQLite error code.
167249  */
167250  static int findLeafNode(
167251    Rtree *pRtree,              /* RTree to search */
167252    i64 iRowid,                 /* The rowid searching for */
167253    RtreeNode **ppLeaf,         /* Write the node here */
167254    sqlite3_int64 *piNode       /* Write the node-id here */
167255  ){
167256    int rc;
167257    *ppLeaf = 0;
167258    sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
167259    if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
167260      i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
167261      if( piNode ) *piNode = iNode;
167262      rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
167263      sqlite3_reset(pRtree->pReadRowid);
167264    }else{
167265      rc = sqlite3_reset(pRtree->pReadRowid);
167266    }
167267    return rc;
167268  }
167269  
167270  /*
167271  ** This function is called to configure the RtreeConstraint object passed
167272  ** as the second argument for a MATCH constraint. The value passed as the
167273  ** first argument to this function is the right-hand operand to the MATCH
167274  ** operator.
167275  */
167276  static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
167277    RtreeMatchArg *pBlob, *pSrc;       /* BLOB returned by geometry function */
167278    sqlite3_rtree_query_info *pInfo;   /* Callback information */
167279  
167280    pSrc = sqlite3_value_pointer(pValue, "RtreeMatchArg");
167281    if( pSrc==0 ) return SQLITE_ERROR;
167282    pInfo = (sqlite3_rtree_query_info*)
167283                  sqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize );
167284    if( !pInfo ) return SQLITE_NOMEM;
167285    memset(pInfo, 0, sizeof(*pInfo));
167286    pBlob = (RtreeMatchArg*)&pInfo[1];
167287    memcpy(pBlob, pSrc, pSrc->iSize);
167288    pInfo->pContext = pBlob->cb.pContext;
167289    pInfo->nParam = pBlob->nParam;
167290    pInfo->aParam = pBlob->aParam;
167291    pInfo->apSqlParam = pBlob->apSqlParam;
167292  
167293    if( pBlob->cb.xGeom ){
167294      pCons->u.xGeom = pBlob->cb.xGeom;
167295    }else{
167296      pCons->op = RTREE_QUERY;
167297      pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
167298    }
167299    pCons->pInfo = pInfo;
167300    return SQLITE_OK;
167301  }
167302  
167303  /* 
167304  ** Rtree virtual table module xFilter method.
167305  */
167306  static int rtreeFilter(
167307    sqlite3_vtab_cursor *pVtabCursor, 
167308    int idxNum, const char *idxStr,
167309    int argc, sqlite3_value **argv
167310  ){
167311    Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
167312    RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
167313    RtreeNode *pRoot = 0;
167314    int ii;
167315    int rc = SQLITE_OK;
167316    int iCell = 0;
167317  
167318    rtreeReference(pRtree);
167319  
167320    /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
167321    freeCursorConstraints(pCsr);
167322    sqlite3_free(pCsr->aPoint);
167323    memset(pCsr, 0, sizeof(RtreeCursor));
167324    pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
167325  
167326    pCsr->iStrategy = idxNum;
167327    if( idxNum==1 ){
167328      /* Special case - lookup by rowid. */
167329      RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
167330      RtreeSearchPoint *p;     /* Search point for the leaf */
167331      i64 iRowid = sqlite3_value_int64(argv[0]);
167332      i64 iNode = 0;
167333      rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
167334      if( rc==SQLITE_OK && pLeaf!=0 ){
167335        p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
167336        assert( p!=0 );  /* Always returns pCsr->sPoint */
167337        pCsr->aNode[0] = pLeaf;
167338        p->id = iNode;
167339        p->eWithin = PARTLY_WITHIN;
167340        rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
167341        p->iCell = (u8)iCell;
167342        RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
167343      }else{
167344        pCsr->atEOF = 1;
167345      }
167346    }else{
167347      /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
167348      ** with the configured constraints. 
167349      */
167350      rc = nodeAcquire(pRtree, 1, 0, &pRoot);
167351      if( rc==SQLITE_OK && argc>0 ){
167352        pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
167353        pCsr->nConstraint = argc;
167354        if( !pCsr->aConstraint ){
167355          rc = SQLITE_NOMEM;
167356        }else{
167357          memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
167358          memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
167359          assert( (idxStr==0 && argc==0)
167360                  || (idxStr && (int)strlen(idxStr)==argc*2) );
167361          for(ii=0; ii<argc; ii++){
167362            RtreeConstraint *p = &pCsr->aConstraint[ii];
167363            p->op = idxStr[ii*2];
167364            p->iCoord = idxStr[ii*2+1]-'0';
167365            if( p->op>=RTREE_MATCH ){
167366              /* A MATCH operator. The right-hand-side must be a blob that
167367              ** can be cast into an RtreeMatchArg object. One created using
167368              ** an sqlite3_rtree_geometry_callback() SQL user function.
167369              */
167370              rc = deserializeGeometry(argv[ii], p);
167371              if( rc!=SQLITE_OK ){
167372                break;
167373              }
167374              p->pInfo->nCoord = pRtree->nDim2;
167375              p->pInfo->anQueue = pCsr->anQueue;
167376              p->pInfo->mxLevel = pRtree->iDepth + 1;
167377            }else{
167378  #ifdef SQLITE_RTREE_INT_ONLY
167379              p->u.rValue = sqlite3_value_int64(argv[ii]);
167380  #else
167381              p->u.rValue = sqlite3_value_double(argv[ii]);
167382  #endif
167383            }
167384          }
167385        }
167386      }
167387      if( rc==SQLITE_OK ){
167388        RtreeSearchPoint *pNew;
167389        pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
167390        if( pNew==0 ) return SQLITE_NOMEM;
167391        pNew->id = 1;
167392        pNew->iCell = 0;
167393        pNew->eWithin = PARTLY_WITHIN;
167394        assert( pCsr->bPoint==1 );
167395        pCsr->aNode[0] = pRoot;
167396        pRoot = 0;
167397        RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
167398        rc = rtreeStepToLeaf(pCsr);
167399      }
167400    }
167401  
167402    nodeRelease(pRtree, pRoot);
167403    rtreeRelease(pRtree);
167404    return rc;
167405  }
167406  
167407  /*
167408  ** Rtree virtual table module xBestIndex method. There are three
167409  ** table scan strategies to choose from (in order from most to 
167410  ** least desirable):
167411  **
167412  **   idxNum     idxStr        Strategy
167413  **   ------------------------------------------------
167414  **     1        Unused        Direct lookup by rowid.
167415  **     2        See below     R-tree query or full-table scan.
167416  **   ------------------------------------------------
167417  **
167418  ** If strategy 1 is used, then idxStr is not meaningful. If strategy
167419  ** 2 is used, idxStr is formatted to contain 2 bytes for each 
167420  ** constraint used. The first two bytes of idxStr correspond to 
167421  ** the constraint in sqlite3_index_info.aConstraintUsage[] with
167422  ** (argvIndex==1) etc.
167423  **
167424  ** The first of each pair of bytes in idxStr identifies the constraint
167425  ** operator as follows:
167426  **
167427  **   Operator    Byte Value
167428  **   ----------------------
167429  **      =        0x41 ('A')
167430  **     <=        0x42 ('B')
167431  **      <        0x43 ('C')
167432  **     >=        0x44 ('D')
167433  **      >        0x45 ('E')
167434  **   MATCH       0x46 ('F')
167435  **   ----------------------
167436  **
167437  ** The second of each pair of bytes identifies the coordinate column
167438  ** to which the constraint applies. The leftmost coordinate column
167439  ** is 'a', the second from the left 'b' etc.
167440  */
167441  static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
167442    Rtree *pRtree = (Rtree*)tab;
167443    int rc = SQLITE_OK;
167444    int ii;
167445    int bMatch = 0;                 /* True if there exists a MATCH constraint */
167446    i64 nRow;                       /* Estimated rows returned by this scan */
167447  
167448    int iIdx = 0;
167449    char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
167450    memset(zIdxStr, 0, sizeof(zIdxStr));
167451  
167452    /* Check if there exists a MATCH constraint - even an unusable one. If there
167453    ** is, do not consider the lookup-by-rowid plan as using such a plan would
167454    ** require the VDBE to evaluate the MATCH constraint, which is not currently
167455    ** possible. */
167456    for(ii=0; ii<pIdxInfo->nConstraint; ii++){
167457      if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
167458        bMatch = 1;
167459      }
167460    }
167461  
167462    assert( pIdxInfo->idxStr==0 );
167463    for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
167464      struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
167465  
167466      if( bMatch==0 && p->usable 
167467       && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ 
167468      ){
167469        /* We have an equality constraint on the rowid. Use strategy 1. */
167470        int jj;
167471        for(jj=0; jj<ii; jj++){
167472          pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
167473          pIdxInfo->aConstraintUsage[jj].omit = 0;
167474        }
167475        pIdxInfo->idxNum = 1;
167476        pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
167477        pIdxInfo->aConstraintUsage[jj].omit = 1;
167478  
167479        /* This strategy involves a two rowid lookups on an B-Tree structures
167480        ** and then a linear search of an R-Tree node. This should be 
167481        ** considered almost as quick as a direct rowid lookup (for which 
167482        ** sqlite uses an internal cost of 0.0). It is expected to return
167483        ** a single row.
167484        */ 
167485        pIdxInfo->estimatedCost = 30.0;
167486        pIdxInfo->estimatedRows = 1;
167487        return SQLITE_OK;
167488      }
167489  
167490      if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
167491        u8 op;
167492        switch( p->op ){
167493          case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
167494          case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
167495          case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
167496          case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
167497          case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
167498          default:
167499            assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
167500            op = RTREE_MATCH; 
167501            break;
167502        }
167503        zIdxStr[iIdx++] = op;
167504        zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');
167505        pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
167506        pIdxInfo->aConstraintUsage[ii].omit = 1;
167507      }
167508    }
167509  
167510    pIdxInfo->idxNum = 2;
167511    pIdxInfo->needToFreeIdxStr = 1;
167512    if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
167513      return SQLITE_NOMEM;
167514    }
167515  
167516    nRow = pRtree->nRowEst >> (iIdx/2);
167517    pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
167518    pIdxInfo->estimatedRows = nRow;
167519  
167520    return rc;
167521  }
167522  
167523  /*
167524  ** Return the N-dimensional volumn of the cell stored in *p.
167525  */
167526  static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
167527    RtreeDValue area = (RtreeDValue)1;
167528    assert( pRtree->nDim>=1 && pRtree->nDim<=5 );
167529  #ifndef SQLITE_RTREE_INT_ONLY
167530    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
167531      switch( pRtree->nDim ){
167532        case 5:  area  = p->aCoord[9].f - p->aCoord[8].f;
167533        case 4:  area *= p->aCoord[7].f - p->aCoord[6].f;
167534        case 3:  area *= p->aCoord[5].f - p->aCoord[4].f;
167535        case 2:  area *= p->aCoord[3].f - p->aCoord[2].f;
167536        default: area *= p->aCoord[1].f - p->aCoord[0].f;
167537      }
167538    }else
167539  #endif
167540    {
167541      switch( pRtree->nDim ){
167542        case 5:  area  = p->aCoord[9].i - p->aCoord[8].i;
167543        case 4:  area *= p->aCoord[7].i - p->aCoord[6].i;
167544        case 3:  area *= p->aCoord[5].i - p->aCoord[4].i;
167545        case 2:  area *= p->aCoord[3].i - p->aCoord[2].i;
167546        default: area *= p->aCoord[1].i - p->aCoord[0].i;
167547      }
167548    }
167549    return area;
167550  }
167551  
167552  /*
167553  ** Return the margin length of cell p. The margin length is the sum
167554  ** of the objects size in each dimension.
167555  */
167556  static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
167557    RtreeDValue margin = 0;
167558    int ii = pRtree->nDim2 - 2;
167559    do{
167560      margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
167561      ii -= 2;
167562    }while( ii>=0 );
167563    return margin;
167564  }
167565  
167566  /*
167567  ** Store the union of cells p1 and p2 in p1.
167568  */
167569  static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
167570    int ii = 0;
167571    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
167572      do{
167573        p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
167574        p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
167575        ii += 2;
167576      }while( ii<pRtree->nDim2 );
167577    }else{
167578      do{
167579        p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
167580        p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
167581        ii += 2;
167582      }while( ii<pRtree->nDim2 );
167583    }
167584  }
167585  
167586  /*
167587  ** Return true if the area covered by p2 is a subset of the area covered
167588  ** by p1. False otherwise.
167589  */
167590  static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
167591    int ii;
167592    int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
167593    for(ii=0; ii<pRtree->nDim2; ii+=2){
167594      RtreeCoord *a1 = &p1->aCoord[ii];
167595      RtreeCoord *a2 = &p2->aCoord[ii];
167596      if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
167597       || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
167598      ){
167599        return 0;
167600      }
167601    }
167602    return 1;
167603  }
167604  
167605  /*
167606  ** Return the amount cell p would grow by if it were unioned with pCell.
167607  */
167608  static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
167609    RtreeDValue area;
167610    RtreeCell cell;
167611    memcpy(&cell, p, sizeof(RtreeCell));
167612    area = cellArea(pRtree, &cell);
167613    cellUnion(pRtree, &cell, pCell);
167614    return (cellArea(pRtree, &cell)-area);
167615  }
167616  
167617  static RtreeDValue cellOverlap(
167618    Rtree *pRtree, 
167619    RtreeCell *p, 
167620    RtreeCell *aCell, 
167621    int nCell
167622  ){
167623    int ii;
167624    RtreeDValue overlap = RTREE_ZERO;
167625    for(ii=0; ii<nCell; ii++){
167626      int jj;
167627      RtreeDValue o = (RtreeDValue)1;
167628      for(jj=0; jj<pRtree->nDim2; jj+=2){
167629        RtreeDValue x1, x2;
167630        x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
167631        x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
167632        if( x2<x1 ){
167633          o = (RtreeDValue)0;
167634          break;
167635        }else{
167636          o = o * (x2-x1);
167637        }
167638      }
167639      overlap += o;
167640    }
167641    return overlap;
167642  }
167643  
167644  
167645  /*
167646  ** This function implements the ChooseLeaf algorithm from Gutman[84].
167647  ** ChooseSubTree in r*tree terminology.
167648  */
167649  static int ChooseLeaf(
167650    Rtree *pRtree,               /* Rtree table */
167651    RtreeCell *pCell,            /* Cell to insert into rtree */
167652    int iHeight,                 /* Height of sub-tree rooted at pCell */
167653    RtreeNode **ppLeaf           /* OUT: Selected leaf page */
167654  ){
167655    int rc;
167656    int ii;
167657    RtreeNode *pNode;
167658    rc = nodeAcquire(pRtree, 1, 0, &pNode);
167659  
167660    for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
167661      int iCell;
167662      sqlite3_int64 iBest = 0;
167663  
167664      RtreeDValue fMinGrowth = RTREE_ZERO;
167665      RtreeDValue fMinArea = RTREE_ZERO;
167666  
167667      int nCell = NCELL(pNode);
167668      RtreeCell cell;
167669      RtreeNode *pChild;
167670  
167671      RtreeCell *aCell = 0;
167672  
167673      /* Select the child node which will be enlarged the least if pCell
167674      ** is inserted into it. Resolve ties by choosing the entry with
167675      ** the smallest area.
167676      */
167677      for(iCell=0; iCell<nCell; iCell++){
167678        int bBest = 0;
167679        RtreeDValue growth;
167680        RtreeDValue area;
167681        nodeGetCell(pRtree, pNode, iCell, &cell);
167682        growth = cellGrowth(pRtree, &cell, pCell);
167683        area = cellArea(pRtree, &cell);
167684        if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
167685          bBest = 1;
167686        }
167687        if( bBest ){
167688          fMinGrowth = growth;
167689          fMinArea = area;
167690          iBest = cell.iRowid;
167691        }
167692      }
167693  
167694      sqlite3_free(aCell);
167695      rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
167696      nodeRelease(pRtree, pNode);
167697      pNode = pChild;
167698    }
167699  
167700    *ppLeaf = pNode;
167701    return rc;
167702  }
167703  
167704  /*
167705  ** A cell with the same content as pCell has just been inserted into
167706  ** the node pNode. This function updates the bounding box cells in
167707  ** all ancestor elements.
167708  */
167709  static int AdjustTree(
167710    Rtree *pRtree,                    /* Rtree table */
167711    RtreeNode *pNode,                 /* Adjust ancestry of this node. */
167712    RtreeCell *pCell                  /* This cell was just inserted */
167713  ){
167714    RtreeNode *p = pNode;
167715    while( p->pParent ){
167716      RtreeNode *pParent = p->pParent;
167717      RtreeCell cell;
167718      int iCell;
167719  
167720      if( nodeParentIndex(pRtree, p, &iCell) ){
167721        return SQLITE_CORRUPT_VTAB;
167722      }
167723  
167724      nodeGetCell(pRtree, pParent, iCell, &cell);
167725      if( !cellContains(pRtree, &cell, pCell) ){
167726        cellUnion(pRtree, &cell, pCell);
167727        nodeOverwriteCell(pRtree, pParent, &cell, iCell);
167728      }
167729   
167730      p = pParent;
167731    }
167732    return SQLITE_OK;
167733  }
167734  
167735  /*
167736  ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
167737  */
167738  static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
167739    sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
167740    sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
167741    sqlite3_step(pRtree->pWriteRowid);
167742    return sqlite3_reset(pRtree->pWriteRowid);
167743  }
167744  
167745  /*
167746  ** Write mapping (iNode->iPar) to the <rtree>_parent table.
167747  */
167748  static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
167749    sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
167750    sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
167751    sqlite3_step(pRtree->pWriteParent);
167752    return sqlite3_reset(pRtree->pWriteParent);
167753  }
167754  
167755  static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
167756  
167757  
167758  /*
167759  ** Arguments aIdx, aDistance and aSpare all point to arrays of size
167760  ** nIdx. The aIdx array contains the set of integers from 0 to 
167761  ** (nIdx-1) in no particular order. This function sorts the values
167762  ** in aIdx according to the indexed values in aDistance. For
167763  ** example, assuming the inputs:
167764  **
167765  **   aIdx      = { 0,   1,   2,   3 }
167766  **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
167767  **
167768  ** this function sets the aIdx array to contain:
167769  **
167770  **   aIdx      = { 0,   1,   2,   3 }
167771  **
167772  ** The aSpare array is used as temporary working space by the
167773  ** sorting algorithm.
167774  */
167775  static void SortByDistance(
167776    int *aIdx, 
167777    int nIdx, 
167778    RtreeDValue *aDistance, 
167779    int *aSpare
167780  ){
167781    if( nIdx>1 ){
167782      int iLeft = 0;
167783      int iRight = 0;
167784  
167785      int nLeft = nIdx/2;
167786      int nRight = nIdx-nLeft;
167787      int *aLeft = aIdx;
167788      int *aRight = &aIdx[nLeft];
167789  
167790      SortByDistance(aLeft, nLeft, aDistance, aSpare);
167791      SortByDistance(aRight, nRight, aDistance, aSpare);
167792  
167793      memcpy(aSpare, aLeft, sizeof(int)*nLeft);
167794      aLeft = aSpare;
167795  
167796      while( iLeft<nLeft || iRight<nRight ){
167797        if( iLeft==nLeft ){
167798          aIdx[iLeft+iRight] = aRight[iRight];
167799          iRight++;
167800        }else if( iRight==nRight ){
167801          aIdx[iLeft+iRight] = aLeft[iLeft];
167802          iLeft++;
167803        }else{
167804          RtreeDValue fLeft = aDistance[aLeft[iLeft]];
167805          RtreeDValue fRight = aDistance[aRight[iRight]];
167806          if( fLeft<fRight ){
167807            aIdx[iLeft+iRight] = aLeft[iLeft];
167808            iLeft++;
167809          }else{
167810            aIdx[iLeft+iRight] = aRight[iRight];
167811            iRight++;
167812          }
167813        }
167814      }
167815  
167816  #if 0
167817      /* Check that the sort worked */
167818      {
167819        int jj;
167820        for(jj=1; jj<nIdx; jj++){
167821          RtreeDValue left = aDistance[aIdx[jj-1]];
167822          RtreeDValue right = aDistance[aIdx[jj]];
167823          assert( left<=right );
167824        }
167825      }
167826  #endif
167827    }
167828  }
167829  
167830  /*
167831  ** Arguments aIdx, aCell and aSpare all point to arrays of size
167832  ** nIdx. The aIdx array contains the set of integers from 0 to 
167833  ** (nIdx-1) in no particular order. This function sorts the values
167834  ** in aIdx according to dimension iDim of the cells in aCell. The
167835  ** minimum value of dimension iDim is considered first, the
167836  ** maximum used to break ties.
167837  **
167838  ** The aSpare array is used as temporary working space by the
167839  ** sorting algorithm.
167840  */
167841  static void SortByDimension(
167842    Rtree *pRtree,
167843    int *aIdx, 
167844    int nIdx, 
167845    int iDim, 
167846    RtreeCell *aCell, 
167847    int *aSpare
167848  ){
167849    if( nIdx>1 ){
167850  
167851      int iLeft = 0;
167852      int iRight = 0;
167853  
167854      int nLeft = nIdx/2;
167855      int nRight = nIdx-nLeft;
167856      int *aLeft = aIdx;
167857      int *aRight = &aIdx[nLeft];
167858  
167859      SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
167860      SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
167861  
167862      memcpy(aSpare, aLeft, sizeof(int)*nLeft);
167863      aLeft = aSpare;
167864      while( iLeft<nLeft || iRight<nRight ){
167865        RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
167866        RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
167867        RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
167868        RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
167869        if( (iLeft!=nLeft) && ((iRight==nRight)
167870         || (xleft1<xright1)
167871         || (xleft1==xright1 && xleft2<xright2)
167872        )){
167873          aIdx[iLeft+iRight] = aLeft[iLeft];
167874          iLeft++;
167875        }else{
167876          aIdx[iLeft+iRight] = aRight[iRight];
167877          iRight++;
167878        }
167879      }
167880  
167881  #if 0
167882      /* Check that the sort worked */
167883      {
167884        int jj;
167885        for(jj=1; jj<nIdx; jj++){
167886          RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
167887          RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
167888          RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
167889          RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
167890          assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
167891        }
167892      }
167893  #endif
167894    }
167895  }
167896  
167897  /*
167898  ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
167899  */
167900  static int splitNodeStartree(
167901    Rtree *pRtree,
167902    RtreeCell *aCell,
167903    int nCell,
167904    RtreeNode *pLeft,
167905    RtreeNode *pRight,
167906    RtreeCell *pBboxLeft,
167907    RtreeCell *pBboxRight
167908  ){
167909    int **aaSorted;
167910    int *aSpare;
167911    int ii;
167912  
167913    int iBestDim = 0;
167914    int iBestSplit = 0;
167915    RtreeDValue fBestMargin = RTREE_ZERO;
167916  
167917    int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
167918  
167919    aaSorted = (int **)sqlite3_malloc(nByte);
167920    if( !aaSorted ){
167921      return SQLITE_NOMEM;
167922    }
167923  
167924    aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
167925    memset(aaSorted, 0, nByte);
167926    for(ii=0; ii<pRtree->nDim; ii++){
167927      int jj;
167928      aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
167929      for(jj=0; jj<nCell; jj++){
167930        aaSorted[ii][jj] = jj;
167931      }
167932      SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
167933    }
167934  
167935    for(ii=0; ii<pRtree->nDim; ii++){
167936      RtreeDValue margin = RTREE_ZERO;
167937      RtreeDValue fBestOverlap = RTREE_ZERO;
167938      RtreeDValue fBestArea = RTREE_ZERO;
167939      int iBestLeft = 0;
167940      int nLeft;
167941  
167942      for(
167943        nLeft=RTREE_MINCELLS(pRtree); 
167944        nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
167945        nLeft++
167946      ){
167947        RtreeCell left;
167948        RtreeCell right;
167949        int kk;
167950        RtreeDValue overlap;
167951        RtreeDValue area;
167952  
167953        memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
167954        memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
167955        for(kk=1; kk<(nCell-1); kk++){
167956          if( kk<nLeft ){
167957            cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
167958          }else{
167959            cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
167960          }
167961        }
167962        margin += cellMargin(pRtree, &left);
167963        margin += cellMargin(pRtree, &right);
167964        overlap = cellOverlap(pRtree, &left, &right, 1);
167965        area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
167966        if( (nLeft==RTREE_MINCELLS(pRtree))
167967         || (overlap<fBestOverlap)
167968         || (overlap==fBestOverlap && area<fBestArea)
167969        ){
167970          iBestLeft = nLeft;
167971          fBestOverlap = overlap;
167972          fBestArea = area;
167973        }
167974      }
167975  
167976      if( ii==0 || margin<fBestMargin ){
167977        iBestDim = ii;
167978        fBestMargin = margin;
167979        iBestSplit = iBestLeft;
167980      }
167981    }
167982  
167983    memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
167984    memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
167985    for(ii=0; ii<nCell; ii++){
167986      RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
167987      RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
167988      RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
167989      nodeInsertCell(pRtree, pTarget, pCell);
167990      cellUnion(pRtree, pBbox, pCell);
167991    }
167992  
167993    sqlite3_free(aaSorted);
167994    return SQLITE_OK;
167995  }
167996  
167997  
167998  static int updateMapping(
167999    Rtree *pRtree, 
168000    i64 iRowid, 
168001    RtreeNode *pNode, 
168002    int iHeight
168003  ){
168004    int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
168005    xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
168006    if( iHeight>0 ){
168007      RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
168008      if( pChild ){
168009        nodeRelease(pRtree, pChild->pParent);
168010        nodeReference(pNode);
168011        pChild->pParent = pNode;
168012      }
168013    }
168014    return xSetMapping(pRtree, iRowid, pNode->iNode);
168015  }
168016  
168017  static int SplitNode(
168018    Rtree *pRtree,
168019    RtreeNode *pNode,
168020    RtreeCell *pCell,
168021    int iHeight
168022  ){
168023    int i;
168024    int newCellIsRight = 0;
168025  
168026    int rc = SQLITE_OK;
168027    int nCell = NCELL(pNode);
168028    RtreeCell *aCell;
168029    int *aiUsed;
168030  
168031    RtreeNode *pLeft = 0;
168032    RtreeNode *pRight = 0;
168033  
168034    RtreeCell leftbbox;
168035    RtreeCell rightbbox;
168036  
168037    /* Allocate an array and populate it with a copy of pCell and 
168038    ** all cells from node pLeft. Then zero the original node.
168039    */
168040    aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
168041    if( !aCell ){
168042      rc = SQLITE_NOMEM;
168043      goto splitnode_out;
168044    }
168045    aiUsed = (int *)&aCell[nCell+1];
168046    memset(aiUsed, 0, sizeof(int)*(nCell+1));
168047    for(i=0; i<nCell; i++){
168048      nodeGetCell(pRtree, pNode, i, &aCell[i]);
168049    }
168050    nodeZero(pRtree, pNode);
168051    memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
168052    nCell++;
168053  
168054    if( pNode->iNode==1 ){
168055      pRight = nodeNew(pRtree, pNode);
168056      pLeft = nodeNew(pRtree, pNode);
168057      pRtree->iDepth++;
168058      pNode->isDirty = 1;
168059      writeInt16(pNode->zData, pRtree->iDepth);
168060    }else{
168061      pLeft = pNode;
168062      pRight = nodeNew(pRtree, pLeft->pParent);
168063      nodeReference(pLeft);
168064    }
168065  
168066    if( !pLeft || !pRight ){
168067      rc = SQLITE_NOMEM;
168068      goto splitnode_out;
168069    }
168070  
168071    memset(pLeft->zData, 0, pRtree->iNodeSize);
168072    memset(pRight->zData, 0, pRtree->iNodeSize);
168073  
168074    rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
168075                           &leftbbox, &rightbbox);
168076    if( rc!=SQLITE_OK ){
168077      goto splitnode_out;
168078    }
168079  
168080    /* Ensure both child nodes have node numbers assigned to them by calling
168081    ** nodeWrite(). Node pRight always needs a node number, as it was created
168082    ** by nodeNew() above. But node pLeft sometimes already has a node number.
168083    ** In this case avoid the all to nodeWrite().
168084    */
168085    if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
168086     || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
168087    ){
168088      goto splitnode_out;
168089    }
168090  
168091    rightbbox.iRowid = pRight->iNode;
168092    leftbbox.iRowid = pLeft->iNode;
168093  
168094    if( pNode->iNode==1 ){
168095      rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
168096      if( rc!=SQLITE_OK ){
168097        goto splitnode_out;
168098      }
168099    }else{
168100      RtreeNode *pParent = pLeft->pParent;
168101      int iCell;
168102      rc = nodeParentIndex(pRtree, pLeft, &iCell);
168103      if( rc==SQLITE_OK ){
168104        nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
168105        rc = AdjustTree(pRtree, pParent, &leftbbox);
168106      }
168107      if( rc!=SQLITE_OK ){
168108        goto splitnode_out;
168109      }
168110    }
168111    if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
168112      goto splitnode_out;
168113    }
168114  
168115    for(i=0; i<NCELL(pRight); i++){
168116      i64 iRowid = nodeGetRowid(pRtree, pRight, i);
168117      rc = updateMapping(pRtree, iRowid, pRight, iHeight);
168118      if( iRowid==pCell->iRowid ){
168119        newCellIsRight = 1;
168120      }
168121      if( rc!=SQLITE_OK ){
168122        goto splitnode_out;
168123      }
168124    }
168125    if( pNode->iNode==1 ){
168126      for(i=0; i<NCELL(pLeft); i++){
168127        i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
168128        rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
168129        if( rc!=SQLITE_OK ){
168130          goto splitnode_out;
168131        }
168132      }
168133    }else if( newCellIsRight==0 ){
168134      rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
168135    }
168136  
168137    if( rc==SQLITE_OK ){
168138      rc = nodeRelease(pRtree, pRight);
168139      pRight = 0;
168140    }
168141    if( rc==SQLITE_OK ){
168142      rc = nodeRelease(pRtree, pLeft);
168143      pLeft = 0;
168144    }
168145  
168146  splitnode_out:
168147    nodeRelease(pRtree, pRight);
168148    nodeRelease(pRtree, pLeft);
168149    sqlite3_free(aCell);
168150    return rc;
168151  }
168152  
168153  /*
168154  ** If node pLeaf is not the root of the r-tree and its pParent pointer is 
168155  ** still NULL, load all ancestor nodes of pLeaf into memory and populate
168156  ** the pLeaf->pParent chain all the way up to the root node.
168157  **
168158  ** This operation is required when a row is deleted (or updated - an update
168159  ** is implemented as a delete followed by an insert). SQLite provides the
168160  ** rowid of the row to delete, which can be used to find the leaf on which
168161  ** the entry resides (argument pLeaf). Once the leaf is located, this 
168162  ** function is called to determine its ancestry.
168163  */
168164  static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
168165    int rc = SQLITE_OK;
168166    RtreeNode *pChild = pLeaf;
168167    while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
168168      int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
168169      sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
168170      rc = sqlite3_step(pRtree->pReadParent);
168171      if( rc==SQLITE_ROW ){
168172        RtreeNode *pTest;           /* Used to test for reference loops */
168173        i64 iNode;                  /* Node number of parent node */
168174  
168175        /* Before setting pChild->pParent, test that we are not creating a
168176        ** loop of references (as we would if, say, pChild==pParent). We don't
168177        ** want to do this as it leads to a memory leak when trying to delete
168178        ** the referenced counted node structures.
168179        */
168180        iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
168181        for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
168182        if( !pTest ){
168183          rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
168184        }
168185      }
168186      rc = sqlite3_reset(pRtree->pReadParent);
168187      if( rc==SQLITE_OK ) rc = rc2;
168188      if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
168189      pChild = pChild->pParent;
168190    }
168191    return rc;
168192  }
168193  
168194  static int deleteCell(Rtree *, RtreeNode *, int, int);
168195  
168196  static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
168197    int rc;
168198    int rc2;
168199    RtreeNode *pParent = 0;
168200    int iCell;
168201  
168202    assert( pNode->nRef==1 );
168203  
168204    /* Remove the entry in the parent cell. */
168205    rc = nodeParentIndex(pRtree, pNode, &iCell);
168206    if( rc==SQLITE_OK ){
168207      pParent = pNode->pParent;
168208      pNode->pParent = 0;
168209      rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
168210    }
168211    rc2 = nodeRelease(pRtree, pParent);
168212    if( rc==SQLITE_OK ){
168213      rc = rc2;
168214    }
168215    if( rc!=SQLITE_OK ){
168216      return rc;
168217    }
168218  
168219    /* Remove the xxx_node entry. */
168220    sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
168221    sqlite3_step(pRtree->pDeleteNode);
168222    if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
168223      return rc;
168224    }
168225  
168226    /* Remove the xxx_parent entry. */
168227    sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
168228    sqlite3_step(pRtree->pDeleteParent);
168229    if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
168230      return rc;
168231    }
168232    
168233    /* Remove the node from the in-memory hash table and link it into
168234    ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
168235    */
168236    nodeHashDelete(pRtree, pNode);
168237    pNode->iNode = iHeight;
168238    pNode->pNext = pRtree->pDeleted;
168239    pNode->nRef++;
168240    pRtree->pDeleted = pNode;
168241  
168242    return SQLITE_OK;
168243  }
168244  
168245  static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
168246    RtreeNode *pParent = pNode->pParent;
168247    int rc = SQLITE_OK; 
168248    if( pParent ){
168249      int ii; 
168250      int nCell = NCELL(pNode);
168251      RtreeCell box;                            /* Bounding box for pNode */
168252      nodeGetCell(pRtree, pNode, 0, &box);
168253      for(ii=1; ii<nCell; ii++){
168254        RtreeCell cell;
168255        nodeGetCell(pRtree, pNode, ii, &cell);
168256        cellUnion(pRtree, &box, &cell);
168257      }
168258      box.iRowid = pNode->iNode;
168259      rc = nodeParentIndex(pRtree, pNode, &ii);
168260      if( rc==SQLITE_OK ){
168261        nodeOverwriteCell(pRtree, pParent, &box, ii);
168262        rc = fixBoundingBox(pRtree, pParent);
168263      }
168264    }
168265    return rc;
168266  }
168267  
168268  /*
168269  ** Delete the cell at index iCell of node pNode. After removing the
168270  ** cell, adjust the r-tree data structure if required.
168271  */
168272  static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
168273    RtreeNode *pParent;
168274    int rc;
168275  
168276    if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
168277      return rc;
168278    }
168279  
168280    /* Remove the cell from the node. This call just moves bytes around
168281    ** the in-memory node image, so it cannot fail.
168282    */
168283    nodeDeleteCell(pRtree, pNode, iCell);
168284  
168285    /* If the node is not the tree root and now has less than the minimum
168286    ** number of cells, remove it from the tree. Otherwise, update the
168287    ** cell in the parent node so that it tightly contains the updated
168288    ** node.
168289    */
168290    pParent = pNode->pParent;
168291    assert( pParent || pNode->iNode==1 );
168292    if( pParent ){
168293      if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
168294        rc = removeNode(pRtree, pNode, iHeight);
168295      }else{
168296        rc = fixBoundingBox(pRtree, pNode);
168297      }
168298    }
168299  
168300    return rc;
168301  }
168302  
168303  static int Reinsert(
168304    Rtree *pRtree, 
168305    RtreeNode *pNode, 
168306    RtreeCell *pCell, 
168307    int iHeight
168308  ){
168309    int *aOrder;
168310    int *aSpare;
168311    RtreeCell *aCell;
168312    RtreeDValue *aDistance;
168313    int nCell;
168314    RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
168315    int iDim;
168316    int ii;
168317    int rc = SQLITE_OK;
168318    int n;
168319  
168320    memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
168321  
168322    nCell = NCELL(pNode)+1;
168323    n = (nCell+1)&(~1);
168324  
168325    /* Allocate the buffers used by this operation. The allocation is
168326    ** relinquished before this function returns.
168327    */
168328    aCell = (RtreeCell *)sqlite3_malloc(n * (
168329      sizeof(RtreeCell)     +         /* aCell array */
168330      sizeof(int)           +         /* aOrder array */
168331      sizeof(int)           +         /* aSpare array */
168332      sizeof(RtreeDValue)             /* aDistance array */
168333    ));
168334    if( !aCell ){
168335      return SQLITE_NOMEM;
168336    }
168337    aOrder    = (int *)&aCell[n];
168338    aSpare    = (int *)&aOrder[n];
168339    aDistance = (RtreeDValue *)&aSpare[n];
168340  
168341    for(ii=0; ii<nCell; ii++){
168342      if( ii==(nCell-1) ){
168343        memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
168344      }else{
168345        nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
168346      }
168347      aOrder[ii] = ii;
168348      for(iDim=0; iDim<pRtree->nDim; iDim++){
168349        aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
168350        aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
168351      }
168352    }
168353    for(iDim=0; iDim<pRtree->nDim; iDim++){
168354      aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
168355    }
168356  
168357    for(ii=0; ii<nCell; ii++){
168358      aDistance[ii] = RTREE_ZERO;
168359      for(iDim=0; iDim<pRtree->nDim; iDim++){
168360        RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
168361                                 DCOORD(aCell[ii].aCoord[iDim*2]));
168362        aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
168363      }
168364    }
168365  
168366    SortByDistance(aOrder, nCell, aDistance, aSpare);
168367    nodeZero(pRtree, pNode);
168368  
168369    for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
168370      RtreeCell *p = &aCell[aOrder[ii]];
168371      nodeInsertCell(pRtree, pNode, p);
168372      if( p->iRowid==pCell->iRowid ){
168373        if( iHeight==0 ){
168374          rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
168375        }else{
168376          rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
168377        }
168378      }
168379    }
168380    if( rc==SQLITE_OK ){
168381      rc = fixBoundingBox(pRtree, pNode);
168382    }
168383    for(; rc==SQLITE_OK && ii<nCell; ii++){
168384      /* Find a node to store this cell in. pNode->iNode currently contains
168385      ** the height of the sub-tree headed by the cell.
168386      */
168387      RtreeNode *pInsert;
168388      RtreeCell *p = &aCell[aOrder[ii]];
168389      rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
168390      if( rc==SQLITE_OK ){
168391        int rc2;
168392        rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
168393        rc2 = nodeRelease(pRtree, pInsert);
168394        if( rc==SQLITE_OK ){
168395          rc = rc2;
168396        }
168397      }
168398    }
168399  
168400    sqlite3_free(aCell);
168401    return rc;
168402  }
168403  
168404  /*
168405  ** Insert cell pCell into node pNode. Node pNode is the head of a 
168406  ** subtree iHeight high (leaf nodes have iHeight==0).
168407  */
168408  static int rtreeInsertCell(
168409    Rtree *pRtree,
168410    RtreeNode *pNode,
168411    RtreeCell *pCell,
168412    int iHeight
168413  ){
168414    int rc = SQLITE_OK;
168415    if( iHeight>0 ){
168416      RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
168417      if( pChild ){
168418        nodeRelease(pRtree, pChild->pParent);
168419        nodeReference(pNode);
168420        pChild->pParent = pNode;
168421      }
168422    }
168423    if( nodeInsertCell(pRtree, pNode, pCell) ){
168424      if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
168425        rc = SplitNode(pRtree, pNode, pCell, iHeight);
168426      }else{
168427        pRtree->iReinsertHeight = iHeight;
168428        rc = Reinsert(pRtree, pNode, pCell, iHeight);
168429      }
168430    }else{
168431      rc = AdjustTree(pRtree, pNode, pCell);
168432      if( rc==SQLITE_OK ){
168433        if( iHeight==0 ){
168434          rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
168435        }else{
168436          rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
168437        }
168438      }
168439    }
168440    return rc;
168441  }
168442  
168443  static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
168444    int ii;
168445    int rc = SQLITE_OK;
168446    int nCell = NCELL(pNode);
168447  
168448    for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
168449      RtreeNode *pInsert;
168450      RtreeCell cell;
168451      nodeGetCell(pRtree, pNode, ii, &cell);
168452  
168453      /* Find a node to store this cell in. pNode->iNode currently contains
168454      ** the height of the sub-tree headed by the cell.
168455      */
168456      rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
168457      if( rc==SQLITE_OK ){
168458        int rc2;
168459        rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
168460        rc2 = nodeRelease(pRtree, pInsert);
168461        if( rc==SQLITE_OK ){
168462          rc = rc2;
168463        }
168464      }
168465    }
168466    return rc;
168467  }
168468  
168469  /*
168470  ** Select a currently unused rowid for a new r-tree record.
168471  */
168472  static int newRowid(Rtree *pRtree, i64 *piRowid){
168473    int rc;
168474    sqlite3_bind_null(pRtree->pWriteRowid, 1);
168475    sqlite3_bind_null(pRtree->pWriteRowid, 2);
168476    sqlite3_step(pRtree->pWriteRowid);
168477    rc = sqlite3_reset(pRtree->pWriteRowid);
168478    *piRowid = sqlite3_last_insert_rowid(pRtree->db);
168479    return rc;
168480  }
168481  
168482  /*
168483  ** Remove the entry with rowid=iDelete from the r-tree structure.
168484  */
168485  static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
168486    int rc;                         /* Return code */
168487    RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
168488    int iCell;                      /* Index of iDelete cell in pLeaf */
168489    RtreeNode *pRoot = 0;           /* Root node of rtree structure */
168490  
168491  
168492    /* Obtain a reference to the root node to initialize Rtree.iDepth */
168493    rc = nodeAcquire(pRtree, 1, 0, &pRoot);
168494  
168495    /* Obtain a reference to the leaf node that contains the entry 
168496    ** about to be deleted. 
168497    */
168498    if( rc==SQLITE_OK ){
168499      rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
168500    }
168501  
168502    /* Delete the cell in question from the leaf node. */
168503    if( rc==SQLITE_OK ){
168504      int rc2;
168505      rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
168506      if( rc==SQLITE_OK ){
168507        rc = deleteCell(pRtree, pLeaf, iCell, 0);
168508      }
168509      rc2 = nodeRelease(pRtree, pLeaf);
168510      if( rc==SQLITE_OK ){
168511        rc = rc2;
168512      }
168513    }
168514  
168515    /* Delete the corresponding entry in the <rtree>_rowid table. */
168516    if( rc==SQLITE_OK ){
168517      sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
168518      sqlite3_step(pRtree->pDeleteRowid);
168519      rc = sqlite3_reset(pRtree->pDeleteRowid);
168520    }
168521  
168522    /* Check if the root node now has exactly one child. If so, remove
168523    ** it, schedule the contents of the child for reinsertion and 
168524    ** reduce the tree height by one.
168525    **
168526    ** This is equivalent to copying the contents of the child into
168527    ** the root node (the operation that Gutman's paper says to perform 
168528    ** in this scenario).
168529    */
168530    if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
168531      int rc2;
168532      RtreeNode *pChild;
168533      i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
168534      rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
168535      if( rc==SQLITE_OK ){
168536        rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
168537      }
168538      rc2 = nodeRelease(pRtree, pChild);
168539      if( rc==SQLITE_OK ) rc = rc2;
168540      if( rc==SQLITE_OK ){
168541        pRtree->iDepth--;
168542        writeInt16(pRoot->zData, pRtree->iDepth);
168543        pRoot->isDirty = 1;
168544      }
168545    }
168546  
168547    /* Re-insert the contents of any underfull nodes removed from the tree. */
168548    for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
168549      if( rc==SQLITE_OK ){
168550        rc = reinsertNodeContent(pRtree, pLeaf);
168551      }
168552      pRtree->pDeleted = pLeaf->pNext;
168553      sqlite3_free(pLeaf);
168554    }
168555  
168556    /* Release the reference to the root node. */
168557    if( rc==SQLITE_OK ){
168558      rc = nodeRelease(pRtree, pRoot);
168559    }else{
168560      nodeRelease(pRtree, pRoot);
168561    }
168562  
168563    return rc;
168564  }
168565  
168566  /*
168567  ** Rounding constants for float->double conversion.
168568  */
168569  #define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
168570  #define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
168571  
168572  #if !defined(SQLITE_RTREE_INT_ONLY)
168573  /*
168574  ** Convert an sqlite3_value into an RtreeValue (presumably a float)
168575  ** while taking care to round toward negative or positive, respectively.
168576  */
168577  static RtreeValue rtreeValueDown(sqlite3_value *v){
168578    double d = sqlite3_value_double(v);
168579    float f = (float)d;
168580    if( f>d ){
168581      f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
168582    }
168583    return f;
168584  }
168585  static RtreeValue rtreeValueUp(sqlite3_value *v){
168586    double d = sqlite3_value_double(v);
168587    float f = (float)d;
168588    if( f<d ){
168589      f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
168590    }
168591    return f;
168592  }
168593  #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
168594  
168595  /*
168596  ** A constraint has failed while inserting a row into an rtree table. 
168597  ** Assuming no OOM error occurs, this function sets the error message 
168598  ** (at pRtree->base.zErrMsg) to an appropriate value and returns
168599  ** SQLITE_CONSTRAINT.
168600  **
168601  ** Parameter iCol is the index of the leftmost column involved in the
168602  ** constraint failure. If it is 0, then the constraint that failed is
168603  ** the unique constraint on the id column. Otherwise, it is the rtree
168604  ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
168605  **
168606  ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
168607  */
168608  static int rtreeConstraintError(Rtree *pRtree, int iCol){
168609    sqlite3_stmt *pStmt = 0;
168610    char *zSql; 
168611    int rc;
168612  
168613    assert( iCol==0 || iCol%2 );
168614    zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
168615    if( zSql ){
168616      rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
168617    }else{
168618      rc = SQLITE_NOMEM;
168619    }
168620    sqlite3_free(zSql);
168621  
168622    if( rc==SQLITE_OK ){
168623      if( iCol==0 ){
168624        const char *zCol = sqlite3_column_name(pStmt, 0);
168625        pRtree->base.zErrMsg = sqlite3_mprintf(
168626            "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
168627        );
168628      }else{
168629        const char *zCol1 = sqlite3_column_name(pStmt, iCol);
168630        const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
168631        pRtree->base.zErrMsg = sqlite3_mprintf(
168632            "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
168633        );
168634      }
168635    }
168636  
168637    sqlite3_finalize(pStmt);
168638    return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
168639  }
168640  
168641  
168642  
168643  /*
168644  ** The xUpdate method for rtree module virtual tables.
168645  */
168646  static int rtreeUpdate(
168647    sqlite3_vtab *pVtab, 
168648    int nData, 
168649    sqlite3_value **azData, 
168650    sqlite_int64 *pRowid
168651  ){
168652    Rtree *pRtree = (Rtree *)pVtab;
168653    int rc = SQLITE_OK;
168654    RtreeCell cell;                 /* New cell to insert if nData>1 */
168655    int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
168656  
168657    rtreeReference(pRtree);
168658    assert(nData>=1);
168659  
168660    cell.iRowid = 0;  /* Used only to suppress a compiler warning */
168661  
168662    /* Constraint handling. A write operation on an r-tree table may return
168663    ** SQLITE_CONSTRAINT for two reasons:
168664    **
168665    **   1. A duplicate rowid value, or
168666    **   2. The supplied data violates the "x2>=x1" constraint.
168667    **
168668    ** In the first case, if the conflict-handling mode is REPLACE, then
168669    ** the conflicting row can be removed before proceeding. In the second
168670    ** case, SQLITE_CONSTRAINT must be returned regardless of the
168671    ** conflict-handling mode specified by the user.
168672    */
168673    if( nData>1 ){
168674      int ii;
168675  
168676      /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
168677      **
168678      ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
168679      ** with "column" that are interpreted as table constraints.
168680      ** Example:  CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
168681      ** This problem was discovered after years of use, so we silently ignore
168682      ** these kinds of misdeclared tables to avoid breaking any legacy.
168683      */
168684      assert( nData<=(pRtree->nDim2 + 3) );
168685  
168686  #ifndef SQLITE_RTREE_INT_ONLY
168687      if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
168688        for(ii=0; ii<nData-4; ii+=2){
168689          cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
168690          cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
168691          if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
168692            rc = rtreeConstraintError(pRtree, ii+1);
168693            goto constraint;
168694          }
168695        }
168696      }else
168697  #endif
168698      {
168699        for(ii=0; ii<nData-4; ii+=2){
168700          cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
168701          cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
168702          if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
168703            rc = rtreeConstraintError(pRtree, ii+1);
168704            goto constraint;
168705          }
168706        }
168707      }
168708  
168709      /* If a rowid value was supplied, check if it is already present in 
168710      ** the table. If so, the constraint has failed. */
168711      if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
168712        cell.iRowid = sqlite3_value_int64(azData[2]);
168713        if( sqlite3_value_type(azData[0])==SQLITE_NULL
168714         || sqlite3_value_int64(azData[0])!=cell.iRowid
168715        ){
168716          int steprc;
168717          sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
168718          steprc = sqlite3_step(pRtree->pReadRowid);
168719          rc = sqlite3_reset(pRtree->pReadRowid);
168720          if( SQLITE_ROW==steprc ){
168721            if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
168722              rc = rtreeDeleteRowid(pRtree, cell.iRowid);
168723            }else{
168724              rc = rtreeConstraintError(pRtree, 0);
168725              goto constraint;
168726            }
168727          }
168728        }
168729        bHaveRowid = 1;
168730      }
168731    }
168732  
168733    /* If azData[0] is not an SQL NULL value, it is the rowid of a
168734    ** record to delete from the r-tree table. The following block does
168735    ** just that.
168736    */
168737    if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
168738      rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
168739    }
168740  
168741    /* If the azData[] array contains more than one element, elements
168742    ** (azData[2]..azData[argc-1]) contain a new record to insert into
168743    ** the r-tree structure.
168744    */
168745    if( rc==SQLITE_OK && nData>1 ){
168746      /* Insert the new record into the r-tree */
168747      RtreeNode *pLeaf = 0;
168748  
168749      /* Figure out the rowid of the new row. */
168750      if( bHaveRowid==0 ){
168751        rc = newRowid(pRtree, &cell.iRowid);
168752      }
168753      *pRowid = cell.iRowid;
168754  
168755      if( rc==SQLITE_OK ){
168756        rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
168757      }
168758      if( rc==SQLITE_OK ){
168759        int rc2;
168760        pRtree->iReinsertHeight = -1;
168761        rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
168762        rc2 = nodeRelease(pRtree, pLeaf);
168763        if( rc==SQLITE_OK ){
168764          rc = rc2;
168765        }
168766      }
168767    }
168768  
168769  constraint:
168770    rtreeRelease(pRtree);
168771    return rc;
168772  }
168773  
168774  /*
168775  ** Called when a transaction starts.
168776  */
168777  static int rtreeBeginTransaction(sqlite3_vtab *pVtab){
168778    Rtree *pRtree = (Rtree *)pVtab;
168779    assert( pRtree->inWrTrans==0 );
168780    pRtree->inWrTrans++;
168781    return SQLITE_OK;
168782  }
168783  
168784  /*
168785  ** Called when a transaction completes (either by COMMIT or ROLLBACK).
168786  ** The sqlite3_blob object should be released at this point.
168787  */
168788  static int rtreeEndTransaction(sqlite3_vtab *pVtab){
168789    Rtree *pRtree = (Rtree *)pVtab;
168790    pRtree->inWrTrans = 0;
168791    nodeBlobReset(pRtree);
168792    return SQLITE_OK;
168793  }
168794  
168795  /*
168796  ** The xRename method for rtree module virtual tables.
168797  */
168798  static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
168799    Rtree *pRtree = (Rtree *)pVtab;
168800    int rc = SQLITE_NOMEM;
168801    char *zSql = sqlite3_mprintf(
168802      "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
168803      "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
168804      "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
168805      , pRtree->zDb, pRtree->zName, zNewName 
168806      , pRtree->zDb, pRtree->zName, zNewName 
168807      , pRtree->zDb, pRtree->zName, zNewName
168808    );
168809    if( zSql ){
168810      nodeBlobReset(pRtree);
168811      rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
168812      sqlite3_free(zSql);
168813    }
168814    return rc;
168815  }
168816  
168817  /*
168818  ** The xSavepoint method.
168819  **
168820  ** This module does not need to do anything to support savepoints. However,
168821  ** it uses this hook to close any open blob handle. This is done because a 
168822  ** DROP TABLE command - which fortunately always opens a savepoint - cannot 
168823  ** succeed if there are any open blob handles. i.e. if the blob handle were
168824  ** not closed here, the following would fail:
168825  **
168826  **   BEGIN;
168827  **     INSERT INTO rtree...
168828  **     DROP TABLE <tablename>;    -- Would fail with SQLITE_LOCKED
168829  **   COMMIT;
168830  */
168831  static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){
168832    Rtree *pRtree = (Rtree *)pVtab;
168833    int iwt = pRtree->inWrTrans;
168834    UNUSED_PARAMETER(iSavepoint);
168835    pRtree->inWrTrans = 0;
168836    nodeBlobReset(pRtree);
168837    pRtree->inWrTrans = iwt;
168838    return SQLITE_OK;
168839  }
168840  
168841  /*
168842  ** This function populates the pRtree->nRowEst variable with an estimate
168843  ** of the number of rows in the virtual table. If possible, this is based
168844  ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
168845  */
168846  static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
168847    const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
168848    char *zSql;
168849    sqlite3_stmt *p;
168850    int rc;
168851    i64 nRow = 0;
168852  
168853    rc = sqlite3_table_column_metadata(
168854        db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
168855    );
168856    if( rc!=SQLITE_OK ){
168857      pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
168858      return rc==SQLITE_ERROR ? SQLITE_OK : rc;
168859    }
168860    zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
168861    if( zSql==0 ){
168862      rc = SQLITE_NOMEM;
168863    }else{
168864      rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
168865      if( rc==SQLITE_OK ){
168866        if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
168867        rc = sqlite3_finalize(p);
168868      }else if( rc!=SQLITE_NOMEM ){
168869        rc = SQLITE_OK;
168870      }
168871  
168872      if( rc==SQLITE_OK ){
168873        if( nRow==0 ){
168874          pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
168875        }else{
168876          pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
168877        }
168878      }
168879      sqlite3_free(zSql);
168880    }
168881  
168882    return rc;
168883  }
168884  
168885  static sqlite3_module rtreeModule = {
168886    2,                          /* iVersion */
168887    rtreeCreate,                /* xCreate - create a table */
168888    rtreeConnect,               /* xConnect - connect to an existing table */
168889    rtreeBestIndex,             /* xBestIndex - Determine search strategy */
168890    rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
168891    rtreeDestroy,               /* xDestroy - Drop a table */
168892    rtreeOpen,                  /* xOpen - open a cursor */
168893    rtreeClose,                 /* xClose - close a cursor */
168894    rtreeFilter,                /* xFilter - configure scan constraints */
168895    rtreeNext,                  /* xNext - advance a cursor */
168896    rtreeEof,                   /* xEof */
168897    rtreeColumn,                /* xColumn - read data */
168898    rtreeRowid,                 /* xRowid - read data */
168899    rtreeUpdate,                /* xUpdate - write data */
168900    rtreeBeginTransaction,      /* xBegin - begin transaction */
168901    rtreeEndTransaction,        /* xSync - sync transaction */
168902    rtreeEndTransaction,        /* xCommit - commit transaction */
168903    rtreeEndTransaction,        /* xRollback - rollback transaction */
168904    0,                          /* xFindFunction - function overloading */
168905    rtreeRename,                /* xRename - rename the table */
168906    rtreeSavepoint,             /* xSavepoint */
168907    0,                          /* xRelease */
168908    0,                          /* xRollbackTo */
168909  };
168910  
168911  static int rtreeSqlInit(
168912    Rtree *pRtree, 
168913    sqlite3 *db, 
168914    const char *zDb, 
168915    const char *zPrefix, 
168916    int isCreate
168917  ){
168918    int rc = SQLITE_OK;
168919  
168920    #define N_STATEMENT 8
168921    static const char *azSql[N_STATEMENT] = {
168922      /* Write the xxx_node table */
168923      "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
168924      "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
168925  
168926      /* Read and write the xxx_rowid table */
168927      "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
168928      "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
168929      "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
168930  
168931      /* Read and write the xxx_parent table */
168932      "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
168933      "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
168934      "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
168935    };
168936    sqlite3_stmt **appStmt[N_STATEMENT];
168937    int i;
168938  
168939    pRtree->db = db;
168940  
168941    if( isCreate ){
168942      char *zCreate = sqlite3_mprintf(
168943  "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
168944  "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
168945  "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
168946                                    " parentnode INTEGER);"
168947  "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
168948        zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
168949      );
168950      if( !zCreate ){
168951        return SQLITE_NOMEM;
168952      }
168953      rc = sqlite3_exec(db, zCreate, 0, 0, 0);
168954      sqlite3_free(zCreate);
168955      if( rc!=SQLITE_OK ){
168956        return rc;
168957      }
168958    }
168959  
168960    appStmt[0] = &pRtree->pWriteNode;
168961    appStmt[1] = &pRtree->pDeleteNode;
168962    appStmt[2] = &pRtree->pReadRowid;
168963    appStmt[3] = &pRtree->pWriteRowid;
168964    appStmt[4] = &pRtree->pDeleteRowid;
168965    appStmt[5] = &pRtree->pReadParent;
168966    appStmt[6] = &pRtree->pWriteParent;
168967    appStmt[7] = &pRtree->pDeleteParent;
168968  
168969    rc = rtreeQueryStat1(db, pRtree);
168970    for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
168971      char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
168972      if( zSql ){
168973        rc = sqlite3_prepare_v3(db, zSql, -1, SQLITE_PREPARE_PERSISTENT,
168974                                appStmt[i], 0); 
168975      }else{
168976        rc = SQLITE_NOMEM;
168977      }
168978      sqlite3_free(zSql);
168979    }
168980  
168981    return rc;
168982  }
168983  
168984  /*
168985  ** The second argument to this function contains the text of an SQL statement
168986  ** that returns a single integer value. The statement is compiled and executed
168987  ** using database connection db. If successful, the integer value returned
168988  ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
168989  ** code is returned and the value of *piVal after returning is not defined.
168990  */
168991  static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
168992    int rc = SQLITE_NOMEM;
168993    if( zSql ){
168994      sqlite3_stmt *pStmt = 0;
168995      rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
168996      if( rc==SQLITE_OK ){
168997        if( SQLITE_ROW==sqlite3_step(pStmt) ){
168998          *piVal = sqlite3_column_int(pStmt, 0);
168999        }
169000        rc = sqlite3_finalize(pStmt);
169001      }
169002    }
169003    return rc;
169004  }
169005  
169006  /*
169007  ** This function is called from within the xConnect() or xCreate() method to
169008  ** determine the node-size used by the rtree table being created or connected
169009  ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
169010  ** Otherwise, an SQLite error code is returned.
169011  **
169012  ** If this function is being called as part of an xConnect(), then the rtree
169013  ** table already exists. In this case the node-size is determined by inspecting
169014  ** the root node of the tree.
169015  **
169016  ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
169017  ** This ensures that each node is stored on a single database page. If the 
169018  ** database page-size is so large that more than RTREE_MAXCELLS entries 
169019  ** would fit in a single node, use a smaller node-size.
169020  */
169021  static int getNodeSize(
169022    sqlite3 *db,                    /* Database handle */
169023    Rtree *pRtree,                  /* Rtree handle */
169024    int isCreate,                   /* True for xCreate, false for xConnect */
169025    char **pzErr                    /* OUT: Error message, if any */
169026  ){
169027    int rc;
169028    char *zSql;
169029    if( isCreate ){
169030      int iPageSize = 0;
169031      zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
169032      rc = getIntFromStmt(db, zSql, &iPageSize);
169033      if( rc==SQLITE_OK ){
169034        pRtree->iNodeSize = iPageSize-64;
169035        if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
169036          pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
169037        }
169038      }else{
169039        *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
169040      }
169041    }else{
169042      zSql = sqlite3_mprintf(
169043          "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
169044          pRtree->zDb, pRtree->zName
169045      );
169046      rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
169047      if( rc!=SQLITE_OK ){
169048        *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
169049      }else if( pRtree->iNodeSize<(512-64) ){
169050        rc = SQLITE_CORRUPT_VTAB;
169051        *pzErr = sqlite3_mprintf("undersize RTree blobs in \"%q_node\"",
169052                                 pRtree->zName);
169053      }
169054    }
169055  
169056    sqlite3_free(zSql);
169057    return rc;
169058  }
169059  
169060  /* 
169061  ** This function is the implementation of both the xConnect and xCreate
169062  ** methods of the r-tree virtual table.
169063  **
169064  **   argv[0]   -> module name
169065  **   argv[1]   -> database name
169066  **   argv[2]   -> table name
169067  **   argv[...] -> column names...
169068  */
169069  static int rtreeInit(
169070    sqlite3 *db,                        /* Database connection */
169071    void *pAux,                         /* One of the RTREE_COORD_* constants */
169072    int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
169073    sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
169074    char **pzErr,                       /* OUT: Error message, if any */
169075    int isCreate                        /* True for xCreate, false for xConnect */
169076  ){
169077    int rc = SQLITE_OK;
169078    Rtree *pRtree;
169079    int nDb;              /* Length of string argv[1] */
169080    int nName;            /* Length of string argv[2] */
169081    int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
169082  
169083    const char *aErrMsg[] = {
169084      0,                                                    /* 0 */
169085      "Wrong number of columns for an rtree table",         /* 1 */
169086      "Too few columns for an rtree table",                 /* 2 */
169087      "Too many columns for an rtree table"                 /* 3 */
169088    };
169089  
169090    int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
169091    if( aErrMsg[iErr] ){
169092      *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
169093      return SQLITE_ERROR;
169094    }
169095  
169096    sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
169097  
169098    /* Allocate the sqlite3_vtab structure */
169099    nDb = (int)strlen(argv[1]);
169100    nName = (int)strlen(argv[2]);
169101    pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
169102    if( !pRtree ){
169103      return SQLITE_NOMEM;
169104    }
169105    memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
169106    pRtree->nBusy = 1;
169107    pRtree->base.pModule = &rtreeModule;
169108    pRtree->zDb = (char *)&pRtree[1];
169109    pRtree->zName = &pRtree->zDb[nDb+1];
169110    pRtree->nDim = (u8)((argc-4)/2);
169111    pRtree->nDim2 = pRtree->nDim*2;
169112    pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
169113    pRtree->eCoordType = (u8)eCoordType;
169114    memcpy(pRtree->zDb, argv[1], nDb);
169115    memcpy(pRtree->zName, argv[2], nName);
169116  
169117    /* Figure out the node size to use. */
169118    rc = getNodeSize(db, pRtree, isCreate, pzErr);
169119  
169120    /* Create/Connect to the underlying relational database schema. If
169121    ** that is successful, call sqlite3_declare_vtab() to configure
169122    ** the r-tree table schema.
169123    */
169124    if( rc==SQLITE_OK ){
169125      if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
169126        *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
169127      }else{
169128        char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
169129        char *zTmp;
169130        int ii;
169131        for(ii=4; zSql && ii<argc; ii++){
169132          zTmp = zSql;
169133          zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
169134          sqlite3_free(zTmp);
169135        }
169136        if( zSql ){
169137          zTmp = zSql;
169138          zSql = sqlite3_mprintf("%s);", zTmp);
169139          sqlite3_free(zTmp);
169140        }
169141        if( !zSql ){
169142          rc = SQLITE_NOMEM;
169143        }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
169144          *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
169145        }
169146        sqlite3_free(zSql);
169147      }
169148    }
169149  
169150    if( rc==SQLITE_OK ){
169151      *ppVtab = (sqlite3_vtab *)pRtree;
169152    }else{
169153      assert( *ppVtab==0 );
169154      assert( pRtree->nBusy==1 );
169155      rtreeRelease(pRtree);
169156    }
169157    return rc;
169158  }
169159  
169160  
169161  /*
169162  ** Implementation of a scalar function that decodes r-tree nodes to
169163  ** human readable strings. This can be used for debugging and analysis.
169164  **
169165  ** The scalar function takes two arguments: (1) the number of dimensions
169166  ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
169167  ** an r-tree node.  For a two-dimensional r-tree structure called "rt", to
169168  ** deserialize all nodes, a statement like:
169169  **
169170  **   SELECT rtreenode(2, data) FROM rt_node;
169171  **
169172  ** The human readable string takes the form of a Tcl list with one
169173  ** entry for each cell in the r-tree node. Each entry is itself a
169174  ** list, containing the 8-byte rowid/pageno followed by the 
169175  ** <num-dimension>*2 coordinates.
169176  */
169177  static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
169178    char *zText = 0;
169179    RtreeNode node;
169180    Rtree tree;
169181    int ii;
169182  
169183    UNUSED_PARAMETER(nArg);
169184    memset(&node, 0, sizeof(RtreeNode));
169185    memset(&tree, 0, sizeof(Rtree));
169186    tree.nDim = (u8)sqlite3_value_int(apArg[0]);
169187    tree.nDim2 = tree.nDim*2;
169188    tree.nBytesPerCell = 8 + 8 * tree.nDim;
169189    node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
169190  
169191    for(ii=0; ii<NCELL(&node); ii++){
169192      char zCell[512];
169193      int nCell = 0;
169194      RtreeCell cell;
169195      int jj;
169196  
169197      nodeGetCell(&tree, &node, ii, &cell);
169198      sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
169199      nCell = (int)strlen(zCell);
169200      for(jj=0; jj<tree.nDim2; jj++){
169201  #ifndef SQLITE_RTREE_INT_ONLY
169202        sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
169203                         (double)cell.aCoord[jj].f);
169204  #else
169205        sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
169206                         cell.aCoord[jj].i);
169207  #endif
169208        nCell = (int)strlen(zCell);
169209      }
169210  
169211      if( zText ){
169212        char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
169213        sqlite3_free(zText);
169214        zText = zTextNew;
169215      }else{
169216        zText = sqlite3_mprintf("{%s}", zCell);
169217      }
169218    }
169219    
169220    sqlite3_result_text(ctx, zText, -1, sqlite3_free);
169221  }
169222  
169223  /* This routine implements an SQL function that returns the "depth" parameter
169224  ** from the front of a blob that is an r-tree node.  For example:
169225  **
169226  **     SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
169227  **
169228  ** The depth value is 0 for all nodes other than the root node, and the root
169229  ** node always has nodeno=1, so the example above is the primary use for this
169230  ** routine.  This routine is intended for testing and analysis only.
169231  */
169232  static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
169233    UNUSED_PARAMETER(nArg);
169234    if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
169235     || sqlite3_value_bytes(apArg[0])<2
169236    ){
169237      sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
169238    }else{
169239      u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
169240      sqlite3_result_int(ctx, readInt16(zBlob));
169241    }
169242  }
169243  
169244  /*
169245  ** Register the r-tree module with database handle db. This creates the
169246  ** virtual table module "rtree" and the debugging/analysis scalar 
169247  ** function "rtreenode".
169248  */
169249  SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
169250    const int utf8 = SQLITE_UTF8;
169251    int rc;
169252  
169253    rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
169254    if( rc==SQLITE_OK ){
169255      rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
169256    }
169257    if( rc==SQLITE_OK ){
169258  #ifdef SQLITE_RTREE_INT_ONLY
169259      void *c = (void *)RTREE_COORD_INT32;
169260  #else
169261      void *c = (void *)RTREE_COORD_REAL32;
169262  #endif
169263      rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
169264    }
169265    if( rc==SQLITE_OK ){
169266      void *c = (void *)RTREE_COORD_INT32;
169267      rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
169268    }
169269  
169270    return rc;
169271  }
169272  
169273  /*
169274  ** This routine deletes the RtreeGeomCallback object that was attached
169275  ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
169276  ** or sqlite3_rtree_query_callback().  In other words, this routine is the
169277  ** destructor for an RtreeGeomCallback objecct.  This routine is called when
169278  ** the corresponding SQL function is deleted.
169279  */
169280  static void rtreeFreeCallback(void *p){
169281    RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
169282    if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
169283    sqlite3_free(p);
169284  }
169285  
169286  /*
169287  ** This routine frees the BLOB that is returned by geomCallback().
169288  */
169289  static void rtreeMatchArgFree(void *pArg){
169290    int i;
169291    RtreeMatchArg *p = (RtreeMatchArg*)pArg;
169292    for(i=0; i<p->nParam; i++){
169293      sqlite3_value_free(p->apSqlParam[i]);
169294    }
169295    sqlite3_free(p);
169296  }
169297  
169298  /*
169299  ** Each call to sqlite3_rtree_geometry_callback() or
169300  ** sqlite3_rtree_query_callback() creates an ordinary SQLite
169301  ** scalar function that is implemented by this routine.
169302  **
169303  ** All this function does is construct an RtreeMatchArg object that
169304  ** contains the geometry-checking callback routines and a list of
169305  ** parameters to this function, then return that RtreeMatchArg object
169306  ** as a BLOB.
169307  **
169308  ** The R-Tree MATCH operator will read the returned BLOB, deserialize
169309  ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
169310  ** out which elements of the R-Tree should be returned by the query.
169311  */
169312  static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
169313    RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
169314    RtreeMatchArg *pBlob;
169315    int nBlob;
169316    int memErr = 0;
169317  
169318    nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
169319             + nArg*sizeof(sqlite3_value*);
169320    pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
169321    if( !pBlob ){
169322      sqlite3_result_error_nomem(ctx);
169323    }else{
169324      int i;
169325      pBlob->iSize = nBlob;
169326      pBlob->cb = pGeomCtx[0];
169327      pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
169328      pBlob->nParam = nArg;
169329      for(i=0; i<nArg; i++){
169330        pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
169331        if( pBlob->apSqlParam[i]==0 ) memErr = 1;
169332  #ifdef SQLITE_RTREE_INT_ONLY
169333        pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
169334  #else
169335        pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
169336  #endif
169337      }
169338      if( memErr ){
169339        sqlite3_result_error_nomem(ctx);
169340        rtreeMatchArgFree(pBlob);
169341      }else{
169342        sqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree);
169343      }
169344    }
169345  }
169346  
169347  /*
169348  ** Register a new geometry function for use with the r-tree MATCH operator.
169349  */
169350  SQLITE_API int sqlite3_rtree_geometry_callback(
169351    sqlite3 *db,                  /* Register SQL function on this connection */
169352    const char *zGeom,            /* Name of the new SQL function */
169353    int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
169354    void *pContext                /* Extra data associated with the callback */
169355  ){
169356    RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
169357  
169358    /* Allocate and populate the context object. */
169359    pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
169360    if( !pGeomCtx ) return SQLITE_NOMEM;
169361    pGeomCtx->xGeom = xGeom;
169362    pGeomCtx->xQueryFunc = 0;
169363    pGeomCtx->xDestructor = 0;
169364    pGeomCtx->pContext = pContext;
169365    return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, 
169366        (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
169367    );
169368  }
169369  
169370  /*
169371  ** Register a new 2nd-generation geometry function for use with the
169372  ** r-tree MATCH operator.
169373  */
169374  SQLITE_API int sqlite3_rtree_query_callback(
169375    sqlite3 *db,                 /* Register SQL function on this connection */
169376    const char *zQueryFunc,      /* Name of new SQL function */
169377    int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
169378    void *pContext,              /* Extra data passed into the callback */
169379    void (*xDestructor)(void*)   /* Destructor for the extra data */
169380  ){
169381    RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
169382  
169383    /* Allocate and populate the context object. */
169384    pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
169385    if( !pGeomCtx ) return SQLITE_NOMEM;
169386    pGeomCtx->xGeom = 0;
169387    pGeomCtx->xQueryFunc = xQueryFunc;
169388    pGeomCtx->xDestructor = xDestructor;
169389    pGeomCtx->pContext = pContext;
169390    return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY, 
169391        (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
169392    );
169393  }
169394  
169395  #if !SQLITE_CORE
169396  #ifdef _WIN32
169397  __declspec(dllexport)
169398  #endif
169399  SQLITE_API int sqlite3_rtree_init(
169400    sqlite3 *db,
169401    char **pzErrMsg,
169402    const sqlite3_api_routines *pApi
169403  ){
169404    SQLITE_EXTENSION_INIT2(pApi)
169405    return sqlite3RtreeInit(db);
169406  }
169407  #endif
169408  
169409  #endif
169410  
169411  /************** End of rtree.c ***********************************************/
169412  /************** Begin file icu.c *********************************************/
169413  /*
169414  ** 2007 May 6
169415  **
169416  ** The author disclaims copyright to this source code.  In place of
169417  ** a legal notice, here is a blessing:
169418  **
169419  **    May you do good and not evil.
169420  **    May you find forgiveness for yourself and forgive others.
169421  **    May you share freely, never taking more than you give.
169422  **
169423  *************************************************************************
169424  ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
169425  **
169426  ** This file implements an integration between the ICU library 
169427  ** ("International Components for Unicode", an open-source library 
169428  ** for handling unicode data) and SQLite. The integration uses 
169429  ** ICU to provide the following to SQLite:
169430  **
169431  **   * An implementation of the SQL regexp() function (and hence REGEXP
169432  **     operator) using the ICU uregex_XX() APIs.
169433  **
169434  **   * Implementations of the SQL scalar upper() and lower() functions
169435  **     for case mapping.
169436  **
169437  **   * Integration of ICU and SQLite collation sequences.
169438  **
169439  **   * An implementation of the LIKE operator that uses ICU to 
169440  **     provide case-independent matching.
169441  */
169442  
169443  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
169444  
169445  /* Include ICU headers */
169446  #include <unicode/utypes.h>
169447  #include <unicode/uregex.h>
169448  #include <unicode/ustring.h>
169449  #include <unicode/ucol.h>
169450  
169451  /* #include <assert.h> */
169452  
169453  #ifndef SQLITE_CORE
169454  /*   #include "sqlite3ext.h" */
169455    SQLITE_EXTENSION_INIT1
169456  #else
169457  /*   #include "sqlite3.h" */
169458  #endif
169459  
169460  /*
169461  ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
169462  ** operator.
169463  */
169464  #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
169465  # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
169466  #endif
169467  
169468  /*
169469  ** Version of sqlite3_free() that is always a function, never a macro.
169470  */
169471  static void xFree(void *p){
169472    sqlite3_free(p);
169473  }
169474  
169475  /*
169476  ** This lookup table is used to help decode the first byte of
169477  ** a multi-byte UTF8 character. It is copied here from SQLite source
169478  ** code file utf8.c.
169479  */
169480  static const unsigned char icuUtf8Trans1[] = {
169481    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
169482    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
169483    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
169484    0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
169485    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
169486    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
169487    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
169488    0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
169489  };
169490  
169491  #define SQLITE_ICU_READ_UTF8(zIn, c)                       \
169492    c = *(zIn++);                                            \
169493    if( c>=0xc0 ){                                           \
169494      c = icuUtf8Trans1[c-0xc0];                             \
169495      while( (*zIn & 0xc0)==0x80 ){                          \
169496        c = (c<<6) + (0x3f & *(zIn++));                      \
169497      }                                                      \
169498    }
169499  
169500  #define SQLITE_ICU_SKIP_UTF8(zIn)                          \
169501    assert( *zIn );                                          \
169502    if( *(zIn++)>=0xc0 ){                                    \
169503      while( (*zIn & 0xc0)==0x80 ){zIn++;}                   \
169504    }
169505  
169506  
169507  /*
169508  ** Compare two UTF-8 strings for equality where the first string is
169509  ** a "LIKE" expression. Return true (1) if they are the same and 
169510  ** false (0) if they are different.
169511  */
169512  static int icuLikeCompare(
169513    const uint8_t *zPattern,   /* LIKE pattern */
169514    const uint8_t *zString,    /* The UTF-8 string to compare against */
169515    const UChar32 uEsc         /* The escape character */
169516  ){
169517    static const uint32_t MATCH_ONE = (uint32_t)'_';
169518    static const uint32_t MATCH_ALL = (uint32_t)'%';
169519  
169520    int prevEscape = 0;     /* True if the previous character was uEsc */
169521  
169522    while( 1 ){
169523  
169524      /* Read (and consume) the next character from the input pattern. */
169525      uint32_t uPattern;
169526      SQLITE_ICU_READ_UTF8(zPattern, uPattern);
169527      if( uPattern==0 ) break;
169528  
169529      /* There are now 4 possibilities:
169530      **
169531      **     1. uPattern is an unescaped match-all character "%",
169532      **     2. uPattern is an unescaped match-one character "_",
169533      **     3. uPattern is an unescaped escape character, or
169534      **     4. uPattern is to be handled as an ordinary character
169535      */
169536      if( !prevEscape && uPattern==MATCH_ALL ){
169537        /* Case 1. */
169538        uint8_t c;
169539  
169540        /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
169541        ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
169542        ** test string.
169543        */
169544        while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
169545          if( c==MATCH_ONE ){
169546            if( *zString==0 ) return 0;
169547            SQLITE_ICU_SKIP_UTF8(zString);
169548          }
169549          zPattern++;
169550        }
169551  
169552        if( *zPattern==0 ) return 1;
169553  
169554        while( *zString ){
169555          if( icuLikeCompare(zPattern, zString, uEsc) ){
169556            return 1;
169557          }
169558          SQLITE_ICU_SKIP_UTF8(zString);
169559        }
169560        return 0;
169561  
169562      }else if( !prevEscape && uPattern==MATCH_ONE ){
169563        /* Case 2. */
169564        if( *zString==0 ) return 0;
169565        SQLITE_ICU_SKIP_UTF8(zString);
169566  
169567      }else if( !prevEscape && uPattern==(uint32_t)uEsc){
169568        /* Case 3. */
169569        prevEscape = 1;
169570  
169571      }else{
169572        /* Case 4. */
169573        uint32_t uString;
169574        SQLITE_ICU_READ_UTF8(zString, uString);
169575        uString = (uint32_t)u_foldCase((UChar32)uString, U_FOLD_CASE_DEFAULT);
169576        uPattern = (uint32_t)u_foldCase((UChar32)uPattern, U_FOLD_CASE_DEFAULT);
169577        if( uString!=uPattern ){
169578          return 0;
169579        }
169580        prevEscape = 0;
169581      }
169582    }
169583  
169584    return *zString==0;
169585  }
169586  
169587  /*
169588  ** Implementation of the like() SQL function.  This function implements
169589  ** the build-in LIKE operator.  The first argument to the function is the
169590  ** pattern and the second argument is the string.  So, the SQL statements:
169591  **
169592  **       A LIKE B
169593  **
169594  ** is implemented as like(B, A). If there is an escape character E, 
169595  **
169596  **       A LIKE B ESCAPE E
169597  **
169598  ** is mapped to like(B, A, E).
169599  */
169600  static void icuLikeFunc(
169601    sqlite3_context *context, 
169602    int argc, 
169603    sqlite3_value **argv
169604  ){
169605    const unsigned char *zA = sqlite3_value_text(argv[0]);
169606    const unsigned char *zB = sqlite3_value_text(argv[1]);
169607    UChar32 uEsc = 0;
169608  
169609    /* Limit the length of the LIKE or GLOB pattern to avoid problems
169610    ** of deep recursion and N*N behavior in patternCompare().
169611    */
169612    if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
169613      sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
169614      return;
169615    }
169616  
169617  
169618    if( argc==3 ){
169619      /* The escape character string must consist of a single UTF-8 character.
169620      ** Otherwise, return an error.
169621      */
169622      int nE= sqlite3_value_bytes(argv[2]);
169623      const unsigned char *zE = sqlite3_value_text(argv[2]);
169624      int i = 0;
169625      if( zE==0 ) return;
169626      U8_NEXT(zE, i, nE, uEsc);
169627      if( i!=nE){
169628        sqlite3_result_error(context, 
169629            "ESCAPE expression must be a single character", -1);
169630        return;
169631      }
169632    }
169633  
169634    if( zA && zB ){
169635      sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
169636    }
169637  }
169638  
169639  /*
169640  ** This function is called when an ICU function called from within
169641  ** the implementation of an SQL scalar function returns an error.
169642  **
169643  ** The scalar function context passed as the first argument is 
169644  ** loaded with an error message based on the following two args.
169645  */
169646  static void icuFunctionError(
169647    sqlite3_context *pCtx,       /* SQLite scalar function context */
169648    const char *zName,           /* Name of ICU function that failed */
169649    UErrorCode e                 /* Error code returned by ICU function */
169650  ){
169651    char zBuf[128];
169652    sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
169653    zBuf[127] = '\0';
169654    sqlite3_result_error(pCtx, zBuf, -1);
169655  }
169656  
169657  /*
169658  ** Function to delete compiled regexp objects. Registered as
169659  ** a destructor function with sqlite3_set_auxdata().
169660  */
169661  static void icuRegexpDelete(void *p){
169662    URegularExpression *pExpr = (URegularExpression *)p;
169663    uregex_close(pExpr);
169664  }
169665  
169666  /*
169667  ** Implementation of SQLite REGEXP operator. This scalar function takes
169668  ** two arguments. The first is a regular expression pattern to compile
169669  ** the second is a string to match against that pattern. If either 
169670  ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
169671  ** is 1 if the string matches the pattern, or 0 otherwise.
169672  **
169673  ** SQLite maps the regexp() function to the regexp() operator such
169674  ** that the following two are equivalent:
169675  **
169676  **     zString REGEXP zPattern
169677  **     regexp(zPattern, zString)
169678  **
169679  ** Uses the following ICU regexp APIs:
169680  **
169681  **     uregex_open()
169682  **     uregex_matches()
169683  **     uregex_close()
169684  */
169685  static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
169686    UErrorCode status = U_ZERO_ERROR;
169687    URegularExpression *pExpr;
169688    UBool res;
169689    const UChar *zString = sqlite3_value_text16(apArg[1]);
169690  
169691    (void)nArg;  /* Unused parameter */
169692  
169693    /* If the left hand side of the regexp operator is NULL, 
169694    ** then the result is also NULL. 
169695    */
169696    if( !zString ){
169697      return;
169698    }
169699  
169700    pExpr = sqlite3_get_auxdata(p, 0);
169701    if( !pExpr ){
169702      const UChar *zPattern = sqlite3_value_text16(apArg[0]);
169703      if( !zPattern ){
169704        return;
169705      }
169706      pExpr = uregex_open(zPattern, -1, 0, 0, &status);
169707  
169708      if( U_SUCCESS(status) ){
169709        sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
169710      }else{
169711        assert(!pExpr);
169712        icuFunctionError(p, "uregex_open", status);
169713        return;
169714      }
169715    }
169716  
169717    /* Configure the text that the regular expression operates on. */
169718    uregex_setText(pExpr, zString, -1, &status);
169719    if( !U_SUCCESS(status) ){
169720      icuFunctionError(p, "uregex_setText", status);
169721      return;
169722    }
169723  
169724    /* Attempt the match */
169725    res = uregex_matches(pExpr, 0, &status);
169726    if( !U_SUCCESS(status) ){
169727      icuFunctionError(p, "uregex_matches", status);
169728      return;
169729    }
169730  
169731    /* Set the text that the regular expression operates on to a NULL
169732    ** pointer. This is not really necessary, but it is tidier than 
169733    ** leaving the regular expression object configured with an invalid
169734    ** pointer after this function returns.
169735    */
169736    uregex_setText(pExpr, 0, 0, &status);
169737  
169738    /* Return 1 or 0. */
169739    sqlite3_result_int(p, res ? 1 : 0);
169740  }
169741  
169742  /*
169743  ** Implementations of scalar functions for case mapping - upper() and 
169744  ** lower(). Function upper() converts its input to upper-case (ABC).
169745  ** Function lower() converts to lower-case (abc).
169746  **
169747  ** ICU provides two types of case mapping, "general" case mapping and
169748  ** "language specific". Refer to ICU documentation for the differences
169749  ** between the two.
169750  **
169751  ** To utilise "general" case mapping, the upper() or lower() scalar 
169752  ** functions are invoked with one argument:
169753  **
169754  **     upper('ABC') -> 'abc'
169755  **     lower('abc') -> 'ABC'
169756  **
169757  ** To access ICU "language specific" case mapping, upper() or lower()
169758  ** should be invoked with two arguments. The second argument is the name
169759  ** of the locale to use. Passing an empty string ("") or SQL NULL value
169760  ** as the second argument is the same as invoking the 1 argument version
169761  ** of upper() or lower().
169762  **
169763  **     lower('I', 'en_us') -> 'i'
169764  **     lower('I', 'tr_tr') -> '\u131' (small dotless i)
169765  **
169766  ** http://www.icu-project.org/userguide/posix.html#case_mappings
169767  */
169768  static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
169769    const UChar *zInput;            /* Pointer to input string */
169770    UChar *zOutput = 0;             /* Pointer to output buffer */
169771    int nInput;                     /* Size of utf-16 input string in bytes */
169772    int nOut;                       /* Size of output buffer in bytes */
169773    int cnt;
169774    int bToUpper;                   /* True for toupper(), false for tolower() */
169775    UErrorCode status;
169776    const char *zLocale = 0;
169777  
169778    assert(nArg==1 || nArg==2);
169779    bToUpper = (sqlite3_user_data(p)!=0);
169780    if( nArg==2 ){
169781      zLocale = (const char *)sqlite3_value_text(apArg[1]);
169782    }
169783  
169784    zInput = sqlite3_value_text16(apArg[0]);
169785    if( !zInput ){
169786      return;
169787    }
169788    nOut = nInput = sqlite3_value_bytes16(apArg[0]);
169789    if( nOut==0 ){
169790      sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
169791      return;
169792    }
169793  
169794    for(cnt=0; cnt<2; cnt++){
169795      UChar *zNew = sqlite3_realloc(zOutput, nOut);
169796      if( zNew==0 ){
169797        sqlite3_free(zOutput);
169798        sqlite3_result_error_nomem(p);
169799        return;
169800      }
169801      zOutput = zNew;
169802      status = U_ZERO_ERROR;
169803      if( bToUpper ){
169804        nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
169805      }else{
169806        nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
169807      }
169808  
169809      if( U_SUCCESS(status) ){
169810        sqlite3_result_text16(p, zOutput, nOut, xFree);
169811      }else if( status==U_BUFFER_OVERFLOW_ERROR ){
169812        assert( cnt==0 );
169813        continue;
169814      }else{
169815        icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
169816      }
169817      return;
169818    }
169819    assert( 0 );     /* Unreachable */
169820  }
169821  
169822  /*
169823  ** Collation sequence destructor function. The pCtx argument points to
169824  ** a UCollator structure previously allocated using ucol_open().
169825  */
169826  static void icuCollationDel(void *pCtx){
169827    UCollator *p = (UCollator *)pCtx;
169828    ucol_close(p);
169829  }
169830  
169831  /*
169832  ** Collation sequence comparison function. The pCtx argument points to
169833  ** a UCollator structure previously allocated using ucol_open().
169834  */
169835  static int icuCollationColl(
169836    void *pCtx,
169837    int nLeft,
169838    const void *zLeft,
169839    int nRight,
169840    const void *zRight
169841  ){
169842    UCollationResult res;
169843    UCollator *p = (UCollator *)pCtx;
169844    res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
169845    switch( res ){
169846      case UCOL_LESS:    return -1;
169847      case UCOL_GREATER: return +1;
169848      case UCOL_EQUAL:   return 0;
169849    }
169850    assert(!"Unexpected return value from ucol_strcoll()");
169851    return 0;
169852  }
169853  
169854  /*
169855  ** Implementation of the scalar function icu_load_collation().
169856  **
169857  ** This scalar function is used to add ICU collation based collation 
169858  ** types to an SQLite database connection. It is intended to be called
169859  ** as follows:
169860  **
169861  **     SELECT icu_load_collation(<locale>, <collation-name>);
169862  **
169863  ** Where <locale> is a string containing an ICU locale identifier (i.e.
169864  ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
169865  ** collation sequence to create.
169866  */
169867  static void icuLoadCollation(
169868    sqlite3_context *p, 
169869    int nArg, 
169870    sqlite3_value **apArg
169871  ){
169872    sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
169873    UErrorCode status = U_ZERO_ERROR;
169874    const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
169875    const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
169876    UCollator *pUCollator;    /* ICU library collation object */
169877    int rc;                   /* Return code from sqlite3_create_collation_x() */
169878  
169879    assert(nArg==2);
169880    (void)nArg; /* Unused parameter */
169881    zLocale = (const char *)sqlite3_value_text(apArg[0]);
169882    zName = (const char *)sqlite3_value_text(apArg[1]);
169883  
169884    if( !zLocale || !zName ){
169885      return;
169886    }
169887  
169888    pUCollator = ucol_open(zLocale, &status);
169889    if( !U_SUCCESS(status) ){
169890      icuFunctionError(p, "ucol_open", status);
169891      return;
169892    }
169893    assert(p);
169894  
169895    rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
169896        icuCollationColl, icuCollationDel
169897    );
169898    if( rc!=SQLITE_OK ){
169899      ucol_close(pUCollator);
169900      sqlite3_result_error(p, "Error registering collation function", -1);
169901    }
169902  }
169903  
169904  /*
169905  ** Register the ICU extension functions with database db.
169906  */
169907  SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
169908    static const struct IcuScalar {
169909      const char *zName;                        /* Function name */
169910      unsigned char nArg;                       /* Number of arguments */
169911      unsigned short enc;                       /* Optimal text encoding */
169912      unsigned char iContext;                   /* sqlite3_user_data() context */
169913      void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
169914    } scalars[] = {
169915      {"icu_load_collation",  2, SQLITE_UTF8,                1, icuLoadCollation},
169916      {"regexp", 2, SQLITE_ANY|SQLITE_DETERMINISTIC,         0, icuRegexpFunc},
169917      {"lower",  1, SQLITE_UTF16|SQLITE_DETERMINISTIC,       0, icuCaseFunc16},
169918      {"lower",  2, SQLITE_UTF16|SQLITE_DETERMINISTIC,       0, icuCaseFunc16},
169919      {"upper",  1, SQLITE_UTF16|SQLITE_DETERMINISTIC,       1, icuCaseFunc16},
169920      {"upper",  2, SQLITE_UTF16|SQLITE_DETERMINISTIC,       1, icuCaseFunc16},
169921      {"lower",  1, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuCaseFunc16},
169922      {"lower",  2, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuCaseFunc16},
169923      {"upper",  1, SQLITE_UTF8|SQLITE_DETERMINISTIC,        1, icuCaseFunc16},
169924      {"upper",  2, SQLITE_UTF8|SQLITE_DETERMINISTIC,        1, icuCaseFunc16},
169925      {"like",   2, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuLikeFunc},
169926      {"like",   3, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuLikeFunc},
169927    };
169928    int rc = SQLITE_OK;
169929    int i;
169930  
169931    
169932    for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
169933      const struct IcuScalar *p = &scalars[i];
169934      rc = sqlite3_create_function(
169935          db, p->zName, p->nArg, p->enc, 
169936          p->iContext ? (void*)db : (void*)0,
169937          p->xFunc, 0, 0
169938      );
169939    }
169940  
169941    return rc;
169942  }
169943  
169944  #if !SQLITE_CORE
169945  #ifdef _WIN32
169946  __declspec(dllexport)
169947  #endif
169948  SQLITE_API int sqlite3_icu_init(
169949    sqlite3 *db, 
169950    char **pzErrMsg,
169951    const sqlite3_api_routines *pApi
169952  ){
169953    SQLITE_EXTENSION_INIT2(pApi)
169954    return sqlite3IcuInit(db);
169955  }
169956  #endif
169957  
169958  #endif
169959  
169960  /************** End of icu.c *************************************************/
169961  /************** Begin file fts3_icu.c ****************************************/
169962  /*
169963  ** 2007 June 22
169964  **
169965  ** The author disclaims copyright to this source code.  In place of
169966  ** a legal notice, here is a blessing:
169967  **
169968  **    May you do good and not evil.
169969  **    May you find forgiveness for yourself and forgive others.
169970  **    May you share freely, never taking more than you give.
169971  **
169972  *************************************************************************
169973  ** This file implements a tokenizer for fts3 based on the ICU library.
169974  */
169975  /* #include "fts3Int.h" */
169976  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
169977  #ifdef SQLITE_ENABLE_ICU
169978  
169979  /* #include <assert.h> */
169980  /* #include <string.h> */
169981  /* #include "fts3_tokenizer.h" */
169982  
169983  #include <unicode/ubrk.h>
169984  /* #include <unicode/ucol.h> */
169985  /* #include <unicode/ustring.h> */
169986  #include <unicode/utf16.h>
169987  
169988  typedef struct IcuTokenizer IcuTokenizer;
169989  typedef struct IcuCursor IcuCursor;
169990  
169991  struct IcuTokenizer {
169992    sqlite3_tokenizer base;
169993    char *zLocale;
169994  };
169995  
169996  struct IcuCursor {
169997    sqlite3_tokenizer_cursor base;
169998  
169999    UBreakIterator *pIter;      /* ICU break-iterator object */
170000    int nChar;                  /* Number of UChar elements in pInput */
170001    UChar *aChar;               /* Copy of input using utf-16 encoding */
170002    int *aOffset;               /* Offsets of each character in utf-8 input */
170003  
170004    int nBuffer;
170005    char *zBuffer;
170006  
170007    int iToken;
170008  };
170009  
170010  /*
170011  ** Create a new tokenizer instance.
170012  */
170013  static int icuCreate(
170014    int argc,                            /* Number of entries in argv[] */
170015    const char * const *argv,            /* Tokenizer creation arguments */
170016    sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
170017  ){
170018    IcuTokenizer *p;
170019    int n = 0;
170020  
170021    if( argc>0 ){
170022      n = strlen(argv[0])+1;
170023    }
170024    p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
170025    if( !p ){
170026      return SQLITE_NOMEM;
170027    }
170028    memset(p, 0, sizeof(IcuTokenizer));
170029  
170030    if( n ){
170031      p->zLocale = (char *)&p[1];
170032      memcpy(p->zLocale, argv[0], n);
170033    }
170034  
170035    *ppTokenizer = (sqlite3_tokenizer *)p;
170036  
170037    return SQLITE_OK;
170038  }
170039  
170040  /*
170041  ** Destroy a tokenizer
170042  */
170043  static int icuDestroy(sqlite3_tokenizer *pTokenizer){
170044    IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
170045    sqlite3_free(p);
170046    return SQLITE_OK;
170047  }
170048  
170049  /*
170050  ** Prepare to begin tokenizing a particular string.  The input
170051  ** string to be tokenized is pInput[0..nBytes-1].  A cursor
170052  ** used to incrementally tokenize this string is returned in 
170053  ** *ppCursor.
170054  */
170055  static int icuOpen(
170056    sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
170057    const char *zInput,                    /* Input string */
170058    int nInput,                            /* Length of zInput in bytes */
170059    sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
170060  ){
170061    IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
170062    IcuCursor *pCsr;
170063  
170064    const int32_t opt = U_FOLD_CASE_DEFAULT;
170065    UErrorCode status = U_ZERO_ERROR;
170066    int nChar;
170067  
170068    UChar32 c;
170069    int iInput = 0;
170070    int iOut = 0;
170071  
170072    *ppCursor = 0;
170073  
170074    if( zInput==0 ){
170075      nInput = 0;
170076      zInput = "";
170077    }else if( nInput<0 ){
170078      nInput = strlen(zInput);
170079    }
170080    nChar = nInput+1;
170081    pCsr = (IcuCursor *)sqlite3_malloc(
170082        sizeof(IcuCursor) +                /* IcuCursor */
170083        ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
170084        (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
170085    );
170086    if( !pCsr ){
170087      return SQLITE_NOMEM;
170088    }
170089    memset(pCsr, 0, sizeof(IcuCursor));
170090    pCsr->aChar = (UChar *)&pCsr[1];
170091    pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
170092  
170093    pCsr->aOffset[iOut] = iInput;
170094    U8_NEXT(zInput, iInput, nInput, c); 
170095    while( c>0 ){
170096      int isError = 0;
170097      c = u_foldCase(c, opt);
170098      U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
170099      if( isError ){
170100        sqlite3_free(pCsr);
170101        return SQLITE_ERROR;
170102      }
170103      pCsr->aOffset[iOut] = iInput;
170104  
170105      if( iInput<nInput ){
170106        U8_NEXT(zInput, iInput, nInput, c);
170107      }else{
170108        c = 0;
170109      }
170110    }
170111  
170112    pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
170113    if( !U_SUCCESS(status) ){
170114      sqlite3_free(pCsr);
170115      return SQLITE_ERROR;
170116    }
170117    pCsr->nChar = iOut;
170118  
170119    ubrk_first(pCsr->pIter);
170120    *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
170121    return SQLITE_OK;
170122  }
170123  
170124  /*
170125  ** Close a tokenization cursor previously opened by a call to icuOpen().
170126  */
170127  static int icuClose(sqlite3_tokenizer_cursor *pCursor){
170128    IcuCursor *pCsr = (IcuCursor *)pCursor;
170129    ubrk_close(pCsr->pIter);
170130    sqlite3_free(pCsr->zBuffer);
170131    sqlite3_free(pCsr);
170132    return SQLITE_OK;
170133  }
170134  
170135  /*
170136  ** Extract the next token from a tokenization cursor.
170137  */
170138  static int icuNext(
170139    sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
170140    const char **ppToken,               /* OUT: *ppToken is the token text */
170141    int *pnBytes,                       /* OUT: Number of bytes in token */
170142    int *piStartOffset,                 /* OUT: Starting offset of token */
170143    int *piEndOffset,                   /* OUT: Ending offset of token */
170144    int *piPosition                     /* OUT: Position integer of token */
170145  ){
170146    IcuCursor *pCsr = (IcuCursor *)pCursor;
170147  
170148    int iStart = 0;
170149    int iEnd = 0;
170150    int nByte = 0;
170151  
170152    while( iStart==iEnd ){
170153      UChar32 c;
170154  
170155      iStart = ubrk_current(pCsr->pIter);
170156      iEnd = ubrk_next(pCsr->pIter);
170157      if( iEnd==UBRK_DONE ){
170158        return SQLITE_DONE;
170159      }
170160  
170161      while( iStart<iEnd ){
170162        int iWhite = iStart;
170163        U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
170164        if( u_isspace(c) ){
170165          iStart = iWhite;
170166        }else{
170167          break;
170168        }
170169      }
170170      assert(iStart<=iEnd);
170171    }
170172  
170173    do {
170174      UErrorCode status = U_ZERO_ERROR;
170175      if( nByte ){
170176        char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
170177        if( !zNew ){
170178          return SQLITE_NOMEM;
170179        }
170180        pCsr->zBuffer = zNew;
170181        pCsr->nBuffer = nByte;
170182      }
170183  
170184      u_strToUTF8(
170185          pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
170186          &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
170187          &status                                  /* Output success/failure */
170188      );
170189    } while( nByte>pCsr->nBuffer );
170190  
170191    *ppToken = pCsr->zBuffer;
170192    *pnBytes = nByte;
170193    *piStartOffset = pCsr->aOffset[iStart];
170194    *piEndOffset = pCsr->aOffset[iEnd];
170195    *piPosition = pCsr->iToken++;
170196  
170197    return SQLITE_OK;
170198  }
170199  
170200  /*
170201  ** The set of routines that implement the simple tokenizer
170202  */
170203  static const sqlite3_tokenizer_module icuTokenizerModule = {
170204    0,                           /* iVersion    */
170205    icuCreate,                   /* xCreate     */
170206    icuDestroy,                  /* xCreate     */
170207    icuOpen,                     /* xOpen       */
170208    icuClose,                    /* xClose      */
170209    icuNext,                     /* xNext       */
170210    0,                           /* xLanguageid */
170211  };
170212  
170213  /*
170214  ** Set *ppModule to point at the implementation of the ICU tokenizer.
170215  */
170216  SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
170217    sqlite3_tokenizer_module const**ppModule
170218  ){
170219    *ppModule = &icuTokenizerModule;
170220  }
170221  
170222  #endif /* defined(SQLITE_ENABLE_ICU) */
170223  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
170224  
170225  /************** End of fts3_icu.c ********************************************/
170226  /************** Begin file sqlite3rbu.c **************************************/
170227  /*
170228  ** 2014 August 30
170229  **
170230  ** The author disclaims copyright to this source code.  In place of
170231  ** a legal notice, here is a blessing:
170232  **
170233  **    May you do good and not evil.
170234  **    May you find forgiveness for yourself and forgive others.
170235  **    May you share freely, never taking more than you give.
170236  **
170237  *************************************************************************
170238  **
170239  **
170240  ** OVERVIEW 
170241  **
170242  **  The RBU extension requires that the RBU update be packaged as an
170243  **  SQLite database. The tables it expects to find are described in
170244  **  sqlite3rbu.h.  Essentially, for each table xyz in the target database
170245  **  that the user wishes to write to, a corresponding data_xyz table is
170246  **  created in the RBU database and populated with one row for each row to
170247  **  update, insert or delete from the target table.
170248  ** 
170249  **  The update proceeds in three stages:
170250  ** 
170251  **  1) The database is updated. The modified database pages are written
170252  **     to a *-oal file. A *-oal file is just like a *-wal file, except
170253  **     that it is named "<database>-oal" instead of "<database>-wal".
170254  **     Because regular SQLite clients do not look for file named
170255  **     "<database>-oal", they go on using the original database in
170256  **     rollback mode while the *-oal file is being generated.
170257  ** 
170258  **     During this stage RBU does not update the database by writing
170259  **     directly to the target tables. Instead it creates "imposter"
170260  **     tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
170261  **     to update each b-tree individually. All updates required by each
170262  **     b-tree are completed before moving on to the next, and all
170263  **     updates are done in sorted key order.
170264  ** 
170265  **  2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
170266  **     location using a call to rename(2). Before doing this the RBU
170267  **     module takes an EXCLUSIVE lock on the database file, ensuring
170268  **     that there are no other active readers.
170269  ** 
170270  **     Once the EXCLUSIVE lock is released, any other database readers
170271  **     detect the new *-wal file and read the database in wal mode. At
170272  **     this point they see the new version of the database - including
170273  **     the updates made as part of the RBU update.
170274  ** 
170275  **  3) The new *-wal file is checkpointed. This proceeds in the same way 
170276  **     as a regular database checkpoint, except that a single frame is
170277  **     checkpointed each time sqlite3rbu_step() is called. If the RBU
170278  **     handle is closed before the entire *-wal file is checkpointed,
170279  **     the checkpoint progress is saved in the RBU database and the
170280  **     checkpoint can be resumed by another RBU client at some point in
170281  **     the future.
170282  **
170283  ** POTENTIAL PROBLEMS
170284  ** 
170285  **  The rename() call might not be portable. And RBU is not currently
170286  **  syncing the directory after renaming the file.
170287  **
170288  **  When state is saved, any commit to the *-oal file and the commit to
170289  **  the RBU update database are not atomic. So if the power fails at the
170290  **  wrong moment they might get out of sync. As the main database will be
170291  **  committed before the RBU update database this will likely either just
170292  **  pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
170293  **  constraint violations).
170294  **
170295  **  If some client does modify the target database mid RBU update, or some
170296  **  other error occurs, the RBU extension will keep throwing errors. It's
170297  **  not really clear how to get out of this state. The system could just
170298  **  by delete the RBU update database and *-oal file and have the device
170299  **  download the update again and start over.
170300  **
170301  **  At present, for an UPDATE, both the new.* and old.* records are
170302  **  collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
170303  **  fields are collected.  This means we're probably writing a lot more
170304  **  data to disk when saving the state of an ongoing update to the RBU
170305  **  update database than is strictly necessary.
170306  ** 
170307  */
170308  
170309  /* #include <assert.h> */
170310  /* #include <string.h> */
170311  /* #include <stdio.h> */
170312  
170313  /* #include "sqlite3.h" */
170314  
170315  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
170316  /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
170317  /************** Begin file sqlite3rbu.h **************************************/
170318  /*
170319  ** 2014 August 30
170320  **
170321  ** The author disclaims copyright to this source code.  In place of
170322  ** a legal notice, here is a blessing:
170323  **
170324  **    May you do good and not evil.
170325  **    May you find forgiveness for yourself and forgive others.
170326  **    May you share freely, never taking more than you give.
170327  **
170328  *************************************************************************
170329  **
170330  ** This file contains the public interface for the RBU extension. 
170331  */
170332  
170333  /*
170334  ** SUMMARY
170335  **
170336  ** Writing a transaction containing a large number of operations on 
170337  ** b-tree indexes that are collectively larger than the available cache
170338  ** memory can be very inefficient. 
170339  **
170340  ** The problem is that in order to update a b-tree, the leaf page (at least)
170341  ** containing the entry being inserted or deleted must be modified. If the
170342  ** working set of leaves is larger than the available cache memory, then a 
170343  ** single leaf that is modified more than once as part of the transaction 
170344  ** may be loaded from or written to the persistent media multiple times.
170345  ** Additionally, because the index updates are likely to be applied in
170346  ** random order, access to pages within the database is also likely to be in 
170347  ** random order, which is itself quite inefficient.
170348  **
170349  ** One way to improve the situation is to sort the operations on each index
170350  ** by index key before applying them to the b-tree. This leads to an IO
170351  ** pattern that resembles a single linear scan through the index b-tree,
170352  ** and all but guarantees each modified leaf page is loaded and stored 
170353  ** exactly once. SQLite uses this trick to improve the performance of
170354  ** CREATE INDEX commands. This extension allows it to be used to improve
170355  ** the performance of large transactions on existing databases.
170356  **
170357  ** Additionally, this extension allows the work involved in writing the 
170358  ** large transaction to be broken down into sub-transactions performed 
170359  ** sequentially by separate processes. This is useful if the system cannot 
170360  ** guarantee that a single update process will run for long enough to apply 
170361  ** the entire update, for example because the update is being applied on a 
170362  ** mobile device that is frequently rebooted. Even after the writer process 
170363  ** has committed one or more sub-transactions, other database clients continue
170364  ** to read from the original database snapshot. In other words, partially 
170365  ** applied transactions are not visible to other clients. 
170366  **
170367  ** "RBU" stands for "Resumable Bulk Update". As in a large database update
170368  ** transmitted via a wireless network to a mobile device. A transaction
170369  ** applied using this extension is hence refered to as an "RBU update".
170370  **
170371  **
170372  ** LIMITATIONS
170373  **
170374  ** An "RBU update" transaction is subject to the following limitations:
170375  **
170376  **   * The transaction must consist of INSERT, UPDATE and DELETE operations
170377  **     only.
170378  **
170379  **   * INSERT statements may not use any default values.
170380  **
170381  **   * UPDATE and DELETE statements must identify their target rows by 
170382  **     non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
170383  **     KEY fields may not be updated or deleted. If the table being written 
170384  **     has no PRIMARY KEY, affected rows must be identified by rowid.
170385  **
170386  **   * UPDATE statements may not modify PRIMARY KEY columns.
170387  **
170388  **   * No triggers will be fired.
170389  **
170390  **   * No foreign key violations are detected or reported.
170391  **
170392  **   * CHECK constraints are not enforced.
170393  **
170394  **   * No constraint handling mode except for "OR ROLLBACK" is supported.
170395  **
170396  **
170397  ** PREPARATION
170398  **
170399  ** An "RBU update" is stored as a separate SQLite database. A database
170400  ** containing an RBU update is an "RBU database". For each table in the 
170401  ** target database to be updated, the RBU database should contain a table
170402  ** named "data_<target name>" containing the same set of columns as the
170403  ** target table, and one more - "rbu_control". The data_% table should 
170404  ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
170405  ** the same type as the corresponding column in the target database.
170406  ** The "rbu_control" column should have no type at all. For example, if
170407  ** the target database contains:
170408  **
170409  **   CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
170410  **
170411  ** Then the RBU database should contain:
170412  **
170413  **   CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
170414  **
170415  ** The order of the columns in the data_% table does not matter.
170416  **
170417  ** Instead of a regular table, the RBU database may also contain virtual
170418  ** tables or view named using the data_<target> naming scheme. 
170419  **
170420  ** Instead of the plain data_<target> naming scheme, RBU database tables 
170421  ** may also be named data<integer>_<target>, where <integer> is any sequence
170422  ** of zero or more numeric characters (0-9). This can be significant because
170423  ** tables within the RBU database are always processed in order sorted by 
170424  ** name. By judicious selection of the <integer> portion of the names
170425  ** of the RBU tables the user can therefore control the order in which they
170426  ** are processed. This can be useful, for example, to ensure that "external
170427  ** content" FTS4 tables are updated before their underlying content tables.
170428  **
170429  ** If the target database table is a virtual table or a table that has no
170430  ** PRIMARY KEY declaration, the data_% table must also contain a column 
170431  ** named "rbu_rowid". This column is mapped to the tables implicit primary 
170432  ** key column - "rowid". Virtual tables for which the "rowid" column does 
170433  ** not function like a primary key value cannot be updated using RBU. For 
170434  ** example, if the target db contains either of the following:
170435  **
170436  **   CREATE VIRTUAL TABLE x1 USING fts3(a, b);
170437  **   CREATE TABLE x1(a, b)
170438  **
170439  ** then the RBU database should contain:
170440  **
170441  **   CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
170442  **
170443  ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
170444  ** target table must be present in the input table. For virtual tables,
170445  ** hidden columns are optional - they are updated by RBU if present in
170446  ** the input table, or not otherwise. For example, to write to an fts4
170447  ** table with a hidden languageid column such as:
170448  **
170449  **   CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
170450  **
170451  ** Either of the following input table schemas may be used:
170452  **
170453  **   CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
170454  **   CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
170455  **
170456  ** For each row to INSERT into the target database as part of the RBU 
170457  ** update, the corresponding data_% table should contain a single record
170458  ** with the "rbu_control" column set to contain integer value 0. The
170459  ** other columns should be set to the values that make up the new record 
170460  ** to insert. 
170461  **
170462  ** If the target database table has an INTEGER PRIMARY KEY, it is not 
170463  ** possible to insert a NULL value into the IPK column. Attempting to 
170464  ** do so results in an SQLITE_MISMATCH error.
170465  **
170466  ** For each row to DELETE from the target database as part of the RBU 
170467  ** update, the corresponding data_% table should contain a single record
170468  ** with the "rbu_control" column set to contain integer value 1. The
170469  ** real primary key values of the row to delete should be stored in the
170470  ** corresponding columns of the data_% table. The values stored in the
170471  ** other columns are not used.
170472  **
170473  ** For each row to UPDATE from the target database as part of the RBU 
170474  ** update, the corresponding data_% table should contain a single record
170475  ** with the "rbu_control" column set to contain a value of type text.
170476  ** The real primary key values identifying the row to update should be 
170477  ** stored in the corresponding columns of the data_% table row, as should
170478  ** the new values of all columns being update. The text value in the 
170479  ** "rbu_control" column must contain the same number of characters as
170480  ** there are columns in the target database table, and must consist entirely
170481  ** of 'x' and '.' characters (or in some special cases 'd' - see below). For 
170482  ** each column that is being updated, the corresponding character is set to
170483  ** 'x'. For those that remain as they are, the corresponding character of the
170484  ** rbu_control value should be set to '.'. For example, given the tables 
170485  ** above, the update statement:
170486  **
170487  **   UPDATE t1 SET c = 'usa' WHERE a = 4;
170488  **
170489  ** is represented by the data_t1 row created by:
170490  **
170491  **   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
170492  **
170493  ** Instead of an 'x' character, characters of the rbu_control value specified
170494  ** for UPDATEs may also be set to 'd'. In this case, instead of updating the
170495  ** target table with the value stored in the corresponding data_% column, the
170496  ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
170497  ** the target table column. rbu_delta() is invoked with two arguments - the
170498  ** original value currently stored in the target table column and the 
170499  ** value specified in the data_xxx table.
170500  **
170501  ** For example, this row:
170502  **
170503  **   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
170504  **
170505  ** is similar to an UPDATE statement such as: 
170506  **
170507  **   UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
170508  **
170509  ** Finally, if an 'f' character appears in place of a 'd' or 's' in an 
170510  ** ota_control string, the contents of the data_xxx table column is assumed
170511  ** to be a "fossil delta" - a patch to be applied to a blob value in the
170512  ** format used by the fossil source-code management system. In this case
170513  ** the existing value within the target database table must be of type BLOB. 
170514  ** It is replaced by the result of applying the specified fossil delta to
170515  ** itself.
170516  **
170517  ** If the target database table is a virtual table or a table with no PRIMARY
170518  ** KEY, the rbu_control value should not include a character corresponding 
170519  ** to the rbu_rowid value. For example, this:
170520  **
170521  **   INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control) 
170522  **       VALUES(NULL, 'usa', 12, '.x');
170523  **
170524  ** causes a result similar to:
170525  **
170526  **   UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
170527  **
170528  ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
170529  ** However, RBU is more efficient if reading the rows in from each data_xxx
170530  ** table in "rowid" order is roughly the same as reading them sorted by
170531  ** the PRIMARY KEY of the corresponding target database table. In other 
170532  ** words, rows should be sorted using the destination table PRIMARY KEY 
170533  ** fields before they are inserted into the data_xxx tables.
170534  **
170535  ** USAGE
170536  **
170537  ** The API declared below allows an application to apply an RBU update 
170538  ** stored on disk to an existing target database. Essentially, the 
170539  ** application:
170540  **
170541  **     1) Opens an RBU handle using the sqlite3rbu_open() function.
170542  **
170543  **     2) Registers any required virtual table modules with the database
170544  **        handle returned by sqlite3rbu_db(). Also, if required, register
170545  **        the rbu_delta() implementation.
170546  **
170547  **     3) Calls the sqlite3rbu_step() function one or more times on
170548  **        the new handle. Each call to sqlite3rbu_step() performs a single
170549  **        b-tree operation, so thousands of calls may be required to apply 
170550  **        a complete update.
170551  **
170552  **     4) Calls sqlite3rbu_close() to close the RBU update handle. If
170553  **        sqlite3rbu_step() has been called enough times to completely
170554  **        apply the update to the target database, then the RBU database
170555  **        is marked as fully applied. Otherwise, the state of the RBU 
170556  **        update application is saved in the RBU database for later 
170557  **        resumption.
170558  **
170559  ** See comments below for more detail on APIs.
170560  **
170561  ** If an update is only partially applied to the target database by the
170562  ** time sqlite3rbu_close() is called, various state information is saved 
170563  ** within the RBU database. This allows subsequent processes to automatically
170564  ** resume the RBU update from where it left off.
170565  **
170566  ** To remove all RBU extension state information, returning an RBU database 
170567  ** to its original contents, it is sufficient to drop all tables that begin
170568  ** with the prefix "rbu_"
170569  **
170570  ** DATABASE LOCKING
170571  **
170572  ** An RBU update may not be applied to a database in WAL mode. Attempting
170573  ** to do so is an error (SQLITE_ERROR).
170574  **
170575  ** While an RBU handle is open, a SHARED lock may be held on the target
170576  ** database file. This means it is possible for other clients to read the
170577  ** database, but not to write it.
170578  **
170579  ** If an RBU update is started and then suspended before it is completed,
170580  ** then an external client writes to the database, then attempting to resume
170581  ** the suspended RBU update is also an error (SQLITE_BUSY).
170582  */
170583  
170584  #ifndef _SQLITE3RBU_H
170585  #define _SQLITE3RBU_H
170586  
170587  /* #include "sqlite3.h"              ** Required for error code definitions ** */
170588  
170589  #if 0
170590  extern "C" {
170591  #endif
170592  
170593  typedef struct sqlite3rbu sqlite3rbu;
170594  
170595  /*
170596  ** Open an RBU handle.
170597  **
170598  ** Argument zTarget is the path to the target database. Argument zRbu is
170599  ** the path to the RBU database. Each call to this function must be matched
170600  ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
170601  ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
170602  ** or zRbu begin with "file:", it will be interpreted as an SQLite 
170603  ** database URI, not a regular file name.
170604  **
170605  ** If the zState argument is passed a NULL value, the RBU extension stores 
170606  ** the current state of the update (how many rows have been updated, which 
170607  ** indexes are yet to be updated etc.) within the RBU database itself. This
170608  ** can be convenient, as it means that the RBU application does not need to
170609  ** organize removing a separate state file after the update is concluded. 
170610  ** Or, if zState is non-NULL, it must be a path to a database file in which 
170611  ** the RBU extension can store the state of the update.
170612  **
170613  ** When resuming an RBU update, the zState argument must be passed the same
170614  ** value as when the RBU update was started.
170615  **
170616  ** Once the RBU update is finished, the RBU extension does not 
170617  ** automatically remove any zState database file, even if it created it.
170618  **
170619  ** By default, RBU uses the default VFS to access the files on disk. To
170620  ** use a VFS other than the default, an SQLite "file:" URI containing a
170621  ** "vfs=..." option may be passed as the zTarget option.
170622  **
170623  ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
170624  ** SQLite's built-in VFSs, including the multiplexor VFS. However it does
170625  ** not work out of the box with zipvfs. Refer to the comment describing
170626  ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
170627  */
170628  SQLITE_API sqlite3rbu *sqlite3rbu_open(
170629    const char *zTarget, 
170630    const char *zRbu,
170631    const char *zState
170632  );
170633  
170634  /*
170635  ** Open an RBU handle to perform an RBU vacuum on database file zTarget.
170636  ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
170637  ** that it can be suspended and resumed like an RBU update.
170638  **
170639  ** The second argument to this function identifies a database in which 
170640  ** to store the state of the RBU vacuum operation if it is suspended. The 
170641  ** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum
170642  ** operation, the state database should either not exist or be empty
170643  ** (contain no tables). If an RBU vacuum is suspended by calling 
170644  ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
170645  ** returned SQLITE_DONE, the vacuum state is stored in the state database. 
170646  ** The vacuum can be resumed by calling this function to open a new RBU
170647  ** handle specifying the same target and state databases.
170648  **
170649  ** If the second argument passed to this function is NULL, then the
170650  ** name of the state database is "<database>-vacuum", where <database>
170651  ** is the name of the target database file. In this case, on UNIX, if the
170652  ** state database is not already present in the file-system, it is created
170653  ** with the same permissions as the target db is made.
170654  **
170655  ** This function does not delete the state database after an RBU vacuum
170656  ** is completed, even if it created it. However, if the call to
170657  ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
170658  ** of the state tables within the state database are zeroed. This way,
170659  ** the next call to sqlite3rbu_vacuum() opens a handle that starts a 
170660  ** new RBU vacuum operation.
170661  **
170662  ** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
170663  ** describing the sqlite3rbu_create_vfs() API function below for 
170664  ** a description of the complications associated with using RBU with 
170665  ** zipvfs databases.
170666  */
170667  SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
170668    const char *zTarget, 
170669    const char *zState
170670  );
170671  
170672  /*
170673  ** Configure a limit for the amount of temp space that may be used by
170674  ** the RBU handle passed as the first argument. The new limit is specified
170675  ** in bytes by the second parameter. If it is positive, the limit is updated.
170676  ** If the second parameter to this function is passed zero, then the limit
170677  ** is removed entirely. If the second parameter is negative, the limit is
170678  ** not modified (this is useful for querying the current limit).
170679  **
170680  ** In all cases the returned value is the current limit in bytes (zero 
170681  ** indicates unlimited).
170682  **
170683  ** If the temp space limit is exceeded during operation, an SQLITE_FULL
170684  ** error is returned.
170685  */
170686  SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu*, sqlite3_int64);
170687  
170688  /*
170689  ** Return the current amount of temp file space, in bytes, currently used by 
170690  ** the RBU handle passed as the only argument.
170691  */
170692  SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu*);
170693  
170694  /*
170695  ** Internally, each RBU connection uses a separate SQLite database 
170696  ** connection to access the target and rbu update databases. This
170697  ** API allows the application direct access to these database handles.
170698  **
170699  ** The first argument passed to this function must be a valid, open, RBU
170700  ** handle. The second argument should be passed zero to access the target
170701  ** database handle, or non-zero to access the rbu update database handle.
170702  ** Accessing the underlying database handles may be useful in the
170703  ** following scenarios:
170704  **
170705  **   * If any target tables are virtual tables, it may be necessary to
170706  **     call sqlite3_create_module() on the target database handle to 
170707  **     register the required virtual table implementations.
170708  **
170709  **   * If the data_xxx tables in the RBU source database are virtual 
170710  **     tables, the application may need to call sqlite3_create_module() on
170711  **     the rbu update db handle to any required virtual table
170712  **     implementations.
170713  **
170714  **   * If the application uses the "rbu_delta()" feature described above,
170715  **     it must use sqlite3_create_function() or similar to register the
170716  **     rbu_delta() implementation with the target database handle.
170717  **
170718  ** If an error has occurred, either while opening or stepping the RBU object,
170719  ** this function may return NULL. The error code and message may be collected
170720  ** when sqlite3rbu_close() is called.
170721  **
170722  ** Database handles returned by this function remain valid until the next
170723  ** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
170724  */
170725  SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);
170726  
170727  /*
170728  ** Do some work towards applying the RBU update to the target db. 
170729  **
170730  ** Return SQLITE_DONE if the update has been completely applied, or 
170731  ** SQLITE_OK if no error occurs but there remains work to do to apply
170732  ** the RBU update. If an error does occur, some other error code is 
170733  ** returned. 
170734  **
170735  ** Once a call to sqlite3rbu_step() has returned a value other than
170736  ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
170737  ** that immediately return the same value.
170738  */
170739  SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
170740  
170741  /*
170742  ** Force RBU to save its state to disk.
170743  **
170744  ** If a power failure or application crash occurs during an update, following
170745  ** system recovery RBU may resume the update from the point at which the state
170746  ** was last saved. In other words, from the most recent successful call to 
170747  ** sqlite3rbu_close() or this function.
170748  **
170749  ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
170750  */
170751  SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
170752  
170753  /*
170754  ** Close an RBU handle. 
170755  **
170756  ** If the RBU update has been completely applied, mark the RBU database
170757  ** as fully applied. Otherwise, assuming no error has occurred, save the
170758  ** current state of the RBU update appliation to the RBU database.
170759  **
170760  ** If an error has already occurred as part of an sqlite3rbu_step()
170761  ** or sqlite3rbu_open() call, or if one occurs within this function, an
170762  ** SQLite error code is returned. Additionally, if pzErrmsg is not NULL,
170763  ** *pzErrmsg may be set to point to a buffer containing a utf-8 formatted
170764  ** English language error message. It is the responsibility of the caller to
170765  ** eventually free any such buffer using sqlite3_free().
170766  **
170767  ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
170768  ** update has been partially applied, or SQLITE_DONE if it has been 
170769  ** completely applied.
170770  */
170771  SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
170772  
170773  /*
170774  ** Return the total number of key-value operations (inserts, deletes or 
170775  ** updates) that have been performed on the target database since the
170776  ** current RBU update was started.
170777  */
170778  SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
170779  
170780  /*
170781  ** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100) 
170782  ** progress indications for the two stages of an RBU update. This API may
170783  ** be useful for driving GUI progress indicators and similar.
170784  **
170785  ** An RBU update is divided into two stages:
170786  **
170787  **   * Stage 1, in which changes are accumulated in an oal/wal file, and
170788  **   * Stage 2, in which the contents of the wal file are copied into the
170789  **     main database.
170790  **
170791  ** The update is visible to non-RBU clients during stage 2. During stage 1
170792  ** non-RBU reader clients may see the original database.
170793  **
170794  ** If this API is called during stage 2 of the update, output variable 
170795  ** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
170796  ** to a value between 0 and 10000 to indicate the permyriadage progress of
170797  ** stage 2. A value of 5000 indicates that stage 2 is half finished, 
170798  ** 9000 indicates that it is 90% finished, and so on.
170799  **
170800  ** If this API is called during stage 1 of the update, output variable 
170801  ** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
170802  ** value to which (*pnOne) is set depends on whether or not the RBU 
170803  ** database contains an "rbu_count" table. The rbu_count table, if it 
170804  ** exists, must contain the same columns as the following:
170805  **
170806  **   CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
170807  **
170808  ** There must be one row in the table for each source (data_xxx) table within
170809  ** the RBU database. The 'tbl' column should contain the name of the source
170810  ** table. The 'cnt' column should contain the number of rows within the
170811  ** source table.
170812  **
170813  ** If the rbu_count table is present and populated correctly and this
170814  ** API is called during stage 1, the *pnOne output variable is set to the
170815  ** permyriadage progress of the same stage. If the rbu_count table does
170816  ** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
170817  ** table exists but is not correctly populated, the value of the *pnOne
170818  ** output variable during stage 1 is undefined.
170819  */
170820  SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int*pnTwo);
170821  
170822  /*
170823  ** Obtain an indication as to the current stage of an RBU update or vacuum.
170824  ** This function always returns one of the SQLITE_RBU_STATE_XXX constants
170825  ** defined in this file. Return values should be interpreted as follows:
170826  **
170827  ** SQLITE_RBU_STATE_OAL:
170828  **   RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
170829  **   may either add further data to the *-oal file, or compute data that will
170830  **   be added by a subsequent call.
170831  **
170832  ** SQLITE_RBU_STATE_MOVE:
170833  **   RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
170834  **   will move the *-oal file to the equivalent *-wal path. If the current
170835  **   operation is an RBU update, then the updated version of the database
170836  **   file will become visible to ordinary SQLite clients following the next
170837  **   call to sqlite3rbu_step().
170838  **
170839  ** SQLITE_RBU_STATE_CHECKPOINT:
170840  **   RBU is currently performing an incremental checkpoint. The next call to
170841  **   sqlite3rbu_step() will copy a page of data from the *-wal file into
170842  **   the target database file.
170843  **
170844  ** SQLITE_RBU_STATE_DONE:
170845  **   The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
170846  **   will immediately return SQLITE_DONE.
170847  **
170848  ** SQLITE_RBU_STATE_ERROR:
170849  **   An error has occurred. Any subsequent calls to sqlite3rbu_step() will
170850  **   immediately return the SQLite error code associated with the error.
170851  */
170852  #define SQLITE_RBU_STATE_OAL        1
170853  #define SQLITE_RBU_STATE_MOVE       2
170854  #define SQLITE_RBU_STATE_CHECKPOINT 3
170855  #define SQLITE_RBU_STATE_DONE       4
170856  #define SQLITE_RBU_STATE_ERROR      5
170857  
170858  SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
170859  
170860  /*
170861  ** Create an RBU VFS named zName that accesses the underlying file-system
170862  ** via existing VFS zParent. Or, if the zParent parameter is passed NULL, 
170863  ** then the new RBU VFS uses the default system VFS to access the file-system.
170864  ** The new object is registered as a non-default VFS with SQLite before 
170865  ** returning.
170866  **
170867  ** Part of the RBU implementation uses a custom VFS object. Usually, this
170868  ** object is created and deleted automatically by RBU. 
170869  **
170870  ** The exception is for applications that also use zipvfs. In this case,
170871  ** the custom VFS must be explicitly created by the user before the RBU
170872  ** handle is opened. The RBU VFS should be installed so that the zipvfs
170873  ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use 
170874  ** (for example multiplexor) to access the file-system. For example,
170875  ** to assemble an RBU enabled VFS stack that uses both zipvfs and 
170876  ** multiplexor (error checking omitted):
170877  **
170878  **     // Create a VFS named "multiplex" (not the default).
170879  **     sqlite3_multiplex_initialize(0, 0);
170880  **
170881  **     // Create an rbu VFS named "rbu" that uses multiplexor. If the
170882  **     // second argument were replaced with NULL, the "rbu" VFS would
170883  **     // access the file-system via the system default VFS, bypassing the
170884  **     // multiplexor.
170885  **     sqlite3rbu_create_vfs("rbu", "multiplex");
170886  **
170887  **     // Create a zipvfs VFS named "zipvfs" that uses rbu.
170888  **     zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
170889  **
170890  **     // Make zipvfs the default VFS.
170891  **     sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
170892  **
170893  ** Because the default VFS created above includes a RBU functionality, it
170894  ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
170895  ** that does not include the RBU layer results in an error.
170896  **
170897  ** The overhead of adding the "rbu" VFS to the system is negligible for 
170898  ** non-RBU users. There is no harm in an application accessing the 
170899  ** file-system via "rbu" all the time, even if it only uses RBU functionality 
170900  ** occasionally.
170901  */
170902  SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);
170903  
170904  /*
170905  ** Deregister and destroy an RBU vfs created by an earlier call to
170906  ** sqlite3rbu_create_vfs().
170907  **
170908  ** VFS objects are not reference counted. If a VFS object is destroyed
170909  ** before all database handles that use it have been closed, the results
170910  ** are undefined.
170911  */
170912  SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
170913  
170914  #if 0
170915  }  /* end of the 'extern "C"' block */
170916  #endif
170917  
170918  #endif /* _SQLITE3RBU_H */
170919  
170920  /************** End of sqlite3rbu.h ******************************************/
170921  /************** Continuing where we left off in sqlite3rbu.c *****************/
170922  
170923  #if defined(_WIN32_WCE)
170924  /* #include "windows.h" */
170925  #endif
170926  
170927  /* Maximum number of prepared UPDATE statements held by this module */
170928  #define SQLITE_RBU_UPDATE_CACHESIZE 16
170929  
170930  /* Delta checksums disabled by default.  Compile with -DRBU_ENABLE_DELTA_CKSUM
170931  ** to enable checksum verification.
170932  */
170933  #ifndef RBU_ENABLE_DELTA_CKSUM
170934  # define RBU_ENABLE_DELTA_CKSUM 0
170935  #endif
170936  
170937  /*
170938  ** Swap two objects of type TYPE.
170939  */
170940  #if !defined(SQLITE_AMALGAMATION)
170941  # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
170942  #endif
170943  
170944  /*
170945  ** The rbu_state table is used to save the state of a partially applied
170946  ** update so that it can be resumed later. The table consists of integer
170947  ** keys mapped to values as follows:
170948  **
170949  ** RBU_STATE_STAGE:
170950  **   May be set to integer values 1, 2, 4 or 5. As follows:
170951  **       1: the *-rbu file is currently under construction.
170952  **       2: the *-rbu file has been constructed, but not yet moved 
170953  **          to the *-wal path.
170954  **       4: the checkpoint is underway.
170955  **       5: the rbu update has been checkpointed.
170956  **
170957  ** RBU_STATE_TBL:
170958  **   Only valid if STAGE==1. The target database name of the table 
170959  **   currently being written.
170960  **
170961  ** RBU_STATE_IDX:
170962  **   Only valid if STAGE==1. The target database name of the index 
170963  **   currently being written, or NULL if the main table is currently being
170964  **   updated.
170965  **
170966  ** RBU_STATE_ROW:
170967  **   Only valid if STAGE==1. Number of rows already processed for the current
170968  **   table/index.
170969  **
170970  ** RBU_STATE_PROGRESS:
170971  **   Trbul number of sqlite3rbu_step() calls made so far as part of this
170972  **   rbu update.
170973  **
170974  ** RBU_STATE_CKPT:
170975  **   Valid if STAGE==4. The 64-bit checksum associated with the wal-index
170976  **   header created by recovering the *-wal file. This is used to detect
170977  **   cases when another client appends frames to the *-wal file in the
170978  **   middle of an incremental checkpoint (an incremental checkpoint cannot
170979  **   be continued if this happens).
170980  **
170981  ** RBU_STATE_COOKIE:
170982  **   Valid if STAGE==1. The current change-counter cookie value in the 
170983  **   target db file.
170984  **
170985  ** RBU_STATE_OALSZ:
170986  **   Valid if STAGE==1. The size in bytes of the *-oal file.
170987  */
170988  #define RBU_STATE_STAGE        1
170989  #define RBU_STATE_TBL          2
170990  #define RBU_STATE_IDX          3
170991  #define RBU_STATE_ROW          4
170992  #define RBU_STATE_PROGRESS     5
170993  #define RBU_STATE_CKPT         6
170994  #define RBU_STATE_COOKIE       7
170995  #define RBU_STATE_OALSZ        8
170996  #define RBU_STATE_PHASEONESTEP 9
170997  
170998  #define RBU_STAGE_OAL         1
170999  #define RBU_STAGE_MOVE        2
171000  #define RBU_STAGE_CAPTURE     3
171001  #define RBU_STAGE_CKPT        4
171002  #define RBU_STAGE_DONE        5
171003  
171004  
171005  #define RBU_CREATE_STATE \
171006    "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
171007  
171008  typedef struct RbuFrame RbuFrame;
171009  typedef struct RbuObjIter RbuObjIter;
171010  typedef struct RbuState RbuState;
171011  typedef struct rbu_vfs rbu_vfs;
171012  typedef struct rbu_file rbu_file;
171013  typedef struct RbuUpdateStmt RbuUpdateStmt;
171014  
171015  #if !defined(SQLITE_AMALGAMATION)
171016  typedef unsigned int u32;
171017  typedef unsigned short u16;
171018  typedef unsigned char u8;
171019  typedef sqlite3_int64 i64;
171020  #endif
171021  
171022  /*
171023  ** These values must match the values defined in wal.c for the equivalent
171024  ** locks. These are not magic numbers as they are part of the SQLite file
171025  ** format.
171026  */
171027  #define WAL_LOCK_WRITE  0
171028  #define WAL_LOCK_CKPT   1
171029  #define WAL_LOCK_READ0  3
171030  
171031  #define SQLITE_FCNTL_RBUCNT    5149216
171032  
171033  /*
171034  ** A structure to store values read from the rbu_state table in memory.
171035  */
171036  struct RbuState {
171037    int eStage;
171038    char *zTbl;
171039    char *zIdx;
171040    i64 iWalCksum;
171041    int nRow;
171042    i64 nProgress;
171043    u32 iCookie;
171044    i64 iOalSz;
171045    i64 nPhaseOneStep;
171046  };
171047  
171048  struct RbuUpdateStmt {
171049    char *zMask;                    /* Copy of update mask used with pUpdate */
171050    sqlite3_stmt *pUpdate;          /* Last update statement (or NULL) */
171051    RbuUpdateStmt *pNext;
171052  };
171053  
171054  /*
171055  ** An iterator of this type is used to iterate through all objects in
171056  ** the target database that require updating. For each such table, the
171057  ** iterator visits, in order:
171058  **
171059  **     * the table itself, 
171060  **     * each index of the table (zero or more points to visit), and
171061  **     * a special "cleanup table" state.
171062  **
171063  ** abIndexed:
171064  **   If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
171065  **   it points to an array of flags nTblCol elements in size. The flag is
171066  **   set for each column that is either a part of the PK or a part of an
171067  **   index. Or clear otherwise.
171068  **   
171069  */
171070  struct RbuObjIter {
171071    sqlite3_stmt *pTblIter;         /* Iterate through tables */
171072    sqlite3_stmt *pIdxIter;         /* Index iterator */
171073    int nTblCol;                    /* Size of azTblCol[] array */
171074    char **azTblCol;                /* Array of unquoted target column names */
171075    char **azTblType;               /* Array of target column types */
171076    int *aiSrcOrder;                /* src table col -> target table col */
171077    u8 *abTblPk;                    /* Array of flags, set on target PK columns */
171078    u8 *abNotNull;                  /* Array of flags, set on NOT NULL columns */
171079    u8 *abIndexed;                  /* Array of flags, set on indexed & PK cols */
171080    int eType;                      /* Table type - an RBU_PK_XXX value */
171081  
171082    /* Output variables. zTbl==0 implies EOF. */
171083    int bCleanup;                   /* True in "cleanup" state */
171084    const char *zTbl;               /* Name of target db table */
171085    const char *zDataTbl;           /* Name of rbu db table (or null) */
171086    const char *zIdx;               /* Name of target db index (or null) */
171087    int iTnum;                      /* Root page of current object */
171088    int iPkTnum;                    /* If eType==EXTERNAL, root of PK index */
171089    int bUnique;                    /* Current index is unique */
171090    int nIndex;                     /* Number of aux. indexes on table zTbl */
171091  
171092    /* Statements created by rbuObjIterPrepareAll() */
171093    int nCol;                       /* Number of columns in current object */
171094    sqlite3_stmt *pSelect;          /* Source data */
171095    sqlite3_stmt *pInsert;          /* Statement for INSERT operations */
171096    sqlite3_stmt *pDelete;          /* Statement for DELETE ops */
171097    sqlite3_stmt *pTmpInsert;       /* Insert into rbu_tmp_$zDataTbl */
171098  
171099    /* Last UPDATE used (for PK b-tree updates only), or NULL. */
171100    RbuUpdateStmt *pRbuUpdate;
171101  };
171102  
171103  /*
171104  ** Values for RbuObjIter.eType
171105  **
171106  **     0: Table does not exist (error)
171107  **     1: Table has an implicit rowid.
171108  **     2: Table has an explicit IPK column.
171109  **     3: Table has an external PK index.
171110  **     4: Table is WITHOUT ROWID.
171111  **     5: Table is a virtual table.
171112  */
171113  #define RBU_PK_NOTABLE        0
171114  #define RBU_PK_NONE           1
171115  #define RBU_PK_IPK            2
171116  #define RBU_PK_EXTERNAL       3
171117  #define RBU_PK_WITHOUT_ROWID  4
171118  #define RBU_PK_VTAB           5
171119  
171120  
171121  /*
171122  ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
171123  ** one of the following operations.
171124  */
171125  #define RBU_INSERT     1          /* Insert on a main table b-tree */
171126  #define RBU_DELETE     2          /* Delete a row from a main table b-tree */
171127  #define RBU_REPLACE    3          /* Delete and then insert a row */
171128  #define RBU_IDX_DELETE 4          /* Delete a row from an aux. index b-tree */
171129  #define RBU_IDX_INSERT 5          /* Insert on an aux. index b-tree */
171130  
171131  #define RBU_UPDATE     6          /* Update a row in a main table b-tree */
171132  
171133  /*
171134  ** A single step of an incremental checkpoint - frame iWalFrame of the wal
171135  ** file should be copied to page iDbPage of the database file.
171136  */
171137  struct RbuFrame {
171138    u32 iDbPage;
171139    u32 iWalFrame;
171140  };
171141  
171142  /*
171143  ** RBU handle.
171144  **
171145  ** nPhaseOneStep:
171146  **   If the RBU database contains an rbu_count table, this value is set to
171147  **   a running estimate of the number of b-tree operations required to 
171148  **   finish populating the *-oal file. This allows the sqlite3_bp_progress()
171149  **   API to calculate the permyriadage progress of populating the *-oal file
171150  **   using the formula:
171151  **
171152  **     permyriadage = (10000 * nProgress) / nPhaseOneStep
171153  **
171154  **   nPhaseOneStep is initialized to the sum of:
171155  **
171156  **     nRow * (nIndex + 1)
171157  **
171158  **   for all source tables in the RBU database, where nRow is the number
171159  **   of rows in the source table and nIndex the number of indexes on the
171160  **   corresponding target database table.
171161  **
171162  **   This estimate is accurate if the RBU update consists entirely of
171163  **   INSERT operations. However, it is inaccurate if:
171164  **
171165  **     * the RBU update contains any UPDATE operations. If the PK specified
171166  **       for an UPDATE operation does not exist in the target table, then
171167  **       no b-tree operations are required on index b-trees. Or if the 
171168  **       specified PK does exist, then (nIndex*2) such operations are
171169  **       required (one delete and one insert on each index b-tree).
171170  **
171171  **     * the RBU update contains any DELETE operations for which the specified
171172  **       PK does not exist. In this case no operations are required on index
171173  **       b-trees.
171174  **
171175  **     * the RBU update contains REPLACE operations. These are similar to
171176  **       UPDATE operations.
171177  **
171178  **   nPhaseOneStep is updated to account for the conditions above during the
171179  **   first pass of each source table. The updated nPhaseOneStep value is
171180  **   stored in the rbu_state table if the RBU update is suspended.
171181  */
171182  struct sqlite3rbu {
171183    int eStage;                     /* Value of RBU_STATE_STAGE field */
171184    sqlite3 *dbMain;                /* target database handle */
171185    sqlite3 *dbRbu;                 /* rbu database handle */
171186    char *zTarget;                  /* Path to target db */
171187    char *zRbu;                     /* Path to rbu db */
171188    char *zState;                   /* Path to state db (or NULL if zRbu) */
171189    char zStateDb[5];               /* Db name for state ("stat" or "main") */
171190    int rc;                         /* Value returned by last rbu_step() call */
171191    char *zErrmsg;                  /* Error message if rc!=SQLITE_OK */
171192    int nStep;                      /* Rows processed for current object */
171193    int nProgress;                  /* Rows processed for all objects */
171194    RbuObjIter objiter;             /* Iterator for skipping through tbl/idx */
171195    const char *zVfsName;           /* Name of automatically created rbu vfs */
171196    rbu_file *pTargetFd;            /* File handle open on target db */
171197    int nPagePerSector;             /* Pages per sector for pTargetFd */
171198    i64 iOalSz;
171199    i64 nPhaseOneStep;
171200  
171201    /* The following state variables are used as part of the incremental
171202    ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
171203    ** function rbuSetupCheckpoint() for details.  */
171204    u32 iMaxFrame;                  /* Largest iWalFrame value in aFrame[] */
171205    u32 mLock;
171206    int nFrame;                     /* Entries in aFrame[] array */
171207    int nFrameAlloc;                /* Allocated size of aFrame[] array */
171208    RbuFrame *aFrame;
171209    int pgsz;
171210    u8 *aBuf;
171211    i64 iWalCksum;
171212    i64 szTemp;                     /* Current size of all temp files in use */
171213    i64 szTempLimit;                /* Total size limit for temp files */
171214  
171215    /* Used in RBU vacuum mode only */
171216    int nRbu;                       /* Number of RBU VFS in the stack */
171217    rbu_file *pRbuFd;               /* Fd for main db of dbRbu */
171218  };
171219  
171220  /*
171221  ** An rbu VFS is implemented using an instance of this structure.
171222  **
171223  ** Variable pRbu is only non-NULL for automatically created RBU VFS objects.
171224  ** It is NULL for RBU VFS objects created explicitly using
171225  ** sqlite3rbu_create_vfs(). It is used to track the total amount of temp
171226  ** space used by the RBU handle.
171227  */
171228  struct rbu_vfs {
171229    sqlite3_vfs base;               /* rbu VFS shim methods */
171230    sqlite3_vfs *pRealVfs;          /* Underlying VFS */
171231    sqlite3_mutex *mutex;           /* Mutex to protect pMain */
171232    sqlite3rbu *pRbu;               /* Owner RBU object */
171233    rbu_file *pMain;                /* Linked list of main db files */
171234  };
171235  
171236  /*
171237  ** Each file opened by an rbu VFS is represented by an instance of
171238  ** the following structure.
171239  **
171240  ** If this is a temporary file (pRbu!=0 && flags&DELETE_ON_CLOSE), variable
171241  ** "sz" is set to the current size of the database file.
171242  */
171243  struct rbu_file {
171244    sqlite3_file base;              /* sqlite3_file methods */
171245    sqlite3_file *pReal;            /* Underlying file handle */
171246    rbu_vfs *pRbuVfs;               /* Pointer to the rbu_vfs object */
171247    sqlite3rbu *pRbu;               /* Pointer to rbu object (rbu target only) */
171248    i64 sz;                         /* Size of file in bytes (temp only) */
171249  
171250    int openFlags;                  /* Flags this file was opened with */
171251    u32 iCookie;                    /* Cookie value for main db files */
171252    u8 iWriteVer;                   /* "write-version" value for main db files */
171253    u8 bNolock;                     /* True to fail EXCLUSIVE locks */
171254  
171255    int nShm;                       /* Number of entries in apShm[] array */
171256    char **apShm;                   /* Array of mmap'd *-shm regions */
171257    char *zDel;                     /* Delete this when closing file */
171258  
171259    const char *zWal;               /* Wal filename for this main db file */
171260    rbu_file *pWalFd;               /* Wal file descriptor for this main db */
171261    rbu_file *pMainNext;            /* Next MAIN_DB file */
171262  };
171263  
171264  /*
171265  ** True for an RBU vacuum handle, or false otherwise.
171266  */
171267  #define rbuIsVacuum(p) ((p)->zTarget==0)
171268  
171269  
171270  /*************************************************************************
171271  ** The following three functions, found below:
171272  **
171273  **   rbuDeltaGetInt()
171274  **   rbuDeltaChecksum()
171275  **   rbuDeltaApply()
171276  **
171277  ** are lifted from the fossil source code (http://fossil-scm.org). They
171278  ** are used to implement the scalar SQL function rbu_fossil_delta().
171279  */
171280  
171281  /*
171282  ** Read bytes from *pz and convert them into a positive integer.  When
171283  ** finished, leave *pz pointing to the first character past the end of
171284  ** the integer.  The *pLen parameter holds the length of the string
171285  ** in *pz and is decremented once for each character in the integer.
171286  */
171287  static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
171288    static const signed char zValue[] = {
171289      -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
171290      -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
171291      -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
171292       0,  1,  2,  3,  4,  5,  6,  7,    8,  9, -1, -1, -1, -1, -1, -1,
171293      -1, 10, 11, 12, 13, 14, 15, 16,   17, 18, 19, 20, 21, 22, 23, 24,
171294      25, 26, 27, 28, 29, 30, 31, 32,   33, 34, 35, -1, -1, -1, -1, 36,
171295      -1, 37, 38, 39, 40, 41, 42, 43,   44, 45, 46, 47, 48, 49, 50, 51,
171296      52, 53, 54, 55, 56, 57, 58, 59,   60, 61, 62, -1, -1, -1, 63, -1,
171297    };
171298    unsigned int v = 0;
171299    int c;
171300    unsigned char *z = (unsigned char*)*pz;
171301    unsigned char *zStart = z;
171302    while( (c = zValue[0x7f&*(z++)])>=0 ){
171303       v = (v<<6) + c;
171304    }
171305    z--;
171306    *pLen -= z - zStart;
171307    *pz = (char*)z;
171308    return v;
171309  }
171310  
171311  #if RBU_ENABLE_DELTA_CKSUM
171312  /*
171313  ** Compute a 32-bit checksum on the N-byte buffer.  Return the result.
171314  */
171315  static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
171316    const unsigned char *z = (const unsigned char *)zIn;
171317    unsigned sum0 = 0;
171318    unsigned sum1 = 0;
171319    unsigned sum2 = 0;
171320    unsigned sum3 = 0;
171321    while(N >= 16){
171322      sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
171323      sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
171324      sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
171325      sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
171326      z += 16;
171327      N -= 16;
171328    }
171329    while(N >= 4){
171330      sum0 += z[0];
171331      sum1 += z[1];
171332      sum2 += z[2];
171333      sum3 += z[3];
171334      z += 4;
171335      N -= 4;
171336    }
171337    sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
171338    switch(N){
171339      case 3:   sum3 += (z[2] << 8);
171340      case 2:   sum3 += (z[1] << 16);
171341      case 1:   sum3 += (z[0] << 24);
171342      default:  ;
171343    }
171344    return sum3;
171345  }
171346  #endif
171347  
171348  /*
171349  ** Apply a delta.
171350  **
171351  ** The output buffer should be big enough to hold the whole output
171352  ** file and a NUL terminator at the end.  The delta_output_size()
171353  ** routine will determine this size for you.
171354  **
171355  ** The delta string should be null-terminated.  But the delta string
171356  ** may contain embedded NUL characters (if the input and output are
171357  ** binary files) so we also have to pass in the length of the delta in
171358  ** the lenDelta parameter.
171359  **
171360  ** This function returns the size of the output file in bytes (excluding
171361  ** the final NUL terminator character).  Except, if the delta string is
171362  ** malformed or intended for use with a source file other than zSrc,
171363  ** then this routine returns -1.
171364  **
171365  ** Refer to the delta_create() documentation above for a description
171366  ** of the delta file format.
171367  */
171368  static int rbuDeltaApply(
171369    const char *zSrc,      /* The source or pattern file */
171370    int lenSrc,            /* Length of the source file */
171371    const char *zDelta,    /* Delta to apply to the pattern */
171372    int lenDelta,          /* Length of the delta */
171373    char *zOut             /* Write the output into this preallocated buffer */
171374  ){
171375    unsigned int limit;
171376    unsigned int total = 0;
171377  #if RBU_ENABLE_DELTA_CKSUM
171378    char *zOrigOut = zOut;
171379  #endif
171380  
171381    limit = rbuDeltaGetInt(&zDelta, &lenDelta);
171382    if( *zDelta!='\n' ){
171383      /* ERROR: size integer not terminated by "\n" */
171384      return -1;
171385    }
171386    zDelta++; lenDelta--;
171387    while( *zDelta && lenDelta>0 ){
171388      unsigned int cnt, ofst;
171389      cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
171390      switch( zDelta[0] ){
171391        case '@': {
171392          zDelta++; lenDelta--;
171393          ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
171394          if( lenDelta>0 && zDelta[0]!=',' ){
171395            /* ERROR: copy command not terminated by ',' */
171396            return -1;
171397          }
171398          zDelta++; lenDelta--;
171399          total += cnt;
171400          if( total>limit ){
171401            /* ERROR: copy exceeds output file size */
171402            return -1;
171403          }
171404          if( (int)(ofst+cnt) > lenSrc ){
171405            /* ERROR: copy extends past end of input */
171406            return -1;
171407          }
171408          memcpy(zOut, &zSrc[ofst], cnt);
171409          zOut += cnt;
171410          break;
171411        }
171412        case ':': {
171413          zDelta++; lenDelta--;
171414          total += cnt;
171415          if( total>limit ){
171416            /* ERROR:  insert command gives an output larger than predicted */
171417            return -1;
171418          }
171419          if( (int)cnt>lenDelta ){
171420            /* ERROR: insert count exceeds size of delta */
171421            return -1;
171422          }
171423          memcpy(zOut, zDelta, cnt);
171424          zOut += cnt;
171425          zDelta += cnt;
171426          lenDelta -= cnt;
171427          break;
171428        }
171429        case ';': {
171430          zDelta++; lenDelta--;
171431          zOut[0] = 0;
171432  #if RBU_ENABLE_DELTA_CKSUM
171433          if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
171434            /* ERROR:  bad checksum */
171435            return -1;
171436          }
171437  #endif
171438          if( total!=limit ){
171439            /* ERROR: generated size does not match predicted size */
171440            return -1;
171441          }
171442          return total;
171443        }
171444        default: {
171445          /* ERROR: unknown delta operator */
171446          return -1;
171447        }
171448      }
171449    }
171450    /* ERROR: unterminated delta */
171451    return -1;
171452  }
171453  
171454  static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
171455    int size;
171456    size = rbuDeltaGetInt(&zDelta, &lenDelta);
171457    if( *zDelta!='\n' ){
171458      /* ERROR: size integer not terminated by "\n" */
171459      return -1;
171460    }
171461    return size;
171462  }
171463  
171464  /*
171465  ** End of code taken from fossil.
171466  *************************************************************************/
171467  
171468  /*
171469  ** Implementation of SQL scalar function rbu_fossil_delta().
171470  **
171471  ** This function applies a fossil delta patch to a blob. Exactly two
171472  ** arguments must be passed to this function. The first is the blob to
171473  ** patch and the second the patch to apply. If no error occurs, this
171474  ** function returns the patched blob.
171475  */
171476  static void rbuFossilDeltaFunc(
171477    sqlite3_context *context,
171478    int argc,
171479    sqlite3_value **argv
171480  ){
171481    const char *aDelta;
171482    int nDelta;
171483    const char *aOrig;
171484    int nOrig;
171485  
171486    int nOut;
171487    int nOut2;
171488    char *aOut;
171489  
171490    assert( argc==2 );
171491  
171492    nOrig = sqlite3_value_bytes(argv[0]);
171493    aOrig = (const char*)sqlite3_value_blob(argv[0]);
171494    nDelta = sqlite3_value_bytes(argv[1]);
171495    aDelta = (const char*)sqlite3_value_blob(argv[1]);
171496  
171497    /* Figure out the size of the output */
171498    nOut = rbuDeltaOutputSize(aDelta, nDelta);
171499    if( nOut<0 ){
171500      sqlite3_result_error(context, "corrupt fossil delta", -1);
171501      return;
171502    }
171503  
171504    aOut = sqlite3_malloc(nOut+1);
171505    if( aOut==0 ){
171506      sqlite3_result_error_nomem(context);
171507    }else{
171508      nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
171509      if( nOut2!=nOut ){
171510        sqlite3_result_error(context, "corrupt fossil delta", -1);
171511      }else{
171512        sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
171513      }
171514    }
171515  }
171516  
171517  
171518  /*
171519  ** Prepare the SQL statement in buffer zSql against database handle db.
171520  ** If successful, set *ppStmt to point to the new statement and return
171521  ** SQLITE_OK. 
171522  **
171523  ** Otherwise, if an error does occur, set *ppStmt to NULL and return
171524  ** an SQLite error code. Additionally, set output variable *pzErrmsg to
171525  ** point to a buffer containing an error message. It is the responsibility
171526  ** of the caller to (eventually) free this buffer using sqlite3_free().
171527  */
171528  static int prepareAndCollectError(
171529    sqlite3 *db, 
171530    sqlite3_stmt **ppStmt,
171531    char **pzErrmsg,
171532    const char *zSql
171533  ){
171534    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
171535    if( rc!=SQLITE_OK ){
171536      *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
171537      *ppStmt = 0;
171538    }
171539    return rc;
171540  }
171541  
171542  /*
171543  ** Reset the SQL statement passed as the first argument. Return a copy
171544  ** of the value returned by sqlite3_reset().
171545  **
171546  ** If an error has occurred, then set *pzErrmsg to point to a buffer
171547  ** containing an error message. It is the responsibility of the caller
171548  ** to eventually free this buffer using sqlite3_free().
171549  */
171550  static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
171551    int rc = sqlite3_reset(pStmt);
171552    if( rc!=SQLITE_OK ){
171553      *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
171554    }
171555    return rc;
171556  }
171557  
171558  /*
171559  ** Unless it is NULL, argument zSql points to a buffer allocated using
171560  ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
171561  ** statement against database db and frees the buffer. If statement 
171562  ** compilation is successful, *ppStmt is set to point to the new statement 
171563  ** handle and SQLITE_OK is returned. 
171564  **
171565  ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
171566  ** returned. In this case, *pzErrmsg may also be set to point to an error
171567  ** message. It is the responsibility of the caller to free this error message
171568  ** buffer using sqlite3_free().
171569  **
171570  ** If argument zSql is NULL, this function assumes that an OOM has occurred.
171571  ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
171572  */
171573  static int prepareFreeAndCollectError(
171574    sqlite3 *db, 
171575    sqlite3_stmt **ppStmt,
171576    char **pzErrmsg,
171577    char *zSql
171578  ){
171579    int rc;
171580    assert( *pzErrmsg==0 );
171581    if( zSql==0 ){
171582      rc = SQLITE_NOMEM;
171583      *ppStmt = 0;
171584    }else{
171585      rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
171586      sqlite3_free(zSql);
171587    }
171588    return rc;
171589  }
171590  
171591  /*
171592  ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
171593  ** by an earlier call to rbuObjIterCacheTableInfo().
171594  */
171595  static void rbuObjIterFreeCols(RbuObjIter *pIter){
171596    int i;
171597    for(i=0; i<pIter->nTblCol; i++){
171598      sqlite3_free(pIter->azTblCol[i]);
171599      sqlite3_free(pIter->azTblType[i]);
171600    }
171601    sqlite3_free(pIter->azTblCol);
171602    pIter->azTblCol = 0;
171603    pIter->azTblType = 0;
171604    pIter->aiSrcOrder = 0;
171605    pIter->abTblPk = 0;
171606    pIter->abNotNull = 0;
171607    pIter->nTblCol = 0;
171608    pIter->eType = 0;               /* Invalid value */
171609  }
171610  
171611  /*
171612  ** Finalize all statements and free all allocations that are specific to
171613  ** the current object (table/index pair).
171614  */
171615  static void rbuObjIterClearStatements(RbuObjIter *pIter){
171616    RbuUpdateStmt *pUp;
171617  
171618    sqlite3_finalize(pIter->pSelect);
171619    sqlite3_finalize(pIter->pInsert);
171620    sqlite3_finalize(pIter->pDelete);
171621    sqlite3_finalize(pIter->pTmpInsert);
171622    pUp = pIter->pRbuUpdate;
171623    while( pUp ){
171624      RbuUpdateStmt *pTmp = pUp->pNext;
171625      sqlite3_finalize(pUp->pUpdate);
171626      sqlite3_free(pUp);
171627      pUp = pTmp;
171628    }
171629    
171630    pIter->pSelect = 0;
171631    pIter->pInsert = 0;
171632    pIter->pDelete = 0;
171633    pIter->pRbuUpdate = 0;
171634    pIter->pTmpInsert = 0;
171635    pIter->nCol = 0;
171636  }
171637  
171638  /*
171639  ** Clean up any resources allocated as part of the iterator object passed
171640  ** as the only argument.
171641  */
171642  static void rbuObjIterFinalize(RbuObjIter *pIter){
171643    rbuObjIterClearStatements(pIter);
171644    sqlite3_finalize(pIter->pTblIter);
171645    sqlite3_finalize(pIter->pIdxIter);
171646    rbuObjIterFreeCols(pIter);
171647    memset(pIter, 0, sizeof(RbuObjIter));
171648  }
171649  
171650  /*
171651  ** Advance the iterator to the next position.
171652  **
171653  ** If no error occurs, SQLITE_OK is returned and the iterator is left 
171654  ** pointing to the next entry. Otherwise, an error code and message is 
171655  ** left in the RBU handle passed as the first argument. A copy of the 
171656  ** error code is returned.
171657  */
171658  static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
171659    int rc = p->rc;
171660    if( rc==SQLITE_OK ){
171661  
171662      /* Free any SQLite statements used while processing the previous object */ 
171663      rbuObjIterClearStatements(pIter);
171664      if( pIter->zIdx==0 ){
171665        rc = sqlite3_exec(p->dbMain,
171666            "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
171667            "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
171668            "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
171669            "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
171670            , 0, 0, &p->zErrmsg
171671        );
171672      }
171673  
171674      if( rc==SQLITE_OK ){
171675        if( pIter->bCleanup ){
171676          rbuObjIterFreeCols(pIter);
171677          pIter->bCleanup = 0;
171678          rc = sqlite3_step(pIter->pTblIter);
171679          if( rc!=SQLITE_ROW ){
171680            rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
171681            pIter->zTbl = 0;
171682          }else{
171683            pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
171684            pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
171685            rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
171686          }
171687        }else{
171688          if( pIter->zIdx==0 ){
171689            sqlite3_stmt *pIdx = pIter->pIdxIter;
171690            rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
171691          }
171692          if( rc==SQLITE_OK ){
171693            rc = sqlite3_step(pIter->pIdxIter);
171694            if( rc!=SQLITE_ROW ){
171695              rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
171696              pIter->bCleanup = 1;
171697              pIter->zIdx = 0;
171698            }else{
171699              pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
171700              pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
171701              pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
171702              rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
171703            }
171704          }
171705        }
171706      }
171707    }
171708  
171709    if( rc!=SQLITE_OK ){
171710      rbuObjIterFinalize(pIter);
171711      p->rc = rc;
171712    }
171713    return rc;
171714  }
171715  
171716  
171717  /*
171718  ** The implementation of the rbu_target_name() SQL function. This function
171719  ** accepts one or two arguments. The first argument is the name of a table -
171720  ** the name of a table in the RBU database.  The second, if it is present, is 1
171721  ** for a view or 0 for a table. 
171722  **
171723  ** For a non-vacuum RBU handle, if the table name matches the pattern:
171724  **
171725  **     data[0-9]_<name>
171726  **
171727  ** where <name> is any sequence of 1 or more characters, <name> is returned.
171728  ** Otherwise, if the only argument does not match the above pattern, an SQL
171729  ** NULL is returned.
171730  **
171731  **     "data_t1"     -> "t1"
171732  **     "data0123_t2" -> "t2"
171733  **     "dataAB_t3"   -> NULL
171734  **
171735  ** For an rbu vacuum handle, a copy of the first argument is returned if
171736  ** the second argument is either missing or 0 (not a view).
171737  */
171738  static void rbuTargetNameFunc(
171739    sqlite3_context *pCtx,
171740    int argc,
171741    sqlite3_value **argv
171742  ){
171743    sqlite3rbu *p = sqlite3_user_data(pCtx);
171744    const char *zIn;
171745    assert( argc==1 || argc==2 );
171746  
171747    zIn = (const char*)sqlite3_value_text(argv[0]);
171748    if( zIn ){
171749      if( rbuIsVacuum(p) ){
171750        if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
171751          sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
171752        }
171753      }else{
171754        if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
171755          int i;
171756          for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
171757          if( zIn[i]=='_' && zIn[i+1] ){
171758            sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
171759          }
171760        }
171761      }
171762    }
171763  }
171764  
171765  /*
171766  ** Initialize the iterator structure passed as the second argument.
171767  **
171768  ** If no error occurs, SQLITE_OK is returned and the iterator is left 
171769  ** pointing to the first entry. Otherwise, an error code and message is 
171770  ** left in the RBU handle passed as the first argument. A copy of the 
171771  ** error code is returned.
171772  */
171773  static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
171774    int rc;
171775    memset(pIter, 0, sizeof(RbuObjIter));
171776  
171777    rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg, 
171778      sqlite3_mprintf(
171779        "SELECT rbu_target_name(name, type='view') AS target, name "
171780        "FROM sqlite_master "
171781        "WHERE type IN ('table', 'view') AND target IS NOT NULL "
171782        " %s "
171783        "ORDER BY name"
171784    , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
171785  
171786    if( rc==SQLITE_OK ){
171787      rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
171788          "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
171789          "  FROM main.sqlite_master "
171790          "  WHERE type='index' AND tbl_name = ?"
171791      );
171792    }
171793  
171794    pIter->bCleanup = 1;
171795    p->rc = rc;
171796    return rbuObjIterNext(p, pIter);
171797  }
171798  
171799  /*
171800  ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
171801  ** an error code is stored in the RBU handle passed as the first argument.
171802  **
171803  ** If an error has already occurred (p->rc is already set to something other
171804  ** than SQLITE_OK), then this function returns NULL without modifying the
171805  ** stored error code. In this case it still calls sqlite3_free() on any 
171806  ** printf() parameters associated with %z conversions.
171807  */
171808  static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
171809    char *zSql = 0;
171810    va_list ap;
171811    va_start(ap, zFmt);
171812    zSql = sqlite3_vmprintf(zFmt, ap);
171813    if( p->rc==SQLITE_OK ){
171814      if( zSql==0 ) p->rc = SQLITE_NOMEM;
171815    }else{
171816      sqlite3_free(zSql);
171817      zSql = 0;
171818    }
171819    va_end(ap);
171820    return zSql;
171821  }
171822  
171823  /*
171824  ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
171825  ** arguments are the usual subsitution values. This function performs
171826  ** the printf() style substitutions and executes the result as an SQL
171827  ** statement on the RBU handles database.
171828  **
171829  ** If an error occurs, an error code and error message is stored in the
171830  ** RBU handle. If an error has already occurred when this function is
171831  ** called, it is a no-op.
171832  */
171833  static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
171834    va_list ap;
171835    char *zSql;
171836    va_start(ap, zFmt);
171837    zSql = sqlite3_vmprintf(zFmt, ap);
171838    if( p->rc==SQLITE_OK ){
171839      if( zSql==0 ){
171840        p->rc = SQLITE_NOMEM;
171841      }else{
171842        p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
171843      }
171844    }
171845    sqlite3_free(zSql);
171846    va_end(ap);
171847    return p->rc;
171848  }
171849  
171850  /*
171851  ** Attempt to allocate and return a pointer to a zeroed block of nByte 
171852  ** bytes. 
171853  **
171854  ** If an error (i.e. an OOM condition) occurs, return NULL and leave an 
171855  ** error code in the rbu handle passed as the first argument. Or, if an 
171856  ** error has already occurred when this function is called, return NULL 
171857  ** immediately without attempting the allocation or modifying the stored
171858  ** error code.
171859  */
171860  static void *rbuMalloc(sqlite3rbu *p, int nByte){
171861    void *pRet = 0;
171862    if( p->rc==SQLITE_OK ){
171863      assert( nByte>0 );
171864      pRet = sqlite3_malloc64(nByte);
171865      if( pRet==0 ){
171866        p->rc = SQLITE_NOMEM;
171867      }else{
171868        memset(pRet, 0, nByte);
171869      }
171870    }
171871    return pRet;
171872  }
171873  
171874  
171875  /*
171876  ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
171877  ** there is room for at least nCol elements. If an OOM occurs, store an
171878  ** error code in the RBU handle passed as the first argument.
171879  */
171880  static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
171881    int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
171882    char **azNew;
171883  
171884    azNew = (char**)rbuMalloc(p, nByte);
171885    if( azNew ){
171886      pIter->azTblCol = azNew;
171887      pIter->azTblType = &azNew[nCol];
171888      pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
171889      pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
171890      pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
171891      pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
171892    }
171893  }
171894  
171895  /*
171896  ** The first argument must be a nul-terminated string. This function
171897  ** returns a copy of the string in memory obtained from sqlite3_malloc().
171898  ** It is the responsibility of the caller to eventually free this memory
171899  ** using sqlite3_free().
171900  **
171901  ** If an OOM condition is encountered when attempting to allocate memory,
171902  ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
171903  ** if the allocation succeeds, (*pRc) is left unchanged.
171904  */
171905  static char *rbuStrndup(const char *zStr, int *pRc){
171906    char *zRet = 0;
171907  
171908    assert( *pRc==SQLITE_OK );
171909    if( zStr ){
171910      size_t nCopy = strlen(zStr) + 1;
171911      zRet = (char*)sqlite3_malloc64(nCopy);
171912      if( zRet ){
171913        memcpy(zRet, zStr, nCopy);
171914      }else{
171915        *pRc = SQLITE_NOMEM;
171916      }
171917    }
171918  
171919    return zRet;
171920  }
171921  
171922  /*
171923  ** Finalize the statement passed as the second argument.
171924  **
171925  ** If the sqlite3_finalize() call indicates that an error occurs, and the
171926  ** rbu handle error code is not already set, set the error code and error
171927  ** message accordingly.
171928  */
171929  static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
171930    sqlite3 *db = sqlite3_db_handle(pStmt);
171931    int rc = sqlite3_finalize(pStmt);
171932    if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
171933      p->rc = rc;
171934      p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
171935    }
171936  }
171937  
171938  /* Determine the type of a table.
171939  **
171940  **   peType is of type (int*), a pointer to an output parameter of type
171941  **   (int). This call sets the output parameter as follows, depending
171942  **   on the type of the table specified by parameters dbName and zTbl.
171943  **
171944  **     RBU_PK_NOTABLE:       No such table.
171945  **     RBU_PK_NONE:          Table has an implicit rowid.
171946  **     RBU_PK_IPK:           Table has an explicit IPK column.
171947  **     RBU_PK_EXTERNAL:      Table has an external PK index.
171948  **     RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
171949  **     RBU_PK_VTAB:          Table is a virtual table.
171950  **
171951  **   Argument *piPk is also of type (int*), and also points to an output
171952  **   parameter. Unless the table has an external primary key index 
171953  **   (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
171954  **   if the table does have an external primary key index, then *piPk
171955  **   is set to the root page number of the primary key index before
171956  **   returning.
171957  **
171958  ** ALGORITHM:
171959  **
171960  **   if( no entry exists in sqlite_master ){
171961  **     return RBU_PK_NOTABLE
171962  **   }else if( sql for the entry starts with "CREATE VIRTUAL" ){
171963  **     return RBU_PK_VTAB
171964  **   }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
171965  **     if( the index that is the pk exists in sqlite_master ){
171966  **       *piPK = rootpage of that index.
171967  **       return RBU_PK_EXTERNAL
171968  **     }else{
171969  **       return RBU_PK_WITHOUT_ROWID
171970  **     }
171971  **   }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
171972  **     return RBU_PK_IPK
171973  **   }else{
171974  **     return RBU_PK_NONE
171975  **   }
171976  */
171977  static void rbuTableType(
171978    sqlite3rbu *p,
171979    const char *zTab,
171980    int *peType,
171981    int *piTnum,
171982    int *piPk
171983  ){
171984    /*
171985    ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
171986    ** 1) PRAGMA index_list = ?
171987    ** 2) SELECT count(*) FROM sqlite_master where name=%Q 
171988    ** 3) PRAGMA table_info = ?
171989    */
171990    sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
171991  
171992    *peType = RBU_PK_NOTABLE;
171993    *piPk = 0;
171994  
171995    assert( p->rc==SQLITE_OK );
171996    p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg, 
171997      sqlite3_mprintf(
171998            "SELECT (sql LIKE 'create virtual%%'), rootpage"
171999            "  FROM sqlite_master"
172000            " WHERE name=%Q", zTab
172001    ));
172002    if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
172003      /* Either an error, or no such table. */
172004      goto rbuTableType_end;
172005    }
172006    if( sqlite3_column_int(aStmt[0], 0) ){
172007      *peType = RBU_PK_VTAB;                     /* virtual table */
172008      goto rbuTableType_end;
172009    }
172010    *piTnum = sqlite3_column_int(aStmt[0], 1);
172011  
172012    p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg, 
172013      sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
172014    );
172015    if( p->rc ) goto rbuTableType_end;
172016    while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
172017      const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
172018      const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
172019      if( zOrig && zIdx && zOrig[0]=='p' ){
172020        p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg, 
172021            sqlite3_mprintf(
172022              "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
172023        ));
172024        if( p->rc==SQLITE_OK ){
172025          if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
172026            *piPk = sqlite3_column_int(aStmt[2], 0);
172027            *peType = RBU_PK_EXTERNAL;
172028          }else{
172029            *peType = RBU_PK_WITHOUT_ROWID;
172030          }
172031        }
172032        goto rbuTableType_end;
172033      }
172034    }
172035  
172036    p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg, 
172037      sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
172038    );
172039    if( p->rc==SQLITE_OK ){
172040      while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
172041        if( sqlite3_column_int(aStmt[3],5)>0 ){
172042          *peType = RBU_PK_IPK;                /* explicit IPK column */
172043          goto rbuTableType_end;
172044        }
172045      }
172046      *peType = RBU_PK_NONE;
172047    }
172048  
172049  rbuTableType_end: {
172050      unsigned int i;
172051      for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
172052        rbuFinalize(p, aStmt[i]);
172053      }
172054    }
172055  }
172056  
172057  /*
172058  ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
172059  ** the pIter->abIndexed[] array.
172060  */
172061  static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
172062    sqlite3_stmt *pList = 0;
172063    int bIndex = 0;
172064  
172065    if( p->rc==SQLITE_OK ){
172066      memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
172067      p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
172068          sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
172069      );
172070    }
172071  
172072    pIter->nIndex = 0;
172073    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
172074      const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
172075      sqlite3_stmt *pXInfo = 0;
172076      if( zIdx==0 ) break;
172077      p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
172078          sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
172079      );
172080      while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
172081        int iCid = sqlite3_column_int(pXInfo, 1);
172082        if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
172083      }
172084      rbuFinalize(p, pXInfo);
172085      bIndex = 1;
172086      pIter->nIndex++;
172087    }
172088  
172089    if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
172090      /* "PRAGMA index_list" includes the main PK b-tree */
172091      pIter->nIndex--;
172092    }
172093  
172094    rbuFinalize(p, pList);
172095    if( bIndex==0 ) pIter->abIndexed = 0;
172096  }
172097  
172098  
172099  /*
172100  ** If they are not already populated, populate the pIter->azTblCol[],
172101  ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
172102  ** the table (not index) that the iterator currently points to.
172103  **
172104  ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
172105  ** an error does occur, an error code and error message are also left in 
172106  ** the RBU handle.
172107  */
172108  static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
172109    if( pIter->azTblCol==0 ){
172110      sqlite3_stmt *pStmt = 0;
172111      int nCol = 0;
172112      int i;                        /* for() loop iterator variable */
172113      int bRbuRowid = 0;            /* If input table has column "rbu_rowid" */
172114      int iOrder = 0;
172115      int iTnum = 0;
172116  
172117      /* Figure out the type of table this step will deal with. */
172118      assert( pIter->eType==0 );
172119      rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
172120      if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
172121        p->rc = SQLITE_ERROR;
172122        p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
172123      }
172124      if( p->rc ) return p->rc;
172125      if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
172126  
172127      assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK 
172128           || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
172129           || pIter->eType==RBU_PK_VTAB
172130      );
172131  
172132      /* Populate the azTblCol[] and nTblCol variables based on the columns
172133      ** of the input table. Ignore any input table columns that begin with
172134      ** "rbu_".  */
172135      p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, 
172136          sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
172137      );
172138      if( p->rc==SQLITE_OK ){
172139        nCol = sqlite3_column_count(pStmt);
172140        rbuAllocateIterArrays(p, pIter, nCol);
172141      }
172142      for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
172143        const char *zName = (const char*)sqlite3_column_name(pStmt, i);
172144        if( sqlite3_strnicmp("rbu_", zName, 4) ){
172145          char *zCopy = rbuStrndup(zName, &p->rc);
172146          pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
172147          pIter->azTblCol[pIter->nTblCol++] = zCopy;
172148        }
172149        else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
172150          bRbuRowid = 1;
172151        }
172152      }
172153      sqlite3_finalize(pStmt);
172154      pStmt = 0;
172155  
172156      if( p->rc==SQLITE_OK
172157       && rbuIsVacuum(p)==0
172158       && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
172159      ){
172160        p->rc = SQLITE_ERROR;
172161        p->zErrmsg = sqlite3_mprintf(
172162            "table %q %s rbu_rowid column", pIter->zDataTbl,
172163            (bRbuRowid ? "may not have" : "requires")
172164        );
172165      }
172166  
172167      /* Check that all non-HIDDEN columns in the destination table are also
172168      ** present in the input table. Populate the abTblPk[], azTblType[] and
172169      ** aiTblOrder[] arrays at the same time.  */
172170      if( p->rc==SQLITE_OK ){
172171        p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg, 
172172            sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
172173        );
172174      }
172175      while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
172176        const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
172177        if( zName==0 ) break;  /* An OOM - finalize() below returns S_NOMEM */
172178        for(i=iOrder; i<pIter->nTblCol; i++){
172179          if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
172180        }
172181        if( i==pIter->nTblCol ){
172182          p->rc = SQLITE_ERROR;
172183          p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
172184              pIter->zDataTbl, zName
172185          );
172186        }else{
172187          int iPk = sqlite3_column_int(pStmt, 5);
172188          int bNotNull = sqlite3_column_int(pStmt, 3);
172189          const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
172190  
172191          if( i!=iOrder ){
172192            SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
172193            SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
172194          }
172195  
172196          pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
172197          pIter->abTblPk[iOrder] = (iPk!=0);
172198          pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
172199          iOrder++;
172200        }
172201      }
172202  
172203      rbuFinalize(p, pStmt);
172204      rbuObjIterCacheIndexedCols(p, pIter);
172205      assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
172206      assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
172207    }
172208  
172209    return p->rc;
172210  }
172211  
172212  /*
172213  ** This function constructs and returns a pointer to a nul-terminated 
172214  ** string containing some SQL clause or list based on one or more of the 
172215  ** column names currently stored in the pIter->azTblCol[] array.
172216  */
172217  static char *rbuObjIterGetCollist(
172218    sqlite3rbu *p,                  /* RBU object */
172219    RbuObjIter *pIter               /* Object iterator for column names */
172220  ){
172221    char *zList = 0;
172222    const char *zSep = "";
172223    int i;
172224    for(i=0; i<pIter->nTblCol; i++){
172225      const char *z = pIter->azTblCol[i];
172226      zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
172227      zSep = ", ";
172228    }
172229    return zList;
172230  }
172231  
172232  /*
172233  ** This function is used to create a SELECT list (the list of SQL 
172234  ** expressions that follows a SELECT keyword) for a SELECT statement 
172235  ** used to read from an data_xxx or rbu_tmp_xxx table while updating the 
172236  ** index object currently indicated by the iterator object passed as the 
172237  ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used 
172238  ** to obtain the required information.
172239  **
172240  ** If the index is of the following form:
172241  **
172242  **   CREATE INDEX i1 ON t1(c, b COLLATE nocase);
172243  **
172244  ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column 
172245  ** "ipk", the returned string is:
172246  **
172247  **   "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
172248  **
172249  ** As well as the returned string, three other malloc'd strings are 
172250  ** returned via output parameters. As follows:
172251  **
172252  **   pzImposterCols: ...
172253  **   pzImposterPk: ...
172254  **   pzWhere: ...
172255  */
172256  static char *rbuObjIterGetIndexCols(
172257    sqlite3rbu *p,                  /* RBU object */
172258    RbuObjIter *pIter,              /* Object iterator for column names */
172259    char **pzImposterCols,          /* OUT: Columns for imposter table */
172260    char **pzImposterPk,            /* OUT: Imposter PK clause */
172261    char **pzWhere,                 /* OUT: WHERE clause */
172262    int *pnBind                     /* OUT: Trbul number of columns */
172263  ){
172264    int rc = p->rc;                 /* Error code */
172265    int rc2;                        /* sqlite3_finalize() return code */
172266    char *zRet = 0;                 /* String to return */
172267    char *zImpCols = 0;             /* String to return via *pzImposterCols */
172268    char *zImpPK = 0;               /* String to return via *pzImposterPK */
172269    char *zWhere = 0;               /* String to return via *pzWhere */
172270    int nBind = 0;                  /* Value to return via *pnBind */
172271    const char *zCom = "";          /* Set to ", " later on */
172272    const char *zAnd = "";          /* Set to " AND " later on */
172273    sqlite3_stmt *pXInfo = 0;       /* PRAGMA index_xinfo = ? */
172274  
172275    if( rc==SQLITE_OK ){
172276      assert( p->zErrmsg==0 );
172277      rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
172278          sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
172279      );
172280    }
172281  
172282    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
172283      int iCid = sqlite3_column_int(pXInfo, 1);
172284      int bDesc = sqlite3_column_int(pXInfo, 3);
172285      const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
172286      const char *zCol;
172287      const char *zType;
172288  
172289      if( iCid<0 ){
172290        /* An integer primary key. If the table has an explicit IPK, use
172291        ** its name. Otherwise, use "rbu_rowid".  */
172292        if( pIter->eType==RBU_PK_IPK ){
172293          int i;
172294          for(i=0; pIter->abTblPk[i]==0; i++);
172295          assert( i<pIter->nTblCol );
172296          zCol = pIter->azTblCol[i];
172297        }else if( rbuIsVacuum(p) ){
172298          zCol = "_rowid_";
172299        }else{
172300          zCol = "rbu_rowid";
172301        }
172302        zType = "INTEGER";
172303      }else{
172304        zCol = pIter->azTblCol[iCid];
172305        zType = pIter->azTblType[iCid];
172306      }
172307  
172308      zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
172309      if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
172310        const char *zOrder = (bDesc ? " DESC" : "");
172311        zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s", 
172312            zImpPK, zCom, nBind, zCol, zOrder
172313        );
172314      }
172315      zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q", 
172316          zImpCols, zCom, nBind, zCol, zType, zCollate
172317      );
172318      zWhere = sqlite3_mprintf(
172319          "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
172320      );
172321      if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
172322      zCom = ", ";
172323      zAnd = " AND ";
172324      nBind++;
172325    }
172326  
172327    rc2 = sqlite3_finalize(pXInfo);
172328    if( rc==SQLITE_OK ) rc = rc2;
172329  
172330    if( rc!=SQLITE_OK ){
172331      sqlite3_free(zRet);
172332      sqlite3_free(zImpCols);
172333      sqlite3_free(zImpPK);
172334      sqlite3_free(zWhere);
172335      zRet = 0;
172336      zImpCols = 0;
172337      zImpPK = 0;
172338      zWhere = 0;
172339      p->rc = rc;
172340    }
172341  
172342    *pzImposterCols = zImpCols;
172343    *pzImposterPk = zImpPK;
172344    *pzWhere = zWhere;
172345    *pnBind = nBind;
172346    return zRet;
172347  }
172348  
172349  /*
172350  ** Assuming the current table columns are "a", "b" and "c", and the zObj
172351  ** paramter is passed "old", return a string of the form:
172352  **
172353  **     "old.a, old.b, old.b"
172354  **
172355  ** With the column names escaped.
172356  **
172357  ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
172358  ** the text ", old._rowid_" to the returned value.
172359  */
172360  static char *rbuObjIterGetOldlist(
172361    sqlite3rbu *p, 
172362    RbuObjIter *pIter,
172363    const char *zObj
172364  ){
172365    char *zList = 0;
172366    if( p->rc==SQLITE_OK && pIter->abIndexed ){
172367      const char *zS = "";
172368      int i;
172369      for(i=0; i<pIter->nTblCol; i++){
172370        if( pIter->abIndexed[i] ){
172371          const char *zCol = pIter->azTblCol[i];
172372          zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
172373        }else{
172374          zList = sqlite3_mprintf("%z%sNULL", zList, zS);
172375        }
172376        zS = ", ";
172377        if( zList==0 ){
172378          p->rc = SQLITE_NOMEM;
172379          break;
172380        }
172381      }
172382  
172383      /* For a table with implicit rowids, append "old._rowid_" to the list. */
172384      if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
172385        zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
172386      }
172387    }
172388    return zList;
172389  }
172390  
172391  /*
172392  ** Return an expression that can be used in a WHERE clause to match the
172393  ** primary key of the current table. For example, if the table is:
172394  **
172395  **   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
172396  **
172397  ** Return the string:
172398  **
172399  **   "b = ?1 AND c = ?2"
172400  */
172401  static char *rbuObjIterGetWhere(
172402    sqlite3rbu *p, 
172403    RbuObjIter *pIter
172404  ){
172405    char *zList = 0;
172406    if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
172407      zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
172408    }else if( pIter->eType==RBU_PK_EXTERNAL ){
172409      const char *zSep = "";
172410      int i;
172411      for(i=0; i<pIter->nTblCol; i++){
172412        if( pIter->abTblPk[i] ){
172413          zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
172414          zSep = " AND ";
172415        }
172416      }
172417      zList = rbuMPrintf(p, 
172418          "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
172419      );
172420  
172421    }else{
172422      const char *zSep = "";
172423      int i;
172424      for(i=0; i<pIter->nTblCol; i++){
172425        if( pIter->abTblPk[i] ){
172426          const char *zCol = pIter->azTblCol[i];
172427          zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
172428          zSep = " AND ";
172429        }
172430      }
172431    }
172432    return zList;
172433  }
172434  
172435  /*
172436  ** The SELECT statement iterating through the keys for the current object
172437  ** (p->objiter.pSelect) currently points to a valid row. However, there
172438  ** is something wrong with the rbu_control value in the rbu_control value
172439  ** stored in the (p->nCol+1)'th column. Set the error code and error message
172440  ** of the RBU handle to something reflecting this.
172441  */
172442  static void rbuBadControlError(sqlite3rbu *p){
172443    p->rc = SQLITE_ERROR;
172444    p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
172445  }
172446  
172447  
172448  /*
172449  ** Return a nul-terminated string containing the comma separated list of
172450  ** assignments that should be included following the "SET" keyword of
172451  ** an UPDATE statement used to update the table object that the iterator
172452  ** passed as the second argument currently points to if the rbu_control
172453  ** column of the data_xxx table entry is set to zMask.
172454  **
172455  ** The memory for the returned string is obtained from sqlite3_malloc().
172456  ** It is the responsibility of the caller to eventually free it using
172457  ** sqlite3_free(). 
172458  **
172459  ** If an OOM error is encountered when allocating space for the new
172460  ** string, an error code is left in the rbu handle passed as the first
172461  ** argument and NULL is returned. Or, if an error has already occurred
172462  ** when this function is called, NULL is returned immediately, without
172463  ** attempting the allocation or modifying the stored error code.
172464  */
172465  static char *rbuObjIterGetSetlist(
172466    sqlite3rbu *p,
172467    RbuObjIter *pIter,
172468    const char *zMask
172469  ){
172470    char *zList = 0;
172471    if( p->rc==SQLITE_OK ){
172472      int i;
172473  
172474      if( (int)strlen(zMask)!=pIter->nTblCol ){
172475        rbuBadControlError(p);
172476      }else{
172477        const char *zSep = "";
172478        for(i=0; i<pIter->nTblCol; i++){
172479          char c = zMask[pIter->aiSrcOrder[i]];
172480          if( c=='x' ){
172481            zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", 
172482                zList, zSep, pIter->azTblCol[i], i+1
172483            );
172484            zSep = ", ";
172485          }
172486          else if( c=='d' ){
172487            zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)", 
172488                zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
172489            );
172490            zSep = ", ";
172491          }
172492          else if( c=='f' ){
172493            zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)", 
172494                zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
172495            );
172496            zSep = ", ";
172497          }
172498        }
172499      }
172500    }
172501    return zList;
172502  }
172503  
172504  /*
172505  ** Return a nul-terminated string consisting of nByte comma separated
172506  ** "?" expressions. For example, if nByte is 3, return a pointer to
172507  ** a buffer containing the string "?,?,?".
172508  **
172509  ** The memory for the returned string is obtained from sqlite3_malloc().
172510  ** It is the responsibility of the caller to eventually free it using
172511  ** sqlite3_free(). 
172512  **
172513  ** If an OOM error is encountered when allocating space for the new
172514  ** string, an error code is left in the rbu handle passed as the first
172515  ** argument and NULL is returned. Or, if an error has already occurred
172516  ** when this function is called, NULL is returned immediately, without
172517  ** attempting the allocation or modifying the stored error code.
172518  */
172519  static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
172520    char *zRet = 0;
172521    int nByte = nBind*2 + 1;
172522  
172523    zRet = (char*)rbuMalloc(p, nByte);
172524    if( zRet ){
172525      int i;
172526      for(i=0; i<nBind; i++){
172527        zRet[i*2] = '?';
172528        zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
172529      }
172530    }
172531    return zRet;
172532  }
172533  
172534  /*
172535  ** The iterator currently points to a table (not index) of type 
172536  ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY 
172537  ** declaration for the corresponding imposter table. For example,
172538  ** if the iterator points to a table created as:
172539  **
172540  **   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
172541  **
172542  ** this function returns:
172543  **
172544  **   PRIMARY KEY("b", "a" DESC)
172545  */
172546  static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
172547    char *z = 0;
172548    assert( pIter->zIdx==0 );
172549    if( p->rc==SQLITE_OK ){
172550      const char *zSep = "PRIMARY KEY(";
172551      sqlite3_stmt *pXList = 0;     /* PRAGMA index_list = (pIter->zTbl) */
172552      sqlite3_stmt *pXInfo = 0;     /* PRAGMA index_xinfo = <pk-index> */
172553     
172554      p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
172555          sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
172556      );
172557      while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
172558        const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
172559        if( zOrig && strcmp(zOrig, "pk")==0 ){
172560          const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
172561          if( zIdx ){
172562            p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
172563                sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
172564            );
172565          }
172566          break;
172567        }
172568      }
172569      rbuFinalize(p, pXList);
172570  
172571      while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
172572        if( sqlite3_column_int(pXInfo, 5) ){
172573          /* int iCid = sqlite3_column_int(pXInfo, 0); */
172574          const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
172575          const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
172576          z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
172577          zSep = ", ";
172578        }
172579      }
172580      z = rbuMPrintf(p, "%z)", z);
172581      rbuFinalize(p, pXInfo);
172582    }
172583    return z;
172584  }
172585  
172586  /*
172587  ** This function creates the second imposter table used when writing to
172588  ** a table b-tree where the table has an external primary key. If the
172589  ** iterator passed as the second argument does not currently point to
172590  ** a table (not index) with an external primary key, this function is a
172591  ** no-op. 
172592  **
172593  ** Assuming the iterator does point to a table with an external PK, this
172594  ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
172595  ** used to access that PK index. For example, if the target table is
172596  ** declared as follows:
172597  **
172598  **   CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
172599  **
172600  ** then the imposter table schema is:
172601  **
172602  **   CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
172603  **
172604  */
172605  static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
172606    if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
172607      int tnum = pIter->iPkTnum;    /* Root page of PK index */
172608      sqlite3_stmt *pQuery = 0;     /* SELECT name ... WHERE rootpage = $tnum */
172609      const char *zIdx = 0;         /* Name of PK index */
172610      sqlite3_stmt *pXInfo = 0;     /* PRAGMA main.index_xinfo = $zIdx */
172611      const char *zComma = "";
172612      char *zCols = 0;              /* Used to build up list of table cols */
172613      char *zPk = 0;                /* Used to build up table PK declaration */
172614  
172615      /* Figure out the name of the primary key index for the current table.
172616      ** This is needed for the argument to "PRAGMA index_xinfo". Set
172617      ** zIdx to point to a nul-terminated string containing this name. */
172618      p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg, 
172619          "SELECT name FROM sqlite_master WHERE rootpage = ?"
172620      );
172621      if( p->rc==SQLITE_OK ){
172622        sqlite3_bind_int(pQuery, 1, tnum);
172623        if( SQLITE_ROW==sqlite3_step(pQuery) ){
172624          zIdx = (const char*)sqlite3_column_text(pQuery, 0);
172625        }
172626      }
172627      if( zIdx ){
172628        p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
172629            sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
172630        );
172631      }
172632      rbuFinalize(p, pQuery);
172633  
172634      while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
172635        int bKey = sqlite3_column_int(pXInfo, 5);
172636        if( bKey ){
172637          int iCid = sqlite3_column_int(pXInfo, 1);
172638          int bDesc = sqlite3_column_int(pXInfo, 3);
172639          const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
172640          zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma, 
172641              iCid, pIter->azTblType[iCid], zCollate
172642          );
172643          zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
172644          zComma = ", ";
172645        }
172646      }
172647      zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
172648      rbuFinalize(p, pXInfo);
172649  
172650      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
172651      rbuMPrintfExec(p, p->dbMain,
172652          "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID", 
172653          zCols, zPk
172654      );
172655      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
172656    }
172657  }
172658  
172659  /*
172660  ** If an error has already occurred when this function is called, it 
172661  ** immediately returns zero (without doing any work). Or, if an error
172662  ** occurs during the execution of this function, it sets the error code
172663  ** in the sqlite3rbu object indicated by the first argument and returns
172664  ** zero.
172665  **
172666  ** The iterator passed as the second argument is guaranteed to point to
172667  ** a table (not an index) when this function is called. This function
172668  ** attempts to create any imposter table required to write to the main
172669  ** table b-tree of the table before returning. Non-zero is returned if
172670  ** an imposter table are created, or zero otherwise.
172671  **
172672  ** An imposter table is required in all cases except RBU_PK_VTAB. Only
172673  ** virtual tables are written to directly. The imposter table has the 
172674  ** same schema as the actual target table (less any UNIQUE constraints). 
172675  ** More precisely, the "same schema" means the same columns, types, 
172676  ** collation sequences. For tables that do not have an external PRIMARY
172677  ** KEY, it also means the same PRIMARY KEY declaration.
172678  */
172679  static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
172680    if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
172681      int tnum = pIter->iTnum;
172682      const char *zComma = "";
172683      char *zSql = 0;
172684      int iCol;
172685      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
172686  
172687      for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
172688        const char *zPk = "";
172689        const char *zCol = pIter->azTblCol[iCol];
172690        const char *zColl = 0;
172691  
172692        p->rc = sqlite3_table_column_metadata(
172693            p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
172694        );
172695  
172696        if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
172697          /* If the target table column is an "INTEGER PRIMARY KEY", add
172698          ** "PRIMARY KEY" to the imposter table column declaration. */
172699          zPk = "PRIMARY KEY ";
172700        }
172701        zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s", 
172702            zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
172703            (pIter->abNotNull[iCol] ? " NOT NULL" : "")
172704        );
172705        zComma = ", ";
172706      }
172707  
172708      if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
172709        char *zPk = rbuWithoutRowidPK(p, pIter);
172710        if( zPk ){
172711          zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
172712        }
172713      }
172714  
172715      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
172716      rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s", 
172717          pIter->zTbl, zSql, 
172718          (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
172719      );
172720      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
172721    }
172722  }
172723  
172724  /*
172725  ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
172726  ** Specifically a statement of the form:
172727  **
172728  **     INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
172729  **
172730  ** The number of bound variables is equal to the number of columns in
172731  ** the target table, plus one (for the rbu_control column), plus one more 
172732  ** (for the rbu_rowid column) if the target table is an implicit IPK or 
172733  ** virtual table.
172734  */
172735  static void rbuObjIterPrepareTmpInsert(
172736    sqlite3rbu *p, 
172737    RbuObjIter *pIter,
172738    const char *zCollist,
172739    const char *zRbuRowid
172740  ){
172741    int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
172742    char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
172743    if( zBind ){
172744      assert( pIter->pTmpInsert==0 );
172745      p->rc = prepareFreeAndCollectError(
172746          p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
172747            "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)", 
172748            p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
172749      ));
172750    }
172751  }
172752  
172753  static void rbuTmpInsertFunc(
172754    sqlite3_context *pCtx, 
172755    int nVal,
172756    sqlite3_value **apVal
172757  ){
172758    sqlite3rbu *p = sqlite3_user_data(pCtx);
172759    int rc = SQLITE_OK;
172760    int i;
172761  
172762    assert( sqlite3_value_int(apVal[0])!=0
172763        || p->objiter.eType==RBU_PK_EXTERNAL 
172764        || p->objiter.eType==RBU_PK_NONE 
172765    );
172766    if( sqlite3_value_int(apVal[0])!=0 ){
172767      p->nPhaseOneStep += p->objiter.nIndex;
172768    }
172769  
172770    for(i=0; rc==SQLITE_OK && i<nVal; i++){
172771      rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
172772    }
172773    if( rc==SQLITE_OK ){
172774      sqlite3_step(p->objiter.pTmpInsert);
172775      rc = sqlite3_reset(p->objiter.pTmpInsert);
172776    }
172777  
172778    if( rc!=SQLITE_OK ){
172779      sqlite3_result_error_code(pCtx, rc);
172780    }
172781  }
172782  
172783  /*
172784  ** Ensure that the SQLite statement handles required to update the 
172785  ** target database object currently indicated by the iterator passed 
172786  ** as the second argument are available.
172787  */
172788  static int rbuObjIterPrepareAll(
172789    sqlite3rbu *p, 
172790    RbuObjIter *pIter,
172791    int nOffset                     /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
172792  ){
172793    assert( pIter->bCleanup==0 );
172794    if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
172795      const int tnum = pIter->iTnum;
172796      char *zCollist = 0;           /* List of indexed columns */
172797      char **pz = &p->zErrmsg;
172798      const char *zIdx = pIter->zIdx;
172799      char *zLimit = 0;
172800  
172801      if( nOffset ){
172802        zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
172803        if( !zLimit ) p->rc = SQLITE_NOMEM;
172804      }
172805  
172806      if( zIdx ){
172807        const char *zTbl = pIter->zTbl;
172808        char *zImposterCols = 0;    /* Columns for imposter table */
172809        char *zImposterPK = 0;      /* Primary key declaration for imposter */
172810        char *zWhere = 0;           /* WHERE clause on PK columns */
172811        char *zBind = 0;
172812        int nBind = 0;
172813  
172814        assert( pIter->eType!=RBU_PK_VTAB );
172815        zCollist = rbuObjIterGetIndexCols(
172816            p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
172817        );
172818        zBind = rbuObjIterGetBindlist(p, nBind);
172819  
172820        /* Create the imposter table used to write to this index. */
172821        sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
172822        sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
172823        rbuMPrintfExec(p, p->dbMain,
172824            "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
172825            zTbl, zImposterCols, zImposterPK
172826        );
172827        sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
172828  
172829        /* Create the statement to insert index entries */
172830        pIter->nCol = nBind;
172831        if( p->rc==SQLITE_OK ){
172832          p->rc = prepareFreeAndCollectError(
172833              p->dbMain, &pIter->pInsert, &p->zErrmsg,
172834            sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
172835          );
172836        }
172837  
172838        /* And to delete index entries */
172839        if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
172840          p->rc = prepareFreeAndCollectError(
172841              p->dbMain, &pIter->pDelete, &p->zErrmsg,
172842            sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
172843          );
172844        }
172845  
172846        /* Create the SELECT statement to read keys in sorted order */
172847        if( p->rc==SQLITE_OK ){
172848          char *zSql;
172849          if( rbuIsVacuum(p) ){
172850            zSql = sqlite3_mprintf(
172851                "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s",
172852                zCollist, 
172853                pIter->zDataTbl,
172854                zCollist, zLimit
172855            );
172856          }else
172857  
172858          if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
172859            zSql = sqlite3_mprintf(
172860                "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
172861                zCollist, p->zStateDb, pIter->zDataTbl,
172862                zCollist, zLimit
172863            );
172864          }else{
172865            zSql = sqlite3_mprintf(
172866                "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
172867                "UNION ALL "
172868                "SELECT %s, rbu_control FROM '%q' "
172869                "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
172870                "ORDER BY %s%s",
172871                zCollist, p->zStateDb, pIter->zDataTbl, 
172872                zCollist, pIter->zDataTbl, 
172873                zCollist, zLimit
172874            );
172875          }
172876          p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
172877        }
172878  
172879        sqlite3_free(zImposterCols);
172880        sqlite3_free(zImposterPK);
172881        sqlite3_free(zWhere);
172882        sqlite3_free(zBind);
172883      }else{
172884        int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
172885                      ||(pIter->eType==RBU_PK_NONE)
172886                      ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
172887        const char *zTbl = pIter->zTbl;       /* Table this step applies to */
172888        const char *zWrite;                   /* Imposter table name */
172889  
172890        char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
172891        char *zWhere = rbuObjIterGetWhere(p, pIter);
172892        char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
172893        char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
172894  
172895        zCollist = rbuObjIterGetCollist(p, pIter);
172896        pIter->nCol = pIter->nTblCol;
172897  
172898        /* Create the imposter table or tables (if required). */
172899        rbuCreateImposterTable(p, pIter);
172900        rbuCreateImposterTable2(p, pIter);
172901        zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
172902  
172903        /* Create the INSERT statement to write to the target PK b-tree */
172904        if( p->rc==SQLITE_OK ){
172905          p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
172906              sqlite3_mprintf(
172907                "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)", 
172908                zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
172909              )
172910          );
172911        }
172912  
172913        /* Create the DELETE statement to write to the target PK b-tree.
172914        ** Because it only performs INSERT operations, this is not required for
172915        ** an rbu vacuum handle.  */
172916        if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
172917          p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
172918              sqlite3_mprintf(
172919                "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
172920              )
172921          );
172922        }
172923  
172924        if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
172925          const char *zRbuRowid = "";
172926          if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
172927            zRbuRowid = ", rbu_rowid";
172928          }
172929  
172930          /* Create the rbu_tmp_xxx table and the triggers to populate it. */
172931          rbuMPrintfExec(p, p->dbRbu,
172932              "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
172933              "SELECT *%s FROM '%q' WHERE 0;"
172934              , p->zStateDb, pIter->zDataTbl
172935              , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
172936              , pIter->zDataTbl
172937          );
172938  
172939          rbuMPrintfExec(p, p->dbMain,
172940              "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
172941              "BEGIN "
172942              "  SELECT rbu_tmp_insert(3, %s);"
172943              "END;"
172944  
172945              "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
172946              "BEGIN "
172947              "  SELECT rbu_tmp_insert(3, %s);"
172948              "END;"
172949  
172950              "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
172951              "BEGIN "
172952              "  SELECT rbu_tmp_insert(4, %s);"
172953              "END;",
172954              zWrite, zTbl, zOldlist,
172955              zWrite, zTbl, zOldlist,
172956              zWrite, zTbl, zNewlist
172957          );
172958  
172959          if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
172960            rbuMPrintfExec(p, p->dbMain,
172961                "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
172962                "BEGIN "
172963                "  SELECT rbu_tmp_insert(0, %s);"
172964                "END;",
172965                zWrite, zTbl, zNewlist
172966            );
172967          }
172968  
172969          rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
172970        }
172971  
172972        /* Create the SELECT statement to read keys from data_xxx */
172973        if( p->rc==SQLITE_OK ){
172974          const char *zRbuRowid = "";
172975          if( bRbuRowid ){
172976            zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
172977          }
172978          p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
172979              sqlite3_mprintf(
172980                "SELECT %s,%s rbu_control%s FROM '%q'%s", 
172981                zCollist, 
172982                (rbuIsVacuum(p) ? "0 AS " : ""),
172983                zRbuRowid,
172984                pIter->zDataTbl, zLimit
172985              )
172986          );
172987        }
172988  
172989        sqlite3_free(zWhere);
172990        sqlite3_free(zOldlist);
172991        sqlite3_free(zNewlist);
172992        sqlite3_free(zBindings);
172993      }
172994      sqlite3_free(zCollist);
172995      sqlite3_free(zLimit);
172996    }
172997    
172998    return p->rc;
172999  }
173000  
173001  /*
173002  ** Set output variable *ppStmt to point to an UPDATE statement that may
173003  ** be used to update the imposter table for the main table b-tree of the
173004  ** table object that pIter currently points to, assuming that the 
173005  ** rbu_control column of the data_xyz table contains zMask.
173006  ** 
173007  ** If the zMask string does not specify any columns to update, then this
173008  ** is not an error. Output variable *ppStmt is set to NULL in this case.
173009  */
173010  static int rbuGetUpdateStmt(
173011    sqlite3rbu *p,                  /* RBU handle */
173012    RbuObjIter *pIter,              /* Object iterator */
173013    const char *zMask,              /* rbu_control value ('x.x.') */
173014    sqlite3_stmt **ppStmt           /* OUT: UPDATE statement handle */
173015  ){
173016    RbuUpdateStmt **pp;
173017    RbuUpdateStmt *pUp = 0;
173018    int nUp = 0;
173019  
173020    /* In case an error occurs */
173021    *ppStmt = 0;
173022  
173023    /* Search for an existing statement. If one is found, shift it to the front
173024    ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
173025    ** to the number of statements currently in the cache and pUp to the
173026    ** last object in the list.  */
173027    for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
173028      pUp = *pp;
173029      if( strcmp(pUp->zMask, zMask)==0 ){
173030        *pp = pUp->pNext;
173031        pUp->pNext = pIter->pRbuUpdate;
173032        pIter->pRbuUpdate = pUp;
173033        *ppStmt = pUp->pUpdate; 
173034        return SQLITE_OK;
173035      }
173036      nUp++;
173037    }
173038    assert( pUp==0 || pUp->pNext==0 );
173039  
173040    if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
173041      for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
173042      *pp = 0;
173043      sqlite3_finalize(pUp->pUpdate);
173044      pUp->pUpdate = 0;
173045    }else{
173046      pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
173047    }
173048  
173049    if( pUp ){
173050      char *zWhere = rbuObjIterGetWhere(p, pIter);
173051      char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
173052      char *zUpdate = 0;
173053  
173054      pUp->zMask = (char*)&pUp[1];
173055      memcpy(pUp->zMask, zMask, pIter->nTblCol);
173056      pUp->pNext = pIter->pRbuUpdate;
173057      pIter->pRbuUpdate = pUp;
173058  
173059      if( zSet ){
173060        const char *zPrefix = "";
173061  
173062        if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
173063        zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s", 
173064            zPrefix, pIter->zTbl, zSet, zWhere
173065        );
173066        p->rc = prepareFreeAndCollectError(
173067            p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
173068        );
173069        *ppStmt = pUp->pUpdate;
173070      }
173071      sqlite3_free(zWhere);
173072      sqlite3_free(zSet);
173073    }
173074  
173075    return p->rc;
173076  }
173077  
173078  static sqlite3 *rbuOpenDbhandle(
173079    sqlite3rbu *p, 
173080    const char *zName, 
173081    int bUseVfs
173082  ){
173083    sqlite3 *db = 0;
173084    if( p->rc==SQLITE_OK ){
173085      const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
173086      p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
173087      if( p->rc ){
173088        p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
173089        sqlite3_close(db);
173090        db = 0;
173091      }
173092    }
173093    return db;
173094  }
173095  
173096  /*
173097  ** Free an RbuState object allocated by rbuLoadState().
173098  */
173099  static void rbuFreeState(RbuState *p){
173100    if( p ){
173101      sqlite3_free(p->zTbl);
173102      sqlite3_free(p->zIdx);
173103      sqlite3_free(p);
173104    }
173105  }
173106  
173107  /*
173108  ** Allocate an RbuState object and load the contents of the rbu_state 
173109  ** table into it. Return a pointer to the new object. It is the 
173110  ** responsibility of the caller to eventually free the object using
173111  ** sqlite3_free().
173112  **
173113  ** If an error occurs, leave an error code and message in the rbu handle
173114  ** and return NULL.
173115  */
173116  static RbuState *rbuLoadState(sqlite3rbu *p){
173117    RbuState *pRet = 0;
173118    sqlite3_stmt *pStmt = 0;
173119    int rc;
173120    int rc2;
173121  
173122    pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
173123    if( pRet==0 ) return 0;
173124  
173125    rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, 
173126        sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
173127    );
173128    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
173129      switch( sqlite3_column_int(pStmt, 0) ){
173130        case RBU_STATE_STAGE:
173131          pRet->eStage = sqlite3_column_int(pStmt, 1);
173132          if( pRet->eStage!=RBU_STAGE_OAL
173133           && pRet->eStage!=RBU_STAGE_MOVE
173134           && pRet->eStage!=RBU_STAGE_CKPT
173135          ){
173136            p->rc = SQLITE_CORRUPT;
173137          }
173138          break;
173139  
173140        case RBU_STATE_TBL:
173141          pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
173142          break;
173143  
173144        case RBU_STATE_IDX:
173145          pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
173146          break;
173147  
173148        case RBU_STATE_ROW:
173149          pRet->nRow = sqlite3_column_int(pStmt, 1);
173150          break;
173151  
173152        case RBU_STATE_PROGRESS:
173153          pRet->nProgress = sqlite3_column_int64(pStmt, 1);
173154          break;
173155  
173156        case RBU_STATE_CKPT:
173157          pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
173158          break;
173159  
173160        case RBU_STATE_COOKIE:
173161          pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
173162          break;
173163  
173164        case RBU_STATE_OALSZ:
173165          pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
173166          break;
173167  
173168        case RBU_STATE_PHASEONESTEP:
173169          pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
173170          break;
173171  
173172        default:
173173          rc = SQLITE_CORRUPT;
173174          break;
173175      }
173176    }
173177    rc2 = sqlite3_finalize(pStmt);
173178    if( rc==SQLITE_OK ) rc = rc2;
173179  
173180    p->rc = rc;
173181    return pRet;
173182  }
173183  
173184  
173185  /*
173186  ** Open the database handle and attach the RBU database as "rbu". If an
173187  ** error occurs, leave an error code and message in the RBU handle.
173188  */
173189  static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
173190    assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
173191    assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
173192  
173193    /* Open the RBU database */
173194    p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
173195  
173196    if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
173197      sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
173198      if( p->zState==0 ){
173199        const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
173200        p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile);
173201      }
173202    }
173203  
173204    /* If using separate RBU and state databases, attach the state database to
173205    ** the RBU db handle now.  */
173206    if( p->zState ){
173207      rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
173208      memcpy(p->zStateDb, "stat", 4);
173209    }else{
173210      memcpy(p->zStateDb, "main", 4);
173211    }
173212  
173213  #if 0
173214    if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
173215      p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
173216    }
173217  #endif
173218  
173219    /* If it has not already been created, create the rbu_state table */
173220    rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
173221  
173222  #if 0
173223    if( rbuIsVacuum(p) ){
173224      if( p->rc==SQLITE_OK ){
173225        int rc2;
173226        int bOk = 0;
173227        sqlite3_stmt *pCnt = 0;
173228        p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
173229            "SELECT count(*) FROM stat.sqlite_master"
173230        );
173231        if( p->rc==SQLITE_OK 
173232         && sqlite3_step(pCnt)==SQLITE_ROW
173233         && 1==sqlite3_column_int(pCnt, 0)
173234        ){
173235          bOk = 1;
173236        }
173237        rc2 = sqlite3_finalize(pCnt);
173238        if( p->rc==SQLITE_OK ) p->rc = rc2;
173239  
173240        if( p->rc==SQLITE_OK && bOk==0 ){
173241          p->rc = SQLITE_ERROR;
173242          p->zErrmsg = sqlite3_mprintf("invalid state database");
173243        }
173244      
173245        if( p->rc==SQLITE_OK ){
173246          p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
173247        }
173248      }
173249    }
173250  #endif
173251  
173252    if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
173253      int bOpen = 0;
173254      int rc;
173255      p->nRbu = 0;
173256      p->pRbuFd = 0;
173257      rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
173258      if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
173259      if( p->eStage>=RBU_STAGE_MOVE ){
173260        bOpen = 1;
173261      }else{
173262        RbuState *pState = rbuLoadState(p);
173263        if( pState ){
173264          bOpen = (pState->eStage>=RBU_STAGE_MOVE);
173265          rbuFreeState(pState);
173266        }
173267      }
173268      if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
173269    }
173270  
173271    p->eStage = 0;
173272    if( p->rc==SQLITE_OK && p->dbMain==0 ){
173273      if( !rbuIsVacuum(p) ){
173274        p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
173275      }else if( p->pRbuFd->pWalFd ){
173276        if( pbRetry ){
173277          p->pRbuFd->bNolock = 0;
173278          sqlite3_close(p->dbRbu);
173279          sqlite3_close(p->dbMain);
173280          p->dbMain = 0;
173281          p->dbRbu = 0;
173282          *pbRetry = 1;
173283          return;
173284        }
173285        p->rc = SQLITE_ERROR;
173286        p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
173287      }else{
173288        char *zTarget;
173289        char *zExtra = 0;
173290        if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
173291          zExtra = &p->zRbu[5];
173292          while( *zExtra ){
173293            if( *zExtra++=='?' ) break;
173294          }
173295          if( *zExtra=='\0' ) zExtra = 0;
173296        }
173297  
173298        zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s", 
173299            sqlite3_db_filename(p->dbRbu, "main"),
173300            (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
173301        );
173302  
173303        if( zTarget==0 ){
173304          p->rc = SQLITE_NOMEM;
173305          return;
173306        }
173307        p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
173308        sqlite3_free(zTarget);
173309      }
173310    }
173311  
173312    if( p->rc==SQLITE_OK ){
173313      p->rc = sqlite3_create_function(p->dbMain, 
173314          "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
173315      );
173316    }
173317  
173318    if( p->rc==SQLITE_OK ){
173319      p->rc = sqlite3_create_function(p->dbMain, 
173320          "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
173321      );
173322    }
173323  
173324    if( p->rc==SQLITE_OK ){
173325      p->rc = sqlite3_create_function(p->dbRbu, 
173326          "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
173327      );
173328    }
173329  
173330    if( p->rc==SQLITE_OK ){
173331      p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
173332    }
173333    rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
173334  
173335    /* Mark the database file just opened as an RBU target database. If 
173336    ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
173337    ** This is an error.  */
173338    if( p->rc==SQLITE_OK ){
173339      p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
173340    }
173341  
173342    if( p->rc==SQLITE_NOTFOUND ){
173343      p->rc = SQLITE_ERROR;
173344      p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
173345    }
173346  }
173347  
173348  /*
173349  ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
173350  ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
173351  **
173352  ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
173353  ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
173354  ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
173355  ** three characters, then shorten the suffix on z[] to be the last three
173356  ** characters of the original suffix.
173357  **
173358  ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
173359  ** do the suffix shortening regardless of URI parameter.
173360  **
173361  ** Examples:
173362  **
173363  **     test.db-journal    =>   test.nal
173364  **     test.db-wal        =>   test.wal
173365  **     test.db-shm        =>   test.shm
173366  **     test.db-mj7f3319fa =>   test.9fa
173367  */
173368  static void rbuFileSuffix3(const char *zBase, char *z){
173369  #ifdef SQLITE_ENABLE_8_3_NAMES
173370  #if SQLITE_ENABLE_8_3_NAMES<2
173371    if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
173372  #endif
173373    {
173374      int i, sz;
173375      sz = (int)strlen(z)&0xffffff;
173376      for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
173377      if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
173378    }
173379  #endif
173380  }
173381  
173382  /*
173383  ** Return the current wal-index header checksum for the target database 
173384  ** as a 64-bit integer.
173385  **
173386  ** The checksum is store in the first page of xShmMap memory as an 8-byte 
173387  ** blob starting at byte offset 40.
173388  */
173389  static i64 rbuShmChecksum(sqlite3rbu *p){
173390    i64 iRet = 0;
173391    if( p->rc==SQLITE_OK ){
173392      sqlite3_file *pDb = p->pTargetFd->pReal;
173393      u32 volatile *ptr;
173394      p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
173395      if( p->rc==SQLITE_OK ){
173396        iRet = ((i64)ptr[10] << 32) + ptr[11];
173397      }
173398    }
173399    return iRet;
173400  }
173401  
173402  /*
173403  ** This function is called as part of initializing or reinitializing an
173404  ** incremental checkpoint. 
173405  **
173406  ** It populates the sqlite3rbu.aFrame[] array with the set of 
173407  ** (wal frame -> db page) copy operations required to checkpoint the 
173408  ** current wal file, and obtains the set of shm locks required to safely 
173409  ** perform the copy operations directly on the file-system.
173410  **
173411  ** If argument pState is not NULL, then the incremental checkpoint is
173412  ** being resumed. In this case, if the checksum of the wal-index-header
173413  ** following recovery is not the same as the checksum saved in the RbuState
173414  ** object, then the rbu handle is set to DONE state. This occurs if some
173415  ** other client appends a transaction to the wal file in the middle of
173416  ** an incremental checkpoint.
173417  */
173418  static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
173419  
173420    /* If pState is NULL, then the wal file may not have been opened and
173421    ** recovered. Running a read-statement here to ensure that doing so
173422    ** does not interfere with the "capture" process below.  */
173423    if( pState==0 ){
173424      p->eStage = 0;
173425      if( p->rc==SQLITE_OK ){
173426        p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
173427      }
173428    }
173429  
173430    /* Assuming no error has occurred, run a "restart" checkpoint with the
173431    ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
173432    ** special behaviour in the rbu VFS:
173433    **
173434    **   * If the exclusive shm WRITER or READ0 lock cannot be obtained,
173435    **     the checkpoint fails with SQLITE_BUSY (normally SQLite would
173436    **     proceed with running a passive checkpoint instead of failing).
173437    **
173438    **   * Attempts to read from the *-wal file or write to the database file
173439    **     do not perform any IO. Instead, the frame/page combinations that
173440    **     would be read/written are recorded in the sqlite3rbu.aFrame[]
173441    **     array.
173442    **
173443    **   * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER, 
173444    **     READ0 and CHECKPOINT locks taken as part of the checkpoint are
173445    **     no-ops. These locks will not be released until the connection
173446    **     is closed.
173447    **
173448    **   * Attempting to xSync() the database file causes an SQLITE_INTERNAL 
173449    **     error.
173450    **
173451    ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
173452    ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
173453    ** array populated with a set of (frame -> page) mappings. Because the 
173454    ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy 
173455    ** data from the wal file into the database file according to the 
173456    ** contents of aFrame[].
173457    */
173458    if( p->rc==SQLITE_OK ){
173459      int rc2;
173460      p->eStage = RBU_STAGE_CAPTURE;
173461      rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
173462      if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
173463    }
173464  
173465    if( p->rc==SQLITE_OK && p->nFrame>0 ){
173466      p->eStage = RBU_STAGE_CKPT;
173467      p->nStep = (pState ? pState->nRow : 0);
173468      p->aBuf = rbuMalloc(p, p->pgsz);
173469      p->iWalCksum = rbuShmChecksum(p);
173470    }
173471  
173472    if( p->rc==SQLITE_OK ){
173473      if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){
173474        p->rc = SQLITE_DONE;
173475        p->eStage = RBU_STAGE_DONE;
173476      }else{
173477        int nSectorSize;
173478        sqlite3_file *pDb = p->pTargetFd->pReal;
173479        sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
173480        assert( p->nPagePerSector==0 );
173481        nSectorSize = pDb->pMethods->xSectorSize(pDb);
173482        if( nSectorSize>p->pgsz ){
173483          p->nPagePerSector = nSectorSize / p->pgsz;
173484        }else{
173485          p->nPagePerSector = 1;
173486        }
173487  
173488        /* Call xSync() on the wal file. This causes SQLite to sync the 
173489        ** directory in which the target database and the wal file reside, in 
173490        ** case it has not been synced since the rename() call in 
173491        ** rbuMoveOalFile(). */
173492        p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL);
173493      }
173494    }
173495  }
173496  
173497  /*
173498  ** Called when iAmt bytes are read from offset iOff of the wal file while
173499  ** the rbu object is in capture mode. Record the frame number of the frame
173500  ** being read in the aFrame[] array.
173501  */
173502  static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
173503    const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
173504    u32 iFrame;
173505  
173506    if( pRbu->mLock!=mReq ){
173507      pRbu->rc = SQLITE_BUSY;
173508      return SQLITE_INTERNAL;
173509    }
173510  
173511    pRbu->pgsz = iAmt;
173512    if( pRbu->nFrame==pRbu->nFrameAlloc ){
173513      int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
173514      RbuFrame *aNew;
173515      aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
173516      if( aNew==0 ) return SQLITE_NOMEM;
173517      pRbu->aFrame = aNew;
173518      pRbu->nFrameAlloc = nNew;
173519    }
173520  
173521    iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
173522    if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
173523    pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
173524    pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
173525    pRbu->nFrame++;
173526    return SQLITE_OK;
173527  }
173528  
173529  /*
173530  ** Called when a page of data is written to offset iOff of the database
173531  ** file while the rbu handle is in capture mode. Record the page number 
173532  ** of the page being written in the aFrame[] array.
173533  */
173534  static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
173535    pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
173536    return SQLITE_OK;
173537  }
173538  
173539  /*
173540  ** This is called as part of an incremental checkpoint operation. Copy
173541  ** a single frame of data from the wal file into the database file, as
173542  ** indicated by the RbuFrame object.
173543  */
173544  static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
173545    sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
173546    sqlite3_file *pDb = p->pTargetFd->pReal;
173547    i64 iOff;
173548  
173549    assert( p->rc==SQLITE_OK );
173550    iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
173551    p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
173552    if( p->rc ) return;
173553  
173554    iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
173555    p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
173556  }
173557  
173558  
173559  /*
173560  ** Take an EXCLUSIVE lock on the database file.
173561  */
173562  static void rbuLockDatabase(sqlite3rbu *p){
173563    sqlite3_file *pReal = p->pTargetFd->pReal;
173564    assert( p->rc==SQLITE_OK );
173565    p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
173566    if( p->rc==SQLITE_OK ){
173567      p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
173568    }
173569  }
173570  
173571  #if defined(_WIN32_WCE)
173572  static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
173573    int nChar;
173574    LPWSTR zWideFilename;
173575  
173576    nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
173577    if( nChar==0 ){
173578      return 0;
173579    }
173580    zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
173581    if( zWideFilename==0 ){
173582      return 0;
173583    }
173584    memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
173585    nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
173586                                  nChar);
173587    if( nChar==0 ){
173588      sqlite3_free(zWideFilename);
173589      zWideFilename = 0;
173590    }
173591    return zWideFilename;
173592  }
173593  #endif
173594  
173595  /*
173596  ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
173597  ** on the database file. This proc moves the *-oal file to the *-wal path,
173598  ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
173599  ** If an error occurs, leave an error code and error message in the rbu 
173600  ** handle.
173601  */
173602  static void rbuMoveOalFile(sqlite3rbu *p){
173603    const char *zBase = sqlite3_db_filename(p->dbMain, "main");
173604    const char *zMove = zBase;
173605    char *zOal;
173606    char *zWal;
173607  
173608    if( rbuIsVacuum(p) ){
173609      zMove = sqlite3_db_filename(p->dbRbu, "main");
173610    }
173611    zOal = sqlite3_mprintf("%s-oal", zMove);
173612    zWal = sqlite3_mprintf("%s-wal", zMove);
173613  
173614    assert( p->eStage==RBU_STAGE_MOVE );
173615    assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
173616    if( zWal==0 || zOal==0 ){
173617      p->rc = SQLITE_NOMEM;
173618    }else{
173619      /* Move the *-oal file to *-wal. At this point connection p->db is
173620      ** holding a SHARED lock on the target database file (because it is
173621      ** in WAL mode). So no other connection may be writing the db. 
173622      **
173623      ** In order to ensure that there are no database readers, an EXCLUSIVE
173624      ** lock is obtained here before the *-oal is moved to *-wal.
173625      */
173626      rbuLockDatabase(p);
173627      if( p->rc==SQLITE_OK ){
173628        rbuFileSuffix3(zBase, zWal);
173629        rbuFileSuffix3(zBase, zOal);
173630  
173631        /* Re-open the databases. */
173632        rbuObjIterFinalize(&p->objiter);
173633        sqlite3_close(p->dbRbu);
173634        sqlite3_close(p->dbMain);
173635        p->dbMain = 0;
173636        p->dbRbu = 0;
173637  
173638  #if defined(_WIN32_WCE)
173639        {
173640          LPWSTR zWideOal;
173641          LPWSTR zWideWal;
173642  
173643          zWideOal = rbuWinUtf8ToUnicode(zOal);
173644          if( zWideOal ){
173645            zWideWal = rbuWinUtf8ToUnicode(zWal);
173646            if( zWideWal ){
173647              if( MoveFileW(zWideOal, zWideWal) ){
173648                p->rc = SQLITE_OK;
173649              }else{
173650                p->rc = SQLITE_IOERR;
173651              }
173652              sqlite3_free(zWideWal);
173653            }else{
173654              p->rc = SQLITE_IOERR_NOMEM;
173655            }
173656            sqlite3_free(zWideOal);
173657          }else{
173658            p->rc = SQLITE_IOERR_NOMEM;
173659          }
173660        }
173661  #else
173662        p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
173663  #endif
173664  
173665        if( p->rc==SQLITE_OK ){
173666          rbuOpenDatabase(p, 0);
173667          rbuSetupCheckpoint(p, 0);
173668        }
173669      }
173670    }
173671  
173672    sqlite3_free(zWal);
173673    sqlite3_free(zOal);
173674  }
173675  
173676  /*
173677  ** The SELECT statement iterating through the keys for the current object
173678  ** (p->objiter.pSelect) currently points to a valid row. This function
173679  ** determines the type of operation requested by this row and returns
173680  ** one of the following values to indicate the result:
173681  **
173682  **     * RBU_INSERT
173683  **     * RBU_DELETE
173684  **     * RBU_IDX_DELETE
173685  **     * RBU_UPDATE
173686  **
173687  ** If RBU_UPDATE is returned, then output variable *pzMask is set to
173688  ** point to the text value indicating the columns to update.
173689  **
173690  ** If the rbu_control field contains an invalid value, an error code and
173691  ** message are left in the RBU handle and zero returned.
173692  */
173693  static int rbuStepType(sqlite3rbu *p, const char **pzMask){
173694    int iCol = p->objiter.nCol;     /* Index of rbu_control column */
173695    int res = 0;                    /* Return value */
173696  
173697    switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
173698      case SQLITE_INTEGER: {
173699        int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
173700        switch( iVal ){
173701          case 0: res = RBU_INSERT;     break;
173702          case 1: res = RBU_DELETE;     break;
173703          case 2: res = RBU_REPLACE;    break;
173704          case 3: res = RBU_IDX_DELETE; break;
173705          case 4: res = RBU_IDX_INSERT; break;
173706        }
173707        break;
173708      }
173709  
173710      case SQLITE_TEXT: {
173711        const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
173712        if( z==0 ){
173713          p->rc = SQLITE_NOMEM;
173714        }else{
173715          *pzMask = (const char*)z;
173716        }
173717        res = RBU_UPDATE;
173718  
173719        break;
173720      }
173721  
173722      default:
173723        break;
173724    }
173725  
173726    if( res==0 ){
173727      rbuBadControlError(p);
173728    }
173729    return res;
173730  }
173731  
173732  #ifdef SQLITE_DEBUG
173733  /*
173734  ** Assert that column iCol of statement pStmt is named zName.
173735  */
173736  static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
173737    const char *zCol = sqlite3_column_name(pStmt, iCol);
173738    assert( 0==sqlite3_stricmp(zName, zCol) );
173739  }
173740  #else
173741  # define assertColumnName(x,y,z)
173742  #endif
173743  
173744  /*
173745  ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
173746  ** RBU_IDX_DELETE. This function performs the work of a single
173747  ** sqlite3rbu_step() call for the type of operation specified by eType.
173748  */
173749  static void rbuStepOneOp(sqlite3rbu *p, int eType){
173750    RbuObjIter *pIter = &p->objiter;
173751    sqlite3_value *pVal;
173752    sqlite3_stmt *pWriter;
173753    int i;
173754  
173755    assert( p->rc==SQLITE_OK );
173756    assert( eType!=RBU_DELETE || pIter->zIdx==0 );
173757    assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
173758         || eType==RBU_INSERT || eType==RBU_IDX_INSERT
173759    );
173760  
173761    /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
173762    ** statement below does actually delete a row, nPhaseOneStep will be
173763    ** incremented by the same amount when SQL function rbu_tmp_insert()
173764    ** is invoked by the trigger.  */
173765    if( eType==RBU_DELETE ){
173766      p->nPhaseOneStep -= p->objiter.nIndex;
173767    }
173768  
173769    if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
173770      pWriter = pIter->pDelete;
173771    }else{
173772      pWriter = pIter->pInsert;
173773    }
173774  
173775    for(i=0; i<pIter->nCol; i++){
173776      /* If this is an INSERT into a table b-tree and the table has an
173777      ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
173778      ** to write a NULL into the IPK column. That is not permitted.  */
173779      if( eType==RBU_INSERT 
173780       && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i] 
173781       && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
173782      ){
173783        p->rc = SQLITE_MISMATCH;
173784        p->zErrmsg = sqlite3_mprintf("datatype mismatch");
173785        return;
173786      }
173787  
173788      if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
173789        continue;
173790      }
173791  
173792      pVal = sqlite3_column_value(pIter->pSelect, i);
173793      p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
173794      if( p->rc ) return;
173795    }
173796    if( pIter->zIdx==0 ){
173797      if( pIter->eType==RBU_PK_VTAB 
173798       || pIter->eType==RBU_PK_NONE 
173799       || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p)) 
173800      ){
173801        /* For a virtual table, or a table with no primary key, the 
173802        ** SELECT statement is:
173803        **
173804        **   SELECT <cols>, rbu_control, rbu_rowid FROM ....
173805        **
173806        ** Hence column_value(pIter->nCol+1).
173807        */
173808        assertColumnName(pIter->pSelect, pIter->nCol+1, 
173809            rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
173810        );
173811        pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
173812        p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
173813      }
173814    }
173815    if( p->rc==SQLITE_OK ){
173816      sqlite3_step(pWriter);
173817      p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
173818    }
173819  }
173820  
173821  /*
173822  ** This function does the work for an sqlite3rbu_step() call.
173823  **
173824  ** The object-iterator (p->objiter) currently points to a valid object,
173825  ** and the input cursor (p->objiter.pSelect) currently points to a valid
173826  ** input row. Perform whatever processing is required and return.
173827  **
173828  ** If no  error occurs, SQLITE_OK is returned. Otherwise, an error code
173829  ** and message is left in the RBU handle and a copy of the error code
173830  ** returned.
173831  */
173832  static int rbuStep(sqlite3rbu *p){
173833    RbuObjIter *pIter = &p->objiter;
173834    const char *zMask = 0;
173835    int eType = rbuStepType(p, &zMask);
173836  
173837    if( eType ){
173838      assert( eType==RBU_INSERT     || eType==RBU_DELETE
173839           || eType==RBU_REPLACE    || eType==RBU_IDX_DELETE
173840           || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
173841      );
173842      assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
173843  
173844      if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
173845        rbuBadControlError(p);
173846      }
173847      else if( eType==RBU_REPLACE ){
173848        if( pIter->zIdx==0 ){
173849          p->nPhaseOneStep += p->objiter.nIndex;
173850          rbuStepOneOp(p, RBU_DELETE);
173851        }
173852        if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
173853      }
173854      else if( eType!=RBU_UPDATE ){
173855        rbuStepOneOp(p, eType);
173856      }
173857      else{
173858        sqlite3_value *pVal;
173859        sqlite3_stmt *pUpdate = 0;
173860        assert( eType==RBU_UPDATE );
173861        p->nPhaseOneStep -= p->objiter.nIndex;
173862        rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
173863        if( pUpdate ){
173864          int i;
173865          for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
173866            char c = zMask[pIter->aiSrcOrder[i]];
173867            pVal = sqlite3_column_value(pIter->pSelect, i);
173868            if( pIter->abTblPk[i] || c!='.' ){
173869              p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
173870            }
173871          }
173872          if( p->rc==SQLITE_OK 
173873           && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE) 
173874          ){
173875            /* Bind the rbu_rowid value to column _rowid_ */
173876            assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
173877            pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
173878            p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
173879          }
173880          if( p->rc==SQLITE_OK ){
173881            sqlite3_step(pUpdate);
173882            p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
173883          }
173884        }
173885      }
173886    }
173887    return p->rc;
173888  }
173889  
173890  /*
173891  ** Increment the schema cookie of the main database opened by p->dbMain.
173892  **
173893  ** Or, if this is an RBU vacuum, set the schema cookie of the main db
173894  ** opened by p->dbMain to one more than the schema cookie of the main
173895  ** db opened by p->dbRbu.
173896  */
173897  static void rbuIncrSchemaCookie(sqlite3rbu *p){
173898    if( p->rc==SQLITE_OK ){
173899      sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
173900      int iCookie = 1000000;
173901      sqlite3_stmt *pStmt;
173902  
173903      p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg, 
173904          "PRAGMA schema_version"
173905      );
173906      if( p->rc==SQLITE_OK ){
173907        /* Coverage: it may be that this sqlite3_step() cannot fail. There
173908        ** is already a transaction open, so the prepared statement cannot
173909        ** throw an SQLITE_SCHEMA exception. The only database page the
173910        ** statement reads is page 1, which is guaranteed to be in the cache.
173911        ** And no memory allocations are required.  */
173912        if( SQLITE_ROW==sqlite3_step(pStmt) ){
173913          iCookie = sqlite3_column_int(pStmt, 0);
173914        }
173915        rbuFinalize(p, pStmt);
173916      }
173917      if( p->rc==SQLITE_OK ){
173918        rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
173919      }
173920    }
173921  }
173922  
173923  /*
173924  ** Update the contents of the rbu_state table within the rbu database. The
173925  ** value stored in the RBU_STATE_STAGE column is eStage. All other values
173926  ** are determined by inspecting the rbu handle passed as the first argument.
173927  */
173928  static void rbuSaveState(sqlite3rbu *p, int eStage){
173929    if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
173930      sqlite3_stmt *pInsert = 0;
173931      rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
173932      int rc;
173933  
173934      assert( p->zErrmsg==0 );
173935      rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg, 
173936          sqlite3_mprintf(
173937            "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
173938            "(%d, %d), "
173939            "(%d, %Q), "
173940            "(%d, %Q), "
173941            "(%d, %d), "
173942            "(%d, %d), "
173943            "(%d, %lld), "
173944            "(%d, %lld), "
173945            "(%d, %lld), "
173946            "(%d, %lld) ",
173947            p->zStateDb,
173948            RBU_STATE_STAGE, eStage,
173949            RBU_STATE_TBL, p->objiter.zTbl, 
173950            RBU_STATE_IDX, p->objiter.zIdx, 
173951            RBU_STATE_ROW, p->nStep, 
173952            RBU_STATE_PROGRESS, p->nProgress,
173953            RBU_STATE_CKPT, p->iWalCksum,
173954            RBU_STATE_COOKIE, (i64)pFd->iCookie,
173955            RBU_STATE_OALSZ, p->iOalSz,
173956            RBU_STATE_PHASEONESTEP, p->nPhaseOneStep
173957        )
173958      );
173959      assert( pInsert==0 || rc==SQLITE_OK );
173960  
173961      if( rc==SQLITE_OK ){
173962        sqlite3_step(pInsert);
173963        rc = sqlite3_finalize(pInsert);
173964      }
173965      if( rc!=SQLITE_OK ) p->rc = rc;
173966    }
173967  }
173968  
173969  
173970  /*
173971  ** The second argument passed to this function is the name of a PRAGMA 
173972  ** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
173973  ** This function executes the following on sqlite3rbu.dbRbu:
173974  **
173975  **   "PRAGMA main.$zPragma"
173976  **
173977  ** where $zPragma is the string passed as the second argument, then
173978  ** on sqlite3rbu.dbMain:
173979  **
173980  **   "PRAGMA main.$zPragma = $val"
173981  **
173982  ** where $val is the value returned by the first PRAGMA invocation.
173983  **
173984  ** In short, it copies the value  of the specified PRAGMA setting from
173985  ** dbRbu to dbMain.
173986  */
173987  static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
173988    if( p->rc==SQLITE_OK ){
173989      sqlite3_stmt *pPragma = 0;
173990      p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg, 
173991          sqlite3_mprintf("PRAGMA main.%s", zPragma)
173992      );
173993      if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
173994        p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
173995            zPragma, sqlite3_column_int(pPragma, 0)
173996        );
173997      }
173998      rbuFinalize(p, pPragma);
173999    }
174000  }
174001  
174002  /*
174003  ** The RBU handle passed as the only argument has just been opened and 
174004  ** the state database is empty. If this RBU handle was opened for an
174005  ** RBU vacuum operation, create the schema in the target db.
174006  */
174007  static void rbuCreateTargetSchema(sqlite3rbu *p){
174008    sqlite3_stmt *pSql = 0;
174009    sqlite3_stmt *pInsert = 0;
174010  
174011    assert( rbuIsVacuum(p) );
174012    p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
174013    if( p->rc==SQLITE_OK ){
174014      p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg, 
174015        "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
174016        " AND name!='sqlite_sequence' "
174017        " ORDER BY type DESC"
174018      );
174019    }
174020  
174021    while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
174022      const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
174023      p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
174024    }
174025    rbuFinalize(p, pSql);
174026    if( p->rc!=SQLITE_OK ) return;
174027  
174028    if( p->rc==SQLITE_OK ){
174029      p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg, 
174030          "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL" 
174031      );
174032    }
174033  
174034    if( p->rc==SQLITE_OK ){
174035      p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg, 
174036          "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
174037      );
174038    }
174039  
174040    while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
174041      int i;
174042      for(i=0; i<5; i++){
174043        sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
174044      }
174045      sqlite3_step(pInsert);
174046      p->rc = sqlite3_reset(pInsert);
174047    }
174048    if( p->rc==SQLITE_OK ){
174049      p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
174050    }
174051  
174052    rbuFinalize(p, pSql);
174053    rbuFinalize(p, pInsert);
174054  }
174055  
174056  /*
174057  ** Step the RBU object.
174058  */
174059  SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
174060    if( p ){
174061      switch( p->eStage ){
174062        case RBU_STAGE_OAL: {
174063          RbuObjIter *pIter = &p->objiter;
174064  
174065          /* If this is an RBU vacuum operation and the state table was empty
174066          ** when this handle was opened, create the target database schema. */
174067          if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
174068            rbuCreateTargetSchema(p);
174069            rbuCopyPragma(p, "user_version");
174070            rbuCopyPragma(p, "application_id");
174071          }
174072  
174073          while( p->rc==SQLITE_OK && pIter->zTbl ){
174074  
174075            if( pIter->bCleanup ){
174076              /* Clean up the rbu_tmp_xxx table for the previous table. It 
174077              ** cannot be dropped as there are currently active SQL statements.
174078              ** But the contents can be deleted.  */
174079              if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
174080                rbuMPrintfExec(p, p->dbRbu, 
174081                    "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
174082                );
174083              }
174084            }else{
174085              rbuObjIterPrepareAll(p, pIter, 0);
174086  
174087              /* Advance to the next row to process. */
174088              if( p->rc==SQLITE_OK ){
174089                int rc = sqlite3_step(pIter->pSelect);
174090                if( rc==SQLITE_ROW ){
174091                  p->nProgress++;
174092                  p->nStep++;
174093                  return rbuStep(p);
174094                }
174095                p->rc = sqlite3_reset(pIter->pSelect);
174096                p->nStep = 0;
174097              }
174098            }
174099  
174100            rbuObjIterNext(p, pIter);
174101          }
174102  
174103          if( p->rc==SQLITE_OK ){
174104            assert( pIter->zTbl==0 );
174105            rbuSaveState(p, RBU_STAGE_MOVE);
174106            rbuIncrSchemaCookie(p);
174107            if( p->rc==SQLITE_OK ){
174108              p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
174109            }
174110            if( p->rc==SQLITE_OK ){
174111              p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
174112            }
174113            p->eStage = RBU_STAGE_MOVE;
174114          }
174115          break;
174116        }
174117  
174118        case RBU_STAGE_MOVE: {
174119          if( p->rc==SQLITE_OK ){
174120            rbuMoveOalFile(p);
174121            p->nProgress++;
174122          }
174123          break;
174124        }
174125  
174126        case RBU_STAGE_CKPT: {
174127          if( p->rc==SQLITE_OK ){
174128            if( p->nStep>=p->nFrame ){
174129              sqlite3_file *pDb = p->pTargetFd->pReal;
174130    
174131              /* Sync the db file */
174132              p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
174133    
174134              /* Update nBackfill */
174135              if( p->rc==SQLITE_OK ){
174136                void volatile *ptr;
174137                p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
174138                if( p->rc==SQLITE_OK ){
174139                  ((u32 volatile*)ptr)[24] = p->iMaxFrame;
174140                }
174141              }
174142    
174143              if( p->rc==SQLITE_OK ){
174144                p->eStage = RBU_STAGE_DONE;
174145                p->rc = SQLITE_DONE;
174146              }
174147            }else{
174148              /* At one point the following block copied a single frame from the
174149              ** wal file to the database file. So that one call to sqlite3rbu_step()
174150              ** checkpointed a single frame. 
174151              **
174152              ** However, if the sector-size is larger than the page-size, and the
174153              ** application calls sqlite3rbu_savestate() or close() immediately
174154              ** after this step, then rbu_step() again, then a power failure occurs,
174155              ** then the database page written here may be damaged. Work around
174156              ** this by checkpointing frames until the next page in the aFrame[]
174157              ** lies on a different disk sector to the current one. */
174158              u32 iSector;
174159              do{
174160                RbuFrame *pFrame = &p->aFrame[p->nStep];
174161                iSector = (pFrame->iDbPage-1) / p->nPagePerSector;
174162                rbuCheckpointFrame(p, pFrame);
174163                p->nStep++;
174164              }while( p->nStep<p->nFrame 
174165                   && iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector)
174166                   && p->rc==SQLITE_OK
174167              );
174168            }
174169            p->nProgress++;
174170          }
174171          break;
174172        }
174173  
174174        default:
174175          break;
174176      }
174177      return p->rc;
174178    }else{
174179      return SQLITE_NOMEM;
174180    }
174181  }
174182  
174183  /*
174184  ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
174185  ** otherwise. Either or both argument may be NULL. Two NULL values are
174186  ** considered equal, and NULL is considered distinct from all other values.
174187  */
174188  static int rbuStrCompare(const char *z1, const char *z2){
174189    if( z1==0 && z2==0 ) return 0;
174190    if( z1==0 || z2==0 ) return 1;
174191    return (sqlite3_stricmp(z1, z2)!=0);
174192  }
174193  
174194  /*
174195  ** This function is called as part of sqlite3rbu_open() when initializing
174196  ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
174197  ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
174198  ** things so that the next call to sqlite3rbu_step() continues on from
174199  ** where the previous rbu handle left off.
174200  **
174201  ** If an error occurs, an error code and error message are left in the
174202  ** rbu handle passed as the first argument.
174203  */
174204  static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
174205    assert( p->rc==SQLITE_OK );
174206    if( pState->zTbl ){
174207      RbuObjIter *pIter = &p->objiter;
174208      int rc = SQLITE_OK;
174209  
174210      while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup 
174211         || rbuStrCompare(pIter->zIdx, pState->zIdx)
174212         || rbuStrCompare(pIter->zTbl, pState->zTbl) 
174213      )){
174214        rc = rbuObjIterNext(p, pIter);
174215      }
174216  
174217      if( rc==SQLITE_OK && !pIter->zTbl ){
174218        rc = SQLITE_ERROR;
174219        p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
174220      }
174221  
174222      if( rc==SQLITE_OK ){
174223        p->nStep = pState->nRow;
174224        rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
174225      }
174226  
174227      p->rc = rc;
174228    }
174229  }
174230  
174231  /*
174232  ** If there is a "*-oal" file in the file-system corresponding to the
174233  ** target database in the file-system, delete it. If an error occurs,
174234  ** leave an error code and error message in the rbu handle.
174235  */
174236  static void rbuDeleteOalFile(sqlite3rbu *p){
174237    char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
174238    if( zOal ){
174239      sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
174240      assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
174241      pVfs->xDelete(pVfs, zOal, 0);
174242      sqlite3_free(zOal);
174243    }
174244  }
174245  
174246  /*
174247  ** Allocate a private rbu VFS for the rbu handle passed as the only
174248  ** argument. This VFS will be used unless the call to sqlite3rbu_open()
174249  ** specified a URI with a vfs=? option in place of a target database
174250  ** file name.
174251  */
174252  static void rbuCreateVfs(sqlite3rbu *p){
174253    int rnd;
174254    char zRnd[64];
174255  
174256    assert( p->rc==SQLITE_OK );
174257    sqlite3_randomness(sizeof(int), (void*)&rnd);
174258    sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
174259    p->rc = sqlite3rbu_create_vfs(zRnd, 0);
174260    if( p->rc==SQLITE_OK ){
174261      sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
174262      assert( pVfs );
174263      p->zVfsName = pVfs->zName;
174264      ((rbu_vfs*)pVfs)->pRbu = p;
174265    }
174266  }
174267  
174268  /*
174269  ** Destroy the private VFS created for the rbu handle passed as the only
174270  ** argument by an earlier call to rbuCreateVfs().
174271  */
174272  static void rbuDeleteVfs(sqlite3rbu *p){
174273    if( p->zVfsName ){
174274      sqlite3rbu_destroy_vfs(p->zVfsName);
174275      p->zVfsName = 0;
174276    }
174277  }
174278  
174279  /*
174280  ** This user-defined SQL function is invoked with a single argument - the
174281  ** name of a table expected to appear in the target database. It returns
174282  ** the number of auxilliary indexes on the table.
174283  */
174284  static void rbuIndexCntFunc(
174285    sqlite3_context *pCtx, 
174286    int nVal,
174287    sqlite3_value **apVal
174288  ){
174289    sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
174290    sqlite3_stmt *pStmt = 0;
174291    char *zErrmsg = 0;
174292    int rc;
174293  
174294    assert( nVal==1 );
174295    
174296    rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg, 
174297        sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
174298          "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
174299    );
174300    if( rc!=SQLITE_OK ){
174301      sqlite3_result_error(pCtx, zErrmsg, -1);
174302    }else{
174303      int nIndex = 0;
174304      if( SQLITE_ROW==sqlite3_step(pStmt) ){
174305        nIndex = sqlite3_column_int(pStmt, 0);
174306      }
174307      rc = sqlite3_finalize(pStmt);
174308      if( rc==SQLITE_OK ){
174309        sqlite3_result_int(pCtx, nIndex);
174310      }else{
174311        sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1);
174312      }
174313    }
174314  
174315    sqlite3_free(zErrmsg);
174316  }
174317  
174318  /*
174319  ** If the RBU database contains the rbu_count table, use it to initialize
174320  ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
174321  ** is assumed to contain the same columns as:
174322  **
174323  **   CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
174324  **
174325  ** There should be one row in the table for each data_xxx table in the
174326  ** database. The 'tbl' column should contain the name of a data_xxx table,
174327  ** and the cnt column the number of rows it contains.
174328  **
174329  ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
174330  ** for all rows in the rbu_count table, where nIndex is the number of 
174331  ** indexes on the corresponding target database table.
174332  */
174333  static void rbuInitPhaseOneSteps(sqlite3rbu *p){
174334    if( p->rc==SQLITE_OK ){
174335      sqlite3_stmt *pStmt = 0;
174336      int bExists = 0;                /* True if rbu_count exists */
174337  
174338      p->nPhaseOneStep = -1;
174339  
174340      p->rc = sqlite3_create_function(p->dbRbu, 
174341          "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
174342      );
174343    
174344      /* Check for the rbu_count table. If it does not exist, or if an error
174345      ** occurs, nPhaseOneStep will be left set to -1. */
174346      if( p->rc==SQLITE_OK ){
174347        p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
174348            "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
174349        );
174350      }
174351      if( p->rc==SQLITE_OK ){
174352        if( SQLITE_ROW==sqlite3_step(pStmt) ){
174353          bExists = 1;
174354        }
174355        p->rc = sqlite3_finalize(pStmt);
174356      }
174357    
174358      if( p->rc==SQLITE_OK && bExists ){
174359        p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
174360            "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
174361            "FROM rbu_count"
174362        );
174363        if( p->rc==SQLITE_OK ){
174364          if( SQLITE_ROW==sqlite3_step(pStmt) ){
174365            p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
174366          }
174367          p->rc = sqlite3_finalize(pStmt);
174368        }
174369      }
174370    }
174371  }
174372  
174373  
174374  static sqlite3rbu *openRbuHandle(
174375    const char *zTarget, 
174376    const char *zRbu,
174377    const char *zState
174378  ){
174379    sqlite3rbu *p;
174380    size_t nTarget = zTarget ? strlen(zTarget) : 0;
174381    size_t nRbu = strlen(zRbu);
174382    size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
174383  
174384    p = (sqlite3rbu*)sqlite3_malloc64(nByte);
174385    if( p ){
174386      RbuState *pState = 0;
174387  
174388      /* Create the custom VFS. */
174389      memset(p, 0, sizeof(sqlite3rbu));
174390      rbuCreateVfs(p);
174391  
174392      /* Open the target, RBU and state databases */
174393      if( p->rc==SQLITE_OK ){
174394        char *pCsr = (char*)&p[1];
174395        int bRetry = 0;
174396        if( zTarget ){
174397          p->zTarget = pCsr;
174398          memcpy(p->zTarget, zTarget, nTarget+1);
174399          pCsr += nTarget+1;
174400        }
174401        p->zRbu = pCsr;
174402        memcpy(p->zRbu, zRbu, nRbu+1);
174403        pCsr += nRbu+1;
174404        if( zState ){
174405          p->zState = rbuMPrintf(p, "%s", zState);
174406        }
174407  
174408        /* If the first attempt to open the database file fails and the bRetry
174409        ** flag it set, this means that the db was not opened because it seemed
174410        ** to be a wal-mode db. But, this may have happened due to an earlier
174411        ** RBU vacuum operation leaving an old wal file in the directory.
174412        ** If this is the case, it will have been checkpointed and deleted
174413        ** when the handle was closed and a second attempt to open the 
174414        ** database may succeed.  */
174415        rbuOpenDatabase(p, &bRetry);
174416        if( bRetry ){
174417          rbuOpenDatabase(p, 0);
174418        }
174419      }
174420  
174421      if( p->rc==SQLITE_OK ){
174422        pState = rbuLoadState(p);
174423        assert( pState || p->rc!=SQLITE_OK );
174424        if( p->rc==SQLITE_OK ){
174425  
174426          if( pState->eStage==0 ){ 
174427            rbuDeleteOalFile(p);
174428            rbuInitPhaseOneSteps(p);
174429            p->eStage = RBU_STAGE_OAL;
174430          }else{
174431            p->eStage = pState->eStage;
174432            p->nPhaseOneStep = pState->nPhaseOneStep;
174433          }
174434          p->nProgress = pState->nProgress;
174435          p->iOalSz = pState->iOalSz;
174436        }
174437      }
174438      assert( p->rc!=SQLITE_OK || p->eStage!=0 );
174439  
174440      if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
174441        if( p->eStage==RBU_STAGE_OAL ){
174442          p->rc = SQLITE_ERROR;
174443          p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
174444        }else if( p->eStage==RBU_STAGE_MOVE ){
174445          p->eStage = RBU_STAGE_CKPT;
174446          p->nStep = 0;
174447        }
174448      }
174449  
174450      if( p->rc==SQLITE_OK 
174451       && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
174452       && pState->eStage!=0
174453      ){
174454        rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
174455        if( pFd->iCookie!=pState->iCookie ){   
174456          /* At this point (pTargetFd->iCookie) contains the value of the
174457          ** change-counter cookie (the thing that gets incremented when a 
174458          ** transaction is committed in rollback mode) currently stored on 
174459          ** page 1 of the database file. */
174460          p->rc = SQLITE_BUSY;
174461          p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
174462              (rbuIsVacuum(p) ? "vacuum" : "update")
174463          );
174464        }
174465      }
174466  
174467      if( p->rc==SQLITE_OK ){
174468        if( p->eStage==RBU_STAGE_OAL ){
174469          sqlite3 *db = p->dbMain;
174470          p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
174471  
174472          /* Point the object iterator at the first object */
174473          if( p->rc==SQLITE_OK ){
174474            p->rc = rbuObjIterFirst(p, &p->objiter);
174475          }
174476  
174477          /* If the RBU database contains no data_xxx tables, declare the RBU
174478          ** update finished.  */
174479          if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
174480            p->rc = SQLITE_DONE;
174481            p->eStage = RBU_STAGE_DONE;
174482          }else{
174483            if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
174484              rbuCopyPragma(p, "page_size");
174485              rbuCopyPragma(p, "auto_vacuum");
174486            }
174487  
174488            /* Open transactions both databases. The *-oal file is opened or
174489            ** created at this point. */
174490            if( p->rc==SQLITE_OK ){
174491              p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
174492            }
174493  
174494            /* Check if the main database is a zipvfs db. If it is, set the upper
174495            ** level pager to use "journal_mode=off". This prevents it from 
174496            ** generating a large journal using a temp file.  */
174497            if( p->rc==SQLITE_OK ){
174498              int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
174499              if( frc==SQLITE_OK ){
174500                p->rc = sqlite3_exec(
174501                  db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
174502              }
174503            }
174504  
174505            if( p->rc==SQLITE_OK ){
174506              rbuSetupOal(p, pState);
174507            }
174508          }
174509        }else if( p->eStage==RBU_STAGE_MOVE ){
174510          /* no-op */
174511        }else if( p->eStage==RBU_STAGE_CKPT ){
174512          rbuSetupCheckpoint(p, pState);
174513        }else if( p->eStage==RBU_STAGE_DONE ){
174514          p->rc = SQLITE_DONE;
174515        }else{
174516          p->rc = SQLITE_CORRUPT;
174517        }
174518      }
174519  
174520      rbuFreeState(pState);
174521    }
174522  
174523    return p;
174524  }
174525  
174526  /*
174527  ** Allocate and return an RBU handle with all fields zeroed except for the
174528  ** error code, which is set to SQLITE_MISUSE.
174529  */
174530  static sqlite3rbu *rbuMisuseError(void){
174531    sqlite3rbu *pRet;
174532    pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
174533    if( pRet ){
174534      memset(pRet, 0, sizeof(sqlite3rbu));
174535      pRet->rc = SQLITE_MISUSE;
174536    }
174537    return pRet;
174538  }
174539  
174540  /*
174541  ** Open and return a new RBU handle. 
174542  */
174543  SQLITE_API sqlite3rbu *sqlite3rbu_open(
174544    const char *zTarget, 
174545    const char *zRbu,
174546    const char *zState
174547  ){
174548    if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
174549    /* TODO: Check that zTarget and zRbu are non-NULL */
174550    return openRbuHandle(zTarget, zRbu, zState);
174551  }
174552  
174553  /*
174554  ** Open a handle to begin or resume an RBU VACUUM operation.
174555  */
174556  SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
174557    const char *zTarget, 
174558    const char *zState
174559  ){
174560    if( zTarget==0 ){ return rbuMisuseError(); }
174561    /* TODO: Check that both arguments are non-NULL */
174562    return openRbuHandle(0, zTarget, zState);
174563  }
174564  
174565  /*
174566  ** Return the database handle used by pRbu.
174567  */
174568  SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
174569    sqlite3 *db = 0;
174570    if( pRbu ){
174571      db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
174572    }
174573    return db;
174574  }
174575  
174576  
174577  /*
174578  ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
174579  ** then edit any error message string so as to remove all occurrences of
174580  ** the pattern "rbu_imp_[0-9]*".
174581  */
174582  static void rbuEditErrmsg(sqlite3rbu *p){
174583    if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
174584      unsigned int i;
174585      size_t nErrmsg = strlen(p->zErrmsg);
174586      for(i=0; i<(nErrmsg-8); i++){
174587        if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
174588          int nDel = 8;
174589          while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
174590          memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
174591          nErrmsg -= nDel;
174592        }
174593      }
174594    }
174595  }
174596  
174597  /*
174598  ** Close the RBU handle.
174599  */
174600  SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
174601    int rc;
174602    if( p ){
174603  
174604      /* Commit the transaction to the *-oal file. */
174605      if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
174606        p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
174607      }
174608  
174609      /* Sync the db file if currently doing an incremental checkpoint */
174610      if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
174611        sqlite3_file *pDb = p->pTargetFd->pReal;
174612        p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
174613      }
174614  
174615      rbuSaveState(p, p->eStage);
174616  
174617      if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
174618        p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
174619      }
174620  
174621      /* Close any open statement handles. */
174622      rbuObjIterFinalize(&p->objiter);
174623  
174624      /* If this is an RBU vacuum handle and the vacuum has either finished
174625      ** successfully or encountered an error, delete the contents of the 
174626      ** state table. This causes the next call to sqlite3rbu_vacuum() 
174627      ** specifying the current target and state databases to start a new
174628      ** vacuum from scratch.  */
174629      if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
174630        int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
174631        if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
174632      }
174633  
174634      /* Close the open database handle and VFS object. */
174635      sqlite3_close(p->dbRbu);
174636      sqlite3_close(p->dbMain);
174637      assert( p->szTemp==0 );
174638      rbuDeleteVfs(p);
174639      sqlite3_free(p->aBuf);
174640      sqlite3_free(p->aFrame);
174641  
174642      rbuEditErrmsg(p);
174643      rc = p->rc;
174644      if( pzErrmsg ){
174645        *pzErrmsg = p->zErrmsg;
174646      }else{
174647        sqlite3_free(p->zErrmsg);
174648      }
174649      sqlite3_free(p->zState);
174650      sqlite3_free(p);
174651    }else{
174652      rc = SQLITE_NOMEM;
174653      *pzErrmsg = 0;
174654    }
174655    return rc;
174656  }
174657  
174658  /*
174659  ** Return the total number of key-value operations (inserts, deletes or 
174660  ** updates) that have been performed on the target database since the
174661  ** current RBU update was started.
174662  */
174663  SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
174664    return pRbu->nProgress;
174665  }
174666  
174667  /*
174668  ** Return permyriadage progress indications for the two main stages of
174669  ** an RBU update.
174670  */
174671  SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
174672    const int MAX_PROGRESS = 10000;
174673    switch( p->eStage ){
174674      case RBU_STAGE_OAL:
174675        if( p->nPhaseOneStep>0 ){
174676          *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
174677        }else{
174678          *pnOne = -1;
174679        }
174680        *pnTwo = 0;
174681        break;
174682  
174683      case RBU_STAGE_MOVE:
174684        *pnOne = MAX_PROGRESS;
174685        *pnTwo = 0;
174686        break;
174687  
174688      case RBU_STAGE_CKPT:
174689        *pnOne = MAX_PROGRESS;
174690        *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
174691        break;
174692  
174693      case RBU_STAGE_DONE:
174694        *pnOne = MAX_PROGRESS;
174695        *pnTwo = MAX_PROGRESS;
174696        break;
174697  
174698      default:
174699        assert( 0 );
174700    }
174701  }
174702  
174703  /*
174704  ** Return the current state of the RBU vacuum or update operation.
174705  */
174706  SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){
174707    int aRes[] = {
174708      0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
174709      0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
174710    };
174711  
174712    assert( RBU_STAGE_OAL==1 );
174713    assert( RBU_STAGE_MOVE==2 );
174714    assert( RBU_STAGE_CKPT==4 );
174715    assert( RBU_STAGE_DONE==5 );
174716    assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
174717    assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
174718    assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
174719    assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
174720  
174721    if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
174722      return SQLITE_RBU_STATE_ERROR;
174723    }else{
174724      assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
174725      assert( p->eStage==RBU_STAGE_OAL
174726           || p->eStage==RBU_STAGE_MOVE
174727           || p->eStage==RBU_STAGE_CKPT
174728           || p->eStage==RBU_STAGE_DONE
174729      );
174730      return aRes[p->eStage];
174731    }
174732  }
174733  
174734  SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
174735    int rc = p->rc;
174736    if( rc==SQLITE_DONE ) return SQLITE_OK;
174737  
174738    assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
174739    if( p->eStage==RBU_STAGE_OAL ){
174740      assert( rc!=SQLITE_DONE );
174741      if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
174742    }
174743  
174744    /* Sync the db file */
174745    if( rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
174746      sqlite3_file *pDb = p->pTargetFd->pReal;
174747      rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
174748    }
174749  
174750    p->rc = rc;
174751    rbuSaveState(p, p->eStage);
174752    rc = p->rc;
174753  
174754    if( p->eStage==RBU_STAGE_OAL ){
174755      assert( rc!=SQLITE_DONE );
174756      if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
174757      if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
174758      if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
174759    }
174760  
174761    p->rc = rc;
174762    return rc;
174763  }
174764  
174765  /**************************************************************************
174766  ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
174767  ** of a standard VFS in the following ways:
174768  **
174769  ** 1. Whenever the first page of a main database file is read or 
174770  **    written, the value of the change-counter cookie is stored in
174771  **    rbu_file.iCookie. Similarly, the value of the "write-version"
174772  **    database header field is stored in rbu_file.iWriteVer. This ensures
174773  **    that the values are always trustworthy within an open transaction.
174774  **
174775  ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
174776  **    member variable of the associated database file descriptor is set
174777  **    to point to the new file. A mutex protected linked list of all main 
174778  **    db fds opened using a particular RBU VFS is maintained at 
174779  **    rbu_vfs.pMain to facilitate this.
174780  **
174781  ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file 
174782  **    object can be marked as the target database of an RBU update. This
174783  **    turns on the following extra special behaviour:
174784  **
174785  ** 3a. If xAccess() is called to check if there exists a *-wal file 
174786  **     associated with an RBU target database currently in RBU_STAGE_OAL
174787  **     stage (preparing the *-oal file), the following special handling
174788  **     applies:
174789  **
174790  **      * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
174791  **        target database may not be in wal mode already.
174792  **
174793  **      * if the *-wal file does not exist, set the output parameter to
174794  **        non-zero (to tell SQLite that it does exist) anyway.
174795  **
174796  **     Then, when xOpen() is called to open the *-wal file associated with
174797  **     the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
174798  **     file, the rbu vfs opens the corresponding *-oal file instead. 
174799  **
174800  ** 3b. The *-shm pages returned by xShmMap() for a target db file in
174801  **     RBU_STAGE_OAL mode are actually stored in heap memory. This is to
174802  **     avoid creating a *-shm file on disk. Additionally, xShmLock() calls
174803  **     are no-ops on target database files in RBU_STAGE_OAL mode. This is
174804  **     because assert() statements in some VFS implementations fail if 
174805  **     xShmLock() is called before xShmMap().
174806  **
174807  ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
174808  **     mode except RBU_STAGE_DONE (all work completed and checkpointed), it 
174809  **     fails with an SQLITE_BUSY error. This is to stop RBU connections
174810  **     from automatically checkpointing a *-wal (or *-oal) file from within
174811  **     sqlite3_close().
174812  **
174813  ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
174814  **     all xWrite() calls on the target database file perform no IO. 
174815  **     Instead the frame and page numbers that would be read and written
174816  **     are recorded. Additionally, successful attempts to obtain exclusive
174817  **     xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target 
174818  **     database file are recorded. xShmLock() calls to unlock the same
174819  **     locks are no-ops (so that once obtained, these locks are never
174820  **     relinquished). Finally, calls to xSync() on the target database
174821  **     file fail with SQLITE_INTERNAL errors.
174822  */
174823  
174824  static void rbuUnlockShm(rbu_file *p){
174825    assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
174826    if( p->pRbu ){
174827      int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
174828      int i;
174829      for(i=0; i<SQLITE_SHM_NLOCK;i++){
174830        if( (1<<i) & p->pRbu->mLock ){
174831          xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
174832        }
174833      }
174834      p->pRbu->mLock = 0;
174835    }
174836  }
174837  
174838  /*
174839  */
174840  static int rbuUpdateTempSize(rbu_file *pFd, sqlite3_int64 nNew){
174841    sqlite3rbu *pRbu = pFd->pRbu;
174842    i64 nDiff = nNew - pFd->sz;
174843    pRbu->szTemp += nDiff;
174844    pFd->sz = nNew;
174845    assert( pRbu->szTemp>=0 );
174846    if( pRbu->szTempLimit && pRbu->szTemp>pRbu->szTempLimit ) return SQLITE_FULL;
174847    return SQLITE_OK;
174848  }
174849  
174850  /*
174851  ** Close an rbu file.
174852  */
174853  static int rbuVfsClose(sqlite3_file *pFile){
174854    rbu_file *p = (rbu_file*)pFile;
174855    int rc;
174856    int i;
174857  
174858    /* Free the contents of the apShm[] array. And the array itself. */
174859    for(i=0; i<p->nShm; i++){
174860      sqlite3_free(p->apShm[i]);
174861    }
174862    sqlite3_free(p->apShm);
174863    p->apShm = 0;
174864    sqlite3_free(p->zDel);
174865  
174866    if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
174867      rbu_file **pp;
174868      sqlite3_mutex_enter(p->pRbuVfs->mutex);
174869      for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
174870      *pp = p->pMainNext;
174871      sqlite3_mutex_leave(p->pRbuVfs->mutex);
174872      rbuUnlockShm(p);
174873      p->pReal->pMethods->xShmUnmap(p->pReal, 0);
174874    }
174875    else if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
174876      rbuUpdateTempSize(p, 0);
174877    }
174878  
174879    /* Close the underlying file handle */
174880    rc = p->pReal->pMethods->xClose(p->pReal);
174881    return rc;
174882  }
174883  
174884  
174885  /*
174886  ** Read and return an unsigned 32-bit big-endian integer from the buffer 
174887  ** passed as the only argument.
174888  */
174889  static u32 rbuGetU32(u8 *aBuf){
174890    return ((u32)aBuf[0] << 24)
174891         + ((u32)aBuf[1] << 16)
174892         + ((u32)aBuf[2] <<  8)
174893         + ((u32)aBuf[3]);
174894  }
174895  
174896  /*
174897  ** Write an unsigned 32-bit value in big-endian format to the supplied
174898  ** buffer.
174899  */
174900  static void rbuPutU32(u8 *aBuf, u32 iVal){
174901    aBuf[0] = (iVal >> 24) & 0xFF;
174902    aBuf[1] = (iVal >> 16) & 0xFF;
174903    aBuf[2] = (iVal >>  8) & 0xFF;
174904    aBuf[3] = (iVal >>  0) & 0xFF;
174905  }
174906  
174907  static void rbuPutU16(u8 *aBuf, u16 iVal){
174908    aBuf[0] = (iVal >>  8) & 0xFF;
174909    aBuf[1] = (iVal >>  0) & 0xFF;
174910  }
174911  
174912  /*
174913  ** Read data from an rbuVfs-file.
174914  */
174915  static int rbuVfsRead(
174916    sqlite3_file *pFile, 
174917    void *zBuf, 
174918    int iAmt, 
174919    sqlite_int64 iOfst
174920  ){
174921    rbu_file *p = (rbu_file*)pFile;
174922    sqlite3rbu *pRbu = p->pRbu;
174923    int rc;
174924  
174925    if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
174926      assert( p->openFlags & SQLITE_OPEN_WAL );
174927      rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
174928    }else{
174929      if( pRbu && pRbu->eStage==RBU_STAGE_OAL 
174930       && (p->openFlags & SQLITE_OPEN_WAL) 
174931       && iOfst>=pRbu->iOalSz 
174932      ){
174933        rc = SQLITE_OK;
174934        memset(zBuf, 0, iAmt);
174935      }else{
174936        rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
174937  #if 1
174938        /* If this is being called to read the first page of the target 
174939        ** database as part of an rbu vacuum operation, synthesize the 
174940        ** contents of the first page if it does not yet exist. Otherwise,
174941        ** SQLite will not check for a *-wal file.  */
174942        if( pRbu && rbuIsVacuum(pRbu) 
174943            && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
174944            && (p->openFlags & SQLITE_OPEN_MAIN_DB)
174945            && pRbu->rc==SQLITE_OK
174946        ){
174947          sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
174948          rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
174949          if( rc==SQLITE_OK ){
174950            u8 *aBuf = (u8*)zBuf;
174951            u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
174952            rbuPutU32(&aBuf[52], iRoot);      /* largest root page number */
174953            rbuPutU32(&aBuf[36], 0);          /* number of free pages */
174954            rbuPutU32(&aBuf[32], 0);          /* first page on free list trunk */
174955            rbuPutU32(&aBuf[28], 1);          /* size of db file in pages */
174956            rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1);  /* Change counter */
174957  
174958            if( iAmt>100 ){
174959              memset(&aBuf[100], 0, iAmt-100);
174960              rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
174961              aBuf[100] = 0x0D;
174962            }
174963          }
174964        }
174965  #endif
174966      }
174967      if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
174968        /* These look like magic numbers. But they are stable, as they are part
174969         ** of the definition of the SQLite file format, which may not change. */
174970        u8 *pBuf = (u8*)zBuf;
174971        p->iCookie = rbuGetU32(&pBuf[24]);
174972        p->iWriteVer = pBuf[19];
174973      }
174974    }
174975    return rc;
174976  }
174977  
174978  /*
174979  ** Write data to an rbuVfs-file.
174980  */
174981  static int rbuVfsWrite(
174982    sqlite3_file *pFile, 
174983    const void *zBuf, 
174984    int iAmt, 
174985    sqlite_int64 iOfst
174986  ){
174987    rbu_file *p = (rbu_file*)pFile;
174988    sqlite3rbu *pRbu = p->pRbu;
174989    int rc;
174990  
174991    if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
174992      assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
174993      rc = rbuCaptureDbWrite(p->pRbu, iOfst);
174994    }else{
174995      if( pRbu ){
174996        if( pRbu->eStage==RBU_STAGE_OAL 
174997         && (p->openFlags & SQLITE_OPEN_WAL) 
174998         && iOfst>=pRbu->iOalSz
174999        ){
175000          pRbu->iOalSz = iAmt + iOfst;
175001        }else if( p->openFlags & SQLITE_OPEN_DELETEONCLOSE ){
175002          i64 szNew = iAmt+iOfst;
175003          if( szNew>p->sz ){
175004            rc = rbuUpdateTempSize(p, szNew);
175005            if( rc!=SQLITE_OK ) return rc;
175006          }
175007        }
175008      }
175009      rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
175010      if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
175011        /* These look like magic numbers. But they are stable, as they are part
175012        ** of the definition of the SQLite file format, which may not change. */
175013        u8 *pBuf = (u8*)zBuf;
175014        p->iCookie = rbuGetU32(&pBuf[24]);
175015        p->iWriteVer = pBuf[19];
175016      }
175017    }
175018    return rc;
175019  }
175020  
175021  /*
175022  ** Truncate an rbuVfs-file.
175023  */
175024  static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
175025    rbu_file *p = (rbu_file*)pFile;
175026    if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
175027      int rc = rbuUpdateTempSize(p, size);
175028      if( rc!=SQLITE_OK ) return rc;
175029    }
175030    return p->pReal->pMethods->xTruncate(p->pReal, size);
175031  }
175032  
175033  /*
175034  ** Sync an rbuVfs-file.
175035  */
175036  static int rbuVfsSync(sqlite3_file *pFile, int flags){
175037    rbu_file *p = (rbu_file *)pFile;
175038    if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
175039      if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
175040        return SQLITE_INTERNAL;
175041      }
175042      return SQLITE_OK;
175043    }
175044    return p->pReal->pMethods->xSync(p->pReal, flags);
175045  }
175046  
175047  /*
175048  ** Return the current file-size of an rbuVfs-file.
175049  */
175050  static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
175051    rbu_file *p = (rbu_file *)pFile;
175052    int rc;
175053    rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
175054  
175055    /* If this is an RBU vacuum operation and this is the target database,
175056    ** pretend that it has at least one page. Otherwise, SQLite will not
175057    ** check for the existance of a *-wal file. rbuVfsRead() contains 
175058    ** similar logic.  */
175059    if( rc==SQLITE_OK && *pSize==0 
175060     && p->pRbu && rbuIsVacuum(p->pRbu) 
175061     && (p->openFlags & SQLITE_OPEN_MAIN_DB)
175062    ){
175063      *pSize = 1024;
175064    }
175065    return rc;
175066  }
175067  
175068  /*
175069  ** Lock an rbuVfs-file.
175070  */
175071  static int rbuVfsLock(sqlite3_file *pFile, int eLock){
175072    rbu_file *p = (rbu_file*)pFile;
175073    sqlite3rbu *pRbu = p->pRbu;
175074    int rc = SQLITE_OK;
175075  
175076    assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
175077    if( eLock==SQLITE_LOCK_EXCLUSIVE 
175078     && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
175079    ){
175080      /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this 
175081      ** prevents it from checkpointing the database from sqlite3_close(). */
175082      rc = SQLITE_BUSY;
175083    }else{
175084      rc = p->pReal->pMethods->xLock(p->pReal, eLock);
175085    }
175086  
175087    return rc;
175088  }
175089  
175090  /*
175091  ** Unlock an rbuVfs-file.
175092  */
175093  static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
175094    rbu_file *p = (rbu_file *)pFile;
175095    return p->pReal->pMethods->xUnlock(p->pReal, eLock);
175096  }
175097  
175098  /*
175099  ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
175100  */
175101  static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
175102    rbu_file *p = (rbu_file *)pFile;
175103    return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
175104  }
175105  
175106  /*
175107  ** File control method. For custom operations on an rbuVfs-file.
175108  */
175109  static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
175110    rbu_file *p = (rbu_file *)pFile;
175111    int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
175112    int rc;
175113  
175114    assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
175115         || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
175116    );
175117    if( op==SQLITE_FCNTL_RBU ){
175118      sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
175119  
175120      /* First try to find another RBU vfs lower down in the vfs stack. If
175121      ** one is found, this vfs will operate in pass-through mode. The lower
175122      ** level vfs will do the special RBU handling.  */
175123      rc = xControl(p->pReal, op, pArg);
175124  
175125      if( rc==SQLITE_NOTFOUND ){
175126        /* Now search for a zipvfs instance lower down in the VFS stack. If
175127        ** one is found, this is an error.  */
175128        void *dummy = 0;
175129        rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
175130        if( rc==SQLITE_OK ){
175131          rc = SQLITE_ERROR;
175132          pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
175133        }else if( rc==SQLITE_NOTFOUND ){
175134          pRbu->pTargetFd = p;
175135          p->pRbu = pRbu;
175136          if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
175137          rc = SQLITE_OK;
175138        }
175139      }
175140      return rc;
175141    }
175142    else if( op==SQLITE_FCNTL_RBUCNT ){
175143      sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
175144      pRbu->nRbu++;
175145      pRbu->pRbuFd = p;
175146      p->bNolock = 1;
175147    }
175148  
175149    rc = xControl(p->pReal, op, pArg);
175150    if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
175151      rbu_vfs *pRbuVfs = p->pRbuVfs;
175152      char *zIn = *(char**)pArg;
175153      char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
175154      *(char**)pArg = zOut;
175155      if( zOut==0 ) rc = SQLITE_NOMEM;
175156    }
175157  
175158    return rc;
175159  }
175160  
175161  /*
175162  ** Return the sector-size in bytes for an rbuVfs-file.
175163  */
175164  static int rbuVfsSectorSize(sqlite3_file *pFile){
175165    rbu_file *p = (rbu_file *)pFile;
175166    return p->pReal->pMethods->xSectorSize(p->pReal);
175167  }
175168  
175169  /*
175170  ** Return the device characteristic flags supported by an rbuVfs-file.
175171  */
175172  static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
175173    rbu_file *p = (rbu_file *)pFile;
175174    return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
175175  }
175176  
175177  /*
175178  ** Take or release a shared-memory lock.
175179  */
175180  static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
175181    rbu_file *p = (rbu_file*)pFile;
175182    sqlite3rbu *pRbu = p->pRbu;
175183    int rc = SQLITE_OK;
175184  
175185  #ifdef SQLITE_AMALGAMATION
175186      assert( WAL_CKPT_LOCK==1 );
175187  #endif
175188  
175189    assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
175190    if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
175191      /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
175192      ** taking this lock also prevents any checkpoints from occurring. 
175193      ** todo: really, it's not clear why this might occur, as 
175194      ** wal_autocheckpoint ought to be turned off.  */
175195      if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
175196    }else{
175197      int bCapture = 0;
175198      if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
175199       && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
175200       && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
175201      ){
175202        bCapture = 1;
175203      }
175204  
175205      if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
175206        rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
175207        if( bCapture && rc==SQLITE_OK ){
175208          pRbu->mLock |= (1 << ofst);
175209        }
175210      }
175211    }
175212  
175213    return rc;
175214  }
175215  
175216  /*
175217  ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
175218  */
175219  static int rbuVfsShmMap(
175220    sqlite3_file *pFile, 
175221    int iRegion, 
175222    int szRegion, 
175223    int isWrite, 
175224    void volatile **pp
175225  ){
175226    rbu_file *p = (rbu_file*)pFile;
175227    int rc = SQLITE_OK;
175228    int eStage = (p->pRbu ? p->pRbu->eStage : 0);
175229  
175230    /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
175231    ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space 
175232    ** instead of a file on disk.  */
175233    assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
175234    if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
175235      if( iRegion<=p->nShm ){
175236        int nByte = (iRegion+1) * sizeof(char*);
175237        char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
175238        if( apNew==0 ){
175239          rc = SQLITE_NOMEM;
175240        }else{
175241          memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
175242          p->apShm = apNew;
175243          p->nShm = iRegion+1;
175244        }
175245      }
175246  
175247      if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
175248        char *pNew = (char*)sqlite3_malloc64(szRegion);
175249        if( pNew==0 ){
175250          rc = SQLITE_NOMEM;
175251        }else{
175252          memset(pNew, 0, szRegion);
175253          p->apShm[iRegion] = pNew;
175254        }
175255      }
175256  
175257      if( rc==SQLITE_OK ){
175258        *pp = p->apShm[iRegion];
175259      }else{
175260        *pp = 0;
175261      }
175262    }else{
175263      assert( p->apShm==0 );
175264      rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
175265    }
175266  
175267    return rc;
175268  }
175269  
175270  /*
175271  ** Memory barrier.
175272  */
175273  static void rbuVfsShmBarrier(sqlite3_file *pFile){
175274    rbu_file *p = (rbu_file *)pFile;
175275    p->pReal->pMethods->xShmBarrier(p->pReal);
175276  }
175277  
175278  /*
175279  ** The xShmUnmap method.
175280  */
175281  static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
175282    rbu_file *p = (rbu_file*)pFile;
175283    int rc = SQLITE_OK;
175284    int eStage = (p->pRbu ? p->pRbu->eStage : 0);
175285  
175286    assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
175287    if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
175288      /* no-op */
175289    }else{
175290      /* Release the checkpointer and writer locks */
175291      rbuUnlockShm(p);
175292      rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
175293    }
175294    return rc;
175295  }
175296  
175297  /*
175298  ** Given that zWal points to a buffer containing a wal file name passed to 
175299  ** either the xOpen() or xAccess() VFS method, return a pointer to the
175300  ** file-handle opened by the same database connection on the corresponding
175301  ** database file.
175302  */
175303  static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
175304    rbu_file *pDb;
175305    sqlite3_mutex_enter(pRbuVfs->mutex);
175306    for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
175307    sqlite3_mutex_leave(pRbuVfs->mutex);
175308    return pDb;
175309  }
175310  
175311  /* 
175312  ** A main database named zName has just been opened. The following 
175313  ** function returns a pointer to a buffer owned by SQLite that contains
175314  ** the name of the *-wal file this db connection will use. SQLite
175315  ** happens to pass a pointer to this buffer when using xAccess()
175316  ** or xOpen() to operate on the *-wal file.  
175317  */
175318  static const char *rbuMainToWal(const char *zName, int flags){
175319    int n = (int)strlen(zName);
175320    const char *z = &zName[n];
175321    if( flags & SQLITE_OPEN_URI ){
175322      int odd = 0;
175323      while( 1 ){
175324        if( z[0]==0 ){
175325          odd = 1 - odd;
175326          if( odd && z[1]==0 ) break;
175327        }
175328        z++;
175329      }
175330      z += 2;
175331    }else{
175332      while( *z==0 ) z++;
175333    }
175334    z += (n + 8 + 1);
175335    return z;
175336  }
175337  
175338  /*
175339  ** Open an rbu file handle.
175340  */
175341  static int rbuVfsOpen(
175342    sqlite3_vfs *pVfs,
175343    const char *zName,
175344    sqlite3_file *pFile,
175345    int flags,
175346    int *pOutFlags
175347  ){
175348    static sqlite3_io_methods rbuvfs_io_methods = {
175349      2,                            /* iVersion */
175350      rbuVfsClose,                  /* xClose */
175351      rbuVfsRead,                   /* xRead */
175352      rbuVfsWrite,                  /* xWrite */
175353      rbuVfsTruncate,               /* xTruncate */
175354      rbuVfsSync,                   /* xSync */
175355      rbuVfsFileSize,               /* xFileSize */
175356      rbuVfsLock,                   /* xLock */
175357      rbuVfsUnlock,                 /* xUnlock */
175358      rbuVfsCheckReservedLock,      /* xCheckReservedLock */
175359      rbuVfsFileControl,            /* xFileControl */
175360      rbuVfsSectorSize,             /* xSectorSize */
175361      rbuVfsDeviceCharacteristics,  /* xDeviceCharacteristics */
175362      rbuVfsShmMap,                 /* xShmMap */
175363      rbuVfsShmLock,                /* xShmLock */
175364      rbuVfsShmBarrier,             /* xShmBarrier */
175365      rbuVfsShmUnmap,               /* xShmUnmap */
175366      0, 0                          /* xFetch, xUnfetch */
175367    };
175368    rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
175369    sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
175370    rbu_file *pFd = (rbu_file *)pFile;
175371    int rc = SQLITE_OK;
175372    const char *zOpen = zName;
175373    int oflags = flags;
175374  
175375    memset(pFd, 0, sizeof(rbu_file));
175376    pFd->pReal = (sqlite3_file*)&pFd[1];
175377    pFd->pRbuVfs = pRbuVfs;
175378    pFd->openFlags = flags;
175379    if( zName ){
175380      if( flags & SQLITE_OPEN_MAIN_DB ){
175381        /* A main database has just been opened. The following block sets
175382        ** (pFd->zWal) to point to a buffer owned by SQLite that contains
175383        ** the name of the *-wal file this db connection will use. SQLite
175384        ** happens to pass a pointer to this buffer when using xAccess()
175385        ** or xOpen() to operate on the *-wal file.  */
175386        pFd->zWal = rbuMainToWal(zName, flags);
175387      }
175388      else if( flags & SQLITE_OPEN_WAL ){
175389        rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
175390        if( pDb ){
175391          if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
175392            /* This call is to open a *-wal file. Intead, open the *-oal. This
175393            ** code ensures that the string passed to xOpen() is terminated by a
175394            ** pair of '\0' bytes in case the VFS attempts to extract a URI 
175395            ** parameter from it.  */
175396            const char *zBase = zName;
175397            size_t nCopy;
175398            char *zCopy;
175399            if( rbuIsVacuum(pDb->pRbu) ){
175400              zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
175401              zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
175402            }
175403            nCopy = strlen(zBase);
175404            zCopy = sqlite3_malloc64(nCopy+2);
175405            if( zCopy ){
175406              memcpy(zCopy, zBase, nCopy);
175407              zCopy[nCopy-3] = 'o';
175408              zCopy[nCopy] = '\0';
175409              zCopy[nCopy+1] = '\0';
175410              zOpen = (const char*)(pFd->zDel = zCopy);
175411            }else{
175412              rc = SQLITE_NOMEM;
175413            }
175414            pFd->pRbu = pDb->pRbu;
175415          }
175416          pDb->pWalFd = pFd;
175417        }
175418      }
175419    }else{
175420      pFd->pRbu = pRbuVfs->pRbu;
175421    }
175422  
175423    if( oflags & SQLITE_OPEN_MAIN_DB 
175424     && sqlite3_uri_boolean(zName, "rbu_memory", 0) 
175425    ){
175426      assert( oflags & SQLITE_OPEN_MAIN_DB );
175427      oflags =  SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
175428                SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
175429      zOpen = 0;
175430    }
175431  
175432    if( rc==SQLITE_OK ){
175433      rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
175434    }
175435    if( pFd->pReal->pMethods ){
175436      /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
175437      ** pointer and, if the file is a main database file, link it into the
175438      ** mutex protected linked list of all such files.  */
175439      pFile->pMethods = &rbuvfs_io_methods;
175440      if( flags & SQLITE_OPEN_MAIN_DB ){
175441        sqlite3_mutex_enter(pRbuVfs->mutex);
175442        pFd->pMainNext = pRbuVfs->pMain;
175443        pRbuVfs->pMain = pFd;
175444        sqlite3_mutex_leave(pRbuVfs->mutex);
175445      }
175446    }else{
175447      sqlite3_free(pFd->zDel);
175448    }
175449  
175450    return rc;
175451  }
175452  
175453  /*
175454  ** Delete the file located at zPath.
175455  */
175456  static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
175457    sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175458    return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
175459  }
175460  
175461  /*
175462  ** Test for access permissions. Return true if the requested permission
175463  ** is available, or false otherwise.
175464  */
175465  static int rbuVfsAccess(
175466    sqlite3_vfs *pVfs, 
175467    const char *zPath, 
175468    int flags, 
175469    int *pResOut
175470  ){
175471    rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
175472    sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
175473    int rc;
175474  
175475    rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
175476  
175477    /* If this call is to check if a *-wal file associated with an RBU target
175478    ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
175479    ** the following special handling is activated:
175480    **
175481    **   a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
175482    **      ensures that the RBU extension never tries to update a database
175483    **      in wal mode, even if the first page of the database file has
175484    **      been damaged. 
175485    **
175486    **   b) if the *-wal file does not exist, claim that it does anyway,
175487    **      causing SQLite to call xOpen() to open it. This call will also
175488    **      be intercepted (see the rbuVfsOpen() function) and the *-oal
175489    **      file opened instead.
175490    */
175491    if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
175492      rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
175493      if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
175494        if( *pResOut ){
175495          rc = SQLITE_CANTOPEN;
175496        }else{
175497          sqlite3_int64 sz = 0;
175498          rc = rbuVfsFileSize(&pDb->base, &sz);
175499          *pResOut = (sz>0);
175500        }
175501      }
175502    }
175503  
175504    return rc;
175505  }
175506  
175507  /*
175508  ** Populate buffer zOut with the full canonical pathname corresponding
175509  ** to the pathname in zPath. zOut is guaranteed to point to a buffer
175510  ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
175511  */
175512  static int rbuVfsFullPathname(
175513    sqlite3_vfs *pVfs, 
175514    const char *zPath, 
175515    int nOut, 
175516    char *zOut
175517  ){
175518    sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175519    return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
175520  }
175521  
175522  #ifndef SQLITE_OMIT_LOAD_EXTENSION
175523  /*
175524  ** Open the dynamic library located at zPath and return a handle.
175525  */
175526  static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
175527    sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175528    return pRealVfs->xDlOpen(pRealVfs, zPath);
175529  }
175530  
175531  /*
175532  ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
175533  ** utf-8 string describing the most recent error encountered associated 
175534  ** with dynamic libraries.
175535  */
175536  static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
175537    sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175538    pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
175539  }
175540  
175541  /*
175542  ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
175543  */
175544  static void (*rbuVfsDlSym(
175545    sqlite3_vfs *pVfs, 
175546    void *pArg, 
175547    const char *zSym
175548  ))(void){
175549    sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175550    return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
175551  }
175552  
175553  /*
175554  ** Close the dynamic library handle pHandle.
175555  */
175556  static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
175557    sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175558    pRealVfs->xDlClose(pRealVfs, pHandle);
175559  }
175560  #endif /* SQLITE_OMIT_LOAD_EXTENSION */
175561  
175562  /*
175563  ** Populate the buffer pointed to by zBufOut with nByte bytes of 
175564  ** random data.
175565  */
175566  static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
175567    sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175568    return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
175569  }
175570  
175571  /*
175572  ** Sleep for nMicro microseconds. Return the number of microseconds 
175573  ** actually slept.
175574  */
175575  static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
175576    sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175577    return pRealVfs->xSleep(pRealVfs, nMicro);
175578  }
175579  
175580  /*
175581  ** Return the current time as a Julian Day number in *pTimeOut.
175582  */
175583  static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
175584    sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175585    return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
175586  }
175587  
175588  /*
175589  ** No-op.
175590  */
175591  static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
175592    return 0;
175593  }
175594  
175595  /*
175596  ** Deregister and destroy an RBU vfs created by an earlier call to
175597  ** sqlite3rbu_create_vfs().
175598  */
175599  SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){
175600    sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
175601    if( pVfs && pVfs->xOpen==rbuVfsOpen ){
175602      sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
175603      sqlite3_vfs_unregister(pVfs);
175604      sqlite3_free(pVfs);
175605    }
175606  }
175607  
175608  /*
175609  ** Create an RBU VFS named zName that accesses the underlying file-system
175610  ** via existing VFS zParent. The new object is registered as a non-default
175611  ** VFS with SQLite before returning.
175612  */
175613  SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
175614  
175615    /* Template for VFS */
175616    static sqlite3_vfs vfs_template = {
175617      1,                            /* iVersion */
175618      0,                            /* szOsFile */
175619      0,                            /* mxPathname */
175620      0,                            /* pNext */
175621      0,                            /* zName */
175622      0,                            /* pAppData */
175623      rbuVfsOpen,                   /* xOpen */
175624      rbuVfsDelete,                 /* xDelete */
175625      rbuVfsAccess,                 /* xAccess */
175626      rbuVfsFullPathname,           /* xFullPathname */
175627  
175628  #ifndef SQLITE_OMIT_LOAD_EXTENSION
175629      rbuVfsDlOpen,                 /* xDlOpen */
175630      rbuVfsDlError,                /* xDlError */
175631      rbuVfsDlSym,                  /* xDlSym */
175632      rbuVfsDlClose,                /* xDlClose */
175633  #else
175634      0, 0, 0, 0,
175635  #endif
175636  
175637      rbuVfsRandomness,             /* xRandomness */
175638      rbuVfsSleep,                  /* xSleep */
175639      rbuVfsCurrentTime,            /* xCurrentTime */
175640      rbuVfsGetLastError,           /* xGetLastError */
175641      0,                            /* xCurrentTimeInt64 (version 2) */
175642      0, 0, 0                       /* Unimplemented version 3 methods */
175643    };
175644  
175645    rbu_vfs *pNew = 0;              /* Newly allocated VFS */
175646    int rc = SQLITE_OK;
175647    size_t nName;
175648    size_t nByte;
175649  
175650    nName = strlen(zName);
175651    nByte = sizeof(rbu_vfs) + nName + 1;
175652    pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
175653    if( pNew==0 ){
175654      rc = SQLITE_NOMEM;
175655    }else{
175656      sqlite3_vfs *pParent;           /* Parent VFS */
175657      memset(pNew, 0, nByte);
175658      pParent = sqlite3_vfs_find(zParent);
175659      if( pParent==0 ){
175660        rc = SQLITE_NOTFOUND;
175661      }else{
175662        char *zSpace;
175663        memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
175664        pNew->base.mxPathname = pParent->mxPathname;
175665        pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
175666        pNew->pRealVfs = pParent;
175667        pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
175668        memcpy(zSpace, zName, nName);
175669  
175670        /* Allocate the mutex and register the new VFS (not as the default) */
175671        pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
175672        if( pNew->mutex==0 ){
175673          rc = SQLITE_NOMEM;
175674        }else{
175675          rc = sqlite3_vfs_register(&pNew->base, 0);
175676        }
175677      }
175678  
175679      if( rc!=SQLITE_OK ){
175680        sqlite3_mutex_free(pNew->mutex);
175681        sqlite3_free(pNew);
175682      }
175683    }
175684  
175685    return rc;
175686  }
175687  
175688  /*
175689  ** Configure the aggregate temp file size limit for this RBU handle.
175690  */
175691  SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu *pRbu, sqlite3_int64 n){
175692    if( n>=0 ){
175693      pRbu->szTempLimit = n;
175694    }
175695    return pRbu->szTempLimit;
175696  }
175697  
175698  SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu *pRbu){
175699    return pRbu->szTemp;
175700  }
175701  
175702  
175703  /**************************************************************************/
175704  
175705  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
175706  
175707  /************** End of sqlite3rbu.c ******************************************/
175708  /************** Begin file dbstat.c ******************************************/
175709  /*
175710  ** 2010 July 12
175711  **
175712  ** The author disclaims copyright to this source code.  In place of
175713  ** a legal notice, here is a blessing:
175714  **
175715  **    May you do good and not evil.
175716  **    May you find forgiveness for yourself and forgive others.
175717  **    May you share freely, never taking more than you give.
175718  **
175719  ******************************************************************************
175720  **
175721  ** This file contains an implementation of the "dbstat" virtual table.
175722  **
175723  ** The dbstat virtual table is used to extract low-level formatting
175724  ** information from an SQLite database in order to implement the
175725  ** "sqlite3_analyzer" utility.  See the ../tool/spaceanal.tcl script
175726  ** for an example implementation.
175727  **
175728  ** Additional information is available on the "dbstat.html" page of the
175729  ** official SQLite documentation.
175730  */
175731  
175732  /* #include "sqliteInt.h"   ** Requires access to internal data structures ** */
175733  #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
175734      && !defined(SQLITE_OMIT_VIRTUALTABLE)
175735  
175736  /*
175737  ** Page paths:
175738  ** 
175739  **   The value of the 'path' column describes the path taken from the 
175740  **   root-node of the b-tree structure to each page. The value of the 
175741  **   root-node path is '/'.
175742  **
175743  **   The value of the path for the left-most child page of the root of
175744  **   a b-tree is '/000/'. (Btrees store content ordered from left to right
175745  **   so the pages to the left have smaller keys than the pages to the right.)
175746  **   The next to left-most child of the root page is
175747  **   '/001', and so on, each sibling page identified by a 3-digit hex 
175748  **   value. The children of the 451st left-most sibling have paths such
175749  **   as '/1c2/000/, '/1c2/001/' etc.
175750  **
175751  **   Overflow pages are specified by appending a '+' character and a 
175752  **   six-digit hexadecimal value to the path to the cell they are linked
175753  **   from. For example, the three overflow pages in a chain linked from 
175754  **   the left-most cell of the 450th child of the root page are identified
175755  **   by the paths:
175756  **
175757  **      '/1c2/000+000000'         // First page in overflow chain
175758  **      '/1c2/000+000001'         // Second page in overflow chain
175759  **      '/1c2/000+000002'         // Third page in overflow chain
175760  **
175761  **   If the paths are sorted using the BINARY collation sequence, then
175762  **   the overflow pages associated with a cell will appear earlier in the
175763  **   sort-order than its child page:
175764  **
175765  **      '/1c2/000/'               // Left-most child of 451st child of root
175766  */
175767  #define VTAB_SCHEMA                                                         \
175768    "CREATE TABLE xx( "                                                       \
175769    "  name       TEXT,             /* Name of table or index */"             \
175770    "  path       TEXT,             /* Path to page from root */"             \
175771    "  pageno     INTEGER,          /* Page number */"                        \
175772    "  pagetype   TEXT,             /* 'internal', 'leaf' or 'overflow' */"   \
175773    "  ncell      INTEGER,          /* Cells on page (0 for overflow) */"     \
175774    "  payload    INTEGER,          /* Bytes of payload on this page */"      \
175775    "  unused     INTEGER,          /* Bytes of unused space on this page */" \
175776    "  mx_payload INTEGER,          /* Largest payload size of all cells */"  \
175777    "  pgoffset   INTEGER,          /* Offset of page in file */"             \
175778    "  pgsize     INTEGER,          /* Size of the page */"                   \
175779    "  schema     TEXT HIDDEN       /* Database schema being analyzed */"     \
175780    ");"
175781  
175782  
175783  typedef struct StatTable StatTable;
175784  typedef struct StatCursor StatCursor;
175785  typedef struct StatPage StatPage;
175786  typedef struct StatCell StatCell;
175787  
175788  struct StatCell {
175789    int nLocal;                     /* Bytes of local payload */
175790    u32 iChildPg;                   /* Child node (or 0 if this is a leaf) */
175791    int nOvfl;                      /* Entries in aOvfl[] */
175792    u32 *aOvfl;                     /* Array of overflow page numbers */
175793    int nLastOvfl;                  /* Bytes of payload on final overflow page */
175794    int iOvfl;                      /* Iterates through aOvfl[] */
175795  };
175796  
175797  struct StatPage {
175798    u32 iPgno;
175799    DbPage *pPg;
175800    int iCell;
175801  
175802    char *zPath;                    /* Path to this page */
175803  
175804    /* Variables populated by statDecodePage(): */
175805    u8 flags;                       /* Copy of flags byte */
175806    int nCell;                      /* Number of cells on page */
175807    int nUnused;                    /* Number of unused bytes on page */
175808    StatCell *aCell;                /* Array of parsed cells */
175809    u32 iRightChildPg;              /* Right-child page number (or 0) */
175810    int nMxPayload;                 /* Largest payload of any cell on this page */
175811  };
175812  
175813  struct StatCursor {
175814    sqlite3_vtab_cursor base;
175815    sqlite3_stmt *pStmt;            /* Iterates through set of root pages */
175816    int isEof;                      /* After pStmt has returned SQLITE_DONE */
175817    int iDb;                        /* Schema used for this query */
175818  
175819    StatPage aPage[32];
175820    int iPage;                      /* Current entry in aPage[] */
175821  
175822    /* Values to return. */
175823    char *zName;                    /* Value of 'name' column */
175824    char *zPath;                    /* Value of 'path' column */
175825    u32 iPageno;                    /* Value of 'pageno' column */
175826    char *zPagetype;                /* Value of 'pagetype' column */
175827    int nCell;                      /* Value of 'ncell' column */
175828    int nPayload;                   /* Value of 'payload' column */
175829    int nUnused;                    /* Value of 'unused' column */
175830    int nMxPayload;                 /* Value of 'mx_payload' column */
175831    i64 iOffset;                    /* Value of 'pgOffset' column */
175832    int szPage;                     /* Value of 'pgSize' column */
175833  };
175834  
175835  struct StatTable {
175836    sqlite3_vtab base;
175837    sqlite3 *db;
175838    int iDb;                        /* Index of database to analyze */
175839  };
175840  
175841  #ifndef get2byte
175842  # define get2byte(x)   ((x)[0]<<8 | (x)[1])
175843  #endif
175844  
175845  /*
175846  ** Connect to or create a statvfs virtual table.
175847  */
175848  static int statConnect(
175849    sqlite3 *db,
175850    void *pAux,
175851    int argc, const char *const*argv,
175852    sqlite3_vtab **ppVtab,
175853    char **pzErr
175854  ){
175855    StatTable *pTab = 0;
175856    int rc = SQLITE_OK;
175857    int iDb;
175858  
175859    if( argc>=4 ){
175860      Token nm;
175861      sqlite3TokenInit(&nm, (char*)argv[3]);
175862      iDb = sqlite3FindDb(db, &nm);
175863      if( iDb<0 ){
175864        *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
175865        return SQLITE_ERROR;
175866      }
175867    }else{
175868      iDb = 0;
175869    }
175870    rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
175871    if( rc==SQLITE_OK ){
175872      pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
175873      if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
175874    }
175875  
175876    assert( rc==SQLITE_OK || pTab==0 );
175877    if( rc==SQLITE_OK ){
175878      memset(pTab, 0, sizeof(StatTable));
175879      pTab->db = db;
175880      pTab->iDb = iDb;
175881    }
175882  
175883    *ppVtab = (sqlite3_vtab*)pTab;
175884    return rc;
175885  }
175886  
175887  /*
175888  ** Disconnect from or destroy a statvfs virtual table.
175889  */
175890  static int statDisconnect(sqlite3_vtab *pVtab){
175891    sqlite3_free(pVtab);
175892    return SQLITE_OK;
175893  }
175894  
175895  /*
175896  ** There is no "best-index". This virtual table always does a linear
175897  ** scan.  However, a schema=? constraint should cause this table to
175898  ** operate on a different database schema, so check for it.
175899  **
175900  ** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
175901  */
175902  static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
175903    int i;
175904  
175905    pIdxInfo->estimatedCost = 1.0e6;  /* Initial cost estimate */
175906  
175907    /* Look for a valid schema=? constraint.  If found, change the idxNum to
175908    ** 1 and request the value of that constraint be sent to xFilter.  And
175909    ** lower the cost estimate to encourage the constrained version to be
175910    ** used.
175911    */
175912    for(i=0; i<pIdxInfo->nConstraint; i++){
175913      if( pIdxInfo->aConstraint[i].usable==0 ) continue;
175914      if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
175915      if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
175916      pIdxInfo->idxNum = 1;
175917      pIdxInfo->estimatedCost = 1.0;
175918      pIdxInfo->aConstraintUsage[i].argvIndex = 1;
175919      pIdxInfo->aConstraintUsage[i].omit = 1;
175920      break;
175921    }
175922  
175923  
175924    /* Records are always returned in ascending order of (name, path). 
175925    ** If this will satisfy the client, set the orderByConsumed flag so that 
175926    ** SQLite does not do an external sort.
175927    */
175928    if( ( pIdxInfo->nOrderBy==1
175929       && pIdxInfo->aOrderBy[0].iColumn==0
175930       && pIdxInfo->aOrderBy[0].desc==0
175931       ) ||
175932        ( pIdxInfo->nOrderBy==2
175933       && pIdxInfo->aOrderBy[0].iColumn==0
175934       && pIdxInfo->aOrderBy[0].desc==0
175935       && pIdxInfo->aOrderBy[1].iColumn==1
175936       && pIdxInfo->aOrderBy[1].desc==0
175937       )
175938    ){
175939      pIdxInfo->orderByConsumed = 1;
175940    }
175941  
175942    return SQLITE_OK;
175943  }
175944  
175945  /*
175946  ** Open a new statvfs cursor.
175947  */
175948  static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
175949    StatTable *pTab = (StatTable *)pVTab;
175950    StatCursor *pCsr;
175951  
175952    pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
175953    if( pCsr==0 ){
175954      return SQLITE_NOMEM_BKPT;
175955    }else{
175956      memset(pCsr, 0, sizeof(StatCursor));
175957      pCsr->base.pVtab = pVTab;
175958      pCsr->iDb = pTab->iDb;
175959    }
175960  
175961    *ppCursor = (sqlite3_vtab_cursor *)pCsr;
175962    return SQLITE_OK;
175963  }
175964  
175965  static void statClearPage(StatPage *p){
175966    int i;
175967    if( p->aCell ){
175968      for(i=0; i<p->nCell; i++){
175969        sqlite3_free(p->aCell[i].aOvfl);
175970      }
175971      sqlite3_free(p->aCell);
175972    }
175973    sqlite3PagerUnref(p->pPg);
175974    sqlite3_free(p->zPath);
175975    memset(p, 0, sizeof(StatPage));
175976  }
175977  
175978  static void statResetCsr(StatCursor *pCsr){
175979    int i;
175980    sqlite3_reset(pCsr->pStmt);
175981    for(i=0; i<ArraySize(pCsr->aPage); i++){
175982      statClearPage(&pCsr->aPage[i]);
175983    }
175984    pCsr->iPage = 0;
175985    sqlite3_free(pCsr->zPath);
175986    pCsr->zPath = 0;
175987    pCsr->isEof = 0;
175988  }
175989  
175990  /*
175991  ** Close a statvfs cursor.
175992  */
175993  static int statClose(sqlite3_vtab_cursor *pCursor){
175994    StatCursor *pCsr = (StatCursor *)pCursor;
175995    statResetCsr(pCsr);
175996    sqlite3_finalize(pCsr->pStmt);
175997    sqlite3_free(pCsr);
175998    return SQLITE_OK;
175999  }
176000  
176001  static void getLocalPayload(
176002    int nUsable,                    /* Usable bytes per page */
176003    u8 flags,                       /* Page flags */
176004    int nTotal,                     /* Total record (payload) size */
176005    int *pnLocal                    /* OUT: Bytes stored locally */
176006  ){
176007    int nLocal;
176008    int nMinLocal;
176009    int nMaxLocal;
176010   
176011    if( flags==0x0D ){              /* Table leaf node */
176012      nMinLocal = (nUsable - 12) * 32 / 255 - 23;
176013      nMaxLocal = nUsable - 35;
176014    }else{                          /* Index interior and leaf nodes */
176015      nMinLocal = (nUsable - 12) * 32 / 255 - 23;
176016      nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
176017    }
176018  
176019    nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
176020    if( nLocal>nMaxLocal ) nLocal = nMinLocal;
176021    *pnLocal = nLocal;
176022  }
176023  
176024  static int statDecodePage(Btree *pBt, StatPage *p){
176025    int nUnused;
176026    int iOff;
176027    int nHdr;
176028    int isLeaf;
176029    int szPage;
176030  
176031    u8 *aData = sqlite3PagerGetData(p->pPg);
176032    u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
176033  
176034    p->flags = aHdr[0];
176035    p->nCell = get2byte(&aHdr[3]);
176036    p->nMxPayload = 0;
176037  
176038    isLeaf = (p->flags==0x0A || p->flags==0x0D);
176039    nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
176040  
176041    nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
176042    nUnused += (int)aHdr[7];
176043    iOff = get2byte(&aHdr[1]);
176044    while( iOff ){
176045      nUnused += get2byte(&aData[iOff+2]);
176046      iOff = get2byte(&aData[iOff]);
176047    }
176048    p->nUnused = nUnused;
176049    p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
176050    szPage = sqlite3BtreeGetPageSize(pBt);
176051  
176052    if( p->nCell ){
176053      int i;                        /* Used to iterate through cells */
176054      int nUsable;                  /* Usable bytes per page */
176055  
176056      sqlite3BtreeEnter(pBt);
176057      nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
176058      sqlite3BtreeLeave(pBt);
176059      p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
176060      if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
176061      memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
176062  
176063      for(i=0; i<p->nCell; i++){
176064        StatCell *pCell = &p->aCell[i];
176065  
176066        iOff = get2byte(&aData[nHdr+i*2]);
176067        if( !isLeaf ){
176068          pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
176069          iOff += 4;
176070        }
176071        if( p->flags==0x05 ){
176072          /* A table interior node. nPayload==0. */
176073        }else{
176074          u32 nPayload;             /* Bytes of payload total (local+overflow) */
176075          int nLocal;               /* Bytes of payload stored locally */
176076          iOff += getVarint32(&aData[iOff], nPayload);
176077          if( p->flags==0x0D ){
176078            u64 dummy;
176079            iOff += sqlite3GetVarint(&aData[iOff], &dummy);
176080          }
176081          if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
176082          getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
176083          pCell->nLocal = nLocal;
176084          assert( nLocal>=0 );
176085          assert( nPayload>=(u32)nLocal );
176086          assert( nLocal<=(nUsable-35) );
176087          if( nPayload>(u32)nLocal ){
176088            int j;
176089            int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
176090            pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
176091            pCell->nOvfl = nOvfl;
176092            pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
176093            if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
176094            pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
176095            for(j=1; j<nOvfl; j++){
176096              int rc;
176097              u32 iPrev = pCell->aOvfl[j-1];
176098              DbPage *pPg = 0;
176099              rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
176100              if( rc!=SQLITE_OK ){
176101                assert( pPg==0 );
176102                return rc;
176103              } 
176104              pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
176105              sqlite3PagerUnref(pPg);
176106            }
176107          }
176108        }
176109      }
176110    }
176111  
176112    return SQLITE_OK;
176113  }
176114  
176115  /*
176116  ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
176117  ** the current value of pCsr->iPageno.
176118  */
176119  static void statSizeAndOffset(StatCursor *pCsr){
176120    StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
176121    Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
176122    Pager *pPager = sqlite3BtreePager(pBt);
176123    sqlite3_file *fd;
176124    sqlite3_int64 x[2];
176125  
176126    /* The default page size and offset */
176127    pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
176128    pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
176129  
176130    /* If connected to a ZIPVFS backend, override the page size and
176131    ** offset with actual values obtained from ZIPVFS.
176132    */
176133    fd = sqlite3PagerFile(pPager);
176134    x[0] = pCsr->iPageno;
176135    if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
176136      pCsr->iOffset = x[0];
176137      pCsr->szPage = (int)x[1];
176138    }
176139  }
176140  
176141  /*
176142  ** Move a statvfs cursor to the next entry in the file.
176143  */
176144  static int statNext(sqlite3_vtab_cursor *pCursor){
176145    int rc;
176146    int nPayload;
176147    char *z;
176148    StatCursor *pCsr = (StatCursor *)pCursor;
176149    StatTable *pTab = (StatTable *)pCursor->pVtab;
176150    Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
176151    Pager *pPager = sqlite3BtreePager(pBt);
176152  
176153    sqlite3_free(pCsr->zPath);
176154    pCsr->zPath = 0;
176155  
176156  statNextRestart:
176157    if( pCsr->aPage[0].pPg==0 ){
176158      rc = sqlite3_step(pCsr->pStmt);
176159      if( rc==SQLITE_ROW ){
176160        int nPage;
176161        u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
176162        sqlite3PagerPagecount(pPager, &nPage);
176163        if( nPage==0 ){
176164          pCsr->isEof = 1;
176165          return sqlite3_reset(pCsr->pStmt);
176166        }
176167        rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
176168        pCsr->aPage[0].iPgno = iRoot;
176169        pCsr->aPage[0].iCell = 0;
176170        pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
176171        pCsr->iPage = 0;
176172        if( z==0 ) rc = SQLITE_NOMEM_BKPT;
176173      }else{
176174        pCsr->isEof = 1;
176175        return sqlite3_reset(pCsr->pStmt);
176176      }
176177    }else{
176178  
176179      /* Page p itself has already been visited. */
176180      StatPage *p = &pCsr->aPage[pCsr->iPage];
176181  
176182      while( p->iCell<p->nCell ){
176183        StatCell *pCell = &p->aCell[p->iCell];
176184        if( pCell->iOvfl<pCell->nOvfl ){
176185          int nUsable;
176186          sqlite3BtreeEnter(pBt);
176187          nUsable = sqlite3BtreeGetPageSize(pBt) - 
176188                          sqlite3BtreeGetReserveNoMutex(pBt);
176189          sqlite3BtreeLeave(pBt);
176190          pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
176191          pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
176192          pCsr->zPagetype = "overflow";
176193          pCsr->nCell = 0;
176194          pCsr->nMxPayload = 0;
176195          pCsr->zPath = z = sqlite3_mprintf(
176196              "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
176197          );
176198          if( pCell->iOvfl<pCell->nOvfl-1 ){
176199            pCsr->nUnused = 0;
176200            pCsr->nPayload = nUsable - 4;
176201          }else{
176202            pCsr->nPayload = pCell->nLastOvfl;
176203            pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
176204          }
176205          pCell->iOvfl++;
176206          statSizeAndOffset(pCsr);
176207          return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
176208        }
176209        if( p->iRightChildPg ) break;
176210        p->iCell++;
176211      }
176212  
176213      if( !p->iRightChildPg || p->iCell>p->nCell ){
176214        statClearPage(p);
176215        if( pCsr->iPage==0 ) return statNext(pCursor);
176216        pCsr->iPage--;
176217        goto statNextRestart; /* Tail recursion */
176218      }
176219      pCsr->iPage++;
176220      assert( p==&pCsr->aPage[pCsr->iPage-1] );
176221  
176222      if( p->iCell==p->nCell ){
176223        p[1].iPgno = p->iRightChildPg;
176224      }else{
176225        p[1].iPgno = p->aCell[p->iCell].iChildPg;
176226      }
176227      rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
176228      p[1].iCell = 0;
176229      p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
176230      p->iCell++;
176231      if( z==0 ) rc = SQLITE_NOMEM_BKPT;
176232    }
176233  
176234  
176235    /* Populate the StatCursor fields with the values to be returned
176236    ** by the xColumn() and xRowid() methods.
176237    */
176238    if( rc==SQLITE_OK ){
176239      int i;
176240      StatPage *p = &pCsr->aPage[pCsr->iPage];
176241      pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
176242      pCsr->iPageno = p->iPgno;
176243  
176244      rc = statDecodePage(pBt, p);
176245      if( rc==SQLITE_OK ){
176246        statSizeAndOffset(pCsr);
176247  
176248        switch( p->flags ){
176249          case 0x05:             /* table internal */
176250          case 0x02:             /* index internal */
176251            pCsr->zPagetype = "internal";
176252            break;
176253          case 0x0D:             /* table leaf */
176254          case 0x0A:             /* index leaf */
176255            pCsr->zPagetype = "leaf";
176256            break;
176257          default:
176258            pCsr->zPagetype = "corrupted";
176259            break;
176260        }
176261        pCsr->nCell = p->nCell;
176262        pCsr->nUnused = p->nUnused;
176263        pCsr->nMxPayload = p->nMxPayload;
176264        pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
176265        if( z==0 ) rc = SQLITE_NOMEM_BKPT;
176266        nPayload = 0;
176267        for(i=0; i<p->nCell; i++){
176268          nPayload += p->aCell[i].nLocal;
176269        }
176270        pCsr->nPayload = nPayload;
176271      }
176272    }
176273  
176274    return rc;
176275  }
176276  
176277  static int statEof(sqlite3_vtab_cursor *pCursor){
176278    StatCursor *pCsr = (StatCursor *)pCursor;
176279    return pCsr->isEof;
176280  }
176281  
176282  static int statFilter(
176283    sqlite3_vtab_cursor *pCursor, 
176284    int idxNum, const char *idxStr,
176285    int argc, sqlite3_value **argv
176286  ){
176287    StatCursor *pCsr = (StatCursor *)pCursor;
176288    StatTable *pTab = (StatTable*)(pCursor->pVtab);
176289    char *zSql;
176290    int rc = SQLITE_OK;
176291    char *zMaster;
176292  
176293    if( idxNum==1 ){
176294      const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
176295      pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
176296      if( pCsr->iDb<0 ){
176297        sqlite3_free(pCursor->pVtab->zErrMsg);
176298        pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
176299        return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
176300      }
176301    }else{
176302      pCsr->iDb = pTab->iDb;
176303    }
176304    statResetCsr(pCsr);
176305    sqlite3_finalize(pCsr->pStmt);
176306    pCsr->pStmt = 0;
176307    zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
176308    zSql = sqlite3_mprintf(
176309        "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
176310        "  UNION ALL  "
176311        "SELECT name, rootpage, type"
176312        "  FROM \"%w\".%s WHERE rootpage!=0"
176313        "  ORDER BY name", pTab->db->aDb[pCsr->iDb].zDbSName, zMaster);
176314    if( zSql==0 ){
176315      return SQLITE_NOMEM_BKPT;
176316    }else{
176317      rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
176318      sqlite3_free(zSql);
176319    }
176320  
176321    if( rc==SQLITE_OK ){
176322      rc = statNext(pCursor);
176323    }
176324    return rc;
176325  }
176326  
176327  static int statColumn(
176328    sqlite3_vtab_cursor *pCursor, 
176329    sqlite3_context *ctx, 
176330    int i
176331  ){
176332    StatCursor *pCsr = (StatCursor *)pCursor;
176333    switch( i ){
176334      case 0:            /* name */
176335        sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
176336        break;
176337      case 1:            /* path */
176338        sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
176339        break;
176340      case 2:            /* pageno */
176341        sqlite3_result_int64(ctx, pCsr->iPageno);
176342        break;
176343      case 3:            /* pagetype */
176344        sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
176345        break;
176346      case 4:            /* ncell */
176347        sqlite3_result_int(ctx, pCsr->nCell);
176348        break;
176349      case 5:            /* payload */
176350        sqlite3_result_int(ctx, pCsr->nPayload);
176351        break;
176352      case 6:            /* unused */
176353        sqlite3_result_int(ctx, pCsr->nUnused);
176354        break;
176355      case 7:            /* mx_payload */
176356        sqlite3_result_int(ctx, pCsr->nMxPayload);
176357        break;
176358      case 8:            /* pgoffset */
176359        sqlite3_result_int64(ctx, pCsr->iOffset);
176360        break;
176361      case 9:            /* pgsize */
176362        sqlite3_result_int(ctx, pCsr->szPage);
176363        break;
176364      default: {          /* schema */
176365        sqlite3 *db = sqlite3_context_db_handle(ctx);
176366        int iDb = pCsr->iDb;
176367        sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
176368        break;
176369      }
176370    }
176371    return SQLITE_OK;
176372  }
176373  
176374  static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
176375    StatCursor *pCsr = (StatCursor *)pCursor;
176376    *pRowid = pCsr->iPageno;
176377    return SQLITE_OK;
176378  }
176379  
176380  /*
176381  ** Invoke this routine to register the "dbstat" virtual table module
176382  */
176383  SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
176384    static sqlite3_module dbstat_module = {
176385      0,                            /* iVersion */
176386      statConnect,                  /* xCreate */
176387      statConnect,                  /* xConnect */
176388      statBestIndex,                /* xBestIndex */
176389      statDisconnect,               /* xDisconnect */
176390      statDisconnect,               /* xDestroy */
176391      statOpen,                     /* xOpen - open a cursor */
176392      statClose,                    /* xClose - close a cursor */
176393      statFilter,                   /* xFilter - configure scan constraints */
176394      statNext,                     /* xNext - advance a cursor */
176395      statEof,                      /* xEof - check for end of scan */
176396      statColumn,                   /* xColumn - read data */
176397      statRowid,                    /* xRowid - read data */
176398      0,                            /* xUpdate */
176399      0,                            /* xBegin */
176400      0,                            /* xSync */
176401      0,                            /* xCommit */
176402      0,                            /* xRollback */
176403      0,                            /* xFindMethod */
176404      0,                            /* xRename */
176405      0,                            /* xSavepoint */
176406      0,                            /* xRelease */
176407      0,                            /* xRollbackTo */
176408    };
176409    return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
176410  }
176411  #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
176412  SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
176413  #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
176414  
176415  /************** End of dbstat.c **********************************************/
176416  /************** Begin file dbpage.c ******************************************/
176417  /*
176418  ** 2017-10-11
176419  **
176420  ** The author disclaims copyright to this source code.  In place of
176421  ** a legal notice, here is a blessing:
176422  **
176423  **    May you do good and not evil.
176424  **    May you find forgiveness for yourself and forgive others.
176425  **    May you share freely, never taking more than you give.
176426  **
176427  ******************************************************************************
176428  **
176429  ** This file contains an implementation of the "sqlite_dbpage" virtual table.
176430  **
176431  ** The sqlite_dbpage virtual table is used to read or write whole raw
176432  ** pages of the database file.  The pager interface is used so that 
176433  ** uncommitted changes and changes recorded in the WAL file are correctly
176434  ** retrieved.
176435  **
176436  ** Usage example:
176437  **
176438  **    SELECT data FROM sqlite_dbpage('aux1') WHERE pgno=123;
176439  **
176440  ** This is an eponymous virtual table so it does not need to be created before
176441  ** use.  The optional argument to the sqlite_dbpage() table name is the
176442  ** schema for the database file that is to be read.  The default schema is
176443  ** "main".
176444  **
176445  ** The data field of sqlite_dbpage table can be updated.  The new
176446  ** value must be a BLOB which is the correct page size, otherwise the
176447  ** update fails.  Rows may not be deleted or inserted.
176448  */
176449  
176450  /* #include "sqliteInt.h"   ** Requires access to internal data structures ** */
176451  #if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \
176452      && !defined(SQLITE_OMIT_VIRTUALTABLE)
176453  
176454  typedef struct DbpageTable DbpageTable;
176455  typedef struct DbpageCursor DbpageCursor;
176456  
176457  struct DbpageCursor {
176458    sqlite3_vtab_cursor base;       /* Base class.  Must be first */
176459    int pgno;                       /* Current page number */
176460    int mxPgno;                     /* Last page to visit on this scan */
176461  };
176462  
176463  struct DbpageTable {
176464    sqlite3_vtab base;              /* Base class.  Must be first */
176465    sqlite3 *db;                    /* The database */
176466    Pager *pPager;                  /* Pager being read/written */
176467    int iDb;                        /* Index of database to analyze */
176468    int szPage;                     /* Size of each page in bytes */
176469    int nPage;                      /* Number of pages in the file */
176470  };
176471  
176472  /*
176473  ** Connect to or create a dbpagevfs virtual table.
176474  */
176475  static int dbpageConnect(
176476    sqlite3 *db,
176477    void *pAux,
176478    int argc, const char *const*argv,
176479    sqlite3_vtab **ppVtab,
176480    char **pzErr
176481  ){
176482    DbpageTable *pTab = 0;
176483    int rc = SQLITE_OK;
176484    int iDb;
176485  
176486    if( argc>=4 ){
176487      Token nm;
176488      sqlite3TokenInit(&nm, (char*)argv[3]);
176489      iDb = sqlite3FindDb(db, &nm);
176490      if( iDb<0 ){
176491        *pzErr = sqlite3_mprintf("no such schema: %s", argv[3]);
176492        return SQLITE_ERROR;
176493      }
176494    }else{
176495      iDb = 0;
176496    }
176497    rc = sqlite3_declare_vtab(db, 
176498            "CREATE TABLE x(pgno INTEGER PRIMARY KEY, data BLOB, schema HIDDEN)");
176499    if( rc==SQLITE_OK ){
176500      pTab = (DbpageTable *)sqlite3_malloc64(sizeof(DbpageTable));
176501      if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
176502    }
176503  
176504    assert( rc==SQLITE_OK || pTab==0 );
176505    if( rc==SQLITE_OK ){
176506      Btree *pBt = db->aDb[iDb].pBt;
176507      memset(pTab, 0, sizeof(DbpageTable));
176508      pTab->db = db;
176509      pTab->iDb = iDb;
176510      pTab->pPager = pBt ? sqlite3BtreePager(pBt) : 0;
176511    }
176512  
176513    *ppVtab = (sqlite3_vtab*)pTab;
176514    return rc;
176515  }
176516  
176517  /*
176518  ** Disconnect from or destroy a dbpagevfs virtual table.
176519  */
176520  static int dbpageDisconnect(sqlite3_vtab *pVtab){
176521    sqlite3_free(pVtab);
176522    return SQLITE_OK;
176523  }
176524  
176525  /*
176526  ** idxNum:
176527  **
176528  **     0     full table scan
176529  **     1     pgno=?1
176530  */
176531  static int dbpageBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
176532    int i;
176533    pIdxInfo->estimatedCost = 1.0e6;  /* Initial cost estimate */
176534    for(i=0; i<pIdxInfo->nConstraint; i++){
176535      struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
176536      if( p->usable && p->iColumn<=0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
176537        pIdxInfo->estimatedRows = 1;
176538        pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
176539        pIdxInfo->estimatedCost = 1.0;
176540        pIdxInfo->idxNum = 1;
176541        pIdxInfo->aConstraintUsage[i].argvIndex = 1;
176542        pIdxInfo->aConstraintUsage[i].omit = 1;
176543        break;
176544      }
176545    }
176546    if( pIdxInfo->nOrderBy>=1
176547     && pIdxInfo->aOrderBy[0].iColumn<=0
176548     && pIdxInfo->aOrderBy[0].desc==0
176549    ){
176550      pIdxInfo->orderByConsumed = 1;
176551    }
176552    return SQLITE_OK;
176553  }
176554  
176555  /*
176556  ** Open a new dbpagevfs cursor.
176557  */
176558  static int dbpageOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
176559    DbpageCursor *pCsr;
176560  
176561    pCsr = (DbpageCursor *)sqlite3_malloc64(sizeof(DbpageCursor));
176562    if( pCsr==0 ){
176563      return SQLITE_NOMEM_BKPT;
176564    }else{
176565      memset(pCsr, 0, sizeof(DbpageCursor));
176566      pCsr->base.pVtab = pVTab;
176567      pCsr->pgno = -1;
176568    }
176569  
176570    *ppCursor = (sqlite3_vtab_cursor *)pCsr;
176571    return SQLITE_OK;
176572  }
176573  
176574  /*
176575  ** Close a dbpagevfs cursor.
176576  */
176577  static int dbpageClose(sqlite3_vtab_cursor *pCursor){
176578    DbpageCursor *pCsr = (DbpageCursor *)pCursor;
176579    sqlite3_free(pCsr);
176580    return SQLITE_OK;
176581  }
176582  
176583  /*
176584  ** Move a dbpagevfs cursor to the next entry in the file.
176585  */
176586  static int dbpageNext(sqlite3_vtab_cursor *pCursor){
176587    int rc = SQLITE_OK;
176588    DbpageCursor *pCsr = (DbpageCursor *)pCursor;
176589    pCsr->pgno++;
176590    return rc;
176591  }
176592  
176593  static int dbpageEof(sqlite3_vtab_cursor *pCursor){
176594    DbpageCursor *pCsr = (DbpageCursor *)pCursor;
176595    return pCsr->pgno > pCsr->mxPgno;
176596  }
176597  
176598  static int dbpageFilter(
176599    sqlite3_vtab_cursor *pCursor, 
176600    int idxNum, const char *idxStr,
176601    int argc, sqlite3_value **argv
176602  ){
176603    DbpageCursor *pCsr = (DbpageCursor *)pCursor;
176604    DbpageTable *pTab = (DbpageTable *)pCursor->pVtab;
176605    int rc = SQLITE_OK;
176606    Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
176607  
176608    pTab->szPage = sqlite3BtreeGetPageSize(pBt);
176609    pTab->nPage = sqlite3BtreeLastPage(pBt);
176610    if( idxNum==1 ){
176611      pCsr->pgno = sqlite3_value_int(argv[0]);
176612      if( pCsr->pgno<1 || pCsr->pgno>pTab->nPage ){
176613        pCsr->pgno = 1;
176614        pCsr->mxPgno = 0;
176615      }else{
176616        pCsr->mxPgno = pCsr->pgno;
176617      }
176618    }else{
176619      pCsr->pgno = 1;
176620      pCsr->mxPgno = pTab->nPage;
176621    }
176622    return rc;
176623  }
176624  
176625  static int dbpageColumn(
176626    sqlite3_vtab_cursor *pCursor, 
176627    sqlite3_context *ctx, 
176628    int i
176629  ){
176630    DbpageCursor *pCsr = (DbpageCursor *)pCursor;
176631    DbpageTable *pTab = (DbpageTable *)pCursor->pVtab;
176632    int rc = SQLITE_OK;
176633    switch( i ){
176634      case 0: {           /* pgno */
176635        sqlite3_result_int(ctx, pCsr->pgno);
176636        break;
176637      }
176638      case 1: {           /* data */
176639        DbPage *pDbPage = 0;
176640        rc = sqlite3PagerGet(pTab->pPager, pCsr->pgno, (DbPage**)&pDbPage, 0);
176641        if( rc==SQLITE_OK ){
176642          sqlite3_result_blob(ctx, sqlite3PagerGetData(pDbPage), pTab->szPage,
176643                              SQLITE_TRANSIENT);
176644        }
176645        sqlite3PagerUnref(pDbPage);
176646        break;
176647      }
176648      default: {          /* schema */
176649        sqlite3 *db = sqlite3_context_db_handle(ctx);
176650        sqlite3_result_text(ctx, db->aDb[pTab->iDb].zDbSName, -1, SQLITE_STATIC);
176651        break;
176652      }
176653    }
176654    return SQLITE_OK;
176655  }
176656  
176657  static int dbpageRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
176658    DbpageCursor *pCsr = (DbpageCursor *)pCursor;
176659    *pRowid = pCsr->pgno;
176660    return SQLITE_OK;
176661  }
176662  
176663  static int dbpageUpdate(
176664    sqlite3_vtab *pVtab,
176665    int argc,
176666    sqlite3_value **argv,
176667    sqlite_int64 *pRowid
176668  ){
176669    DbpageTable *pTab = (DbpageTable *)pVtab;
176670    int pgno;
176671    DbPage *pDbPage = 0;
176672    int rc = SQLITE_OK;
176673    char *zErr = 0;
176674  
176675    if( argc==1 ){
176676      zErr = "cannot delete";
176677      goto update_fail;
176678    }
176679    pgno = sqlite3_value_int(argv[0]);
176680    if( pgno<1 || pgno>pTab->nPage ){
176681      zErr = "bad page number";
176682      goto update_fail;
176683    }
176684    if( sqlite3_value_int(argv[1])!=pgno ){
176685      zErr = "cannot insert";
176686      goto update_fail;
176687    }
176688    if( sqlite3_value_type(argv[3])!=SQLITE_BLOB 
176689     || sqlite3_value_bytes(argv[3])!=pTab->szPage 
176690    ){
176691      zErr = "bad page value";
176692      goto update_fail;
176693    }
176694    rc = sqlite3PagerGet(pTab->pPager, pgno, (DbPage**)&pDbPage, 0);
176695    if( rc==SQLITE_OK ){
176696      rc = sqlite3PagerWrite(pDbPage);
176697      if( rc==SQLITE_OK ){
176698        memcpy(sqlite3PagerGetData(pDbPage),
176699               sqlite3_value_blob(argv[3]),
176700               pTab->szPage);
176701      }
176702    }
176703    sqlite3PagerUnref(pDbPage);
176704    return rc;
176705  
176706  update_fail:
176707    sqlite3_free(pVtab->zErrMsg);
176708    pVtab->zErrMsg = sqlite3_mprintf("%s", zErr);
176709    return SQLITE_ERROR;
176710  }
176711  
176712  /*
176713  ** Invoke this routine to register the "dbpage" virtual table module
176714  */
176715  SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){
176716    static sqlite3_module dbpage_module = {
176717      0,                            /* iVersion */
176718      dbpageConnect,                /* xCreate */
176719      dbpageConnect,                /* xConnect */
176720      dbpageBestIndex,              /* xBestIndex */
176721      dbpageDisconnect,             /* xDisconnect */
176722      dbpageDisconnect,             /* xDestroy */
176723      dbpageOpen,                   /* xOpen - open a cursor */
176724      dbpageClose,                  /* xClose - close a cursor */
176725      dbpageFilter,                 /* xFilter - configure scan constraints */
176726      dbpageNext,                   /* xNext - advance a cursor */
176727      dbpageEof,                    /* xEof - check for end of scan */
176728      dbpageColumn,                 /* xColumn - read data */
176729      dbpageRowid,                  /* xRowid - read data */
176730      dbpageUpdate,                 /* xUpdate */
176731      0,                            /* xBegin */
176732      0,                            /* xSync */
176733      0,                            /* xCommit */
176734      0,                            /* xRollback */
176735      0,                            /* xFindMethod */
176736      0,                            /* xRename */
176737      0,                            /* xSavepoint */
176738      0,                            /* xRelease */
176739      0,                            /* xRollbackTo */
176740    };
176741    return sqlite3_create_module(db, "sqlite_dbpage", &dbpage_module, 0);
176742  }
176743  #elif defined(SQLITE_ENABLE_DBPAGE_VTAB)
176744  SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){ return SQLITE_OK; }
176745  #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
176746  
176747  /************** End of dbpage.c **********************************************/
176748  /************** Begin file sqlite3session.c **********************************/
176749  
176750  #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
176751  /* #include "sqlite3session.h" */
176752  /* #include <assert.h> */
176753  /* #include <string.h> */
176754  
176755  #ifndef SQLITE_AMALGAMATION
176756  /* # include "sqliteInt.h" */
176757  /* # include "vdbeInt.h" */
176758  #endif
176759  
176760  typedef struct SessionTable SessionTable;
176761  typedef struct SessionChange SessionChange;
176762  typedef struct SessionBuffer SessionBuffer;
176763  typedef struct SessionInput SessionInput;
176764  
176765  /*
176766  ** Minimum chunk size used by streaming versions of functions.
176767  */
176768  #ifndef SESSIONS_STRM_CHUNK_SIZE
176769  # ifdef SQLITE_TEST
176770  #   define SESSIONS_STRM_CHUNK_SIZE 64
176771  # else
176772  #   define SESSIONS_STRM_CHUNK_SIZE 1024
176773  # endif
176774  #endif
176775  
176776  typedef struct SessionHook SessionHook;
176777  struct SessionHook {
176778    void *pCtx;
176779    int (*xOld)(void*,int,sqlite3_value**);
176780    int (*xNew)(void*,int,sqlite3_value**);
176781    int (*xCount)(void*);
176782    int (*xDepth)(void*);
176783  };
176784  
176785  /*
176786  ** Session handle structure.
176787  */
176788  struct sqlite3_session {
176789    sqlite3 *db;                    /* Database handle session is attached to */
176790    char *zDb;                      /* Name of database session is attached to */
176791    int bEnable;                    /* True if currently recording */
176792    int bIndirect;                  /* True if all changes are indirect */
176793    int bAutoAttach;                /* True to auto-attach tables */
176794    int rc;                         /* Non-zero if an error has occurred */
176795    void *pFilterCtx;               /* First argument to pass to xTableFilter */
176796    int (*xTableFilter)(void *pCtx, const char *zTab);
176797    sqlite3_session *pNext;         /* Next session object on same db. */
176798    SessionTable *pTable;           /* List of attached tables */
176799    SessionHook hook;               /* APIs to grab new and old data with */
176800  };
176801  
176802  /*
176803  ** Instances of this structure are used to build strings or binary records.
176804  */
176805  struct SessionBuffer {
176806    u8 *aBuf;                       /* Pointer to changeset buffer */
176807    int nBuf;                       /* Size of buffer aBuf */
176808    int nAlloc;                     /* Size of allocation containing aBuf */
176809  };
176810  
176811  /*
176812  ** An object of this type is used internally as an abstraction for 
176813  ** input data. Input data may be supplied either as a single large buffer
176814  ** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
176815  **  sqlite3changeset_start_strm()).
176816  */
176817  struct SessionInput {
176818    int bNoDiscard;                 /* If true, discard no data */
176819    int iCurrent;                   /* Offset in aData[] of current change */
176820    int iNext;                      /* Offset in aData[] of next change */
176821    u8 *aData;                      /* Pointer to buffer containing changeset */
176822    int nData;                      /* Number of bytes in aData */
176823  
176824    SessionBuffer buf;              /* Current read buffer */
176825    int (*xInput)(void*, void*, int*);        /* Input stream call (or NULL) */
176826    void *pIn;                                /* First argument to xInput */
176827    int bEof;                       /* Set to true after xInput finished */
176828  };
176829  
176830  /*
176831  ** Structure for changeset iterators.
176832  */
176833  struct sqlite3_changeset_iter {
176834    SessionInput in;                /* Input buffer or stream */
176835    SessionBuffer tblhdr;           /* Buffer to hold apValue/zTab/abPK/ */
176836    int bPatchset;                  /* True if this is a patchset */
176837    int rc;                         /* Iterator error code */
176838    sqlite3_stmt *pConflict;        /* Points to conflicting row, if any */
176839    char *zTab;                     /* Current table */
176840    int nCol;                       /* Number of columns in zTab */
176841    int op;                         /* Current operation */
176842    int bIndirect;                  /* True if current change was indirect */
176843    u8 *abPK;                       /* Primary key array */
176844    sqlite3_value **apValue;        /* old.* and new.* values */
176845  };
176846  
176847  /*
176848  ** Each session object maintains a set of the following structures, one
176849  ** for each table the session object is monitoring. The structures are
176850  ** stored in a linked list starting at sqlite3_session.pTable.
176851  **
176852  ** The keys of the SessionTable.aChange[] hash table are all rows that have
176853  ** been modified in any way since the session object was attached to the
176854  ** table.
176855  **
176856  ** The data associated with each hash-table entry is a structure containing
176857  ** a subset of the initial values that the modified row contained at the
176858  ** start of the session. Or no initial values if the row was inserted.
176859  */
176860  struct SessionTable {
176861    SessionTable *pNext;
176862    char *zName;                    /* Local name of table */
176863    int nCol;                       /* Number of columns in table zName */
176864    const char **azCol;             /* Column names */
176865    u8 *abPK;                       /* Array of primary key flags */
176866    int nEntry;                     /* Total number of entries in hash table */
176867    int nChange;                    /* Size of apChange[] array */
176868    SessionChange **apChange;       /* Hash table buckets */
176869  };
176870  
176871  /* 
176872  ** RECORD FORMAT:
176873  **
176874  ** The following record format is similar to (but not compatible with) that 
176875  ** used in SQLite database files. This format is used as part of the 
176876  ** change-set binary format, and so must be architecture independent.
176877  **
176878  ** Unlike the SQLite database record format, each field is self-contained -
176879  ** there is no separation of header and data. Each field begins with a
176880  ** single byte describing its type, as follows:
176881  **
176882  **       0x00: Undefined value.
176883  **       0x01: Integer value.
176884  **       0x02: Real value.
176885  **       0x03: Text value.
176886  **       0x04: Blob value.
176887  **       0x05: SQL NULL value.
176888  **
176889  ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
176890  ** and so on in sqlite3.h. For undefined and NULL values, the field consists
176891  ** only of the single type byte. For other types of values, the type byte
176892  ** is followed by:
176893  **
176894  **   Text values:
176895  **     A varint containing the number of bytes in the value (encoded using
176896  **     UTF-8). Followed by a buffer containing the UTF-8 representation
176897  **     of the text value. There is no nul terminator.
176898  **
176899  **   Blob values:
176900  **     A varint containing the number of bytes in the value, followed by
176901  **     a buffer containing the value itself.
176902  **
176903  **   Integer values:
176904  **     An 8-byte big-endian integer value.
176905  **
176906  **   Real values:
176907  **     An 8-byte big-endian IEEE 754-2008 real value.
176908  **
176909  ** Varint values are encoded in the same way as varints in the SQLite 
176910  ** record format.
176911  **
176912  ** CHANGESET FORMAT:
176913  **
176914  ** A changeset is a collection of DELETE, UPDATE and INSERT operations on
176915  ** one or more tables. Operations on a single table are grouped together,
176916  ** but may occur in any order (i.e. deletes, updates and inserts are all
176917  ** mixed together).
176918  **
176919  ** Each group of changes begins with a table header:
176920  **
176921  **   1 byte: Constant 0x54 (capital 'T')
176922  **   Varint: Number of columns in the table.
176923  **   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
176924  **   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
176925  **
176926  ** Followed by one or more changes to the table.
176927  **
176928  **   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
176929  **   1 byte: The "indirect-change" flag.
176930  **   old.* record: (delete and update only)
176931  **   new.* record: (insert and update only)
176932  **
176933  ** The "old.*" and "new.*" records, if present, are N field records in the
176934  ** format described above under "RECORD FORMAT", where N is the number of
176935  ** columns in the table. The i'th field of each record is associated with
176936  ** the i'th column of the table, counting from left to right in the order
176937  ** in which columns were declared in the CREATE TABLE statement.
176938  **
176939  ** The new.* record that is part of each INSERT change contains the values
176940  ** that make up the new row. Similarly, the old.* record that is part of each
176941  ** DELETE change contains the values that made up the row that was deleted 
176942  ** from the database. In the changeset format, the records that are part
176943  ** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
176944  ** fields.
176945  **
176946  ** Within the old.* record associated with an UPDATE change, all fields
176947  ** associated with table columns that are not PRIMARY KEY columns and are
176948  ** not modified by the UPDATE change are set to "undefined". Other fields
176949  ** are set to the values that made up the row before the UPDATE that the
176950  ** change records took place. Within the new.* record, fields associated 
176951  ** with table columns modified by the UPDATE change contain the new 
176952  ** values. Fields associated with table columns that are not modified
176953  ** are set to "undefined".
176954  **
176955  ** PATCHSET FORMAT:
176956  **
176957  ** A patchset is also a collection of changes. It is similar to a changeset,
176958  ** but leaves undefined those fields that are not useful if no conflict
176959  ** resolution is required when applying the changeset.
176960  **
176961  ** Each group of changes begins with a table header:
176962  **
176963  **   1 byte: Constant 0x50 (capital 'P')
176964  **   Varint: Number of columns in the table.
176965  **   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
176966  **   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
176967  **
176968  ** Followed by one or more changes to the table.
176969  **
176970  **   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
176971  **   1 byte: The "indirect-change" flag.
176972  **   single record: (PK fields for DELETE, PK and modified fields for UPDATE,
176973  **                   full record for INSERT).
176974  **
176975  ** As in the changeset format, each field of the single record that is part
176976  ** of a patchset change is associated with the correspondingly positioned
176977  ** table column, counting from left to right within the CREATE TABLE 
176978  ** statement.
176979  **
176980  ** For a DELETE change, all fields within the record except those associated
176981  ** with PRIMARY KEY columns are set to "undefined". The PRIMARY KEY fields
176982  ** contain the values identifying the row to delete.
176983  **
176984  ** For an UPDATE change, all fields except those associated with PRIMARY KEY
176985  ** columns and columns that are modified by the UPDATE are set to "undefined".
176986  ** PRIMARY KEY fields contain the values identifying the table row to update,
176987  ** and fields associated with modified columns contain the new column values.
176988  **
176989  ** The records associated with INSERT changes are in the same format as for
176990  ** changesets. It is not possible for a record associated with an INSERT
176991  ** change to contain a field set to "undefined".
176992  */
176993  
176994  /*
176995  ** For each row modified during a session, there exists a single instance of
176996  ** this structure stored in a SessionTable.aChange[] hash table.
176997  */
176998  struct SessionChange {
176999    int op;                         /* One of UPDATE, DELETE, INSERT */
177000    int bIndirect;                  /* True if this change is "indirect" */
177001    int nRecord;                    /* Number of bytes in buffer aRecord[] */
177002    u8 *aRecord;                    /* Buffer containing old.* record */
177003    SessionChange *pNext;           /* For hash-table collisions */
177004  };
177005  
177006  /*
177007  ** Write a varint with value iVal into the buffer at aBuf. Return the 
177008  ** number of bytes written.
177009  */
177010  static int sessionVarintPut(u8 *aBuf, int iVal){
177011    return putVarint32(aBuf, iVal);
177012  }
177013  
177014  /*
177015  ** Return the number of bytes required to store value iVal as a varint.
177016  */
177017  static int sessionVarintLen(int iVal){
177018    return sqlite3VarintLen(iVal);
177019  }
177020  
177021  /*
177022  ** Read a varint value from aBuf[] into *piVal. Return the number of 
177023  ** bytes read.
177024  */
177025  static int sessionVarintGet(u8 *aBuf, int *piVal){
177026    return getVarint32(aBuf, *piVal);
177027  }
177028  
177029  /* Load an unaligned and unsigned 32-bit integer */
177030  #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
177031  
177032  /*
177033  ** Read a 64-bit big-endian integer value from buffer aRec[]. Return
177034  ** the value read.
177035  */
177036  static sqlite3_int64 sessionGetI64(u8 *aRec){
177037    u64 x = SESSION_UINT32(aRec);
177038    u32 y = SESSION_UINT32(aRec+4);
177039    x = (x<<32) + y;
177040    return (sqlite3_int64)x;
177041  }
177042  
177043  /*
177044  ** Write a 64-bit big-endian integer value to the buffer aBuf[].
177045  */
177046  static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
177047    aBuf[0] = (i>>56) & 0xFF;
177048    aBuf[1] = (i>>48) & 0xFF;
177049    aBuf[2] = (i>>40) & 0xFF;
177050    aBuf[3] = (i>>32) & 0xFF;
177051    aBuf[4] = (i>>24) & 0xFF;
177052    aBuf[5] = (i>>16) & 0xFF;
177053    aBuf[6] = (i>> 8) & 0xFF;
177054    aBuf[7] = (i>> 0) & 0xFF;
177055  }
177056  
177057  /*
177058  ** This function is used to serialize the contents of value pValue (see
177059  ** comment titled "RECORD FORMAT" above).
177060  **
177061  ** If it is non-NULL, the serialized form of the value is written to 
177062  ** buffer aBuf. *pnWrite is set to the number of bytes written before
177063  ** returning. Or, if aBuf is NULL, the only thing this function does is
177064  ** set *pnWrite.
177065  **
177066  ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
177067  ** within a call to sqlite3_value_text() (may fail if the db is utf-16)) 
177068  ** SQLITE_NOMEM is returned.
177069  */
177070  static int sessionSerializeValue(
177071    u8 *aBuf,                       /* If non-NULL, write serialized value here */
177072    sqlite3_value *pValue,          /* Value to serialize */
177073    int *pnWrite                    /* IN/OUT: Increment by bytes written */
177074  ){
177075    int nByte;                      /* Size of serialized value in bytes */
177076  
177077    if( pValue ){
177078      int eType;                    /* Value type (SQLITE_NULL, TEXT etc.) */
177079    
177080      eType = sqlite3_value_type(pValue);
177081      if( aBuf ) aBuf[0] = eType;
177082    
177083      switch( eType ){
177084        case SQLITE_NULL: 
177085          nByte = 1;
177086          break;
177087    
177088        case SQLITE_INTEGER: 
177089        case SQLITE_FLOAT:
177090          if( aBuf ){
177091            /* TODO: SQLite does something special to deal with mixed-endian
177092            ** floating point values (e.g. ARM7). This code probably should
177093            ** too.  */
177094            u64 i;
177095            if( eType==SQLITE_INTEGER ){
177096              i = (u64)sqlite3_value_int64(pValue);
177097            }else{
177098              double r;
177099              assert( sizeof(double)==8 && sizeof(u64)==8 );
177100              r = sqlite3_value_double(pValue);
177101              memcpy(&i, &r, 8);
177102            }
177103            sessionPutI64(&aBuf[1], i);
177104          }
177105          nByte = 9; 
177106          break;
177107    
177108        default: {
177109          u8 *z;
177110          int n;
177111          int nVarint;
177112    
177113          assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
177114          if( eType==SQLITE_TEXT ){
177115            z = (u8 *)sqlite3_value_text(pValue);
177116          }else{
177117            z = (u8 *)sqlite3_value_blob(pValue);
177118          }
177119          n = sqlite3_value_bytes(pValue);
177120          if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
177121          nVarint = sessionVarintLen(n);
177122    
177123          if( aBuf ){
177124            sessionVarintPut(&aBuf[1], n);
177125            if( n ) memcpy(&aBuf[nVarint + 1], z, n);
177126          }
177127    
177128          nByte = 1 + nVarint + n;
177129          break;
177130        }
177131      }
177132    }else{
177133      nByte = 1;
177134      if( aBuf ) aBuf[0] = '\0';
177135    }
177136  
177137    if( pnWrite ) *pnWrite += nByte;
177138    return SQLITE_OK;
177139  }
177140  
177141  
177142  /*
177143  ** This macro is used to calculate hash key values for data structures. In
177144  ** order to use this macro, the entire data structure must be represented
177145  ** as a series of unsigned integers. In order to calculate a hash-key value
177146  ** for a data structure represented as three such integers, the macro may
177147  ** then be used as follows:
177148  **
177149  **    int hash_key_value;
177150  **    hash_key_value = HASH_APPEND(0, <value 1>);
177151  **    hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
177152  **    hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
177153  **
177154  ** In practice, the data structures this macro is used for are the primary
177155  ** key values of modified rows.
177156  */
177157  #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
177158  
177159  /*
177160  ** Append the hash of the 64-bit integer passed as the second argument to the
177161  ** hash-key value passed as the first. Return the new hash-key value.
177162  */
177163  static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
177164    h = HASH_APPEND(h, i & 0xFFFFFFFF);
177165    return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
177166  }
177167  
177168  /*
177169  ** Append the hash of the blob passed via the second and third arguments to 
177170  ** the hash-key value passed as the first. Return the new hash-key value.
177171  */
177172  static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
177173    int i;
177174    for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
177175    return h;
177176  }
177177  
177178  /*
177179  ** Append the hash of the data type passed as the second argument to the
177180  ** hash-key value passed as the first. Return the new hash-key value.
177181  */
177182  static unsigned int sessionHashAppendType(unsigned int h, int eType){
177183    return HASH_APPEND(h, eType);
177184  }
177185  
177186  /*
177187  ** This function may only be called from within a pre-update callback.
177188  ** It calculates a hash based on the primary key values of the old.* or 
177189  ** new.* row currently available and, assuming no error occurs, writes it to
177190  ** *piHash before returning. If the primary key contains one or more NULL
177191  ** values, *pbNullPK is set to true before returning.
177192  **
177193  ** If an error occurs, an SQLite error code is returned and the final values
177194  ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
177195  ** and the output variables are set as described above.
177196  */
177197  static int sessionPreupdateHash(
177198    sqlite3_session *pSession,      /* Session object that owns pTab */
177199    SessionTable *pTab,             /* Session table handle */
177200    int bNew,                       /* True to hash the new.* PK */
177201    int *piHash,                    /* OUT: Hash value */
177202    int *pbNullPK                   /* OUT: True if there are NULL values in PK */
177203  ){
177204    unsigned int h = 0;             /* Hash value to return */
177205    int i;                          /* Used to iterate through columns */
177206  
177207    assert( *pbNullPK==0 );
177208    assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
177209    for(i=0; i<pTab->nCol; i++){
177210      if( pTab->abPK[i] ){
177211        int rc;
177212        int eType;
177213        sqlite3_value *pVal;
177214  
177215        if( bNew ){
177216          rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
177217        }else{
177218          rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
177219        }
177220        if( rc!=SQLITE_OK ) return rc;
177221  
177222        eType = sqlite3_value_type(pVal);
177223        h = sessionHashAppendType(h, eType);
177224        if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
177225          i64 iVal;
177226          if( eType==SQLITE_INTEGER ){
177227            iVal = sqlite3_value_int64(pVal);
177228          }else{
177229            double rVal = sqlite3_value_double(pVal);
177230            assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
177231            memcpy(&iVal, &rVal, 8);
177232          }
177233          h = sessionHashAppendI64(h, iVal);
177234        }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
177235          const u8 *z;
177236          int n;
177237          if( eType==SQLITE_TEXT ){
177238            z = (const u8 *)sqlite3_value_text(pVal);
177239          }else{
177240            z = (const u8 *)sqlite3_value_blob(pVal);
177241          }
177242          n = sqlite3_value_bytes(pVal);
177243          if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
177244          h = sessionHashAppendBlob(h, n, z);
177245        }else{
177246          assert( eType==SQLITE_NULL );
177247          *pbNullPK = 1;
177248        }
177249      }
177250    }
177251  
177252    *piHash = (h % pTab->nChange);
177253    return SQLITE_OK;
177254  }
177255  
177256  /*
177257  ** The buffer that the argument points to contains a serialized SQL value.
177258  ** Return the number of bytes of space occupied by the value (including
177259  ** the type byte).
177260  */
177261  static int sessionSerialLen(u8 *a){
177262    int e = *a;
177263    int n;
177264    if( e==0 ) return 1;
177265    if( e==SQLITE_NULL ) return 1;
177266    if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
177267    return sessionVarintGet(&a[1], &n) + 1 + n;
177268  }
177269  
177270  /*
177271  ** Based on the primary key values stored in change aRecord, calculate a
177272  ** hash key. Assume the has table has nBucket buckets. The hash keys
177273  ** calculated by this function are compatible with those calculated by
177274  ** sessionPreupdateHash().
177275  **
177276  ** The bPkOnly argument is non-zero if the record at aRecord[] is from
177277  ** a patchset DELETE. In this case the non-PK fields are omitted entirely.
177278  */
177279  static unsigned int sessionChangeHash(
177280    SessionTable *pTab,             /* Table handle */
177281    int bPkOnly,                    /* Record consists of PK fields only */
177282    u8 *aRecord,                    /* Change record */
177283    int nBucket                     /* Assume this many buckets in hash table */
177284  ){
177285    unsigned int h = 0;             /* Value to return */
177286    int i;                          /* Used to iterate through columns */
177287    u8 *a = aRecord;                /* Used to iterate through change record */
177288  
177289    for(i=0; i<pTab->nCol; i++){
177290      int eType = *a;
177291      int isPK = pTab->abPK[i];
177292      if( bPkOnly && isPK==0 ) continue;
177293  
177294      /* It is not possible for eType to be SQLITE_NULL here. The session 
177295      ** module does not record changes for rows with NULL values stored in
177296      ** primary key columns. */
177297      assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT 
177298           || eType==SQLITE_TEXT || eType==SQLITE_BLOB 
177299           || eType==SQLITE_NULL || eType==0 
177300      );
177301      assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
177302  
177303      if( isPK ){
177304        a++;
177305        h = sessionHashAppendType(h, eType);
177306        if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
177307          h = sessionHashAppendI64(h, sessionGetI64(a));
177308          a += 8;
177309        }else{
177310          int n; 
177311          a += sessionVarintGet(a, &n);
177312          h = sessionHashAppendBlob(h, n, a);
177313          a += n;
177314        }
177315      }else{
177316        a += sessionSerialLen(a);
177317      }
177318    }
177319    return (h % nBucket);
177320  }
177321  
177322  /*
177323  ** Arguments aLeft and aRight are pointers to change records for table pTab.
177324  ** This function returns true if the two records apply to the same row (i.e.
177325  ** have the same values stored in the primary key columns), or false 
177326  ** otherwise.
177327  */
177328  static int sessionChangeEqual(
177329    SessionTable *pTab,             /* Table used for PK definition */
177330    int bLeftPkOnly,                /* True if aLeft[] contains PK fields only */
177331    u8 *aLeft,                      /* Change record */
177332    int bRightPkOnly,               /* True if aRight[] contains PK fields only */
177333    u8 *aRight                      /* Change record */
177334  ){
177335    u8 *a1 = aLeft;                 /* Cursor to iterate through aLeft */
177336    u8 *a2 = aRight;                /* Cursor to iterate through aRight */
177337    int iCol;                       /* Used to iterate through table columns */
177338  
177339    for(iCol=0; iCol<pTab->nCol; iCol++){
177340      if( pTab->abPK[iCol] ){
177341        int n1 = sessionSerialLen(a1);
177342        int n2 = sessionSerialLen(a2);
177343  
177344        if( pTab->abPK[iCol] && (n1!=n2 || memcmp(a1, a2, n1)) ){
177345          return 0;
177346        }
177347        a1 += n1;
177348        a2 += n2;
177349      }else{
177350        if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
177351        if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
177352      }
177353    }
177354  
177355    return 1;
177356  }
177357  
177358  /*
177359  ** Arguments aLeft and aRight both point to buffers containing change
177360  ** records with nCol columns. This function "merges" the two records into
177361  ** a single records which is written to the buffer at *paOut. *paOut is
177362  ** then set to point to one byte after the last byte written before 
177363  ** returning.
177364  **
177365  ** The merging of records is done as follows: For each column, if the 
177366  ** aRight record contains a value for the column, copy the value from
177367  ** their. Otherwise, if aLeft contains a value, copy it. If neither
177368  ** record contains a value for a given column, then neither does the
177369  ** output record.
177370  */
177371  static void sessionMergeRecord(
177372    u8 **paOut, 
177373    int nCol,
177374    u8 *aLeft,
177375    u8 *aRight
177376  ){
177377    u8 *a1 = aLeft;                 /* Cursor used to iterate through aLeft */
177378    u8 *a2 = aRight;                /* Cursor used to iterate through aRight */
177379    u8 *aOut = *paOut;              /* Output cursor */
177380    int iCol;                       /* Used to iterate from 0 to nCol */
177381  
177382    for(iCol=0; iCol<nCol; iCol++){
177383      int n1 = sessionSerialLen(a1);
177384      int n2 = sessionSerialLen(a2);
177385      if( *a2 ){
177386        memcpy(aOut, a2, n2);
177387        aOut += n2;
177388      }else{
177389        memcpy(aOut, a1, n1);
177390        aOut += n1;
177391      }
177392      a1 += n1;
177393      a2 += n2;
177394    }
177395  
177396    *paOut = aOut;
177397  }
177398  
177399  /*
177400  ** This is a helper function used by sessionMergeUpdate().
177401  **
177402  ** When this function is called, both *paOne and *paTwo point to a value 
177403  ** within a change record. Before it returns, both have been advanced so 
177404  ** as to point to the next value in the record.
177405  **
177406  ** If, when this function is called, *paTwo points to a valid value (i.e.
177407  ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
177408  ** pointer is returned and *pnVal is set to the number of bytes in the 
177409  ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
177410  ** set to the number of bytes in the value at *paOne. If *paOne points
177411  ** to the "no value" placeholder, *pnVal is set to 1. In other words:
177412  **
177413  **   if( *paTwo is valid ) return *paTwo;
177414  **   return *paOne;
177415  **
177416  */
177417  static u8 *sessionMergeValue(
177418    u8 **paOne,                     /* IN/OUT: Left-hand buffer pointer */
177419    u8 **paTwo,                     /* IN/OUT: Right-hand buffer pointer */
177420    int *pnVal                      /* OUT: Bytes in returned value */
177421  ){
177422    u8 *a1 = *paOne;
177423    u8 *a2 = *paTwo;
177424    u8 *pRet = 0;
177425    int n1;
177426  
177427    assert( a1 );
177428    if( a2 ){
177429      int n2 = sessionSerialLen(a2);
177430      if( *a2 ){
177431        *pnVal = n2;
177432        pRet = a2;
177433      }
177434      *paTwo = &a2[n2];
177435    }
177436  
177437    n1 = sessionSerialLen(a1);
177438    if( pRet==0 ){
177439      *pnVal = n1;
177440      pRet = a1;
177441    }
177442    *paOne = &a1[n1];
177443  
177444    return pRet;
177445  }
177446  
177447  /*
177448  ** This function is used by changeset_concat() to merge two UPDATE changes
177449  ** on the same row.
177450  */
177451  static int sessionMergeUpdate(
177452    u8 **paOut,                     /* IN/OUT: Pointer to output buffer */
177453    SessionTable *pTab,             /* Table change pertains to */
177454    int bPatchset,                  /* True if records are patchset records */
177455    u8 *aOldRecord1,                /* old.* record for first change */
177456    u8 *aOldRecord2,                /* old.* record for second change */
177457    u8 *aNewRecord1,                /* new.* record for first change */
177458    u8 *aNewRecord2                 /* new.* record for second change */
177459  ){
177460    u8 *aOld1 = aOldRecord1;
177461    u8 *aOld2 = aOldRecord2;
177462    u8 *aNew1 = aNewRecord1;
177463    u8 *aNew2 = aNewRecord2;
177464  
177465    u8 *aOut = *paOut;
177466    int i;
177467  
177468    if( bPatchset==0 ){
177469      int bRequired = 0;
177470  
177471      assert( aOldRecord1 && aNewRecord1 );
177472  
177473      /* Write the old.* vector first. */
177474      for(i=0; i<pTab->nCol; i++){
177475        int nOld;
177476        u8 *aOld;
177477        int nNew;
177478        u8 *aNew;
177479  
177480        aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
177481        aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
177482        if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
177483          if( pTab->abPK[i]==0 ) bRequired = 1;
177484          memcpy(aOut, aOld, nOld);
177485          aOut += nOld;
177486        }else{
177487          *(aOut++) = '\0';
177488        }
177489      }
177490  
177491      if( !bRequired ) return 0;
177492    }
177493  
177494    /* Write the new.* vector */
177495    aOld1 = aOldRecord1;
177496    aOld2 = aOldRecord2;
177497    aNew1 = aNewRecord1;
177498    aNew2 = aNewRecord2;
177499    for(i=0; i<pTab->nCol; i++){
177500      int nOld;
177501      u8 *aOld;
177502      int nNew;
177503      u8 *aNew;
177504  
177505      aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
177506      aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
177507      if( bPatchset==0 
177508       && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew))) 
177509      ){
177510        *(aOut++) = '\0';
177511      }else{
177512        memcpy(aOut, aNew, nNew);
177513        aOut += nNew;
177514      }
177515    }
177516  
177517    *paOut = aOut;
177518    return 1;
177519  }
177520  
177521  /*
177522  ** This function is only called from within a pre-update-hook callback.
177523  ** It determines if the current pre-update-hook change affects the same row
177524  ** as the change stored in argument pChange. If so, it returns true. Otherwise
177525  ** if the pre-update-hook does not affect the same row as pChange, it returns
177526  ** false.
177527  */
177528  static int sessionPreupdateEqual(
177529    sqlite3_session *pSession,      /* Session object that owns SessionTable */
177530    SessionTable *pTab,             /* Table associated with change */
177531    SessionChange *pChange,         /* Change to compare to */
177532    int op                          /* Current pre-update operation */
177533  ){
177534    int iCol;                       /* Used to iterate through columns */
177535    u8 *a = pChange->aRecord;       /* Cursor used to scan change record */
177536  
177537    assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
177538    for(iCol=0; iCol<pTab->nCol; iCol++){
177539      if( !pTab->abPK[iCol] ){
177540        a += sessionSerialLen(a);
177541      }else{
177542        sqlite3_value *pVal;        /* Value returned by preupdate_new/old */
177543        int rc;                     /* Error code from preupdate_new/old */
177544        int eType = *a++;           /* Type of value from change record */
177545  
177546        /* The following calls to preupdate_new() and preupdate_old() can not
177547        ** fail. This is because they cache their return values, and by the
177548        ** time control flows to here they have already been called once from
177549        ** within sessionPreupdateHash(). The first two asserts below verify
177550        ** this (that the method has already been called). */
177551        if( op==SQLITE_INSERT ){
177552          /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
177553          rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
177554        }else{
177555          /* assert( db->pPreUpdate->pUnpacked ); */
177556          rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
177557        }
177558        assert( rc==SQLITE_OK );
177559        if( sqlite3_value_type(pVal)!=eType ) return 0;
177560  
177561        /* A SessionChange object never has a NULL value in a PK column */
177562        assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
177563             || eType==SQLITE_BLOB    || eType==SQLITE_TEXT
177564        );
177565  
177566        if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
177567          i64 iVal = sessionGetI64(a);
177568          a += 8;
177569          if( eType==SQLITE_INTEGER ){
177570            if( sqlite3_value_int64(pVal)!=iVal ) return 0;
177571          }else{
177572            double rVal;
177573            assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
177574            memcpy(&rVal, &iVal, 8);
177575            if( sqlite3_value_double(pVal)!=rVal ) return 0;
177576          }
177577        }else{
177578          int n;
177579          const u8 *z;
177580          a += sessionVarintGet(a, &n);
177581          if( sqlite3_value_bytes(pVal)!=n ) return 0;
177582          if( eType==SQLITE_TEXT ){
177583            z = sqlite3_value_text(pVal);
177584          }else{
177585            z = sqlite3_value_blob(pVal);
177586          }
177587          if( memcmp(a, z, n) ) return 0;
177588          a += n;
177589          break;
177590        }
177591      }
177592    }
177593  
177594    return 1;
177595  }
177596  
177597  /*
177598  ** If required, grow the hash table used to store changes on table pTab 
177599  ** (part of the session pSession). If a fatal OOM error occurs, set the
177600  ** session object to failed and return SQLITE_ERROR. Otherwise, return
177601  ** SQLITE_OK.
177602  **
177603  ** It is possible that a non-fatal OOM error occurs in this function. In
177604  ** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
177605  ** Growing the hash table in this case is a performance optimization only,
177606  ** it is not required for correct operation.
177607  */
177608  static int sessionGrowHash(int bPatchset, SessionTable *pTab){
177609    if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
177610      int i;
177611      SessionChange **apNew;
177612      int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
177613  
177614      apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
177615      if( apNew==0 ){
177616        if( pTab->nChange==0 ){
177617          return SQLITE_ERROR;
177618        }
177619        return SQLITE_OK;
177620      }
177621      memset(apNew, 0, sizeof(SessionChange *) * nNew);
177622  
177623      for(i=0; i<pTab->nChange; i++){
177624        SessionChange *p;
177625        SessionChange *pNext;
177626        for(p=pTab->apChange[i]; p; p=pNext){
177627          int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
177628          int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
177629          pNext = p->pNext;
177630          p->pNext = apNew[iHash];
177631          apNew[iHash] = p;
177632        }
177633      }
177634  
177635      sqlite3_free(pTab->apChange);
177636      pTab->nChange = nNew;
177637      pTab->apChange = apNew;
177638    }
177639  
177640    return SQLITE_OK;
177641  }
177642  
177643  /*
177644  ** This function queries the database for the names of the columns of table
177645  ** zThis, in schema zDb. It is expected that the table has nCol columns. If
177646  ** not, SQLITE_SCHEMA is returned and none of the output variables are
177647  ** populated.
177648  **
177649  ** Otherwise, if they are not NULL, variable *pnCol is set to the number
177650  ** of columns in the database table and variable *pzTab is set to point to a
177651  ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
177652  ** point to an array of pointers to column names. And *pabPK (again, if not
177653  ** NULL) is set to point to an array of booleans - true if the corresponding
177654  ** column is part of the primary key.
177655  **
177656  ** For example, if the table is declared as:
177657  **
177658  **     CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
177659  **
177660  ** Then the four output variables are populated as follows:
177661  **
177662  **     *pnCol  = 4
177663  **     *pzTab  = "tbl1"
177664  **     *pazCol = {"w", "x", "y", "z"}
177665  **     *pabPK  = {1, 0, 0, 1}
177666  **
177667  ** All returned buffers are part of the same single allocation, which must
177668  ** be freed using sqlite3_free() by the caller. If pazCol was not NULL, then
177669  ** pointer *pazCol should be freed to release all memory. Otherwise, pointer
177670  ** *pabPK. It is illegal for both pazCol and pabPK to be NULL.
177671  */
177672  static int sessionTableInfo(
177673    sqlite3 *db,                    /* Database connection */
177674    const char *zDb,                /* Name of attached database (e.g. "main") */
177675    const char *zThis,              /* Table name */
177676    int *pnCol,                     /* OUT: number of columns */
177677    const char **pzTab,             /* OUT: Copy of zThis */
177678    const char ***pazCol,           /* OUT: Array of column names for table */
177679    u8 **pabPK                      /* OUT: Array of booleans - true for PK col */
177680  ){
177681    char *zPragma;
177682    sqlite3_stmt *pStmt;
177683    int rc;
177684    int nByte;
177685    int nDbCol = 0;
177686    int nThis;
177687    int i;
177688    u8 *pAlloc = 0;
177689    char **azCol = 0;
177690    u8 *abPK = 0;
177691  
177692    assert( pazCol && pabPK );
177693  
177694    nThis = sqlite3Strlen30(zThis);
177695    zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
177696    if( !zPragma ) return SQLITE_NOMEM;
177697  
177698    rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
177699    sqlite3_free(zPragma);
177700    if( rc!=SQLITE_OK ) return rc;
177701  
177702    nByte = nThis + 1;
177703    while( SQLITE_ROW==sqlite3_step(pStmt) ){
177704      nByte += sqlite3_column_bytes(pStmt, 1);
177705      nDbCol++;
177706    }
177707    rc = sqlite3_reset(pStmt);
177708  
177709    if( rc==SQLITE_OK ){
177710      nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
177711      pAlloc = sqlite3_malloc(nByte);
177712      if( pAlloc==0 ){
177713        rc = SQLITE_NOMEM;
177714      }
177715    }
177716    if( rc==SQLITE_OK ){
177717      azCol = (char **)pAlloc;
177718      pAlloc = (u8 *)&azCol[nDbCol];
177719      abPK = (u8 *)pAlloc;
177720      pAlloc = &abPK[nDbCol];
177721      if( pzTab ){
177722        memcpy(pAlloc, zThis, nThis+1);
177723        *pzTab = (char *)pAlloc;
177724        pAlloc += nThis+1;
177725      }
177726    
177727      i = 0;
177728      while( SQLITE_ROW==sqlite3_step(pStmt) ){
177729        int nName = sqlite3_column_bytes(pStmt, 1);
177730        const unsigned char *zName = sqlite3_column_text(pStmt, 1);
177731        if( zName==0 ) break;
177732        memcpy(pAlloc, zName, nName+1);
177733        azCol[i] = (char *)pAlloc;
177734        pAlloc += nName+1;
177735        abPK[i] = sqlite3_column_int(pStmt, 5);
177736        i++;
177737      }
177738      rc = sqlite3_reset(pStmt);
177739    
177740    }
177741  
177742    /* If successful, populate the output variables. Otherwise, zero them and
177743    ** free any allocation made. An error code will be returned in this case.
177744    */
177745    if( rc==SQLITE_OK ){
177746      *pazCol = (const char **)azCol;
177747      *pabPK = abPK;
177748      *pnCol = nDbCol;
177749    }else{
177750      *pazCol = 0;
177751      *pabPK = 0;
177752      *pnCol = 0;
177753      if( pzTab ) *pzTab = 0;
177754      sqlite3_free(azCol);
177755    }
177756    sqlite3_finalize(pStmt);
177757    return rc;
177758  }
177759  
177760  /*
177761  ** This function is only called from within a pre-update handler for a
177762  ** write to table pTab, part of session pSession. If this is the first
177763  ** write to this table, initalize the SessionTable.nCol, azCol[] and
177764  ** abPK[] arrays accordingly.
177765  **
177766  ** If an error occurs, an error code is stored in sqlite3_session.rc and
177767  ** non-zero returned. Or, if no error occurs but the table has no primary
177768  ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
177769  ** indicate that updates on this table should be ignored. SessionTable.abPK 
177770  ** is set to NULL in this case.
177771  */
177772  static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
177773    if( pTab->nCol==0 ){
177774      u8 *abPK;
177775      assert( pTab->azCol==0 || pTab->abPK==0 );
177776      pSession->rc = sessionTableInfo(pSession->db, pSession->zDb, 
177777          pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
177778      );
177779      if( pSession->rc==SQLITE_OK ){
177780        int i;
177781        for(i=0; i<pTab->nCol; i++){
177782          if( abPK[i] ){
177783            pTab->abPK = abPK;
177784            break;
177785          }
177786        }
177787      }
177788    }
177789    return (pSession->rc || pTab->abPK==0);
177790  }
177791  
177792  /*
177793  ** This function is only called from with a pre-update-hook reporting a 
177794  ** change on table pTab (attached to session pSession). The type of change
177795  ** (UPDATE, INSERT, DELETE) is specified by the first argument.
177796  **
177797  ** Unless one is already present or an error occurs, an entry is added
177798  ** to the changed-rows hash table associated with table pTab.
177799  */
177800  static void sessionPreupdateOneChange(
177801    int op,                         /* One of SQLITE_UPDATE, INSERT, DELETE */
177802    sqlite3_session *pSession,      /* Session object pTab is attached to */
177803    SessionTable *pTab              /* Table that change applies to */
177804  ){
177805    int iHash; 
177806    int bNull = 0; 
177807    int rc = SQLITE_OK;
177808  
177809    if( pSession->rc ) return;
177810  
177811    /* Load table details if required */
177812    if( sessionInitTable(pSession, pTab) ) return;
177813  
177814    /* Check the number of columns in this xPreUpdate call matches the 
177815    ** number of columns in the table.  */
177816    if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
177817      pSession->rc = SQLITE_SCHEMA;
177818      return;
177819    }
177820  
177821    /* Grow the hash table if required */
177822    if( sessionGrowHash(0, pTab) ){
177823      pSession->rc = SQLITE_NOMEM;
177824      return;
177825    }
177826  
177827    /* Calculate the hash-key for this change. If the primary key of the row
177828    ** includes a NULL value, exit early. Such changes are ignored by the
177829    ** session module. */
177830    rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
177831    if( rc!=SQLITE_OK ) goto error_out;
177832  
177833    if( bNull==0 ){
177834      /* Search the hash table for an existing record for this row. */
177835      SessionChange *pC;
177836      for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
177837        if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
177838      }
177839  
177840      if( pC==0 ){
177841        /* Create a new change object containing all the old values (if
177842        ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
177843        ** values (if this is an INSERT). */
177844        SessionChange *pChange; /* New change object */
177845        int nByte;              /* Number of bytes to allocate */
177846        int i;                  /* Used to iterate through columns */
177847    
177848        assert( rc==SQLITE_OK );
177849        pTab->nEntry++;
177850    
177851        /* Figure out how large an allocation is required */
177852        nByte = sizeof(SessionChange);
177853        for(i=0; i<pTab->nCol; i++){
177854          sqlite3_value *p = 0;
177855          if( op!=SQLITE_INSERT ){
177856            TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
177857            assert( trc==SQLITE_OK );
177858          }else if( pTab->abPK[i] ){
177859            TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
177860            assert( trc==SQLITE_OK );
177861          }
177862  
177863          /* This may fail if SQLite value p contains a utf-16 string that must
177864          ** be converted to utf-8 and an OOM error occurs while doing so. */
177865          rc = sessionSerializeValue(0, p, &nByte);
177866          if( rc!=SQLITE_OK ) goto error_out;
177867        }
177868    
177869        /* Allocate the change object */
177870        pChange = (SessionChange *)sqlite3_malloc(nByte);
177871        if( !pChange ){
177872          rc = SQLITE_NOMEM;
177873          goto error_out;
177874        }else{
177875          memset(pChange, 0, sizeof(SessionChange));
177876          pChange->aRecord = (u8 *)&pChange[1];
177877        }
177878    
177879        /* Populate the change object. None of the preupdate_old(),
177880        ** preupdate_new() or SerializeValue() calls below may fail as all
177881        ** required values and encodings have already been cached in memory.
177882        ** It is not possible for an OOM to occur in this block. */
177883        nByte = 0;
177884        for(i=0; i<pTab->nCol; i++){
177885          sqlite3_value *p = 0;
177886          if( op!=SQLITE_INSERT ){
177887            pSession->hook.xOld(pSession->hook.pCtx, i, &p);
177888          }else if( pTab->abPK[i] ){
177889            pSession->hook.xNew(pSession->hook.pCtx, i, &p);
177890          }
177891          sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
177892        }
177893  
177894        /* Add the change to the hash-table */
177895        if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
177896          pChange->bIndirect = 1;
177897        }
177898        pChange->nRecord = nByte;
177899        pChange->op = op;
177900        pChange->pNext = pTab->apChange[iHash];
177901        pTab->apChange[iHash] = pChange;
177902  
177903      }else if( pC->bIndirect ){
177904        /* If the existing change is considered "indirect", but this current
177905        ** change is "direct", mark the change object as direct. */
177906        if( pSession->hook.xDepth(pSession->hook.pCtx)==0 
177907         && pSession->bIndirect==0 
177908        ){
177909          pC->bIndirect = 0;
177910        }
177911      }
177912    }
177913  
177914    /* If an error has occurred, mark the session object as failed. */
177915   error_out:
177916    if( rc!=SQLITE_OK ){
177917      pSession->rc = rc;
177918    }
177919  }
177920  
177921  static int sessionFindTable(
177922    sqlite3_session *pSession, 
177923    const char *zName,
177924    SessionTable **ppTab
177925  ){
177926    int rc = SQLITE_OK;
177927    int nName = sqlite3Strlen30(zName);
177928    SessionTable *pRet;
177929  
177930    /* Search for an existing table */
177931    for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
177932      if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
177933    }
177934  
177935    if( pRet==0 && pSession->bAutoAttach ){
177936      /* If there is a table-filter configured, invoke it. If it returns 0,
177937      ** do not automatically add the new table. */
177938      if( pSession->xTableFilter==0
177939       || pSession->xTableFilter(pSession->pFilterCtx, zName) 
177940      ){
177941        rc = sqlite3session_attach(pSession, zName);
177942        if( rc==SQLITE_OK ){
177943          for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
177944          assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
177945        }
177946      }
177947    }
177948  
177949    assert( rc==SQLITE_OK || pRet==0 );
177950    *ppTab = pRet;
177951    return rc;
177952  }
177953  
177954  /*
177955  ** The 'pre-update' hook registered by this module with SQLite databases.
177956  */
177957  static void xPreUpdate(
177958    void *pCtx,                     /* Copy of third arg to preupdate_hook() */
177959    sqlite3 *db,                    /* Database handle */
177960    int op,                         /* SQLITE_UPDATE, DELETE or INSERT */
177961    char const *zDb,                /* Database name */
177962    char const *zName,              /* Table name */
177963    sqlite3_int64 iKey1,            /* Rowid of row about to be deleted/updated */
177964    sqlite3_int64 iKey2             /* New rowid value (for a rowid UPDATE) */
177965  ){
177966    sqlite3_session *pSession;
177967    int nDb = sqlite3Strlen30(zDb);
177968  
177969    assert( sqlite3_mutex_held(db->mutex) );
177970  
177971    for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
177972      SessionTable *pTab;
177973  
177974      /* If this session is attached to a different database ("main", "temp" 
177975      ** etc.), or if it is not currently enabled, there is nothing to do. Skip 
177976      ** to the next session object attached to this database. */
177977      if( pSession->bEnable==0 ) continue;
177978      if( pSession->rc ) continue;
177979      if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
177980  
177981      pSession->rc = sessionFindTable(pSession, zName, &pTab);
177982      if( pTab ){
177983        assert( pSession->rc==SQLITE_OK );
177984        sessionPreupdateOneChange(op, pSession, pTab);
177985        if( op==SQLITE_UPDATE ){
177986          sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
177987        }
177988      }
177989    }
177990  }
177991  
177992  /*
177993  ** The pre-update hook implementations.
177994  */
177995  static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
177996    return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
177997  }
177998  static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
177999    return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
178000  }
178001  static int sessionPreupdateCount(void *pCtx){
178002    return sqlite3_preupdate_count((sqlite3*)pCtx);
178003  }
178004  static int sessionPreupdateDepth(void *pCtx){
178005    return sqlite3_preupdate_depth((sqlite3*)pCtx);
178006  }
178007  
178008  /*
178009  ** Install the pre-update hooks on the session object passed as the only
178010  ** argument.
178011  */
178012  static void sessionPreupdateHooks(
178013    sqlite3_session *pSession
178014  ){
178015    pSession->hook.pCtx = (void*)pSession->db;
178016    pSession->hook.xOld = sessionPreupdateOld;
178017    pSession->hook.xNew = sessionPreupdateNew;
178018    pSession->hook.xCount = sessionPreupdateCount;
178019    pSession->hook.xDepth = sessionPreupdateDepth;
178020  }
178021  
178022  typedef struct SessionDiffCtx SessionDiffCtx;
178023  struct SessionDiffCtx {
178024    sqlite3_stmt *pStmt;
178025    int nOldOff;
178026  };
178027  
178028  /*
178029  ** The diff hook implementations.
178030  */
178031  static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
178032    SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
178033    *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
178034    return SQLITE_OK;
178035  }
178036  static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
178037    SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
178038    *ppVal = sqlite3_column_value(p->pStmt, iVal);
178039     return SQLITE_OK;
178040  }
178041  static int sessionDiffCount(void *pCtx){
178042    SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
178043    return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
178044  }
178045  static int sessionDiffDepth(void *pCtx){
178046    return 0;
178047  }
178048  
178049  /*
178050  ** Install the diff hooks on the session object passed as the only
178051  ** argument.
178052  */
178053  static void sessionDiffHooks(
178054    sqlite3_session *pSession,
178055    SessionDiffCtx *pDiffCtx
178056  ){
178057    pSession->hook.pCtx = (void*)pDiffCtx;
178058    pSession->hook.xOld = sessionDiffOld;
178059    pSession->hook.xNew = sessionDiffNew;
178060    pSession->hook.xCount = sessionDiffCount;
178061    pSession->hook.xDepth = sessionDiffDepth;
178062  }
178063  
178064  static char *sessionExprComparePK(
178065    int nCol,
178066    const char *zDb1, const char *zDb2, 
178067    const char *zTab,
178068    const char **azCol, u8 *abPK
178069  ){
178070    int i;
178071    const char *zSep = "";
178072    char *zRet = 0;
178073  
178074    for(i=0; i<nCol; i++){
178075      if( abPK[i] ){
178076        zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
178077            zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
178078        );
178079        zSep = " AND ";
178080        if( zRet==0 ) break;
178081      }
178082    }
178083  
178084    return zRet;
178085  }
178086  
178087  static char *sessionExprCompareOther(
178088    int nCol,
178089    const char *zDb1, const char *zDb2, 
178090    const char *zTab,
178091    const char **azCol, u8 *abPK
178092  ){
178093    int i;
178094    const char *zSep = "";
178095    char *zRet = 0;
178096    int bHave = 0;
178097  
178098    for(i=0; i<nCol; i++){
178099      if( abPK[i]==0 ){
178100        bHave = 1;
178101        zRet = sqlite3_mprintf(
178102            "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
178103            zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
178104        );
178105        zSep = " OR ";
178106        if( zRet==0 ) break;
178107      }
178108    }
178109  
178110    if( bHave==0 ){
178111      assert( zRet==0 );
178112      zRet = sqlite3_mprintf("0");
178113    }
178114  
178115    return zRet;
178116  }
178117  
178118  static char *sessionSelectFindNew(
178119    int nCol,
178120    const char *zDb1,      /* Pick rows in this db only */
178121    const char *zDb2,      /* But not in this one */
178122    const char *zTbl,      /* Table name */
178123    const char *zExpr
178124  ){
178125    char *zRet = sqlite3_mprintf(
178126        "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
178127        "  SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
178128        ")",
178129        zDb1, zTbl, zDb2, zTbl, zExpr
178130    );
178131    return zRet;
178132  }
178133  
178134  static int sessionDiffFindNew(
178135    int op,
178136    sqlite3_session *pSession,
178137    SessionTable *pTab,
178138    const char *zDb1,
178139    const char *zDb2,
178140    char *zExpr
178141  ){
178142    int rc = SQLITE_OK;
178143    char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
178144  
178145    if( zStmt==0 ){
178146      rc = SQLITE_NOMEM;
178147    }else{
178148      sqlite3_stmt *pStmt;
178149      rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
178150      if( rc==SQLITE_OK ){
178151        SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
178152        pDiffCtx->pStmt = pStmt;
178153        pDiffCtx->nOldOff = 0;
178154        while( SQLITE_ROW==sqlite3_step(pStmt) ){
178155          sessionPreupdateOneChange(op, pSession, pTab);
178156        }
178157        rc = sqlite3_finalize(pStmt);
178158      }
178159      sqlite3_free(zStmt);
178160    }
178161  
178162    return rc;
178163  }
178164  
178165  static int sessionDiffFindModified(
178166    sqlite3_session *pSession, 
178167    SessionTable *pTab, 
178168    const char *zFrom, 
178169    const char *zExpr
178170  ){
178171    int rc = SQLITE_OK;
178172  
178173    char *zExpr2 = sessionExprCompareOther(pTab->nCol,
178174        pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
178175    );
178176    if( zExpr2==0 ){
178177      rc = SQLITE_NOMEM;
178178    }else{
178179      char *zStmt = sqlite3_mprintf(
178180          "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
178181          pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
178182      );
178183      if( zStmt==0 ){
178184        rc = SQLITE_NOMEM;
178185      }else{
178186        sqlite3_stmt *pStmt;
178187        rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
178188  
178189        if( rc==SQLITE_OK ){
178190          SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
178191          pDiffCtx->pStmt = pStmt;
178192          pDiffCtx->nOldOff = pTab->nCol;
178193          while( SQLITE_ROW==sqlite3_step(pStmt) ){
178194            sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
178195          }
178196          rc = sqlite3_finalize(pStmt);
178197        }
178198        sqlite3_free(zStmt);
178199      }
178200    }
178201  
178202    return rc;
178203  }
178204  
178205  SQLITE_API int sqlite3session_diff(
178206    sqlite3_session *pSession,
178207    const char *zFrom,
178208    const char *zTbl,
178209    char **pzErrMsg
178210  ){
178211    const char *zDb = pSession->zDb;
178212    int rc = pSession->rc;
178213    SessionDiffCtx d;
178214  
178215    memset(&d, 0, sizeof(d));
178216    sessionDiffHooks(pSession, &d);
178217  
178218    sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
178219    if( pzErrMsg ) *pzErrMsg = 0;
178220    if( rc==SQLITE_OK ){
178221      char *zExpr = 0;
178222      sqlite3 *db = pSession->db;
178223      SessionTable *pTo;            /* Table zTbl */
178224  
178225      /* Locate and if necessary initialize the target table object */
178226      rc = sessionFindTable(pSession, zTbl, &pTo);
178227      if( pTo==0 ) goto diff_out;
178228      if( sessionInitTable(pSession, pTo) ){
178229        rc = pSession->rc;
178230        goto diff_out;
178231      }
178232  
178233      /* Check the table schemas match */
178234      if( rc==SQLITE_OK ){
178235        int bHasPk = 0;
178236        int bMismatch = 0;
178237        int nCol;                   /* Columns in zFrom.zTbl */
178238        u8 *abPK;
178239        const char **azCol = 0;
178240        rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
178241        if( rc==SQLITE_OK ){
178242          if( pTo->nCol!=nCol ){
178243            bMismatch = 1;
178244          }else{
178245            int i;
178246            for(i=0; i<nCol; i++){
178247              if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
178248              if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
178249              if( abPK[i] ) bHasPk = 1;
178250            }
178251          }
178252  
178253        }
178254        sqlite3_free((char*)azCol);
178255        if( bMismatch ){
178256          *pzErrMsg = sqlite3_mprintf("table schemas do not match");
178257          rc = SQLITE_SCHEMA;
178258        }
178259        if( bHasPk==0 ){
178260          /* Ignore tables with no primary keys */
178261          goto diff_out;
178262        }
178263      }
178264  
178265      if( rc==SQLITE_OK ){
178266        zExpr = sessionExprComparePK(pTo->nCol, 
178267            zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
178268        );
178269      }
178270  
178271      /* Find new rows */
178272      if( rc==SQLITE_OK ){
178273        rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
178274      }
178275  
178276      /* Find old rows */
178277      if( rc==SQLITE_OK ){
178278        rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
178279      }
178280  
178281      /* Find modified rows */
178282      if( rc==SQLITE_OK ){
178283        rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
178284      }
178285  
178286      sqlite3_free(zExpr);
178287    }
178288  
178289   diff_out:
178290    sessionPreupdateHooks(pSession);
178291    sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
178292    return rc;
178293  }
178294  
178295  /*
178296  ** Create a session object. This session object will record changes to
178297  ** database zDb attached to connection db.
178298  */
178299  SQLITE_API int sqlite3session_create(
178300    sqlite3 *db,                    /* Database handle */
178301    const char *zDb,                /* Name of db (e.g. "main") */
178302    sqlite3_session **ppSession     /* OUT: New session object */
178303  ){
178304    sqlite3_session *pNew;          /* Newly allocated session object */
178305    sqlite3_session *pOld;          /* Session object already attached to db */
178306    int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
178307  
178308    /* Zero the output value in case an error occurs. */
178309    *ppSession = 0;
178310  
178311    /* Allocate and populate the new session object. */
178312    pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
178313    if( !pNew ) return SQLITE_NOMEM;
178314    memset(pNew, 0, sizeof(sqlite3_session));
178315    pNew->db = db;
178316    pNew->zDb = (char *)&pNew[1];
178317    pNew->bEnable = 1;
178318    memcpy(pNew->zDb, zDb, nDb+1);
178319    sessionPreupdateHooks(pNew);
178320  
178321    /* Add the new session object to the linked list of session objects 
178322    ** attached to database handle $db. Do this under the cover of the db
178323    ** handle mutex.  */
178324    sqlite3_mutex_enter(sqlite3_db_mutex(db));
178325    pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
178326    pNew->pNext = pOld;
178327    sqlite3_mutex_leave(sqlite3_db_mutex(db));
178328  
178329    *ppSession = pNew;
178330    return SQLITE_OK;
178331  }
178332  
178333  /*
178334  ** Free the list of table objects passed as the first argument. The contents
178335  ** of the changed-rows hash tables are also deleted.
178336  */
178337  static void sessionDeleteTable(SessionTable *pList){
178338    SessionTable *pNext;
178339    SessionTable *pTab;
178340  
178341    for(pTab=pList; pTab; pTab=pNext){
178342      int i;
178343      pNext = pTab->pNext;
178344      for(i=0; i<pTab->nChange; i++){
178345        SessionChange *p;
178346        SessionChange *pNextChange;
178347        for(p=pTab->apChange[i]; p; p=pNextChange){
178348          pNextChange = p->pNext;
178349          sqlite3_free(p);
178350        }
178351      }
178352      sqlite3_free((char*)pTab->azCol);  /* cast works around VC++ bug */
178353      sqlite3_free(pTab->apChange);
178354      sqlite3_free(pTab);
178355    }
178356  }
178357  
178358  /*
178359  ** Delete a session object previously allocated using sqlite3session_create().
178360  */
178361  SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
178362    sqlite3 *db = pSession->db;
178363    sqlite3_session *pHead;
178364    sqlite3_session **pp;
178365  
178366    /* Unlink the session from the linked list of sessions attached to the
178367    ** database handle. Hold the db mutex while doing so.  */
178368    sqlite3_mutex_enter(sqlite3_db_mutex(db));
178369    pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
178370    for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
178371      if( (*pp)==pSession ){
178372        *pp = (*pp)->pNext;
178373        if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
178374        break;
178375      }
178376    }
178377    sqlite3_mutex_leave(sqlite3_db_mutex(db));
178378  
178379    /* Delete all attached table objects. And the contents of their 
178380    ** associated hash-tables. */
178381    sessionDeleteTable(pSession->pTable);
178382  
178383    /* Free the session object itself. */
178384    sqlite3_free(pSession);
178385  }
178386  
178387  /*
178388  ** Set a table filter on a Session Object.
178389  */
178390  SQLITE_API void sqlite3session_table_filter(
178391    sqlite3_session *pSession, 
178392    int(*xFilter)(void*, const char*),
178393    void *pCtx                      /* First argument passed to xFilter */
178394  ){
178395    pSession->bAutoAttach = 1;
178396    pSession->pFilterCtx = pCtx;
178397    pSession->xTableFilter = xFilter;
178398  }
178399  
178400  /*
178401  ** Attach a table to a session. All subsequent changes made to the table
178402  ** while the session object is enabled will be recorded.
178403  **
178404  ** Only tables that have a PRIMARY KEY defined may be attached. It does
178405  ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
178406  ** or not.
178407  */
178408  SQLITE_API int sqlite3session_attach(
178409    sqlite3_session *pSession,      /* Session object */
178410    const char *zName               /* Table name */
178411  ){
178412    int rc = SQLITE_OK;
178413    sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
178414  
178415    if( !zName ){
178416      pSession->bAutoAttach = 1;
178417    }else{
178418      SessionTable *pTab;           /* New table object (if required) */
178419      int nName;                    /* Number of bytes in string zName */
178420  
178421      /* First search for an existing entry. If one is found, this call is
178422      ** a no-op. Return early. */
178423      nName = sqlite3Strlen30(zName);
178424      for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
178425        if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
178426      }
178427  
178428      if( !pTab ){
178429        /* Allocate new SessionTable object. */
178430        pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
178431        if( !pTab ){
178432          rc = SQLITE_NOMEM;
178433        }else{
178434          /* Populate the new SessionTable object and link it into the list.
178435          ** The new object must be linked onto the end of the list, not 
178436          ** simply added to the start of it in order to ensure that tables
178437          ** appear in the correct order when a changeset or patchset is
178438          ** eventually generated. */
178439          SessionTable **ppTab;
178440          memset(pTab, 0, sizeof(SessionTable));
178441          pTab->zName = (char *)&pTab[1];
178442          memcpy(pTab->zName, zName, nName+1);
178443          for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
178444          *ppTab = pTab;
178445        }
178446      }
178447    }
178448  
178449    sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
178450    return rc;
178451  }
178452  
178453  /*
178454  ** Ensure that there is room in the buffer to append nByte bytes of data.
178455  ** If not, use sqlite3_realloc() to grow the buffer so that there is.
178456  **
178457  ** If successful, return zero. Otherwise, if an OOM condition is encountered,
178458  ** set *pRc to SQLITE_NOMEM and return non-zero.
178459  */
178460  static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
178461    if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
178462      u8 *aNew;
178463      int nNew = p->nAlloc ? p->nAlloc : 128;
178464      do {
178465        nNew = nNew*2;
178466      }while( nNew<(p->nBuf+nByte) );
178467  
178468      aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew);
178469      if( 0==aNew ){
178470        *pRc = SQLITE_NOMEM;
178471      }else{
178472        p->aBuf = aNew;
178473        p->nAlloc = nNew;
178474      }
178475    }
178476    return (*pRc!=SQLITE_OK);
178477  }
178478  
178479  /*
178480  ** Append the value passed as the second argument to the buffer passed
178481  ** as the first.
178482  **
178483  ** This function is a no-op if *pRc is non-zero when it is called.
178484  ** Otherwise, if an error occurs, *pRc is set to an SQLite error code
178485  ** before returning.
178486  */
178487  static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
178488    int rc = *pRc;
178489    if( rc==SQLITE_OK ){
178490      int nByte = 0;
178491      rc = sessionSerializeValue(0, pVal, &nByte);
178492      sessionBufferGrow(p, nByte, &rc);
178493      if( rc==SQLITE_OK ){
178494        rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
178495        p->nBuf += nByte;
178496      }else{
178497        *pRc = rc;
178498      }
178499    }
178500  }
178501  
178502  /*
178503  ** This function is a no-op if *pRc is other than SQLITE_OK when it is 
178504  ** called. Otherwise, append a single byte to the buffer. 
178505  **
178506  ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
178507  ** returning.
178508  */
178509  static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
178510    if( 0==sessionBufferGrow(p, 1, pRc) ){
178511      p->aBuf[p->nBuf++] = v;
178512    }
178513  }
178514  
178515  /*
178516  ** This function is a no-op if *pRc is other than SQLITE_OK when it is 
178517  ** called. Otherwise, append a single varint to the buffer. 
178518  **
178519  ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
178520  ** returning.
178521  */
178522  static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
178523    if( 0==sessionBufferGrow(p, 9, pRc) ){
178524      p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
178525    }
178526  }
178527  
178528  /*
178529  ** This function is a no-op if *pRc is other than SQLITE_OK when it is 
178530  ** called. Otherwise, append a blob of data to the buffer. 
178531  **
178532  ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
178533  ** returning.
178534  */
178535  static void sessionAppendBlob(
178536    SessionBuffer *p, 
178537    const u8 *aBlob, 
178538    int nBlob, 
178539    int *pRc
178540  ){
178541    if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
178542      memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
178543      p->nBuf += nBlob;
178544    }
178545  }
178546  
178547  /*
178548  ** This function is a no-op if *pRc is other than SQLITE_OK when it is 
178549  ** called. Otherwise, append a string to the buffer. All bytes in the string
178550  ** up to (but not including) the nul-terminator are written to the buffer.
178551  **
178552  ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
178553  ** returning.
178554  */
178555  static void sessionAppendStr(
178556    SessionBuffer *p, 
178557    const char *zStr, 
178558    int *pRc
178559  ){
178560    int nStr = sqlite3Strlen30(zStr);
178561    if( 0==sessionBufferGrow(p, nStr, pRc) ){
178562      memcpy(&p->aBuf[p->nBuf], zStr, nStr);
178563      p->nBuf += nStr;
178564    }
178565  }
178566  
178567  /*
178568  ** This function is a no-op if *pRc is other than SQLITE_OK when it is 
178569  ** called. Otherwise, append the string representation of integer iVal
178570  ** to the buffer. No nul-terminator is written.
178571  **
178572  ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
178573  ** returning.
178574  */
178575  static void sessionAppendInteger(
178576    SessionBuffer *p,               /* Buffer to append to */
178577    int iVal,                       /* Value to write the string rep. of */
178578    int *pRc                        /* IN/OUT: Error code */
178579  ){
178580    char aBuf[24];
178581    sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
178582    sessionAppendStr(p, aBuf, pRc);
178583  }
178584  
178585  /*
178586  ** This function is a no-op if *pRc is other than SQLITE_OK when it is 
178587  ** called. Otherwise, append the string zStr enclosed in quotes (") and
178588  ** with any embedded quote characters escaped to the buffer. No 
178589  ** nul-terminator byte is written.
178590  **
178591  ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
178592  ** returning.
178593  */
178594  static void sessionAppendIdent(
178595    SessionBuffer *p,               /* Buffer to a append to */
178596    const char *zStr,               /* String to quote, escape and append */
178597    int *pRc                        /* IN/OUT: Error code */
178598  ){
178599    int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
178600    if( 0==sessionBufferGrow(p, nStr, pRc) ){
178601      char *zOut = (char *)&p->aBuf[p->nBuf];
178602      const char *zIn = zStr;
178603      *zOut++ = '"';
178604      while( *zIn ){
178605        if( *zIn=='"' ) *zOut++ = '"';
178606        *zOut++ = *(zIn++);
178607      }
178608      *zOut++ = '"';
178609      p->nBuf = (int)((u8 *)zOut - p->aBuf);
178610    }
178611  }
178612  
178613  /*
178614  ** This function is a no-op if *pRc is other than SQLITE_OK when it is
178615  ** called. Otherwse, it appends the serialized version of the value stored
178616  ** in column iCol of the row that SQL statement pStmt currently points
178617  ** to to the buffer.
178618  */
178619  static void sessionAppendCol(
178620    SessionBuffer *p,               /* Buffer to append to */
178621    sqlite3_stmt *pStmt,            /* Handle pointing to row containing value */
178622    int iCol,                       /* Column to read value from */
178623    int *pRc                        /* IN/OUT: Error code */
178624  ){
178625    if( *pRc==SQLITE_OK ){
178626      int eType = sqlite3_column_type(pStmt, iCol);
178627      sessionAppendByte(p, (u8)eType, pRc);
178628      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
178629        sqlite3_int64 i;
178630        u8 aBuf[8];
178631        if( eType==SQLITE_INTEGER ){
178632          i = sqlite3_column_int64(pStmt, iCol);
178633        }else{
178634          double r = sqlite3_column_double(pStmt, iCol);
178635          memcpy(&i, &r, 8);
178636        }
178637        sessionPutI64(aBuf, i);
178638        sessionAppendBlob(p, aBuf, 8, pRc);
178639      }
178640      if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
178641        u8 *z;
178642        int nByte;
178643        if( eType==SQLITE_BLOB ){
178644          z = (u8 *)sqlite3_column_blob(pStmt, iCol);
178645        }else{
178646          z = (u8 *)sqlite3_column_text(pStmt, iCol);
178647        }
178648        nByte = sqlite3_column_bytes(pStmt, iCol);
178649        if( z || (eType==SQLITE_BLOB && nByte==0) ){
178650          sessionAppendVarint(p, nByte, pRc);
178651          sessionAppendBlob(p, z, nByte, pRc);
178652        }else{
178653          *pRc = SQLITE_NOMEM;
178654        }
178655      }
178656    }
178657  }
178658  
178659  /*
178660  **
178661  ** This function appends an update change to the buffer (see the comments 
178662  ** under "CHANGESET FORMAT" at the top of the file). An update change 
178663  ** consists of:
178664  **
178665  **   1 byte:  SQLITE_UPDATE (0x17)
178666  **   n bytes: old.* record (see RECORD FORMAT)
178667  **   m bytes: new.* record (see RECORD FORMAT)
178668  **
178669  ** The SessionChange object passed as the third argument contains the
178670  ** values that were stored in the row when the session began (the old.*
178671  ** values). The statement handle passed as the second argument points
178672  ** at the current version of the row (the new.* values).
178673  **
178674  ** If all of the old.* values are equal to their corresponding new.* value
178675  ** (i.e. nothing has changed), then no data at all is appended to the buffer.
178676  **
178677  ** Otherwise, the old.* record contains all primary key values and the 
178678  ** original values of any fields that have been modified. The new.* record 
178679  ** contains the new values of only those fields that have been modified.
178680  */ 
178681  static int sessionAppendUpdate(
178682    SessionBuffer *pBuf,            /* Buffer to append to */
178683    int bPatchset,                  /* True for "patchset", 0 for "changeset" */
178684    sqlite3_stmt *pStmt,            /* Statement handle pointing at new row */
178685    SessionChange *p,               /* Object containing old values */
178686    u8 *abPK                        /* Boolean array - true for PK columns */
178687  ){
178688    int rc = SQLITE_OK;
178689    SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
178690    int bNoop = 1;                /* Set to zero if any values are modified */
178691    int nRewind = pBuf->nBuf;     /* Set to zero if any values are modified */
178692    int i;                        /* Used to iterate through columns */
178693    u8 *pCsr = p->aRecord;        /* Used to iterate through old.* values */
178694  
178695    sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
178696    sessionAppendByte(pBuf, p->bIndirect, &rc);
178697    for(i=0; i<sqlite3_column_count(pStmt); i++){
178698      int bChanged = 0;
178699      int nAdvance;
178700      int eType = *pCsr;
178701      switch( eType ){
178702        case SQLITE_NULL:
178703          nAdvance = 1;
178704          if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
178705            bChanged = 1;
178706          }
178707          break;
178708  
178709        case SQLITE_FLOAT:
178710        case SQLITE_INTEGER: {
178711          nAdvance = 9;
178712          if( eType==sqlite3_column_type(pStmt, i) ){
178713            sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
178714            if( eType==SQLITE_INTEGER ){
178715              if( iVal==sqlite3_column_int64(pStmt, i) ) break;
178716            }else{
178717              double dVal;
178718              memcpy(&dVal, &iVal, 8);
178719              if( dVal==sqlite3_column_double(pStmt, i) ) break;
178720            }
178721          }
178722          bChanged = 1;
178723          break;
178724        }
178725  
178726        default: {
178727          int n;
178728          int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
178729          assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
178730          nAdvance = nHdr + n;
178731          if( eType==sqlite3_column_type(pStmt, i) 
178732           && n==sqlite3_column_bytes(pStmt, i) 
178733           && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
178734          ){
178735            break;
178736          }
178737          bChanged = 1;
178738        }
178739      }
178740  
178741      /* If at least one field has been modified, this is not a no-op. */
178742      if( bChanged ) bNoop = 0;
178743  
178744      /* Add a field to the old.* record. This is omitted if this modules is
178745      ** currently generating a patchset. */
178746      if( bPatchset==0 ){
178747        if( bChanged || abPK[i] ){
178748          sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
178749        }else{
178750          sessionAppendByte(pBuf, 0, &rc);
178751        }
178752      }
178753  
178754      /* Add a field to the new.* record. Or the only record if currently
178755      ** generating a patchset.  */
178756      if( bChanged || (bPatchset && abPK[i]) ){
178757        sessionAppendCol(&buf2, pStmt, i, &rc);
178758      }else{
178759        sessionAppendByte(&buf2, 0, &rc);
178760      }
178761  
178762      pCsr += nAdvance;
178763    }
178764  
178765    if( bNoop ){
178766      pBuf->nBuf = nRewind;
178767    }else{
178768      sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
178769    }
178770    sqlite3_free(buf2.aBuf);
178771  
178772    return rc;
178773  }
178774  
178775  /*
178776  ** Append a DELETE change to the buffer passed as the first argument. Use
178777  ** the changeset format if argument bPatchset is zero, or the patchset
178778  ** format otherwise.
178779  */
178780  static int sessionAppendDelete(
178781    SessionBuffer *pBuf,            /* Buffer to append to */
178782    int bPatchset,                  /* True for "patchset", 0 for "changeset" */
178783    SessionChange *p,               /* Object containing old values */
178784    int nCol,                       /* Number of columns in table */
178785    u8 *abPK                        /* Boolean array - true for PK columns */
178786  ){
178787    int rc = SQLITE_OK;
178788  
178789    sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
178790    sessionAppendByte(pBuf, p->bIndirect, &rc);
178791  
178792    if( bPatchset==0 ){
178793      sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
178794    }else{
178795      int i;
178796      u8 *a = p->aRecord;
178797      for(i=0; i<nCol; i++){
178798        u8 *pStart = a;
178799        int eType = *a++;
178800  
178801        switch( eType ){
178802          case 0:
178803          case SQLITE_NULL:
178804            assert( abPK[i]==0 );
178805            break;
178806  
178807          case SQLITE_FLOAT:
178808          case SQLITE_INTEGER:
178809            a += 8;
178810            break;
178811  
178812          default: {
178813            int n;
178814            a += sessionVarintGet(a, &n);
178815            a += n;
178816            break;
178817          }
178818        }
178819        if( abPK[i] ){
178820          sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
178821        }
178822      }
178823      assert( (a - p->aRecord)==p->nRecord );
178824    }
178825  
178826    return rc;
178827  }
178828  
178829  /*
178830  ** Formulate and prepare a SELECT statement to retrieve a row from table
178831  ** zTab in database zDb based on its primary key. i.e.
178832  **
178833  **   SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
178834  */
178835  static int sessionSelectStmt(
178836    sqlite3 *db,                    /* Database handle */
178837    const char *zDb,                /* Database name */
178838    const char *zTab,               /* Table name */
178839    int nCol,                       /* Number of columns in table */
178840    const char **azCol,             /* Names of table columns */
178841    u8 *abPK,                       /* PRIMARY KEY  array */
178842    sqlite3_stmt **ppStmt           /* OUT: Prepared SELECT statement */
178843  ){
178844    int rc = SQLITE_OK;
178845    int i;
178846    const char *zSep = "";
178847    SessionBuffer buf = {0, 0, 0};
178848  
178849    sessionAppendStr(&buf, "SELECT * FROM ", &rc);
178850    sessionAppendIdent(&buf, zDb, &rc);
178851    sessionAppendStr(&buf, ".", &rc);
178852    sessionAppendIdent(&buf, zTab, &rc);
178853    sessionAppendStr(&buf, " WHERE ", &rc);
178854    for(i=0; i<nCol; i++){
178855      if( abPK[i] ){
178856        sessionAppendStr(&buf, zSep, &rc);
178857        sessionAppendIdent(&buf, azCol[i], &rc);
178858        sessionAppendStr(&buf, " = ?", &rc);
178859        sessionAppendInteger(&buf, i+1, &rc);
178860        zSep = " AND ";
178861      }
178862    }
178863    if( rc==SQLITE_OK ){
178864      rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, ppStmt, 0);
178865    }
178866    sqlite3_free(buf.aBuf);
178867    return rc;
178868  }
178869  
178870  /*
178871  ** Bind the PRIMARY KEY values from the change passed in argument pChange
178872  ** to the SELECT statement passed as the first argument. The SELECT statement
178873  ** is as prepared by function sessionSelectStmt().
178874  **
178875  ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
178876  ** error code (e.g. SQLITE_NOMEM) otherwise.
178877  */
178878  static int sessionSelectBind(
178879    sqlite3_stmt *pSelect,          /* SELECT from sessionSelectStmt() */
178880    int nCol,                       /* Number of columns in table */
178881    u8 *abPK,                       /* PRIMARY KEY array */
178882    SessionChange *pChange          /* Change structure */
178883  ){
178884    int i;
178885    int rc = SQLITE_OK;
178886    u8 *a = pChange->aRecord;
178887  
178888    for(i=0; i<nCol && rc==SQLITE_OK; i++){
178889      int eType = *a++;
178890  
178891      switch( eType ){
178892        case 0:
178893        case SQLITE_NULL:
178894          assert( abPK[i]==0 );
178895          break;
178896  
178897        case SQLITE_INTEGER: {
178898          if( abPK[i] ){
178899            i64 iVal = sessionGetI64(a);
178900            rc = sqlite3_bind_int64(pSelect, i+1, iVal);
178901          }
178902          a += 8;
178903          break;
178904        }
178905  
178906        case SQLITE_FLOAT: {
178907          if( abPK[i] ){
178908            double rVal;
178909            i64 iVal = sessionGetI64(a);
178910            memcpy(&rVal, &iVal, 8);
178911            rc = sqlite3_bind_double(pSelect, i+1, rVal);
178912          }
178913          a += 8;
178914          break;
178915        }
178916  
178917        case SQLITE_TEXT: {
178918          int n;
178919          a += sessionVarintGet(a, &n);
178920          if( abPK[i] ){
178921            rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
178922          }
178923          a += n;
178924          break;
178925        }
178926  
178927        default: {
178928          int n;
178929          assert( eType==SQLITE_BLOB );
178930          a += sessionVarintGet(a, &n);
178931          if( abPK[i] ){
178932            rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
178933          }
178934          a += n;
178935          break;
178936        }
178937      }
178938    }
178939  
178940    return rc;
178941  }
178942  
178943  /*
178944  ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
178945  ** is called. Otherwise, append a serialized table header (part of the binary 
178946  ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
178947  ** SQLite error code before returning.
178948  */
178949  static void sessionAppendTableHdr(
178950    SessionBuffer *pBuf,            /* Append header to this buffer */
178951    int bPatchset,                  /* Use the patchset format if true */
178952    SessionTable *pTab,             /* Table object to append header for */
178953    int *pRc                        /* IN/OUT: Error code */
178954  ){
178955    /* Write a table header */
178956    sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
178957    sessionAppendVarint(pBuf, pTab->nCol, pRc);
178958    sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
178959    sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
178960  }
178961  
178962  /*
178963  ** Generate either a changeset (if argument bPatchset is zero) or a patchset
178964  ** (if it is non-zero) based on the current contents of the session object
178965  ** passed as the first argument.
178966  **
178967  ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
178968  ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
178969  ** occurs, an SQLite error code is returned and both output variables set 
178970  ** to 0.
178971  */
178972  static int sessionGenerateChangeset(
178973    sqlite3_session *pSession,      /* Session object */
178974    int bPatchset,                  /* True for patchset, false for changeset */
178975    int (*xOutput)(void *pOut, const void *pData, int nData),
178976    void *pOut,                     /* First argument for xOutput */
178977    int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
178978    void **ppChangeset              /* OUT: Buffer containing changeset */
178979  ){
178980    sqlite3 *db = pSession->db;     /* Source database handle */
178981    SessionTable *pTab;             /* Used to iterate through attached tables */
178982    SessionBuffer buf = {0,0,0};    /* Buffer in which to accumlate changeset */
178983    int rc;                         /* Return code */
178984  
178985    assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
178986  
178987    /* Zero the output variables in case an error occurs. If this session
178988    ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
178989    ** this call will be a no-op.  */
178990    if( xOutput==0 ){
178991      *pnChangeset = 0;
178992      *ppChangeset = 0;
178993    }
178994  
178995    if( pSession->rc ) return pSession->rc;
178996    rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
178997    if( rc!=SQLITE_OK ) return rc;
178998  
178999    sqlite3_mutex_enter(sqlite3_db_mutex(db));
179000  
179001    for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
179002      if( pTab->nEntry ){
179003        const char *zName = pTab->zName;
179004        int nCol;                   /* Number of columns in table */
179005        u8 *abPK;                   /* Primary key array */
179006        const char **azCol = 0;     /* Table columns */
179007        int i;                      /* Used to iterate through hash buckets */
179008        sqlite3_stmt *pSel = 0;     /* SELECT statement to query table pTab */
179009        int nRewind = buf.nBuf;     /* Initial size of write buffer */
179010        int nNoop;                  /* Size of buffer after writing tbl header */
179011  
179012        /* Check the table schema is still Ok. */
179013        rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
179014        if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
179015          rc = SQLITE_SCHEMA;
179016        }
179017  
179018        /* Write a table header */
179019        sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
179020  
179021        /* Build and compile a statement to execute: */
179022        if( rc==SQLITE_OK ){
179023          rc = sessionSelectStmt(
179024              db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
179025        }
179026  
179027        nNoop = buf.nBuf;
179028        for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
179029          SessionChange *p;         /* Used to iterate through changes */
179030  
179031          for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
179032            rc = sessionSelectBind(pSel, nCol, abPK, p);
179033            if( rc!=SQLITE_OK ) continue;
179034            if( sqlite3_step(pSel)==SQLITE_ROW ){
179035              if( p->op==SQLITE_INSERT ){
179036                int iCol;
179037                sessionAppendByte(&buf, SQLITE_INSERT, &rc);
179038                sessionAppendByte(&buf, p->bIndirect, &rc);
179039                for(iCol=0; iCol<nCol; iCol++){
179040                  sessionAppendCol(&buf, pSel, iCol, &rc);
179041                }
179042              }else{
179043                rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
179044              }
179045            }else if( p->op!=SQLITE_INSERT ){
179046              rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
179047            }
179048            if( rc==SQLITE_OK ){
179049              rc = sqlite3_reset(pSel);
179050            }
179051  
179052            /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass
179053            ** its contents to the xOutput() callback. */
179054            if( xOutput 
179055             && rc==SQLITE_OK 
179056             && buf.nBuf>nNoop 
179057             && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE 
179058            ){
179059              rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
179060              nNoop = -1;
179061              buf.nBuf = 0;
179062            }
179063  
179064          }
179065        }
179066  
179067        sqlite3_finalize(pSel);
179068        if( buf.nBuf==nNoop ){
179069          buf.nBuf = nRewind;
179070        }
179071        sqlite3_free((char*)azCol);  /* cast works around VC++ bug */
179072      }
179073    }
179074  
179075    if( rc==SQLITE_OK ){
179076      if( xOutput==0 ){
179077        *pnChangeset = buf.nBuf;
179078        *ppChangeset = buf.aBuf;
179079        buf.aBuf = 0;
179080      }else if( buf.nBuf>0 ){
179081        rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
179082      }
179083    }
179084  
179085    sqlite3_free(buf.aBuf);
179086    sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
179087    sqlite3_mutex_leave(sqlite3_db_mutex(db));
179088    return rc;
179089  }
179090  
179091  /*
179092  ** Obtain a changeset object containing all changes recorded by the 
179093  ** session object passed as the first argument.
179094  **
179095  ** It is the responsibility of the caller to eventually free the buffer 
179096  ** using sqlite3_free().
179097  */
179098  SQLITE_API int sqlite3session_changeset(
179099    sqlite3_session *pSession,      /* Session object */
179100    int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
179101    void **ppChangeset              /* OUT: Buffer containing changeset */
179102  ){
179103    return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
179104  }
179105  
179106  /*
179107  ** Streaming version of sqlite3session_changeset().
179108  */
179109  SQLITE_API int sqlite3session_changeset_strm(
179110    sqlite3_session *pSession,
179111    int (*xOutput)(void *pOut, const void *pData, int nData),
179112    void *pOut
179113  ){
179114    return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
179115  }
179116  
179117  /*
179118  ** Streaming version of sqlite3session_patchset().
179119  */
179120  SQLITE_API int sqlite3session_patchset_strm(
179121    sqlite3_session *pSession,
179122    int (*xOutput)(void *pOut, const void *pData, int nData),
179123    void *pOut
179124  ){
179125    return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
179126  }
179127  
179128  /*
179129  ** Obtain a patchset object containing all changes recorded by the 
179130  ** session object passed as the first argument.
179131  **
179132  ** It is the responsibility of the caller to eventually free the buffer 
179133  ** using sqlite3_free().
179134  */
179135  SQLITE_API int sqlite3session_patchset(
179136    sqlite3_session *pSession,      /* Session object */
179137    int *pnPatchset,                /* OUT: Size of buffer at *ppChangeset */
179138    void **ppPatchset               /* OUT: Buffer containing changeset */
179139  ){
179140    return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
179141  }
179142  
179143  /*
179144  ** Enable or disable the session object passed as the first argument.
179145  */
179146  SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
179147    int ret;
179148    sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
179149    if( bEnable>=0 ){
179150      pSession->bEnable = bEnable;
179151    }
179152    ret = pSession->bEnable;
179153    sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
179154    return ret;
179155  }
179156  
179157  /*
179158  ** Enable or disable the session object passed as the first argument.
179159  */
179160  SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
179161    int ret;
179162    sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
179163    if( bIndirect>=0 ){
179164      pSession->bIndirect = bIndirect;
179165    }
179166    ret = pSession->bIndirect;
179167    sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
179168    return ret;
179169  }
179170  
179171  /*
179172  ** Return true if there have been no changes to monitored tables recorded
179173  ** by the session object passed as the only argument.
179174  */
179175  SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){
179176    int ret = 0;
179177    SessionTable *pTab;
179178  
179179    sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
179180    for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
179181      ret = (pTab->nEntry>0);
179182    }
179183    sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
179184  
179185    return (ret==0);
179186  }
179187  
179188  /*
179189  ** Do the work for either sqlite3changeset_start() or start_strm().
179190  */
179191  static int sessionChangesetStart(
179192    sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
179193    int (*xInput)(void *pIn, void *pData, int *pnData),
179194    void *pIn,
179195    int nChangeset,                 /* Size of buffer pChangeset in bytes */
179196    void *pChangeset                /* Pointer to buffer containing changeset */
179197  ){
179198    sqlite3_changeset_iter *pRet;   /* Iterator to return */
179199    int nByte;                      /* Number of bytes to allocate for iterator */
179200  
179201    assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
179202  
179203    /* Zero the output variable in case an error occurs. */
179204    *pp = 0;
179205  
179206    /* Allocate and initialize the iterator structure. */
179207    nByte = sizeof(sqlite3_changeset_iter);
179208    pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
179209    if( !pRet ) return SQLITE_NOMEM;
179210    memset(pRet, 0, sizeof(sqlite3_changeset_iter));
179211    pRet->in.aData = (u8 *)pChangeset;
179212    pRet->in.nData = nChangeset;
179213    pRet->in.xInput = xInput;
179214    pRet->in.pIn = pIn;
179215    pRet->in.bEof = (xInput ? 0 : 1);
179216  
179217    /* Populate the output variable and return success. */
179218    *pp = pRet;
179219    return SQLITE_OK;
179220  }
179221  
179222  /*
179223  ** Create an iterator used to iterate through the contents of a changeset.
179224  */
179225  SQLITE_API int sqlite3changeset_start(
179226    sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
179227    int nChangeset,                 /* Size of buffer pChangeset in bytes */
179228    void *pChangeset                /* Pointer to buffer containing changeset */
179229  ){
179230    return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset);
179231  }
179232  
179233  /*
179234  ** Streaming version of sqlite3changeset_start().
179235  */
179236  SQLITE_API int sqlite3changeset_start_strm(
179237    sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
179238    int (*xInput)(void *pIn, void *pData, int *pnData),
179239    void *pIn
179240  ){
179241    return sessionChangesetStart(pp, xInput, pIn, 0, 0);
179242  }
179243  
179244  /*
179245  ** If the SessionInput object passed as the only argument is a streaming
179246  ** object and the buffer is full, discard some data to free up space.
179247  */
179248  static void sessionDiscardData(SessionInput *pIn){
179249    if( pIn->bEof && pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){
179250      int nMove = pIn->buf.nBuf - pIn->iNext;
179251      assert( nMove>=0 );
179252      if( nMove>0 ){
179253        memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
179254      }
179255      pIn->buf.nBuf -= pIn->iNext;
179256      pIn->iNext = 0;
179257      pIn->nData = pIn->buf.nBuf;
179258    }
179259  }
179260  
179261  /*
179262  ** Ensure that there are at least nByte bytes available in the buffer. Or,
179263  ** if there are not nByte bytes remaining in the input, that all available
179264  ** data is in the buffer.
179265  **
179266  ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
179267  */
179268  static int sessionInputBuffer(SessionInput *pIn, int nByte){
179269    int rc = SQLITE_OK;
179270    if( pIn->xInput ){
179271      while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
179272        int nNew = SESSIONS_STRM_CHUNK_SIZE;
179273  
179274        if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
179275        if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
179276          rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
179277          if( nNew==0 ){
179278            pIn->bEof = 1;
179279          }else{
179280            pIn->buf.nBuf += nNew;
179281          }
179282        }
179283  
179284        pIn->aData = pIn->buf.aBuf;
179285        pIn->nData = pIn->buf.nBuf;
179286      }
179287    }
179288    return rc;
179289  }
179290  
179291  /*
179292  ** When this function is called, *ppRec points to the start of a record
179293  ** that contains nCol values. This function advances the pointer *ppRec
179294  ** until it points to the byte immediately following that record.
179295  */
179296  static void sessionSkipRecord(
179297    u8 **ppRec,                     /* IN/OUT: Record pointer */
179298    int nCol                        /* Number of values in record */
179299  ){
179300    u8 *aRec = *ppRec;
179301    int i;
179302    for(i=0; i<nCol; i++){
179303      int eType = *aRec++;
179304      if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
179305        int nByte;
179306        aRec += sessionVarintGet((u8*)aRec, &nByte);
179307        aRec += nByte;
179308      }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
179309        aRec += 8;
179310      }
179311    }
179312  
179313    *ppRec = aRec;
179314  }
179315  
179316  /*
179317  ** This function sets the value of the sqlite3_value object passed as the
179318  ** first argument to a copy of the string or blob held in the aData[] 
179319  ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
179320  ** error occurs.
179321  */
179322  static int sessionValueSetStr(
179323    sqlite3_value *pVal,            /* Set the value of this object */
179324    u8 *aData,                      /* Buffer containing string or blob data */
179325    int nData,                      /* Size of buffer aData[] in bytes */
179326    u8 enc                          /* String encoding (0 for blobs) */
179327  ){
179328    /* In theory this code could just pass SQLITE_TRANSIENT as the final
179329    ** argument to sqlite3ValueSetStr() and have the copy created 
179330    ** automatically. But doing so makes it difficult to detect any OOM
179331    ** error. Hence the code to create the copy externally. */
179332    u8 *aCopy = sqlite3_malloc(nData+1);
179333    if( aCopy==0 ) return SQLITE_NOMEM;
179334    memcpy(aCopy, aData, nData);
179335    sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
179336    return SQLITE_OK;
179337  }
179338  
179339  /*
179340  ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
179341  ** for details.
179342  **
179343  ** When this function is called, *paChange points to the start of the record
179344  ** to deserialize. Assuming no error occurs, *paChange is set to point to
179345  ** one byte after the end of the same record before this function returns.
179346  ** If the argument abPK is NULL, then the record contains nCol values. Or,
179347  ** if abPK is other than NULL, then the record contains only the PK fields
179348  ** (in other words, it is a patchset DELETE record).
179349  **
179350  ** If successful, each element of the apOut[] array (allocated by the caller)
179351  ** is set to point to an sqlite3_value object containing the value read
179352  ** from the corresponding position in the record. If that value is not
179353  ** included in the record (i.e. because the record is part of an UPDATE change
179354  ** and the field was not modified), the corresponding element of apOut[] is
179355  ** set to NULL.
179356  **
179357  ** It is the responsibility of the caller to free all sqlite_value structures
179358  ** using sqlite3_free().
179359  **
179360  ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
179361  ** The apOut[] array may have been partially populated in this case.
179362  */
179363  static int sessionReadRecord(
179364    SessionInput *pIn,              /* Input data */
179365    int nCol,                       /* Number of values in record */
179366    u8 *abPK,                       /* Array of primary key flags, or NULL */
179367    sqlite3_value **apOut           /* Write values to this array */
179368  ){
179369    int i;                          /* Used to iterate through columns */
179370    int rc = SQLITE_OK;
179371  
179372    for(i=0; i<nCol && rc==SQLITE_OK; i++){
179373      int eType = 0;                /* Type of value (SQLITE_NULL, TEXT etc.) */
179374      if( abPK && abPK[i]==0 ) continue;
179375      rc = sessionInputBuffer(pIn, 9);
179376      if( rc==SQLITE_OK ){
179377        eType = pIn->aData[pIn->iNext++];
179378      }
179379  
179380      assert( apOut[i]==0 );
179381      if( eType ){
179382        apOut[i] = sqlite3ValueNew(0);
179383        if( !apOut[i] ) rc = SQLITE_NOMEM;
179384      }
179385  
179386      if( rc==SQLITE_OK ){
179387        u8 *aVal = &pIn->aData[pIn->iNext];
179388        if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
179389          int nByte;
179390          pIn->iNext += sessionVarintGet(aVal, &nByte);
179391          rc = sessionInputBuffer(pIn, nByte);
179392          if( rc==SQLITE_OK ){
179393            u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
179394            rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
179395          }
179396          pIn->iNext += nByte;
179397        }
179398        if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
179399          sqlite3_int64 v = sessionGetI64(aVal);
179400          if( eType==SQLITE_INTEGER ){
179401            sqlite3VdbeMemSetInt64(apOut[i], v);
179402          }else{
179403            double d;
179404            memcpy(&d, &v, 8);
179405            sqlite3VdbeMemSetDouble(apOut[i], d);
179406          }
179407          pIn->iNext += 8;
179408        }
179409      }
179410    }
179411  
179412    return rc;
179413  }
179414  
179415  /*
179416  ** The input pointer currently points to the second byte of a table-header.
179417  ** Specifically, to the following:
179418  **
179419  **   + number of columns in table (varint)
179420  **   + array of PK flags (1 byte per column),
179421  **   + table name (nul terminated).
179422  **
179423  ** This function ensures that all of the above is present in the input 
179424  ** buffer (i.e. that it can be accessed without any calls to xInput()).
179425  ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
179426  ** The input pointer is not moved.
179427  */
179428  static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
179429    int rc = SQLITE_OK;
179430    int nCol = 0;
179431    int nRead = 0;
179432  
179433    rc = sessionInputBuffer(pIn, 9);
179434    if( rc==SQLITE_OK ){
179435      nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
179436      rc = sessionInputBuffer(pIn, nRead+nCol+100);
179437      nRead += nCol;
179438    }
179439  
179440    while( rc==SQLITE_OK ){
179441      while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
179442        nRead++;
179443      }
179444      if( (pIn->iNext + nRead)<pIn->nData ) break;
179445      rc = sessionInputBuffer(pIn, nRead + 100);
179446    }
179447    *pnByte = nRead+1;
179448    return rc;
179449  }
179450  
179451  /*
179452  ** The input pointer currently points to the first byte of the first field
179453  ** of a record consisting of nCol columns. This function ensures the entire
179454  ** record is buffered. It does not move the input pointer.
179455  **
179456  ** If successful, SQLITE_OK is returned and *pnByte is set to the size of
179457  ** the record in bytes. Otherwise, an SQLite error code is returned. The
179458  ** final value of *pnByte is undefined in this case.
179459  */
179460  static int sessionChangesetBufferRecord(
179461    SessionInput *pIn,              /* Input data */
179462    int nCol,                       /* Number of columns in record */
179463    int *pnByte                     /* OUT: Size of record in bytes */
179464  ){
179465    int rc = SQLITE_OK;
179466    int nByte = 0;
179467    int i;
179468    for(i=0; rc==SQLITE_OK && i<nCol; i++){
179469      int eType;
179470      rc = sessionInputBuffer(pIn, nByte + 10);
179471      if( rc==SQLITE_OK ){
179472        eType = pIn->aData[pIn->iNext + nByte++];
179473        if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
179474          int n;
179475          nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
179476          nByte += n;
179477          rc = sessionInputBuffer(pIn, nByte);
179478        }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
179479          nByte += 8;
179480        }
179481      }
179482    }
179483    *pnByte = nByte;
179484    return rc;
179485  }
179486  
179487  /*
179488  ** The input pointer currently points to the second byte of a table-header.
179489  ** Specifically, to the following:
179490  **
179491  **   + number of columns in table (varint)
179492  **   + array of PK flags (1 byte per column),
179493  **   + table name (nul terminated).
179494  **
179495  ** This function decodes the table-header and populates the p->nCol, 
179496  ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is 
179497  ** also allocated or resized according to the new value of p->nCol. The
179498  ** input pointer is left pointing to the byte following the table header.
179499  **
179500  ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
179501  ** is returned and the final values of the various fields enumerated above
179502  ** are undefined.
179503  */
179504  static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
179505    int rc;
179506    int nCopy;
179507    assert( p->rc==SQLITE_OK );
179508  
179509    rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
179510    if( rc==SQLITE_OK ){
179511      int nByte;
179512      int nVarint;
179513      nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
179514      nCopy -= nVarint;
179515      p->in.iNext += nVarint;
179516      nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
179517      p->tblhdr.nBuf = 0;
179518      sessionBufferGrow(&p->tblhdr, nByte, &rc);
179519    }
179520  
179521    if( rc==SQLITE_OK ){
179522      int iPK = sizeof(sqlite3_value*)*p->nCol*2;
179523      memset(p->tblhdr.aBuf, 0, iPK);
179524      memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
179525      p->in.iNext += nCopy;
179526    }
179527  
179528    p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
179529    p->abPK = (u8*)&p->apValue[p->nCol*2];
179530    p->zTab = (char*)&p->abPK[p->nCol];
179531    return (p->rc = rc);
179532  }
179533  
179534  /*
179535  ** Advance the changeset iterator to the next change.
179536  **
179537  ** If both paRec and pnRec are NULL, then this function works like the public
179538  ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
179539  ** sqlite3changeset_new() and old() APIs may be used to query for values.
179540  **
179541  ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
179542  ** record is written to *paRec before returning and the number of bytes in
179543  ** the record to *pnRec.
179544  **
179545  ** Either way, this function returns SQLITE_ROW if the iterator is 
179546  ** successfully advanced to the next change in the changeset, an SQLite 
179547  ** error code if an error occurs, or SQLITE_DONE if there are no further 
179548  ** changes in the changeset.
179549  */
179550  static int sessionChangesetNext(
179551    sqlite3_changeset_iter *p,      /* Changeset iterator */
179552    u8 **paRec,                     /* If non-NULL, store record pointer here */
179553    int *pnRec                      /* If non-NULL, store size of record here */
179554  ){
179555    int i;
179556    u8 op;
179557  
179558    assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
179559  
179560    /* If the iterator is in the error-state, return immediately. */
179561    if( p->rc!=SQLITE_OK ) return p->rc;
179562  
179563    /* Free the current contents of p->apValue[], if any. */
179564    if( p->apValue ){
179565      for(i=0; i<p->nCol*2; i++){
179566        sqlite3ValueFree(p->apValue[i]);
179567      }
179568      memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
179569    }
179570  
179571    /* Make sure the buffer contains at least 10 bytes of input data, or all
179572    ** remaining data if there are less than 10 bytes available. This is
179573    ** sufficient either for the 'T' or 'P' byte and the varint that follows
179574    ** it, or for the two single byte values otherwise. */
179575    p->rc = sessionInputBuffer(&p->in, 2);
179576    if( p->rc!=SQLITE_OK ) return p->rc;
179577  
179578    /* If the iterator is already at the end of the changeset, return DONE. */
179579    if( p->in.iNext>=p->in.nData ){
179580      return SQLITE_DONE;
179581    }
179582  
179583    sessionDiscardData(&p->in);
179584    p->in.iCurrent = p->in.iNext;
179585  
179586    op = p->in.aData[p->in.iNext++];
179587    while( op=='T' || op=='P' ){
179588      p->bPatchset = (op=='P');
179589      if( sessionChangesetReadTblhdr(p) ) return p->rc;
179590      if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
179591      p->in.iCurrent = p->in.iNext;
179592      if( p->in.iNext>=p->in.nData ) return SQLITE_DONE;
179593      op = p->in.aData[p->in.iNext++];
179594    }
179595  
179596    p->op = op;
179597    p->bIndirect = p->in.aData[p->in.iNext++];
179598    if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
179599      return (p->rc = SQLITE_CORRUPT_BKPT);
179600    }
179601  
179602    if( paRec ){ 
179603      int nVal;                     /* Number of values to buffer */
179604      if( p->bPatchset==0 && op==SQLITE_UPDATE ){
179605        nVal = p->nCol * 2;
179606      }else if( p->bPatchset && op==SQLITE_DELETE ){
179607        nVal = 0;
179608        for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
179609      }else{
179610        nVal = p->nCol;
179611      }
179612      p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
179613      if( p->rc!=SQLITE_OK ) return p->rc;
179614      *paRec = &p->in.aData[p->in.iNext];
179615      p->in.iNext += *pnRec;
179616    }else{
179617  
179618      /* If this is an UPDATE or DELETE, read the old.* record. */
179619      if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
179620        u8 *abPK = p->bPatchset ? p->abPK : 0;
179621        p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue);
179622        if( p->rc!=SQLITE_OK ) return p->rc;
179623      }
179624  
179625      /* If this is an INSERT or UPDATE, read the new.* record. */
179626      if( p->op!=SQLITE_DELETE ){
179627        p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]);
179628        if( p->rc!=SQLITE_OK ) return p->rc;
179629      }
179630  
179631      if( p->bPatchset && p->op==SQLITE_UPDATE ){
179632        /* If this is an UPDATE that is part of a patchset, then all PK and
179633        ** modified fields are present in the new.* record. The old.* record
179634        ** is currently completely empty. This block shifts the PK fields from
179635        ** new.* to old.*, to accommodate the code that reads these arrays.  */
179636        for(i=0; i<p->nCol; i++){
179637          assert( p->apValue[i]==0 );
179638          assert( p->abPK[i]==0 || p->apValue[i+p->nCol] );
179639          if( p->abPK[i] ){
179640            p->apValue[i] = p->apValue[i+p->nCol];
179641            p->apValue[i+p->nCol] = 0;
179642          }
179643        }
179644      }
179645    }
179646  
179647    return SQLITE_ROW;
179648  }
179649  
179650  /*
179651  ** Advance an iterator created by sqlite3changeset_start() to the next
179652  ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
179653  ** or SQLITE_CORRUPT.
179654  **
179655  ** This function may not be called on iterators passed to a conflict handler
179656  ** callback by changeset_apply().
179657  */
179658  SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){
179659    return sessionChangesetNext(p, 0, 0);
179660  }
179661  
179662  /*
179663  ** The following function extracts information on the current change
179664  ** from a changeset iterator. It may only be called after changeset_next()
179665  ** has returned SQLITE_ROW.
179666  */
179667  SQLITE_API int sqlite3changeset_op(
179668    sqlite3_changeset_iter *pIter,  /* Iterator handle */
179669    const char **pzTab,             /* OUT: Pointer to table name */
179670    int *pnCol,                     /* OUT: Number of columns in table */
179671    int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */
179672    int *pbIndirect                 /* OUT: True if change is indirect */
179673  ){
179674    *pOp = pIter->op;
179675    *pnCol = pIter->nCol;
179676    *pzTab = pIter->zTab;
179677    if( pbIndirect ) *pbIndirect = pIter->bIndirect;
179678    return SQLITE_OK;
179679  }
179680  
179681  /*
179682  ** Return information regarding the PRIMARY KEY and number of columns in
179683  ** the database table affected by the change that pIter currently points
179684  ** to. This function may only be called after changeset_next() returns
179685  ** SQLITE_ROW.
179686  */
179687  SQLITE_API int sqlite3changeset_pk(
179688    sqlite3_changeset_iter *pIter,  /* Iterator object */
179689    unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */
179690    int *pnCol                      /* OUT: Number of entries in output array */
179691  ){
179692    *pabPK = pIter->abPK;
179693    if( pnCol ) *pnCol = pIter->nCol;
179694    return SQLITE_OK;
179695  }
179696  
179697  /*
179698  ** This function may only be called while the iterator is pointing to an
179699  ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
179700  ** Otherwise, SQLITE_MISUSE is returned.
179701  **
179702  ** It sets *ppValue to point to an sqlite3_value structure containing the
179703  ** iVal'th value in the old.* record. Or, if that particular value is not
179704  ** included in the record (because the change is an UPDATE and the field
179705  ** was not modified and is not a PK column), set *ppValue to NULL.
179706  **
179707  ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
179708  ** not modified. Otherwise, SQLITE_OK.
179709  */
179710  SQLITE_API int sqlite3changeset_old(
179711    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
179712    int iVal,                       /* Index of old.* value to retrieve */
179713    sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */
179714  ){
179715    if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
179716      return SQLITE_MISUSE;
179717    }
179718    if( iVal<0 || iVal>=pIter->nCol ){
179719      return SQLITE_RANGE;
179720    }
179721    *ppValue = pIter->apValue[iVal];
179722    return SQLITE_OK;
179723  }
179724  
179725  /*
179726  ** This function may only be called while the iterator is pointing to an
179727  ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
179728  ** Otherwise, SQLITE_MISUSE is returned.
179729  **
179730  ** It sets *ppValue to point to an sqlite3_value structure containing the
179731  ** iVal'th value in the new.* record. Or, if that particular value is not
179732  ** included in the record (because the change is an UPDATE and the field
179733  ** was not modified), set *ppValue to NULL.
179734  **
179735  ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
179736  ** not modified. Otherwise, SQLITE_OK.
179737  */
179738  SQLITE_API int sqlite3changeset_new(
179739    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
179740    int iVal,                       /* Index of new.* value to retrieve */
179741    sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */
179742  ){
179743    if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
179744      return SQLITE_MISUSE;
179745    }
179746    if( iVal<0 || iVal>=pIter->nCol ){
179747      return SQLITE_RANGE;
179748    }
179749    *ppValue = pIter->apValue[pIter->nCol+iVal];
179750    return SQLITE_OK;
179751  }
179752  
179753  /*
179754  ** The following two macros are used internally. They are similar to the
179755  ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
179756  ** they omit all error checking and return a pointer to the requested value.
179757  */
179758  #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
179759  #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
179760  
179761  /*
179762  ** This function may only be called with a changeset iterator that has been
179763  ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT 
179764  ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
179765  **
179766  ** If successful, *ppValue is set to point to an sqlite3_value structure
179767  ** containing the iVal'th value of the conflicting record.
179768  **
179769  ** If value iVal is out-of-range or some other error occurs, an SQLite error
179770  ** code is returned. Otherwise, SQLITE_OK.
179771  */
179772  SQLITE_API int sqlite3changeset_conflict(
179773    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
179774    int iVal,                       /* Index of conflict record value to fetch */
179775    sqlite3_value **ppValue         /* OUT: Value from conflicting row */
179776  ){
179777    if( !pIter->pConflict ){
179778      return SQLITE_MISUSE;
179779    }
179780    if( iVal<0 || iVal>=pIter->nCol ){
179781      return SQLITE_RANGE;
179782    }
179783    *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
179784    return SQLITE_OK;
179785  }
179786  
179787  /*
179788  ** This function may only be called with an iterator passed to an
179789  ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
179790  ** it sets the output variable to the total number of known foreign key
179791  ** violations in the destination database and returns SQLITE_OK.
179792  **
179793  ** In all other cases this function returns SQLITE_MISUSE.
179794  */
179795  SQLITE_API int sqlite3changeset_fk_conflicts(
179796    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
179797    int *pnOut                      /* OUT: Number of FK violations */
179798  ){
179799    if( pIter->pConflict || pIter->apValue ){
179800      return SQLITE_MISUSE;
179801    }
179802    *pnOut = pIter->nCol;
179803    return SQLITE_OK;
179804  }
179805  
179806  
179807  /*
179808  ** Finalize an iterator allocated with sqlite3changeset_start().
179809  **
179810  ** This function may not be called on iterators passed to a conflict handler
179811  ** callback by changeset_apply().
179812  */
179813  SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
179814    int rc = SQLITE_OK;
179815    if( p ){
179816      int i;                        /* Used to iterate through p->apValue[] */
179817      rc = p->rc;
179818      if( p->apValue ){
179819        for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
179820      }
179821      sqlite3_free(p->tblhdr.aBuf);
179822      sqlite3_free(p->in.buf.aBuf);
179823      sqlite3_free(p);
179824    }
179825    return rc;
179826  }
179827  
179828  static int sessionChangesetInvert(
179829    SessionInput *pInput,           /* Input changeset */
179830    int (*xOutput)(void *pOut, const void *pData, int nData),
179831    void *pOut,
179832    int *pnInverted,                /* OUT: Number of bytes in output changeset */
179833    void **ppInverted               /* OUT: Inverse of pChangeset */
179834  ){
179835    int rc = SQLITE_OK;             /* Return value */
179836    SessionBuffer sOut;             /* Output buffer */
179837    int nCol = 0;                   /* Number of cols in current table */
179838    u8 *abPK = 0;                   /* PK array for current table */
179839    sqlite3_value **apVal = 0;      /* Space for values for UPDATE inversion */
179840    SessionBuffer sPK = {0, 0, 0};  /* PK array for current table */
179841  
179842    /* Initialize the output buffer */
179843    memset(&sOut, 0, sizeof(SessionBuffer));
179844  
179845    /* Zero the output variables in case an error occurs. */
179846    if( ppInverted ){
179847      *ppInverted = 0;
179848      *pnInverted = 0;
179849    }
179850  
179851    while( 1 ){
179852      u8 eType;
179853  
179854      /* Test for EOF. */
179855      if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
179856      if( pInput->iNext>=pInput->nData ) break;
179857      eType = pInput->aData[pInput->iNext];
179858  
179859      switch( eType ){
179860        case 'T': {
179861          /* A 'table' record consists of:
179862          **
179863          **   * A constant 'T' character,
179864          **   * Number of columns in said table (a varint),
179865          **   * An array of nCol bytes (sPK),
179866          **   * A nul-terminated table name.
179867          */
179868          int nByte;
179869          int nVar;
179870          pInput->iNext++;
179871          if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
179872            goto finished_invert;
179873          }
179874          nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
179875          sPK.nBuf = 0;
179876          sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
179877          sessionAppendByte(&sOut, eType, &rc);
179878          sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
179879          if( rc ) goto finished_invert;
179880  
179881          pInput->iNext += nByte;
179882          sqlite3_free(apVal);
179883          apVal = 0;
179884          abPK = sPK.aBuf;
179885          break;
179886        }
179887  
179888        case SQLITE_INSERT:
179889        case SQLITE_DELETE: {
179890          int nByte;
179891          int bIndirect = pInput->aData[pInput->iNext+1];
179892          int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
179893          pInput->iNext += 2;
179894          assert( rc==SQLITE_OK );
179895          rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
179896          sessionAppendByte(&sOut, eType2, &rc);
179897          sessionAppendByte(&sOut, bIndirect, &rc);
179898          sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
179899          pInput->iNext += nByte;
179900          if( rc ) goto finished_invert;
179901          break;
179902        }
179903  
179904        case SQLITE_UPDATE: {
179905          int iCol;
179906  
179907          if( 0==apVal ){
179908            apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
179909            if( 0==apVal ){
179910              rc = SQLITE_NOMEM;
179911              goto finished_invert;
179912            }
179913            memset(apVal, 0, sizeof(apVal[0])*nCol*2);
179914          }
179915  
179916          /* Write the header for the new UPDATE change. Same as the original. */
179917          sessionAppendByte(&sOut, eType, &rc);
179918          sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
179919  
179920          /* Read the old.* and new.* records for the update change. */
179921          pInput->iNext += 2;
179922          rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
179923          if( rc==SQLITE_OK ){
179924            rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
179925          }
179926  
179927          /* Write the new old.* record. Consists of the PK columns from the
179928          ** original old.* record, and the other values from the original
179929          ** new.* record. */
179930          for(iCol=0; iCol<nCol; iCol++){
179931            sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
179932            sessionAppendValue(&sOut, pVal, &rc);
179933          }
179934  
179935          /* Write the new new.* record. Consists of a copy of all values
179936          ** from the original old.* record, except for the PK columns, which
179937          ** are set to "undefined". */
179938          for(iCol=0; iCol<nCol; iCol++){
179939            sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
179940            sessionAppendValue(&sOut, pVal, &rc);
179941          }
179942  
179943          for(iCol=0; iCol<nCol*2; iCol++){
179944            sqlite3ValueFree(apVal[iCol]);
179945          }
179946          memset(apVal, 0, sizeof(apVal[0])*nCol*2);
179947          if( rc!=SQLITE_OK ){
179948            goto finished_invert;
179949          }
179950  
179951          break;
179952        }
179953  
179954        default:
179955          rc = SQLITE_CORRUPT_BKPT;
179956          goto finished_invert;
179957      }
179958  
179959      assert( rc==SQLITE_OK );
179960      if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
179961        rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
179962        sOut.nBuf = 0;
179963        if( rc!=SQLITE_OK ) goto finished_invert;
179964      }
179965    }
179966  
179967    assert( rc==SQLITE_OK );
179968    if( pnInverted ){
179969      *pnInverted = sOut.nBuf;
179970      *ppInverted = sOut.aBuf;
179971      sOut.aBuf = 0;
179972    }else if( sOut.nBuf>0 ){
179973      rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
179974    }
179975  
179976   finished_invert:
179977    sqlite3_free(sOut.aBuf);
179978    sqlite3_free(apVal);
179979    sqlite3_free(sPK.aBuf);
179980    return rc;
179981  }
179982  
179983  
179984  /*
179985  ** Invert a changeset object.
179986  */
179987  SQLITE_API int sqlite3changeset_invert(
179988    int nChangeset,                 /* Number of bytes in input */
179989    const void *pChangeset,         /* Input changeset */
179990    int *pnInverted,                /* OUT: Number of bytes in output changeset */
179991    void **ppInverted               /* OUT: Inverse of pChangeset */
179992  ){
179993    SessionInput sInput;
179994  
179995    /* Set up the input stream */
179996    memset(&sInput, 0, sizeof(SessionInput));
179997    sInput.nData = nChangeset;
179998    sInput.aData = (u8*)pChangeset;
179999  
180000    return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
180001  }
180002  
180003  /*
180004  ** Streaming version of sqlite3changeset_invert().
180005  */
180006  SQLITE_API int sqlite3changeset_invert_strm(
180007    int (*xInput)(void *pIn, void *pData, int *pnData),
180008    void *pIn,
180009    int (*xOutput)(void *pOut, const void *pData, int nData),
180010    void *pOut
180011  ){
180012    SessionInput sInput;
180013    int rc;
180014  
180015    /* Set up the input stream */
180016    memset(&sInput, 0, sizeof(SessionInput));
180017    sInput.xInput = xInput;
180018    sInput.pIn = pIn;
180019  
180020    rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
180021    sqlite3_free(sInput.buf.aBuf);
180022    return rc;
180023  }
180024  
180025  typedef struct SessionApplyCtx SessionApplyCtx;
180026  struct SessionApplyCtx {
180027    sqlite3 *db;
180028    sqlite3_stmt *pDelete;          /* DELETE statement */
180029    sqlite3_stmt *pUpdate;          /* UPDATE statement */
180030    sqlite3_stmt *pInsert;          /* INSERT statement */
180031    sqlite3_stmt *pSelect;          /* SELECT statement */
180032    int nCol;                       /* Size of azCol[] and abPK[] arrays */
180033    const char **azCol;             /* Array of column names */
180034    u8 *abPK;                       /* Boolean array - true if column is in PK */
180035  
180036    int bDeferConstraints;          /* True to defer constraints */
180037    SessionBuffer constraints;      /* Deferred constraints are stored here */
180038  };
180039  
180040  /*
180041  ** Formulate a statement to DELETE a row from database db. Assuming a table
180042  ** structure like this:
180043  **
180044  **     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
180045  **
180046  ** The DELETE statement looks like this:
180047  **
180048  **     DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
180049  **
180050  ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
180051  ** matching b and d values, or 1 otherwise. The second case comes up if the
180052  ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
180053  **
180054  ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
180055  ** pointing to the prepared version of the SQL statement.
180056  */
180057  static int sessionDeleteRow(
180058    sqlite3 *db,                    /* Database handle */
180059    const char *zTab,               /* Table name */
180060    SessionApplyCtx *p              /* Session changeset-apply context */
180061  ){
180062    int i;
180063    const char *zSep = "";
180064    int rc = SQLITE_OK;
180065    SessionBuffer buf = {0, 0, 0};
180066    int nPk = 0;
180067  
180068    sessionAppendStr(&buf, "DELETE FROM ", &rc);
180069    sessionAppendIdent(&buf, zTab, &rc);
180070    sessionAppendStr(&buf, " WHERE ", &rc);
180071  
180072    for(i=0; i<p->nCol; i++){
180073      if( p->abPK[i] ){
180074        nPk++;
180075        sessionAppendStr(&buf, zSep, &rc);
180076        sessionAppendIdent(&buf, p->azCol[i], &rc);
180077        sessionAppendStr(&buf, " = ?", &rc);
180078        sessionAppendInteger(&buf, i+1, &rc);
180079        zSep = " AND ";
180080      }
180081    }
180082  
180083    if( nPk<p->nCol ){
180084      sessionAppendStr(&buf, " AND (?", &rc);
180085      sessionAppendInteger(&buf, p->nCol+1, &rc);
180086      sessionAppendStr(&buf, " OR ", &rc);
180087  
180088      zSep = "";
180089      for(i=0; i<p->nCol; i++){
180090        if( !p->abPK[i] ){
180091          sessionAppendStr(&buf, zSep, &rc);
180092          sessionAppendIdent(&buf, p->azCol[i], &rc);
180093          sessionAppendStr(&buf, " IS ?", &rc);
180094          sessionAppendInteger(&buf, i+1, &rc);
180095          zSep = "AND ";
180096        }
180097      }
180098      sessionAppendStr(&buf, ")", &rc);
180099    }
180100  
180101    if( rc==SQLITE_OK ){
180102      rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
180103    }
180104    sqlite3_free(buf.aBuf);
180105  
180106    return rc;
180107  }
180108  
180109  /*
180110  ** Formulate and prepare a statement to UPDATE a row from database db. 
180111  ** Assuming a table structure like this:
180112  **
180113  **     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
180114  **
180115  ** The UPDATE statement looks like this:
180116  **
180117  **     UPDATE x SET
180118  **     a = CASE WHEN ?2  THEN ?3  ELSE a END,
180119  **     b = CASE WHEN ?5  THEN ?6  ELSE b END,
180120  **     c = CASE WHEN ?8  THEN ?9  ELSE c END,
180121  **     d = CASE WHEN ?11 THEN ?12 ELSE d END
180122  **     WHERE a = ?1 AND c = ?7 AND (?13 OR 
180123  **       (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
180124  **     )
180125  **
180126  ** For each column in the table, there are three variables to bind:
180127  **
180128  **     ?(i*3+1)    The old.* value of the column, if any.
180129  **     ?(i*3+2)    A boolean flag indicating that the value is being modified.
180130  **     ?(i*3+3)    The new.* value of the column, if any.
180131  **
180132  ** Also, a boolean flag that, if set to true, causes the statement to update
180133  ** a row even if the non-PK values do not match. This is required if the
180134  ** conflict-handler is invoked with CHANGESET_DATA and returns
180135  ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
180136  **
180137  ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
180138  ** pointing to the prepared version of the SQL statement.
180139  */
180140  static int sessionUpdateRow(
180141    sqlite3 *db,                    /* Database handle */
180142    const char *zTab,               /* Table name */
180143    SessionApplyCtx *p              /* Session changeset-apply context */
180144  ){
180145    int rc = SQLITE_OK;
180146    int i;
180147    const char *zSep = "";
180148    SessionBuffer buf = {0, 0, 0};
180149  
180150    /* Append "UPDATE tbl SET " */
180151    sessionAppendStr(&buf, "UPDATE ", &rc);
180152    sessionAppendIdent(&buf, zTab, &rc);
180153    sessionAppendStr(&buf, " SET ", &rc);
180154  
180155    /* Append the assignments */
180156    for(i=0; i<p->nCol; i++){
180157      sessionAppendStr(&buf, zSep, &rc);
180158      sessionAppendIdent(&buf, p->azCol[i], &rc);
180159      sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
180160      sessionAppendInteger(&buf, i*3+2, &rc);
180161      sessionAppendStr(&buf, " THEN ?", &rc);
180162      sessionAppendInteger(&buf, i*3+3, &rc);
180163      sessionAppendStr(&buf, " ELSE ", &rc);
180164      sessionAppendIdent(&buf, p->azCol[i], &rc);
180165      sessionAppendStr(&buf, " END", &rc);
180166      zSep = ", ";
180167    }
180168  
180169    /* Append the PK part of the WHERE clause */
180170    sessionAppendStr(&buf, " WHERE ", &rc);
180171    for(i=0; i<p->nCol; i++){
180172      if( p->abPK[i] ){
180173        sessionAppendIdent(&buf, p->azCol[i], &rc);
180174        sessionAppendStr(&buf, " = ?", &rc);
180175        sessionAppendInteger(&buf, i*3+1, &rc);
180176        sessionAppendStr(&buf, " AND ", &rc);
180177      }
180178    }
180179  
180180    /* Append the non-PK part of the WHERE clause */
180181    sessionAppendStr(&buf, " (?", &rc);
180182    sessionAppendInteger(&buf, p->nCol*3+1, &rc);
180183    sessionAppendStr(&buf, " OR 1", &rc);
180184    for(i=0; i<p->nCol; i++){
180185      if( !p->abPK[i] ){
180186        sessionAppendStr(&buf, " AND (?", &rc);
180187        sessionAppendInteger(&buf, i*3+2, &rc);
180188        sessionAppendStr(&buf, "=0 OR ", &rc);
180189        sessionAppendIdent(&buf, p->azCol[i], &rc);
180190        sessionAppendStr(&buf, " IS ?", &rc);
180191        sessionAppendInteger(&buf, i*3+1, &rc);
180192        sessionAppendStr(&buf, ")", &rc);
180193      }
180194    }
180195    sessionAppendStr(&buf, ")", &rc);
180196  
180197    if( rc==SQLITE_OK ){
180198      rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
180199    }
180200    sqlite3_free(buf.aBuf);
180201  
180202    return rc;
180203  }
180204  
180205  /*
180206  ** Formulate and prepare an SQL statement to query table zTab by primary
180207  ** key. Assuming the following table structure:
180208  **
180209  **     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
180210  **
180211  ** The SELECT statement looks like this:
180212  **
180213  **     SELECT * FROM x WHERE a = ?1 AND c = ?3
180214  **
180215  ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
180216  ** pointing to the prepared version of the SQL statement.
180217  */
180218  static int sessionSelectRow(
180219    sqlite3 *db,                    /* Database handle */
180220    const char *zTab,               /* Table name */
180221    SessionApplyCtx *p              /* Session changeset-apply context */
180222  ){
180223    return sessionSelectStmt(
180224        db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
180225  }
180226  
180227  /*
180228  ** Formulate and prepare an INSERT statement to add a record to table zTab.
180229  ** For example:
180230  **
180231  **     INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
180232  **
180233  ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
180234  ** pointing to the prepared version of the SQL statement.
180235  */
180236  static int sessionInsertRow(
180237    sqlite3 *db,                    /* Database handle */
180238    const char *zTab,               /* Table name */
180239    SessionApplyCtx *p              /* Session changeset-apply context */
180240  ){
180241    int rc = SQLITE_OK;
180242    int i;
180243    SessionBuffer buf = {0, 0, 0};
180244  
180245    sessionAppendStr(&buf, "INSERT INTO main.", &rc);
180246    sessionAppendIdent(&buf, zTab, &rc);
180247    sessionAppendStr(&buf, "(", &rc);
180248    for(i=0; i<p->nCol; i++){
180249      if( i!=0 ) sessionAppendStr(&buf, ", ", &rc);
180250      sessionAppendIdent(&buf, p->azCol[i], &rc);
180251    }
180252  
180253    sessionAppendStr(&buf, ") VALUES(?", &rc);
180254    for(i=1; i<p->nCol; i++){
180255      sessionAppendStr(&buf, ", ?", &rc);
180256    }
180257    sessionAppendStr(&buf, ")", &rc);
180258  
180259    if( rc==SQLITE_OK ){
180260      rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
180261    }
180262    sqlite3_free(buf.aBuf);
180263    return rc;
180264  }
180265  
180266  /*
180267  ** A wrapper around sqlite3_bind_value() that detects an extra problem. 
180268  ** See comments in the body of this function for details.
180269  */
180270  static int sessionBindValue(
180271    sqlite3_stmt *pStmt,            /* Statement to bind value to */
180272    int i,                          /* Parameter number to bind to */
180273    sqlite3_value *pVal             /* Value to bind */
180274  ){
180275    int eType = sqlite3_value_type(pVal);
180276    /* COVERAGE: The (pVal->z==0) branch is never true using current versions
180277    ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
180278    ** the (pVal->z) variable remains as it was or the type of the value is
180279    ** set to SQLITE_NULL.  */
180280    if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
180281      /* This condition occurs when an earlier OOM in a call to
180282      ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
180283      ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
180284      return SQLITE_NOMEM;
180285    }
180286    return sqlite3_bind_value(pStmt, i, pVal);
180287  }
180288  
180289  /*
180290  ** Iterator pIter must point to an SQLITE_INSERT entry. This function 
180291  ** transfers new.* values from the current iterator entry to statement
180292  ** pStmt. The table being inserted into has nCol columns.
180293  **
180294  ** New.* value $i from the iterator is bound to variable ($i+1) of 
180295  ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
180296  ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
180297  ** to an array nCol elements in size. In this case only those values for 
180298  ** which abPK[$i] is true are read from the iterator and bound to the 
180299  ** statement.
180300  **
180301  ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
180302  */
180303  static int sessionBindRow(
180304    sqlite3_changeset_iter *pIter,  /* Iterator to read values from */
180305    int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
180306    int nCol,                       /* Number of columns */
180307    u8 *abPK,                       /* If not NULL, bind only if true */
180308    sqlite3_stmt *pStmt             /* Bind values to this statement */
180309  ){
180310    int i;
180311    int rc = SQLITE_OK;
180312  
180313    /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
180314    ** argument iterator points to a suitable entry. Make sure that xValue 
180315    ** is one of these to guarantee that it is safe to ignore the return 
180316    ** in the code below. */
180317    assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
180318  
180319    for(i=0; rc==SQLITE_OK && i<nCol; i++){
180320      if( !abPK || abPK[i] ){
180321        sqlite3_value *pVal;
180322        (void)xValue(pIter, i, &pVal);
180323        rc = sessionBindValue(pStmt, i+1, pVal);
180324      }
180325    }
180326    return rc;
180327  }
180328  
180329  /*
180330  ** SQL statement pSelect is as generated by the sessionSelectRow() function.
180331  ** This function binds the primary key values from the change that changeset
180332  ** iterator pIter points to to the SELECT and attempts to seek to the table
180333  ** entry. If a row is found, the SELECT statement left pointing at the row 
180334  ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
180335  ** has occured, the statement is reset and SQLITE_OK is returned. If an
180336  ** error occurs, the statement is reset and an SQLite error code is returned.
180337  **
180338  ** If this function returns SQLITE_ROW, the caller must eventually reset() 
180339  ** statement pSelect. If any other value is returned, the statement does
180340  ** not require a reset().
180341  **
180342  ** If the iterator currently points to an INSERT record, bind values from the
180343  ** new.* record to the SELECT statement. Or, if it points to a DELETE or
180344  ** UPDATE, bind values from the old.* record. 
180345  */
180346  static int sessionSeekToRow(
180347    sqlite3 *db,                    /* Database handle */
180348    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
180349    u8 *abPK,                       /* Primary key flags array */
180350    sqlite3_stmt *pSelect           /* SELECT statement from sessionSelectRow() */
180351  ){
180352    int rc;                         /* Return code */
180353    int nCol;                       /* Number of columns in table */
180354    int op;                         /* Changset operation (SQLITE_UPDATE etc.) */
180355    const char *zDummy;             /* Unused */
180356  
180357    sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
180358    rc = sessionBindRow(pIter, 
180359        op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
180360        nCol, abPK, pSelect
180361    );
180362  
180363    if( rc==SQLITE_OK ){
180364      rc = sqlite3_step(pSelect);
180365      if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
180366    }
180367  
180368    return rc;
180369  }
180370  
180371  /*
180372  ** Invoke the conflict handler for the change that the changeset iterator
180373  ** currently points to.
180374  **
180375  ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
180376  ** If argument pbReplace is NULL, then the type of conflict handler invoked
180377  ** depends solely on eType, as follows:
180378  **
180379  **    eType value                 Value passed to xConflict
180380  **    -------------------------------------------------
180381  **    CHANGESET_DATA              CHANGESET_NOTFOUND
180382  **    CHANGESET_CONFLICT          CHANGESET_CONSTRAINT
180383  **
180384  ** Or, if pbReplace is not NULL, then an attempt is made to find an existing
180385  ** record with the same primary key as the record about to be deleted, updated
180386  ** or inserted. If such a record can be found, it is available to the conflict
180387  ** handler as the "conflicting" record. In this case the type of conflict
180388  ** handler invoked is as follows:
180389  **
180390  **    eType value         PK Record found?   Value passed to xConflict
180391  **    ----------------------------------------------------------------
180392  **    CHANGESET_DATA      Yes                CHANGESET_DATA
180393  **    CHANGESET_DATA      No                 CHANGESET_NOTFOUND
180394  **    CHANGESET_CONFLICT  Yes                CHANGESET_CONFLICT
180395  **    CHANGESET_CONFLICT  No                 CHANGESET_CONSTRAINT
180396  **
180397  ** If pbReplace is not NULL, and a record with a matching PK is found, and
180398  ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
180399  ** is set to non-zero before returning SQLITE_OK.
180400  **
180401  ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
180402  ** returned. Or, if the conflict handler returns an invalid value, 
180403  ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
180404  ** this function returns SQLITE_OK.
180405  */
180406  static int sessionConflictHandler(
180407    int eType,                      /* Either CHANGESET_DATA or CONFLICT */
180408    SessionApplyCtx *p,             /* changeset_apply() context */
180409    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
180410    int(*xConflict)(void *, int, sqlite3_changeset_iter*),
180411    void *pCtx,                     /* First argument for conflict handler */
180412    int *pbReplace                  /* OUT: Set to true if PK row is found */
180413  ){
180414    int res = 0;                    /* Value returned by conflict handler */
180415    int rc;
180416    int nCol;
180417    int op;
180418    const char *zDummy;
180419  
180420    sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
180421  
180422    assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
180423    assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
180424    assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
180425  
180426    /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
180427    if( pbReplace ){
180428      rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
180429    }else{
180430      rc = SQLITE_OK;
180431    }
180432  
180433    if( rc==SQLITE_ROW ){
180434      /* There exists another row with the new.* primary key. */
180435      pIter->pConflict = p->pSelect;
180436      res = xConflict(pCtx, eType, pIter);
180437      pIter->pConflict = 0;
180438      rc = sqlite3_reset(p->pSelect);
180439    }else if( rc==SQLITE_OK ){
180440      if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
180441        /* Instead of invoking the conflict handler, append the change blob
180442        ** to the SessionApplyCtx.constraints buffer. */
180443        u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
180444        int nBlob = pIter->in.iNext - pIter->in.iCurrent;
180445        sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
180446        res = SQLITE_CHANGESET_OMIT;
180447      }else{
180448        /* No other row with the new.* primary key. */
180449        res = xConflict(pCtx, eType+1, pIter);
180450        if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
180451      }
180452    }
180453  
180454    if( rc==SQLITE_OK ){
180455      switch( res ){
180456        case SQLITE_CHANGESET_REPLACE:
180457          assert( pbReplace );
180458          *pbReplace = 1;
180459          break;
180460  
180461        case SQLITE_CHANGESET_OMIT:
180462          break;
180463  
180464        case SQLITE_CHANGESET_ABORT:
180465          rc = SQLITE_ABORT;
180466          break;
180467  
180468        default:
180469          rc = SQLITE_MISUSE;
180470          break;
180471      }
180472    }
180473  
180474    return rc;
180475  }
180476  
180477  /*
180478  ** Attempt to apply the change that the iterator passed as the first argument
180479  ** currently points to to the database. If a conflict is encountered, invoke
180480  ** the conflict handler callback.
180481  **
180482  ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
180483  ** one is encountered, update or delete the row with the matching primary key
180484  ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
180485  ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
180486  ** to true before returning. In this case the caller will invoke this function
180487  ** again, this time with pbRetry set to NULL.
180488  **
180489  ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is 
180490  ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
180491  ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
180492  ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
180493  ** before retrying. In this case the caller attempts to remove the conflicting
180494  ** row before invoking this function again, this time with pbReplace set 
180495  ** to NULL.
180496  **
180497  ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
180498  ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is 
180499  ** returned.
180500  */
180501  static int sessionApplyOneOp(
180502    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
180503    SessionApplyCtx *p,             /* changeset_apply() context */
180504    int(*xConflict)(void *, int, sqlite3_changeset_iter *),
180505    void *pCtx,                     /* First argument for the conflict handler */
180506    int *pbReplace,                 /* OUT: True to remove PK row and retry */
180507    int *pbRetry                    /* OUT: True to retry. */
180508  ){
180509    const char *zDummy;
180510    int op;
180511    int nCol;
180512    int rc = SQLITE_OK;
180513  
180514    assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
180515    assert( p->azCol && p->abPK );
180516    assert( !pbReplace || *pbReplace==0 );
180517  
180518    sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
180519  
180520    if( op==SQLITE_DELETE ){
180521  
180522      /* Bind values to the DELETE statement. If conflict handling is required,
180523      ** bind values for all columns and set bound variable (nCol+1) to true.
180524      ** Or, if conflict handling is not required, bind just the PK column
180525      ** values and, if it exists, set (nCol+1) to false. Conflict handling
180526      ** is not required if:
180527      **
180528      **   * this is a patchset, or
180529      **   * (pbRetry==0), or
180530      **   * all columns of the table are PK columns (in this case there is
180531      **     no (nCol+1) variable to bind to).
180532      */
180533      u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
180534      rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
180535      if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
180536        rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
180537      }
180538      if( rc!=SQLITE_OK ) return rc;
180539  
180540      sqlite3_step(p->pDelete);
180541      rc = sqlite3_reset(p->pDelete);
180542      if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
180543        rc = sessionConflictHandler(
180544            SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
180545        );
180546      }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
180547        rc = sessionConflictHandler(
180548            SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
180549        );
180550      }
180551  
180552    }else if( op==SQLITE_UPDATE ){
180553      int i;
180554  
180555      /* Bind values to the UPDATE statement. */
180556      for(i=0; rc==SQLITE_OK && i<nCol; i++){
180557        sqlite3_value *pOld = sessionChangesetOld(pIter, i);
180558        sqlite3_value *pNew = sessionChangesetNew(pIter, i);
180559  
180560        sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
180561        if( pOld ){
180562          rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
180563        }
180564        if( rc==SQLITE_OK && pNew ){
180565          rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
180566        }
180567      }
180568      if( rc==SQLITE_OK ){
180569        sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
180570      }
180571      if( rc!=SQLITE_OK ) return rc;
180572  
180573      /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
180574      ** the result will be SQLITE_OK with 0 rows modified. */
180575      sqlite3_step(p->pUpdate);
180576      rc = sqlite3_reset(p->pUpdate);
180577  
180578      if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
180579        /* A NOTFOUND or DATA error. Search the table to see if it contains
180580        ** a row with a matching primary key. If so, this is a DATA conflict.
180581        ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
180582  
180583        rc = sessionConflictHandler(
180584            SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
180585        );
180586  
180587      }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
180588        /* This is always a CONSTRAINT conflict. */
180589        rc = sessionConflictHandler(
180590            SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
180591        );
180592      }
180593  
180594    }else{
180595      assert( op==SQLITE_INSERT );
180596      rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
180597      if( rc!=SQLITE_OK ) return rc;
180598  
180599      sqlite3_step(p->pInsert);
180600      rc = sqlite3_reset(p->pInsert);
180601      if( (rc&0xff)==SQLITE_CONSTRAINT ){
180602        rc = sessionConflictHandler(
180603            SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
180604        );
180605      }
180606    }
180607  
180608    return rc;
180609  }
180610  
180611  /*
180612  ** Attempt to apply the change that the iterator passed as the first argument
180613  ** currently points to to the database. If a conflict is encountered, invoke
180614  ** the conflict handler callback.
180615  **
180616  ** The difference between this function and sessionApplyOne() is that this
180617  ** function handles the case where the conflict-handler is invoked and 
180618  ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
180619  ** retried in some manner.
180620  */
180621  static int sessionApplyOneWithRetry(
180622    sqlite3 *db,                    /* Apply change to "main" db of this handle */
180623    sqlite3_changeset_iter *pIter,  /* Changeset iterator to read change from */
180624    SessionApplyCtx *pApply,        /* Apply context */
180625    int(*xConflict)(void*, int, sqlite3_changeset_iter*),
180626    void *pCtx                      /* First argument passed to xConflict */
180627  ){
180628    int bReplace = 0;
180629    int bRetry = 0;
180630    int rc;
180631  
180632    rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
180633    assert( rc==SQLITE_OK || (bRetry==0 && bReplace==0) );
180634  
180635    /* If the bRetry flag is set, the change has not been applied due to an
180636    ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
180637    ** a row with the correct PK is present in the db, but one or more other
180638    ** fields do not contain the expected values) and the conflict handler 
180639    ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
180640    ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
180641    ** the SQLITE_CHANGESET_DATA problem.  */
180642    if( bRetry ){
180643      assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
180644      rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
180645    }
180646  
180647    /* If the bReplace flag is set, the change is an INSERT that has not
180648    ** been performed because the database already contains a row with the
180649    ** specified primary key and the conflict handler returned
180650    ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
180651    ** before reattempting the INSERT.  */
180652    else if( bReplace ){
180653      assert( pIter->op==SQLITE_INSERT );
180654      rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
180655      if( rc==SQLITE_OK ){
180656        rc = sessionBindRow(pIter, 
180657            sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
180658        sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
180659      }
180660      if( rc==SQLITE_OK ){
180661        sqlite3_step(pApply->pDelete);
180662        rc = sqlite3_reset(pApply->pDelete);
180663      }
180664      if( rc==SQLITE_OK ){
180665        rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
180666      }
180667      if( rc==SQLITE_OK ){
180668        rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
180669      }
180670    }
180671  
180672    return rc;
180673  }
180674  
180675  /*
180676  ** Retry the changes accumulated in the pApply->constraints buffer.
180677  */
180678  static int sessionRetryConstraints(
180679    sqlite3 *db, 
180680    int bPatchset,
180681    const char *zTab,
180682    SessionApplyCtx *pApply,
180683    int(*xConflict)(void*, int, sqlite3_changeset_iter*),
180684    void *pCtx                      /* First argument passed to xConflict */
180685  ){
180686    int rc = SQLITE_OK;
180687  
180688    while( pApply->constraints.nBuf ){
180689      sqlite3_changeset_iter *pIter2 = 0;
180690      SessionBuffer cons = pApply->constraints;
180691      memset(&pApply->constraints, 0, sizeof(SessionBuffer));
180692  
180693      rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf);
180694      if( rc==SQLITE_OK ){
180695        int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
180696        int rc2;
180697        pIter2->bPatchset = bPatchset;
180698        pIter2->zTab = (char*)zTab;
180699        pIter2->nCol = pApply->nCol;
180700        pIter2->abPK = pApply->abPK;
180701        sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
180702        pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
180703        if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
180704  
180705        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
180706          rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
180707        }
180708  
180709        rc2 = sqlite3changeset_finalize(pIter2);
180710        if( rc==SQLITE_OK ) rc = rc2;
180711      }
180712      assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
180713  
180714      sqlite3_free(cons.aBuf);
180715      if( rc!=SQLITE_OK ) break;
180716      if( pApply->constraints.nBuf>=cons.nBuf ){
180717        /* No progress was made on the last round. */
180718        pApply->bDeferConstraints = 0;
180719      }
180720    }
180721  
180722    return rc;
180723  }
180724  
180725  /*
180726  ** Argument pIter is a changeset iterator that has been initialized, but
180727  ** not yet passed to sqlite3changeset_next(). This function applies the 
180728  ** changeset to the main database attached to handle "db". The supplied
180729  ** conflict handler callback is invoked to resolve any conflicts encountered
180730  ** while applying the change.
180731  */
180732  static int sessionChangesetApply(
180733    sqlite3 *db,                    /* Apply change to "main" db of this handle */
180734    sqlite3_changeset_iter *pIter,  /* Changeset to apply */
180735    int(*xFilter)(
180736      void *pCtx,                   /* Copy of sixth arg to _apply() */
180737      const char *zTab              /* Table name */
180738    ),
180739    int(*xConflict)(
180740      void *pCtx,                   /* Copy of fifth arg to _apply() */
180741      int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
180742      sqlite3_changeset_iter *p     /* Handle describing change and conflict */
180743    ),
180744    void *pCtx                      /* First argument passed to xConflict */
180745  ){
180746    int schemaMismatch = 0;
180747    int rc;                         /* Return code */
180748    const char *zTab = 0;           /* Name of current table */
180749    int nTab = 0;                   /* Result of sqlite3Strlen30(zTab) */
180750    SessionApplyCtx sApply;         /* changeset_apply() context object */
180751    int bPatchset;
180752  
180753    assert( xConflict!=0 );
180754  
180755    pIter->in.bNoDiscard = 1;
180756    memset(&sApply, 0, sizeof(sApply));
180757    sqlite3_mutex_enter(sqlite3_db_mutex(db));
180758    rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
180759    if( rc==SQLITE_OK ){
180760      rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
180761    }
180762    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
180763      int nCol;
180764      int op;
180765      const char *zNew;
180766      
180767      sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
180768  
180769      if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
180770        u8 *abPK;
180771  
180772        rc = sessionRetryConstraints(
180773            db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
180774        );
180775        if( rc!=SQLITE_OK ) break;
180776  
180777        sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */
180778        sqlite3_finalize(sApply.pDelete);
180779        sqlite3_finalize(sApply.pUpdate); 
180780        sqlite3_finalize(sApply.pInsert);
180781        sqlite3_finalize(sApply.pSelect);
180782        memset(&sApply, 0, sizeof(sApply));
180783        sApply.db = db;
180784        sApply.bDeferConstraints = 1;
180785  
180786        /* If an xFilter() callback was specified, invoke it now. If the 
180787        ** xFilter callback returns zero, skip this table. If it returns
180788        ** non-zero, proceed. */
180789        schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
180790        if( schemaMismatch ){
180791          zTab = sqlite3_mprintf("%s", zNew);
180792          if( zTab==0 ){
180793            rc = SQLITE_NOMEM;
180794            break;
180795          }
180796          nTab = (int)strlen(zTab);
180797          sApply.azCol = (const char **)zTab;
180798        }else{
180799          int nMinCol = 0;
180800          int i;
180801  
180802          sqlite3changeset_pk(pIter, &abPK, 0);
180803          rc = sessionTableInfo(
180804              db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
180805          );
180806          if( rc!=SQLITE_OK ) break;
180807          for(i=0; i<sApply.nCol; i++){
180808            if( sApply.abPK[i] ) nMinCol = i+1;
180809          }
180810    
180811          if( sApply.nCol==0 ){
180812            schemaMismatch = 1;
180813            sqlite3_log(SQLITE_SCHEMA, 
180814                "sqlite3changeset_apply(): no such table: %s", zTab
180815            );
180816          }
180817          else if( sApply.nCol<nCol ){
180818            schemaMismatch = 1;
180819            sqlite3_log(SQLITE_SCHEMA, 
180820                "sqlite3changeset_apply(): table %s has %d columns, "
180821                "expected %d or more", 
180822                zTab, sApply.nCol, nCol
180823            );
180824          }
180825          else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){
180826            schemaMismatch = 1;
180827            sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
180828                "primary key mismatch for table %s", zTab
180829            );
180830          }
180831          else{
180832            sApply.nCol = nCol;
180833            if((rc = sessionSelectRow(db, zTab, &sApply))
180834            || (rc = sessionUpdateRow(db, zTab, &sApply))
180835            || (rc = sessionDeleteRow(db, zTab, &sApply))
180836            || (rc = sessionInsertRow(db, zTab, &sApply))
180837            ){
180838              break;
180839            }
180840          }
180841          nTab = sqlite3Strlen30(zTab);
180842        }
180843      }
180844  
180845      /* If there is a schema mismatch on the current table, proceed to the
180846      ** next change. A log message has already been issued. */
180847      if( schemaMismatch ) continue;
180848  
180849      rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
180850    }
180851  
180852    bPatchset = pIter->bPatchset;
180853    if( rc==SQLITE_OK ){
180854      rc = sqlite3changeset_finalize(pIter);
180855    }else{
180856      sqlite3changeset_finalize(pIter);
180857    }
180858  
180859    if( rc==SQLITE_OK ){
180860      rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
180861    }
180862  
180863    if( rc==SQLITE_OK ){
180864      int nFk, notUsed;
180865      sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
180866      if( nFk!=0 ){
180867        int res = SQLITE_CHANGESET_ABORT;
180868        sqlite3_changeset_iter sIter;
180869        memset(&sIter, 0, sizeof(sIter));
180870        sIter.nCol = nFk;
180871        res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
180872        if( res!=SQLITE_CHANGESET_OMIT ){
180873          rc = SQLITE_CONSTRAINT;
180874        }
180875      }
180876    }
180877    sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
180878  
180879    if( rc==SQLITE_OK ){
180880      rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
180881    }else{
180882      sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
180883      sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
180884    }
180885  
180886    sqlite3_finalize(sApply.pInsert);
180887    sqlite3_finalize(sApply.pDelete);
180888    sqlite3_finalize(sApply.pUpdate);
180889    sqlite3_finalize(sApply.pSelect);
180890    sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */
180891    sqlite3_free((char*)sApply.constraints.aBuf);
180892    sqlite3_mutex_leave(sqlite3_db_mutex(db));
180893    return rc;
180894  }
180895  
180896  /*
180897  ** Apply the changeset passed via pChangeset/nChangeset to the main database
180898  ** attached to handle "db". Invoke the supplied conflict handler callback
180899  ** to resolve any conflicts encountered while applying the change.
180900  */
180901  SQLITE_API int sqlite3changeset_apply(
180902    sqlite3 *db,                    /* Apply change to "main" db of this handle */
180903    int nChangeset,                 /* Size of changeset in bytes */
180904    void *pChangeset,               /* Changeset blob */
180905    int(*xFilter)(
180906      void *pCtx,                   /* Copy of sixth arg to _apply() */
180907      const char *zTab              /* Table name */
180908    ),
180909    int(*xConflict)(
180910      void *pCtx,                   /* Copy of fifth arg to _apply() */
180911      int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
180912      sqlite3_changeset_iter *p     /* Handle describing change and conflict */
180913    ),
180914    void *pCtx                      /* First argument passed to xConflict */
180915  ){
180916    sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */  
180917    int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset);
180918    if( rc==SQLITE_OK ){
180919      rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
180920    }
180921    return rc;
180922  }
180923  
180924  /*
180925  ** Apply the changeset passed via xInput/pIn to the main database
180926  ** attached to handle "db". Invoke the supplied conflict handler callback
180927  ** to resolve any conflicts encountered while applying the change.
180928  */
180929  SQLITE_API int sqlite3changeset_apply_strm(
180930    sqlite3 *db,                    /* Apply change to "main" db of this handle */
180931    int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
180932    void *pIn,                                          /* First arg for xInput */
180933    int(*xFilter)(
180934      void *pCtx,                   /* Copy of sixth arg to _apply() */
180935      const char *zTab              /* Table name */
180936    ),
180937    int(*xConflict)(
180938      void *pCtx,                   /* Copy of sixth arg to _apply() */
180939      int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
180940      sqlite3_changeset_iter *p     /* Handle describing change and conflict */
180941    ),
180942    void *pCtx                      /* First argument passed to xConflict */
180943  ){
180944    sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */  
180945    int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
180946    if( rc==SQLITE_OK ){
180947      rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
180948    }
180949    return rc;
180950  }
180951  
180952  /*
180953  ** sqlite3_changegroup handle.
180954  */
180955  struct sqlite3_changegroup {
180956    int rc;                         /* Error code */
180957    int bPatch;                     /* True to accumulate patchsets */
180958    SessionTable *pList;            /* List of tables in current patch */
180959  };
180960  
180961  /*
180962  ** This function is called to merge two changes to the same row together as
180963  ** part of an sqlite3changeset_concat() operation. A new change object is
180964  ** allocated and a pointer to it stored in *ppNew.
180965  */
180966  static int sessionChangeMerge(
180967    SessionTable *pTab,             /* Table structure */
180968    int bPatchset,                  /* True for patchsets */
180969    SessionChange *pExist,          /* Existing change */
180970    int op2,                        /* Second change operation */
180971    int bIndirect,                  /* True if second change is indirect */
180972    u8 *aRec,                       /* Second change record */
180973    int nRec,                       /* Number of bytes in aRec */
180974    SessionChange **ppNew           /* OUT: Merged change */
180975  ){
180976    SessionChange *pNew = 0;
180977  
180978    if( !pExist ){
180979      pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
180980      if( !pNew ){
180981        return SQLITE_NOMEM;
180982      }
180983      memset(pNew, 0, sizeof(SessionChange));
180984      pNew->op = op2;
180985      pNew->bIndirect = bIndirect;
180986      pNew->nRecord = nRec;
180987      pNew->aRecord = (u8*)&pNew[1];
180988      memcpy(pNew->aRecord, aRec, nRec);
180989    }else{
180990      int op1 = pExist->op;
180991  
180992      /* 
180993      **   op1=INSERT, op2=INSERT      ->      Unsupported. Discard op2.
180994      **   op1=INSERT, op2=UPDATE      ->      INSERT.
180995      **   op1=INSERT, op2=DELETE      ->      (none)
180996      **
180997      **   op1=UPDATE, op2=INSERT      ->      Unsupported. Discard op2.
180998      **   op1=UPDATE, op2=UPDATE      ->      UPDATE.
180999      **   op1=UPDATE, op2=DELETE      ->      DELETE.
181000      **
181001      **   op1=DELETE, op2=INSERT      ->      UPDATE.
181002      **   op1=DELETE, op2=UPDATE      ->      Unsupported. Discard op2.
181003      **   op1=DELETE, op2=DELETE      ->      Unsupported. Discard op2.
181004      */   
181005      if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
181006       || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
181007       || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
181008       || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
181009      ){
181010        pNew = pExist;
181011      }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
181012        sqlite3_free(pExist);
181013        assert( pNew==0 );
181014      }else{
181015        u8 *aExist = pExist->aRecord;
181016        int nByte;
181017        u8 *aCsr;
181018  
181019        /* Allocate a new SessionChange object. Ensure that the aRecord[]
181020        ** buffer of the new object is large enough to hold any record that
181021        ** may be generated by combining the input records.  */
181022        nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
181023        pNew = (SessionChange *)sqlite3_malloc(nByte);
181024        if( !pNew ){
181025          sqlite3_free(pExist);
181026          return SQLITE_NOMEM;
181027        }
181028        memset(pNew, 0, sizeof(SessionChange));
181029        pNew->bIndirect = (bIndirect && pExist->bIndirect);
181030        aCsr = pNew->aRecord = (u8 *)&pNew[1];
181031  
181032        if( op1==SQLITE_INSERT ){             /* INSERT + UPDATE */
181033          u8 *a1 = aRec;
181034          assert( op2==SQLITE_UPDATE );
181035          pNew->op = SQLITE_INSERT;
181036          if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
181037          sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
181038        }else if( op1==SQLITE_DELETE ){       /* DELETE + INSERT */
181039          assert( op2==SQLITE_INSERT );
181040          pNew->op = SQLITE_UPDATE;
181041          if( bPatchset ){
181042            memcpy(aCsr, aRec, nRec);
181043            aCsr += nRec;
181044          }else{
181045            if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
181046              sqlite3_free(pNew);
181047              pNew = 0;
181048            }
181049          }
181050        }else if( op2==SQLITE_UPDATE ){       /* UPDATE + UPDATE */
181051          u8 *a1 = aExist;
181052          u8 *a2 = aRec;
181053          assert( op1==SQLITE_UPDATE );
181054          if( bPatchset==0 ){
181055            sessionSkipRecord(&a1, pTab->nCol);
181056            sessionSkipRecord(&a2, pTab->nCol);
181057          }
181058          pNew->op = SQLITE_UPDATE;
181059          if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
181060            sqlite3_free(pNew);
181061            pNew = 0;
181062          }
181063        }else{                                /* UPDATE + DELETE */
181064          assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
181065          pNew->op = SQLITE_DELETE;
181066          if( bPatchset ){
181067            memcpy(aCsr, aRec, nRec);
181068            aCsr += nRec;
181069          }else{
181070            sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
181071          }
181072        }
181073  
181074        if( pNew ){
181075          pNew->nRecord = (int)(aCsr - pNew->aRecord);
181076        }
181077        sqlite3_free(pExist);
181078      }
181079    }
181080  
181081    *ppNew = pNew;
181082    return SQLITE_OK;
181083  }
181084  
181085  /*
181086  ** Add all changes in the changeset traversed by the iterator passed as
181087  ** the first argument to the changegroup hash tables.
181088  */
181089  static int sessionChangesetToHash(
181090    sqlite3_changeset_iter *pIter,   /* Iterator to read from */
181091    sqlite3_changegroup *pGrp        /* Changegroup object to add changeset to */
181092  ){
181093    u8 *aRec;
181094    int nRec;
181095    int rc = SQLITE_OK;
181096    SessionTable *pTab = 0;
181097  
181098  
181099    while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec) ){
181100      const char *zNew;
181101      int nCol;
181102      int op;
181103      int iHash;
181104      int bIndirect;
181105      SessionChange *pChange;
181106      SessionChange *pExist = 0;
181107      SessionChange **pp;
181108  
181109      if( pGrp->pList==0 ){
181110        pGrp->bPatch = pIter->bPatchset;
181111      }else if( pIter->bPatchset!=pGrp->bPatch ){
181112        rc = SQLITE_ERROR;
181113        break;
181114      }
181115  
181116      sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
181117      if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
181118        /* Search the list for a matching table */
181119        int nNew = (int)strlen(zNew);
181120        u8 *abPK;
181121  
181122        sqlite3changeset_pk(pIter, &abPK, 0);
181123        for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
181124          if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
181125        }
181126        if( !pTab ){
181127          SessionTable **ppTab;
181128  
181129          pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
181130          if( !pTab ){
181131            rc = SQLITE_NOMEM;
181132            break;
181133          }
181134          memset(pTab, 0, sizeof(SessionTable));
181135          pTab->nCol = nCol;
181136          pTab->abPK = (u8*)&pTab[1];
181137          memcpy(pTab->abPK, abPK, nCol);
181138          pTab->zName = (char*)&pTab->abPK[nCol];
181139          memcpy(pTab->zName, zNew, nNew+1);
181140  
181141          /* The new object must be linked on to the end of the list, not
181142          ** simply added to the start of it. This is to ensure that the
181143          ** tables within the output of sqlite3changegroup_output() are in 
181144          ** the right order.  */
181145          for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
181146          *ppTab = pTab;
181147        }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
181148          rc = SQLITE_SCHEMA;
181149          break;
181150        }
181151      }
181152  
181153      if( sessionGrowHash(pIter->bPatchset, pTab) ){
181154        rc = SQLITE_NOMEM;
181155        break;
181156      }
181157      iHash = sessionChangeHash(
181158          pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
181159      );
181160  
181161      /* Search for existing entry. If found, remove it from the hash table. 
181162      ** Code below may link it back in.
181163      */
181164      for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
181165        int bPkOnly1 = 0;
181166        int bPkOnly2 = 0;
181167        if( pIter->bPatchset ){
181168          bPkOnly1 = (*pp)->op==SQLITE_DELETE;
181169          bPkOnly2 = op==SQLITE_DELETE;
181170        }
181171        if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
181172          pExist = *pp;
181173          *pp = (*pp)->pNext;
181174          pTab->nEntry--;
181175          break;
181176        }
181177      }
181178  
181179      rc = sessionChangeMerge(pTab, 
181180          pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
181181      );
181182      if( rc ) break;
181183      if( pChange ){
181184        pChange->pNext = pTab->apChange[iHash];
181185        pTab->apChange[iHash] = pChange;
181186        pTab->nEntry++;
181187      }
181188    }
181189  
181190    if( rc==SQLITE_OK ) rc = pIter->rc;
181191    return rc;
181192  }
181193  
181194  /*
181195  ** Serialize a changeset (or patchset) based on all changesets (or patchsets)
181196  ** added to the changegroup object passed as the first argument.
181197  **
181198  ** If xOutput is not NULL, then the changeset/patchset is returned to the
181199  ** user via one or more calls to xOutput, as with the other streaming
181200  ** interfaces. 
181201  **
181202  ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
181203  ** buffer containing the output changeset before this function returns. In
181204  ** this case (*pnOut) is set to the size of the output buffer in bytes. It
181205  ** is the responsibility of the caller to free the output buffer using
181206  ** sqlite3_free() when it is no longer required.
181207  **
181208  ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
181209  ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
181210  ** are both set to 0 before returning.
181211  */
181212  static int sessionChangegroupOutput(
181213    sqlite3_changegroup *pGrp,
181214    int (*xOutput)(void *pOut, const void *pData, int nData),
181215    void *pOut,
181216    int *pnOut,
181217    void **ppOut
181218  ){
181219    int rc = SQLITE_OK;
181220    SessionBuffer buf = {0, 0, 0};
181221    SessionTable *pTab;
181222    assert( xOutput==0 || (ppOut==0 && pnOut==0) );
181223  
181224    /* Create the serialized output changeset based on the contents of the
181225    ** hash tables attached to the SessionTable objects in list p->pList. 
181226    */
181227    for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
181228      int i;
181229      if( pTab->nEntry==0 ) continue;
181230  
181231      sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
181232      for(i=0; i<pTab->nChange; i++){
181233        SessionChange *p;
181234        for(p=pTab->apChange[i]; p; p=p->pNext){
181235          sessionAppendByte(&buf, p->op, &rc);
181236          sessionAppendByte(&buf, p->bIndirect, &rc);
181237          sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
181238        }
181239      }
181240  
181241      if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
181242        rc = xOutput(pOut, buf.aBuf, buf.nBuf);
181243        buf.nBuf = 0;
181244      }
181245    }
181246  
181247    if( rc==SQLITE_OK ){
181248      if( xOutput ){
181249        if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
181250      }else{
181251        *ppOut = buf.aBuf;
181252        *pnOut = buf.nBuf;
181253        buf.aBuf = 0;
181254      }
181255    }
181256    sqlite3_free(buf.aBuf);
181257  
181258    return rc;
181259  }
181260  
181261  /*
181262  ** Allocate a new, empty, sqlite3_changegroup.
181263  */
181264  SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){
181265    int rc = SQLITE_OK;             /* Return code */
181266    sqlite3_changegroup *p;         /* New object */
181267    p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
181268    if( p==0 ){
181269      rc = SQLITE_NOMEM;
181270    }else{
181271      memset(p, 0, sizeof(sqlite3_changegroup));
181272    }
181273    *pp = p;
181274    return rc;
181275  }
181276  
181277  /*
181278  ** Add the changeset currently stored in buffer pData, size nData bytes,
181279  ** to changeset-group p.
181280  */
181281  SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
181282    sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */
181283    int rc;                         /* Return code */
181284  
181285    rc = sqlite3changeset_start(&pIter, nData, pData);
181286    if( rc==SQLITE_OK ){
181287      rc = sessionChangesetToHash(pIter, pGrp);
181288    }
181289    sqlite3changeset_finalize(pIter);
181290    return rc;
181291  }
181292  
181293  /*
181294  ** Obtain a buffer containing a changeset representing the concatenation
181295  ** of all changesets added to the group so far.
181296  */
181297  SQLITE_API int sqlite3changegroup_output(
181298      sqlite3_changegroup *pGrp,
181299      int *pnData,
181300      void **ppData
181301  ){
181302    return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
181303  }
181304  
181305  /*
181306  ** Streaming versions of changegroup_add().
181307  */
181308  SQLITE_API int sqlite3changegroup_add_strm(
181309    sqlite3_changegroup *pGrp,
181310    int (*xInput)(void *pIn, void *pData, int *pnData),
181311    void *pIn
181312  ){
181313    sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */
181314    int rc;                         /* Return code */
181315  
181316    rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
181317    if( rc==SQLITE_OK ){
181318      rc = sessionChangesetToHash(pIter, pGrp);
181319    }
181320    sqlite3changeset_finalize(pIter);
181321    return rc;
181322  }
181323  
181324  /*
181325  ** Streaming versions of changegroup_output().
181326  */
181327  SQLITE_API int sqlite3changegroup_output_strm(
181328    sqlite3_changegroup *pGrp,
181329    int (*xOutput)(void *pOut, const void *pData, int nData), 
181330    void *pOut
181331  ){
181332    return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
181333  }
181334  
181335  /*
181336  ** Delete a changegroup object.
181337  */
181338  SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
181339    if( pGrp ){
181340      sessionDeleteTable(pGrp->pList);
181341      sqlite3_free(pGrp);
181342    }
181343  }
181344  
181345  /* 
181346  ** Combine two changesets together.
181347  */
181348  SQLITE_API int sqlite3changeset_concat(
181349    int nLeft,                      /* Number of bytes in lhs input */
181350    void *pLeft,                    /* Lhs input changeset */
181351    int nRight                      /* Number of bytes in rhs input */,
181352    void *pRight,                   /* Rhs input changeset */
181353    int *pnOut,                     /* OUT: Number of bytes in output changeset */
181354    void **ppOut                    /* OUT: changeset (left <concat> right) */
181355  ){
181356    sqlite3_changegroup *pGrp;
181357    int rc;
181358  
181359    rc = sqlite3changegroup_new(&pGrp);
181360    if( rc==SQLITE_OK ){
181361      rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
181362    }
181363    if( rc==SQLITE_OK ){
181364      rc = sqlite3changegroup_add(pGrp, nRight, pRight);
181365    }
181366    if( rc==SQLITE_OK ){
181367      rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
181368    }
181369    sqlite3changegroup_delete(pGrp);
181370  
181371    return rc;
181372  }
181373  
181374  /*
181375  ** Streaming version of sqlite3changeset_concat().
181376  */
181377  SQLITE_API int sqlite3changeset_concat_strm(
181378    int (*xInputA)(void *pIn, void *pData, int *pnData),
181379    void *pInA,
181380    int (*xInputB)(void *pIn, void *pData, int *pnData),
181381    void *pInB,
181382    int (*xOutput)(void *pOut, const void *pData, int nData),
181383    void *pOut
181384  ){
181385    sqlite3_changegroup *pGrp;
181386    int rc;
181387  
181388    rc = sqlite3changegroup_new(&pGrp);
181389    if( rc==SQLITE_OK ){
181390      rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
181391    }
181392    if( rc==SQLITE_OK ){
181393      rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
181394    }
181395    if( rc==SQLITE_OK ){
181396      rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
181397    }
181398    sqlite3changegroup_delete(pGrp);
181399  
181400    return rc;
181401  }
181402  
181403  #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
181404  
181405  /************** End of sqlite3session.c **************************************/
181406  /************** Begin file json1.c *******************************************/
181407  /*
181408  ** 2015-08-12
181409  **
181410  ** The author disclaims copyright to this source code.  In place of
181411  ** a legal notice, here is a blessing:
181412  **
181413  **    May you do good and not evil.
181414  **    May you find forgiveness for yourself and forgive others.
181415  **    May you share freely, never taking more than you give.
181416  **
181417  ******************************************************************************
181418  **
181419  ** This SQLite extension implements JSON functions.  The interface is
181420  ** modeled after MySQL JSON functions:
181421  **
181422  **     https://dev.mysql.com/doc/refman/5.7/en/json.html
181423  **
181424  ** For the time being, all JSON is stored as pure text.  (We might add
181425  ** a JSONB type in the future which stores a binary encoding of JSON in
181426  ** a BLOB, but there is no support for JSONB in the current implementation.
181427  ** This implementation parses JSON text at 250 MB/s, so it is hard to see
181428  ** how JSONB might improve on that.)
181429  */
181430  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
181431  #if !defined(SQLITEINT_H)
181432  /* #include "sqlite3ext.h" */
181433  #endif
181434  SQLITE_EXTENSION_INIT1
181435  /* #include <assert.h> */
181436  /* #include <string.h> */
181437  /* #include <stdlib.h> */
181438  /* #include <stdarg.h> */
181439  
181440  /* Mark a function parameter as unused, to suppress nuisance compiler
181441  ** warnings. */
181442  #ifndef UNUSED_PARAM
181443  # define UNUSED_PARAM(X)  (void)(X)
181444  #endif
181445  
181446  #ifndef LARGEST_INT64
181447  # define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
181448  # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
181449  #endif
181450  
181451  /*
181452  ** Versions of isspace(), isalnum() and isdigit() to which it is safe
181453  ** to pass signed char values.
181454  */
181455  #ifdef sqlite3Isdigit
181456     /* Use the SQLite core versions if this routine is part of the
181457     ** SQLite amalgamation */
181458  #  define safe_isdigit(x)  sqlite3Isdigit(x)
181459  #  define safe_isalnum(x)  sqlite3Isalnum(x)
181460  #  define safe_isxdigit(x) sqlite3Isxdigit(x)
181461  #else
181462     /* Use the standard library for separate compilation */
181463  #include <ctype.h>  /* amalgamator: keep */
181464  #  define safe_isdigit(x)  isdigit((unsigned char)(x))
181465  #  define safe_isalnum(x)  isalnum((unsigned char)(x))
181466  #  define safe_isxdigit(x) isxdigit((unsigned char)(x))
181467  #endif
181468  
181469  /*
181470  ** Growing our own isspace() routine this way is twice as fast as
181471  ** the library isspace() function, resulting in a 7% overall performance
181472  ** increase for the parser.  (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
181473  */
181474  static const char jsonIsSpace[] = {
181475    0, 0, 0, 0, 0, 0, 0, 0,     0, 1, 1, 0, 0, 1, 0, 0,
181476    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
181477    1, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
181478    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
181479    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
181480    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
181481    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
181482    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
181483    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
181484    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
181485    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
181486    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
181487    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
181488    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
181489    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
181490    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
181491  };
181492  #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
181493  
181494  #ifndef SQLITE_AMALGAMATION
181495    /* Unsigned integer types.  These are already defined in the sqliteInt.h,
181496    ** but the definitions need to be repeated for separate compilation. */
181497    typedef sqlite3_uint64 u64;
181498    typedef unsigned int u32;
181499    typedef unsigned short int u16;
181500    typedef unsigned char u8;
181501  #endif
181502  
181503  /* Objects */
181504  typedef struct JsonString JsonString;
181505  typedef struct JsonNode JsonNode;
181506  typedef struct JsonParse JsonParse;
181507  
181508  /* An instance of this object represents a JSON string
181509  ** under construction.  Really, this is a generic string accumulator
181510  ** that can be and is used to create strings other than JSON.
181511  */
181512  struct JsonString {
181513    sqlite3_context *pCtx;   /* Function context - put error messages here */
181514    char *zBuf;              /* Append JSON content here */
181515    u64 nAlloc;              /* Bytes of storage available in zBuf[] */
181516    u64 nUsed;               /* Bytes of zBuf[] currently used */
181517    u8 bStatic;              /* True if zBuf is static space */
181518    u8 bErr;                 /* True if an error has been encountered */
181519    char zSpace[100];        /* Initial static space */
181520  };
181521  
181522  /* JSON type values
181523  */
181524  #define JSON_NULL     0
181525  #define JSON_TRUE     1
181526  #define JSON_FALSE    2
181527  #define JSON_INT      3
181528  #define JSON_REAL     4
181529  #define JSON_STRING   5
181530  #define JSON_ARRAY    6
181531  #define JSON_OBJECT   7
181532  
181533  /* The "subtype" set for JSON values */
181534  #define JSON_SUBTYPE  74    /* Ascii for "J" */
181535  
181536  /*
181537  ** Names of the various JSON types:
181538  */
181539  static const char * const jsonType[] = {
181540    "null", "true", "false", "integer", "real", "text", "array", "object"
181541  };
181542  
181543  /* Bit values for the JsonNode.jnFlag field
181544  */
181545  #define JNODE_RAW     0x01         /* Content is raw, not JSON encoded */
181546  #define JNODE_ESCAPE  0x02         /* Content is text with \ escapes */
181547  #define JNODE_REMOVE  0x04         /* Do not output */
181548  #define JNODE_REPLACE 0x08         /* Replace with JsonNode.u.iReplace */
181549  #define JNODE_PATCH   0x10         /* Patch with JsonNode.u.pPatch */
181550  #define JNODE_APPEND  0x20         /* More ARRAY/OBJECT entries at u.iAppend */
181551  #define JNODE_LABEL   0x40         /* Is a label of an object */
181552  
181553  
181554  /* A single node of parsed JSON
181555  */
181556  struct JsonNode {
181557    u8 eType;              /* One of the JSON_ type values */
181558    u8 jnFlags;            /* JNODE flags */
181559    u32 n;                 /* Bytes of content, or number of sub-nodes */
181560    union {
181561      const char *zJContent; /* Content for INT, REAL, and STRING */
181562      u32 iAppend;           /* More terms for ARRAY and OBJECT */
181563      u32 iKey;              /* Key for ARRAY objects in json_tree() */
181564      u32 iReplace;          /* Replacement content for JNODE_REPLACE */
181565      JsonNode *pPatch;      /* Node chain of patch for JNODE_PATCH */
181566    } u;
181567  };
181568  
181569  /* A completely parsed JSON string
181570  */
181571  struct JsonParse {
181572    u32 nNode;         /* Number of slots of aNode[] used */
181573    u32 nAlloc;        /* Number of slots of aNode[] allocated */
181574    JsonNode *aNode;   /* Array of nodes containing the parse */
181575    const char *zJson; /* Original JSON string */
181576    u32 *aUp;          /* Index of parent of each node */
181577    u8 oom;            /* Set to true if out of memory */
181578    u8 nErr;           /* Number of errors seen */
181579    u16 iDepth;        /* Nesting depth */
181580    int nJson;         /* Length of the zJson string in bytes */
181581  };
181582  
181583  /*
181584  ** Maximum nesting depth of JSON for this implementation.
181585  **
181586  ** This limit is needed to avoid a stack overflow in the recursive
181587  ** descent parser.  A depth of 2000 is far deeper than any sane JSON
181588  ** should go.
181589  */
181590  #define JSON_MAX_DEPTH  2000
181591  
181592  /**************************************************************************
181593  ** Utility routines for dealing with JsonString objects
181594  **************************************************************************/
181595  
181596  /* Set the JsonString object to an empty string
181597  */
181598  static void jsonZero(JsonString *p){
181599    p->zBuf = p->zSpace;
181600    p->nAlloc = sizeof(p->zSpace);
181601    p->nUsed = 0;
181602    p->bStatic = 1;
181603  }
181604  
181605  /* Initialize the JsonString object
181606  */
181607  static void jsonInit(JsonString *p, sqlite3_context *pCtx){
181608    p->pCtx = pCtx;
181609    p->bErr = 0;
181610    jsonZero(p);
181611  }
181612  
181613  
181614  /* Free all allocated memory and reset the JsonString object back to its
181615  ** initial state.
181616  */
181617  static void jsonReset(JsonString *p){
181618    if( !p->bStatic ) sqlite3_free(p->zBuf);
181619    jsonZero(p);
181620  }
181621  
181622  
181623  /* Report an out-of-memory (OOM) condition 
181624  */
181625  static void jsonOom(JsonString *p){
181626    p->bErr = 1;
181627    sqlite3_result_error_nomem(p->pCtx);
181628    jsonReset(p);
181629  }
181630  
181631  /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
181632  ** Return zero on success.  Return non-zero on an OOM error
181633  */
181634  static int jsonGrow(JsonString *p, u32 N){
181635    u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
181636    char *zNew;
181637    if( p->bStatic ){
181638      if( p->bErr ) return 1;
181639      zNew = sqlite3_malloc64(nTotal);
181640      if( zNew==0 ){
181641        jsonOom(p);
181642        return SQLITE_NOMEM;
181643      }
181644      memcpy(zNew, p->zBuf, (size_t)p->nUsed);
181645      p->zBuf = zNew;
181646      p->bStatic = 0;
181647    }else{
181648      zNew = sqlite3_realloc64(p->zBuf, nTotal);
181649      if( zNew==0 ){
181650        jsonOom(p);
181651        return SQLITE_NOMEM;
181652      }
181653      p->zBuf = zNew;
181654    }
181655    p->nAlloc = nTotal;
181656    return SQLITE_OK;
181657  }
181658  
181659  /* Append N bytes from zIn onto the end of the JsonString string.
181660  */
181661  static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
181662    if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
181663    memcpy(p->zBuf+p->nUsed, zIn, N);
181664    p->nUsed += N;
181665  }
181666  
181667  /* Append formatted text (not to exceed N bytes) to the JsonString.
181668  */
181669  static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
181670    va_list ap;
181671    if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
181672    va_start(ap, zFormat);
181673    sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
181674    va_end(ap);
181675    p->nUsed += (int)strlen(p->zBuf+p->nUsed);
181676  }
181677  
181678  /* Append a single character
181679  */
181680  static void jsonAppendChar(JsonString *p, char c){
181681    if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
181682    p->zBuf[p->nUsed++] = c;
181683  }
181684  
181685  /* Append a comma separator to the output buffer, if the previous
181686  ** character is not '[' or '{'.
181687  */
181688  static void jsonAppendSeparator(JsonString *p){
181689    char c;
181690    if( p->nUsed==0 ) return;
181691    c = p->zBuf[p->nUsed-1];
181692    if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
181693  }
181694  
181695  /* Append the N-byte string in zIn to the end of the JsonString string
181696  ** under construction.  Enclose the string in "..." and escape
181697  ** any double-quotes or backslash characters contained within the
181698  ** string.
181699  */
181700  static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
181701    u32 i;
181702    if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
181703    p->zBuf[p->nUsed++] = '"';
181704    for(i=0; i<N; i++){
181705      unsigned char c = ((unsigned const char*)zIn)[i];
181706      if( c=='"' || c=='\\' ){
181707        json_simple_escape:
181708        if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
181709        p->zBuf[p->nUsed++] = '\\';
181710      }else if( c<=0x1f ){
181711        static const char aSpecial[] = {
181712           0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
181713           0, 0, 0, 0, 0, 0, 0, 0,   0,   0,   0, 0,   0,   0, 0, 0
181714        };
181715        assert( sizeof(aSpecial)==32 );
181716        assert( aSpecial['\b']=='b' );
181717        assert( aSpecial['\f']=='f' );
181718        assert( aSpecial['\n']=='n' );
181719        assert( aSpecial['\r']=='r' );
181720        assert( aSpecial['\t']=='t' );
181721        if( aSpecial[c] ){
181722          c = aSpecial[c];
181723          goto json_simple_escape;
181724        }
181725        if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
181726        p->zBuf[p->nUsed++] = '\\';
181727        p->zBuf[p->nUsed++] = 'u';
181728        p->zBuf[p->nUsed++] = '0';
181729        p->zBuf[p->nUsed++] = '0';
181730        p->zBuf[p->nUsed++] = '0' + (c>>4);
181731        c = "0123456789abcdef"[c&0xf];
181732      }
181733      p->zBuf[p->nUsed++] = c;
181734    }
181735    p->zBuf[p->nUsed++] = '"';
181736    assert( p->nUsed<p->nAlloc );
181737  }
181738  
181739  /*
181740  ** Append a function parameter value to the JSON string under 
181741  ** construction.
181742  */
181743  static void jsonAppendValue(
181744    JsonString *p,                 /* Append to this JSON string */
181745    sqlite3_value *pValue          /* Value to append */
181746  ){
181747    switch( sqlite3_value_type(pValue) ){
181748      case SQLITE_NULL: {
181749        jsonAppendRaw(p, "null", 4);
181750        break;
181751      }
181752      case SQLITE_INTEGER:
181753      case SQLITE_FLOAT: {
181754        const char *z = (const char*)sqlite3_value_text(pValue);
181755        u32 n = (u32)sqlite3_value_bytes(pValue);
181756        jsonAppendRaw(p, z, n);
181757        break;
181758      }
181759      case SQLITE_TEXT: {
181760        const char *z = (const char*)sqlite3_value_text(pValue);
181761        u32 n = (u32)sqlite3_value_bytes(pValue);
181762        if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
181763          jsonAppendRaw(p, z, n);
181764        }else{
181765          jsonAppendString(p, z, n);
181766        }
181767        break;
181768      }
181769      default: {
181770        if( p->bErr==0 ){
181771          sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
181772          p->bErr = 2;
181773          jsonReset(p);
181774        }
181775        break;
181776      }
181777    }
181778  }
181779  
181780  
181781  /* Make the JSON in p the result of the SQL function.
181782  */
181783  static void jsonResult(JsonString *p){
181784    if( p->bErr==0 ){
181785      sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed, 
181786                            p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
181787                            SQLITE_UTF8);
181788      jsonZero(p);
181789    }
181790    assert( p->bStatic );
181791  }
181792  
181793  /**************************************************************************
181794  ** Utility routines for dealing with JsonNode and JsonParse objects
181795  **************************************************************************/
181796  
181797  /*
181798  ** Return the number of consecutive JsonNode slots need to represent
181799  ** the parsed JSON at pNode.  The minimum answer is 1.  For ARRAY and
181800  ** OBJECT types, the number might be larger.
181801  **
181802  ** Appended elements are not counted.  The value returned is the number
181803  ** by which the JsonNode counter should increment in order to go to the
181804  ** next peer value.
181805  */
181806  static u32 jsonNodeSize(JsonNode *pNode){
181807    return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
181808  }
181809  
181810  /*
181811  ** Reclaim all memory allocated by a JsonParse object.  But do not
181812  ** delete the JsonParse object itself.
181813  */
181814  static void jsonParseReset(JsonParse *pParse){
181815    sqlite3_free(pParse->aNode);
181816    pParse->aNode = 0;
181817    pParse->nNode = 0;
181818    pParse->nAlloc = 0;
181819    sqlite3_free(pParse->aUp);
181820    pParse->aUp = 0;
181821  }
181822  
181823  /*
181824  ** Free a JsonParse object that was obtained from sqlite3_malloc().
181825  */
181826  static void jsonParseFree(JsonParse *pParse){
181827    jsonParseReset(pParse);
181828    sqlite3_free(pParse);
181829  }
181830  
181831  /*
181832  ** Convert the JsonNode pNode into a pure JSON string and
181833  ** append to pOut.  Subsubstructure is also included.  Return
181834  ** the number of JsonNode objects that are encoded.
181835  */
181836  static void jsonRenderNode(
181837    JsonNode *pNode,               /* The node to render */
181838    JsonString *pOut,              /* Write JSON here */
181839    sqlite3_value **aReplace       /* Replacement values */
181840  ){
181841    if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
181842      if( pNode->jnFlags & JNODE_REPLACE ){
181843        jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
181844        return;
181845      }
181846      pNode = pNode->u.pPatch;
181847    }
181848    switch( pNode->eType ){
181849      default: {
181850        assert( pNode->eType==JSON_NULL );
181851        jsonAppendRaw(pOut, "null", 4);
181852        break;
181853      }
181854      case JSON_TRUE: {
181855        jsonAppendRaw(pOut, "true", 4);
181856        break;
181857      }
181858      case JSON_FALSE: {
181859        jsonAppendRaw(pOut, "false", 5);
181860        break;
181861      }
181862      case JSON_STRING: {
181863        if( pNode->jnFlags & JNODE_RAW ){
181864          jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
181865          break;
181866        }
181867        /* Fall through into the next case */
181868      }
181869      case JSON_REAL:
181870      case JSON_INT: {
181871        jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
181872        break;
181873      }
181874      case JSON_ARRAY: {
181875        u32 j = 1;
181876        jsonAppendChar(pOut, '[');
181877        for(;;){
181878          while( j<=pNode->n ){
181879            if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
181880              jsonAppendSeparator(pOut);
181881              jsonRenderNode(&pNode[j], pOut, aReplace);
181882            }
181883            j += jsonNodeSize(&pNode[j]);
181884          }
181885          if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
181886          pNode = &pNode[pNode->u.iAppend];
181887          j = 1;
181888        }
181889        jsonAppendChar(pOut, ']');
181890        break;
181891      }
181892      case JSON_OBJECT: {
181893        u32 j = 1;
181894        jsonAppendChar(pOut, '{');
181895        for(;;){
181896          while( j<=pNode->n ){
181897            if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
181898              jsonAppendSeparator(pOut);
181899              jsonRenderNode(&pNode[j], pOut, aReplace);
181900              jsonAppendChar(pOut, ':');
181901              jsonRenderNode(&pNode[j+1], pOut, aReplace);
181902            }
181903            j += 1 + jsonNodeSize(&pNode[j+1]);
181904          }
181905          if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
181906          pNode = &pNode[pNode->u.iAppend];
181907          j = 1;
181908        }
181909        jsonAppendChar(pOut, '}');
181910        break;
181911      }
181912    }
181913  }
181914  
181915  /*
181916  ** Return a JsonNode and all its descendents as a JSON string.
181917  */
181918  static void jsonReturnJson(
181919    JsonNode *pNode,            /* Node to return */
181920    sqlite3_context *pCtx,      /* Return value for this function */
181921    sqlite3_value **aReplace    /* Array of replacement values */
181922  ){
181923    JsonString s;
181924    jsonInit(&s, pCtx);
181925    jsonRenderNode(pNode, &s, aReplace);
181926    jsonResult(&s);
181927    sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
181928  }
181929  
181930  /*
181931  ** Make the JsonNode the return value of the function.
181932  */
181933  static void jsonReturn(
181934    JsonNode *pNode,            /* Node to return */
181935    sqlite3_context *pCtx,      /* Return value for this function */
181936    sqlite3_value **aReplace    /* Array of replacement values */
181937  ){
181938    switch( pNode->eType ){
181939      default: {
181940        assert( pNode->eType==JSON_NULL );
181941        sqlite3_result_null(pCtx);
181942        break;
181943      }
181944      case JSON_TRUE: {
181945        sqlite3_result_int(pCtx, 1);
181946        break;
181947      }
181948      case JSON_FALSE: {
181949        sqlite3_result_int(pCtx, 0);
181950        break;
181951      }
181952      case JSON_INT: {
181953        sqlite3_int64 i = 0;
181954        const char *z = pNode->u.zJContent;
181955        if( z[0]=='-' ){ z++; }
181956        while( z[0]>='0' && z[0]<='9' ){
181957          unsigned v = *(z++) - '0';
181958          if( i>=LARGEST_INT64/10 ){
181959            if( i>LARGEST_INT64/10 ) goto int_as_real;
181960            if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
181961            if( v==9 ) goto int_as_real;
181962            if( v==8 ){
181963              if( pNode->u.zJContent[0]=='-' ){
181964                sqlite3_result_int64(pCtx, SMALLEST_INT64);
181965                goto int_done;
181966              }else{
181967                goto int_as_real;
181968              }
181969            }
181970          }
181971          i = i*10 + v;
181972        }
181973        if( pNode->u.zJContent[0]=='-' ){ i = -i; }
181974        sqlite3_result_int64(pCtx, i);
181975        int_done:
181976        break;
181977        int_as_real: /* fall through to real */;
181978      }
181979      case JSON_REAL: {
181980        double r;
181981  #ifdef SQLITE_AMALGAMATION
181982        const char *z = pNode->u.zJContent;
181983        sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
181984  #else
181985        r = strtod(pNode->u.zJContent, 0);
181986  #endif
181987        sqlite3_result_double(pCtx, r);
181988        break;
181989      }
181990      case JSON_STRING: {
181991  #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
181992        ** json_insert() and json_replace() and those routines do not
181993        ** call jsonReturn() */
181994        if( pNode->jnFlags & JNODE_RAW ){
181995          sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
181996                              SQLITE_TRANSIENT);
181997        }else 
181998  #endif
181999        assert( (pNode->jnFlags & JNODE_RAW)==0 );
182000        if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
182001          /* JSON formatted without any backslash-escapes */
182002          sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
182003                              SQLITE_TRANSIENT);
182004        }else{
182005          /* Translate JSON formatted string into raw text */
182006          u32 i;
182007          u32 n = pNode->n;
182008          const char *z = pNode->u.zJContent;
182009          char *zOut;
182010          u32 j;
182011          zOut = sqlite3_malloc( n+1 );
182012          if( zOut==0 ){
182013            sqlite3_result_error_nomem(pCtx);
182014            break;
182015          }
182016          for(i=1, j=0; i<n-1; i++){
182017            char c = z[i];
182018            if( c!='\\' ){
182019              zOut[j++] = c;
182020            }else{
182021              c = z[++i];
182022              if( c=='u' ){
182023                u32 v = 0, k;
182024                for(k=0; k<4; i++, k++){
182025                  assert( i<n-2 );
182026                  c = z[i+1];
182027                  assert( safe_isxdigit(c) );
182028                  if( c<='9' ) v = v*16 + c - '0';
182029                  else if( c<='F' ) v = v*16 + c - 'A' + 10;
182030                  else v = v*16 + c - 'a' + 10;
182031                }
182032                if( v==0 ) break;
182033                if( v<=0x7f ){
182034                  zOut[j++] = (char)v;
182035                }else if( v<=0x7ff ){
182036                  zOut[j++] = (char)(0xc0 | (v>>6));
182037                  zOut[j++] = 0x80 | (v&0x3f);
182038                }else{
182039                  zOut[j++] = (char)(0xe0 | (v>>12));
182040                  zOut[j++] = 0x80 | ((v>>6)&0x3f);
182041                  zOut[j++] = 0x80 | (v&0x3f);
182042                }
182043              }else{
182044                if( c=='b' ){
182045                  c = '\b';
182046                }else if( c=='f' ){
182047                  c = '\f';
182048                }else if( c=='n' ){
182049                  c = '\n';
182050                }else if( c=='r' ){
182051                  c = '\r';
182052                }else if( c=='t' ){
182053                  c = '\t';
182054                }
182055                zOut[j++] = c;
182056              }
182057            }
182058          }
182059          zOut[j] = 0;
182060          sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
182061        }
182062        break;
182063      }
182064      case JSON_ARRAY:
182065      case JSON_OBJECT: {
182066        jsonReturnJson(pNode, pCtx, aReplace);
182067        break;
182068      }
182069    }
182070  }
182071  
182072  /* Forward reference */
182073  static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
182074  
182075  /*
182076  ** A macro to hint to the compiler that a function should not be
182077  ** inlined.
182078  */
182079  #if defined(__GNUC__)
182080  #  define JSON_NOINLINE  __attribute__((noinline))
182081  #elif defined(_MSC_VER) && _MSC_VER>=1310
182082  #  define JSON_NOINLINE  __declspec(noinline)
182083  #else
182084  #  define JSON_NOINLINE
182085  #endif
182086  
182087  
182088  static JSON_NOINLINE int jsonParseAddNodeExpand(
182089    JsonParse *pParse,        /* Append the node to this object */
182090    u32 eType,                /* Node type */
182091    u32 n,                    /* Content size or sub-node count */
182092    const char *zContent      /* Content */
182093  ){
182094    u32 nNew;
182095    JsonNode *pNew;
182096    assert( pParse->nNode>=pParse->nAlloc );
182097    if( pParse->oom ) return -1;
182098    nNew = pParse->nAlloc*2 + 10;
182099    pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
182100    if( pNew==0 ){
182101      pParse->oom = 1;
182102      return -1;
182103    }
182104    pParse->nAlloc = nNew;
182105    pParse->aNode = pNew;
182106    assert( pParse->nNode<pParse->nAlloc );
182107    return jsonParseAddNode(pParse, eType, n, zContent);
182108  }
182109  
182110  /*
182111  ** Create a new JsonNode instance based on the arguments and append that
182112  ** instance to the JsonParse.  Return the index in pParse->aNode[] of the
182113  ** new node, or -1 if a memory allocation fails.
182114  */
182115  static int jsonParseAddNode(
182116    JsonParse *pParse,        /* Append the node to this object */
182117    u32 eType,                /* Node type */
182118    u32 n,                    /* Content size or sub-node count */
182119    const char *zContent      /* Content */
182120  ){
182121    JsonNode *p;
182122    if( pParse->nNode>=pParse->nAlloc ){
182123      return jsonParseAddNodeExpand(pParse, eType, n, zContent);
182124    }
182125    p = &pParse->aNode[pParse->nNode];
182126    p->eType = (u8)eType;
182127    p->jnFlags = 0;
182128    p->n = n;
182129    p->u.zJContent = zContent;
182130    return pParse->nNode++;
182131  }
182132  
182133  /*
182134  ** Return true if z[] begins with 4 (or more) hexadecimal digits
182135  */
182136  static int jsonIs4Hex(const char *z){
182137    int i;
182138    for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
182139    return 1;
182140  }
182141  
182142  /*
182143  ** Parse a single JSON value which begins at pParse->zJson[i].  Return the
182144  ** index of the first character past the end of the value parsed.
182145  **
182146  ** Return negative for a syntax error.  Special cases:  return -2 if the
182147  ** first non-whitespace character is '}' and return -3 if the first
182148  ** non-whitespace character is ']'.
182149  */
182150  static int jsonParseValue(JsonParse *pParse, u32 i){
182151    char c;
182152    u32 j;
182153    int iThis;
182154    int x;
182155    JsonNode *pNode;
182156    const char *z = pParse->zJson;
182157    while( safe_isspace(z[i]) ){ i++; }
182158    if( (c = z[i])=='{' ){
182159      /* Parse object */
182160      iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
182161      if( iThis<0 ) return -1;
182162      for(j=i+1;;j++){
182163        while( safe_isspace(z[j]) ){ j++; }
182164        if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
182165        x = jsonParseValue(pParse, j);
182166        if( x<0 ){
182167          pParse->iDepth--;
182168          if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
182169          return -1;
182170        }
182171        if( pParse->oom ) return -1;
182172        pNode = &pParse->aNode[pParse->nNode-1];
182173        if( pNode->eType!=JSON_STRING ) return -1;
182174        pNode->jnFlags |= JNODE_LABEL;
182175        j = x;
182176        while( safe_isspace(z[j]) ){ j++; }
182177        if( z[j]!=':' ) return -1;
182178        j++;
182179        x = jsonParseValue(pParse, j);
182180        pParse->iDepth--;
182181        if( x<0 ) return -1;
182182        j = x;
182183        while( safe_isspace(z[j]) ){ j++; }
182184        c = z[j];
182185        if( c==',' ) continue;
182186        if( c!='}' ) return -1;
182187        break;
182188      }
182189      pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
182190      return j+1;
182191    }else if( c=='[' ){
182192      /* Parse array */
182193      iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
182194      if( iThis<0 ) return -1;
182195      for(j=i+1;;j++){
182196        while( safe_isspace(z[j]) ){ j++; }
182197        if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
182198        x = jsonParseValue(pParse, j);
182199        pParse->iDepth--;
182200        if( x<0 ){
182201          if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
182202          return -1;
182203        }
182204        j = x;
182205        while( safe_isspace(z[j]) ){ j++; }
182206        c = z[j];
182207        if( c==',' ) continue;
182208        if( c!=']' ) return -1;
182209        break;
182210      }
182211      pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
182212      return j+1;
182213    }else if( c=='"' ){
182214      /* Parse string */
182215      u8 jnFlags = 0;
182216      j = i+1;
182217      for(;;){
182218        c = z[j];
182219        if( (c & ~0x1f)==0 ){
182220          /* Control characters are not allowed in strings */
182221          return -1;
182222        }
182223        if( c=='\\' ){
182224          c = z[++j];
182225          if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
182226             || c=='n' || c=='r' || c=='t'
182227             || (c=='u' && jsonIs4Hex(z+j+1)) ){
182228            jnFlags = JNODE_ESCAPE;
182229          }else{
182230            return -1;
182231          }
182232        }else if( c=='"' ){
182233          break;
182234        }
182235        j++;
182236      }
182237      jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
182238      if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
182239      return j+1;
182240    }else if( c=='n'
182241           && strncmp(z+i,"null",4)==0
182242           && !safe_isalnum(z[i+4]) ){
182243      jsonParseAddNode(pParse, JSON_NULL, 0, 0);
182244      return i+4;
182245    }else if( c=='t'
182246           && strncmp(z+i,"true",4)==0
182247           && !safe_isalnum(z[i+4]) ){
182248      jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
182249      return i+4;
182250    }else if( c=='f'
182251           && strncmp(z+i,"false",5)==0
182252           && !safe_isalnum(z[i+5]) ){
182253      jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
182254      return i+5;
182255    }else if( c=='-' || (c>='0' && c<='9') ){
182256      /* Parse number */
182257      u8 seenDP = 0;
182258      u8 seenE = 0;
182259      assert( '-' < '0' );
182260      if( c<='0' ){
182261        j = c=='-' ? i+1 : i;
182262        if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
182263      }
182264      j = i+1;
182265      for(;; j++){
182266        c = z[j];
182267        if( c>='0' && c<='9' ) continue;
182268        if( c=='.' ){
182269          if( z[j-1]=='-' ) return -1;
182270          if( seenDP ) return -1;
182271          seenDP = 1;
182272          continue;
182273        }
182274        if( c=='e' || c=='E' ){
182275          if( z[j-1]<'0' ) return -1;
182276          if( seenE ) return -1;
182277          seenDP = seenE = 1;
182278          c = z[j+1];
182279          if( c=='+' || c=='-' ){
182280            j++;
182281            c = z[j+1];
182282          }
182283          if( c<'0' || c>'9' ) return -1;
182284          continue;
182285        }
182286        break;
182287      }
182288      if( z[j-1]<'0' ) return -1;
182289      jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
182290                          j - i, &z[i]);
182291      return j;
182292    }else if( c=='}' ){
182293      return -2;  /* End of {...} */
182294    }else if( c==']' ){
182295      return -3;  /* End of [...] */
182296    }else if( c==0 ){
182297      return 0;   /* End of file */
182298    }else{
182299      return -1;  /* Syntax error */
182300    }
182301  }
182302  
182303  /*
182304  ** Parse a complete JSON string.  Return 0 on success or non-zero if there
182305  ** are any errors.  If an error occurs, free all memory associated with
182306  ** pParse.
182307  **
182308  ** pParse is uninitialized when this routine is called.
182309  */
182310  static int jsonParse(
182311    JsonParse *pParse,           /* Initialize and fill this JsonParse object */
182312    sqlite3_context *pCtx,       /* Report errors here */
182313    const char *zJson            /* Input JSON text to be parsed */
182314  ){
182315    int i;
182316    memset(pParse, 0, sizeof(*pParse));
182317    if( zJson==0 ) return 1;
182318    pParse->zJson = zJson;
182319    i = jsonParseValue(pParse, 0);
182320    if( pParse->oom ) i = -1;
182321    if( i>0 ){
182322      assert( pParse->iDepth==0 );
182323      while( safe_isspace(zJson[i]) ) i++;
182324      if( zJson[i] ) i = -1;
182325    }
182326    if( i<=0 ){
182327      if( pCtx!=0 ){
182328        if( pParse->oom ){
182329          sqlite3_result_error_nomem(pCtx);
182330        }else{
182331          sqlite3_result_error(pCtx, "malformed JSON", -1);
182332        }
182333      }
182334      jsonParseReset(pParse);
182335      return 1;
182336    }
182337    return 0;
182338  }
182339  
182340  /* Mark node i of pParse as being a child of iParent.  Call recursively
182341  ** to fill in all the descendants of node i.
182342  */
182343  static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
182344    JsonNode *pNode = &pParse->aNode[i];
182345    u32 j;
182346    pParse->aUp[i] = iParent;
182347    switch( pNode->eType ){
182348      case JSON_ARRAY: {
182349        for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
182350          jsonParseFillInParentage(pParse, i+j, i);
182351        }
182352        break;
182353      }
182354      case JSON_OBJECT: {
182355        for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
182356          pParse->aUp[i+j] = i;
182357          jsonParseFillInParentage(pParse, i+j+1, i);
182358        }
182359        break;
182360      }
182361      default: {
182362        break;
182363      }
182364    }
182365  }
182366  
182367  /*
182368  ** Compute the parentage of all nodes in a completed parse.
182369  */
182370  static int jsonParseFindParents(JsonParse *pParse){
182371    u32 *aUp;
182372    assert( pParse->aUp==0 );
182373    aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
182374    if( aUp==0 ){
182375      pParse->oom = 1;
182376      return SQLITE_NOMEM;
182377    }
182378    jsonParseFillInParentage(pParse, 0, 0);
182379    return SQLITE_OK;
182380  }
182381  
182382  /*
182383  ** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
182384  */
182385  #define JSON_CACHE_ID  (-429938)
182386  
182387  /*
182388  ** Obtain a complete parse of the JSON found in the first argument
182389  ** of the argv array.  Use the sqlite3_get_auxdata() cache for this
182390  ** parse if it is available.  If the cache is not available or if it
182391  ** is no longer valid, parse the JSON again and return the new parse,
182392  ** and also register the new parse so that it will be available for
182393  ** future sqlite3_get_auxdata() calls.
182394  */
182395  static JsonParse *jsonParseCached(
182396    sqlite3_context *pCtx,
182397    sqlite3_value **argv
182398  ){
182399    const char *zJson = (const char*)sqlite3_value_text(argv[0]);
182400    int nJson = sqlite3_value_bytes(argv[0]);
182401    JsonParse *p;
182402    if( zJson==0 ) return 0;
182403    p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
182404    if( p && p->nJson==nJson && memcmp(p->zJson,zJson,nJson)==0 ){
182405      p->nErr = 0;
182406      return p; /* The cached entry matches, so return it */
182407    }
182408    p = sqlite3_malloc( sizeof(*p) + nJson + 1 );
182409    if( p==0 ){
182410      sqlite3_result_error_nomem(pCtx);
182411      return 0;
182412    }
182413    memset(p, 0, sizeof(*p));
182414    p->zJson = (char*)&p[1];
182415    memcpy((char*)p->zJson, zJson, nJson+1);
182416    if( jsonParse(p, pCtx, p->zJson) ){
182417      sqlite3_free(p);
182418      return 0;
182419    }
182420    p->nJson = nJson;
182421    sqlite3_set_auxdata(pCtx, JSON_CACHE_ID, p, (void(*)(void*))jsonParseFree);
182422    return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
182423  }
182424  
182425  /*
182426  ** Compare the OBJECT label at pNode against zKey,nKey.  Return true on
182427  ** a match.
182428  */
182429  static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
182430    if( pNode->jnFlags & JNODE_RAW ){
182431      if( pNode->n!=nKey ) return 0;
182432      return strncmp(pNode->u.zJContent, zKey, nKey)==0;
182433    }else{
182434      if( pNode->n!=nKey+2 ) return 0;
182435      return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
182436    }
182437  }
182438  
182439  /* forward declaration */
182440  static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
182441  
182442  /*
182443  ** Search along zPath to find the node specified.  Return a pointer
182444  ** to that node, or NULL if zPath is malformed or if there is no such
182445  ** node.
182446  **
182447  ** If pApnd!=0, then try to append new nodes to complete zPath if it is
182448  ** possible to do so and if no existing node corresponds to zPath.  If
182449  ** new nodes are appended *pApnd is set to 1.
182450  */
182451  static JsonNode *jsonLookupStep(
182452    JsonParse *pParse,      /* The JSON to search */
182453    u32 iRoot,              /* Begin the search at this node */
182454    const char *zPath,      /* The path to search */
182455    int *pApnd,             /* Append nodes to complete path if not NULL */
182456    const char **pzErr      /* Make *pzErr point to any syntax error in zPath */
182457  ){
182458    u32 i, j, nKey;
182459    const char *zKey;
182460    JsonNode *pRoot = &pParse->aNode[iRoot];
182461    if( zPath[0]==0 ) return pRoot;
182462    if( zPath[0]=='.' ){
182463      if( pRoot->eType!=JSON_OBJECT ) return 0;
182464      zPath++;
182465      if( zPath[0]=='"' ){
182466        zKey = zPath + 1;
182467        for(i=1; zPath[i] && zPath[i]!='"'; i++){}
182468        nKey = i-1;
182469        if( zPath[i] ){
182470          i++;
182471        }else{
182472          *pzErr = zPath;
182473          return 0;
182474        }
182475      }else{
182476        zKey = zPath;
182477        for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
182478        nKey = i;
182479      }
182480      if( nKey==0 ){
182481        *pzErr = zPath;
182482        return 0;
182483      }
182484      j = 1;
182485      for(;;){
182486        while( j<=pRoot->n ){
182487          if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
182488            return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
182489          }
182490          j++;
182491          j += jsonNodeSize(&pRoot[j]);
182492        }
182493        if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
182494        iRoot += pRoot->u.iAppend;
182495        pRoot = &pParse->aNode[iRoot];
182496        j = 1;
182497      }
182498      if( pApnd ){
182499        u32 iStart, iLabel;
182500        JsonNode *pNode;
182501        iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
182502        iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
182503        zPath += i;
182504        pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
182505        if( pParse->oom ) return 0;
182506        if( pNode ){
182507          pRoot = &pParse->aNode[iRoot];
182508          pRoot->u.iAppend = iStart - iRoot;
182509          pRoot->jnFlags |= JNODE_APPEND;
182510          pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
182511        }
182512        return pNode;
182513      }
182514    }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
182515      if( pRoot->eType!=JSON_ARRAY ) return 0;
182516      i = 0;
182517      j = 1;
182518      while( safe_isdigit(zPath[j]) ){
182519        i = i*10 + zPath[j] - '0';
182520        j++;
182521      }
182522      if( zPath[j]!=']' ){
182523        *pzErr = zPath;
182524        return 0;
182525      }
182526      zPath += j + 1;
182527      j = 1;
182528      for(;;){
182529        while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
182530          if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
182531          j += jsonNodeSize(&pRoot[j]);
182532        }
182533        if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
182534        iRoot += pRoot->u.iAppend;
182535        pRoot = &pParse->aNode[iRoot];
182536        j = 1;
182537      }
182538      if( j<=pRoot->n ){
182539        return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
182540      }
182541      if( i==0 && pApnd ){
182542        u32 iStart;
182543        JsonNode *pNode;
182544        iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
182545        pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
182546        if( pParse->oom ) return 0;
182547        if( pNode ){
182548          pRoot = &pParse->aNode[iRoot];
182549          pRoot->u.iAppend = iStart - iRoot;
182550          pRoot->jnFlags |= JNODE_APPEND;
182551        }
182552        return pNode;
182553      }
182554    }else{
182555      *pzErr = zPath;
182556    }
182557    return 0;
182558  }
182559  
182560  /*
182561  ** Append content to pParse that will complete zPath.  Return a pointer
182562  ** to the inserted node, or return NULL if the append fails.
182563  */
182564  static JsonNode *jsonLookupAppend(
182565    JsonParse *pParse,     /* Append content to the JSON parse */
182566    const char *zPath,     /* Description of content to append */
182567    int *pApnd,            /* Set this flag to 1 */
182568    const char **pzErr     /* Make this point to any syntax error */
182569  ){
182570    *pApnd = 1;
182571    if( zPath[0]==0 ){
182572      jsonParseAddNode(pParse, JSON_NULL, 0, 0);
182573      return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
182574    }
182575    if( zPath[0]=='.' ){
182576      jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
182577    }else if( strncmp(zPath,"[0]",3)==0 ){
182578      jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
182579    }else{
182580      return 0;
182581    }
182582    if( pParse->oom ) return 0;
182583    return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
182584  }
182585  
182586  /*
182587  ** Return the text of a syntax error message on a JSON path.  Space is
182588  ** obtained from sqlite3_malloc().
182589  */
182590  static char *jsonPathSyntaxError(const char *zErr){
182591    return sqlite3_mprintf("JSON path error near '%q'", zErr);
182592  }
182593  
182594  /*
182595  ** Do a node lookup using zPath.  Return a pointer to the node on success.
182596  ** Return NULL if not found or if there is an error.
182597  **
182598  ** On an error, write an error message into pCtx and increment the
182599  ** pParse->nErr counter.
182600  **
182601  ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
182602  ** nodes are appended.
182603  */
182604  static JsonNode *jsonLookup(
182605    JsonParse *pParse,      /* The JSON to search */
182606    const char *zPath,      /* The path to search */
182607    int *pApnd,             /* Append nodes to complete path if not NULL */
182608    sqlite3_context *pCtx   /* Report errors here, if not NULL */
182609  ){
182610    const char *zErr = 0;
182611    JsonNode *pNode = 0;
182612    char *zMsg;
182613  
182614    if( zPath==0 ) return 0;
182615    if( zPath[0]!='$' ){
182616      zErr = zPath;
182617      goto lookup_err;
182618    }
182619    zPath++;
182620    pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
182621    if( zErr==0 ) return pNode;
182622  
182623  lookup_err:
182624    pParse->nErr++;
182625    assert( zErr!=0 && pCtx!=0 );
182626    zMsg = jsonPathSyntaxError(zErr);
182627    if( zMsg ){
182628      sqlite3_result_error(pCtx, zMsg, -1);
182629      sqlite3_free(zMsg);
182630    }else{
182631      sqlite3_result_error_nomem(pCtx);
182632    }
182633    return 0;
182634  }
182635  
182636  
182637  /*
182638  ** Report the wrong number of arguments for json_insert(), json_replace()
182639  ** or json_set().
182640  */
182641  static void jsonWrongNumArgs(
182642    sqlite3_context *pCtx,
182643    const char *zFuncName
182644  ){
182645    char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
182646                                 zFuncName);
182647    sqlite3_result_error(pCtx, zMsg, -1);
182648    sqlite3_free(zMsg);     
182649  }
182650  
182651  /*
182652  ** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
182653  */
182654  static void jsonRemoveAllNulls(JsonNode *pNode){
182655    int i, n;
182656    assert( pNode->eType==JSON_OBJECT );
182657    n = pNode->n;
182658    for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
182659      switch( pNode[i].eType ){
182660        case JSON_NULL:
182661          pNode[i].jnFlags |= JNODE_REMOVE;
182662          break;
182663        case JSON_OBJECT:
182664          jsonRemoveAllNulls(&pNode[i]);
182665          break;
182666      }
182667    }
182668  }
182669  
182670  
182671  /****************************************************************************
182672  ** SQL functions used for testing and debugging
182673  ****************************************************************************/
182674  
182675  #ifdef SQLITE_DEBUG
182676  /*
182677  ** The json_parse(JSON) function returns a string which describes
182678  ** a parse of the JSON provided.  Or it returns NULL if JSON is not
182679  ** well-formed.
182680  */
182681  static void jsonParseFunc(
182682    sqlite3_context *ctx,
182683    int argc,
182684    sqlite3_value **argv
182685  ){
182686    JsonString s;       /* Output string - not real JSON */
182687    JsonParse x;        /* The parse */
182688    u32 i;
182689  
182690    assert( argc==1 );
182691    if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
182692    jsonParseFindParents(&x);
182693    jsonInit(&s, ctx);
182694    for(i=0; i<x.nNode; i++){
182695      const char *zType;
182696      if( x.aNode[i].jnFlags & JNODE_LABEL ){
182697        assert( x.aNode[i].eType==JSON_STRING );
182698        zType = "label";
182699      }else{
182700        zType = jsonType[x.aNode[i].eType];
182701      }
182702      jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
182703                 i, zType, x.aNode[i].n, x.aUp[i]);
182704      if( x.aNode[i].u.zJContent!=0 ){
182705        jsonAppendRaw(&s, " ", 1);
182706        jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
182707      }
182708      jsonAppendRaw(&s, "\n", 1);
182709    }
182710    jsonParseReset(&x);
182711    jsonResult(&s);
182712  }
182713  
182714  /*
182715  ** The json_test1(JSON) function return true (1) if the input is JSON
182716  ** text generated by another json function.  It returns (0) if the input
182717  ** is not known to be JSON.
182718  */
182719  static void jsonTest1Func(
182720    sqlite3_context *ctx,
182721    int argc,
182722    sqlite3_value **argv
182723  ){
182724    UNUSED_PARAM(argc);
182725    sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
182726  }
182727  #endif /* SQLITE_DEBUG */
182728  
182729  /****************************************************************************
182730  ** Scalar SQL function implementations
182731  ****************************************************************************/
182732  
182733  /*
182734  ** Implementation of the json_QUOTE(VALUE) function.  Return a JSON value
182735  ** corresponding to the SQL value input.  Mostly this means putting 
182736  ** double-quotes around strings and returning the unquoted string "null"
182737  ** when given a NULL input.
182738  */
182739  static void jsonQuoteFunc(
182740    sqlite3_context *ctx,
182741    int argc,
182742    sqlite3_value **argv
182743  ){
182744    JsonString jx;
182745    UNUSED_PARAM(argc);
182746  
182747    jsonInit(&jx, ctx);
182748    jsonAppendValue(&jx, argv[0]);
182749    jsonResult(&jx);
182750    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
182751  }
182752  
182753  /*
182754  ** Implementation of the json_array(VALUE,...) function.  Return a JSON
182755  ** array that contains all values given in arguments.  Or if any argument
182756  ** is a BLOB, throw an error.
182757  */
182758  static void jsonArrayFunc(
182759    sqlite3_context *ctx,
182760    int argc,
182761    sqlite3_value **argv
182762  ){
182763    int i;
182764    JsonString jx;
182765  
182766    jsonInit(&jx, ctx);
182767    jsonAppendChar(&jx, '[');
182768    for(i=0; i<argc; i++){
182769      jsonAppendSeparator(&jx);
182770      jsonAppendValue(&jx, argv[i]);
182771    }
182772    jsonAppendChar(&jx, ']');
182773    jsonResult(&jx);
182774    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
182775  }
182776  
182777  
182778  /*
182779  ** json_array_length(JSON)
182780  ** json_array_length(JSON, PATH)
182781  **
182782  ** Return the number of elements in the top-level JSON array.  
182783  ** Return 0 if the input is not a well-formed JSON array.
182784  */
182785  static void jsonArrayLengthFunc(
182786    sqlite3_context *ctx,
182787    int argc,
182788    sqlite3_value **argv
182789  ){
182790    JsonParse *p;          /* The parse */
182791    sqlite3_int64 n = 0;
182792    u32 i;
182793    JsonNode *pNode;
182794  
182795    p = jsonParseCached(ctx, argv);
182796    if( p==0 ) return;
182797    assert( p->nNode );
182798    if( argc==2 ){
182799      const char *zPath = (const char*)sqlite3_value_text(argv[1]);
182800      pNode = jsonLookup(p, zPath, 0, ctx);
182801    }else{
182802      pNode = p->aNode;
182803    }
182804    if( pNode==0 ){
182805      return;
182806    }
182807    if( pNode->eType==JSON_ARRAY ){
182808      assert( (pNode->jnFlags & JNODE_APPEND)==0 );
182809      for(i=1; i<=pNode->n; n++){
182810        i += jsonNodeSize(&pNode[i]);
182811      }
182812    }
182813    sqlite3_result_int64(ctx, n);
182814  }
182815  
182816  /*
182817  ** json_extract(JSON, PATH, ...)
182818  **
182819  ** Return the element described by PATH.  Return NULL if there is no
182820  ** PATH element.  If there are multiple PATHs, then return a JSON array
182821  ** with the result from each path.  Throw an error if the JSON or any PATH
182822  ** is malformed.
182823  */
182824  static void jsonExtractFunc(
182825    sqlite3_context *ctx,
182826    int argc,
182827    sqlite3_value **argv
182828  ){
182829    JsonParse *p;          /* The parse */
182830    JsonNode *pNode;
182831    const char *zPath;
182832    JsonString jx;
182833    int i;
182834  
182835    if( argc<2 ) return;
182836    p = jsonParseCached(ctx, argv);
182837    if( p==0 ) return;
182838    jsonInit(&jx, ctx);
182839    jsonAppendChar(&jx, '[');
182840    for(i=1; i<argc; i++){
182841      zPath = (const char*)sqlite3_value_text(argv[i]);
182842      pNode = jsonLookup(p, zPath, 0, ctx);
182843      if( p->nErr ) break;
182844      if( argc>2 ){
182845        jsonAppendSeparator(&jx);
182846        if( pNode ){
182847          jsonRenderNode(pNode, &jx, 0);
182848        }else{
182849          jsonAppendRaw(&jx, "null", 4);
182850        }
182851      }else if( pNode ){
182852        jsonReturn(pNode, ctx, 0);
182853      }
182854    }
182855    if( argc>2 && i==argc ){
182856      jsonAppendChar(&jx, ']');
182857      jsonResult(&jx);
182858      sqlite3_result_subtype(ctx, JSON_SUBTYPE);
182859    }
182860    jsonReset(&jx);
182861  }
182862  
182863  /* This is the RFC 7396 MergePatch algorithm.
182864  */
182865  static JsonNode *jsonMergePatch(
182866    JsonParse *pParse,   /* The JSON parser that contains the TARGET */
182867    u32 iTarget,         /* Node of the TARGET in pParse */
182868    JsonNode *pPatch     /* The PATCH */
182869  ){
182870    u32 i, j;
182871    u32 iRoot;
182872    JsonNode *pTarget;
182873    if( pPatch->eType!=JSON_OBJECT ){
182874      return pPatch;
182875    }
182876    assert( iTarget>=0 && iTarget<pParse->nNode );
182877    pTarget = &pParse->aNode[iTarget];
182878    assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
182879    if( pTarget->eType!=JSON_OBJECT ){
182880      jsonRemoveAllNulls(pPatch);
182881      return pPatch;
182882    }
182883    iRoot = iTarget;
182884    for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
182885      u32 nKey;
182886      const char *zKey;
182887      assert( pPatch[i].eType==JSON_STRING );
182888      assert( pPatch[i].jnFlags & JNODE_LABEL );
182889      nKey = pPatch[i].n;
182890      zKey = pPatch[i].u.zJContent;
182891      assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
182892      for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
182893        assert( pTarget[j].eType==JSON_STRING );
182894        assert( pTarget[j].jnFlags & JNODE_LABEL );
182895        assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
182896        if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
182897          if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
182898          if( pPatch[i+1].eType==JSON_NULL ){
182899            pTarget[j+1].jnFlags |= JNODE_REMOVE;
182900          }else{
182901            JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
182902            if( pNew==0 ) return 0;
182903            pTarget = &pParse->aNode[iTarget];
182904            if( pNew!=&pTarget[j+1] ){
182905              pTarget[j+1].u.pPatch = pNew;
182906              pTarget[j+1].jnFlags |= JNODE_PATCH;
182907            }
182908          }
182909          break;
182910        }
182911      }
182912      if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
182913        int iStart, iPatch;
182914        iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
182915        jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
182916        iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
182917        if( pParse->oom ) return 0;
182918        jsonRemoveAllNulls(pPatch);
182919        pTarget = &pParse->aNode[iTarget];
182920        pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
182921        pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
182922        iRoot = iStart;
182923        pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
182924        pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
182925      }
182926    }
182927    return pTarget;
182928  }
182929  
182930  /*
182931  ** Implementation of the json_mergepatch(JSON1,JSON2) function.  Return a JSON
182932  ** object that is the result of running the RFC 7396 MergePatch() algorithm
182933  ** on the two arguments.
182934  */
182935  static void jsonPatchFunc(
182936    sqlite3_context *ctx,
182937    int argc,
182938    sqlite3_value **argv
182939  ){
182940    JsonParse x;     /* The JSON that is being patched */
182941    JsonParse y;     /* The patch */
182942    JsonNode *pResult;   /* The result of the merge */
182943  
182944    UNUSED_PARAM(argc);
182945    if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
182946    if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
182947      jsonParseReset(&x);
182948      return;
182949    }
182950    pResult = jsonMergePatch(&x, 0, y.aNode);
182951    assert( pResult!=0 || x.oom );
182952    if( pResult ){
182953      jsonReturnJson(pResult, ctx, 0);
182954    }else{
182955      sqlite3_result_error_nomem(ctx);
182956    }
182957    jsonParseReset(&x);
182958    jsonParseReset(&y);
182959  }
182960  
182961  
182962  /*
182963  ** Implementation of the json_object(NAME,VALUE,...) function.  Return a JSON
182964  ** object that contains all name/value given in arguments.  Or if any name
182965  ** is not a string or if any value is a BLOB, throw an error.
182966  */
182967  static void jsonObjectFunc(
182968    sqlite3_context *ctx,
182969    int argc,
182970    sqlite3_value **argv
182971  ){
182972    int i;
182973    JsonString jx;
182974    const char *z;
182975    u32 n;
182976  
182977    if( argc&1 ){
182978      sqlite3_result_error(ctx, "json_object() requires an even number "
182979                                    "of arguments", -1);
182980      return;
182981    }
182982    jsonInit(&jx, ctx);
182983    jsonAppendChar(&jx, '{');
182984    for(i=0; i<argc; i+=2){
182985      if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
182986        sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
182987        jsonReset(&jx);
182988        return;
182989      }
182990      jsonAppendSeparator(&jx);
182991      z = (const char*)sqlite3_value_text(argv[i]);
182992      n = (u32)sqlite3_value_bytes(argv[i]);
182993      jsonAppendString(&jx, z, n);
182994      jsonAppendChar(&jx, ':');
182995      jsonAppendValue(&jx, argv[i+1]);
182996    }
182997    jsonAppendChar(&jx, '}');
182998    jsonResult(&jx);
182999    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
183000  }
183001  
183002  
183003  /*
183004  ** json_remove(JSON, PATH, ...)
183005  **
183006  ** Remove the named elements from JSON and return the result.  malformed
183007  ** JSON or PATH arguments result in an error.
183008  */
183009  static void jsonRemoveFunc(
183010    sqlite3_context *ctx,
183011    int argc,
183012    sqlite3_value **argv
183013  ){
183014    JsonParse x;          /* The parse */
183015    JsonNode *pNode;
183016    const char *zPath;
183017    u32 i;
183018  
183019    if( argc<1 ) return;
183020    if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
183021    assert( x.nNode );
183022    for(i=1; i<(u32)argc; i++){
183023      zPath = (const char*)sqlite3_value_text(argv[i]);
183024      if( zPath==0 ) goto remove_done;
183025      pNode = jsonLookup(&x, zPath, 0, ctx);
183026      if( x.nErr ) goto remove_done;
183027      if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
183028    }
183029    if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
183030      jsonReturnJson(x.aNode, ctx, 0);
183031    }
183032  remove_done:
183033    jsonParseReset(&x);
183034  }
183035  
183036  /*
183037  ** json_replace(JSON, PATH, VALUE, ...)
183038  **
183039  ** Replace the value at PATH with VALUE.  If PATH does not already exist,
183040  ** this routine is a no-op.  If JSON or PATH is malformed, throw an error.
183041  */
183042  static void jsonReplaceFunc(
183043    sqlite3_context *ctx,
183044    int argc,
183045    sqlite3_value **argv
183046  ){
183047    JsonParse x;          /* The parse */
183048    JsonNode *pNode;
183049    const char *zPath;
183050    u32 i;
183051  
183052    if( argc<1 ) return;
183053    if( (argc&1)==0 ) {
183054      jsonWrongNumArgs(ctx, "replace");
183055      return;
183056    }
183057    if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
183058    assert( x.nNode );
183059    for(i=1; i<(u32)argc; i+=2){
183060      zPath = (const char*)sqlite3_value_text(argv[i]);
183061      pNode = jsonLookup(&x, zPath, 0, ctx);
183062      if( x.nErr ) goto replace_err;
183063      if( pNode ){
183064        pNode->jnFlags |= (u8)JNODE_REPLACE;
183065        pNode->u.iReplace = i + 1;
183066      }
183067    }
183068    if( x.aNode[0].jnFlags & JNODE_REPLACE ){
183069      sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
183070    }else{
183071      jsonReturnJson(x.aNode, ctx, argv);
183072    }
183073  replace_err:
183074    jsonParseReset(&x);
183075  }
183076  
183077  /*
183078  ** json_set(JSON, PATH, VALUE, ...)
183079  **
183080  ** Set the value at PATH to VALUE.  Create the PATH if it does not already
183081  ** exist.  Overwrite existing values that do exist.
183082  ** If JSON or PATH is malformed, throw an error.
183083  **
183084  ** json_insert(JSON, PATH, VALUE, ...)
183085  **
183086  ** Create PATH and initialize it to VALUE.  If PATH already exists, this
183087  ** routine is a no-op.  If JSON or PATH is malformed, throw an error.
183088  */
183089  static void jsonSetFunc(
183090    sqlite3_context *ctx,
183091    int argc,
183092    sqlite3_value **argv
183093  ){
183094    JsonParse x;          /* The parse */
183095    JsonNode *pNode;
183096    const char *zPath;
183097    u32 i;
183098    int bApnd;
183099    int bIsSet = *(int*)sqlite3_user_data(ctx);
183100  
183101    if( argc<1 ) return;
183102    if( (argc&1)==0 ) {
183103      jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
183104      return;
183105    }
183106    if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
183107    assert( x.nNode );
183108    for(i=1; i<(u32)argc; i+=2){
183109      zPath = (const char*)sqlite3_value_text(argv[i]);
183110      bApnd = 0;
183111      pNode = jsonLookup(&x, zPath, &bApnd, ctx);
183112      if( x.oom ){
183113        sqlite3_result_error_nomem(ctx);
183114        goto jsonSetDone;
183115      }else if( x.nErr ){
183116        goto jsonSetDone;
183117      }else if( pNode && (bApnd || bIsSet) ){
183118        pNode->jnFlags |= (u8)JNODE_REPLACE;
183119        pNode->u.iReplace = i + 1;
183120      }
183121    }
183122    if( x.aNode[0].jnFlags & JNODE_REPLACE ){
183123      sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
183124    }else{
183125      jsonReturnJson(x.aNode, ctx, argv);
183126    }
183127  jsonSetDone:
183128    jsonParseReset(&x);
183129  }
183130  
183131  /*
183132  ** json_type(JSON)
183133  ** json_type(JSON, PATH)
183134  **
183135  ** Return the top-level "type" of a JSON string.  Throw an error if
183136  ** either the JSON or PATH inputs are not well-formed.
183137  */
183138  static void jsonTypeFunc(
183139    sqlite3_context *ctx,
183140    int argc,
183141    sqlite3_value **argv
183142  ){
183143    JsonParse x;          /* The parse */
183144    const char *zPath;
183145    JsonNode *pNode;
183146  
183147    if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
183148    assert( x.nNode );
183149    if( argc==2 ){
183150      zPath = (const char*)sqlite3_value_text(argv[1]);
183151      pNode = jsonLookup(&x, zPath, 0, ctx);
183152    }else{
183153      pNode = x.aNode;
183154    }
183155    if( pNode ){
183156      sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
183157    }
183158    jsonParseReset(&x);
183159  }
183160  
183161  /*
183162  ** json_valid(JSON)
183163  **
183164  ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
183165  ** Return 0 otherwise.
183166  */
183167  static void jsonValidFunc(
183168    sqlite3_context *ctx,
183169    int argc,
183170    sqlite3_value **argv
183171  ){
183172    JsonParse x;          /* The parse */
183173    int rc = 0;
183174  
183175    UNUSED_PARAM(argc);
183176    if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
183177      rc = 1;
183178    }
183179    jsonParseReset(&x);
183180    sqlite3_result_int(ctx, rc);
183181  }
183182  
183183  
183184  /****************************************************************************
183185  ** Aggregate SQL function implementations
183186  ****************************************************************************/
183187  /*
183188  ** json_group_array(VALUE)
183189  **
183190  ** Return a JSON array composed of all values in the aggregate.
183191  */
183192  static void jsonArrayStep(
183193    sqlite3_context *ctx,
183194    int argc,
183195    sqlite3_value **argv
183196  ){
183197    JsonString *pStr;
183198    UNUSED_PARAM(argc);
183199    pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
183200    if( pStr ){
183201      if( pStr->zBuf==0 ){
183202        jsonInit(pStr, ctx);
183203        jsonAppendChar(pStr, '[');
183204      }else{
183205        jsonAppendChar(pStr, ',');
183206        pStr->pCtx = ctx;
183207      }
183208      jsonAppendValue(pStr, argv[0]);
183209    }
183210  }
183211  static void jsonArrayFinal(sqlite3_context *ctx){
183212    JsonString *pStr;
183213    pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
183214    if( pStr ){
183215      pStr->pCtx = ctx;
183216      jsonAppendChar(pStr, ']');
183217      if( pStr->bErr ){
183218        if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
183219        assert( pStr->bStatic );
183220      }else{
183221        sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
183222                            pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
183223        pStr->bStatic = 1;
183224      }
183225    }else{
183226      sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
183227    }
183228    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
183229  }
183230  
183231  /*
183232  ** json_group_obj(NAME,VALUE)
183233  **
183234  ** Return a JSON object composed of all names and values in the aggregate.
183235  */
183236  static void jsonObjectStep(
183237    sqlite3_context *ctx,
183238    int argc,
183239    sqlite3_value **argv
183240  ){
183241    JsonString *pStr;
183242    const char *z;
183243    u32 n;
183244    UNUSED_PARAM(argc);
183245    pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
183246    if( pStr ){
183247      if( pStr->zBuf==0 ){
183248        jsonInit(pStr, ctx);
183249        jsonAppendChar(pStr, '{');
183250      }else{
183251        jsonAppendChar(pStr, ',');
183252        pStr->pCtx = ctx;
183253      }
183254      z = (const char*)sqlite3_value_text(argv[0]);
183255      n = (u32)sqlite3_value_bytes(argv[0]);
183256      jsonAppendString(pStr, z, n);
183257      jsonAppendChar(pStr, ':');
183258      jsonAppendValue(pStr, argv[1]);
183259    }
183260  }
183261  static void jsonObjectFinal(sqlite3_context *ctx){
183262    JsonString *pStr;
183263    pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
183264    if( pStr ){
183265      jsonAppendChar(pStr, '}');
183266      if( pStr->bErr ){
183267        if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
183268        assert( pStr->bStatic );
183269      }else{
183270        sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
183271                            pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
183272        pStr->bStatic = 1;
183273      }
183274    }else{
183275      sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
183276    }
183277    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
183278  }
183279  
183280  
183281  #ifndef SQLITE_OMIT_VIRTUALTABLE
183282  /****************************************************************************
183283  ** The json_each virtual table
183284  ****************************************************************************/
183285  typedef struct JsonEachCursor JsonEachCursor;
183286  struct JsonEachCursor {
183287    sqlite3_vtab_cursor base;  /* Base class - must be first */
183288    u32 iRowid;                /* The rowid */
183289    u32 iBegin;                /* The first node of the scan */
183290    u32 i;                     /* Index in sParse.aNode[] of current row */
183291    u32 iEnd;                  /* EOF when i equals or exceeds this value */
183292    u8 eType;                  /* Type of top-level element */
183293    u8 bRecursive;             /* True for json_tree().  False for json_each() */
183294    char *zJson;               /* Input JSON */
183295    char *zRoot;               /* Path by which to filter zJson */
183296    JsonParse sParse;          /* Parse of the input JSON */
183297  };
183298  
183299  /* Constructor for the json_each virtual table */
183300  static int jsonEachConnect(
183301    sqlite3 *db,
183302    void *pAux,
183303    int argc, const char *const*argv,
183304    sqlite3_vtab **ppVtab,
183305    char **pzErr
183306  ){
183307    sqlite3_vtab *pNew;
183308    int rc;
183309  
183310  /* Column numbers */
183311  #define JEACH_KEY     0
183312  #define JEACH_VALUE   1
183313  #define JEACH_TYPE    2
183314  #define JEACH_ATOM    3
183315  #define JEACH_ID      4
183316  #define JEACH_PARENT  5
183317  #define JEACH_FULLKEY 6
183318  #define JEACH_PATH    7
183319  #define JEACH_JSON    8
183320  #define JEACH_ROOT    9
183321  
183322    UNUSED_PARAM(pzErr);
183323    UNUSED_PARAM(argv);
183324    UNUSED_PARAM(argc);
183325    UNUSED_PARAM(pAux);
183326    rc = sqlite3_declare_vtab(db, 
183327       "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
183328                      "json HIDDEN,root HIDDEN)");
183329    if( rc==SQLITE_OK ){
183330      pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
183331      if( pNew==0 ) return SQLITE_NOMEM;
183332      memset(pNew, 0, sizeof(*pNew));
183333    }
183334    return rc;
183335  }
183336  
183337  /* destructor for json_each virtual table */
183338  static int jsonEachDisconnect(sqlite3_vtab *pVtab){
183339    sqlite3_free(pVtab);
183340    return SQLITE_OK;
183341  }
183342  
183343  /* constructor for a JsonEachCursor object for json_each(). */
183344  static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
183345    JsonEachCursor *pCur;
183346  
183347    UNUSED_PARAM(p);
183348    pCur = sqlite3_malloc( sizeof(*pCur) );
183349    if( pCur==0 ) return SQLITE_NOMEM;
183350    memset(pCur, 0, sizeof(*pCur));
183351    *ppCursor = &pCur->base;
183352    return SQLITE_OK;
183353  }
183354  
183355  /* constructor for a JsonEachCursor object for json_tree(). */
183356  static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
183357    int rc = jsonEachOpenEach(p, ppCursor);
183358    if( rc==SQLITE_OK ){
183359      JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
183360      pCur->bRecursive = 1;
183361    }
183362    return rc;
183363  }
183364  
183365  /* Reset a JsonEachCursor back to its original state.  Free any memory
183366  ** held. */
183367  static void jsonEachCursorReset(JsonEachCursor *p){
183368    sqlite3_free(p->zJson);
183369    sqlite3_free(p->zRoot);
183370    jsonParseReset(&p->sParse);
183371    p->iRowid = 0;
183372    p->i = 0;
183373    p->iEnd = 0;
183374    p->eType = 0;
183375    p->zJson = 0;
183376    p->zRoot = 0;
183377  }
183378  
183379  /* Destructor for a jsonEachCursor object */
183380  static int jsonEachClose(sqlite3_vtab_cursor *cur){
183381    JsonEachCursor *p = (JsonEachCursor*)cur;
183382    jsonEachCursorReset(p);
183383    sqlite3_free(cur);
183384    return SQLITE_OK;
183385  }
183386  
183387  /* Return TRUE if the jsonEachCursor object has been advanced off the end
183388  ** of the JSON object */
183389  static int jsonEachEof(sqlite3_vtab_cursor *cur){
183390    JsonEachCursor *p = (JsonEachCursor*)cur;
183391    return p->i >= p->iEnd;
183392  }
183393  
183394  /* Advance the cursor to the next element for json_tree() */
183395  static int jsonEachNext(sqlite3_vtab_cursor *cur){
183396    JsonEachCursor *p = (JsonEachCursor*)cur;
183397    if( p->bRecursive ){
183398      if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
183399      p->i++;
183400      p->iRowid++;
183401      if( p->i<p->iEnd ){
183402        u32 iUp = p->sParse.aUp[p->i];
183403        JsonNode *pUp = &p->sParse.aNode[iUp];
183404        p->eType = pUp->eType;
183405        if( pUp->eType==JSON_ARRAY ){
183406          if( iUp==p->i-1 ){
183407            pUp->u.iKey = 0;
183408          }else{
183409            pUp->u.iKey++;
183410          }
183411        }
183412      }
183413    }else{
183414      switch( p->eType ){
183415        case JSON_ARRAY: {
183416          p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
183417          p->iRowid++;
183418          break;
183419        }
183420        case JSON_OBJECT: {
183421          p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
183422          p->iRowid++;
183423          break;
183424        }
183425        default: {
183426          p->i = p->iEnd;
183427          break;
183428        }
183429      }
183430    }
183431    return SQLITE_OK;
183432  }
183433  
183434  /* Append the name of the path for element i to pStr
183435  */
183436  static void jsonEachComputePath(
183437    JsonEachCursor *p,       /* The cursor */
183438    JsonString *pStr,        /* Write the path here */
183439    u32 i                    /* Path to this element */
183440  ){
183441    JsonNode *pNode, *pUp;
183442    u32 iUp;
183443    if( i==0 ){
183444      jsonAppendChar(pStr, '$');
183445      return;
183446    }
183447    iUp = p->sParse.aUp[i];
183448    jsonEachComputePath(p, pStr, iUp);
183449    pNode = &p->sParse.aNode[i];
183450    pUp = &p->sParse.aNode[iUp];
183451    if( pUp->eType==JSON_ARRAY ){
183452      jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
183453    }else{
183454      assert( pUp->eType==JSON_OBJECT );
183455      if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
183456      assert( pNode->eType==JSON_STRING );
183457      assert( pNode->jnFlags & JNODE_LABEL );
183458      jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
183459    }
183460  }
183461  
183462  /* Return the value of a column */
183463  static int jsonEachColumn(
183464    sqlite3_vtab_cursor *cur,   /* The cursor */
183465    sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
183466    int i                       /* Which column to return */
183467  ){
183468    JsonEachCursor *p = (JsonEachCursor*)cur;
183469    JsonNode *pThis = &p->sParse.aNode[p->i];
183470    switch( i ){
183471      case JEACH_KEY: {
183472        if( p->i==0 ) break;
183473        if( p->eType==JSON_OBJECT ){
183474          jsonReturn(pThis, ctx, 0);
183475        }else if( p->eType==JSON_ARRAY ){
183476          u32 iKey;
183477          if( p->bRecursive ){
183478            if( p->iRowid==0 ) break;
183479            iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
183480          }else{
183481            iKey = p->iRowid;
183482          }
183483          sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
183484        }
183485        break;
183486      }
183487      case JEACH_VALUE: {
183488        if( pThis->jnFlags & JNODE_LABEL ) pThis++;
183489        jsonReturn(pThis, ctx, 0);
183490        break;
183491      }
183492      case JEACH_TYPE: {
183493        if( pThis->jnFlags & JNODE_LABEL ) pThis++;
183494        sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
183495        break;
183496      }
183497      case JEACH_ATOM: {
183498        if( pThis->jnFlags & JNODE_LABEL ) pThis++;
183499        if( pThis->eType>=JSON_ARRAY ) break;
183500        jsonReturn(pThis, ctx, 0);
183501        break;
183502      }
183503      case JEACH_ID: {
183504        sqlite3_result_int64(ctx, 
183505           (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
183506        break;
183507      }
183508      case JEACH_PARENT: {
183509        if( p->i>p->iBegin && p->bRecursive ){
183510          sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
183511        }
183512        break;
183513      }
183514      case JEACH_FULLKEY: {
183515        JsonString x;
183516        jsonInit(&x, ctx);
183517        if( p->bRecursive ){
183518          jsonEachComputePath(p, &x, p->i);
183519        }else{
183520          if( p->zRoot ){
183521            jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
183522          }else{
183523            jsonAppendChar(&x, '$');
183524          }
183525          if( p->eType==JSON_ARRAY ){
183526            jsonPrintf(30, &x, "[%d]", p->iRowid);
183527          }else{
183528            jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
183529          }
183530        }
183531        jsonResult(&x);
183532        break;
183533      }
183534      case JEACH_PATH: {
183535        if( p->bRecursive ){
183536          JsonString x;
183537          jsonInit(&x, ctx);
183538          jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
183539          jsonResult(&x);
183540          break;
183541        }
183542        /* For json_each() path and root are the same so fall through
183543        ** into the root case */
183544      }
183545      default: {
183546        const char *zRoot = p->zRoot;
183547        if( zRoot==0 ) zRoot = "$";
183548        sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
183549        break;
183550      }
183551      case JEACH_JSON: {
183552        assert( i==JEACH_JSON );
183553        sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
183554        break;
183555      }
183556    }
183557    return SQLITE_OK;
183558  }
183559  
183560  /* Return the current rowid value */
183561  static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
183562    JsonEachCursor *p = (JsonEachCursor*)cur;
183563    *pRowid = p->iRowid;
183564    return SQLITE_OK;
183565  }
183566  
183567  /* The query strategy is to look for an equality constraint on the json
183568  ** column.  Without such a constraint, the table cannot operate.  idxNum is
183569  ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
183570  ** and 0 otherwise.
183571  */
183572  static int jsonEachBestIndex(
183573    sqlite3_vtab *tab,
183574    sqlite3_index_info *pIdxInfo
183575  ){
183576    int i;
183577    int jsonIdx = -1;
183578    int rootIdx = -1;
183579    const struct sqlite3_index_constraint *pConstraint;
183580  
183581    UNUSED_PARAM(tab);
183582    pConstraint = pIdxInfo->aConstraint;
183583    for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
183584      if( pConstraint->usable==0 ) continue;
183585      if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
183586      switch( pConstraint->iColumn ){
183587        case JEACH_JSON:   jsonIdx = i;    break;
183588        case JEACH_ROOT:   rootIdx = i;    break;
183589        default:           /* no-op */     break;
183590      }
183591    }
183592    if( jsonIdx<0 ){
183593      pIdxInfo->idxNum = 0;
183594      pIdxInfo->estimatedCost = 1e99;
183595    }else{
183596      pIdxInfo->estimatedCost = 1.0;
183597      pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
183598      pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
183599      if( rootIdx<0 ){
183600        pIdxInfo->idxNum = 1;
183601      }else{
183602        pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
183603        pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
183604        pIdxInfo->idxNum = 3;
183605      }
183606    }
183607    return SQLITE_OK;
183608  }
183609  
183610  /* Start a search on a new JSON string */
183611  static int jsonEachFilter(
183612    sqlite3_vtab_cursor *cur,
183613    int idxNum, const char *idxStr,
183614    int argc, sqlite3_value **argv
183615  ){
183616    JsonEachCursor *p = (JsonEachCursor*)cur;
183617    const char *z;
183618    const char *zRoot = 0;
183619    sqlite3_int64 n;
183620  
183621    UNUSED_PARAM(idxStr);
183622    UNUSED_PARAM(argc);
183623    jsonEachCursorReset(p);
183624    if( idxNum==0 ) return SQLITE_OK;
183625    z = (const char*)sqlite3_value_text(argv[0]);
183626    if( z==0 ) return SQLITE_OK;
183627    n = sqlite3_value_bytes(argv[0]);
183628    p->zJson = sqlite3_malloc64( n+1 );
183629    if( p->zJson==0 ) return SQLITE_NOMEM;
183630    memcpy(p->zJson, z, (size_t)n+1);
183631    if( jsonParse(&p->sParse, 0, p->zJson) ){
183632      int rc = SQLITE_NOMEM;
183633      if( p->sParse.oom==0 ){
183634        sqlite3_free(cur->pVtab->zErrMsg);
183635        cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
183636        if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
183637      }
183638      jsonEachCursorReset(p);
183639      return rc;
183640    }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
183641      jsonEachCursorReset(p);
183642      return SQLITE_NOMEM;
183643    }else{
183644      JsonNode *pNode = 0;
183645      if( idxNum==3 ){
183646        const char *zErr = 0;
183647        zRoot = (const char*)sqlite3_value_text(argv[1]);
183648        if( zRoot==0 ) return SQLITE_OK;
183649        n = sqlite3_value_bytes(argv[1]);
183650        p->zRoot = sqlite3_malloc64( n+1 );
183651        if( p->zRoot==0 ) return SQLITE_NOMEM;
183652        memcpy(p->zRoot, zRoot, (size_t)n+1);
183653        if( zRoot[0]!='$' ){
183654          zErr = zRoot;
183655        }else{
183656          pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
183657        }
183658        if( zErr ){
183659          sqlite3_free(cur->pVtab->zErrMsg);
183660          cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
183661          jsonEachCursorReset(p);
183662          return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
183663        }else if( pNode==0 ){
183664          return SQLITE_OK;
183665        }
183666      }else{
183667        pNode = p->sParse.aNode;
183668      }
183669      p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
183670      p->eType = pNode->eType;
183671      if( p->eType>=JSON_ARRAY ){
183672        pNode->u.iKey = 0;
183673        p->iEnd = p->i + pNode->n + 1;
183674        if( p->bRecursive ){
183675          p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
183676          if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
183677            p->i--;
183678          }
183679        }else{
183680          p->i++;
183681        }
183682      }else{
183683        p->iEnd = p->i+1;
183684      }
183685    }
183686    return SQLITE_OK;
183687  }
183688  
183689  /* The methods of the json_each virtual table */
183690  static sqlite3_module jsonEachModule = {
183691    0,                         /* iVersion */
183692    0,                         /* xCreate */
183693    jsonEachConnect,           /* xConnect */
183694    jsonEachBestIndex,         /* xBestIndex */
183695    jsonEachDisconnect,        /* xDisconnect */
183696    0,                         /* xDestroy */
183697    jsonEachOpenEach,          /* xOpen - open a cursor */
183698    jsonEachClose,             /* xClose - close a cursor */
183699    jsonEachFilter,            /* xFilter - configure scan constraints */
183700    jsonEachNext,              /* xNext - advance a cursor */
183701    jsonEachEof,               /* xEof - check for end of scan */
183702    jsonEachColumn,            /* xColumn - read data */
183703    jsonEachRowid,             /* xRowid - read data */
183704    0,                         /* xUpdate */
183705    0,                         /* xBegin */
183706    0,                         /* xSync */
183707    0,                         /* xCommit */
183708    0,                         /* xRollback */
183709    0,                         /* xFindMethod */
183710    0,                         /* xRename */
183711    0,                         /* xSavepoint */
183712    0,                         /* xRelease */
183713    0                          /* xRollbackTo */
183714  };
183715  
183716  /* The methods of the json_tree virtual table. */
183717  static sqlite3_module jsonTreeModule = {
183718    0,                         /* iVersion */
183719    0,                         /* xCreate */
183720    jsonEachConnect,           /* xConnect */
183721    jsonEachBestIndex,         /* xBestIndex */
183722    jsonEachDisconnect,        /* xDisconnect */
183723    0,                         /* xDestroy */
183724    jsonEachOpenTree,          /* xOpen - open a cursor */
183725    jsonEachClose,             /* xClose - close a cursor */
183726    jsonEachFilter,            /* xFilter - configure scan constraints */
183727    jsonEachNext,              /* xNext - advance a cursor */
183728    jsonEachEof,               /* xEof - check for end of scan */
183729    jsonEachColumn,            /* xColumn - read data */
183730    jsonEachRowid,             /* xRowid - read data */
183731    0,                         /* xUpdate */
183732    0,                         /* xBegin */
183733    0,                         /* xSync */
183734    0,                         /* xCommit */
183735    0,                         /* xRollback */
183736    0,                         /* xFindMethod */
183737    0,                         /* xRename */
183738    0,                         /* xSavepoint */
183739    0,                         /* xRelease */
183740    0                          /* xRollbackTo */
183741  };
183742  #endif /* SQLITE_OMIT_VIRTUALTABLE */
183743  
183744  /****************************************************************************
183745  ** The following routines are the only publically visible identifiers in this
183746  ** file.  Call the following routines in order to register the various SQL
183747  ** functions and the virtual table implemented by this file.
183748  ****************************************************************************/
183749  
183750  SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
183751    int rc = SQLITE_OK;
183752    unsigned int i;
183753    static const struct {
183754       const char *zName;
183755       int nArg;
183756       int flag;
183757       void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
183758    } aFunc[] = {
183759      { "json",                 1, 0,   jsonRemoveFunc        },
183760      { "json_array",          -1, 0,   jsonArrayFunc         },
183761      { "json_array_length",    1, 0,   jsonArrayLengthFunc   },
183762      { "json_array_length",    2, 0,   jsonArrayLengthFunc   },
183763      { "json_extract",        -1, 0,   jsonExtractFunc       },
183764      { "json_insert",         -1, 0,   jsonSetFunc           },
183765      { "json_object",         -1, 0,   jsonObjectFunc        },
183766      { "json_patch",           2, 0,   jsonPatchFunc         },
183767      { "json_quote",           1, 0,   jsonQuoteFunc         },
183768      { "json_remove",         -1, 0,   jsonRemoveFunc        },
183769      { "json_replace",        -1, 0,   jsonReplaceFunc       },
183770      { "json_set",            -1, 1,   jsonSetFunc           },
183771      { "json_type",            1, 0,   jsonTypeFunc          },
183772      { "json_type",            2, 0,   jsonTypeFunc          },
183773      { "json_valid",           1, 0,   jsonValidFunc         },
183774  
183775  #if SQLITE_DEBUG
183776      /* DEBUG and TESTING functions */
183777      { "json_parse",           1, 0,   jsonParseFunc         },
183778      { "json_test1",           1, 0,   jsonTest1Func         },
183779  #endif
183780    };
183781    static const struct {
183782       const char *zName;
183783       int nArg;
183784       void (*xStep)(sqlite3_context*,int,sqlite3_value**);
183785       void (*xFinal)(sqlite3_context*);
183786    } aAgg[] = {
183787      { "json_group_array",     1,   jsonArrayStep,   jsonArrayFinal  },
183788      { "json_group_object",    2,   jsonObjectStep,  jsonObjectFinal },
183789    };
183790  #ifndef SQLITE_OMIT_VIRTUALTABLE
183791    static const struct {
183792       const char *zName;
183793       sqlite3_module *pModule;
183794    } aMod[] = {
183795      { "json_each",            &jsonEachModule               },
183796      { "json_tree",            &jsonTreeModule               },
183797    };
183798  #endif
183799    for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
183800      rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
183801                                   SQLITE_UTF8 | SQLITE_DETERMINISTIC, 
183802                                   (void*)&aFunc[i].flag,
183803                                   aFunc[i].xFunc, 0, 0);
183804    }
183805    for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
183806      rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg,
183807                                   SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
183808                                   0, aAgg[i].xStep, aAgg[i].xFinal);
183809    }
183810  #ifndef SQLITE_OMIT_VIRTUALTABLE
183811    for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
183812      rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
183813    }
183814  #endif
183815    return rc;
183816  }
183817  
183818  
183819  #ifndef SQLITE_CORE
183820  #ifdef _WIN32
183821  __declspec(dllexport)
183822  #endif
183823  SQLITE_API int sqlite3_json_init(
183824    sqlite3 *db, 
183825    char **pzErrMsg, 
183826    const sqlite3_api_routines *pApi
183827  ){
183828    SQLITE_EXTENSION_INIT2(pApi);
183829    (void)pzErrMsg;  /* Unused parameter */
183830    return sqlite3Json1Init(db);
183831  }
183832  #endif
183833  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
183834  
183835  /************** End of json1.c ***********************************************/
183836  /************** Begin file fts5.c ********************************************/
183837  
183838  
183839  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) 
183840  
183841  #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
183842  # define NDEBUG 1
183843  #endif
183844  #if defined(NDEBUG) && defined(SQLITE_DEBUG)
183845  # undef NDEBUG
183846  #endif
183847  
183848  /*
183849  ** 2014 May 31
183850  **
183851  ** The author disclaims copyright to this source code.  In place of
183852  ** a legal notice, here is a blessing:
183853  **
183854  **    May you do good and not evil.
183855  **    May you find forgiveness for yourself and forgive others.
183856  **    May you share freely, never taking more than you give.
183857  **
183858  ******************************************************************************
183859  **
183860  ** Interfaces to extend FTS5. Using the interfaces defined in this file, 
183861  ** FTS5 may be extended with:
183862  **
183863  **     * custom tokenizers, and
183864  **     * custom auxiliary functions.
183865  */
183866  
183867  
183868  #ifndef _FTS5_H
183869  #define _FTS5_H
183870  
183871  /* #include "sqlite3.h" */
183872  
183873  #if 0
183874  extern "C" {
183875  #endif
183876  
183877  /*************************************************************************
183878  ** CUSTOM AUXILIARY FUNCTIONS
183879  **
183880  ** Virtual table implementations may overload SQL functions by implementing
183881  ** the sqlite3_module.xFindFunction() method.
183882  */
183883  
183884  typedef struct Fts5ExtensionApi Fts5ExtensionApi;
183885  typedef struct Fts5Context Fts5Context;
183886  typedef struct Fts5PhraseIter Fts5PhraseIter;
183887  
183888  typedef void (*fts5_extension_function)(
183889    const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
183890    Fts5Context *pFts,              /* First arg to pass to pApi functions */
183891    sqlite3_context *pCtx,          /* Context for returning result/error */
183892    int nVal,                       /* Number of values in apVal[] array */
183893    sqlite3_value **apVal           /* Array of trailing arguments */
183894  );
183895  
183896  struct Fts5PhraseIter {
183897    const unsigned char *a;
183898    const unsigned char *b;
183899  };
183900  
183901  /*
183902  ** EXTENSION API FUNCTIONS
183903  **
183904  ** xUserData(pFts):
183905  **   Return a copy of the context pointer the extension function was 
183906  **   registered with.
183907  **
183908  ** xColumnTotalSize(pFts, iCol, pnToken):
183909  **   If parameter iCol is less than zero, set output variable *pnToken
183910  **   to the total number of tokens in the FTS5 table. Or, if iCol is
183911  **   non-negative but less than the number of columns in the table, return
183912  **   the total number of tokens in column iCol, considering all rows in 
183913  **   the FTS5 table.
183914  **
183915  **   If parameter iCol is greater than or equal to the number of columns
183916  **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
183917  **   an OOM condition or IO error), an appropriate SQLite error code is 
183918  **   returned.
183919  **
183920  ** xColumnCount(pFts):
183921  **   Return the number of columns in the table.
183922  **
183923  ** xColumnSize(pFts, iCol, pnToken):
183924  **   If parameter iCol is less than zero, set output variable *pnToken
183925  **   to the total number of tokens in the current row. Or, if iCol is
183926  **   non-negative but less than the number of columns in the table, set
183927  **   *pnToken to the number of tokens in column iCol of the current row.
183928  **
183929  **   If parameter iCol is greater than or equal to the number of columns
183930  **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
183931  **   an OOM condition or IO error), an appropriate SQLite error code is 
183932  **   returned.
183933  **
183934  **   This function may be quite inefficient if used with an FTS5 table
183935  **   created with the "columnsize=0" option.
183936  **
183937  ** xColumnText:
183938  **   This function attempts to retrieve the text of column iCol of the
183939  **   current document. If successful, (*pz) is set to point to a buffer
183940  **   containing the text in utf-8 encoding, (*pn) is set to the size in bytes
183941  **   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
183942  **   if an error occurs, an SQLite error code is returned and the final values
183943  **   of (*pz) and (*pn) are undefined.
183944  **
183945  ** xPhraseCount:
183946  **   Returns the number of phrases in the current query expression.
183947  **
183948  ** xPhraseSize:
183949  **   Returns the number of tokens in phrase iPhrase of the query. Phrases
183950  **   are numbered starting from zero.
183951  **
183952  ** xInstCount:
183953  **   Set *pnInst to the total number of occurrences of all phrases within
183954  **   the query within the current row. Return SQLITE_OK if successful, or
183955  **   an error code (i.e. SQLITE_NOMEM) if an error occurs.
183956  **
183957  **   This API can be quite slow if used with an FTS5 table created with the
183958  **   "detail=none" or "detail=column" option. If the FTS5 table is created 
183959  **   with either "detail=none" or "detail=column" and "content=" option 
183960  **   (i.e. if it is a contentless table), then this API always returns 0.
183961  **
183962  ** xInst:
183963  **   Query for the details of phrase match iIdx within the current row.
183964  **   Phrase matches are numbered starting from zero, so the iIdx argument
183965  **   should be greater than or equal to zero and smaller than the value
183966  **   output by xInstCount().
183967  **
183968  **   Usually, output parameter *piPhrase is set to the phrase number, *piCol
183969  **   to the column in which it occurs and *piOff the token offset of the
183970  **   first token of the phrase. The exception is if the table was created
183971  **   with the offsets=0 option specified. In this case *piOff is always
183972  **   set to -1.
183973  **
183974  **   Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM) 
183975  **   if an error occurs.
183976  **
183977  **   This API can be quite slow if used with an FTS5 table created with the
183978  **   "detail=none" or "detail=column" option. 
183979  **
183980  ** xRowid:
183981  **   Returns the rowid of the current row.
183982  **
183983  ** xTokenize:
183984  **   Tokenize text using the tokenizer belonging to the FTS5 table.
183985  **
183986  ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
183987  **   This API function is used to query the FTS table for phrase iPhrase
183988  **   of the current query. Specifically, a query equivalent to:
183989  **
183990  **       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
183991  **
183992  **   with $p set to a phrase equivalent to the phrase iPhrase of the
183993  **   current query is executed. Any column filter that applies to
183994  **   phrase iPhrase of the current query is included in $p. For each 
183995  **   row visited, the callback function passed as the fourth argument 
183996  **   is invoked. The context and API objects passed to the callback 
183997  **   function may be used to access the properties of each matched row.
183998  **   Invoking Api.xUserData() returns a copy of the pointer passed as 
183999  **   the third argument to pUserData.
184000  **
184001  **   If the callback function returns any value other than SQLITE_OK, the
184002  **   query is abandoned and the xQueryPhrase function returns immediately.
184003  **   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
184004  **   Otherwise, the error code is propagated upwards.
184005  **
184006  **   If the query runs to completion without incident, SQLITE_OK is returned.
184007  **   Or, if some error occurs before the query completes or is aborted by
184008  **   the callback, an SQLite error code is returned.
184009  **
184010  **
184011  ** xSetAuxdata(pFts5, pAux, xDelete)
184012  **
184013  **   Save the pointer passed as the second argument as the extension functions 
184014  **   "auxiliary data". The pointer may then be retrieved by the current or any
184015  **   future invocation of the same fts5 extension function made as part of
184016  **   of the same MATCH query using the xGetAuxdata() API.
184017  **
184018  **   Each extension function is allocated a single auxiliary data slot for
184019  **   each FTS query (MATCH expression). If the extension function is invoked 
184020  **   more than once for a single FTS query, then all invocations share a 
184021  **   single auxiliary data context.
184022  **
184023  **   If there is already an auxiliary data pointer when this function is
184024  **   invoked, then it is replaced by the new pointer. If an xDelete callback
184025  **   was specified along with the original pointer, it is invoked at this
184026  **   point.
184027  **
184028  **   The xDelete callback, if one is specified, is also invoked on the
184029  **   auxiliary data pointer after the FTS5 query has finished.
184030  **
184031  **   If an error (e.g. an OOM condition) occurs within this function, an
184032  **   the auxiliary data is set to NULL and an error code returned. If the
184033  **   xDelete parameter was not NULL, it is invoked on the auxiliary data
184034  **   pointer before returning.
184035  **
184036  **
184037  ** xGetAuxdata(pFts5, bClear)
184038  **
184039  **   Returns the current auxiliary data pointer for the fts5 extension 
184040  **   function. See the xSetAuxdata() method for details.
184041  **
184042  **   If the bClear argument is non-zero, then the auxiliary data is cleared
184043  **   (set to NULL) before this function returns. In this case the xDelete,
184044  **   if any, is not invoked.
184045  **
184046  **
184047  ** xRowCount(pFts5, pnRow)
184048  **
184049  **   This function is used to retrieve the total number of rows in the table.
184050  **   In other words, the same value that would be returned by:
184051  **
184052  **        SELECT count(*) FROM ftstable;
184053  **
184054  ** xPhraseFirst()
184055  **   This function is used, along with type Fts5PhraseIter and the xPhraseNext
184056  **   method, to iterate through all instances of a single query phrase within
184057  **   the current row. This is the same information as is accessible via the
184058  **   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
184059  **   to use, this API may be faster under some circumstances. To iterate 
184060  **   through instances of phrase iPhrase, use the following code:
184061  **
184062  **       Fts5PhraseIter iter;
184063  **       int iCol, iOff;
184064  **       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
184065  **           iCol>=0;
184066  **           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
184067  **       ){
184068  **         // An instance of phrase iPhrase at offset iOff of column iCol
184069  **       }
184070  **
184071  **   The Fts5PhraseIter structure is defined above. Applications should not
184072  **   modify this structure directly - it should only be used as shown above
184073  **   with the xPhraseFirst() and xPhraseNext() API methods (and by
184074  **   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
184075  **
184076  **   This API can be quite slow if used with an FTS5 table created with the
184077  **   "detail=none" or "detail=column" option. If the FTS5 table is created 
184078  **   with either "detail=none" or "detail=column" and "content=" option 
184079  **   (i.e. if it is a contentless table), then this API always iterates
184080  **   through an empty set (all calls to xPhraseFirst() set iCol to -1).
184081  **
184082  ** xPhraseNext()
184083  **   See xPhraseFirst above.
184084  **
184085  ** xPhraseFirstColumn()
184086  **   This function and xPhraseNextColumn() are similar to the xPhraseFirst()
184087  **   and xPhraseNext() APIs described above. The difference is that instead
184088  **   of iterating through all instances of a phrase in the current row, these
184089  **   APIs are used to iterate through the set of columns in the current row
184090  **   that contain one or more instances of a specified phrase. For example:
184091  **
184092  **       Fts5PhraseIter iter;
184093  **       int iCol;
184094  **       for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
184095  **           iCol>=0;
184096  **           pApi->xPhraseNextColumn(pFts, &iter, &iCol)
184097  **       ){
184098  **         // Column iCol contains at least one instance of phrase iPhrase
184099  **       }
184100  **
184101  **   This API can be quite slow if used with an FTS5 table created with the
184102  **   "detail=none" option. If the FTS5 table is created with either 
184103  **   "detail=none" "content=" option (i.e. if it is a contentless table), 
184104  **   then this API always iterates through an empty set (all calls to 
184105  **   xPhraseFirstColumn() set iCol to -1).
184106  **
184107  **   The information accessed using this API and its companion
184108  **   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
184109  **   (or xInst/xInstCount). The chief advantage of this API is that it is
184110  **   significantly more efficient than those alternatives when used with
184111  **   "detail=column" tables.  
184112  **
184113  ** xPhraseNextColumn()
184114  **   See xPhraseFirstColumn above.
184115  */
184116  struct Fts5ExtensionApi {
184117    int iVersion;                   /* Currently always set to 3 */
184118  
184119    void *(*xUserData)(Fts5Context*);
184120  
184121    int (*xColumnCount)(Fts5Context*);
184122    int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
184123    int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
184124  
184125    int (*xTokenize)(Fts5Context*, 
184126      const char *pText, int nText, /* Text to tokenize */
184127      void *pCtx,                   /* Context passed to xToken() */
184128      int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
184129    );
184130  
184131    int (*xPhraseCount)(Fts5Context*);
184132    int (*xPhraseSize)(Fts5Context*, int iPhrase);
184133  
184134    int (*xInstCount)(Fts5Context*, int *pnInst);
184135    int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
184136  
184137    sqlite3_int64 (*xRowid)(Fts5Context*);
184138    int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
184139    int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
184140  
184141    int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
184142      int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
184143    );
184144    int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
184145    void *(*xGetAuxdata)(Fts5Context*, int bClear);
184146  
184147    int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
184148    void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
184149  
184150    int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
184151    void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
184152  };
184153  
184154  /* 
184155  ** CUSTOM AUXILIARY FUNCTIONS
184156  *************************************************************************/
184157  
184158  /*************************************************************************
184159  ** CUSTOM TOKENIZERS
184160  **
184161  ** Applications may also register custom tokenizer types. A tokenizer 
184162  ** is registered by providing fts5 with a populated instance of the 
184163  ** following structure. All structure methods must be defined, setting
184164  ** any member of the fts5_tokenizer struct to NULL leads to undefined
184165  ** behaviour. The structure methods are expected to function as follows:
184166  **
184167  ** xCreate:
184168  **   This function is used to allocate and initialize a tokenizer instance.
184169  **   A tokenizer instance is required to actually tokenize text.
184170  **
184171  **   The first argument passed to this function is a copy of the (void*)
184172  **   pointer provided by the application when the fts5_tokenizer object
184173  **   was registered with FTS5 (the third argument to xCreateTokenizer()). 
184174  **   The second and third arguments are an array of nul-terminated strings
184175  **   containing the tokenizer arguments, if any, specified following the
184176  **   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
184177  **   to create the FTS5 table.
184178  **
184179  **   The final argument is an output variable. If successful, (*ppOut) 
184180  **   should be set to point to the new tokenizer handle and SQLITE_OK
184181  **   returned. If an error occurs, some value other than SQLITE_OK should
184182  **   be returned. In this case, fts5 assumes that the final value of *ppOut 
184183  **   is undefined.
184184  **
184185  ** xDelete:
184186  **   This function is invoked to delete a tokenizer handle previously
184187  **   allocated using xCreate(). Fts5 guarantees that this function will
184188  **   be invoked exactly once for each successful call to xCreate().
184189  **
184190  ** xTokenize:
184191  **   This function is expected to tokenize the nText byte string indicated 
184192  **   by argument pText. pText may or may not be nul-terminated. The first
184193  **   argument passed to this function is a pointer to an Fts5Tokenizer object
184194  **   returned by an earlier call to xCreate().
184195  **
184196  **   The second argument indicates the reason that FTS5 is requesting
184197  **   tokenization of the supplied text. This is always one of the following
184198  **   four values:
184199  **
184200  **   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
184201  **            or removed from the FTS table. The tokenizer is being invoked to
184202  **            determine the set of tokens to add to (or delete from) the
184203  **            FTS index.
184204  **
184205  **       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed 
184206  **            against the FTS index. The tokenizer is being called to tokenize 
184207  **            a bareword or quoted string specified as part of the query.
184208  **
184209  **       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
184210  **            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
184211  **            followed by a "*" character, indicating that the last token
184212  **            returned by the tokenizer will be treated as a token prefix.
184213  **
184214  **       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to 
184215  **            satisfy an fts5_api.xTokenize() request made by an auxiliary
184216  **            function. Or an fts5_api.xColumnSize() request made by the same
184217  **            on a columnsize=0 database.  
184218  **   </ul>
184219  **
184220  **   For each token in the input string, the supplied callback xToken() must
184221  **   be invoked. The first argument to it should be a copy of the pointer
184222  **   passed as the second argument to xTokenize(). The third and fourth
184223  **   arguments are a pointer to a buffer containing the token text, and the
184224  **   size of the token in bytes. The 4th and 5th arguments are the byte offsets
184225  **   of the first byte of and first byte immediately following the text from
184226  **   which the token is derived within the input.
184227  **
184228  **   The second argument passed to the xToken() callback ("tflags") should
184229  **   normally be set to 0. The exception is if the tokenizer supports 
184230  **   synonyms. In this case see the discussion below for details.
184231  **
184232  **   FTS5 assumes the xToken() callback is invoked for each token in the 
184233  **   order that they occur within the input text.
184234  **
184235  **   If an xToken() callback returns any value other than SQLITE_OK, then
184236  **   the tokenization should be abandoned and the xTokenize() method should
184237  **   immediately return a copy of the xToken() return value. Or, if the
184238  **   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
184239  **   if an error occurs with the xTokenize() implementation itself, it
184240  **   may abandon the tokenization and return any error code other than
184241  **   SQLITE_OK or SQLITE_DONE.
184242  **
184243  ** SYNONYM SUPPORT
184244  **
184245  **   Custom tokenizers may also support synonyms. Consider a case in which a
184246  **   user wishes to query for a phrase such as "first place". Using the 
184247  **   built-in tokenizers, the FTS5 query 'first + place' will match instances
184248  **   of "first place" within the document set, but not alternative forms
184249  **   such as "1st place". In some applications, it would be better to match
184250  **   all instances of "first place" or "1st place" regardless of which form
184251  **   the user specified in the MATCH query text.
184252  **
184253  **   There are several ways to approach this in FTS5:
184254  **
184255  **   <ol><li> By mapping all synonyms to a single token. In this case, the 
184256  **            In the above example, this means that the tokenizer returns the
184257  **            same token for inputs "first" and "1st". Say that token is in
184258  **            fact "first", so that when the user inserts the document "I won
184259  **            1st place" entries are added to the index for tokens "i", "won",
184260  **            "first" and "place". If the user then queries for '1st + place',
184261  **            the tokenizer substitutes "first" for "1st" and the query works
184262  **            as expected.
184263  **
184264  **       <li> By adding multiple synonyms for a single term to the FTS index.
184265  **            In this case, when tokenizing query text, the tokenizer may 
184266  **            provide multiple synonyms for a single term within the document.
184267  **            FTS5 then queries the index for each synonym individually. For
184268  **            example, faced with the query:
184269  **
184270  **   <codeblock>
184271  **     ... MATCH 'first place'</codeblock>
184272  **
184273  **            the tokenizer offers both "1st" and "first" as synonyms for the
184274  **            first token in the MATCH query and FTS5 effectively runs a query 
184275  **            similar to:
184276  **
184277  **   <codeblock>
184278  **     ... MATCH '(first OR 1st) place'</codeblock>
184279  **
184280  **            except that, for the purposes of auxiliary functions, the query
184281  **            still appears to contain just two phrases - "(first OR 1st)" 
184282  **            being treated as a single phrase.
184283  **
184284  **       <li> By adding multiple synonyms for a single term to the FTS index.
184285  **            Using this method, when tokenizing document text, the tokenizer
184286  **            provides multiple synonyms for each token. So that when a 
184287  **            document such as "I won first place" is tokenized, entries are
184288  **            added to the FTS index for "i", "won", "first", "1st" and
184289  **            "place".
184290  **
184291  **            This way, even if the tokenizer does not provide synonyms
184292  **            when tokenizing query text (it should not - to do would be
184293  **            inefficient), it doesn't matter if the user queries for 
184294  **            'first + place' or '1st + place', as there are entires in the
184295  **            FTS index corresponding to both forms of the first token.
184296  **   </ol>
184297  **
184298  **   Whether it is parsing document or query text, any call to xToken that
184299  **   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
184300  **   is considered to supply a synonym for the previous token. For example,
184301  **   when parsing the document "I won first place", a tokenizer that supports
184302  **   synonyms would call xToken() 5 times, as follows:
184303  **
184304  **   <codeblock>
184305  **       xToken(pCtx, 0, "i",                      1,  0,  1);
184306  **       xToken(pCtx, 0, "won",                    3,  2,  5);
184307  **       xToken(pCtx, 0, "first",                  5,  6, 11);
184308  **       xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3,  6, 11);
184309  **       xToken(pCtx, 0, "place",                  5, 12, 17);
184310  **</codeblock>
184311  **
184312  **   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
184313  **   xToken() is called. Multiple synonyms may be specified for a single token
184314  **   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence. 
184315  **   There is no limit to the number of synonyms that may be provided for a
184316  **   single token.
184317  **
184318  **   In many cases, method (1) above is the best approach. It does not add 
184319  **   extra data to the FTS index or require FTS5 to query for multiple terms,
184320  **   so it is efficient in terms of disk space and query speed. However, it
184321  **   does not support prefix queries very well. If, as suggested above, the
184322  **   token "first" is subsituted for "1st" by the tokenizer, then the query:
184323  **
184324  **   <codeblock>
184325  **     ... MATCH '1s*'</codeblock>
184326  **
184327  **   will not match documents that contain the token "1st" (as the tokenizer
184328  **   will probably not map "1s" to any prefix of "first").
184329  **
184330  **   For full prefix support, method (3) may be preferred. In this case, 
184331  **   because the index contains entries for both "first" and "1st", prefix
184332  **   queries such as 'fi*' or '1s*' will match correctly. However, because
184333  **   extra entries are added to the FTS index, this method uses more space
184334  **   within the database.
184335  **
184336  **   Method (2) offers a midpoint between (1) and (3). Using this method,
184337  **   a query such as '1s*' will match documents that contain the literal 
184338  **   token "1st", but not "first" (assuming the tokenizer is not able to
184339  **   provide synonyms for prefixes). However, a non-prefix query like '1st'
184340  **   will match against "1st" and "first". This method does not require
184341  **   extra disk space, as no extra entries are added to the FTS index. 
184342  **   On the other hand, it may require more CPU cycles to run MATCH queries,
184343  **   as separate queries of the FTS index are required for each synonym.
184344  **
184345  **   When using methods (2) or (3), it is important that the tokenizer only
184346  **   provide synonyms when tokenizing document text (method (2)) or query
184347  **   text (method (3)), not both. Doing so will not cause any errors, but is
184348  **   inefficient.
184349  */
184350  typedef struct Fts5Tokenizer Fts5Tokenizer;
184351  typedef struct fts5_tokenizer fts5_tokenizer;
184352  struct fts5_tokenizer {
184353    int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
184354    void (*xDelete)(Fts5Tokenizer*);
184355    int (*xTokenize)(Fts5Tokenizer*, 
184356        void *pCtx,
184357        int flags,            /* Mask of FTS5_TOKENIZE_* flags */
184358        const char *pText, int nText, 
184359        int (*xToken)(
184360          void *pCtx,         /* Copy of 2nd argument to xTokenize() */
184361          int tflags,         /* Mask of FTS5_TOKEN_* flags */
184362          const char *pToken, /* Pointer to buffer containing token */
184363          int nToken,         /* Size of token in bytes */
184364          int iStart,         /* Byte offset of token within input text */
184365          int iEnd            /* Byte offset of end of token within input text */
184366        )
184367    );
184368  };
184369  
184370  /* Flags that may be passed as the third argument to xTokenize() */
184371  #define FTS5_TOKENIZE_QUERY     0x0001
184372  #define FTS5_TOKENIZE_PREFIX    0x0002
184373  #define FTS5_TOKENIZE_DOCUMENT  0x0004
184374  #define FTS5_TOKENIZE_AUX       0x0008
184375  
184376  /* Flags that may be passed by the tokenizer implementation back to FTS5
184377  ** as the third argument to the supplied xToken callback. */
184378  #define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */
184379  
184380  /*
184381  ** END OF CUSTOM TOKENIZERS
184382  *************************************************************************/
184383  
184384  /*************************************************************************
184385  ** FTS5 EXTENSION REGISTRATION API
184386  */
184387  typedef struct fts5_api fts5_api;
184388  struct fts5_api {
184389    int iVersion;                   /* Currently always set to 2 */
184390  
184391    /* Create a new tokenizer */
184392    int (*xCreateTokenizer)(
184393      fts5_api *pApi,
184394      const char *zName,
184395      void *pContext,
184396      fts5_tokenizer *pTokenizer,
184397      void (*xDestroy)(void*)
184398    );
184399  
184400    /* Find an existing tokenizer */
184401    int (*xFindTokenizer)(
184402      fts5_api *pApi,
184403      const char *zName,
184404      void **ppContext,
184405      fts5_tokenizer *pTokenizer
184406    );
184407  
184408    /* Create a new auxiliary function */
184409    int (*xCreateFunction)(
184410      fts5_api *pApi,
184411      const char *zName,
184412      void *pContext,
184413      fts5_extension_function xFunction,
184414      void (*xDestroy)(void*)
184415    );
184416  };
184417  
184418  /*
184419  ** END OF REGISTRATION API
184420  *************************************************************************/
184421  
184422  #if 0
184423  }  /* end of the 'extern "C"' block */
184424  #endif
184425  
184426  #endif /* _FTS5_H */
184427  
184428  /*
184429  ** 2014 May 31
184430  **
184431  ** The author disclaims copyright to this source code.  In place of
184432  ** a legal notice, here is a blessing:
184433  **
184434  **    May you do good and not evil.
184435  **    May you find forgiveness for yourself and forgive others.
184436  **    May you share freely, never taking more than you give.
184437  **
184438  ******************************************************************************
184439  **
184440  */
184441  #ifndef _FTS5INT_H
184442  #define _FTS5INT_H
184443  
184444  /* #include "fts5.h" */
184445  /* #include "sqlite3ext.h" */
184446  SQLITE_EXTENSION_INIT1
184447  
184448  /* #include <string.h> */
184449  /* #include <assert.h> */
184450  
184451  #ifndef SQLITE_AMALGAMATION
184452  
184453  typedef unsigned char  u8;
184454  typedef unsigned int   u32;
184455  typedef unsigned short u16;
184456  typedef short i16;
184457  typedef sqlite3_int64 i64;
184458  typedef sqlite3_uint64 u64;
184459  
184460  #ifndef ArraySize
184461  # define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
184462  #endif
184463  
184464  #define testcase(x)
184465  #define ALWAYS(x) 1
184466  #define NEVER(x) 0
184467  
184468  #define MIN(x,y) (((x) < (y)) ? (x) : (y))
184469  #define MAX(x,y) (((x) > (y)) ? (x) : (y))
184470  
184471  /*
184472  ** Constants for the largest and smallest possible 64-bit signed integers.
184473  */
184474  # define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
184475  # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
184476  
184477  #endif
184478  
184479  /* Truncate very long tokens to this many bytes. Hard limit is 
184480  ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
184481  ** field that occurs at the start of each leaf page (see fts5_index.c). */
184482  #define FTS5_MAX_TOKEN_SIZE 32768
184483  
184484  /*
184485  ** Maximum number of prefix indexes on single FTS5 table. This must be
184486  ** less than 32. If it is set to anything large than that, an #error
184487  ** directive in fts5_index.c will cause the build to fail.
184488  */
184489  #define FTS5_MAX_PREFIX_INDEXES 31
184490  
184491  #define FTS5_DEFAULT_NEARDIST 10
184492  #define FTS5_DEFAULT_RANK     "bm25"
184493  
184494  /* Name of rank and rowid columns */
184495  #define FTS5_RANK_NAME "rank"
184496  #define FTS5_ROWID_NAME "rowid"
184497  
184498  #ifdef SQLITE_DEBUG
184499  # define FTS5_CORRUPT sqlite3Fts5Corrupt()
184500  static int sqlite3Fts5Corrupt(void);
184501  #else
184502  # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
184503  #endif
184504  
184505  /*
184506  ** The assert_nc() macro is similar to the assert() macro, except that it
184507  ** is used for assert() conditions that are true only if it can be 
184508  ** guranteed that the database is not corrupt.
184509  */
184510  #ifdef SQLITE_DEBUG
184511  SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
184512  # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
184513  #else
184514  # define assert_nc(x) assert(x)
184515  #endif
184516  
184517  /* Mark a function parameter as unused, to suppress nuisance compiler
184518  ** warnings. */
184519  #ifndef UNUSED_PARAM
184520  # define UNUSED_PARAM(X)  (void)(X)
184521  #endif
184522  
184523  #ifndef UNUSED_PARAM2
184524  # define UNUSED_PARAM2(X, Y)  (void)(X), (void)(Y)
184525  #endif
184526  
184527  typedef struct Fts5Global Fts5Global;
184528  typedef struct Fts5Colset Fts5Colset;
184529  
184530  /* If a NEAR() clump or phrase may only match a specific set of columns, 
184531  ** then an object of the following type is used to record the set of columns.
184532  ** Each entry in the aiCol[] array is a column that may be matched.
184533  **
184534  ** This object is used by fts5_expr.c and fts5_index.c.
184535  */
184536  struct Fts5Colset {
184537    int nCol;
184538    int aiCol[1];
184539  };
184540  
184541  
184542  
184543  /**************************************************************************
184544  ** Interface to code in fts5_config.c. fts5_config.c contains contains code
184545  ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
184546  */
184547  
184548  typedef struct Fts5Config Fts5Config;
184549  
184550  /*
184551  ** An instance of the following structure encodes all information that can
184552  ** be gleaned from the CREATE VIRTUAL TABLE statement.
184553  **
184554  ** And all information loaded from the %_config table.
184555  **
184556  ** nAutomerge:
184557  **   The minimum number of segments that an auto-merge operation should
184558  **   attempt to merge together. A value of 1 sets the object to use the 
184559  **   compile time default. Zero disables auto-merge altogether.
184560  **
184561  ** zContent:
184562  **
184563  ** zContentRowid:
184564  **   The value of the content_rowid= option, if one was specified. Or 
184565  **   the string "rowid" otherwise. This text is not quoted - if it is
184566  **   used as part of an SQL statement it needs to be quoted appropriately.
184567  **
184568  ** zContentExprlist:
184569  **
184570  ** pzErrmsg:
184571  **   This exists in order to allow the fts5_index.c module to return a 
184572  **   decent error message if it encounters a file-format version it does
184573  **   not understand.
184574  **
184575  ** bColumnsize:
184576  **   True if the %_docsize table is created.
184577  **
184578  ** bPrefixIndex:
184579  **   This is only used for debugging. If set to false, any prefix indexes
184580  **   are ignored. This value is configured using:
184581  **
184582  **       INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
184583  **
184584  */
184585  struct Fts5Config {
184586    sqlite3 *db;                    /* Database handle */
184587    char *zDb;                      /* Database holding FTS index (e.g. "main") */
184588    char *zName;                    /* Name of FTS index */
184589    int nCol;                       /* Number of columns */
184590    char **azCol;                   /* Column names */
184591    u8 *abUnindexed;                /* True for unindexed columns */
184592    int nPrefix;                    /* Number of prefix indexes */
184593    int *aPrefix;                   /* Sizes in bytes of nPrefix prefix indexes */
184594    int eContent;                   /* An FTS5_CONTENT value */
184595    char *zContent;                 /* content table */ 
184596    char *zContentRowid;            /* "content_rowid=" option value */ 
184597    int bColumnsize;                /* "columnsize=" option value (dflt==1) */
184598    int eDetail;                    /* FTS5_DETAIL_XXX value */
184599    char *zContentExprlist;
184600    Fts5Tokenizer *pTok;
184601    fts5_tokenizer *pTokApi;
184602  
184603    /* Values loaded from the %_config table */
184604    int iCookie;                    /* Incremented when %_config is modified */
184605    int pgsz;                       /* Approximate page size used in %_data */
184606    int nAutomerge;                 /* 'automerge' setting */
184607    int nCrisisMerge;               /* Maximum allowed segments per level */
184608    int nUsermerge;                 /* 'usermerge' setting */
184609    int nHashSize;                  /* Bytes of memory for in-memory hash */
184610    char *zRank;                    /* Name of rank function */
184611    char *zRankArgs;                /* Arguments to rank function */
184612  
184613    /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
184614    char **pzErrmsg;
184615  
184616  #ifdef SQLITE_DEBUG
184617    int bPrefixIndex;               /* True to use prefix-indexes */
184618  #endif
184619  };
184620  
184621  /* Current expected value of %_config table 'version' field */
184622  #define FTS5_CURRENT_VERSION 4
184623  
184624  #define FTS5_CONTENT_NORMAL   0
184625  #define FTS5_CONTENT_NONE     1
184626  #define FTS5_CONTENT_EXTERNAL 2
184627  
184628  #define FTS5_DETAIL_FULL    0
184629  #define FTS5_DETAIL_NONE    1
184630  #define FTS5_DETAIL_COLUMNS 2
184631  
184632  
184633  
184634  static int sqlite3Fts5ConfigParse(
184635      Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
184636  );
184637  static void sqlite3Fts5ConfigFree(Fts5Config*);
184638  
184639  static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
184640  
184641  static int sqlite3Fts5Tokenize(
184642    Fts5Config *pConfig,            /* FTS5 Configuration object */
184643    int flags,                      /* FTS5_TOKENIZE_* flags */
184644    const char *pText, int nText,   /* Text to tokenize */
184645    void *pCtx,                     /* Context passed to xToken() */
184646    int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
184647  );
184648  
184649  static void sqlite3Fts5Dequote(char *z);
184650  
184651  /* Load the contents of the %_config table */
184652  static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
184653  
184654  /* Set the value of a single config attribute */
184655  static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
184656  
184657  static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
184658  
184659  /*
184660  ** End of interface to code in fts5_config.c.
184661  **************************************************************************/
184662  
184663  /**************************************************************************
184664  ** Interface to code in fts5_buffer.c.
184665  */
184666  
184667  /*
184668  ** Buffer object for the incremental building of string data.
184669  */
184670  typedef struct Fts5Buffer Fts5Buffer;
184671  struct Fts5Buffer {
184672    u8 *p;
184673    int n;
184674    int nSpace;
184675  };
184676  
184677  static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
184678  static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
184679  static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
184680  static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
184681  static void sqlite3Fts5BufferFree(Fts5Buffer*);
184682  static void sqlite3Fts5BufferZero(Fts5Buffer*);
184683  static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
184684  static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
184685  
184686  static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
184687  
184688  #define fts5BufferZero(x)             sqlite3Fts5BufferZero(x)
184689  #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
184690  #define fts5BufferFree(a)             sqlite3Fts5BufferFree(a)
184691  #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
184692  #define fts5BufferSet(a,b,c,d)        sqlite3Fts5BufferSet(a,b,c,d)
184693  
184694  #define fts5BufferGrow(pRc,pBuf,nn) ( \
184695    (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
184696      sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
184697  )
184698  
184699  /* Write and decode big-endian 32-bit integer values */
184700  static void sqlite3Fts5Put32(u8*, int);
184701  static int sqlite3Fts5Get32(const u8*);
184702  
184703  #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
184704  #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
184705  
184706  typedef struct Fts5PoslistReader Fts5PoslistReader;
184707  struct Fts5PoslistReader {
184708    /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
184709    const u8 *a;                    /* Position list to iterate through */
184710    int n;                          /* Size of buffer at a[] in bytes */
184711    int i;                          /* Current offset in a[] */
184712  
184713    u8 bFlag;                       /* For client use (any custom purpose) */
184714  
184715    /* Output variables */
184716    u8 bEof;                        /* Set to true at EOF */
184717    i64 iPos;                       /* (iCol<<32) + iPos */
184718  };
184719  static int sqlite3Fts5PoslistReaderInit(
184720    const u8 *a, int n,             /* Poslist buffer to iterate through */
184721    Fts5PoslistReader *pIter        /* Iterator object to initialize */
184722  );
184723  static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
184724  
184725  typedef struct Fts5PoslistWriter Fts5PoslistWriter;
184726  struct Fts5PoslistWriter {
184727    i64 iPrev;
184728  };
184729  static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
184730  static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
184731  
184732  static int sqlite3Fts5PoslistNext64(
184733    const u8 *a, int n,             /* Buffer containing poslist */
184734    int *pi,                        /* IN/OUT: Offset within a[] */
184735    i64 *piOff                      /* IN/OUT: Current offset */
184736  );
184737  
184738  /* Malloc utility */
184739  static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
184740  static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
184741  
184742  /* Character set tests (like isspace(), isalpha() etc.) */
184743  static int sqlite3Fts5IsBareword(char t);
184744  
184745  
184746  /* Bucket of terms object used by the integrity-check in offsets=0 mode. */
184747  typedef struct Fts5Termset Fts5Termset;
184748  static int sqlite3Fts5TermsetNew(Fts5Termset**);
184749  static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
184750  static void sqlite3Fts5TermsetFree(Fts5Termset*);
184751  
184752  /*
184753  ** End of interface to code in fts5_buffer.c.
184754  **************************************************************************/
184755  
184756  /**************************************************************************
184757  ** Interface to code in fts5_index.c. fts5_index.c contains contains code
184758  ** to access the data stored in the %_data table.
184759  */
184760  
184761  typedef struct Fts5Index Fts5Index;
184762  typedef struct Fts5IndexIter Fts5IndexIter;
184763  
184764  struct Fts5IndexIter {
184765    i64 iRowid;
184766    const u8 *pData;
184767    int nData;
184768    u8 bEof;
184769  };
184770  
184771  #define sqlite3Fts5IterEof(x) ((x)->bEof)
184772  
184773  /*
184774  ** Values used as part of the flags argument passed to IndexQuery().
184775  */
184776  #define FTS5INDEX_QUERY_PREFIX     0x0001   /* Prefix query */
184777  #define FTS5INDEX_QUERY_DESC       0x0002   /* Docs in descending rowid order */
184778  #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004   /* Do not use prefix index */
184779  #define FTS5INDEX_QUERY_SCAN       0x0008   /* Scan query (fts5vocab) */
184780  
184781  /* The following are used internally by the fts5_index.c module. They are
184782  ** defined here only to make it easier to avoid clashes with the flags
184783  ** above. */
184784  #define FTS5INDEX_QUERY_SKIPEMPTY  0x0010
184785  #define FTS5INDEX_QUERY_NOOUTPUT   0x0020
184786  
184787  /*
184788  ** Create/destroy an Fts5Index object.
184789  */
184790  static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
184791  static int sqlite3Fts5IndexClose(Fts5Index *p);
184792  
184793  /*
184794  ** Return a simple checksum value based on the arguments.
184795  */
184796  static u64 sqlite3Fts5IndexEntryCksum(
184797    i64 iRowid, 
184798    int iCol, 
184799    int iPos, 
184800    int iIdx,
184801    const char *pTerm,
184802    int nTerm
184803  );
184804  
184805  /*
184806  ** Argument p points to a buffer containing utf-8 text that is n bytes in 
184807  ** size. Return the number of bytes in the nChar character prefix of the
184808  ** buffer, or 0 if there are less than nChar characters in total.
184809  */
184810  static int sqlite3Fts5IndexCharlenToBytelen(
184811    const char *p, 
184812    int nByte, 
184813    int nChar
184814  );
184815  
184816  /*
184817  ** Open a new iterator to iterate though all rowids that match the 
184818  ** specified token or token prefix.
184819  */
184820  static int sqlite3Fts5IndexQuery(
184821    Fts5Index *p,                   /* FTS index to query */
184822    const char *pToken, int nToken, /* Token (or prefix) to query for */
184823    int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
184824    Fts5Colset *pColset,            /* Match these columns only */
184825    Fts5IndexIter **ppIter          /* OUT: New iterator object */
184826  );
184827  
184828  /*
184829  ** The various operations on open token or token prefix iterators opened
184830  ** using sqlite3Fts5IndexQuery().
184831  */
184832  static int sqlite3Fts5IterNext(Fts5IndexIter*);
184833  static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
184834  
184835  /*
184836  ** Close an iterator opened by sqlite3Fts5IndexQuery().
184837  */
184838  static void sqlite3Fts5IterClose(Fts5IndexIter*);
184839  
184840  /*
184841  ** This interface is used by the fts5vocab module.
184842  */
184843  static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
184844  static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
184845  
184846  
184847  /*
184848  ** Insert or remove data to or from the index. Each time a document is 
184849  ** added to or removed from the index, this function is called one or more
184850  ** times.
184851  **
184852  ** For an insert, it must be called once for each token in the new document.
184853  ** If the operation is a delete, it must be called (at least) once for each
184854  ** unique token in the document with an iCol value less than zero. The iPos
184855  ** argument is ignored for a delete.
184856  */
184857  static int sqlite3Fts5IndexWrite(
184858    Fts5Index *p,                   /* Index to write to */
184859    int iCol,                       /* Column token appears in (-ve -> delete) */
184860    int iPos,                       /* Position of token within column */
184861    const char *pToken, int nToken  /* Token to add or remove to or from index */
184862  );
184863  
184864  /*
184865  ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
184866  ** document iDocid.
184867  */
184868  static int sqlite3Fts5IndexBeginWrite(
184869    Fts5Index *p,                   /* Index to write to */
184870    int bDelete,                    /* True if current operation is a delete */
184871    i64 iDocid                      /* Docid to add or remove data from */
184872  );
184873  
184874  /*
184875  ** Flush any data stored in the in-memory hash tables to the database.
184876  ** Also close any open blob handles.
184877  */
184878  static int sqlite3Fts5IndexSync(Fts5Index *p);
184879  
184880  /*
184881  ** Discard any data stored in the in-memory hash tables. Do not write it
184882  ** to the database. Additionally, assume that the contents of the %_data
184883  ** table may have changed on disk. So any in-memory caches of %_data 
184884  ** records must be invalidated.
184885  */
184886  static int sqlite3Fts5IndexRollback(Fts5Index *p);
184887  
184888  /*
184889  ** Get or set the "averages" values.
184890  */
184891  static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
184892  static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
184893  
184894  /*
184895  ** Functions called by the storage module as part of integrity-check.
184896  */
184897  static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
184898  
184899  /* 
184900  ** Called during virtual module initialization to register UDF 
184901  ** fts5_decode() with SQLite 
184902  */
184903  static int sqlite3Fts5IndexInit(sqlite3*);
184904  
184905  static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
184906  
184907  /*
184908  ** Return the total number of entries read from the %_data table by 
184909  ** this connection since it was created.
184910  */
184911  static int sqlite3Fts5IndexReads(Fts5Index *p);
184912  
184913  static int sqlite3Fts5IndexReinit(Fts5Index *p);
184914  static int sqlite3Fts5IndexOptimize(Fts5Index *p);
184915  static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
184916  static int sqlite3Fts5IndexReset(Fts5Index *p);
184917  
184918  static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
184919  
184920  /*
184921  ** End of interface to code in fts5_index.c.
184922  **************************************************************************/
184923  
184924  /**************************************************************************
184925  ** Interface to code in fts5_varint.c. 
184926  */
184927  static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
184928  static int sqlite3Fts5GetVarintLen(u32 iVal);
184929  static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
184930  static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
184931  
184932  #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
184933  #define fts5GetVarint    sqlite3Fts5GetVarint
184934  
184935  #define fts5FastGetVarint32(a, iOff, nVal) {      \
184936    nVal = (a)[iOff++];                             \
184937    if( nVal & 0x80 ){                              \
184938      iOff--;                                       \
184939      iOff += fts5GetVarint32(&(a)[iOff], nVal);    \
184940    }                                               \
184941  }
184942  
184943  
184944  /*
184945  ** End of interface to code in fts5_varint.c.
184946  **************************************************************************/
184947  
184948  
184949  /**************************************************************************
184950  ** Interface to code in fts5.c. 
184951  */
184952  
184953  static int sqlite3Fts5GetTokenizer(
184954    Fts5Global*, 
184955    const char **azArg,
184956    int nArg,
184957    Fts5Tokenizer**,
184958    fts5_tokenizer**,
184959    char **pzErr
184960  );
184961  
184962  static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **);
184963  
184964  /*
184965  ** End of interface to code in fts5.c.
184966  **************************************************************************/
184967  
184968  /**************************************************************************
184969  ** Interface to code in fts5_hash.c. 
184970  */
184971  typedef struct Fts5Hash Fts5Hash;
184972  
184973  /*
184974  ** Create a hash table, free a hash table.
184975  */
184976  static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
184977  static void sqlite3Fts5HashFree(Fts5Hash*);
184978  
184979  static int sqlite3Fts5HashWrite(
184980    Fts5Hash*,
184981    i64 iRowid,                     /* Rowid for this entry */
184982    int iCol,                       /* Column token appears in (-ve -> delete) */
184983    int iPos,                       /* Position of token within column */
184984    char bByte,
184985    const char *pToken, int nToken  /* Token to add or remove to or from index */
184986  );
184987  
184988  /*
184989  ** Empty (but do not delete) a hash table.
184990  */
184991  static void sqlite3Fts5HashClear(Fts5Hash*);
184992  
184993  static int sqlite3Fts5HashQuery(
184994    Fts5Hash*,                      /* Hash table to query */
184995    const char *pTerm, int nTerm,   /* Query term */
184996    const u8 **ppDoclist,           /* OUT: Pointer to doclist for pTerm */
184997    int *pnDoclist                  /* OUT: Size of doclist in bytes */
184998  );
184999  
185000  static int sqlite3Fts5HashScanInit(
185001    Fts5Hash*,                      /* Hash table to query */
185002    const char *pTerm, int nTerm    /* Query prefix */
185003  );
185004  static void sqlite3Fts5HashScanNext(Fts5Hash*);
185005  static int sqlite3Fts5HashScanEof(Fts5Hash*);
185006  static void sqlite3Fts5HashScanEntry(Fts5Hash *,
185007    const char **pzTerm,            /* OUT: term (nul-terminated) */
185008    const u8 **ppDoclist,           /* OUT: pointer to doclist */
185009    int *pnDoclist                  /* OUT: size of doclist in bytes */
185010  );
185011  
185012  
185013  /*
185014  ** End of interface to code in fts5_hash.c.
185015  **************************************************************************/
185016  
185017  /**************************************************************************
185018  ** Interface to code in fts5_storage.c. fts5_storage.c contains contains 
185019  ** code to access the data stored in the %_content and %_docsize tables.
185020  */
185021  
185022  #define FTS5_STMT_SCAN_ASC  0     /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
185023  #define FTS5_STMT_SCAN_DESC 1     /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
185024  #define FTS5_STMT_LOOKUP    2     /* SELECT rowid, * FROM ... WHERE rowid=? */
185025  
185026  typedef struct Fts5Storage Fts5Storage;
185027  
185028  static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
185029  static int sqlite3Fts5StorageClose(Fts5Storage *p);
185030  static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
185031  
185032  static int sqlite3Fts5DropAll(Fts5Config*);
185033  static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
185034  
185035  static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
185036  static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
185037  static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
185038  
185039  static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
185040  
185041  static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
185042  static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
185043  
185044  static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
185045  static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
185046  static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
185047  
185048  static int sqlite3Fts5StorageSync(Fts5Storage *p);
185049  static int sqlite3Fts5StorageRollback(Fts5Storage *p);
185050  
185051  static int sqlite3Fts5StorageConfigValue(
185052      Fts5Storage *p, const char*, sqlite3_value*, int
185053  );
185054  
185055  static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
185056  static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
185057  static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
185058  static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
185059  static int sqlite3Fts5StorageReset(Fts5Storage *p);
185060  
185061  /*
185062  ** End of interface to code in fts5_storage.c.
185063  **************************************************************************/
185064  
185065  
185066  /**************************************************************************
185067  ** Interface to code in fts5_expr.c. 
185068  */
185069  typedef struct Fts5Expr Fts5Expr;
185070  typedef struct Fts5ExprNode Fts5ExprNode;
185071  typedef struct Fts5Parse Fts5Parse;
185072  typedef struct Fts5Token Fts5Token;
185073  typedef struct Fts5ExprPhrase Fts5ExprPhrase;
185074  typedef struct Fts5ExprNearset Fts5ExprNearset;
185075  
185076  struct Fts5Token {
185077    const char *p;                  /* Token text (not NULL terminated) */
185078    int n;                          /* Size of buffer p in bytes */
185079  };
185080  
185081  /* Parse a MATCH expression. */
185082  static int sqlite3Fts5ExprNew(
185083    Fts5Config *pConfig, 
185084    int iCol,                       /* Column on LHS of MATCH operator */
185085    const char *zExpr,
185086    Fts5Expr **ppNew, 
185087    char **pzErr
185088  );
185089  
185090  /*
185091  ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
185092  **     rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
185093  **     rc = sqlite3Fts5ExprNext(pExpr)
185094  ** ){
185095  **   // The document with rowid iRowid matches the expression!
185096  **   i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
185097  ** }
185098  */
185099  static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
185100  static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
185101  static int sqlite3Fts5ExprEof(Fts5Expr*);
185102  static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
185103  
185104  static void sqlite3Fts5ExprFree(Fts5Expr*);
185105  
185106  /* Called during startup to register a UDF with SQLite */
185107  static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
185108  
185109  static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
185110  static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
185111  static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
185112  
185113  typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
185114  static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
185115  static int sqlite3Fts5ExprPopulatePoslists(
185116      Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
185117  );
185118  static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
185119  
185120  static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
185121  
185122  static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
185123  
185124  /*******************************************
185125  ** The fts5_expr.c API above this point is used by the other hand-written
185126  ** C code in this module. The interfaces below this point are called by
185127  ** the parser code in fts5parse.y.  */
185128  
185129  static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
185130  
185131  static Fts5ExprNode *sqlite3Fts5ParseNode(
185132    Fts5Parse *pParse,
185133    int eType,
185134    Fts5ExprNode *pLeft,
185135    Fts5ExprNode *pRight,
185136    Fts5ExprNearset *pNear
185137  );
185138  
185139  static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
185140    Fts5Parse *pParse,
185141    Fts5ExprNode *pLeft,
185142    Fts5ExprNode *pRight
185143  );
185144  
185145  static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
185146    Fts5Parse *pParse, 
185147    Fts5ExprPhrase *pPhrase, 
185148    Fts5Token *pToken,
185149    int bPrefix
185150  );
185151  
185152  static Fts5ExprNearset *sqlite3Fts5ParseNearset(
185153    Fts5Parse*, 
185154    Fts5ExprNearset*,
185155    Fts5ExprPhrase* 
185156  );
185157  
185158  static Fts5Colset *sqlite3Fts5ParseColset(
185159    Fts5Parse*, 
185160    Fts5Colset*, 
185161    Fts5Token *
185162  );
185163  
185164  static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
185165  static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
185166  static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
185167  
185168  static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
185169  static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNode*, Fts5Colset*);
185170  static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*);
185171  static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
185172  static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
185173  
185174  /*
185175  ** End of interface to code in fts5_expr.c.
185176  **************************************************************************/
185177  
185178  
185179  
185180  /**************************************************************************
185181  ** Interface to code in fts5_aux.c. 
185182  */
185183  
185184  static int sqlite3Fts5AuxInit(fts5_api*);
185185  /*
185186  ** End of interface to code in fts5_aux.c.
185187  **************************************************************************/
185188  
185189  /**************************************************************************
185190  ** Interface to code in fts5_tokenizer.c. 
185191  */
185192  
185193  static int sqlite3Fts5TokenizerInit(fts5_api*);
185194  /*
185195  ** End of interface to code in fts5_tokenizer.c.
185196  **************************************************************************/
185197  
185198  /**************************************************************************
185199  ** Interface to code in fts5_vocab.c. 
185200  */
185201  
185202  static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
185203  
185204  /*
185205  ** End of interface to code in fts5_vocab.c.
185206  **************************************************************************/
185207  
185208  
185209  /**************************************************************************
185210  ** Interface to automatically generated code in fts5_unicode2.c. 
185211  */
185212  static int sqlite3Fts5UnicodeIsalnum(int c);
185213  static int sqlite3Fts5UnicodeIsdiacritic(int c);
185214  static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
185215  /*
185216  ** End of interface to code in fts5_unicode2.c.
185217  **************************************************************************/
185218  
185219  #endif
185220  
185221  #define FTS5_OR                               1
185222  #define FTS5_AND                              2
185223  #define FTS5_NOT                              3
185224  #define FTS5_TERM                             4
185225  #define FTS5_COLON                            5
185226  #define FTS5_MINUS                            6
185227  #define FTS5_LCP                              7
185228  #define FTS5_RCP                              8
185229  #define FTS5_STRING                           9
185230  #define FTS5_LP                              10
185231  #define FTS5_RP                              11
185232  #define FTS5_COMMA                           12
185233  #define FTS5_PLUS                            13
185234  #define FTS5_STAR                            14
185235  
185236  /*
185237  ** 2000-05-29
185238  **
185239  ** The author disclaims copyright to this source code.  In place of
185240  ** a legal notice, here is a blessing:
185241  **
185242  **    May you do good and not evil.
185243  **    May you find forgiveness for yourself and forgive others.
185244  **    May you share freely, never taking more than you give.
185245  **
185246  *************************************************************************
185247  ** Driver template for the LEMON parser generator.
185248  **
185249  ** The "lemon" program processes an LALR(1) input grammar file, then uses
185250  ** this template to construct a parser.  The "lemon" program inserts text
185251  ** at each "%%" line.  Also, any "P-a-r-s-e" identifer prefix (without the
185252  ** interstitial "-" characters) contained in this template is changed into
185253  ** the value of the %name directive from the grammar.  Otherwise, the content
185254  ** of this template is copied straight through into the generate parser
185255  ** source file.
185256  **
185257  ** The following is the concatenation of all %include directives from the
185258  ** input grammar file:
185259  */
185260  /* #include <stdio.h> */
185261  /************ Begin %include sections from the grammar ************************/
185262  
185263  /* #include "fts5Int.h" */
185264  /* #include "fts5parse.h" */
185265  
185266  /*
185267  ** Disable all error recovery processing in the parser push-down
185268  ** automaton.
185269  */
185270  #define fts5YYNOERRORRECOVERY 1
185271  
185272  /*
185273  ** Make fts5yytestcase() the same as testcase()
185274  */
185275  #define fts5yytestcase(X) testcase(X)
185276  
185277  /*
185278  ** Indicate that sqlite3ParserFree() will never be called with a null
185279  ** pointer.
185280  */
185281  #define fts5YYPARSEFREENOTNULL 1
185282  
185283  /*
185284  ** Alternative datatype for the argument to the malloc() routine passed
185285  ** into sqlite3ParserAlloc().  The default is size_t.
185286  */
185287  #define fts5YYMALLOCARGTYPE  u64
185288  
185289  /**************** End of %include directives **********************************/
185290  /* These constants specify the various numeric values for terminal symbols
185291  ** in a format understandable to "makeheaders".  This section is blank unless
185292  ** "lemon" is run with the "-m" command-line option.
185293  ***************** Begin makeheaders token definitions *************************/
185294  /**************** End makeheaders token definitions ***************************/
185295  
185296  /* The next sections is a series of control #defines.
185297  ** various aspects of the generated parser.
185298  **    fts5YYCODETYPE         is the data type used to store the integer codes
185299  **                       that represent terminal and non-terminal symbols.
185300  **                       "unsigned char" is used if there are fewer than
185301  **                       256 symbols.  Larger types otherwise.
185302  **    fts5YYNOCODE           is a number of type fts5YYCODETYPE that is not used for
185303  **                       any terminal or nonterminal symbol.
185304  **    fts5YYFALLBACK         If defined, this indicates that one or more tokens
185305  **                       (also known as: "terminal symbols") have fall-back
185306  **                       values which should be used if the original symbol
185307  **                       would not parse.  This permits keywords to sometimes
185308  **                       be used as identifiers, for example.
185309  **    fts5YYACTIONTYPE       is the data type used for "action codes" - numbers
185310  **                       that indicate what to do in response to the next
185311  **                       token.
185312  **    sqlite3Fts5ParserFTS5TOKENTYPE     is the data type used for minor type for terminal
185313  **                       symbols.  Background: A "minor type" is a semantic
185314  **                       value associated with a terminal or non-terminal
185315  **                       symbols.  For example, for an "ID" terminal symbol,
185316  **                       the minor type might be the name of the identifier.
185317  **                       Each non-terminal can have a different minor type.
185318  **                       Terminal symbols all have the same minor type, though.
185319  **                       This macros defines the minor type for terminal 
185320  **                       symbols.
185321  **    fts5YYMINORTYPE        is the data type used for all minor types.
185322  **                       This is typically a union of many types, one of
185323  **                       which is sqlite3Fts5ParserFTS5TOKENTYPE.  The entry in the union
185324  **                       for terminal symbols is called "fts5yy0".
185325  **    fts5YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
185326  **                       zero the stack is dynamically sized using realloc()
185327  **    sqlite3Fts5ParserARG_SDECL     A static variable declaration for the %extra_argument
185328  **    sqlite3Fts5ParserARG_PDECL     A parameter declaration for the %extra_argument
185329  **    sqlite3Fts5ParserARG_STORE     Code to store %extra_argument into fts5yypParser
185330  **    sqlite3Fts5ParserARG_FETCH     Code to extract %extra_argument from fts5yypParser
185331  **    fts5YYERRORSYMBOL      is the code number of the error symbol.  If not
185332  **                       defined, then do no error processing.
185333  **    fts5YYNSTATE           the combined number of states.
185334  **    fts5YYNRULE            the number of rules in the grammar
185335  **    fts5YY_MAX_SHIFT       Maximum value for shift actions
185336  **    fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
185337  **    fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
185338  **    fts5YY_MIN_REDUCE      Minimum value for reduce actions
185339  **    fts5YY_MAX_REDUCE      Maximum value for reduce actions
185340  **    fts5YY_ERROR_ACTION    The fts5yy_action[] code for syntax error
185341  **    fts5YY_ACCEPT_ACTION   The fts5yy_action[] code for accept
185342  **    fts5YY_NO_ACTION       The fts5yy_action[] code for no-op
185343  */
185344  #ifndef INTERFACE
185345  # define INTERFACE 1
185346  #endif
185347  /************* Begin control #defines *****************************************/
185348  #define fts5YYCODETYPE unsigned char
185349  #define fts5YYNOCODE 28
185350  #define fts5YYACTIONTYPE unsigned char
185351  #define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
185352  typedef union {
185353    int fts5yyinit;
185354    sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
185355    int fts5yy4;
185356    Fts5Colset* fts5yy11;
185357    Fts5ExprNode* fts5yy24;
185358    Fts5ExprNearset* fts5yy46;
185359    Fts5ExprPhrase* fts5yy53;
185360  } fts5YYMINORTYPE;
185361  #ifndef fts5YYSTACKDEPTH
185362  #define fts5YYSTACKDEPTH 100
185363  #endif
185364  #define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
185365  #define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
185366  #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse
185367  #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse
185368  #define fts5YYNSTATE             33
185369  #define fts5YYNRULE              27
185370  #define fts5YY_MAX_SHIFT         32
185371  #define fts5YY_MIN_SHIFTREDUCE   50
185372  #define fts5YY_MAX_SHIFTREDUCE   76
185373  #define fts5YY_MIN_REDUCE        77
185374  #define fts5YY_MAX_REDUCE        103
185375  #define fts5YY_ERROR_ACTION      104
185376  #define fts5YY_ACCEPT_ACTION     105
185377  #define fts5YY_NO_ACTION         106
185378  /************* End control #defines *******************************************/
185379  
185380  /* Define the fts5yytestcase() macro to be a no-op if is not already defined
185381  ** otherwise.
185382  **
185383  ** Applications can choose to define fts5yytestcase() in the %include section
185384  ** to a macro that can assist in verifying code coverage.  For production
185385  ** code the fts5yytestcase() macro should be turned off.  But it is useful
185386  ** for testing.
185387  */
185388  #ifndef fts5yytestcase
185389  # define fts5yytestcase(X)
185390  #endif
185391  
185392  
185393  /* Next are the tables used to determine what action to take based on the
185394  ** current state and lookahead token.  These tables are used to implement
185395  ** functions that take a state number and lookahead value and return an
185396  ** action integer.  
185397  **
185398  ** Suppose the action integer is N.  Then the action is determined as
185399  ** follows
185400  **
185401  **   0 <= N <= fts5YY_MAX_SHIFT             Shift N.  That is, push the lookahead
185402  **                                      token onto the stack and goto state N.
185403  **
185404  **   N between fts5YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
185405  **     and fts5YY_MAX_SHIFTREDUCE           reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
185406  **
185407  **   N between fts5YY_MIN_REDUCE            Reduce by rule N-fts5YY_MIN_REDUCE
185408  **     and fts5YY_MAX_REDUCE
185409  **
185410  **   N == fts5YY_ERROR_ACTION               A syntax error has occurred.
185411  **
185412  **   N == fts5YY_ACCEPT_ACTION              The parser accepts its input.
185413  **
185414  **   N == fts5YY_NO_ACTION                  No such action.  Denotes unused
185415  **                                      slots in the fts5yy_action[] table.
185416  **
185417  ** The action table is constructed as a single large table named fts5yy_action[].
185418  ** Given state S and lookahead X, the action is computed as either:
185419  **
185420  **    (A)   N = fts5yy_action[ fts5yy_shift_ofst[S] + X ]
185421  **    (B)   N = fts5yy_default[S]
185422  **
185423  ** The (A) formula is preferred.  The B formula is used instead if:
185424  **    (1)  The fts5yy_shift_ofst[S]+X value is out of range, or
185425  **    (2)  fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X, or
185426  **    (3)  fts5yy_shift_ofst[S] equal fts5YY_SHIFT_USE_DFLT.
185427  ** (Implementation note: fts5YY_SHIFT_USE_DFLT is chosen so that
185428  ** fts5YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X.
185429  ** Hence only tests (1) and (2) need to be evaluated.)
185430  **
185431  ** The formulas above are for computing the action when the lookahead is
185432  ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
185433  ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
185434  ** the fts5yy_shift_ofst[] array and fts5YY_REDUCE_USE_DFLT is used in place of
185435  ** fts5YY_SHIFT_USE_DFLT.
185436  **
185437  ** The following are the tables generated in this section:
185438  **
185439  **  fts5yy_action[]        A single table containing all actions.
185440  **  fts5yy_lookahead[]     A table containing the lookahead for each entry in
185441  **                     fts5yy_action.  Used to detect hash collisions.
185442  **  fts5yy_shift_ofst[]    For each state, the offset into fts5yy_action for
185443  **                     shifting terminals.
185444  **  fts5yy_reduce_ofst[]   For each state, the offset into fts5yy_action for
185445  **                     shifting non-terminals after a reduce.
185446  **  fts5yy_default[]       Default action for each state.
185447  **
185448  *********** Begin parsing tables **********************************************/
185449  #define fts5YY_ACTTAB_COUNT (98)
185450  static const fts5YYACTIONTYPE fts5yy_action[] = {
185451   /*     0 */   105,   19,   90,    6,   26,   93,   92,   24,   24,   17,
185452   /*    10 */    90,    6,   26,   16,   92,   54,   24,   18,   90,    6,
185453   /*    20 */    26,   10,   92,   12,   24,   75,   86,   90,    6,   26,
185454   /*    30 */    13,   92,   75,   24,   20,   90,    6,   26,  101,   92,
185455   /*    40 */    56,   24,   27,   90,    6,   26,  100,   92,   21,   24,
185456   /*    50 */    23,   15,   30,   11,    1,   91,   22,   25,    9,   92,
185457   /*    60 */     7,   24,    3,    4,    5,    3,    4,    5,    3,   77,
185458   /*    70 */     4,    5,    3,   61,   23,   15,   60,   11,   80,   12,
185459   /*    80 */     2,   13,   68,   10,   29,   52,   55,   75,   31,   32,
185460   /*    90 */     8,   28,    5,    3,   51,   55,   72,   14,
185461  };
185462  static const fts5YYCODETYPE fts5yy_lookahead[] = {
185463   /*     0 */    16,   17,   18,   19,   20,   22,   22,   24,   24,   17,
185464   /*    10 */    18,   19,   20,    7,   22,    9,   24,   17,   18,   19,
185465   /*    20 */    20,   10,   22,    9,   24,   14,   17,   18,   19,   20,
185466   /*    30 */     9,   22,   14,   24,   17,   18,   19,   20,   26,   22,
185467   /*    40 */     9,   24,   17,   18,   19,   20,   26,   22,   21,   24,
185468   /*    50 */     6,    7,   13,    9,   10,   18,   21,   20,    5,   22,
185469   /*    60 */     5,   24,    3,    1,    2,    3,    1,    2,    3,    0,
185470   /*    70 */     1,    2,    3,   11,    6,    7,   11,    9,    5,    9,
185471   /*    80 */    10,    9,   11,   10,   12,    8,    9,   14,   24,   25,
185472   /*    90 */    23,   24,    2,    3,    8,    9,    9,    9,
185473  };
185474  #define fts5YY_SHIFT_USE_DFLT (98)
185475  #define fts5YY_SHIFT_COUNT    (32)
185476  #define fts5YY_SHIFT_MIN      (0)
185477  #define fts5YY_SHIFT_MAX      (90)
185478  static const unsigned char fts5yy_shift_ofst[] = {
185479   /*     0 */    44,   44,   44,   44,   44,   44,   68,   70,   72,   14,
185480   /*    10 */    21,   73,   11,   18,   18,   31,   31,   62,   65,   69,
185481   /*    20 */    90,   77,   86,    6,   39,   53,   55,   59,   39,   87,
185482   /*    30 */    88,   39,   71,
185483  };
185484  #define fts5YY_REDUCE_USE_DFLT (-18)
185485  #define fts5YY_REDUCE_COUNT (16)
185486  #define fts5YY_REDUCE_MIN   (-17)
185487  #define fts5YY_REDUCE_MAX   (67)
185488  static const signed char fts5yy_reduce_ofst[] = {
185489   /*     0 */   -16,   -8,    0,    9,   17,   25,   37,  -17,   64,  -17,
185490   /*    10 */    67,   12,   12,   12,   20,   27,   35,
185491  };
185492  static const fts5YYACTIONTYPE fts5yy_default[] = {
185493   /*     0 */   104,  104,  104,  104,  104,  104,   89,  104,   98,  104,
185494   /*    10 */   104,  103,  103,  103,  103,  104,  104,  104,  104,  104,
185495   /*    20 */    85,  104,  104,  104,   94,  104,  104,   84,   96,  104,
185496   /*    30 */   104,   97,  104,
185497  };
185498  /********** End of lemon-generated parsing tables *****************************/
185499  
185500  /* The next table maps tokens (terminal symbols) into fallback tokens.  
185501  ** If a construct like the following:
185502  ** 
185503  **      %fallback ID X Y Z.
185504  **
185505  ** appears in the grammar, then ID becomes a fallback token for X, Y,
185506  ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
185507  ** but it does not parse, the type of the token is changed to ID and
185508  ** the parse is retried before an error is thrown.
185509  **
185510  ** This feature can be used, for example, to cause some keywords in a language
185511  ** to revert to identifiers if they keyword does not apply in the context where
185512  ** it appears.
185513  */
185514  #ifdef fts5YYFALLBACK
185515  static const fts5YYCODETYPE fts5yyFallback[] = {
185516  };
185517  #endif /* fts5YYFALLBACK */
185518  
185519  /* The following structure represents a single element of the
185520  ** parser's stack.  Information stored includes:
185521  **
185522  **   +  The state number for the parser at this level of the stack.
185523  **
185524  **   +  The value of the token stored at this level of the stack.
185525  **      (In other words, the "major" token.)
185526  **
185527  **   +  The semantic value stored at this level of the stack.  This is
185528  **      the information used by the action routines in the grammar.
185529  **      It is sometimes called the "minor" token.
185530  **
185531  ** After the "shift" half of a SHIFTREDUCE action, the stateno field
185532  ** actually contains the reduce action for the second half of the
185533  ** SHIFTREDUCE.
185534  */
185535  struct fts5yyStackEntry {
185536    fts5YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
185537    fts5YYCODETYPE major;      /* The major token value.  This is the code
185538                           ** number for the token at this stack level */
185539    fts5YYMINORTYPE minor;     /* The user-supplied minor token value.  This
185540                           ** is the value of the token  */
185541  };
185542  typedef struct fts5yyStackEntry fts5yyStackEntry;
185543  
185544  /* The state of the parser is completely contained in an instance of
185545  ** the following structure */
185546  struct fts5yyParser {
185547    fts5yyStackEntry *fts5yytos;          /* Pointer to top element of the stack */
185548  #ifdef fts5YYTRACKMAXSTACKDEPTH
185549    int fts5yyhwm;                    /* High-water mark of the stack */
185550  #endif
185551  #ifndef fts5YYNOERRORRECOVERY
185552    int fts5yyerrcnt;                 /* Shifts left before out of the error */
185553  #endif
185554    sqlite3Fts5ParserARG_SDECL                /* A place to hold %extra_argument */
185555  #if fts5YYSTACKDEPTH<=0
185556    int fts5yystksz;                  /* Current side of the stack */
185557    fts5yyStackEntry *fts5yystack;        /* The parser's stack */
185558    fts5yyStackEntry fts5yystk0;          /* First stack entry */
185559  #else
185560    fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH];  /* The parser's stack */
185561    fts5yyStackEntry *fts5yystackEnd;            /* Last entry in the stack */
185562  #endif
185563  };
185564  typedef struct fts5yyParser fts5yyParser;
185565  
185566  #ifndef NDEBUG
185567  /* #include <stdio.h> */
185568  static FILE *fts5yyTraceFILE = 0;
185569  static char *fts5yyTracePrompt = 0;
185570  #endif /* NDEBUG */
185571  
185572  #ifndef NDEBUG
185573  /* 
185574  ** Turn parser tracing on by giving a stream to which to write the trace
185575  ** and a prompt to preface each trace message.  Tracing is turned off
185576  ** by making either argument NULL 
185577  **
185578  ** Inputs:
185579  ** <ul>
185580  ** <li> A FILE* to which trace output should be written.
185581  **      If NULL, then tracing is turned off.
185582  ** <li> A prefix string written at the beginning of every
185583  **      line of trace output.  If NULL, then tracing is
185584  **      turned off.
185585  ** </ul>
185586  **
185587  ** Outputs:
185588  ** None.
185589  */
185590  static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
185591    fts5yyTraceFILE = TraceFILE;
185592    fts5yyTracePrompt = zTracePrompt;
185593    if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
185594    else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
185595  }
185596  #endif /* NDEBUG */
185597  
185598  #ifndef NDEBUG
185599  /* For tracing shifts, the names of all terminals and nonterminals
185600  ** are required.  The following table supplies these names */
185601  static const char *const fts5yyTokenName[] = { 
185602    "$",             "OR",            "AND",           "NOT",         
185603    "TERM",          "COLON",         "MINUS",         "LCP",         
185604    "RCP",           "STRING",        "LP",            "RP",          
185605    "COMMA",         "PLUS",          "STAR",          "error",       
185606    "input",         "expr",          "cnearset",      "exprlist",    
185607    "colset",        "colsetlist",    "nearset",       "nearphrases", 
185608    "phrase",        "neardist_opt",  "star_opt",    
185609  };
185610  #endif /* NDEBUG */
185611  
185612  #ifndef NDEBUG
185613  /* For tracing reduce actions, the names of all rules are required.
185614  */
185615  static const char *const fts5yyRuleName[] = {
185616   /*   0 */ "input ::= expr",
185617   /*   1 */ "colset ::= MINUS LCP colsetlist RCP",
185618   /*   2 */ "colset ::= LCP colsetlist RCP",
185619   /*   3 */ "colset ::= STRING",
185620   /*   4 */ "colset ::= MINUS STRING",
185621   /*   5 */ "colsetlist ::= colsetlist STRING",
185622   /*   6 */ "colsetlist ::= STRING",
185623   /*   7 */ "expr ::= expr AND expr",
185624   /*   8 */ "expr ::= expr OR expr",
185625   /*   9 */ "expr ::= expr NOT expr",
185626   /*  10 */ "expr ::= colset COLON LP expr RP",
185627   /*  11 */ "expr ::= LP expr RP",
185628   /*  12 */ "expr ::= exprlist",
185629   /*  13 */ "exprlist ::= cnearset",
185630   /*  14 */ "exprlist ::= exprlist cnearset",
185631   /*  15 */ "cnearset ::= nearset",
185632   /*  16 */ "cnearset ::= colset COLON nearset",
185633   /*  17 */ "nearset ::= phrase",
185634   /*  18 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
185635   /*  19 */ "nearphrases ::= phrase",
185636   /*  20 */ "nearphrases ::= nearphrases phrase",
185637   /*  21 */ "neardist_opt ::=",
185638   /*  22 */ "neardist_opt ::= COMMA STRING",
185639   /*  23 */ "phrase ::= phrase PLUS STRING star_opt",
185640   /*  24 */ "phrase ::= STRING star_opt",
185641   /*  25 */ "star_opt ::= STAR",
185642   /*  26 */ "star_opt ::=",
185643  };
185644  #endif /* NDEBUG */
185645  
185646  
185647  #if fts5YYSTACKDEPTH<=0
185648  /*
185649  ** Try to increase the size of the parser stack.  Return the number
185650  ** of errors.  Return 0 on success.
185651  */
185652  static int fts5yyGrowStack(fts5yyParser *p){
185653    int newSize;
185654    int idx;
185655    fts5yyStackEntry *pNew;
185656  
185657    newSize = p->fts5yystksz*2 + 100;
185658    idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;
185659    if( p->fts5yystack==&p->fts5yystk0 ){
185660      pNew = malloc(newSize*sizeof(pNew[0]));
185661      if( pNew ) pNew[0] = p->fts5yystk0;
185662    }else{
185663      pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
185664    }
185665    if( pNew ){
185666      p->fts5yystack = pNew;
185667      p->fts5yytos = &p->fts5yystack[idx];
185668  #ifndef NDEBUG
185669      if( fts5yyTraceFILE ){
185670        fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
185671                fts5yyTracePrompt, p->fts5yystksz, newSize);
185672      }
185673  #endif
185674      p->fts5yystksz = newSize;
185675    }
185676    return pNew==0; 
185677  }
185678  #endif
185679  
185680  /* Datatype of the argument to the memory allocated passed as the
185681  ** second argument to sqlite3Fts5ParserAlloc() below.  This can be changed by
185682  ** putting an appropriate #define in the %include section of the input
185683  ** grammar.
185684  */
185685  #ifndef fts5YYMALLOCARGTYPE
185686  # define fts5YYMALLOCARGTYPE size_t
185687  #endif
185688  
185689  /* Initialize a new parser that has already been allocated.
185690  */
185691  static void sqlite3Fts5ParserInit(void *fts5yypParser){
185692    fts5yyParser *pParser = (fts5yyParser*)fts5yypParser;
185693  #ifdef fts5YYTRACKMAXSTACKDEPTH
185694    pParser->fts5yyhwm = 0;
185695  #endif
185696  #if fts5YYSTACKDEPTH<=0
185697    pParser->fts5yytos = NULL;
185698    pParser->fts5yystack = NULL;
185699    pParser->fts5yystksz = 0;
185700    if( fts5yyGrowStack(pParser) ){
185701      pParser->fts5yystack = &pParser->fts5yystk0;
185702      pParser->fts5yystksz = 1;
185703    }
185704  #endif
185705  #ifndef fts5YYNOERRORRECOVERY
185706    pParser->fts5yyerrcnt = -1;
185707  #endif
185708    pParser->fts5yytos = pParser->fts5yystack;
185709    pParser->fts5yystack[0].stateno = 0;
185710    pParser->fts5yystack[0].major = 0;
185711  #if fts5YYSTACKDEPTH>0
185712    pParser->fts5yystackEnd = &pParser->fts5yystack[fts5YYSTACKDEPTH-1];
185713  #endif
185714  }
185715  
185716  #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
185717  /* 
185718  ** This function allocates a new parser.
185719  ** The only argument is a pointer to a function which works like
185720  ** malloc.
185721  **
185722  ** Inputs:
185723  ** A pointer to the function used to allocate memory.
185724  **
185725  ** Outputs:
185726  ** A pointer to a parser.  This pointer is used in subsequent calls
185727  ** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
185728  */
185729  static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE)){
185730    fts5yyParser *pParser;
185731    pParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
185732    if( pParser ) sqlite3Fts5ParserInit(pParser);
185733    return pParser;
185734  }
185735  #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
185736  
185737  
185738  /* The following function deletes the "minor type" or semantic value
185739  ** associated with a symbol.  The symbol can be either a terminal
185740  ** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
185741  ** a pointer to the value to be deleted.  The code used to do the 
185742  ** deletions is derived from the %destructor and/or %token_destructor
185743  ** directives of the input grammar.
185744  */
185745  static void fts5yy_destructor(
185746    fts5yyParser *fts5yypParser,    /* The parser */
185747    fts5YYCODETYPE fts5yymajor,     /* Type code for object to destroy */
185748    fts5YYMINORTYPE *fts5yypminor   /* The object to be destroyed */
185749  ){
185750    sqlite3Fts5ParserARG_FETCH;
185751    switch( fts5yymajor ){
185752      /* Here is inserted the actions which take place when a
185753      ** terminal or non-terminal is destroyed.  This can happen
185754      ** when the symbol is popped from the stack during a
185755      ** reduce or during error processing or when a parser is 
185756      ** being destroyed before it is finished parsing.
185757      **
185758      ** Note: during a reduce, the only symbols destroyed are those
185759      ** which appear on the RHS of the rule, but which are *not* used
185760      ** inside the C code.
185761      */
185762  /********* Begin destructor definitions ***************************************/
185763      case 16: /* input */
185764  {
185765   (void)pParse; 
185766  }
185767        break;
185768      case 17: /* expr */
185769      case 18: /* cnearset */
185770      case 19: /* exprlist */
185771  {
185772   sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24)); 
185773  }
185774        break;
185775      case 20: /* colset */
185776      case 21: /* colsetlist */
185777  {
185778   sqlite3_free((fts5yypminor->fts5yy11)); 
185779  }
185780        break;
185781      case 22: /* nearset */
185782      case 23: /* nearphrases */
185783  {
185784   sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46)); 
185785  }
185786        break;
185787      case 24: /* phrase */
185788  {
185789   sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53)); 
185790  }
185791        break;
185792  /********* End destructor definitions *****************************************/
185793      default:  break;   /* If no destructor action specified: do nothing */
185794    }
185795  }
185796  
185797  /*
185798  ** Pop the parser's stack once.
185799  **
185800  ** If there is a destructor routine associated with the token which
185801  ** is popped from the stack, then call it.
185802  */
185803  static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
185804    fts5yyStackEntry *fts5yytos;
185805    assert( pParser->fts5yytos!=0 );
185806    assert( pParser->fts5yytos > pParser->fts5yystack );
185807    fts5yytos = pParser->fts5yytos--;
185808  #ifndef NDEBUG
185809    if( fts5yyTraceFILE ){
185810      fprintf(fts5yyTraceFILE,"%sPopping %s\n",
185811        fts5yyTracePrompt,
185812        fts5yyTokenName[fts5yytos->major]);
185813    }
185814  #endif
185815    fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
185816  }
185817  
185818  /*
185819  ** Clear all secondary memory allocations from the parser
185820  */
185821  static void sqlite3Fts5ParserFinalize(void *p){
185822    fts5yyParser *pParser = (fts5yyParser*)p;
185823    while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);
185824  #if fts5YYSTACKDEPTH<=0
185825    if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);
185826  #endif
185827  }
185828  
185829  #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
185830  /* 
185831  ** Deallocate and destroy a parser.  Destructors are called for
185832  ** all stack elements before shutting the parser down.
185833  **
185834  ** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
185835  ** is defined in a %include section of the input grammar) then it is
185836  ** assumed that the input pointer is never NULL.
185837  */
185838  static void sqlite3Fts5ParserFree(
185839    void *p,                    /* The parser to be deleted */
185840    void (*freeProc)(void*)     /* Function used to reclaim memory */
185841  ){
185842  #ifndef fts5YYPARSEFREENEVERNULL
185843    if( p==0 ) return;
185844  #endif
185845    sqlite3Fts5ParserFinalize(p);
185846    (*freeProc)(p);
185847  }
185848  #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
185849  
185850  /*
185851  ** Return the peak depth of the stack for a parser.
185852  */
185853  #ifdef fts5YYTRACKMAXSTACKDEPTH
185854  static int sqlite3Fts5ParserStackPeak(void *p){
185855    fts5yyParser *pParser = (fts5yyParser*)p;
185856    return pParser->fts5yyhwm;
185857  }
185858  #endif
185859  
185860  /*
185861  ** Find the appropriate action for a parser given the terminal
185862  ** look-ahead token iLookAhead.
185863  */
185864  static unsigned int fts5yy_find_shift_action(
185865    fts5yyParser *pParser,        /* The parser */
185866    fts5YYCODETYPE iLookAhead     /* The look-ahead token */
185867  ){
185868    int i;
185869    int stateno = pParser->fts5yytos->stateno;
185870   
185871    if( stateno>=fts5YY_MIN_REDUCE ) return stateno;
185872    assert( stateno <= fts5YY_SHIFT_COUNT );
185873    do{
185874      i = fts5yy_shift_ofst[stateno];
185875      assert( iLookAhead!=fts5YYNOCODE );
185876      i += iLookAhead;
185877      if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
185878  #ifdef fts5YYFALLBACK
185879        fts5YYCODETYPE iFallback;            /* Fallback token */
185880        if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
185881               && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
185882  #ifndef NDEBUG
185883          if( fts5yyTraceFILE ){
185884            fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
185885               fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
185886          }
185887  #endif
185888          assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
185889          iLookAhead = iFallback;
185890          continue;
185891        }
185892  #endif
185893  #ifdef fts5YYWILDCARD
185894        {
185895          int j = i - iLookAhead + fts5YYWILDCARD;
185896          if( 
185897  #if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
185898            j>=0 &&
185899  #endif
185900  #if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
185901            j<fts5YY_ACTTAB_COUNT &&
185902  #endif
185903            fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0
185904          ){
185905  #ifndef NDEBUG
185906            if( fts5yyTraceFILE ){
185907              fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
185908                 fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
185909                 fts5yyTokenName[fts5YYWILDCARD]);
185910            }
185911  #endif /* NDEBUG */
185912            return fts5yy_action[j];
185913          }
185914        }
185915  #endif /* fts5YYWILDCARD */
185916        return fts5yy_default[stateno];
185917      }else{
185918        return fts5yy_action[i];
185919      }
185920    }while(1);
185921  }
185922  
185923  /*
185924  ** Find the appropriate action for a parser given the non-terminal
185925  ** look-ahead token iLookAhead.
185926  */
185927  static int fts5yy_find_reduce_action(
185928    int stateno,              /* Current state number */
185929    fts5YYCODETYPE iLookAhead     /* The look-ahead token */
185930  ){
185931    int i;
185932  #ifdef fts5YYERRORSYMBOL
185933    if( stateno>fts5YY_REDUCE_COUNT ){
185934      return fts5yy_default[stateno];
185935    }
185936  #else
185937    assert( stateno<=fts5YY_REDUCE_COUNT );
185938  #endif
185939    i = fts5yy_reduce_ofst[stateno];
185940    assert( i!=fts5YY_REDUCE_USE_DFLT );
185941    assert( iLookAhead!=fts5YYNOCODE );
185942    i += iLookAhead;
185943  #ifdef fts5YYERRORSYMBOL
185944    if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
185945      return fts5yy_default[stateno];
185946    }
185947  #else
185948    assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
185949    assert( fts5yy_lookahead[i]==iLookAhead );
185950  #endif
185951    return fts5yy_action[i];
185952  }
185953  
185954  /*
185955  ** The following routine is called if the stack overflows.
185956  */
185957  static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
185958     sqlite3Fts5ParserARG_FETCH;
185959  #ifndef NDEBUG
185960     if( fts5yyTraceFILE ){
185961       fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
185962     }
185963  #endif
185964     while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
185965     /* Here code is inserted which will execute if the parser
185966     ** stack every overflows */
185967  /******** Begin %stack_overflow code ******************************************/
185968  
185969    sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
185970  /******** End %stack_overflow code ********************************************/
185971     sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
185972  }
185973  
185974  /*
185975  ** Print tracing information for a SHIFT action
185976  */
185977  #ifndef NDEBUG
185978  static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState){
185979    if( fts5yyTraceFILE ){
185980      if( fts5yyNewState<fts5YYNSTATE ){
185981        fprintf(fts5yyTraceFILE,"%sShift '%s', go to state %d\n",
185982           fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major],
185983           fts5yyNewState);
185984      }else{
185985        fprintf(fts5yyTraceFILE,"%sShift '%s'\n",
185986           fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major]);
185987      }
185988    }
185989  }
185990  #else
185991  # define fts5yyTraceShift(X,Y)
185992  #endif
185993  
185994  /*
185995  ** Perform a shift action.
185996  */
185997  static void fts5yy_shift(
185998    fts5yyParser *fts5yypParser,          /* The parser to be shifted */
185999    int fts5yyNewState,               /* The new state to shift in */
186000    int fts5yyMajor,                  /* The major token to shift in */
186001    sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor        /* The minor token to shift in */
186002  ){
186003    fts5yyStackEntry *fts5yytos;
186004    fts5yypParser->fts5yytos++;
186005  #ifdef fts5YYTRACKMAXSTACKDEPTH
186006    if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
186007      fts5yypParser->fts5yyhwm++;
186008      assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
186009    }
186010  #endif
186011  #if fts5YYSTACKDEPTH>0 
186012    if( fts5yypParser->fts5yytos>fts5yypParser->fts5yystackEnd ){
186013      fts5yypParser->fts5yytos--;
186014      fts5yyStackOverflow(fts5yypParser);
186015      return;
186016    }
186017  #else
186018    if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){
186019      if( fts5yyGrowStack(fts5yypParser) ){
186020        fts5yypParser->fts5yytos--;
186021        fts5yyStackOverflow(fts5yypParser);
186022        return;
186023      }
186024    }
186025  #endif
186026    if( fts5yyNewState > fts5YY_MAX_SHIFT ){
186027      fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
186028    }
186029    fts5yytos = fts5yypParser->fts5yytos;
186030    fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState;
186031    fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor;
186032    fts5yytos->minor.fts5yy0 = fts5yyMinor;
186033    fts5yyTraceShift(fts5yypParser, fts5yyNewState);
186034  }
186035  
186036  /* The following table contains information about every rule that
186037  ** is used during the reduce.
186038  */
186039  static const struct {
186040    fts5YYCODETYPE lhs;       /* Symbol on the left-hand side of the rule */
186041    signed char nrhs;     /* Negative of the number of RHS symbols in the rule */
186042  } fts5yyRuleInfo[] = {
186043    { 16, -1 },
186044    { 20, -4 },
186045    { 20, -3 },
186046    { 20, -1 },
186047    { 20, -2 },
186048    { 21, -2 },
186049    { 21, -1 },
186050    { 17, -3 },
186051    { 17, -3 },
186052    { 17, -3 },
186053    { 17, -5 },
186054    { 17, -3 },
186055    { 17, -1 },
186056    { 19, -1 },
186057    { 19, -2 },
186058    { 18, -1 },
186059    { 18, -3 },
186060    { 22, -1 },
186061    { 22, -5 },
186062    { 23, -1 },
186063    { 23, -2 },
186064    { 25, 0 },
186065    { 25, -2 },
186066    { 24, -4 },
186067    { 24, -2 },
186068    { 26, -1 },
186069    { 26, 0 },
186070  };
186071  
186072  static void fts5yy_accept(fts5yyParser*);  /* Forward Declaration */
186073  
186074  /*
186075  ** Perform a reduce action and the shift that must immediately
186076  ** follow the reduce.
186077  */
186078  static void fts5yy_reduce(
186079    fts5yyParser *fts5yypParser,         /* The parser */
186080    unsigned int fts5yyruleno        /* Number of the rule by which to reduce */
186081  ){
186082    int fts5yygoto;                     /* The next state */
186083    int fts5yyact;                      /* The next action */
186084    fts5yyStackEntry *fts5yymsp;            /* The top of the parser's stack */
186085    int fts5yysize;                     /* Amount to pop the stack */
186086    sqlite3Fts5ParserARG_FETCH;
186087    fts5yymsp = fts5yypParser->fts5yytos;
186088  #ifndef NDEBUG
186089    if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
186090      fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
186091      fprintf(fts5yyTraceFILE, "%sReduce [%s], go to state %d.\n", fts5yyTracePrompt,
186092        fts5yyRuleName[fts5yyruleno], fts5yymsp[fts5yysize].stateno);
186093    }
186094  #endif /* NDEBUG */
186095  
186096    /* Check that the stack is large enough to grow by a single entry
186097    ** if the RHS of the rule is empty.  This ensures that there is room
186098    ** enough on the stack to push the LHS value */
186099    if( fts5yyRuleInfo[fts5yyruleno].nrhs==0 ){
186100  #ifdef fts5YYTRACKMAXSTACKDEPTH
186101      if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
186102        fts5yypParser->fts5yyhwm++;
186103        assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
186104      }
186105  #endif
186106  #if fts5YYSTACKDEPTH>0 
186107      if( fts5yypParser->fts5yytos>=fts5yypParser->fts5yystackEnd ){
186108        fts5yyStackOverflow(fts5yypParser);
186109        return;
186110      }
186111  #else
186112      if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){
186113        if( fts5yyGrowStack(fts5yypParser) ){
186114          fts5yyStackOverflow(fts5yypParser);
186115          return;
186116        }
186117        fts5yymsp = fts5yypParser->fts5yytos;
186118      }
186119  #endif
186120    }
186121  
186122    switch( fts5yyruleno ){
186123    /* Beginning here are the reduction cases.  A typical example
186124    ** follows:
186125    **   case 0:
186126    **  #line <lineno> <grammarfile>
186127    **     { ... }           // User supplied code
186128    **  #line <lineno> <thisfile>
186129    **     break;
186130    */
186131  /********** Begin reduce actions **********************************************/
186132          fts5YYMINORTYPE fts5yylhsminor;
186133        case 0: /* input ::= expr */
186134  { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); }
186135          break;
186136        case 1: /* colset ::= MINUS LCP colsetlist RCP */
186137  { 
186138      fts5yymsp[-3].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
186139  }
186140          break;
186141        case 2: /* colset ::= LCP colsetlist RCP */
186142  { fts5yymsp[-2].minor.fts5yy11 = fts5yymsp[-1].minor.fts5yy11; }
186143          break;
186144        case 3: /* colset ::= STRING */
186145  {
186146    fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
186147  }
186148    fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
186149          break;
186150        case 4: /* colset ::= MINUS STRING */
186151  {
186152    fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
186153    fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
186154  }
186155          break;
186156        case 5: /* colsetlist ::= colsetlist STRING */
186157  { 
186158    fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); }
186159    fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
186160          break;
186161        case 6: /* colsetlist ::= STRING */
186162  { 
186163    fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0); 
186164  }
186165    fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
186166          break;
186167        case 7: /* expr ::= expr AND expr */
186168  {
186169    fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
186170  }
186171    fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
186172          break;
186173        case 8: /* expr ::= expr OR expr */
186174  {
186175    fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
186176  }
186177    fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
186178          break;
186179        case 9: /* expr ::= expr NOT expr */
186180  {
186181    fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
186182  }
186183    fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
186184          break;
186185        case 10: /* expr ::= colset COLON LP expr RP */
186186  {
186187    sqlite3Fts5ParseSetColset(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[-4].minor.fts5yy11);
186188    fts5yylhsminor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;
186189  }
186190    fts5yymsp[-4].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
186191          break;
186192        case 11: /* expr ::= LP expr RP */
186193  {fts5yymsp[-2].minor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;}
186194          break;
186195        case 12: /* expr ::= exprlist */
186196        case 13: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==13);
186197  {fts5yylhsminor.fts5yy24 = fts5yymsp[0].minor.fts5yy24;}
186198    fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
186199          break;
186200        case 14: /* exprlist ::= exprlist cnearset */
186201  {
186202    fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24);
186203  }
186204    fts5yymsp[-1].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
186205          break;
186206        case 15: /* cnearset ::= nearset */
186207  { 
186208    fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46); 
186209  }
186210    fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
186211          break;
186212        case 16: /* cnearset ::= colset COLON nearset */
186213  { 
186214    fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46); 
186215    sqlite3Fts5ParseSetColset(pParse, fts5yylhsminor.fts5yy24, fts5yymsp[-2].minor.fts5yy11);
186216  }
186217    fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
186218          break;
186219        case 17: /* nearset ::= phrase */
186220  { fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); }
186221    fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
186222          break;
186223        case 18: /* nearset ::= STRING LP nearphrases neardist_opt RP */
186224  {
186225    sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
186226    sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy46, &fts5yymsp[-1].minor.fts5yy0);
186227    fts5yylhsminor.fts5yy46 = fts5yymsp[-2].minor.fts5yy46;
186228  }
186229    fts5yymsp[-4].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
186230          break;
186231        case 19: /* nearphrases ::= phrase */
186232  { 
186233    fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); 
186234  }
186235    fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
186236          break;
186237        case 20: /* nearphrases ::= nearphrases phrase */
186238  {
186239    fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy46, fts5yymsp[0].minor.fts5yy53);
186240  }
186241    fts5yymsp[-1].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
186242          break;
186243        case 21: /* neardist_opt ::= */
186244  { fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
186245          break;
186246        case 22: /* neardist_opt ::= COMMA STRING */
186247  { fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
186248          break;
186249        case 23: /* phrase ::= phrase PLUS STRING star_opt */
186250  { 
186251    fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
186252  }
186253    fts5yymsp[-3].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
186254          break;
186255        case 24: /* phrase ::= STRING star_opt */
186256  { 
186257    fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
186258  }
186259    fts5yymsp[-1].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
186260          break;
186261        case 25: /* star_opt ::= STAR */
186262  { fts5yymsp[0].minor.fts5yy4 = 1; }
186263          break;
186264        case 26: /* star_opt ::= */
186265  { fts5yymsp[1].minor.fts5yy4 = 0; }
186266          break;
186267        default:
186268          break;
186269  /********** End reduce actions ************************************************/
186270    };
186271    assert( fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
186272    fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
186273    fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
186274    fts5yyact = fts5yy_find_reduce_action(fts5yymsp[fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
186275  
186276    /* There are no SHIFTREDUCE actions on nonterminals because the table
186277    ** generator has simplified them to pure REDUCE actions. */
186278    assert( !(fts5yyact>fts5YY_MAX_SHIFT && fts5yyact<=fts5YY_MAX_SHIFTREDUCE) );
186279  
186280    /* It is not possible for a REDUCE to be followed by an error */
186281    assert( fts5yyact!=fts5YY_ERROR_ACTION );
186282  
186283    if( fts5yyact==fts5YY_ACCEPT_ACTION ){
186284      fts5yypParser->fts5yytos += fts5yysize;
186285      fts5yy_accept(fts5yypParser);
186286    }else{
186287      fts5yymsp += fts5yysize+1;
186288      fts5yypParser->fts5yytos = fts5yymsp;
186289      fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
186290      fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
186291      fts5yyTraceShift(fts5yypParser, fts5yyact);
186292    }
186293  }
186294  
186295  /*
186296  ** The following code executes when the parse fails
186297  */
186298  #ifndef fts5YYNOERRORRECOVERY
186299  static void fts5yy_parse_failed(
186300    fts5yyParser *fts5yypParser           /* The parser */
186301  ){
186302    sqlite3Fts5ParserARG_FETCH;
186303  #ifndef NDEBUG
186304    if( fts5yyTraceFILE ){
186305      fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
186306    }
186307  #endif
186308    while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
186309    /* Here code is inserted which will be executed whenever the
186310    ** parser fails */
186311  /************ Begin %parse_failure code ***************************************/
186312  /************ End %parse_failure code *****************************************/
186313    sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
186314  }
186315  #endif /* fts5YYNOERRORRECOVERY */
186316  
186317  /*
186318  ** The following code executes when a syntax error first occurs.
186319  */
186320  static void fts5yy_syntax_error(
186321    fts5yyParser *fts5yypParser,           /* The parser */
186322    int fts5yymajor,                   /* The major type of the error token */
186323    sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor         /* The minor type of the error token */
186324  ){
186325    sqlite3Fts5ParserARG_FETCH;
186326  #define FTS5TOKEN fts5yyminor
186327  /************ Begin %syntax_error code ****************************************/
186328  
186329    UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
186330    sqlite3Fts5ParseError(
186331      pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
186332    );
186333  /************ End %syntax_error code ******************************************/
186334    sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
186335  }
186336  
186337  /*
186338  ** The following is executed when the parser accepts
186339  */
186340  static void fts5yy_accept(
186341    fts5yyParser *fts5yypParser           /* The parser */
186342  ){
186343    sqlite3Fts5ParserARG_FETCH;
186344  #ifndef NDEBUG
186345    if( fts5yyTraceFILE ){
186346      fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
186347    }
186348  #endif
186349  #ifndef fts5YYNOERRORRECOVERY
186350    fts5yypParser->fts5yyerrcnt = -1;
186351  #endif
186352    assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
186353    /* Here code is inserted which will be executed whenever the
186354    ** parser accepts */
186355  /*********** Begin %parse_accept code *****************************************/
186356  /*********** End %parse_accept code *******************************************/
186357    sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
186358  }
186359  
186360  /* The main parser program.
186361  ** The first argument is a pointer to a structure obtained from
186362  ** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
186363  ** The second argument is the major token number.  The third is
186364  ** the minor token.  The fourth optional argument is whatever the
186365  ** user wants (and specified in the grammar) and is available for
186366  ** use by the action routines.
186367  **
186368  ** Inputs:
186369  ** <ul>
186370  ** <li> A pointer to the parser (an opaque structure.)
186371  ** <li> The major token number.
186372  ** <li> The minor token number.
186373  ** <li> An option argument of a grammar-specified type.
186374  ** </ul>
186375  **
186376  ** Outputs:
186377  ** None.
186378  */
186379  static void sqlite3Fts5Parser(
186380    void *fts5yyp,                   /* The parser */
186381    int fts5yymajor,                 /* The major token code number */
186382    sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor       /* The value for the token */
186383    sqlite3Fts5ParserARG_PDECL               /* Optional %extra_argument parameter */
186384  ){
186385    fts5YYMINORTYPE fts5yyminorunion;
186386    unsigned int fts5yyact;   /* The parser action. */
186387  #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
186388    int fts5yyendofinput;     /* True if we are at the end of input */
186389  #endif
186390  #ifdef fts5YYERRORSYMBOL
186391    int fts5yyerrorhit = 0;   /* True if fts5yymajor has invoked an error */
186392  #endif
186393    fts5yyParser *fts5yypParser;  /* The parser */
186394  
186395    fts5yypParser = (fts5yyParser*)fts5yyp;
186396    assert( fts5yypParser->fts5yytos!=0 );
186397  #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
186398    fts5yyendofinput = (fts5yymajor==0);
186399  #endif
186400    sqlite3Fts5ParserARG_STORE;
186401  
186402  #ifndef NDEBUG
186403    if( fts5yyTraceFILE ){
186404      fprintf(fts5yyTraceFILE,"%sInput '%s'\n",fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
186405    }
186406  #endif
186407  
186408    do{
186409      fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor);
186410      if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
186411        fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,fts5yyminor);
186412  #ifndef fts5YYNOERRORRECOVERY
186413        fts5yypParser->fts5yyerrcnt--;
186414  #endif
186415        fts5yymajor = fts5YYNOCODE;
186416      }else if( fts5yyact <= fts5YY_MAX_REDUCE ){
186417        fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE);
186418      }else{
186419        assert( fts5yyact == fts5YY_ERROR_ACTION );
186420        fts5yyminorunion.fts5yy0 = fts5yyminor;
186421  #ifdef fts5YYERRORSYMBOL
186422        int fts5yymx;
186423  #endif
186424  #ifndef NDEBUG
186425        if( fts5yyTraceFILE ){
186426          fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
186427        }
186428  #endif
186429  #ifdef fts5YYERRORSYMBOL
186430        /* A syntax error has occurred.
186431        ** The response to an error depends upon whether or not the
186432        ** grammar defines an error token "ERROR".  
186433        **
186434        ** This is what we do if the grammar does define ERROR:
186435        **
186436        **  * Call the %syntax_error function.
186437        **
186438        **  * Begin popping the stack until we enter a state where
186439        **    it is legal to shift the error symbol, then shift
186440        **    the error symbol.
186441        **
186442        **  * Set the error count to three.
186443        **
186444        **  * Begin accepting and shifting new tokens.  No new error
186445        **    processing will occur until three tokens have been
186446        **    shifted successfully.
186447        **
186448        */
186449        if( fts5yypParser->fts5yyerrcnt<0 ){
186450          fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
186451        }
186452        fts5yymx = fts5yypParser->fts5yytos->major;
186453        if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
186454  #ifndef NDEBUG
186455          if( fts5yyTraceFILE ){
186456            fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
186457               fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
186458          }
186459  #endif
186460          fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
186461          fts5yymajor = fts5YYNOCODE;
186462        }else{
186463          while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack
186464              && fts5yymx != fts5YYERRORSYMBOL
186465              && (fts5yyact = fts5yy_find_reduce_action(
186466                          fts5yypParser->fts5yytos->stateno,
186467                          fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE
186468          ){
186469            fts5yy_pop_parser_stack(fts5yypParser);
186470          }
186471          if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
186472            fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
186473            fts5yy_parse_failed(fts5yypParser);
186474  #ifndef fts5YYNOERRORRECOVERY
186475            fts5yypParser->fts5yyerrcnt = -1;
186476  #endif
186477            fts5yymajor = fts5YYNOCODE;
186478          }else if( fts5yymx!=fts5YYERRORSYMBOL ){
186479            fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
186480          }
186481        }
186482        fts5yypParser->fts5yyerrcnt = 3;
186483        fts5yyerrorhit = 1;
186484  #elif defined(fts5YYNOERRORRECOVERY)
186485        /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
186486        ** do any kind of error recovery.  Instead, simply invoke the syntax
186487        ** error routine and continue going as if nothing had happened.
186488        **
186489        ** Applications can set this macro (for example inside %include) if
186490        ** they intend to abandon the parse upon the first syntax error seen.
186491        */
186492        fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
186493        fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
186494        fts5yymajor = fts5YYNOCODE;
186495        
186496  #else  /* fts5YYERRORSYMBOL is not defined */
186497        /* This is what we do if the grammar does not define ERROR:
186498        **
186499        **  * Report an error message, and throw away the input token.
186500        **
186501        **  * If the input token is $, then fail the parse.
186502        **
186503        ** As before, subsequent error messages are suppressed until
186504        ** three input tokens have been successfully shifted.
186505        */
186506        if( fts5yypParser->fts5yyerrcnt<=0 ){
186507          fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
186508        }
186509        fts5yypParser->fts5yyerrcnt = 3;
186510        fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
186511        if( fts5yyendofinput ){
186512          fts5yy_parse_failed(fts5yypParser);
186513  #ifndef fts5YYNOERRORRECOVERY
186514          fts5yypParser->fts5yyerrcnt = -1;
186515  #endif
186516        }
186517        fts5yymajor = fts5YYNOCODE;
186518  #endif
186519      }
186520    }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );
186521  #ifndef NDEBUG
186522    if( fts5yyTraceFILE ){
186523      fts5yyStackEntry *i;
186524      char cDiv = '[';
186525      fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
186526      for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
186527        fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
186528        cDiv = ' ';
186529      }
186530      fprintf(fts5yyTraceFILE,"]\n");
186531    }
186532  #endif
186533    return;
186534  }
186535  
186536  /*
186537  ** 2014 May 31
186538  **
186539  ** The author disclaims copyright to this source code.  In place of
186540  ** a legal notice, here is a blessing:
186541  **
186542  **    May you do good and not evil.
186543  **    May you find forgiveness for yourself and forgive others.
186544  **    May you share freely, never taking more than you give.
186545  **
186546  ******************************************************************************
186547  */
186548  
186549  
186550  /* #include "fts5Int.h" */
186551  #include <math.h>                 /* amalgamator: keep */
186552  
186553  /*
186554  ** Object used to iterate through all "coalesced phrase instances" in 
186555  ** a single column of the current row. If the phrase instances in the
186556  ** column being considered do not overlap, this object simply iterates
186557  ** through them. Or, if they do overlap (share one or more tokens in
186558  ** common), each set of overlapping instances is treated as a single
186559  ** match. See documentation for the highlight() auxiliary function for
186560  ** details.
186561  **
186562  ** Usage is:
186563  **
186564  **   for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
186565  **      (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
186566  **      rc = fts5CInstIterNext(&iter)
186567  **   ){
186568  **     printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
186569  **   }
186570  **
186571  */
186572  typedef struct CInstIter CInstIter;
186573  struct CInstIter {
186574    const Fts5ExtensionApi *pApi;   /* API offered by current FTS version */
186575    Fts5Context *pFts;              /* First arg to pass to pApi functions */
186576    int iCol;                       /* Column to search */
186577    int iInst;                      /* Next phrase instance index */
186578    int nInst;                      /* Total number of phrase instances */
186579  
186580    /* Output variables */
186581    int iStart;                     /* First token in coalesced phrase instance */
186582    int iEnd;                       /* Last token in coalesced phrase instance */
186583  };
186584  
186585  /*
186586  ** Advance the iterator to the next coalesced phrase instance. Return
186587  ** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
186588  */
186589  static int fts5CInstIterNext(CInstIter *pIter){
186590    int rc = SQLITE_OK;
186591    pIter->iStart = -1;
186592    pIter->iEnd = -1;
186593  
186594    while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
186595      int ip; int ic; int io;
186596      rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
186597      if( rc==SQLITE_OK ){
186598        if( ic==pIter->iCol ){
186599          int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
186600          if( pIter->iStart<0 ){
186601            pIter->iStart = io;
186602            pIter->iEnd = iEnd;
186603          }else if( io<=pIter->iEnd ){
186604            if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
186605          }else{
186606            break;
186607          }
186608        }
186609        pIter->iInst++;
186610      }
186611    }
186612  
186613    return rc;
186614  }
186615  
186616  /*
186617  ** Initialize the iterator object indicated by the final parameter to 
186618  ** iterate through coalesced phrase instances in column iCol.
186619  */
186620  static int fts5CInstIterInit(
186621    const Fts5ExtensionApi *pApi,
186622    Fts5Context *pFts,
186623    int iCol,
186624    CInstIter *pIter
186625  ){
186626    int rc;
186627  
186628    memset(pIter, 0, sizeof(CInstIter));
186629    pIter->pApi = pApi;
186630    pIter->pFts = pFts;
186631    pIter->iCol = iCol;
186632    rc = pApi->xInstCount(pFts, &pIter->nInst);
186633  
186634    if( rc==SQLITE_OK ){
186635      rc = fts5CInstIterNext(pIter);
186636    }
186637  
186638    return rc;
186639  }
186640  
186641  
186642  
186643  /*************************************************************************
186644  ** Start of highlight() implementation.
186645  */
186646  typedef struct HighlightContext HighlightContext;
186647  struct HighlightContext {
186648    CInstIter iter;                 /* Coalesced Instance Iterator */
186649    int iPos;                       /* Current token offset in zIn[] */
186650    int iRangeStart;                /* First token to include */
186651    int iRangeEnd;                  /* If non-zero, last token to include */
186652    const char *zOpen;              /* Opening highlight */
186653    const char *zClose;             /* Closing highlight */
186654    const char *zIn;                /* Input text */
186655    int nIn;                        /* Size of input text in bytes */
186656    int iOff;                       /* Current offset within zIn[] */
186657    char *zOut;                     /* Output value */
186658  };
186659  
186660  /*
186661  ** Append text to the HighlightContext output string - p->zOut. Argument
186662  ** z points to a buffer containing n bytes of text to append. If n is 
186663  ** negative, everything up until the first '\0' is appended to the output.
186664  **
186665  ** If *pRc is set to any value other than SQLITE_OK when this function is 
186666  ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered, 
186667  ** *pRc is set to an error code before returning. 
186668  */
186669  static void fts5HighlightAppend(
186670    int *pRc, 
186671    HighlightContext *p, 
186672    const char *z, int n
186673  ){
186674    if( *pRc==SQLITE_OK ){
186675      if( n<0 ) n = (int)strlen(z);
186676      p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
186677      if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
186678    }
186679  }
186680  
186681  /*
186682  ** Tokenizer callback used by implementation of highlight() function.
186683  */
186684  static int fts5HighlightCb(
186685    void *pContext,                 /* Pointer to HighlightContext object */
186686    int tflags,                     /* Mask of FTS5_TOKEN_* flags */
186687    const char *pToken,             /* Buffer containing token */
186688    int nToken,                     /* Size of token in bytes */
186689    int iStartOff,                  /* Start offset of token */
186690    int iEndOff                     /* End offset of token */
186691  ){
186692    HighlightContext *p = (HighlightContext*)pContext;
186693    int rc = SQLITE_OK;
186694    int iPos;
186695  
186696    UNUSED_PARAM2(pToken, nToken);
186697  
186698    if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
186699    iPos = p->iPos++;
186700  
186701    if( p->iRangeEnd>0 ){
186702      if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
186703      if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
186704    }
186705  
186706    if( iPos==p->iter.iStart ){
186707      fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
186708      fts5HighlightAppend(&rc, p, p->zOpen, -1);
186709      p->iOff = iStartOff;
186710    }
186711  
186712    if( iPos==p->iter.iEnd ){
186713      if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
186714        fts5HighlightAppend(&rc, p, p->zOpen, -1);
186715      }
186716      fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
186717      fts5HighlightAppend(&rc, p, p->zClose, -1);
186718      p->iOff = iEndOff;
186719      if( rc==SQLITE_OK ){
186720        rc = fts5CInstIterNext(&p->iter);
186721      }
186722    }
186723  
186724    if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
186725      fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
186726      p->iOff = iEndOff;
186727      if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
186728        fts5HighlightAppend(&rc, p, p->zClose, -1);
186729      }
186730    }
186731  
186732    return rc;
186733  }
186734  
186735  /*
186736  ** Implementation of highlight() function.
186737  */
186738  static void fts5HighlightFunction(
186739    const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
186740    Fts5Context *pFts,              /* First arg to pass to pApi functions */
186741    sqlite3_context *pCtx,          /* Context for returning result/error */
186742    int nVal,                       /* Number of values in apVal[] array */
186743    sqlite3_value **apVal           /* Array of trailing arguments */
186744  ){
186745    HighlightContext ctx;
186746    int rc;
186747    int iCol;
186748  
186749    if( nVal!=3 ){
186750      const char *zErr = "wrong number of arguments to function highlight()";
186751      sqlite3_result_error(pCtx, zErr, -1);
186752      return;
186753    }
186754  
186755    iCol = sqlite3_value_int(apVal[0]);
186756    memset(&ctx, 0, sizeof(HighlightContext));
186757    ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
186758    ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
186759    rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
186760  
186761    if( ctx.zIn ){
186762      if( rc==SQLITE_OK ){
186763        rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
186764      }
186765  
186766      if( rc==SQLITE_OK ){
186767        rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
186768      }
186769      fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
186770  
186771      if( rc==SQLITE_OK ){
186772        sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
186773      }
186774      sqlite3_free(ctx.zOut);
186775    }
186776    if( rc!=SQLITE_OK ){
186777      sqlite3_result_error_code(pCtx, rc);
186778    }
186779  }
186780  /*
186781  ** End of highlight() implementation.
186782  **************************************************************************/
186783  
186784  /*
186785  ** Context object passed to the fts5SentenceFinderCb() function.
186786  */
186787  typedef struct Fts5SFinder Fts5SFinder;
186788  struct Fts5SFinder {
186789    int iPos;                       /* Current token position */
186790    int nFirstAlloc;                /* Allocated size of aFirst[] */
186791    int nFirst;                     /* Number of entries in aFirst[] */
186792    int *aFirst;                    /* Array of first token in each sentence */
186793    const char *zDoc;               /* Document being tokenized */
186794  };
186795  
186796  /*
186797  ** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if
186798  ** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an
186799  ** error occurs.
186800  */
186801  static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){
186802    if( p->nFirstAlloc==p->nFirst ){
186803      int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64;
186804      int *aNew;
186805  
186806      aNew = (int*)sqlite3_realloc(p->aFirst, nNew*sizeof(int));
186807      if( aNew==0 ) return SQLITE_NOMEM;
186808      p->aFirst = aNew;
186809      p->nFirstAlloc = nNew;
186810    }
186811    p->aFirst[p->nFirst++] = iAdd;
186812    return SQLITE_OK;
186813  }
186814  
186815  /*
186816  ** This function is an xTokenize() callback used by the auxiliary snippet()
186817  ** function. Its job is to identify tokens that are the first in a sentence.
186818  ** For each such token, an entry is added to the SFinder.aFirst[] array.
186819  */
186820  static int fts5SentenceFinderCb(
186821    void *pContext,                 /* Pointer to HighlightContext object */
186822    int tflags,                     /* Mask of FTS5_TOKEN_* flags */
186823    const char *pToken,             /* Buffer containing token */
186824    int nToken,                     /* Size of token in bytes */
186825    int iStartOff,                  /* Start offset of token */
186826    int iEndOff                     /* End offset of token */
186827  ){
186828    int rc = SQLITE_OK;
186829  
186830    UNUSED_PARAM2(pToken, nToken);
186831    UNUSED_PARAM(iEndOff);
186832  
186833    if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
186834      Fts5SFinder *p = (Fts5SFinder*)pContext;
186835      if( p->iPos>0 ){
186836        int i;
186837        char c = 0;
186838        for(i=iStartOff-1; i>=0; i--){
186839          c = p->zDoc[i];
186840          if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break;
186841        }
186842        if( i!=iStartOff-1 && (c=='.' || c==':') ){
186843          rc = fts5SentenceFinderAdd(p, p->iPos);
186844        }
186845      }else{
186846        rc = fts5SentenceFinderAdd(p, 0);
186847      }
186848      p->iPos++;
186849    }
186850    return rc;
186851  }
186852  
186853  static int fts5SnippetScore(
186854    const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
186855    Fts5Context *pFts,              /* First arg to pass to pApi functions */
186856    int nDocsize,                   /* Size of column in tokens */
186857    unsigned char *aSeen,           /* Array with one element per query phrase */
186858    int iCol,                       /* Column to score */
186859    int iPos,                       /* Starting offset to score */
186860    int nToken,                     /* Max tokens per snippet */
186861    int *pnScore,                   /* OUT: Score */
186862    int *piPos                      /* OUT: Adjusted offset */
186863  ){
186864    int rc;
186865    int i;
186866    int ip = 0;
186867    int ic = 0;
186868    int iOff = 0;
186869    int iFirst = -1;
186870    int nInst;
186871    int nScore = 0;
186872    int iLast = 0;
186873  
186874    rc = pApi->xInstCount(pFts, &nInst);
186875    for(i=0; i<nInst && rc==SQLITE_OK; i++){
186876      rc = pApi->xInst(pFts, i, &ip, &ic, &iOff);
186877      if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<(iPos+nToken) ){
186878        nScore += (aSeen[ip] ? 1 : 1000);
186879        aSeen[ip] = 1;
186880        if( iFirst<0 ) iFirst = iOff;
186881        iLast = iOff + pApi->xPhraseSize(pFts, ip);
186882      }
186883    }
186884  
186885    *pnScore = nScore;
186886    if( piPos ){
186887      int iAdj = iFirst - (nToken - (iLast-iFirst)) / 2;
186888      if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken;
186889      if( iAdj<0 ) iAdj = 0;
186890      *piPos = iAdj;
186891    }
186892  
186893    return rc;
186894  }
186895  
186896  /*
186897  ** Implementation of snippet() function.
186898  */
186899  static void fts5SnippetFunction(
186900    const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
186901    Fts5Context *pFts,              /* First arg to pass to pApi functions */
186902    sqlite3_context *pCtx,          /* Context for returning result/error */
186903    int nVal,                       /* Number of values in apVal[] array */
186904    sqlite3_value **apVal           /* Array of trailing arguments */
186905  ){
186906    HighlightContext ctx;
186907    int rc = SQLITE_OK;             /* Return code */
186908    int iCol;                       /* 1st argument to snippet() */
186909    const char *zEllips;            /* 4th argument to snippet() */
186910    int nToken;                     /* 5th argument to snippet() */
186911    int nInst = 0;                  /* Number of instance matches this row */
186912    int i;                          /* Used to iterate through instances */
186913    int nPhrase;                    /* Number of phrases in query */
186914    unsigned char *aSeen;           /* Array of "seen instance" flags */
186915    int iBestCol;                   /* Column containing best snippet */
186916    int iBestStart = 0;             /* First token of best snippet */
186917    int nBestScore = 0;             /* Score of best snippet */
186918    int nColSize = 0;               /* Total size of iBestCol in tokens */
186919    Fts5SFinder sFinder;            /* Used to find the beginnings of sentences */
186920    int nCol;
186921  
186922    if( nVal!=5 ){
186923      const char *zErr = "wrong number of arguments to function snippet()";
186924      sqlite3_result_error(pCtx, zErr, -1);
186925      return;
186926    }
186927  
186928    nCol = pApi->xColumnCount(pFts);
186929    memset(&ctx, 0, sizeof(HighlightContext));
186930    iCol = sqlite3_value_int(apVal[0]);
186931    ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
186932    ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
186933    zEllips = (const char*)sqlite3_value_text(apVal[3]);
186934    nToken = sqlite3_value_int(apVal[4]);
186935  
186936    iBestCol = (iCol>=0 ? iCol : 0);
186937    nPhrase = pApi->xPhraseCount(pFts);
186938    aSeen = sqlite3_malloc(nPhrase);
186939    if( aSeen==0 ){
186940      rc = SQLITE_NOMEM;
186941    }
186942    if( rc==SQLITE_OK ){
186943      rc = pApi->xInstCount(pFts, &nInst);
186944    }
186945  
186946    memset(&sFinder, 0, sizeof(Fts5SFinder));
186947    for(i=0; i<nCol; i++){
186948      if( iCol<0 || iCol==i ){
186949        int nDoc;
186950        int nDocsize;
186951        int ii;
186952        sFinder.iPos = 0;
186953        sFinder.nFirst = 0;
186954        rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);
186955        if( rc!=SQLITE_OK ) break;
186956        rc = pApi->xTokenize(pFts, 
186957            sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb
186958        );
186959        if( rc!=SQLITE_OK ) break;
186960        rc = pApi->xColumnSize(pFts, i, &nDocsize);
186961        if( rc!=SQLITE_OK ) break;
186962  
186963        for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){
186964          int ip, ic, io;
186965          int iAdj;
186966          int nScore;
186967          int jj;
186968  
186969          rc = pApi->xInst(pFts, ii, &ip, &ic, &io);
186970          if( ic!=i || rc!=SQLITE_OK ) continue;
186971          memset(aSeen, 0, nPhrase);
186972          rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
186973              io, nToken, &nScore, &iAdj
186974          );
186975          if( rc==SQLITE_OK && nScore>nBestScore ){
186976            nBestScore = nScore;
186977            iBestCol = i;
186978            iBestStart = iAdj;
186979            nColSize = nDocsize;
186980          }
186981  
186982          if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){
186983            for(jj=0; jj<(sFinder.nFirst-1); jj++){
186984              if( sFinder.aFirst[jj+1]>io ) break;
186985            }
186986  
186987            if( sFinder.aFirst[jj]<io ){
186988              memset(aSeen, 0, nPhrase);
186989              rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i, 
186990                sFinder.aFirst[jj], nToken, &nScore, 0
186991              );
186992  
186993              nScore += (sFinder.aFirst[jj]==0 ? 120 : 100);
186994              if( rc==SQLITE_OK && nScore>nBestScore ){
186995                nBestScore = nScore;
186996                iBestCol = i;
186997                iBestStart = sFinder.aFirst[jj];
186998                nColSize = nDocsize;
186999              }
187000            }
187001          }
187002        }
187003      }
187004    }
187005  
187006    if( rc==SQLITE_OK ){
187007      rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
187008    }
187009    if( rc==SQLITE_OK && nColSize==0 ){
187010      rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
187011    }
187012    if( ctx.zIn ){
187013      if( rc==SQLITE_OK ){
187014        rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
187015      }
187016  
187017      ctx.iRangeStart = iBestStart;
187018      ctx.iRangeEnd = iBestStart + nToken - 1;
187019  
187020      if( iBestStart>0 ){
187021        fts5HighlightAppend(&rc, &ctx, zEllips, -1);
187022      }
187023  
187024      /* Advance iterator ctx.iter so that it points to the first coalesced
187025      ** phrase instance at or following position iBestStart. */
187026      while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){
187027        rc = fts5CInstIterNext(&ctx.iter);
187028      }
187029  
187030      if( rc==SQLITE_OK ){
187031        rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
187032      }
187033      if( ctx.iRangeEnd>=(nColSize-1) ){
187034        fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
187035      }else{
187036        fts5HighlightAppend(&rc, &ctx, zEllips, -1);
187037      }
187038    }
187039    if( rc==SQLITE_OK ){
187040      sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
187041    }else{
187042      sqlite3_result_error_code(pCtx, rc);
187043    }
187044    sqlite3_free(ctx.zOut);
187045    sqlite3_free(aSeen);
187046    sqlite3_free(sFinder.aFirst);
187047  }
187048  
187049  /************************************************************************/
187050  
187051  /*
187052  ** The first time the bm25() function is called for a query, an instance
187053  ** of the following structure is allocated and populated.
187054  */
187055  typedef struct Fts5Bm25Data Fts5Bm25Data;
187056  struct Fts5Bm25Data {
187057    int nPhrase;                    /* Number of phrases in query */
187058    double avgdl;                   /* Average number of tokens in each row */
187059    double *aIDF;                   /* IDF for each phrase */
187060    double *aFreq;                  /* Array used to calculate phrase freq. */
187061  };
187062  
187063  /*
187064  ** Callback used by fts5Bm25GetData() to count the number of rows in the
187065  ** table matched by each individual phrase within the query.
187066  */
187067  static int fts5CountCb(
187068    const Fts5ExtensionApi *pApi, 
187069    Fts5Context *pFts,
187070    void *pUserData                 /* Pointer to sqlite3_int64 variable */
187071  ){
187072    sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
187073    UNUSED_PARAM2(pApi, pFts);
187074    (*pn)++;
187075    return SQLITE_OK;
187076  }
187077  
187078  /*
187079  ** Set *ppData to point to the Fts5Bm25Data object for the current query. 
187080  ** If the object has not already been allocated, allocate and populate it
187081  ** now.
187082  */
187083  static int fts5Bm25GetData(
187084    const Fts5ExtensionApi *pApi, 
187085    Fts5Context *pFts,
187086    Fts5Bm25Data **ppData           /* OUT: bm25-data object for this query */
187087  ){
187088    int rc = SQLITE_OK;             /* Return code */
187089    Fts5Bm25Data *p;                /* Object to return */
187090  
187091    p = pApi->xGetAuxdata(pFts, 0);
187092    if( p==0 ){
187093      int nPhrase;                  /* Number of phrases in query */
187094      sqlite3_int64 nRow = 0;       /* Number of rows in table */
187095      sqlite3_int64 nToken = 0;     /* Number of tokens in table */
187096      int nByte;                    /* Bytes of space to allocate */
187097      int i;
187098  
187099      /* Allocate the Fts5Bm25Data object */
187100      nPhrase = pApi->xPhraseCount(pFts);
187101      nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
187102      p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
187103      if( p==0 ){
187104        rc = SQLITE_NOMEM;
187105      }else{
187106        memset(p, 0, nByte);
187107        p->nPhrase = nPhrase;
187108        p->aIDF = (double*)&p[1];
187109        p->aFreq = &p->aIDF[nPhrase];
187110      }
187111  
187112      /* Calculate the average document length for this FTS5 table */
187113      if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
187114      if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
187115      if( rc==SQLITE_OK ) p->avgdl = (double)nToken  / (double)nRow;
187116  
187117      /* Calculate an IDF for each phrase in the query */
187118      for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
187119        sqlite3_int64 nHit = 0;
187120        rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
187121        if( rc==SQLITE_OK ){
187122          /* Calculate the IDF (Inverse Document Frequency) for phrase i.
187123          ** This is done using the standard BM25 formula as found on wikipedia:
187124          **
187125          **   IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
187126          **
187127          ** where "N" is the total number of documents in the set and nHit
187128          ** is the number that contain at least one instance of the phrase
187129          ** under consideration.
187130          **
187131          ** The problem with this is that if (N < 2*nHit), the IDF is 
187132          ** negative. Which is undesirable. So the mimimum allowable IDF is
187133          ** (1e-6) - roughly the same as a term that appears in just over
187134          ** half of set of 5,000,000 documents.  */
187135          double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
187136          if( idf<=0.0 ) idf = 1e-6;
187137          p->aIDF[i] = idf;
187138        }
187139      }
187140  
187141      if( rc!=SQLITE_OK ){
187142        sqlite3_free(p);
187143      }else{
187144        rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
187145      }
187146      if( rc!=SQLITE_OK ) p = 0;
187147    }
187148    *ppData = p;
187149    return rc;
187150  }
187151  
187152  /*
187153  ** Implementation of bm25() function.
187154  */
187155  static void fts5Bm25Function(
187156    const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
187157    Fts5Context *pFts,              /* First arg to pass to pApi functions */
187158    sqlite3_context *pCtx,          /* Context for returning result/error */
187159    int nVal,                       /* Number of values in apVal[] array */
187160    sqlite3_value **apVal           /* Array of trailing arguments */
187161  ){
187162    const double k1 = 1.2;          /* Constant "k1" from BM25 formula */
187163    const double b = 0.75;          /* Constant "b" from BM25 formula */
187164    int rc = SQLITE_OK;             /* Error code */
187165    double score = 0.0;             /* SQL function return value */
187166    Fts5Bm25Data *pData;            /* Values allocated/calculated once only */
187167    int i;                          /* Iterator variable */
187168    int nInst = 0;                  /* Value returned by xInstCount() */
187169    double D = 0.0;                 /* Total number of tokens in row */
187170    double *aFreq = 0;              /* Array of phrase freq. for current row */
187171  
187172    /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
187173    ** for each phrase in the query for the current row. */
187174    rc = fts5Bm25GetData(pApi, pFts, &pData);
187175    if( rc==SQLITE_OK ){
187176      aFreq = pData->aFreq;
187177      memset(aFreq, 0, sizeof(double) * pData->nPhrase);
187178      rc = pApi->xInstCount(pFts, &nInst);
187179    }
187180    for(i=0; rc==SQLITE_OK && i<nInst; i++){
187181      int ip; int ic; int io;
187182      rc = pApi->xInst(pFts, i, &ip, &ic, &io);
187183      if( rc==SQLITE_OK ){
187184        double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
187185        aFreq[ip] += w;
187186      }
187187    }
187188  
187189    /* Figure out the total size of the current row in tokens. */
187190    if( rc==SQLITE_OK ){
187191      int nTok;
187192      rc = pApi->xColumnSize(pFts, -1, &nTok);
187193      D = (double)nTok;
187194    }
187195  
187196    /* Determine the BM25 score for the current row. */
187197    for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
187198      score += pData->aIDF[i] * (
187199        ( aFreq[i] * (k1 + 1.0) ) / 
187200        ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
187201      );
187202    }
187203    
187204    /* If no error has occurred, return the calculated score. Otherwise,
187205    ** throw an SQL exception.  */
187206    if( rc==SQLITE_OK ){
187207      sqlite3_result_double(pCtx, -1.0 * score);
187208    }else{
187209      sqlite3_result_error_code(pCtx, rc);
187210    }
187211  }
187212  
187213  static int sqlite3Fts5AuxInit(fts5_api *pApi){
187214    struct Builtin {
187215      const char *zFunc;            /* Function name (nul-terminated) */
187216      void *pUserData;              /* User-data pointer */
187217      fts5_extension_function xFunc;/* Callback function */
187218      void (*xDestroy)(void*);      /* Destructor function */
187219    } aBuiltin [] = {
187220      { "snippet",   0, fts5SnippetFunction, 0 },
187221      { "highlight", 0, fts5HighlightFunction, 0 },
187222      { "bm25",      0, fts5Bm25Function,    0 },
187223    };
187224    int rc = SQLITE_OK;             /* Return code */
187225    int i;                          /* To iterate through builtin functions */
187226  
187227    for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
187228      rc = pApi->xCreateFunction(pApi,
187229          aBuiltin[i].zFunc,
187230          aBuiltin[i].pUserData,
187231          aBuiltin[i].xFunc,
187232          aBuiltin[i].xDestroy
187233      );
187234    }
187235  
187236    return rc;
187237  }
187238  
187239  
187240  
187241  /*
187242  ** 2014 May 31
187243  **
187244  ** The author disclaims copyright to this source code.  In place of
187245  ** a legal notice, here is a blessing:
187246  **
187247  **    May you do good and not evil.
187248  **    May you find forgiveness for yourself and forgive others.
187249  **    May you share freely, never taking more than you give.
187250  **
187251  ******************************************************************************
187252  */
187253  
187254  
187255  
187256  /* #include "fts5Int.h" */
187257  
187258  static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
187259    if( (u32)pBuf->nSpace<nByte ){
187260      u32 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
187261      u8 *pNew;
187262      while( nNew<nByte ){
187263        nNew = nNew * 2;
187264      }
187265      pNew = sqlite3_realloc(pBuf->p, nNew);
187266      if( pNew==0 ){
187267        *pRc = SQLITE_NOMEM;
187268        return 1;
187269      }else{
187270        pBuf->nSpace = nNew;
187271        pBuf->p = pNew;
187272      }
187273    }
187274    return 0;
187275  }
187276  
187277  
187278  /*
187279  ** Encode value iVal as an SQLite varint and append it to the buffer object
187280  ** pBuf. If an OOM error occurs, set the error code in p.
187281  */
187282  static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
187283    if( fts5BufferGrow(pRc, pBuf, 9) ) return;
187284    pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
187285  }
187286  
187287  static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
187288    aBuf[0] = (iVal>>24) & 0x00FF;
187289    aBuf[1] = (iVal>>16) & 0x00FF;
187290    aBuf[2] = (iVal>> 8) & 0x00FF;
187291    aBuf[3] = (iVal>> 0) & 0x00FF;
187292  }
187293  
187294  static int sqlite3Fts5Get32(const u8 *aBuf){
187295    return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
187296  }
187297  
187298  /*
187299  ** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set 
187300  ** the error code in p. If an error has already occurred when this function
187301  ** is called, it is a no-op.
187302  */
187303  static void sqlite3Fts5BufferAppendBlob(
187304    int *pRc,
187305    Fts5Buffer *pBuf, 
187306    u32 nData, 
187307    const u8 *pData
187308  ){
187309    assert_nc( *pRc || nData>=0 );
187310    if( nData ){
187311      if( fts5BufferGrow(pRc, pBuf, nData) ) return;
187312      memcpy(&pBuf->p[pBuf->n], pData, nData);
187313      pBuf->n += nData;
187314    }
187315  }
187316  
187317  /*
187318  ** Append the nul-terminated string zStr to the buffer pBuf. This function
187319  ** ensures that the byte following the buffer data is set to 0x00, even 
187320  ** though this byte is not included in the pBuf->n count.
187321  */
187322  static void sqlite3Fts5BufferAppendString(
187323    int *pRc,
187324    Fts5Buffer *pBuf, 
187325    const char *zStr
187326  ){
187327    int nStr = (int)strlen(zStr);
187328    sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
187329    pBuf->n--;
187330  }
187331  
187332  /*
187333  ** Argument zFmt is a printf() style format string. This function performs
187334  ** the printf() style processing, then appends the results to buffer pBuf.
187335  **
187336  ** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte 
187337  ** following the buffer data is set to 0x00, even though this byte is not
187338  ** included in the pBuf->n count.
187339  */ 
187340  static void sqlite3Fts5BufferAppendPrintf(
187341    int *pRc,
187342    Fts5Buffer *pBuf, 
187343    char *zFmt, ...
187344  ){
187345    if( *pRc==SQLITE_OK ){
187346      char *zTmp;
187347      va_list ap;
187348      va_start(ap, zFmt);
187349      zTmp = sqlite3_vmprintf(zFmt, ap);
187350      va_end(ap);
187351  
187352      if( zTmp==0 ){
187353        *pRc = SQLITE_NOMEM;
187354      }else{
187355        sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
187356        sqlite3_free(zTmp);
187357      }
187358    }
187359  }
187360  
187361  static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
187362    char *zRet = 0;
187363    if( *pRc==SQLITE_OK ){
187364      va_list ap;
187365      va_start(ap, zFmt);
187366      zRet = sqlite3_vmprintf(zFmt, ap);
187367      va_end(ap);
187368      if( zRet==0 ){
187369        *pRc = SQLITE_NOMEM; 
187370      }
187371    }
187372    return zRet;
187373  }
187374   
187375  
187376  /*
187377  ** Free any buffer allocated by pBuf. Zero the structure before returning.
187378  */
187379  static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
187380    sqlite3_free(pBuf->p);
187381    memset(pBuf, 0, sizeof(Fts5Buffer));
187382  }
187383  
187384  /*
187385  ** Zero the contents of the buffer object. But do not free the associated 
187386  ** memory allocation.
187387  */
187388  static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
187389    pBuf->n = 0;
187390  }
187391  
187392  /*
187393  ** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
187394  ** the error code in p. If an error has already occurred when this function
187395  ** is called, it is a no-op.
187396  */
187397  static void sqlite3Fts5BufferSet(
187398    int *pRc,
187399    Fts5Buffer *pBuf, 
187400    int nData, 
187401    const u8 *pData
187402  ){
187403    pBuf->n = 0;
187404    sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
187405  }
187406  
187407  static int sqlite3Fts5PoslistNext64(
187408    const u8 *a, int n,             /* Buffer containing poslist */
187409    int *pi,                        /* IN/OUT: Offset within a[] */
187410    i64 *piOff                      /* IN/OUT: Current offset */
187411  ){
187412    int i = *pi;
187413    if( i>=n ){
187414      /* EOF */
187415      *piOff = -1;
187416      return 1;  
187417    }else{
187418      i64 iOff = *piOff;
187419      int iVal;
187420      fts5FastGetVarint32(a, i, iVal);
187421      if( iVal==1 ){
187422        fts5FastGetVarint32(a, i, iVal);
187423        iOff = ((i64)iVal) << 32;
187424        fts5FastGetVarint32(a, i, iVal);
187425      }
187426      *piOff = iOff + (iVal-2);
187427      *pi = i;
187428      return 0;
187429    }
187430  }
187431  
187432  
187433  /*
187434  ** Advance the iterator object passed as the only argument. Return true
187435  ** if the iterator reaches EOF, or false otherwise.
187436  */
187437  static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
187438    if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
187439      pIter->bEof = 1;
187440    }
187441    return pIter->bEof;
187442  }
187443  
187444  static int sqlite3Fts5PoslistReaderInit(
187445    const u8 *a, int n,             /* Poslist buffer to iterate through */
187446    Fts5PoslistReader *pIter        /* Iterator object to initialize */
187447  ){
187448    memset(pIter, 0, sizeof(*pIter));
187449    pIter->a = a;
187450    pIter->n = n;
187451    sqlite3Fts5PoslistReaderNext(pIter);
187452    return pIter->bEof;
187453  }
187454  
187455  /*
187456  ** Append position iPos to the position list being accumulated in buffer
187457  ** pBuf, which must be already be large enough to hold the new data.
187458  ** The previous position written to this list is *piPrev. *piPrev is set
187459  ** to iPos before returning.
187460  */
187461  static void sqlite3Fts5PoslistSafeAppend(
187462    Fts5Buffer *pBuf, 
187463    i64 *piPrev, 
187464    i64 iPos
187465  ){
187466    static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
187467    if( (iPos & colmask) != (*piPrev & colmask) ){
187468      pBuf->p[pBuf->n++] = 1;
187469      pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
187470      *piPrev = (iPos & colmask);
187471    }
187472    pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
187473    *piPrev = iPos;
187474  }
187475  
187476  static int sqlite3Fts5PoslistWriterAppend(
187477    Fts5Buffer *pBuf, 
187478    Fts5PoslistWriter *pWriter,
187479    i64 iPos
187480  ){
187481    int rc = 0;   /* Initialized only to suppress erroneous warning from Clang */
187482    if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
187483    sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
187484    return SQLITE_OK;
187485  }
187486  
187487  static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
187488    void *pRet = 0;
187489    if( *pRc==SQLITE_OK ){
187490      pRet = sqlite3_malloc(nByte);
187491      if( pRet==0 ){
187492        if( nByte>0 ) *pRc = SQLITE_NOMEM;
187493      }else{
187494        memset(pRet, 0, nByte);
187495      }
187496    }
187497    return pRet;
187498  }
187499  
187500  /*
187501  ** Return a nul-terminated copy of the string indicated by pIn. If nIn
187502  ** is non-negative, then it is the length of the string in bytes. Otherwise,
187503  ** the length of the string is determined using strlen().
187504  **
187505  ** It is the responsibility of the caller to eventually free the returned
187506  ** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned. 
187507  */
187508  static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
187509    char *zRet = 0;
187510    if( *pRc==SQLITE_OK ){
187511      if( nIn<0 ){
187512        nIn = (int)strlen(pIn);
187513      }
187514      zRet = (char*)sqlite3_malloc(nIn+1);
187515      if( zRet ){
187516        memcpy(zRet, pIn, nIn);
187517        zRet[nIn] = '\0';
187518      }else{
187519        *pRc = SQLITE_NOMEM;
187520      }
187521    }
187522    return zRet;
187523  }
187524  
187525  
187526  /*
187527  ** Return true if character 't' may be part of an FTS5 bareword, or false
187528  ** otherwise. Characters that may be part of barewords:
187529  **
187530  **   * All non-ASCII characters,
187531  **   * The 52 upper and lower case ASCII characters, and
187532  **   * The 10 integer ASCII characters.
187533  **   * The underscore character "_" (0x5F).
187534  **   * The unicode "subsitute" character (0x1A).
187535  */
187536  static int sqlite3Fts5IsBareword(char t){
187537    u8 aBareword[128] = {
187538      0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00 .. 0x0F */
187539      0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 1, 0, 0, 0, 0, 0,   /* 0x10 .. 0x1F */
187540      0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20 .. 0x2F */
187541      1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30 .. 0x3F */
187542      0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40 .. 0x4F */
187543      1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 1,   /* 0x50 .. 0x5F */
187544      0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60 .. 0x6F */
187545      1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 0    /* 0x70 .. 0x7F */
187546    };
187547  
187548    return (t & 0x80) || aBareword[(int)t];
187549  }
187550  
187551  
187552  /*************************************************************************
187553  */
187554  typedef struct Fts5TermsetEntry Fts5TermsetEntry;
187555  struct Fts5TermsetEntry {
187556    char *pTerm;
187557    int nTerm;
187558    int iIdx;                       /* Index (main or aPrefix[] entry) */
187559    Fts5TermsetEntry *pNext;
187560  };
187561  
187562  struct Fts5Termset {
187563    Fts5TermsetEntry *apHash[512];
187564  };
187565  
187566  static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
187567    int rc = SQLITE_OK;
187568    *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
187569    return rc;
187570  }
187571  
187572  static int sqlite3Fts5TermsetAdd(
187573    Fts5Termset *p, 
187574    int iIdx,
187575    const char *pTerm, int nTerm, 
187576    int *pbPresent
187577  ){
187578    int rc = SQLITE_OK;
187579    *pbPresent = 0;
187580    if( p ){
187581      int i;
187582      u32 hash = 13;
187583      Fts5TermsetEntry *pEntry;
187584  
187585      /* Calculate a hash value for this term. This is the same hash checksum
187586      ** used by the fts5_hash.c module. This is not important for correct
187587      ** operation of the module, but is necessary to ensure that some tests
187588      ** designed to produce hash table collisions really do work.  */
187589      for(i=nTerm-1; i>=0; i--){
187590        hash = (hash << 3) ^ hash ^ pTerm[i];
187591      }
187592      hash = (hash << 3) ^ hash ^ iIdx;
187593      hash = hash % ArraySize(p->apHash);
187594  
187595      for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
187596        if( pEntry->iIdx==iIdx 
187597            && pEntry->nTerm==nTerm 
187598            && memcmp(pEntry->pTerm, pTerm, nTerm)==0 
187599        ){
187600          *pbPresent = 1;
187601          break;
187602        }
187603      }
187604  
187605      if( pEntry==0 ){
187606        pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
187607        if( pEntry ){
187608          pEntry->pTerm = (char*)&pEntry[1];
187609          pEntry->nTerm = nTerm;
187610          pEntry->iIdx = iIdx;
187611          memcpy(pEntry->pTerm, pTerm, nTerm);
187612          pEntry->pNext = p->apHash[hash];
187613          p->apHash[hash] = pEntry;
187614        }
187615      }
187616    }
187617  
187618    return rc;
187619  }
187620  
187621  static void sqlite3Fts5TermsetFree(Fts5Termset *p){
187622    if( p ){
187623      u32 i;
187624      for(i=0; i<ArraySize(p->apHash); i++){
187625        Fts5TermsetEntry *pEntry = p->apHash[i];
187626        while( pEntry ){
187627          Fts5TermsetEntry *pDel = pEntry;
187628          pEntry = pEntry->pNext;
187629          sqlite3_free(pDel);
187630        }
187631      }
187632      sqlite3_free(p);
187633    }
187634  }
187635  
187636  /*
187637  ** 2014 Jun 09
187638  **
187639  ** The author disclaims copyright to this source code.  In place of
187640  ** a legal notice, here is a blessing:
187641  **
187642  **    May you do good and not evil.
187643  **    May you find forgiveness for yourself and forgive others.
187644  **    May you share freely, never taking more than you give.
187645  **
187646  ******************************************************************************
187647  **
187648  ** This is an SQLite module implementing full-text search.
187649  */
187650  
187651  
187652  /* #include "fts5Int.h" */
187653  
187654  #define FTS5_DEFAULT_PAGE_SIZE   4050
187655  #define FTS5_DEFAULT_AUTOMERGE      4
187656  #define FTS5_DEFAULT_USERMERGE      4
187657  #define FTS5_DEFAULT_CRISISMERGE   16
187658  #define FTS5_DEFAULT_HASHSIZE    (1024*1024)
187659  
187660  /* Maximum allowed page size */
187661  #define FTS5_MAX_PAGE_SIZE (128*1024)
187662  
187663  static int fts5_iswhitespace(char x){
187664    return (x==' ');
187665  }
187666  
187667  static int fts5_isopenquote(char x){
187668    return (x=='"' || x=='\'' || x=='[' || x=='`');
187669  }
187670  
187671  /*
187672  ** Argument pIn points to a character that is part of a nul-terminated 
187673  ** string. Return a pointer to the first character following *pIn in 
187674  ** the string that is not a white-space character.
187675  */
187676  static const char *fts5ConfigSkipWhitespace(const char *pIn){
187677    const char *p = pIn;
187678    if( p ){
187679      while( fts5_iswhitespace(*p) ){ p++; }
187680    }
187681    return p;
187682  }
187683  
187684  /*
187685  ** Argument pIn points to a character that is part of a nul-terminated 
187686  ** string. Return a pointer to the first character following *pIn in 
187687  ** the string that is not a "bareword" character.
187688  */
187689  static const char *fts5ConfigSkipBareword(const char *pIn){
187690    const char *p = pIn;
187691    while ( sqlite3Fts5IsBareword(*p) ) p++;
187692    if( p==pIn ) p = 0;
187693    return p;
187694  }
187695  
187696  static int fts5_isdigit(char a){
187697    return (a>='0' && a<='9');
187698  }
187699  
187700  
187701  
187702  static const char *fts5ConfigSkipLiteral(const char *pIn){
187703    const char *p = pIn;
187704    switch( *p ){
187705      case 'n': case 'N':
187706        if( sqlite3_strnicmp("null", p, 4)==0 ){
187707          p = &p[4];
187708        }else{
187709          p = 0;
187710        }
187711        break;
187712  
187713      case 'x': case 'X':
187714        p++;
187715        if( *p=='\'' ){
187716          p++;
187717          while( (*p>='a' && *p<='f') 
187718              || (*p>='A' && *p<='F') 
187719              || (*p>='0' && *p<='9') 
187720              ){
187721            p++;
187722          }
187723          if( *p=='\'' && 0==((p-pIn)%2) ){
187724            p++;
187725          }else{
187726            p = 0;
187727          }
187728        }else{
187729          p = 0;
187730        }
187731        break;
187732  
187733      case '\'':
187734        p++;
187735        while( p ){
187736          if( *p=='\'' ){
187737            p++;
187738            if( *p!='\'' ) break;
187739          }
187740          p++;
187741          if( *p==0 ) p = 0;
187742        }
187743        break;
187744  
187745      default:
187746        /* maybe a number */
187747        if( *p=='+' || *p=='-' ) p++;
187748        while( fts5_isdigit(*p) ) p++;
187749  
187750        /* At this point, if the literal was an integer, the parse is 
187751        ** finished. Or, if it is a floating point value, it may continue
187752        ** with either a decimal point or an 'E' character. */
187753        if( *p=='.' && fts5_isdigit(p[1]) ){
187754          p += 2;
187755          while( fts5_isdigit(*p) ) p++;
187756        }
187757        if( p==pIn ) p = 0;
187758  
187759        break;
187760    }
187761  
187762    return p;
187763  }
187764  
187765  /*
187766  ** The first character of the string pointed to by argument z is guaranteed
187767  ** to be an open-quote character (see function fts5_isopenquote()).
187768  **
187769  ** This function searches for the corresponding close-quote character within
187770  ** the string and, if found, dequotes the string in place and adds a new
187771  ** nul-terminator byte.
187772  **
187773  ** If the close-quote is found, the value returned is the byte offset of
187774  ** the character immediately following it. Or, if the close-quote is not 
187775  ** found, -1 is returned. If -1 is returned, the buffer is left in an 
187776  ** undefined state.
187777  */
187778  static int fts5Dequote(char *z){
187779    char q;
187780    int iIn = 1;
187781    int iOut = 0;
187782    q = z[0];
187783  
187784    /* Set stack variable q to the close-quote character */
187785    assert( q=='[' || q=='\'' || q=='"' || q=='`' );
187786    if( q=='[' ) q = ']';  
187787  
187788    while( ALWAYS(z[iIn]) ){
187789      if( z[iIn]==q ){
187790        if( z[iIn+1]!=q ){
187791          /* Character iIn was the close quote. */
187792          iIn++;
187793          break;
187794        }else{
187795          /* Character iIn and iIn+1 form an escaped quote character. Skip
187796          ** the input cursor past both and copy a single quote character 
187797          ** to the output buffer. */
187798          iIn += 2;
187799          z[iOut++] = q;
187800        }
187801      }else{
187802        z[iOut++] = z[iIn++];
187803      }
187804    }
187805  
187806    z[iOut] = '\0';
187807    return iIn;
187808  }
187809  
187810  /*
187811  ** Convert an SQL-style quoted string into a normal string by removing
187812  ** the quote characters.  The conversion is done in-place.  If the
187813  ** input does not begin with a quote character, then this routine
187814  ** is a no-op.
187815  **
187816  ** Examples:
187817  **
187818  **     "abc"   becomes   abc
187819  **     'xyz'   becomes   xyz
187820  **     [pqr]   becomes   pqr
187821  **     `mno`   becomes   mno
187822  */
187823  static void sqlite3Fts5Dequote(char *z){
187824    char quote;                     /* Quote character (if any ) */
187825  
187826    assert( 0==fts5_iswhitespace(z[0]) );
187827    quote = z[0];
187828    if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
187829      fts5Dequote(z);
187830    }
187831  }
187832  
187833  
187834  struct Fts5Enum {
187835    const char *zName;
187836    int eVal;
187837  };
187838  typedef struct Fts5Enum Fts5Enum;
187839  
187840  static int fts5ConfigSetEnum(
187841    const Fts5Enum *aEnum, 
187842    const char *zEnum, 
187843    int *peVal
187844  ){
187845    int nEnum = (int)strlen(zEnum);
187846    int i;
187847    int iVal = -1;
187848  
187849    for(i=0; aEnum[i].zName; i++){
187850      if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
187851        if( iVal>=0 ) return SQLITE_ERROR;
187852        iVal = aEnum[i].eVal;
187853      }
187854    }
187855  
187856    *peVal = iVal;
187857    return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
187858  }
187859  
187860  /*
187861  ** Parse a "special" CREATE VIRTUAL TABLE directive and update
187862  ** configuration object pConfig as appropriate.
187863  **
187864  ** If successful, object pConfig is updated and SQLITE_OK returned. If
187865  ** an error occurs, an SQLite error code is returned and an error message
187866  ** may be left in *pzErr. It is the responsibility of the caller to
187867  ** eventually free any such error message using sqlite3_free().
187868  */
187869  static int fts5ConfigParseSpecial(
187870    Fts5Global *pGlobal,
187871    Fts5Config *pConfig,            /* Configuration object to update */
187872    const char *zCmd,               /* Special command to parse */
187873    const char *zArg,               /* Argument to parse */
187874    char **pzErr                    /* OUT: Error message */
187875  ){
187876    int rc = SQLITE_OK;
187877    int nCmd = (int)strlen(zCmd);
187878    if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
187879      const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
187880      const char *p;
187881      int bFirst = 1;
187882      if( pConfig->aPrefix==0 ){
187883        pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
187884        if( rc ) return rc;
187885      }
187886  
187887      p = zArg;
187888      while( 1 ){
187889        int nPre = 0;
187890  
187891        while( p[0]==' ' ) p++;
187892        if( bFirst==0 && p[0]==',' ){
187893          p++;
187894          while( p[0]==' ' ) p++;
187895        }else if( p[0]=='\0' ){
187896          break;
187897        }
187898        if( p[0]<'0' || p[0]>'9' ){
187899          *pzErr = sqlite3_mprintf("malformed prefix=... directive");
187900          rc = SQLITE_ERROR;
187901          break;
187902        }
187903  
187904        if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
187905          *pzErr = sqlite3_mprintf(
187906              "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
187907          );
187908          rc = SQLITE_ERROR;
187909          break;
187910        }
187911  
187912        while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
187913          nPre = nPre*10 + (p[0] - '0');
187914          p++;
187915        }
187916  
187917        if( nPre<=0 || nPre>=1000 ){
187918          *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
187919          rc = SQLITE_ERROR;
187920          break;
187921        }
187922  
187923        pConfig->aPrefix[pConfig->nPrefix] = nPre;
187924        pConfig->nPrefix++;
187925        bFirst = 0;
187926      }
187927      assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
187928      return rc;
187929    }
187930  
187931    if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
187932      const char *p = (const char*)zArg;
187933      int nArg = (int)strlen(zArg) + 1;
187934      char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
187935      char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
187936      char *pSpace = pDel;
187937  
187938      if( azArg && pSpace ){
187939        if( pConfig->pTok ){
187940          *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
187941          rc = SQLITE_ERROR;
187942        }else{
187943          for(nArg=0; p && *p; nArg++){
187944            const char *p2 = fts5ConfigSkipWhitespace(p);
187945            if( *p2=='\'' ){
187946              p = fts5ConfigSkipLiteral(p2);
187947            }else{
187948              p = fts5ConfigSkipBareword(p2);
187949            }
187950            if( p ){
187951              memcpy(pSpace, p2, p-p2);
187952              azArg[nArg] = pSpace;
187953              sqlite3Fts5Dequote(pSpace);
187954              pSpace += (p - p2) + 1;
187955              p = fts5ConfigSkipWhitespace(p);
187956            }
187957          }
187958          if( p==0 ){
187959            *pzErr = sqlite3_mprintf("parse error in tokenize directive");
187960            rc = SQLITE_ERROR;
187961          }else{
187962            rc = sqlite3Fts5GetTokenizer(pGlobal, 
187963                (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
187964                pzErr
187965            );
187966          }
187967        }
187968      }
187969  
187970      sqlite3_free(azArg);
187971      sqlite3_free(pDel);
187972      return rc;
187973    }
187974  
187975    if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
187976      if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
187977        *pzErr = sqlite3_mprintf("multiple content=... directives");
187978        rc = SQLITE_ERROR;
187979      }else{
187980        if( zArg[0] ){
187981          pConfig->eContent = FTS5_CONTENT_EXTERNAL;
187982          pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
187983        }else{
187984          pConfig->eContent = FTS5_CONTENT_NONE;
187985        }
187986      }
187987      return rc;
187988    }
187989  
187990    if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
187991      if( pConfig->zContentRowid ){
187992        *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
187993        rc = SQLITE_ERROR;
187994      }else{
187995        pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
187996      }
187997      return rc;
187998    }
187999  
188000    if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
188001      if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
188002        *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
188003        rc = SQLITE_ERROR;
188004      }else{
188005        pConfig->bColumnsize = (zArg[0]=='1');
188006      }
188007      return rc;
188008    }
188009  
188010    if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
188011      const Fts5Enum aDetail[] = {
188012        { "none", FTS5_DETAIL_NONE },
188013        { "full", FTS5_DETAIL_FULL },
188014        { "columns", FTS5_DETAIL_COLUMNS },
188015        { 0, 0 }
188016      };
188017  
188018      if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
188019        *pzErr = sqlite3_mprintf("malformed detail=... directive");
188020      }
188021      return rc;
188022    }
188023  
188024    *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
188025    return SQLITE_ERROR;
188026  }
188027  
188028  /*
188029  ** Allocate an instance of the default tokenizer ("simple") at 
188030  ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
188031  ** code if an error occurs.
188032  */
188033  static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
188034    assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
188035    return sqlite3Fts5GetTokenizer(
188036        pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
188037    );
188038  }
188039  
188040  /*
188041  ** Gobble up the first bareword or quoted word from the input buffer zIn.
188042  ** Return a pointer to the character immediately following the last in
188043  ** the gobbled word if successful, or a NULL pointer otherwise (failed
188044  ** to find close-quote character).
188045  **
188046  ** Before returning, set pzOut to point to a new buffer containing a
188047  ** nul-terminated, dequoted copy of the gobbled word. If the word was
188048  ** quoted, *pbQuoted is also set to 1 before returning.
188049  **
188050  ** If *pRc is other than SQLITE_OK when this function is called, it is
188051  ** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
188052  ** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
188053  ** set if a parse error (failed to find close quote) occurs.
188054  */
188055  static const char *fts5ConfigGobbleWord(
188056    int *pRc,                       /* IN/OUT: Error code */
188057    const char *zIn,                /* Buffer to gobble string/bareword from */
188058    char **pzOut,                   /* OUT: malloc'd buffer containing str/bw */
188059    int *pbQuoted                   /* OUT: Set to true if dequoting required */
188060  ){
188061    const char *zRet = 0;
188062  
188063    int nIn = (int)strlen(zIn);
188064    char *zOut = sqlite3_malloc(nIn+1);
188065  
188066    assert( *pRc==SQLITE_OK );
188067    *pbQuoted = 0;
188068    *pzOut = 0;
188069  
188070    if( zOut==0 ){
188071      *pRc = SQLITE_NOMEM;
188072    }else{
188073      memcpy(zOut, zIn, nIn+1);
188074      if( fts5_isopenquote(zOut[0]) ){
188075        int ii = fts5Dequote(zOut);
188076        zRet = &zIn[ii];
188077        *pbQuoted = 1;
188078      }else{
188079        zRet = fts5ConfigSkipBareword(zIn);
188080        if( zRet ){
188081          zOut[zRet-zIn] = '\0';
188082        }
188083      }
188084    }
188085  
188086    if( zRet==0 ){
188087      sqlite3_free(zOut);
188088    }else{
188089      *pzOut = zOut;
188090    }
188091  
188092    return zRet;
188093  }
188094  
188095  static int fts5ConfigParseColumn(
188096    Fts5Config *p, 
188097    char *zCol, 
188098    char *zArg, 
188099    char **pzErr
188100  ){
188101    int rc = SQLITE_OK;
188102    if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME) 
188103     || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME) 
188104    ){
188105      *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
188106      rc = SQLITE_ERROR;
188107    }else if( zArg ){
188108      if( 0==sqlite3_stricmp(zArg, "unindexed") ){
188109        p->abUnindexed[p->nCol] = 1;
188110      }else{
188111        *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
188112        rc = SQLITE_ERROR;
188113      }
188114    }
188115  
188116    p->azCol[p->nCol++] = zCol;
188117    return rc;
188118  }
188119  
188120  /*
188121  ** Populate the Fts5Config.zContentExprlist string.
188122  */
188123  static int fts5ConfigMakeExprlist(Fts5Config *p){
188124    int i;
188125    int rc = SQLITE_OK;
188126    Fts5Buffer buf = {0, 0, 0};
188127  
188128    sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
188129    if( p->eContent!=FTS5_CONTENT_NONE ){
188130      for(i=0; i<p->nCol; i++){
188131        if( p->eContent==FTS5_CONTENT_EXTERNAL ){
188132          sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
188133        }else{
188134          sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
188135        }
188136      }
188137    }
188138  
188139    assert( p->zContentExprlist==0 );
188140    p->zContentExprlist = (char*)buf.p;
188141    return rc;
188142  }
188143  
188144  /*
188145  ** Arguments nArg/azArg contain the string arguments passed to the xCreate
188146  ** or xConnect method of the virtual table. This function attempts to 
188147  ** allocate an instance of Fts5Config containing the results of parsing
188148  ** those arguments.
188149  **
188150  ** If successful, SQLITE_OK is returned and *ppOut is set to point to the
188151  ** new Fts5Config object. If an error occurs, an SQLite error code is 
188152  ** returned, *ppOut is set to NULL and an error message may be left in
188153  ** *pzErr. It is the responsibility of the caller to eventually free any 
188154  ** such error message using sqlite3_free().
188155  */
188156  static int sqlite3Fts5ConfigParse(
188157    Fts5Global *pGlobal,
188158    sqlite3 *db,
188159    int nArg,                       /* Number of arguments */
188160    const char **azArg,             /* Array of nArg CREATE VIRTUAL TABLE args */
188161    Fts5Config **ppOut,             /* OUT: Results of parse */
188162    char **pzErr                    /* OUT: Error message */
188163  ){
188164    int rc = SQLITE_OK;             /* Return code */
188165    Fts5Config *pRet;               /* New object to return */
188166    int i;
188167    int nByte;
188168  
188169    *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
188170    if( pRet==0 ) return SQLITE_NOMEM;
188171    memset(pRet, 0, sizeof(Fts5Config));
188172    pRet->db = db;
188173    pRet->iCookie = -1;
188174  
188175    nByte = nArg * (sizeof(char*) + sizeof(u8));
188176    pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
188177    pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
188178    pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
188179    pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
188180    pRet->bColumnsize = 1;
188181    pRet->eDetail = FTS5_DETAIL_FULL;
188182  #ifdef SQLITE_DEBUG
188183    pRet->bPrefixIndex = 1;
188184  #endif
188185    if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
188186      *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
188187      rc = SQLITE_ERROR;
188188    }
188189  
188190    for(i=3; rc==SQLITE_OK && i<nArg; i++){
188191      const char *zOrig = azArg[i];
188192      const char *z;
188193      char *zOne = 0;
188194      char *zTwo = 0;
188195      int bOption = 0;
188196      int bMustBeCol = 0;
188197  
188198      z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
188199      z = fts5ConfigSkipWhitespace(z);
188200      if( z && *z=='=' ){
188201        bOption = 1;
188202        z++;
188203        if( bMustBeCol ) z = 0;
188204      }
188205      z = fts5ConfigSkipWhitespace(z);
188206      if( z && z[0] ){
188207        int bDummy;
188208        z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
188209        if( z && z[0] ) z = 0;
188210      }
188211  
188212      if( rc==SQLITE_OK ){
188213        if( z==0 ){
188214          *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
188215          rc = SQLITE_ERROR;
188216        }else{
188217          if( bOption ){
188218            rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
188219          }else{
188220            rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
188221            zOne = 0;
188222          }
188223        }
188224      }
188225  
188226      sqlite3_free(zOne);
188227      sqlite3_free(zTwo);
188228    }
188229  
188230    /* If a tokenizer= option was successfully parsed, the tokenizer has
188231    ** already been allocated. Otherwise, allocate an instance of the default
188232    ** tokenizer (unicode61) now.  */
188233    if( rc==SQLITE_OK && pRet->pTok==0 ){
188234      rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
188235    }
188236  
188237    /* If no zContent option was specified, fill in the default values. */
188238    if( rc==SQLITE_OK && pRet->zContent==0 ){
188239      const char *zTail = 0;
188240      assert( pRet->eContent==FTS5_CONTENT_NORMAL 
188241           || pRet->eContent==FTS5_CONTENT_NONE 
188242      );
188243      if( pRet->eContent==FTS5_CONTENT_NORMAL ){
188244        zTail = "content";
188245      }else if( pRet->bColumnsize ){
188246        zTail = "docsize";
188247      }
188248  
188249      if( zTail ){
188250        pRet->zContent = sqlite3Fts5Mprintf(
188251            &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
188252        );
188253      }
188254    }
188255  
188256    if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
188257      pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
188258    }
188259  
188260    /* Formulate the zContentExprlist text */
188261    if( rc==SQLITE_OK ){
188262      rc = fts5ConfigMakeExprlist(pRet);
188263    }
188264  
188265    if( rc!=SQLITE_OK ){
188266      sqlite3Fts5ConfigFree(pRet);
188267      *ppOut = 0;
188268    }
188269    return rc;
188270  }
188271  
188272  /*
188273  ** Free the configuration object passed as the only argument.
188274  */
188275  static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
188276    if( pConfig ){
188277      int i;
188278      if( pConfig->pTok ){
188279        pConfig->pTokApi->xDelete(pConfig->pTok);
188280      }
188281      sqlite3_free(pConfig->zDb);
188282      sqlite3_free(pConfig->zName);
188283      for(i=0; i<pConfig->nCol; i++){
188284        sqlite3_free(pConfig->azCol[i]);
188285      }
188286      sqlite3_free(pConfig->azCol);
188287      sqlite3_free(pConfig->aPrefix);
188288      sqlite3_free(pConfig->zRank);
188289      sqlite3_free(pConfig->zRankArgs);
188290      sqlite3_free(pConfig->zContent);
188291      sqlite3_free(pConfig->zContentRowid);
188292      sqlite3_free(pConfig->zContentExprlist);
188293      sqlite3_free(pConfig);
188294    }
188295  }
188296  
188297  /*
188298  ** Call sqlite3_declare_vtab() based on the contents of the configuration
188299  ** object passed as the only argument. Return SQLITE_OK if successful, or
188300  ** an SQLite error code if an error occurs.
188301  */
188302  static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
188303    int i;
188304    int rc = SQLITE_OK;
188305    char *zSql;
188306  
188307    zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
188308    for(i=0; zSql && i<pConfig->nCol; i++){
188309      const char *zSep = (i==0?"":", ");
188310      zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
188311    }
188312    zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)", 
188313        zSql, pConfig->zName, FTS5_RANK_NAME
188314    );
188315  
188316    assert( zSql || rc==SQLITE_NOMEM );
188317    if( zSql ){
188318      rc = sqlite3_declare_vtab(pConfig->db, zSql);
188319      sqlite3_free(zSql);
188320    }
188321    
188322    return rc;
188323  }
188324  
188325  /*
188326  ** Tokenize the text passed via the second and third arguments.
188327  **
188328  ** The callback is invoked once for each token in the input text. The
188329  ** arguments passed to it are, in order:
188330  **
188331  **     void *pCtx          // Copy of 4th argument to sqlite3Fts5Tokenize()
188332  **     const char *pToken  // Pointer to buffer containing token
188333  **     int nToken          // Size of token in bytes
188334  **     int iStart          // Byte offset of start of token within input text
188335  **     int iEnd            // Byte offset of end of token within input text
188336  **     int iPos            // Position of token in input (first token is 0)
188337  **
188338  ** If the callback returns a non-zero value the tokenization is abandoned
188339  ** and no further callbacks are issued. 
188340  **
188341  ** This function returns SQLITE_OK if successful or an SQLite error code
188342  ** if an error occurs. If the tokenization was abandoned early because
188343  ** the callback returned SQLITE_DONE, this is not an error and this function
188344  ** still returns SQLITE_OK. Or, if the tokenization was abandoned early
188345  ** because the callback returned another non-zero value, it is assumed
188346  ** to be an SQLite error code and returned to the caller.
188347  */
188348  static int sqlite3Fts5Tokenize(
188349    Fts5Config *pConfig,            /* FTS5 Configuration object */
188350    int flags,                      /* FTS5_TOKENIZE_* flags */
188351    const char *pText, int nText,   /* Text to tokenize */
188352    void *pCtx,                     /* Context passed to xToken() */
188353    int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
188354  ){
188355    if( pText==0 ) return SQLITE_OK;
188356    return pConfig->pTokApi->xTokenize(
188357        pConfig->pTok, pCtx, flags, pText, nText, xToken
188358    );
188359  }
188360  
188361  /*
188362  ** Argument pIn points to the first character in what is expected to be
188363  ** a comma-separated list of SQL literals followed by a ')' character.
188364  ** If it actually is this, return a pointer to the ')'. Otherwise, return
188365  ** NULL to indicate a parse error.
188366  */
188367  static const char *fts5ConfigSkipArgs(const char *pIn){
188368    const char *p = pIn;
188369    
188370    while( 1 ){
188371      p = fts5ConfigSkipWhitespace(p);
188372      p = fts5ConfigSkipLiteral(p);
188373      p = fts5ConfigSkipWhitespace(p);
188374      if( p==0 || *p==')' ) break;
188375      if( *p!=',' ){
188376        p = 0;
188377        break;
188378      }
188379      p++;
188380    }
188381  
188382    return p;
188383  }
188384  
188385  /*
188386  ** Parameter zIn contains a rank() function specification. The format of 
188387  ** this is:
188388  **
188389  **   + Bareword (function name)
188390  **   + Open parenthesis - "("
188391  **   + Zero or more SQL literals in a comma separated list
188392  **   + Close parenthesis - ")"
188393  */
188394  static int sqlite3Fts5ConfigParseRank(
188395    const char *zIn,                /* Input string */
188396    char **pzRank,                  /* OUT: Rank function name */
188397    char **pzRankArgs               /* OUT: Rank function arguments */
188398  ){
188399    const char *p = zIn;
188400    const char *pRank;
188401    char *zRank = 0;
188402    char *zRankArgs = 0;
188403    int rc = SQLITE_OK;
188404  
188405    *pzRank = 0;
188406    *pzRankArgs = 0;
188407  
188408    if( p==0 ){
188409      rc = SQLITE_ERROR;
188410    }else{
188411      p = fts5ConfigSkipWhitespace(p);
188412      pRank = p;
188413      p = fts5ConfigSkipBareword(p);
188414  
188415      if( p ){
188416        zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
188417        if( zRank ) memcpy(zRank, pRank, p-pRank);
188418      }else{
188419        rc = SQLITE_ERROR;
188420      }
188421  
188422      if( rc==SQLITE_OK ){
188423        p = fts5ConfigSkipWhitespace(p);
188424        if( *p!='(' ) rc = SQLITE_ERROR;
188425        p++;
188426      }
188427      if( rc==SQLITE_OK ){
188428        const char *pArgs; 
188429        p = fts5ConfigSkipWhitespace(p);
188430        pArgs = p;
188431        if( *p!=')' ){
188432          p = fts5ConfigSkipArgs(p);
188433          if( p==0 ){
188434            rc = SQLITE_ERROR;
188435          }else{
188436            zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
188437            if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
188438          }
188439        }
188440      }
188441    }
188442  
188443    if( rc!=SQLITE_OK ){
188444      sqlite3_free(zRank);
188445      assert( zRankArgs==0 );
188446    }else{
188447      *pzRank = zRank;
188448      *pzRankArgs = zRankArgs;
188449    }
188450    return rc;
188451  }
188452  
188453  static int sqlite3Fts5ConfigSetValue(
188454    Fts5Config *pConfig, 
188455    const char *zKey, 
188456    sqlite3_value *pVal,
188457    int *pbBadkey
188458  ){
188459    int rc = SQLITE_OK;
188460  
188461    if( 0==sqlite3_stricmp(zKey, "pgsz") ){
188462      int pgsz = 0;
188463      if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
188464        pgsz = sqlite3_value_int(pVal);
188465      }
188466      if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
188467        *pbBadkey = 1;
188468      }else{
188469        pConfig->pgsz = pgsz;
188470      }
188471    }
188472  
188473    else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
188474      int nHashSize = -1;
188475      if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
188476        nHashSize = sqlite3_value_int(pVal);
188477      }
188478      if( nHashSize<=0 ){
188479        *pbBadkey = 1;
188480      }else{
188481        pConfig->nHashSize = nHashSize;
188482      }
188483    }
188484  
188485    else if( 0==sqlite3_stricmp(zKey, "automerge") ){
188486      int nAutomerge = -1;
188487      if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
188488        nAutomerge = sqlite3_value_int(pVal);
188489      }
188490      if( nAutomerge<0 || nAutomerge>64 ){
188491        *pbBadkey = 1;
188492      }else{
188493        if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
188494        pConfig->nAutomerge = nAutomerge;
188495      }
188496    }
188497  
188498    else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
188499      int nUsermerge = -1;
188500      if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
188501        nUsermerge = sqlite3_value_int(pVal);
188502      }
188503      if( nUsermerge<2 || nUsermerge>16 ){
188504        *pbBadkey = 1;
188505      }else{
188506        pConfig->nUsermerge = nUsermerge;
188507      }
188508    }
188509  
188510    else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
188511      int nCrisisMerge = -1;
188512      if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
188513        nCrisisMerge = sqlite3_value_int(pVal);
188514      }
188515      if( nCrisisMerge<0 ){
188516        *pbBadkey = 1;
188517      }else{
188518        if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
188519        pConfig->nCrisisMerge = nCrisisMerge;
188520      }
188521    }
188522  
188523    else if( 0==sqlite3_stricmp(zKey, "rank") ){
188524      const char *zIn = (const char*)sqlite3_value_text(pVal);
188525      char *zRank;
188526      char *zRankArgs;
188527      rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
188528      if( rc==SQLITE_OK ){
188529        sqlite3_free(pConfig->zRank);
188530        sqlite3_free(pConfig->zRankArgs);
188531        pConfig->zRank = zRank;
188532        pConfig->zRankArgs = zRankArgs;
188533      }else if( rc==SQLITE_ERROR ){
188534        rc = SQLITE_OK;
188535        *pbBadkey = 1;
188536      }
188537    }else{
188538      *pbBadkey = 1;
188539    }
188540    return rc;
188541  }
188542  
188543  /*
188544  ** Load the contents of the %_config table into memory.
188545  */
188546  static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
188547    const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
188548    char *zSql;
188549    sqlite3_stmt *p = 0;
188550    int rc = SQLITE_OK;
188551    int iVersion = 0;
188552  
188553    /* Set default values */
188554    pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
188555    pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
188556    pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
188557    pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
188558    pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
188559  
188560    zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
188561    if( zSql ){
188562      rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
188563      sqlite3_free(zSql);
188564    }
188565  
188566    assert( rc==SQLITE_OK || p==0 );
188567    if( rc==SQLITE_OK ){
188568      while( SQLITE_ROW==sqlite3_step(p) ){
188569        const char *zK = (const char*)sqlite3_column_text(p, 0);
188570        sqlite3_value *pVal = sqlite3_column_value(p, 1);
188571        if( 0==sqlite3_stricmp(zK, "version") ){
188572          iVersion = sqlite3_value_int(pVal);
188573        }else{
188574          int bDummy = 0;
188575          sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
188576        }
188577      }
188578      rc = sqlite3_finalize(p);
188579    }
188580    
188581    if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
188582      rc = SQLITE_ERROR;
188583      if( pConfig->pzErrmsg ){
188584        assert( 0==*pConfig->pzErrmsg );
188585        *pConfig->pzErrmsg = sqlite3_mprintf(
188586            "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
188587            iVersion, FTS5_CURRENT_VERSION
188588        );
188589      }
188590    }
188591  
188592    if( rc==SQLITE_OK ){
188593      pConfig->iCookie = iCookie;
188594    }
188595    return rc;
188596  }
188597  
188598  /*
188599  ** 2014 May 31
188600  **
188601  ** The author disclaims copyright to this source code.  In place of
188602  ** a legal notice, here is a blessing:
188603  **
188604  **    May you do good and not evil.
188605  **    May you find forgiveness for yourself and forgive others.
188606  **    May you share freely, never taking more than you give.
188607  **
188608  ******************************************************************************
188609  **
188610  */
188611  
188612  
188613  
188614  /* #include "fts5Int.h" */
188615  /* #include "fts5parse.h" */
188616  
188617  /*
188618  ** All token types in the generated fts5parse.h file are greater than 0.
188619  */
188620  #define FTS5_EOF 0
188621  
188622  #define FTS5_LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
188623  
188624  typedef struct Fts5ExprTerm Fts5ExprTerm;
188625  
188626  /*
188627  ** Functions generated by lemon from fts5parse.y.
188628  */
188629  static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
188630  static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
188631  static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
188632  #ifndef NDEBUG
188633  /* #include <stdio.h> */
188634  static void sqlite3Fts5ParserTrace(FILE*, char*);
188635  #endif
188636  
188637  
188638  struct Fts5Expr {
188639    Fts5Index *pIndex;
188640    Fts5Config *pConfig;
188641    Fts5ExprNode *pRoot;
188642    int bDesc;                      /* Iterate in descending rowid order */
188643    int nPhrase;                    /* Number of phrases in expression */
188644    Fts5ExprPhrase **apExprPhrase;  /* Pointers to phrase objects */
188645  };
188646  
188647  /*
188648  ** eType:
188649  **   Expression node type. Always one of:
188650  **
188651  **       FTS5_AND                 (nChild, apChild valid)
188652  **       FTS5_OR                  (nChild, apChild valid)
188653  **       FTS5_NOT                 (nChild, apChild valid)
188654  **       FTS5_STRING              (pNear valid)
188655  **       FTS5_TERM                (pNear valid)
188656  */
188657  struct Fts5ExprNode {
188658    int eType;                      /* Node type */
188659    int bEof;                       /* True at EOF */
188660    int bNomatch;                   /* True if entry is not a match */
188661  
188662    /* Next method for this node. */
188663    int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
188664  
188665    i64 iRowid;                     /* Current rowid */
188666    Fts5ExprNearset *pNear;         /* For FTS5_STRING - cluster of phrases */
188667  
188668    /* Child nodes. For a NOT node, this array always contains 2 entries. For 
188669    ** AND or OR nodes, it contains 2 or more entries.  */
188670    int nChild;                     /* Number of child nodes */
188671    Fts5ExprNode *apChild[1];       /* Array of child nodes */
188672  };
188673  
188674  #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
188675  
188676  /*
188677  ** Invoke the xNext method of an Fts5ExprNode object. This macro should be
188678  ** used as if it has the same signature as the xNext() methods themselves.
188679  */
188680  #define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
188681  
188682  /*
188683  ** An instance of the following structure represents a single search term
188684  ** or term prefix.
188685  */
188686  struct Fts5ExprTerm {
188687    int bPrefix;                    /* True for a prefix term */
188688    char *zTerm;                    /* nul-terminated term */
188689    Fts5IndexIter *pIter;           /* Iterator for this term */
188690    Fts5ExprTerm *pSynonym;         /* Pointer to first in list of synonyms */
188691  };
188692  
188693  /*
188694  ** A phrase. One or more terms that must appear in a contiguous sequence
188695  ** within a document for it to match.
188696  */
188697  struct Fts5ExprPhrase {
188698    Fts5ExprNode *pNode;            /* FTS5_STRING node this phrase is part of */
188699    Fts5Buffer poslist;             /* Current position list */
188700    int nTerm;                      /* Number of entries in aTerm[] */
188701    Fts5ExprTerm aTerm[1];          /* Terms that make up this phrase */
188702  };
188703  
188704  /*
188705  ** One or more phrases that must appear within a certain token distance of
188706  ** each other within each matching document.
188707  */
188708  struct Fts5ExprNearset {
188709    int nNear;                      /* NEAR parameter */
188710    Fts5Colset *pColset;            /* Columns to search (NULL -> all columns) */
188711    int nPhrase;                    /* Number of entries in aPhrase[] array */
188712    Fts5ExprPhrase *apPhrase[1];    /* Array of phrase pointers */
188713  };
188714  
188715  
188716  /*
188717  ** Parse context.
188718  */
188719  struct Fts5Parse {
188720    Fts5Config *pConfig;
188721    char *zErr;
188722    int rc;
188723    int nPhrase;                    /* Size of apPhrase array */
188724    Fts5ExprPhrase **apPhrase;      /* Array of all phrases */
188725    Fts5ExprNode *pExpr;            /* Result of a successful parse */
188726  };
188727  
188728  static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
188729    va_list ap;
188730    va_start(ap, zFmt);
188731    if( pParse->rc==SQLITE_OK ){
188732      pParse->zErr = sqlite3_vmprintf(zFmt, ap);
188733      pParse->rc = SQLITE_ERROR;
188734    }
188735    va_end(ap);
188736  }
188737  
188738  static int fts5ExprIsspace(char t){
188739    return t==' ' || t=='\t' || t=='\n' || t=='\r';
188740  }
188741  
188742  /*
188743  ** Read the first token from the nul-terminated string at *pz.
188744  */
188745  static int fts5ExprGetToken(
188746    Fts5Parse *pParse, 
188747    const char **pz,                /* IN/OUT: Pointer into buffer */
188748    Fts5Token *pToken
188749  ){
188750    const char *z = *pz;
188751    int tok;
188752  
188753    /* Skip past any whitespace */
188754    while( fts5ExprIsspace(*z) ) z++;
188755  
188756    pToken->p = z;
188757    pToken->n = 1;
188758    switch( *z ){
188759      case '(':  tok = FTS5_LP;    break;
188760      case ')':  tok = FTS5_RP;    break;
188761      case '{':  tok = FTS5_LCP;   break;
188762      case '}':  tok = FTS5_RCP;   break;
188763      case ':':  tok = FTS5_COLON; break;
188764      case ',':  tok = FTS5_COMMA; break;
188765      case '+':  tok = FTS5_PLUS;  break;
188766      case '*':  tok = FTS5_STAR;  break;
188767      case '-':  tok = FTS5_MINUS; break;
188768      case '\0': tok = FTS5_EOF;   break;
188769  
188770      case '"': {
188771        const char *z2;
188772        tok = FTS5_STRING;
188773  
188774        for(z2=&z[1]; 1; z2++){
188775          if( z2[0]=='"' ){
188776            z2++;
188777            if( z2[0]!='"' ) break;
188778          }
188779          if( z2[0]=='\0' ){
188780            sqlite3Fts5ParseError(pParse, "unterminated string");
188781            return FTS5_EOF;
188782          }
188783        }
188784        pToken->n = (z2 - z);
188785        break;
188786      }
188787  
188788      default: {
188789        const char *z2;
188790        if( sqlite3Fts5IsBareword(z[0])==0 ){
188791          sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
188792          return FTS5_EOF;
188793        }
188794        tok = FTS5_STRING;
188795        for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
188796        pToken->n = (z2 - z);
188797        if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 )  tok = FTS5_OR;
188798        if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
188799        if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
188800        break;
188801      }
188802    }
188803  
188804    *pz = &pToken->p[pToken->n];
188805    return tok;
188806  }
188807  
188808  static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
188809  static void fts5ParseFree(void *p){ sqlite3_free(p); }
188810  
188811  static int sqlite3Fts5ExprNew(
188812    Fts5Config *pConfig,            /* FTS5 Configuration */
188813    int iCol,
188814    const char *zExpr,              /* Expression text */
188815    Fts5Expr **ppNew, 
188816    char **pzErr
188817  ){
188818    Fts5Parse sParse;
188819    Fts5Token token;
188820    const char *z = zExpr;
188821    int t;                          /* Next token type */
188822    void *pEngine;
188823    Fts5Expr *pNew;
188824  
188825    *ppNew = 0;
188826    *pzErr = 0;
188827    memset(&sParse, 0, sizeof(sParse));
188828    pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
188829    if( pEngine==0 ){ return SQLITE_NOMEM; }
188830    sParse.pConfig = pConfig;
188831  
188832    do {
188833      t = fts5ExprGetToken(&sParse, &z, &token);
188834      sqlite3Fts5Parser(pEngine, t, token, &sParse);
188835    }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
188836    sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
188837  
188838    /* If the LHS of the MATCH expression was a user column, apply the
188839    ** implicit column-filter.  */
188840    if( iCol<pConfig->nCol && sParse.pExpr && sParse.rc==SQLITE_OK ){
188841      int n = sizeof(Fts5Colset);
188842      Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n);
188843      if( pColset ){
188844        pColset->nCol = 1;
188845        pColset->aiCol[0] = iCol;
188846        sqlite3Fts5ParseSetColset(&sParse, sParse.pExpr, pColset);
188847      }
188848    }
188849  
188850    assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
188851    if( sParse.rc==SQLITE_OK ){
188852      *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
188853      if( pNew==0 ){
188854        sParse.rc = SQLITE_NOMEM;
188855        sqlite3Fts5ParseNodeFree(sParse.pExpr);
188856      }else{
188857        if( !sParse.pExpr ){
188858          const int nByte = sizeof(Fts5ExprNode);
188859          pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
188860          if( pNew->pRoot ){
188861            pNew->pRoot->bEof = 1;
188862          }
188863        }else{
188864          pNew->pRoot = sParse.pExpr;
188865        }
188866        pNew->pIndex = 0;
188867        pNew->pConfig = pConfig;
188868        pNew->apExprPhrase = sParse.apPhrase;
188869        pNew->nPhrase = sParse.nPhrase;
188870        sParse.apPhrase = 0;
188871      }
188872    }else{
188873      sqlite3Fts5ParseNodeFree(sParse.pExpr);
188874    }
188875  
188876    sqlite3_free(sParse.apPhrase);
188877    *pzErr = sParse.zErr;
188878    return sParse.rc;
188879  }
188880  
188881  /*
188882  ** Free the expression node object passed as the only argument.
188883  */
188884  static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
188885    if( p ){
188886      int i;
188887      for(i=0; i<p->nChild; i++){
188888        sqlite3Fts5ParseNodeFree(p->apChild[i]);
188889      }
188890      sqlite3Fts5ParseNearsetFree(p->pNear);
188891      sqlite3_free(p);
188892    }
188893  }
188894  
188895  /*
188896  ** Free the expression object passed as the only argument.
188897  */
188898  static void sqlite3Fts5ExprFree(Fts5Expr *p){
188899    if( p ){
188900      sqlite3Fts5ParseNodeFree(p->pRoot);
188901      sqlite3_free(p->apExprPhrase);
188902      sqlite3_free(p);
188903    }
188904  }
188905  
188906  /*
188907  ** Argument pTerm must be a synonym iterator. Return the current rowid
188908  ** that it points to.
188909  */
188910  static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
188911    i64 iRet = 0;
188912    int bRetValid = 0;
188913    Fts5ExprTerm *p;
188914  
188915    assert( pTerm->pSynonym );
188916    assert( bDesc==0 || bDesc==1 );
188917    for(p=pTerm; p; p=p->pSynonym){
188918      if( 0==sqlite3Fts5IterEof(p->pIter) ){
188919        i64 iRowid = p->pIter->iRowid;
188920        if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
188921          iRet = iRowid;
188922          bRetValid = 1;
188923        }
188924      }
188925    }
188926  
188927    if( pbEof && bRetValid==0 ) *pbEof = 1;
188928    return iRet;
188929  }
188930  
188931  /*
188932  ** Argument pTerm must be a synonym iterator.
188933  */
188934  static int fts5ExprSynonymList(
188935    Fts5ExprTerm *pTerm, 
188936    i64 iRowid,
188937    Fts5Buffer *pBuf,               /* Use this buffer for space if required */
188938    u8 **pa, int *pn
188939  ){
188940    Fts5PoslistReader aStatic[4];
188941    Fts5PoslistReader *aIter = aStatic;
188942    int nIter = 0;
188943    int nAlloc = 4;
188944    int rc = SQLITE_OK;
188945    Fts5ExprTerm *p;
188946  
188947    assert( pTerm->pSynonym );
188948    for(p=pTerm; p; p=p->pSynonym){
188949      Fts5IndexIter *pIter = p->pIter;
188950      if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
188951        if( pIter->nData==0 ) continue;
188952        if( nIter==nAlloc ){
188953          int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
188954          Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
188955          if( aNew==0 ){
188956            rc = SQLITE_NOMEM;
188957            goto synonym_poslist_out;
188958          }
188959          memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
188960          nAlloc = nAlloc*2;
188961          if( aIter!=aStatic ) sqlite3_free(aIter);
188962          aIter = aNew;
188963        }
188964        sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
188965        assert( aIter[nIter].bEof==0 );
188966        nIter++;
188967      }
188968    }
188969  
188970    if( nIter==1 ){
188971      *pa = (u8*)aIter[0].a;
188972      *pn = aIter[0].n;
188973    }else{
188974      Fts5PoslistWriter writer = {0};
188975      i64 iPrev = -1;
188976      fts5BufferZero(pBuf);
188977      while( 1 ){
188978        int i;
188979        i64 iMin = FTS5_LARGEST_INT64;
188980        for(i=0; i<nIter; i++){
188981          if( aIter[i].bEof==0 ){
188982            if( aIter[i].iPos==iPrev ){
188983              if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
188984            }
188985            if( aIter[i].iPos<iMin ){
188986              iMin = aIter[i].iPos;
188987            }
188988          }
188989        }
188990        if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
188991        rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
188992        iPrev = iMin;
188993      }
188994      if( rc==SQLITE_OK ){
188995        *pa = pBuf->p;
188996        *pn = pBuf->n;
188997      }
188998    }
188999  
189000   synonym_poslist_out:
189001    if( aIter!=aStatic ) sqlite3_free(aIter);
189002    return rc;
189003  }
189004  
189005  
189006  /*
189007  ** All individual term iterators in pPhrase are guaranteed to be valid and
189008  ** pointing to the same rowid when this function is called. This function 
189009  ** checks if the current rowid really is a match, and if so populates
189010  ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
189011  ** is set to true if this is really a match, or false otherwise.
189012  **
189013  ** SQLITE_OK is returned if an error occurs, or an SQLite error code 
189014  ** otherwise. It is not considered an error code if the current rowid is 
189015  ** not a match.
189016  */
189017  static int fts5ExprPhraseIsMatch(
189018    Fts5ExprNode *pNode,            /* Node pPhrase belongs to */
189019    Fts5ExprPhrase *pPhrase,        /* Phrase object to initialize */
189020    int *pbMatch                    /* OUT: Set to true if really a match */
189021  ){
189022    Fts5PoslistWriter writer = {0};
189023    Fts5PoslistReader aStatic[4];
189024    Fts5PoslistReader *aIter = aStatic;
189025    int i;
189026    int rc = SQLITE_OK;
189027    
189028    fts5BufferZero(&pPhrase->poslist);
189029  
189030    /* If the aStatic[] array is not large enough, allocate a large array
189031    ** using sqlite3_malloc(). This approach could be improved upon. */
189032    if( pPhrase->nTerm>ArraySize(aStatic) ){
189033      int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
189034      aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
189035      if( !aIter ) return SQLITE_NOMEM;
189036    }
189037    memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
189038  
189039    /* Initialize a term iterator for each term in the phrase */
189040    for(i=0; i<pPhrase->nTerm; i++){
189041      Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
189042      int n = 0;
189043      int bFlag = 0;
189044      u8 *a = 0;
189045      if( pTerm->pSynonym ){
189046        Fts5Buffer buf = {0, 0, 0};
189047        rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
189048        if( rc ){
189049          sqlite3_free(a);
189050          goto ismatch_out;
189051        }
189052        if( a==buf.p ) bFlag = 1;
189053      }else{
189054        a = (u8*)pTerm->pIter->pData;
189055        n = pTerm->pIter->nData;
189056      }
189057      sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
189058      aIter[i].bFlag = (u8)bFlag;
189059      if( aIter[i].bEof ) goto ismatch_out;
189060    }
189061  
189062    while( 1 ){
189063      int bMatch;
189064      i64 iPos = aIter[0].iPos;
189065      do {
189066        bMatch = 1;
189067        for(i=0; i<pPhrase->nTerm; i++){
189068          Fts5PoslistReader *pPos = &aIter[i];
189069          i64 iAdj = iPos + i;
189070          if( pPos->iPos!=iAdj ){
189071            bMatch = 0;
189072            while( pPos->iPos<iAdj ){
189073              if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
189074            }
189075            if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
189076          }
189077        }
189078      }while( bMatch==0 );
189079  
189080      /* Append position iPos to the output */
189081      rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
189082      if( rc!=SQLITE_OK ) goto ismatch_out;
189083  
189084      for(i=0; i<pPhrase->nTerm; i++){
189085        if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
189086      }
189087    }
189088  
189089   ismatch_out:
189090    *pbMatch = (pPhrase->poslist.n>0);
189091    for(i=0; i<pPhrase->nTerm; i++){
189092      if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
189093    }
189094    if( aIter!=aStatic ) sqlite3_free(aIter);
189095    return rc;
189096  }
189097  
189098  typedef struct Fts5LookaheadReader Fts5LookaheadReader;
189099  struct Fts5LookaheadReader {
189100    const u8 *a;                    /* Buffer containing position list */
189101    int n;                          /* Size of buffer a[] in bytes */
189102    int i;                          /* Current offset in position list */
189103    i64 iPos;                       /* Current position */
189104    i64 iLookahead;                 /* Next position */
189105  };
189106  
189107  #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
189108  
189109  static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
189110    p->iPos = p->iLookahead;
189111    if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
189112      p->iLookahead = FTS5_LOOKAHEAD_EOF;
189113    }
189114    return (p->iPos==FTS5_LOOKAHEAD_EOF);
189115  }
189116  
189117  static int fts5LookaheadReaderInit(
189118    const u8 *a, int n,             /* Buffer to read position list from */
189119    Fts5LookaheadReader *p          /* Iterator object to initialize */
189120  ){
189121    memset(p, 0, sizeof(Fts5LookaheadReader));
189122    p->a = a;
189123    p->n = n;
189124    fts5LookaheadReaderNext(p);
189125    return fts5LookaheadReaderNext(p);
189126  }
189127  
189128  typedef struct Fts5NearTrimmer Fts5NearTrimmer;
189129  struct Fts5NearTrimmer {
189130    Fts5LookaheadReader reader;     /* Input iterator */
189131    Fts5PoslistWriter writer;       /* Writer context */
189132    Fts5Buffer *pOut;               /* Output poslist */
189133  };
189134  
189135  /*
189136  ** The near-set object passed as the first argument contains more than
189137  ** one phrase. All phrases currently point to the same row. The
189138  ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
189139  ** tests if the current row contains instances of each phrase sufficiently
189140  ** close together to meet the NEAR constraint. Non-zero is returned if it
189141  ** does, or zero otherwise.
189142  **
189143  ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
189144  ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
189145  ** occurs within this function (*pRc) is set accordingly before returning.
189146  ** The return value is undefined in both these cases.
189147  ** 
189148  ** If no error occurs and non-zero (a match) is returned, the position-list
189149  ** of each phrase object is edited to contain only those entries that
189150  ** meet the constraint before returning.
189151  */
189152  static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
189153    Fts5NearTrimmer aStatic[4];
189154    Fts5NearTrimmer *a = aStatic;
189155    Fts5ExprPhrase **apPhrase = pNear->apPhrase;
189156  
189157    int i;
189158    int rc = *pRc;
189159    int bMatch;
189160  
189161    assert( pNear->nPhrase>1 );
189162  
189163    /* If the aStatic[] array is not large enough, allocate a large array
189164    ** using sqlite3_malloc(). This approach could be improved upon. */
189165    if( pNear->nPhrase>ArraySize(aStatic) ){
189166      int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
189167      a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
189168    }else{
189169      memset(aStatic, 0, sizeof(aStatic));
189170    }
189171    if( rc!=SQLITE_OK ){
189172      *pRc = rc;
189173      return 0;
189174    }
189175  
189176    /* Initialize a lookahead iterator for each phrase. After passing the
189177    ** buffer and buffer size to the lookaside-reader init function, zero
189178    ** the phrase poslist buffer. The new poslist for the phrase (containing
189179    ** the same entries as the original with some entries removed on account 
189180    ** of the NEAR constraint) is written over the original even as it is
189181    ** being read. This is safe as the entries for the new poslist are a
189182    ** subset of the old, so it is not possible for data yet to be read to
189183    ** be overwritten.  */
189184    for(i=0; i<pNear->nPhrase; i++){
189185      Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
189186      fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
189187      pPoslist->n = 0;
189188      a[i].pOut = pPoslist;
189189    }
189190  
189191    while( 1 ){
189192      int iAdv;
189193      i64 iMin;
189194      i64 iMax;
189195  
189196      /* This block advances the phrase iterators until they point to a set of
189197      ** entries that together comprise a match.  */
189198      iMax = a[0].reader.iPos;
189199      do {
189200        bMatch = 1;
189201        for(i=0; i<pNear->nPhrase; i++){
189202          Fts5LookaheadReader *pPos = &a[i].reader;
189203          iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
189204          if( pPos->iPos<iMin || pPos->iPos>iMax ){
189205            bMatch = 0;
189206            while( pPos->iPos<iMin ){
189207              if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
189208            }
189209            if( pPos->iPos>iMax ) iMax = pPos->iPos;
189210          }
189211        }
189212      }while( bMatch==0 );
189213  
189214      /* Add an entry to each output position list */
189215      for(i=0; i<pNear->nPhrase; i++){
189216        i64 iPos = a[i].reader.iPos;
189217        Fts5PoslistWriter *pWriter = &a[i].writer;
189218        if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
189219          sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
189220        }
189221      }
189222  
189223      iAdv = 0;
189224      iMin = a[0].reader.iLookahead;
189225      for(i=0; i<pNear->nPhrase; i++){
189226        if( a[i].reader.iLookahead < iMin ){
189227          iMin = a[i].reader.iLookahead;
189228          iAdv = i;
189229        }
189230      }
189231      if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
189232    }
189233  
189234    ismatch_out: {
189235      int bRet = a[0].pOut->n>0;
189236      *pRc = rc;
189237      if( a!=aStatic ) sqlite3_free(a);
189238      return bRet;
189239    }
189240  }
189241  
189242  /*
189243  ** Advance iterator pIter until it points to a value equal to or laster
189244  ** than the initial value of *piLast. If this means the iterator points
189245  ** to a value laster than *piLast, update *piLast to the new lastest value.
189246  **
189247  ** If the iterator reaches EOF, set *pbEof to true before returning. If
189248  ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
189249  ** are set, return a non-zero value. Otherwise, return zero.
189250  */
189251  static int fts5ExprAdvanceto(
189252    Fts5IndexIter *pIter,           /* Iterator to advance */
189253    int bDesc,                      /* True if iterator is "rowid DESC" */
189254    i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
189255    int *pRc,                       /* OUT: Error code */
189256    int *pbEof                      /* OUT: Set to true if EOF */
189257  ){
189258    i64 iLast = *piLast;
189259    i64 iRowid;
189260  
189261    iRowid = pIter->iRowid;
189262    if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
189263      int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
189264      if( rc || sqlite3Fts5IterEof(pIter) ){
189265        *pRc = rc;
189266        *pbEof = 1;
189267        return 1;
189268      }
189269      iRowid = pIter->iRowid;
189270      assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
189271    }
189272    *piLast = iRowid;
189273  
189274    return 0;
189275  }
189276  
189277  static int fts5ExprSynonymAdvanceto(
189278    Fts5ExprTerm *pTerm,            /* Term iterator to advance */
189279    int bDesc,                      /* True if iterator is "rowid DESC" */
189280    i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
189281    int *pRc                        /* OUT: Error code */
189282  ){
189283    int rc = SQLITE_OK;
189284    i64 iLast = *piLast;
189285    Fts5ExprTerm *p;
189286    int bEof = 0;
189287  
189288    for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
189289      if( sqlite3Fts5IterEof(p->pIter)==0 ){
189290        i64 iRowid = p->pIter->iRowid;
189291        if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
189292          rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
189293        }
189294      }
189295    }
189296  
189297    if( rc!=SQLITE_OK ){
189298      *pRc = rc;
189299      bEof = 1;
189300    }else{
189301      *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
189302    }
189303    return bEof;
189304  }
189305  
189306  
189307  static int fts5ExprNearTest(
189308    int *pRc,
189309    Fts5Expr *pExpr,                /* Expression that pNear is a part of */
189310    Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_STRING) */
189311  ){
189312    Fts5ExprNearset *pNear = pNode->pNear;
189313    int rc = *pRc;
189314  
189315    if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
189316      Fts5ExprTerm *pTerm;
189317      Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
189318      pPhrase->poslist.n = 0;
189319      for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
189320        Fts5IndexIter *pIter = pTerm->pIter;
189321        if( sqlite3Fts5IterEof(pIter)==0 ){
189322          if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
189323            pPhrase->poslist.n = 1;
189324          }
189325        }
189326      }
189327      return pPhrase->poslist.n;
189328    }else{
189329      int i;
189330  
189331      /* Check that each phrase in the nearset matches the current row.
189332      ** Populate the pPhrase->poslist buffers at the same time. If any
189333      ** phrase is not a match, break out of the loop early.  */
189334      for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
189335        Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
189336        if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym || pNear->pColset ){
189337          int bMatch = 0;
189338          rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
189339          if( bMatch==0 ) break;
189340        }else{
189341          Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
189342          fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
189343        }
189344      }
189345  
189346      *pRc = rc;
189347      if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
189348        return 1;
189349      }
189350      return 0;
189351    }
189352  }
189353  
189354  
189355  /*
189356  ** Initialize all term iterators in the pNear object. If any term is found
189357  ** to match no documents at all, return immediately without initializing any
189358  ** further iterators.
189359  **
189360  ** If an error occurs, return an SQLite error code. Otherwise, return
189361  ** SQLITE_OK. It is not considered an error if some term matches zero
189362  ** documents.
189363  */
189364  static int fts5ExprNearInitAll(
189365    Fts5Expr *pExpr,
189366    Fts5ExprNode *pNode
189367  ){
189368    Fts5ExprNearset *pNear = pNode->pNear;
189369    int i;
189370  
189371    assert( pNode->bNomatch==0 );
189372    for(i=0; i<pNear->nPhrase; i++){
189373      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
189374      if( pPhrase->nTerm==0 ){
189375        pNode->bEof = 1;
189376        return SQLITE_OK;
189377      }else{
189378        int j;
189379        for(j=0; j<pPhrase->nTerm; j++){
189380          Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
189381          Fts5ExprTerm *p;
189382          int bHit = 0;
189383  
189384          for(p=pTerm; p; p=p->pSynonym){
189385            int rc;
189386            if( p->pIter ){
189387              sqlite3Fts5IterClose(p->pIter);
189388              p->pIter = 0;
189389            }
189390            rc = sqlite3Fts5IndexQuery(
189391                pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
189392                (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
189393                (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
189394                pNear->pColset,
189395                &p->pIter
189396            );
189397            assert( (rc==SQLITE_OK)==(p->pIter!=0) );
189398            if( rc!=SQLITE_OK ) return rc;
189399            if( 0==sqlite3Fts5IterEof(p->pIter) ){
189400              bHit = 1;
189401            }
189402          }
189403  
189404          if( bHit==0 ){
189405            pNode->bEof = 1;
189406            return SQLITE_OK;
189407          }
189408        }
189409      }
189410    }
189411  
189412    pNode->bEof = 0;
189413    return SQLITE_OK;
189414  }
189415  
189416  /*
189417  ** If pExpr is an ASC iterator, this function returns a value with the
189418  ** same sign as:
189419  **
189420  **   (iLhs - iRhs)
189421  **
189422  ** Otherwise, if this is a DESC iterator, the opposite is returned:
189423  **
189424  **   (iRhs - iLhs)
189425  */
189426  static int fts5RowidCmp(
189427    Fts5Expr *pExpr,
189428    i64 iLhs,
189429    i64 iRhs
189430  ){
189431    assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
189432    if( pExpr->bDesc==0 ){
189433      if( iLhs<iRhs ) return -1;
189434      return (iLhs > iRhs);
189435    }else{
189436      if( iLhs>iRhs ) return -1;
189437      return (iLhs < iRhs);
189438    }
189439  }
189440  
189441  static void fts5ExprSetEof(Fts5ExprNode *pNode){
189442    int i;
189443    pNode->bEof = 1;
189444    pNode->bNomatch = 0;
189445    for(i=0; i<pNode->nChild; i++){
189446      fts5ExprSetEof(pNode->apChild[i]);
189447    }
189448  }
189449  
189450  static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
189451    if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
189452      Fts5ExprNearset *pNear = pNode->pNear;
189453      int i;
189454      for(i=0; i<pNear->nPhrase; i++){
189455        Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
189456        pPhrase->poslist.n = 0;
189457      }
189458    }else{
189459      int i;
189460      for(i=0; i<pNode->nChild; i++){
189461        fts5ExprNodeZeroPoslist(pNode->apChild[i]);
189462      }
189463    }
189464  }
189465  
189466  
189467  
189468  /*
189469  ** Compare the values currently indicated by the two nodes as follows:
189470  **
189471  **    res = (*p1) - (*p2)
189472  **
189473  ** Nodes that point to values that come later in the iteration order are
189474  ** considered to be larger. Nodes at EOF are the largest of all.
189475  **
189476  ** This means that if the iteration order is ASC, then numerically larger
189477  ** rowids are considered larger. Or if it is the default DESC, numerically
189478  ** smaller rowids are larger.
189479  */
189480  static int fts5NodeCompare(
189481    Fts5Expr *pExpr,
189482    Fts5ExprNode *p1, 
189483    Fts5ExprNode *p2
189484  ){
189485    if( p2->bEof ) return -1;
189486    if( p1->bEof ) return +1;
189487    return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
189488  }
189489  
189490  /*
189491  ** All individual term iterators in pNear are guaranteed to be valid when
189492  ** this function is called. This function checks if all term iterators
189493  ** point to the same rowid, and if not, advances them until they do.
189494  ** If an EOF is reached before this happens, *pbEof is set to true before
189495  ** returning.
189496  **
189497  ** SQLITE_OK is returned if an error occurs, or an SQLite error code 
189498  ** otherwise. It is not considered an error code if an iterator reaches
189499  ** EOF.
189500  */
189501  static int fts5ExprNodeTest_STRING(
189502    Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
189503    Fts5ExprNode *pNode
189504  ){
189505    Fts5ExprNearset *pNear = pNode->pNear;
189506    Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
189507    int rc = SQLITE_OK;
189508    i64 iLast;                      /* Lastest rowid any iterator points to */
189509    int i, j;                       /* Phrase and token index, respectively */
189510    int bMatch;                     /* True if all terms are at the same rowid */
189511    const int bDesc = pExpr->bDesc;
189512  
189513    /* Check that this node should not be FTS5_TERM */
189514    assert( pNear->nPhrase>1 
189515         || pNear->apPhrase[0]->nTerm>1 
189516         || pNear->apPhrase[0]->aTerm[0].pSynonym
189517    );
189518  
189519    /* Initialize iLast, the "lastest" rowid any iterator points to. If the
189520    ** iterator skips through rowids in the default ascending order, this means
189521    ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
189522    ** means the minimum rowid.  */
189523    if( pLeft->aTerm[0].pSynonym ){
189524      iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
189525    }else{
189526      iLast = pLeft->aTerm[0].pIter->iRowid;
189527    }
189528  
189529    do {
189530      bMatch = 1;
189531      for(i=0; i<pNear->nPhrase; i++){
189532        Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
189533        for(j=0; j<pPhrase->nTerm; j++){
189534          Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
189535          if( pTerm->pSynonym ){
189536            i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
189537            if( iRowid==iLast ) continue;
189538            bMatch = 0;
189539            if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
189540              pNode->bNomatch = 0;
189541              pNode->bEof = 1;
189542              return rc;
189543            }
189544          }else{
189545            Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
189546            if( pIter->iRowid==iLast || pIter->bEof ) continue;
189547            bMatch = 0;
189548            if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
189549              return rc;
189550            }
189551          }
189552        }
189553      }
189554    }while( bMatch==0 );
189555  
189556    pNode->iRowid = iLast;
189557    pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
189558    assert( pNode->bEof==0 || pNode->bNomatch==0 );
189559  
189560    return rc;
189561  }
189562  
189563  /*
189564  ** Advance the first term iterator in the first phrase of pNear. Set output
189565  ** variable *pbEof to true if it reaches EOF or if an error occurs.
189566  **
189567  ** Return SQLITE_OK if successful, or an SQLite error code if an error
189568  ** occurs.
189569  */
189570  static int fts5ExprNodeNext_STRING(
189571    Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
189572    Fts5ExprNode *pNode,            /* FTS5_STRING or FTS5_TERM node */
189573    int bFromValid,
189574    i64 iFrom 
189575  ){
189576    Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
189577    int rc = SQLITE_OK;
189578  
189579    pNode->bNomatch = 0;
189580    if( pTerm->pSynonym ){
189581      int bEof = 1;
189582      Fts5ExprTerm *p;
189583  
189584      /* Find the firstest rowid any synonym points to. */
189585      i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
189586  
189587      /* Advance each iterator that currently points to iRowid. Or, if iFrom
189588      ** is valid - each iterator that points to a rowid before iFrom.  */
189589      for(p=pTerm; p; p=p->pSynonym){
189590        if( sqlite3Fts5IterEof(p->pIter)==0 ){
189591          i64 ii = p->pIter->iRowid;
189592          if( ii==iRowid 
189593           || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc) 
189594          ){
189595            if( bFromValid ){
189596              rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
189597            }else{
189598              rc = sqlite3Fts5IterNext(p->pIter);
189599            }
189600            if( rc!=SQLITE_OK ) break;
189601            if( sqlite3Fts5IterEof(p->pIter)==0 ){
189602              bEof = 0;
189603            }
189604          }else{
189605            bEof = 0;
189606          }
189607        }
189608      }
189609  
189610      /* Set the EOF flag if either all synonym iterators are at EOF or an
189611      ** error has occurred.  */
189612      pNode->bEof = (rc || bEof);
189613    }else{
189614      Fts5IndexIter *pIter = pTerm->pIter;
189615  
189616      assert( Fts5NodeIsString(pNode) );
189617      if( bFromValid ){
189618        rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
189619      }else{
189620        rc = sqlite3Fts5IterNext(pIter);
189621      }
189622  
189623      pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
189624    }
189625  
189626    if( pNode->bEof==0 ){
189627      assert( rc==SQLITE_OK );
189628      rc = fts5ExprNodeTest_STRING(pExpr, pNode);
189629    }
189630  
189631    return rc;
189632  }
189633  
189634  
189635  static int fts5ExprNodeTest_TERM(
189636    Fts5Expr *pExpr,                /* Expression that pNear is a part of */
189637    Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_TERM) */
189638  ){
189639    /* As this "NEAR" object is actually a single phrase that consists 
189640    ** of a single term only, grab pointers into the poslist managed by the
189641    ** fts5_index.c iterator object. This is much faster than synthesizing 
189642    ** a new poslist the way we have to for more complicated phrase or NEAR
189643    ** expressions.  */
189644    Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
189645    Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
189646  
189647    assert( pNode->eType==FTS5_TERM );
189648    assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
189649    assert( pPhrase->aTerm[0].pSynonym==0 );
189650  
189651    pPhrase->poslist.n = pIter->nData;
189652    if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
189653      pPhrase->poslist.p = (u8*)pIter->pData;
189654    }
189655    pNode->iRowid = pIter->iRowid;
189656    pNode->bNomatch = (pPhrase->poslist.n==0);
189657    return SQLITE_OK;
189658  }
189659  
189660  /*
189661  ** xNext() method for a node of type FTS5_TERM.
189662  */
189663  static int fts5ExprNodeNext_TERM(
189664    Fts5Expr *pExpr, 
189665    Fts5ExprNode *pNode,
189666    int bFromValid,
189667    i64 iFrom
189668  ){
189669    int rc;
189670    Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
189671  
189672    assert( pNode->bEof==0 );
189673    if( bFromValid ){
189674      rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
189675    }else{
189676      rc = sqlite3Fts5IterNext(pIter);
189677    }
189678    if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
189679      rc = fts5ExprNodeTest_TERM(pExpr, pNode);
189680    }else{
189681      pNode->bEof = 1;
189682      pNode->bNomatch = 0;
189683    }
189684    return rc;
189685  }
189686  
189687  static void fts5ExprNodeTest_OR(
189688    Fts5Expr *pExpr,                /* Expression of which pNode is a part */
189689    Fts5ExprNode *pNode             /* Expression node to test */
189690  ){
189691    Fts5ExprNode *pNext = pNode->apChild[0];
189692    int i;
189693  
189694    for(i=1; i<pNode->nChild; i++){
189695      Fts5ExprNode *pChild = pNode->apChild[i];
189696      int cmp = fts5NodeCompare(pExpr, pNext, pChild);
189697      if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
189698        pNext = pChild;
189699      }
189700    }
189701    pNode->iRowid = pNext->iRowid;
189702    pNode->bEof = pNext->bEof;
189703    pNode->bNomatch = pNext->bNomatch;
189704  }
189705  
189706  static int fts5ExprNodeNext_OR(
189707    Fts5Expr *pExpr, 
189708    Fts5ExprNode *pNode,
189709    int bFromValid,
189710    i64 iFrom
189711  ){
189712    int i;
189713    i64 iLast = pNode->iRowid;
189714  
189715    for(i=0; i<pNode->nChild; i++){
189716      Fts5ExprNode *p1 = pNode->apChild[i];
189717      assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
189718      if( p1->bEof==0 ){
189719        if( (p1->iRowid==iLast) 
189720         || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
189721        ){
189722          int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
189723          if( rc!=SQLITE_OK ){
189724            pNode->bNomatch = 0;
189725            return rc;
189726          }
189727        }
189728      }
189729    }
189730  
189731    fts5ExprNodeTest_OR(pExpr, pNode);
189732    return SQLITE_OK;
189733  }
189734  
189735  /*
189736  ** Argument pNode is an FTS5_AND node.
189737  */
189738  static int fts5ExprNodeTest_AND(
189739    Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
189740    Fts5ExprNode *pAnd              /* FTS5_AND node to advance */
189741  ){
189742    int iChild;
189743    i64 iLast = pAnd->iRowid;
189744    int rc = SQLITE_OK;
189745    int bMatch;
189746  
189747    assert( pAnd->bEof==0 );
189748    do {
189749      pAnd->bNomatch = 0;
189750      bMatch = 1;
189751      for(iChild=0; iChild<pAnd->nChild; iChild++){
189752        Fts5ExprNode *pChild = pAnd->apChild[iChild];
189753        int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
189754        if( cmp>0 ){
189755          /* Advance pChild until it points to iLast or laster */
189756          rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
189757          if( rc!=SQLITE_OK ){
189758            pAnd->bNomatch = 0;
189759            return rc;
189760          }
189761        }
189762  
189763        /* If the child node is now at EOF, so is the parent AND node. Otherwise,
189764        ** the child node is guaranteed to have advanced at least as far as
189765        ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
189766        ** new lastest rowid seen so far.  */
189767        assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
189768        if( pChild->bEof ){
189769          fts5ExprSetEof(pAnd);
189770          bMatch = 1;
189771          break;
189772        }else if( iLast!=pChild->iRowid ){
189773          bMatch = 0;
189774          iLast = pChild->iRowid;
189775        }
189776  
189777        if( pChild->bNomatch ){
189778          pAnd->bNomatch = 1;
189779        }
189780      }
189781    }while( bMatch==0 );
189782  
189783    if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
189784      fts5ExprNodeZeroPoslist(pAnd);
189785    }
189786    pAnd->iRowid = iLast;
189787    return SQLITE_OK;
189788  }
189789  
189790  static int fts5ExprNodeNext_AND(
189791    Fts5Expr *pExpr, 
189792    Fts5ExprNode *pNode,
189793    int bFromValid,
189794    i64 iFrom
189795  ){
189796    int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
189797    if( rc==SQLITE_OK ){
189798      rc = fts5ExprNodeTest_AND(pExpr, pNode);
189799    }else{
189800      pNode->bNomatch = 0;
189801    }
189802    return rc;
189803  }
189804  
189805  static int fts5ExprNodeTest_NOT(
189806    Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
189807    Fts5ExprNode *pNode             /* FTS5_NOT node to advance */
189808  ){
189809    int rc = SQLITE_OK;
189810    Fts5ExprNode *p1 = pNode->apChild[0];
189811    Fts5ExprNode *p2 = pNode->apChild[1];
189812    assert( pNode->nChild==2 );
189813  
189814    while( rc==SQLITE_OK && p1->bEof==0 ){
189815      int cmp = fts5NodeCompare(pExpr, p1, p2);
189816      if( cmp>0 ){
189817        rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
189818        cmp = fts5NodeCompare(pExpr, p1, p2);
189819      }
189820      assert( rc!=SQLITE_OK || cmp<=0 );
189821      if( cmp || p2->bNomatch ) break;
189822      rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
189823    }
189824    pNode->bEof = p1->bEof;
189825    pNode->bNomatch = p1->bNomatch;
189826    pNode->iRowid = p1->iRowid;
189827    if( p1->bEof ){
189828      fts5ExprNodeZeroPoslist(p2);
189829    }
189830    return rc;
189831  }
189832  
189833  static int fts5ExprNodeNext_NOT(
189834    Fts5Expr *pExpr, 
189835    Fts5ExprNode *pNode,
189836    int bFromValid,
189837    i64 iFrom
189838  ){
189839    int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
189840    if( rc==SQLITE_OK ){
189841      rc = fts5ExprNodeTest_NOT(pExpr, pNode);
189842    }
189843    if( rc!=SQLITE_OK ){
189844      pNode->bNomatch = 0;
189845    }
189846    return rc;
189847  }
189848  
189849  /*
189850  ** If pNode currently points to a match, this function returns SQLITE_OK
189851  ** without modifying it. Otherwise, pNode is advanced until it does point
189852  ** to a match or EOF is reached.
189853  */
189854  static int fts5ExprNodeTest(
189855    Fts5Expr *pExpr,                /* Expression of which pNode is a part */
189856    Fts5ExprNode *pNode             /* Expression node to test */
189857  ){
189858    int rc = SQLITE_OK;
189859    if( pNode->bEof==0 ){
189860      switch( pNode->eType ){
189861  
189862        case FTS5_STRING: {
189863          rc = fts5ExprNodeTest_STRING(pExpr, pNode);
189864          break;
189865        }
189866  
189867        case FTS5_TERM: {
189868          rc = fts5ExprNodeTest_TERM(pExpr, pNode);
189869          break;
189870        }
189871  
189872        case FTS5_AND: {
189873          rc = fts5ExprNodeTest_AND(pExpr, pNode);
189874          break;
189875        }
189876  
189877        case FTS5_OR: {
189878          fts5ExprNodeTest_OR(pExpr, pNode);
189879          break;
189880        }
189881  
189882        default: assert( pNode->eType==FTS5_NOT ); {
189883          rc = fts5ExprNodeTest_NOT(pExpr, pNode);
189884          break;
189885        }
189886      }
189887    }
189888    return rc;
189889  }
189890  
189891   
189892  /*
189893  ** Set node pNode, which is part of expression pExpr, to point to the first
189894  ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
189895  **
189896  ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
189897  ** It is not an error if there are no matches.
189898  */
189899  static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
189900    int rc = SQLITE_OK;
189901    pNode->bEof = 0;
189902    pNode->bNomatch = 0;
189903  
189904    if( Fts5NodeIsString(pNode) ){
189905      /* Initialize all term iterators in the NEAR object. */
189906      rc = fts5ExprNearInitAll(pExpr, pNode);
189907    }else if( pNode->xNext==0 ){
189908      pNode->bEof = 1;
189909    }else{
189910      int i;
189911      int nEof = 0;
189912      for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
189913        Fts5ExprNode *pChild = pNode->apChild[i];
189914        rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
189915        assert( pChild->bEof==0 || pChild->bEof==1 );
189916        nEof += pChild->bEof;
189917      }
189918      pNode->iRowid = pNode->apChild[0]->iRowid;
189919  
189920      switch( pNode->eType ){
189921        case FTS5_AND:
189922          if( nEof>0 ) fts5ExprSetEof(pNode);
189923          break;
189924  
189925        case FTS5_OR:
189926          if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
189927          break;
189928  
189929        default:
189930          assert( pNode->eType==FTS5_NOT );
189931          pNode->bEof = pNode->apChild[0]->bEof;
189932          break;
189933      }
189934    }
189935  
189936    if( rc==SQLITE_OK ){
189937      rc = fts5ExprNodeTest(pExpr, pNode);
189938    }
189939    return rc;
189940  }
189941  
189942  
189943  /*
189944  ** Begin iterating through the set of documents in index pIdx matched by
189945  ** the MATCH expression passed as the first argument. If the "bDesc" 
189946  ** parameter is passed a non-zero value, iteration is in descending rowid 
189947  ** order. Or, if it is zero, in ascending order.
189948  **
189949  ** If iterating in ascending rowid order (bDesc==0), the first document
189950  ** visited is that with the smallest rowid that is larger than or equal
189951  ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
189952  ** then the first document visited must have a rowid smaller than or
189953  ** equal to iFirst.
189954  **
189955  ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
189956  ** is not considered an error if the query does not match any documents.
189957  */
189958  static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
189959    Fts5ExprNode *pRoot = p->pRoot;
189960    int rc;                         /* Return code */
189961  
189962    p->pIndex = pIdx;
189963    p->bDesc = bDesc;
189964    rc = fts5ExprNodeFirst(p, pRoot);
189965  
189966    /* If not at EOF but the current rowid occurs earlier than iFirst in
189967    ** the iteration order, move to document iFirst or later. */
189968    if( rc==SQLITE_OK 
189969     && 0==pRoot->bEof 
189970     && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0 
189971    ){
189972      rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
189973    }
189974  
189975    /* If the iterator is not at a real match, skip forward until it is. */
189976    while( pRoot->bNomatch ){
189977      assert( pRoot->bEof==0 && rc==SQLITE_OK );
189978      rc = fts5ExprNodeNext(p, pRoot, 0, 0);
189979    }
189980    return rc;
189981  }
189982  
189983  /*
189984  ** Move to the next document 
189985  **
189986  ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
189987  ** is not considered an error if the query does not match any documents.
189988  */
189989  static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
189990    int rc;
189991    Fts5ExprNode *pRoot = p->pRoot;
189992    assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
189993    do {
189994      rc = fts5ExprNodeNext(p, pRoot, 0, 0);
189995      assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
189996    }while( pRoot->bNomatch );
189997    if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
189998      pRoot->bEof = 1;
189999    }
190000    return rc;
190001  }
190002  
190003  static int sqlite3Fts5ExprEof(Fts5Expr *p){
190004    return p->pRoot->bEof;
190005  }
190006  
190007  static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
190008    return p->pRoot->iRowid;
190009  }
190010  
190011  static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
190012    int rc = SQLITE_OK;
190013    *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
190014    return rc;
190015  }
190016  
190017  /*
190018  ** Free the phrase object passed as the only argument.
190019  */
190020  static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
190021    if( pPhrase ){
190022      int i;
190023      for(i=0; i<pPhrase->nTerm; i++){
190024        Fts5ExprTerm *pSyn;
190025        Fts5ExprTerm *pNext;
190026        Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
190027        sqlite3_free(pTerm->zTerm);
190028        sqlite3Fts5IterClose(pTerm->pIter);
190029        for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
190030          pNext = pSyn->pSynonym;
190031          sqlite3Fts5IterClose(pSyn->pIter);
190032          fts5BufferFree((Fts5Buffer*)&pSyn[1]);
190033          sqlite3_free(pSyn);
190034        }
190035      }
190036      if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
190037      sqlite3_free(pPhrase);
190038    }
190039  }
190040  
190041  /*
190042  ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
190043  ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
190044  ** appended to it and the results returned.
190045  **
190046  ** If an OOM error occurs, both the pNear and pPhrase objects are freed and
190047  ** NULL returned.
190048  */
190049  static Fts5ExprNearset *sqlite3Fts5ParseNearset(
190050    Fts5Parse *pParse,              /* Parse context */
190051    Fts5ExprNearset *pNear,         /* Existing nearset, or NULL */
190052    Fts5ExprPhrase *pPhrase         /* Recently parsed phrase */
190053  ){
190054    const int SZALLOC = 8;
190055    Fts5ExprNearset *pRet = 0;
190056  
190057    if( pParse->rc==SQLITE_OK ){
190058      if( pPhrase==0 ){
190059        return pNear;
190060      }
190061      if( pNear==0 ){
190062        int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
190063        pRet = sqlite3_malloc(nByte);
190064        if( pRet==0 ){
190065          pParse->rc = SQLITE_NOMEM;
190066        }else{
190067          memset(pRet, 0, nByte);
190068        }
190069      }else if( (pNear->nPhrase % SZALLOC)==0 ){
190070        int nNew = pNear->nPhrase + SZALLOC;
190071        int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
190072  
190073        pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
190074        if( pRet==0 ){
190075          pParse->rc = SQLITE_NOMEM;
190076        }
190077      }else{
190078        pRet = pNear;
190079      }
190080    }
190081  
190082    if( pRet==0 ){
190083      assert( pParse->rc!=SQLITE_OK );
190084      sqlite3Fts5ParseNearsetFree(pNear);
190085      sqlite3Fts5ParsePhraseFree(pPhrase);
190086    }else{
190087      if( pRet->nPhrase>0 ){
190088        Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
190089        assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
190090        if( pPhrase->nTerm==0 ){
190091          fts5ExprPhraseFree(pPhrase);
190092          pRet->nPhrase--;
190093          pParse->nPhrase--;
190094          pPhrase = pLast;
190095        }else if( pLast->nTerm==0 ){
190096          fts5ExprPhraseFree(pLast);
190097          pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
190098          pParse->nPhrase--;
190099          pRet->nPhrase--;
190100        }
190101      }
190102      pRet->apPhrase[pRet->nPhrase++] = pPhrase;
190103    }
190104    return pRet;
190105  }
190106  
190107  typedef struct TokenCtx TokenCtx;
190108  struct TokenCtx {
190109    Fts5ExprPhrase *pPhrase;
190110    int rc;
190111  };
190112  
190113  /*
190114  ** Callback for tokenizing terms used by ParseTerm().
190115  */
190116  static int fts5ParseTokenize(
190117    void *pContext,                 /* Pointer to Fts5InsertCtx object */
190118    int tflags,                     /* Mask of FTS5_TOKEN_* flags */
190119    const char *pToken,             /* Buffer containing token */
190120    int nToken,                     /* Size of token in bytes */
190121    int iUnused1,                   /* Start offset of token */
190122    int iUnused2                    /* End offset of token */
190123  ){
190124    int rc = SQLITE_OK;
190125    const int SZALLOC = 8;
190126    TokenCtx *pCtx = (TokenCtx*)pContext;
190127    Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
190128  
190129    UNUSED_PARAM2(iUnused1, iUnused2);
190130  
190131    /* If an error has already occurred, this is a no-op */
190132    if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
190133    if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
190134  
190135    if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
190136      Fts5ExprTerm *pSyn;
190137      int nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
190138      pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
190139      if( pSyn==0 ){
190140        rc = SQLITE_NOMEM;
190141      }else{
190142        memset(pSyn, 0, nByte);
190143        pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
190144        memcpy(pSyn->zTerm, pToken, nToken);
190145        pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
190146        pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
190147      }
190148    }else{
190149      Fts5ExprTerm *pTerm;
190150      if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
190151        Fts5ExprPhrase *pNew;
190152        int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
190153  
190154        pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase, 
190155            sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
190156        );
190157        if( pNew==0 ){
190158          rc = SQLITE_NOMEM;
190159        }else{
190160          if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
190161          pCtx->pPhrase = pPhrase = pNew;
190162          pNew->nTerm = nNew - SZALLOC;
190163        }
190164      }
190165  
190166      if( rc==SQLITE_OK ){
190167        pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
190168        memset(pTerm, 0, sizeof(Fts5ExprTerm));
190169        pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
190170      }
190171    }
190172  
190173    pCtx->rc = rc;
190174    return rc;
190175  }
190176  
190177  
190178  /*
190179  ** Free the phrase object passed as the only argument.
190180  */
190181  static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
190182    fts5ExprPhraseFree(pPhrase);
190183  }
190184  
190185  /*
190186  ** Free the phrase object passed as the second argument.
190187  */
190188  static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
190189    if( pNear ){
190190      int i;
190191      for(i=0; i<pNear->nPhrase; i++){
190192        fts5ExprPhraseFree(pNear->apPhrase[i]);
190193      }
190194      sqlite3_free(pNear->pColset);
190195      sqlite3_free(pNear);
190196    }
190197  }
190198  
190199  static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
190200    assert( pParse->pExpr==0 );
190201    pParse->pExpr = p;
190202  }
190203  
190204  /*
190205  ** This function is called by the parser to process a string token. The
190206  ** string may or may not be quoted. In any case it is tokenized and a
190207  ** phrase object consisting of all tokens returned.
190208  */
190209  static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
190210    Fts5Parse *pParse,              /* Parse context */
190211    Fts5ExprPhrase *pAppend,        /* Phrase to append to */
190212    Fts5Token *pToken,              /* String to tokenize */
190213    int bPrefix                     /* True if there is a trailing "*" */
190214  ){
190215    Fts5Config *pConfig = pParse->pConfig;
190216    TokenCtx sCtx;                  /* Context object passed to callback */
190217    int rc;                         /* Tokenize return code */
190218    char *z = 0;
190219  
190220    memset(&sCtx, 0, sizeof(TokenCtx));
190221    sCtx.pPhrase = pAppend;
190222  
190223    rc = fts5ParseStringFromToken(pToken, &z);
190224    if( rc==SQLITE_OK ){
190225      int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_PREFIX : 0);
190226      int n;
190227      sqlite3Fts5Dequote(z);
190228      n = (int)strlen(z);
190229      rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
190230    }
190231    sqlite3_free(z);
190232    if( rc || (rc = sCtx.rc) ){
190233      pParse->rc = rc;
190234      fts5ExprPhraseFree(sCtx.pPhrase);
190235      sCtx.pPhrase = 0;
190236    }else{
190237  
190238      if( pAppend==0 ){
190239        if( (pParse->nPhrase % 8)==0 ){
190240          int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
190241          Fts5ExprPhrase **apNew;
190242          apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
190243          if( apNew==0 ){
190244            pParse->rc = SQLITE_NOMEM;
190245            fts5ExprPhraseFree(sCtx.pPhrase);
190246            return 0;
190247          }
190248          pParse->apPhrase = apNew;
190249        }
190250        pParse->nPhrase++;
190251      }
190252  
190253      if( sCtx.pPhrase==0 ){
190254        /* This happens when parsing a token or quoted phrase that contains
190255        ** no token characters at all. (e.g ... MATCH '""'). */
190256        sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
190257      }else if( sCtx.pPhrase->nTerm ){
190258        sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = bPrefix;
190259      }
190260      pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
190261    }
190262  
190263    return sCtx.pPhrase;
190264  }
190265  
190266  /*
190267  ** Create a new FTS5 expression by cloning phrase iPhrase of the
190268  ** expression passed as the second argument.
190269  */
190270  static int sqlite3Fts5ExprClonePhrase(
190271    Fts5Expr *pExpr, 
190272    int iPhrase, 
190273    Fts5Expr **ppNew
190274  ){
190275    int rc = SQLITE_OK;             /* Return code */
190276    Fts5ExprPhrase *pOrig;          /* The phrase extracted from pExpr */
190277    Fts5Expr *pNew = 0;             /* Expression to return via *ppNew */
190278    TokenCtx sCtx = {0,0};          /* Context object for fts5ParseTokenize */
190279  
190280    pOrig = pExpr->apExprPhrase[iPhrase];
190281    pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
190282    if( rc==SQLITE_OK ){
190283      pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc, 
190284          sizeof(Fts5ExprPhrase*));
190285    }
190286    if( rc==SQLITE_OK ){
190287      pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc, 
190288          sizeof(Fts5ExprNode));
190289    }
190290    if( rc==SQLITE_OK ){
190291      pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc, 
190292          sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
190293    }
190294    if( rc==SQLITE_OK ){
190295      Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
190296      if( pColsetOrig ){
190297        int nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
190298        Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
190299        if( pColset ){ 
190300          memcpy(pColset, pColsetOrig, nByte);
190301        }
190302        pNew->pRoot->pNear->pColset = pColset;
190303      }
190304    }
190305  
190306    if( pOrig->nTerm ){
190307      int i;                          /* Used to iterate through phrase terms */
190308      for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
190309        int tflags = 0;
190310        Fts5ExprTerm *p;
190311        for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
190312          const char *zTerm = p->zTerm;
190313          rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
190314              0, 0);
190315          tflags = FTS5_TOKEN_COLOCATED;
190316        }
190317        if( rc==SQLITE_OK ){
190318          sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
190319        }
190320      }
190321    }else{
190322      /* This happens when parsing a token or quoted phrase that contains
190323      ** no token characters at all. (e.g ... MATCH '""'). */
190324      sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));
190325    }
190326  
190327    if( rc==SQLITE_OK ){
190328      /* All the allocations succeeded. Put the expression object together. */
190329      pNew->pIndex = pExpr->pIndex;
190330      pNew->pConfig = pExpr->pConfig;
190331      pNew->nPhrase = 1;
190332      pNew->apExprPhrase[0] = sCtx.pPhrase;
190333      pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
190334      pNew->pRoot->pNear->nPhrase = 1;
190335      sCtx.pPhrase->pNode = pNew->pRoot;
190336  
190337      if( pOrig->nTerm==1 && pOrig->aTerm[0].pSynonym==0 ){
190338        pNew->pRoot->eType = FTS5_TERM;
190339        pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
190340      }else{
190341        pNew->pRoot->eType = FTS5_STRING;
190342        pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
190343      }
190344    }else{
190345      sqlite3Fts5ExprFree(pNew);
190346      fts5ExprPhraseFree(sCtx.pPhrase);
190347      pNew = 0;
190348    }
190349  
190350    *ppNew = pNew;
190351    return rc;
190352  }
190353  
190354  
190355  /*
190356  ** Token pTok has appeared in a MATCH expression where the NEAR operator
190357  ** is expected. If token pTok does not contain "NEAR", store an error
190358  ** in the pParse object.
190359  */
190360  static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
190361    if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
190362      sqlite3Fts5ParseError(
190363          pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
190364      );
190365    }
190366  }
190367  
190368  static void sqlite3Fts5ParseSetDistance(
190369    Fts5Parse *pParse, 
190370    Fts5ExprNearset *pNear,
190371    Fts5Token *p
190372  ){
190373    if( pNear ){
190374      int nNear = 0;
190375      int i;
190376      if( p->n ){
190377        for(i=0; i<p->n; i++){
190378          char c = (char)p->p[i];
190379          if( c<'0' || c>'9' ){
190380            sqlite3Fts5ParseError(
190381                pParse, "expected integer, got \"%.*s\"", p->n, p->p
190382                );
190383            return;
190384          }
190385          nNear = nNear * 10 + (p->p[i] - '0');
190386        }
190387      }else{
190388        nNear = FTS5_DEFAULT_NEARDIST;
190389      }
190390      pNear->nNear = nNear;
190391    }
190392  }
190393  
190394  /*
190395  ** The second argument passed to this function may be NULL, or it may be
190396  ** an existing Fts5Colset object. This function returns a pointer to
190397  ** a new colset object containing the contents of (p) with new value column
190398  ** number iCol appended. 
190399  **
190400  ** If an OOM error occurs, store an error code in pParse and return NULL.
190401  ** The old colset object (if any) is not freed in this case.
190402  */
190403  static Fts5Colset *fts5ParseColset(
190404    Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
190405    Fts5Colset *p,                  /* Existing colset object */
190406    int iCol                        /* New column to add to colset object */
190407  ){
190408    int nCol = p ? p->nCol : 0;     /* Num. columns already in colset object */
190409    Fts5Colset *pNew;               /* New colset object to return */
190410  
190411    assert( pParse->rc==SQLITE_OK );
190412    assert( iCol>=0 && iCol<pParse->pConfig->nCol );
190413  
190414    pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
190415    if( pNew==0 ){
190416      pParse->rc = SQLITE_NOMEM;
190417    }else{
190418      int *aiCol = pNew->aiCol;
190419      int i, j;
190420      for(i=0; i<nCol; i++){
190421        if( aiCol[i]==iCol ) return pNew;
190422        if( aiCol[i]>iCol ) break;
190423      }
190424      for(j=nCol; j>i; j--){
190425        aiCol[j] = aiCol[j-1];
190426      }
190427      aiCol[i] = iCol;
190428      pNew->nCol = nCol+1;
190429  
190430  #ifndef NDEBUG
190431      /* Check that the array is in order and contains no duplicate entries. */
190432      for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
190433  #endif
190434    }
190435  
190436    return pNew;
190437  }
190438  
190439  /*
190440  ** Allocate and return an Fts5Colset object specifying the inverse of
190441  ** the colset passed as the second argument. Free the colset passed
190442  ** as the second argument before returning.
190443  */
190444  static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){
190445    Fts5Colset *pRet;
190446    int nCol = pParse->pConfig->nCol;
190447  
190448    pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc, 
190449        sizeof(Fts5Colset) + sizeof(int)*nCol
190450    );
190451    if( pRet ){
190452      int i;
190453      int iOld = 0;
190454      for(i=0; i<nCol; i++){
190455        if( iOld>=p->nCol || p->aiCol[iOld]!=i ){
190456          pRet->aiCol[pRet->nCol++] = i;
190457        }else{
190458          iOld++;
190459        }
190460      }
190461    }
190462  
190463    sqlite3_free(p);
190464    return pRet;
190465  }
190466  
190467  static Fts5Colset *sqlite3Fts5ParseColset(
190468    Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
190469    Fts5Colset *pColset,            /* Existing colset object */
190470    Fts5Token *p
190471  ){
190472    Fts5Colset *pRet = 0;
190473    int iCol;
190474    char *z;                        /* Dequoted copy of token p */
190475  
190476    z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
190477    if( pParse->rc==SQLITE_OK ){
190478      Fts5Config *pConfig = pParse->pConfig;
190479      sqlite3Fts5Dequote(z);
190480      for(iCol=0; iCol<pConfig->nCol; iCol++){
190481        if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
190482      }
190483      if( iCol==pConfig->nCol ){
190484        sqlite3Fts5ParseError(pParse, "no such column: %s", z);
190485      }else{
190486        pRet = fts5ParseColset(pParse, pColset, iCol);
190487      }
190488      sqlite3_free(z);
190489    }
190490  
190491    if( pRet==0 ){
190492      assert( pParse->rc!=SQLITE_OK );
190493      sqlite3_free(pColset);
190494    }
190495  
190496    return pRet;
190497  }
190498  
190499  /*
190500  ** If argument pOrig is NULL, or if (*pRc) is set to anything other than
190501  ** SQLITE_OK when this function is called, NULL is returned. 
190502  **
190503  ** Otherwise, a copy of (*pOrig) is made into memory obtained from
190504  ** sqlite3Fts5MallocZero() and a pointer to it returned. If the allocation
190505  ** fails, (*pRc) is set to SQLITE_NOMEM and NULL is returned.
190506  */
190507  static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){
190508    Fts5Colset *pRet;
190509    if( pOrig ){
190510      int nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int);
190511      pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte);
190512      if( pRet ){ 
190513        memcpy(pRet, pOrig, nByte);
190514      }
190515    }else{
190516      pRet = 0;
190517    }
190518    return pRet;
190519  }
190520  
190521  /*
190522  ** Remove from colset pColset any columns that are not also in colset pMerge.
190523  */
190524  static void fts5MergeColset(Fts5Colset *pColset, Fts5Colset *pMerge){
190525    int iIn = 0;          /* Next input in pColset */
190526    int iMerge = 0;       /* Next input in pMerge */
190527    int iOut = 0;         /* Next output slot in pColset */
190528  
190529    while( iIn<pColset->nCol && iMerge<pMerge->nCol ){
190530      int iDiff = pColset->aiCol[iIn] - pMerge->aiCol[iMerge];
190531      if( iDiff==0 ){
190532        pColset->aiCol[iOut++] = pMerge->aiCol[iMerge];
190533        iMerge++;
190534        iIn++;
190535      }else if( iDiff>0 ){
190536        iMerge++;
190537      }else{
190538        iIn++;
190539      }
190540    }
190541    pColset->nCol = iOut;
190542  }
190543  
190544  /*
190545  ** Recursively apply colset pColset to expression node pNode and all of
190546  ** its decendents. If (*ppFree) is not NULL, it contains a spare copy
190547  ** of pColset. This function may use the spare copy and set (*ppFree) to
190548  ** zero, or it may create copies of pColset using fts5CloneColset().
190549  */
190550  static void fts5ParseSetColset(
190551    Fts5Parse *pParse, 
190552    Fts5ExprNode *pNode, 
190553    Fts5Colset *pColset,
190554    Fts5Colset **ppFree
190555  ){
190556    if( pParse->rc==SQLITE_OK ){
190557      assert( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING 
190558           || pNode->eType==FTS5_AND  || pNode->eType==FTS5_OR
190559           || pNode->eType==FTS5_NOT  || pNode->eType==FTS5_EOF
190560      );
190561      if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
190562        Fts5ExprNearset *pNear = pNode->pNear;
190563        if( pNear->pColset ){
190564          fts5MergeColset(pNear->pColset, pColset);
190565          if( pNear->pColset->nCol==0 ){
190566            pNode->eType = FTS5_EOF;
190567            pNode->xNext = 0;
190568          }
190569        }else if( *ppFree ){
190570          pNear->pColset = pColset;
190571          *ppFree = 0;
190572        }else{
190573          pNear->pColset = fts5CloneColset(&pParse->rc, pColset);
190574        }
190575      }else{
190576        int i;
190577        assert( pNode->eType!=FTS5_EOF || pNode->nChild==0 );
190578        for(i=0; i<pNode->nChild; i++){
190579          fts5ParseSetColset(pParse, pNode->apChild[i], pColset, ppFree);
190580        }
190581      }
190582    }
190583  }
190584  
190585  /*
190586  ** Apply colset pColset to expression node pExpr and all of its descendents.
190587  */
190588  static void sqlite3Fts5ParseSetColset(
190589    Fts5Parse *pParse, 
190590    Fts5ExprNode *pExpr, 
190591    Fts5Colset *pColset 
190592  ){
190593    Fts5Colset *pFree = pColset;
190594    if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
190595      pParse->rc = SQLITE_ERROR;
190596      pParse->zErr = sqlite3_mprintf(
190597        "fts5: column queries are not supported (detail=none)"
190598      );
190599    }else{
190600      fts5ParseSetColset(pParse, pExpr, pColset, &pFree);
190601    }
190602    sqlite3_free(pFree);
190603  }
190604  
190605  static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
190606    switch( pNode->eType ){
190607      case FTS5_STRING: {
190608        Fts5ExprNearset *pNear = pNode->pNear;
190609        if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1 
190610         && pNear->apPhrase[0]->aTerm[0].pSynonym==0
190611        ){
190612          pNode->eType = FTS5_TERM;
190613          pNode->xNext = fts5ExprNodeNext_TERM;
190614        }else{
190615          pNode->xNext = fts5ExprNodeNext_STRING;
190616        }
190617        break;
190618      };
190619  
190620      case FTS5_OR: {
190621        pNode->xNext = fts5ExprNodeNext_OR;
190622        break;
190623      };
190624  
190625      case FTS5_AND: {
190626        pNode->xNext = fts5ExprNodeNext_AND;
190627        break;
190628      };
190629  
190630      default: assert( pNode->eType==FTS5_NOT ); {
190631        pNode->xNext = fts5ExprNodeNext_NOT;
190632        break;
190633      };
190634    }
190635  }
190636  
190637  static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
190638    if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
190639      int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
190640      memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
190641      p->nChild += pSub->nChild;
190642      sqlite3_free(pSub);
190643    }else{
190644      p->apChild[p->nChild++] = pSub;
190645    }
190646  }
190647  
190648  /*
190649  ** Allocate and return a new expression object. If anything goes wrong (i.e.
190650  ** OOM error), leave an error code in pParse and return NULL.
190651  */
190652  static Fts5ExprNode *sqlite3Fts5ParseNode(
190653    Fts5Parse *pParse,              /* Parse context */
190654    int eType,                      /* FTS5_STRING, AND, OR or NOT */
190655    Fts5ExprNode *pLeft,            /* Left hand child expression */
190656    Fts5ExprNode *pRight,           /* Right hand child expression */
190657    Fts5ExprNearset *pNear          /* For STRING expressions, the near cluster */
190658  ){
190659    Fts5ExprNode *pRet = 0;
190660  
190661    if( pParse->rc==SQLITE_OK ){
190662      int nChild = 0;               /* Number of children of returned node */
190663      int nByte;                    /* Bytes of space to allocate for this node */
190664   
190665      assert( (eType!=FTS5_STRING && !pNear)
190666           || (eType==FTS5_STRING && !pLeft && !pRight)
190667      );
190668      if( eType==FTS5_STRING && pNear==0 ) return 0;
190669      if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
190670      if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
190671  
190672      if( eType==FTS5_NOT ){
190673        nChild = 2;
190674      }else if( eType==FTS5_AND || eType==FTS5_OR ){
190675        nChild = 2;
190676        if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
190677        if( pRight->eType==eType ) nChild += pRight->nChild-1;
190678      }
190679  
190680      nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
190681      pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
190682  
190683      if( pRet ){
190684        pRet->eType = eType;
190685        pRet->pNear = pNear;
190686        fts5ExprAssignXNext(pRet);
190687        if( eType==FTS5_STRING ){
190688          int iPhrase;
190689          for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
190690            pNear->apPhrase[iPhrase]->pNode = pRet;
190691            if( pNear->apPhrase[iPhrase]->nTerm==0 ){
190692              pRet->xNext = 0;
190693              pRet->eType = FTS5_EOF;
190694            }
190695          }
190696  
190697          if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL 
190698           && (pNear->nPhrase!=1 || pNear->apPhrase[0]->nTerm>1)
190699          ){
190700            assert( pParse->rc==SQLITE_OK );
190701            pParse->rc = SQLITE_ERROR;
190702            assert( pParse->zErr==0 );
190703            pParse->zErr = sqlite3_mprintf(
190704                "fts5: %s queries are not supported (detail!=full)", 
190705                pNear->nPhrase==1 ? "phrase": "NEAR"
190706            );
190707            sqlite3_free(pRet);
190708            pRet = 0;
190709          }
190710  
190711        }else{
190712          fts5ExprAddChildren(pRet, pLeft);
190713          fts5ExprAddChildren(pRet, pRight);
190714        }
190715      }
190716    }
190717  
190718    if( pRet==0 ){
190719      assert( pParse->rc!=SQLITE_OK );
190720      sqlite3Fts5ParseNodeFree(pLeft);
190721      sqlite3Fts5ParseNodeFree(pRight);
190722      sqlite3Fts5ParseNearsetFree(pNear);
190723    }
190724    return pRet;
190725  }
190726  
190727  static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
190728    Fts5Parse *pParse,              /* Parse context */
190729    Fts5ExprNode *pLeft,            /* Left hand child expression */
190730    Fts5ExprNode *pRight            /* Right hand child expression */
190731  ){
190732    Fts5ExprNode *pRet = 0;
190733    Fts5ExprNode *pPrev;
190734  
190735    if( pParse->rc ){
190736      sqlite3Fts5ParseNodeFree(pLeft);
190737      sqlite3Fts5ParseNodeFree(pRight);
190738    }else{
190739  
190740      assert( pLeft->eType==FTS5_STRING 
190741          || pLeft->eType==FTS5_TERM
190742          || pLeft->eType==FTS5_EOF
190743          || pLeft->eType==FTS5_AND
190744      );
190745      assert( pRight->eType==FTS5_STRING 
190746          || pRight->eType==FTS5_TERM 
190747          || pRight->eType==FTS5_EOF 
190748      );
190749  
190750      if( pLeft->eType==FTS5_AND ){
190751        pPrev = pLeft->apChild[pLeft->nChild-1];
190752      }else{
190753        pPrev = pLeft;
190754      }
190755      assert( pPrev->eType==FTS5_STRING 
190756          || pPrev->eType==FTS5_TERM 
190757          || pPrev->eType==FTS5_EOF 
190758          );
190759  
190760      if( pRight->eType==FTS5_EOF ){
190761        assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
190762        sqlite3Fts5ParseNodeFree(pRight);
190763        pRet = pLeft;
190764        pParse->nPhrase--;
190765      }
190766      else if( pPrev->eType==FTS5_EOF ){
190767        Fts5ExprPhrase **ap;
190768  
190769        if( pPrev==pLeft ){
190770          pRet = pRight;
190771        }else{
190772          pLeft->apChild[pLeft->nChild-1] = pRight;
190773          pRet = pLeft;
190774        }
190775  
190776        ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
190777        assert( ap[0]==pPrev->pNear->apPhrase[0] );
190778        memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
190779        pParse->nPhrase--;
190780  
190781        sqlite3Fts5ParseNodeFree(pPrev);
190782      }
190783      else{
190784        pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
190785      }
190786    }
190787  
190788    return pRet;
190789  }
190790  
190791  static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
190792    int nByte = 0;
190793    Fts5ExprTerm *p;
190794    char *zQuoted;
190795  
190796    /* Determine the maximum amount of space required. */
190797    for(p=pTerm; p; p=p->pSynonym){
190798      nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
190799    }
190800    zQuoted = sqlite3_malloc(nByte);
190801  
190802    if( zQuoted ){
190803      int i = 0;
190804      for(p=pTerm; p; p=p->pSynonym){
190805        char *zIn = p->zTerm;
190806        zQuoted[i++] = '"';
190807        while( *zIn ){
190808          if( *zIn=='"' ) zQuoted[i++] = '"';
190809          zQuoted[i++] = *zIn++;
190810        }
190811        zQuoted[i++] = '"';
190812        if( p->pSynonym ) zQuoted[i++] = '|';
190813      }
190814      if( pTerm->bPrefix ){
190815        zQuoted[i++] = ' ';
190816        zQuoted[i++] = '*';
190817      }
190818      zQuoted[i++] = '\0';
190819    }
190820    return zQuoted;
190821  }
190822  
190823  static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
190824    char *zNew;
190825    va_list ap;
190826    va_start(ap, zFmt);
190827    zNew = sqlite3_vmprintf(zFmt, ap);
190828    va_end(ap);
190829    if( zApp && zNew ){
190830      char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
190831      sqlite3_free(zNew);
190832      zNew = zNew2;
190833    }
190834    sqlite3_free(zApp);
190835    return zNew;
190836  }
190837  
190838  /*
190839  ** Compose a tcl-readable representation of expression pExpr. Return a 
190840  ** pointer to a buffer containing that representation. It is the 
190841  ** responsibility of the caller to at some point free the buffer using 
190842  ** sqlite3_free().
190843  */
190844  static char *fts5ExprPrintTcl(
190845    Fts5Config *pConfig, 
190846    const char *zNearsetCmd,
190847    Fts5ExprNode *pExpr
190848  ){
190849    char *zRet = 0;
190850    if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
190851      Fts5ExprNearset *pNear = pExpr->pNear;
190852      int i; 
190853      int iTerm;
190854  
190855      zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
190856      if( zRet==0 ) return 0;
190857      if( pNear->pColset ){
190858        int *aiCol = pNear->pColset->aiCol;
190859        int nCol = pNear->pColset->nCol;
190860        if( nCol==1 ){
190861          zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
190862        }else{
190863          zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
190864          for(i=1; i<pNear->pColset->nCol; i++){
190865            zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
190866          }
190867          zRet = fts5PrintfAppend(zRet, "} ");
190868        }
190869        if( zRet==0 ) return 0;
190870      }
190871  
190872      if( pNear->nPhrase>1 ){
190873        zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
190874        if( zRet==0 ) return 0;
190875      }
190876  
190877      zRet = fts5PrintfAppend(zRet, "--");
190878      if( zRet==0 ) return 0;
190879  
190880      for(i=0; i<pNear->nPhrase; i++){
190881        Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
190882  
190883        zRet = fts5PrintfAppend(zRet, " {");
190884        for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
190885          char *zTerm = pPhrase->aTerm[iTerm].zTerm;
190886          zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
190887          if( pPhrase->aTerm[iTerm].bPrefix ){
190888            zRet = fts5PrintfAppend(zRet, "*");
190889          }
190890        }
190891  
190892        if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
190893        if( zRet==0 ) return 0;
190894      }
190895  
190896    }else{
190897      char const *zOp = 0;
190898      int i;
190899      switch( pExpr->eType ){
190900        case FTS5_AND: zOp = "AND"; break;
190901        case FTS5_NOT: zOp = "NOT"; break;
190902        default: 
190903          assert( pExpr->eType==FTS5_OR );
190904          zOp = "OR"; 
190905          break;
190906      }
190907  
190908      zRet = sqlite3_mprintf("%s", zOp);
190909      for(i=0; zRet && i<pExpr->nChild; i++){
190910        char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
190911        if( !z ){
190912          sqlite3_free(zRet);
190913          zRet = 0;
190914        }else{
190915          zRet = fts5PrintfAppend(zRet, " [%z]", z);
190916        }
190917      }
190918    }
190919  
190920    return zRet;
190921  }
190922  
190923  static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
190924    char *zRet = 0;
190925    if( pExpr->eType==0 ){
190926      return sqlite3_mprintf("\"\"");
190927    }else
190928    if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
190929      Fts5ExprNearset *pNear = pExpr->pNear;
190930      int i; 
190931      int iTerm;
190932  
190933      if( pNear->pColset ){
190934        int iCol = pNear->pColset->aiCol[0];
190935        zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
190936        if( zRet==0 ) return 0;
190937      }
190938  
190939      if( pNear->nPhrase>1 ){
190940        zRet = fts5PrintfAppend(zRet, "NEAR(");
190941        if( zRet==0 ) return 0;
190942      }
190943  
190944      for(i=0; i<pNear->nPhrase; i++){
190945        Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
190946        if( i!=0 ){
190947          zRet = fts5PrintfAppend(zRet, " ");
190948          if( zRet==0 ) return 0;
190949        }
190950        for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
190951          char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
190952          if( zTerm ){
190953            zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
190954            sqlite3_free(zTerm);
190955          }
190956          if( zTerm==0 || zRet==0 ){
190957            sqlite3_free(zRet);
190958            return 0;
190959          }
190960        }
190961      }
190962  
190963      if( pNear->nPhrase>1 ){
190964        zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
190965        if( zRet==0 ) return 0;
190966      }
190967  
190968    }else{
190969      char const *zOp = 0;
190970      int i;
190971  
190972      switch( pExpr->eType ){
190973        case FTS5_AND: zOp = " AND "; break;
190974        case FTS5_NOT: zOp = " NOT "; break;
190975        default:  
190976          assert( pExpr->eType==FTS5_OR );
190977          zOp = " OR "; 
190978          break;
190979      }
190980  
190981      for(i=0; i<pExpr->nChild; i++){
190982        char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
190983        if( z==0 ){
190984          sqlite3_free(zRet);
190985          zRet = 0;
190986        }else{
190987          int e = pExpr->apChild[i]->eType;
190988          int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
190989          zRet = fts5PrintfAppend(zRet, "%s%s%z%s", 
190990              (i==0 ? "" : zOp),
190991              (b?"(":""), z, (b?")":"")
190992          );
190993        }
190994        if( zRet==0 ) break;
190995      }
190996    }
190997  
190998    return zRet;
190999  }
191000  
191001  /*
191002  ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
191003  ** and fts5_expr_tcl() (bTcl!=0).
191004  */
191005  static void fts5ExprFunction(
191006    sqlite3_context *pCtx,          /* Function call context */
191007    int nArg,                       /* Number of args */
191008    sqlite3_value **apVal,          /* Function arguments */
191009    int bTcl
191010  ){
191011    Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
191012    sqlite3 *db = sqlite3_context_db_handle(pCtx);
191013    const char *zExpr = 0;
191014    char *zErr = 0;
191015    Fts5Expr *pExpr = 0;
191016    int rc;
191017    int i;
191018  
191019    const char **azConfig;          /* Array of arguments for Fts5Config */
191020    const char *zNearsetCmd = "nearset";
191021    int nConfig;                    /* Size of azConfig[] */
191022    Fts5Config *pConfig = 0;
191023    int iArg = 1;
191024  
191025    if( nArg<1 ){
191026      zErr = sqlite3_mprintf("wrong number of arguments to function %s",
191027          bTcl ? "fts5_expr_tcl" : "fts5_expr"
191028      );
191029      sqlite3_result_error(pCtx, zErr, -1);
191030      sqlite3_free(zErr);
191031      return;
191032    }
191033  
191034    if( bTcl && nArg>1 ){
191035      zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
191036      iArg = 2;
191037    }
191038  
191039    nConfig = 3 + (nArg-iArg);
191040    azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
191041    if( azConfig==0 ){
191042      sqlite3_result_error_nomem(pCtx);
191043      return;
191044    }
191045    azConfig[0] = 0;
191046    azConfig[1] = "main";
191047    azConfig[2] = "tbl";
191048    for(i=3; iArg<nArg; iArg++){
191049      azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
191050    }
191051  
191052    zExpr = (const char*)sqlite3_value_text(apVal[0]);
191053  
191054    rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
191055    if( rc==SQLITE_OK ){
191056      rc = sqlite3Fts5ExprNew(pConfig, pConfig->nCol, zExpr, &pExpr, &zErr);
191057    }
191058    if( rc==SQLITE_OK ){
191059      char *zText;
191060      if( pExpr->pRoot->xNext==0 ){
191061        zText = sqlite3_mprintf("");
191062      }else if( bTcl ){
191063        zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
191064      }else{
191065        zText = fts5ExprPrint(pConfig, pExpr->pRoot);
191066      }
191067      if( zText==0 ){
191068        rc = SQLITE_NOMEM;
191069      }else{
191070        sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
191071        sqlite3_free(zText);
191072      }
191073    }
191074  
191075    if( rc!=SQLITE_OK ){
191076      if( zErr ){
191077        sqlite3_result_error(pCtx, zErr, -1);
191078        sqlite3_free(zErr);
191079      }else{
191080        sqlite3_result_error_code(pCtx, rc);
191081      }
191082    }
191083    sqlite3_free((void *)azConfig);
191084    sqlite3Fts5ConfigFree(pConfig);
191085    sqlite3Fts5ExprFree(pExpr);
191086  }
191087  
191088  static void fts5ExprFunctionHr(
191089    sqlite3_context *pCtx,          /* Function call context */
191090    int nArg,                       /* Number of args */
191091    sqlite3_value **apVal           /* Function arguments */
191092  ){
191093    fts5ExprFunction(pCtx, nArg, apVal, 0);
191094  }
191095  static void fts5ExprFunctionTcl(
191096    sqlite3_context *pCtx,          /* Function call context */
191097    int nArg,                       /* Number of args */
191098    sqlite3_value **apVal           /* Function arguments */
191099  ){
191100    fts5ExprFunction(pCtx, nArg, apVal, 1);
191101  }
191102  
191103  /*
191104  ** The implementation of an SQLite user-defined-function that accepts a
191105  ** single integer as an argument. If the integer is an alpha-numeric 
191106  ** unicode code point, 1 is returned. Otherwise 0.
191107  */
191108  static void fts5ExprIsAlnum(
191109    sqlite3_context *pCtx,          /* Function call context */
191110    int nArg,                       /* Number of args */
191111    sqlite3_value **apVal           /* Function arguments */
191112  ){
191113    int iCode;
191114    if( nArg!=1 ){
191115      sqlite3_result_error(pCtx, 
191116          "wrong number of arguments to function fts5_isalnum", -1
191117      );
191118      return;
191119    }
191120    iCode = sqlite3_value_int(apVal[0]);
191121    sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode));
191122  }
191123  
191124  static void fts5ExprFold(
191125    sqlite3_context *pCtx,          /* Function call context */
191126    int nArg,                       /* Number of args */
191127    sqlite3_value **apVal           /* Function arguments */
191128  ){
191129    if( nArg!=1 && nArg!=2 ){
191130      sqlite3_result_error(pCtx, 
191131          "wrong number of arguments to function fts5_fold", -1
191132      );
191133    }else{
191134      int iCode;
191135      int bRemoveDiacritics = 0;
191136      iCode = sqlite3_value_int(apVal[0]);
191137      if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
191138      sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
191139    }
191140  }
191141  
191142  /*
191143  ** This is called during initialization to register the fts5_expr() scalar
191144  ** UDF with the SQLite handle passed as the only argument.
191145  */
191146  static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
191147    struct Fts5ExprFunc {
191148      const char *z;
191149      void (*x)(sqlite3_context*,int,sqlite3_value**);
191150    } aFunc[] = {
191151      { "fts5_expr",     fts5ExprFunctionHr },
191152      { "fts5_expr_tcl", fts5ExprFunctionTcl },
191153      { "fts5_isalnum",  fts5ExprIsAlnum },
191154      { "fts5_fold",     fts5ExprFold },
191155    };
191156    int i;
191157    int rc = SQLITE_OK;
191158    void *pCtx = (void*)pGlobal;
191159  
191160    for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
191161      struct Fts5ExprFunc *p = &aFunc[i];
191162      rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
191163    }
191164  
191165    /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */
191166  #ifndef NDEBUG
191167    (void)sqlite3Fts5ParserTrace;
191168  #endif
191169  
191170    return rc;
191171  }
191172  
191173  /*
191174  ** Return the number of phrases in expression pExpr.
191175  */
191176  static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
191177    return (pExpr ? pExpr->nPhrase : 0);
191178  }
191179  
191180  /*
191181  ** Return the number of terms in the iPhrase'th phrase in pExpr.
191182  */
191183  static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
191184    if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
191185    return pExpr->apExprPhrase[iPhrase]->nTerm;
191186  }
191187  
191188  /*
191189  ** This function is used to access the current position list for phrase
191190  ** iPhrase.
191191  */
191192  static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
191193    int nRet;
191194    Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
191195    Fts5ExprNode *pNode = pPhrase->pNode;
191196    if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
191197      *pa = pPhrase->poslist.p;
191198      nRet = pPhrase->poslist.n;
191199    }else{
191200      *pa = 0;
191201      nRet = 0;
191202    }
191203    return nRet;
191204  }
191205  
191206  struct Fts5PoslistPopulator {
191207    Fts5PoslistWriter writer;
191208    int bOk;                        /* True if ok to populate */
191209    int bMiss;
191210  };
191211  
191212  static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
191213    Fts5PoslistPopulator *pRet;
191214    pRet = sqlite3_malloc(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
191215    if( pRet ){
191216      int i;
191217      memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
191218      for(i=0; i<pExpr->nPhrase; i++){
191219        Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
191220        Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
191221        assert( pExpr->apExprPhrase[i]->nTerm==1 );
191222        if( bLive && 
191223            (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
191224        ){
191225          pRet[i].bMiss = 1;
191226        }else{
191227          pBuf->n = 0;
191228        }
191229      }
191230    }
191231    return pRet;
191232  }
191233  
191234  struct Fts5ExprCtx {
191235    Fts5Expr *pExpr;
191236    Fts5PoslistPopulator *aPopulator;
191237    i64 iOff;
191238  };
191239  typedef struct Fts5ExprCtx Fts5ExprCtx;
191240  
191241  /*
191242  ** TODO: Make this more efficient!
191243  */
191244  static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
191245    int i;
191246    for(i=0; i<pColset->nCol; i++){
191247      if( pColset->aiCol[i]==iCol ) return 1;
191248    }
191249    return 0;
191250  }
191251  
191252  static int fts5ExprPopulatePoslistsCb(
191253    void *pCtx,                /* Copy of 2nd argument to xTokenize() */
191254    int tflags,                /* Mask of FTS5_TOKEN_* flags */
191255    const char *pToken,        /* Pointer to buffer containing token */
191256    int nToken,                /* Size of token in bytes */
191257    int iUnused1,              /* Byte offset of token within input text */
191258    int iUnused2               /* Byte offset of end of token within input text */
191259  ){
191260    Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
191261    Fts5Expr *pExpr = p->pExpr;
191262    int i;
191263  
191264    UNUSED_PARAM2(iUnused1, iUnused2);
191265  
191266    if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
191267    if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
191268    for(i=0; i<pExpr->nPhrase; i++){
191269      Fts5ExprTerm *pTerm;
191270      if( p->aPopulator[i].bOk==0 ) continue;
191271      for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
191272        int nTerm = (int)strlen(pTerm->zTerm);
191273        if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
191274         && memcmp(pTerm->zTerm, pToken, nTerm)==0
191275        ){
191276          int rc = sqlite3Fts5PoslistWriterAppend(
191277              &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
191278          );
191279          if( rc ) return rc;
191280          break;
191281        }
191282      }
191283    }
191284    return SQLITE_OK;
191285  }
191286  
191287  static int sqlite3Fts5ExprPopulatePoslists(
191288    Fts5Config *pConfig,
191289    Fts5Expr *pExpr, 
191290    Fts5PoslistPopulator *aPopulator,
191291    int iCol, 
191292    const char *z, int n
191293  ){
191294    int i;
191295    Fts5ExprCtx sCtx;
191296    sCtx.pExpr = pExpr;
191297    sCtx.aPopulator = aPopulator;
191298    sCtx.iOff = (((i64)iCol) << 32) - 1;
191299  
191300    for(i=0; i<pExpr->nPhrase; i++){
191301      Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
191302      Fts5Colset *pColset = pNode->pNear->pColset;
191303      if( (pColset && 0==fts5ExprColsetTest(pColset, iCol)) 
191304       || aPopulator[i].bMiss
191305      ){
191306        aPopulator[i].bOk = 0;
191307      }else{
191308        aPopulator[i].bOk = 1;
191309      }
191310    }
191311  
191312    return sqlite3Fts5Tokenize(pConfig, 
191313        FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
191314    );
191315  }
191316  
191317  static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
191318    if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
191319      pNode->pNear->apPhrase[0]->poslist.n = 0;
191320    }else{
191321      int i;
191322      for(i=0; i<pNode->nChild; i++){
191323        fts5ExprClearPoslists(pNode->apChild[i]);
191324      }
191325    }
191326  }
191327  
191328  static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
191329    pNode->iRowid = iRowid;
191330    pNode->bEof = 0;
191331    switch( pNode->eType ){
191332      case FTS5_TERM:
191333      case FTS5_STRING:
191334        return (pNode->pNear->apPhrase[0]->poslist.n>0);
191335  
191336      case FTS5_AND: {
191337        int i;
191338        for(i=0; i<pNode->nChild; i++){
191339          if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
191340            fts5ExprClearPoslists(pNode);
191341            return 0;
191342          }
191343        }
191344        break;
191345      }
191346  
191347      case FTS5_OR: {
191348        int i;
191349        int bRet = 0;
191350        for(i=0; i<pNode->nChild; i++){
191351          if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
191352            bRet = 1;
191353          }
191354        }
191355        return bRet;
191356      }
191357  
191358      default: {
191359        assert( pNode->eType==FTS5_NOT );
191360        if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
191361            || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
191362          ){
191363          fts5ExprClearPoslists(pNode);
191364          return 0;
191365        }
191366        break;
191367      }
191368    }
191369    return 1;
191370  }
191371  
191372  static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
191373    fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
191374  }
191375  
191376  /*
191377  ** This function is only called for detail=columns tables. 
191378  */
191379  static int sqlite3Fts5ExprPhraseCollist(
191380    Fts5Expr *pExpr, 
191381    int iPhrase, 
191382    const u8 **ppCollist, 
191383    int *pnCollist
191384  ){
191385    Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
191386    Fts5ExprNode *pNode = pPhrase->pNode;
191387    int rc = SQLITE_OK;
191388  
191389    assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
191390    assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
191391  
191392    if( pNode->bEof==0 
191393     && pNode->iRowid==pExpr->pRoot->iRowid 
191394     && pPhrase->poslist.n>0
191395    ){
191396      Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
191397      if( pTerm->pSynonym ){
191398        Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
191399        rc = fts5ExprSynonymList(
191400            pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
191401        );
191402      }else{
191403        *ppCollist = pPhrase->aTerm[0].pIter->pData;
191404        *pnCollist = pPhrase->aTerm[0].pIter->nData;
191405      }
191406    }else{
191407      *ppCollist = 0;
191408      *pnCollist = 0;
191409    }
191410  
191411    return rc;
191412  }
191413  
191414  
191415  /*
191416  ** 2014 August 11
191417  **
191418  ** The author disclaims copyright to this source code.  In place of
191419  ** a legal notice, here is a blessing:
191420  **
191421  **    May you do good and not evil.
191422  **    May you find forgiveness for yourself and forgive others.
191423  **    May you share freely, never taking more than you give.
191424  **
191425  ******************************************************************************
191426  **
191427  */
191428  
191429  
191430  
191431  /* #include "fts5Int.h" */
191432  
191433  typedef struct Fts5HashEntry Fts5HashEntry;
191434  
191435  /*
191436  ** This file contains the implementation of an in-memory hash table used
191437  ** to accumuluate "term -> doclist" content before it is flused to a level-0
191438  ** segment.
191439  */
191440  
191441  
191442  struct Fts5Hash {
191443    int eDetail;                    /* Copy of Fts5Config.eDetail */
191444    int *pnByte;                    /* Pointer to bytes counter */
191445    int nEntry;                     /* Number of entries currently in hash */
191446    int nSlot;                      /* Size of aSlot[] array */
191447    Fts5HashEntry *pScan;           /* Current ordered scan item */
191448    Fts5HashEntry **aSlot;          /* Array of hash slots */
191449  };
191450  
191451  /*
191452  ** Each entry in the hash table is represented by an object of the 
191453  ** following type. Each object, its key (a nul-terminated string) and 
191454  ** its current data are stored in a single memory allocation. The 
191455  ** key immediately follows the object in memory. The position list
191456  ** data immediately follows the key data in memory.
191457  **
191458  ** The data that follows the key is in a similar, but not identical format
191459  ** to the doclist data stored in the database. It is:
191460  **
191461  **   * Rowid, as a varint
191462  **   * Position list, without 0x00 terminator.
191463  **   * Size of previous position list and rowid, as a 4 byte
191464  **     big-endian integer.
191465  **
191466  ** iRowidOff:
191467  **   Offset of last rowid written to data area. Relative to first byte of
191468  **   structure.
191469  **
191470  ** nData:
191471  **   Bytes of data written since iRowidOff.
191472  */
191473  struct Fts5HashEntry {
191474    Fts5HashEntry *pHashNext;       /* Next hash entry with same hash-key */
191475    Fts5HashEntry *pScanNext;       /* Next entry in sorted order */
191476    
191477    int nAlloc;                     /* Total size of allocation */
191478    int iSzPoslist;                 /* Offset of space for 4-byte poslist size */
191479    int nData;                      /* Total bytes of data (incl. structure) */
191480    int nKey;                       /* Length of key in bytes */
191481    u8 bDel;                        /* Set delete-flag @ iSzPoslist */
191482    u8 bContent;                    /* Set content-flag (detail=none mode) */
191483    i16 iCol;                       /* Column of last value written */
191484    int iPos;                       /* Position of last value written */
191485    i64 iRowid;                     /* Rowid of last value written */
191486  };
191487  
191488  /*
191489  ** Eqivalent to:
191490  **
191491  **   char *fts5EntryKey(Fts5HashEntry *pEntry){ return zKey; }
191492  */
191493  #define fts5EntryKey(p) ( ((char *)(&(p)[1])) )
191494  
191495  
191496  /*
191497  ** Allocate a new hash table.
191498  */
191499  static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
191500    int rc = SQLITE_OK;
191501    Fts5Hash *pNew;
191502  
191503    *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
191504    if( pNew==0 ){
191505      rc = SQLITE_NOMEM;
191506    }else{
191507      int nByte;
191508      memset(pNew, 0, sizeof(Fts5Hash));
191509      pNew->pnByte = pnByte;
191510      pNew->eDetail = pConfig->eDetail;
191511  
191512      pNew->nSlot = 1024;
191513      nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
191514      pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
191515      if( pNew->aSlot==0 ){
191516        sqlite3_free(pNew);
191517        *ppNew = 0;
191518        rc = SQLITE_NOMEM;
191519      }else{
191520        memset(pNew->aSlot, 0, nByte);
191521      }
191522    }
191523    return rc;
191524  }
191525  
191526  /*
191527  ** Free a hash table object.
191528  */
191529  static void sqlite3Fts5HashFree(Fts5Hash *pHash){
191530    if( pHash ){
191531      sqlite3Fts5HashClear(pHash);
191532      sqlite3_free(pHash->aSlot);
191533      sqlite3_free(pHash);
191534    }
191535  }
191536  
191537  /*
191538  ** Empty (but do not delete) a hash table.
191539  */
191540  static void sqlite3Fts5HashClear(Fts5Hash *pHash){
191541    int i;
191542    for(i=0; i<pHash->nSlot; i++){
191543      Fts5HashEntry *pNext;
191544      Fts5HashEntry *pSlot;
191545      for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
191546        pNext = pSlot->pHashNext;
191547        sqlite3_free(pSlot);
191548      }
191549    }
191550    memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
191551    pHash->nEntry = 0;
191552  }
191553  
191554  static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
191555    int i;
191556    unsigned int h = 13;
191557    for(i=n-1; i>=0; i--){
191558      h = (h << 3) ^ h ^ p[i];
191559    }
191560    return (h % nSlot);
191561  }
191562  
191563  static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
191564    int i;
191565    unsigned int h = 13;
191566    for(i=n-1; i>=0; i--){
191567      h = (h << 3) ^ h ^ p[i];
191568    }
191569    h = (h << 3) ^ h ^ b;
191570    return (h % nSlot);
191571  }
191572  
191573  /*
191574  ** Resize the hash table by doubling the number of slots.
191575  */
191576  static int fts5HashResize(Fts5Hash *pHash){
191577    int nNew = pHash->nSlot*2;
191578    int i;
191579    Fts5HashEntry **apNew;
191580    Fts5HashEntry **apOld = pHash->aSlot;
191581  
191582    apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
191583    if( !apNew ) return SQLITE_NOMEM;
191584    memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
191585  
191586    for(i=0; i<pHash->nSlot; i++){
191587      while( apOld[i] ){
191588        unsigned int iHash;
191589        Fts5HashEntry *p = apOld[i];
191590        apOld[i] = p->pHashNext;
191591        iHash = fts5HashKey(nNew, (u8*)fts5EntryKey(p),
191592                            (int)strlen(fts5EntryKey(p)));
191593        p->pHashNext = apNew[iHash];
191594        apNew[iHash] = p;
191595      }
191596    }
191597  
191598    sqlite3_free(apOld);
191599    pHash->nSlot = nNew;
191600    pHash->aSlot = apNew;
191601    return SQLITE_OK;
191602  }
191603  
191604  static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){
191605    if( p->iSzPoslist ){
191606      u8 *pPtr = (u8*)p;
191607      if( pHash->eDetail==FTS5_DETAIL_NONE ){
191608        assert( p->nData==p->iSzPoslist );
191609        if( p->bDel ){
191610          pPtr[p->nData++] = 0x00;
191611          if( p->bContent ){
191612            pPtr[p->nData++] = 0x00;
191613          }
191614        }
191615      }else{
191616        int nSz = (p->nData - p->iSzPoslist - 1);       /* Size in bytes */
191617        int nPos = nSz*2 + p->bDel;                     /* Value of nPos field */
191618  
191619        assert( p->bDel==0 || p->bDel==1 );
191620        if( nPos<=127 ){
191621          pPtr[p->iSzPoslist] = (u8)nPos;
191622        }else{
191623          int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
191624          memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
191625          sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
191626          p->nData += (nByte-1);
191627        }
191628      }
191629  
191630      p->iSzPoslist = 0;
191631      p->bDel = 0;
191632      p->bContent = 0;
191633    }
191634  }
191635  
191636  /*
191637  ** Add an entry to the in-memory hash table. The key is the concatenation
191638  ** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
191639  **
191640  **     (bByte || pToken) -> (iRowid,iCol,iPos)
191641  **
191642  ** Or, if iCol is negative, then the value is a delete marker.
191643  */
191644  static int sqlite3Fts5HashWrite(
191645    Fts5Hash *pHash,
191646    i64 iRowid,                     /* Rowid for this entry */
191647    int iCol,                       /* Column token appears in (-ve -> delete) */
191648    int iPos,                       /* Position of token within column */
191649    char bByte,                     /* First byte of token */
191650    const char *pToken, int nToken  /* Token to add or remove to or from index */
191651  ){
191652    unsigned int iHash;
191653    Fts5HashEntry *p;
191654    u8 *pPtr;
191655    int nIncr = 0;                  /* Amount to increment (*pHash->pnByte) by */
191656    int bNew;                       /* If non-delete entry should be written */
191657    
191658    bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
191659  
191660    /* Attempt to locate an existing hash entry */
191661    iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
191662    for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
191663      char *zKey = fts5EntryKey(p);
191664      if( zKey[0]==bByte 
191665       && p->nKey==nToken
191666       && memcmp(&zKey[1], pToken, nToken)==0 
191667      ){
191668        break;
191669      }
191670    }
191671  
191672    /* If an existing hash entry cannot be found, create a new one. */
191673    if( p==0 ){
191674      /* Figure out how much space to allocate */
191675      char *zKey;
191676      int nByte = sizeof(Fts5HashEntry) + (nToken+1) + 1 + 64;
191677      if( nByte<128 ) nByte = 128;
191678  
191679      /* Grow the Fts5Hash.aSlot[] array if necessary. */
191680      if( (pHash->nEntry*2)>=pHash->nSlot ){
191681        int rc = fts5HashResize(pHash);
191682        if( rc!=SQLITE_OK ) return rc;
191683        iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
191684      }
191685  
191686      /* Allocate new Fts5HashEntry and add it to the hash table. */
191687      p = (Fts5HashEntry*)sqlite3_malloc(nByte);
191688      if( !p ) return SQLITE_NOMEM;
191689      memset(p, 0, sizeof(Fts5HashEntry));
191690      p->nAlloc = nByte;
191691      zKey = fts5EntryKey(p);
191692      zKey[0] = bByte;
191693      memcpy(&zKey[1], pToken, nToken);
191694      assert( iHash==fts5HashKey(pHash->nSlot, (u8*)zKey, nToken+1) );
191695      p->nKey = nToken;
191696      zKey[nToken+1] = '\0';
191697      p->nData = nToken+1 + 1 + sizeof(Fts5HashEntry);
191698      p->pHashNext = pHash->aSlot[iHash];
191699      pHash->aSlot[iHash] = p;
191700      pHash->nEntry++;
191701  
191702      /* Add the first rowid field to the hash-entry */
191703      p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
191704      p->iRowid = iRowid;
191705  
191706      p->iSzPoslist = p->nData;
191707      if( pHash->eDetail!=FTS5_DETAIL_NONE ){
191708        p->nData += 1;
191709        p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
191710      }
191711  
191712      nIncr += p->nData;
191713    }else{
191714  
191715      /* Appending to an existing hash-entry. Check that there is enough 
191716      ** space to append the largest possible new entry. Worst case scenario 
191717      ** is:
191718      **
191719      **     + 9 bytes for a new rowid,
191720      **     + 4 byte reserved for the "poslist size" varint.
191721      **     + 1 byte for a "new column" byte,
191722      **     + 3 bytes for a new column number (16-bit max) as a varint,
191723      **     + 5 bytes for the new position offset (32-bit max).
191724      */
191725      if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
191726        int nNew = p->nAlloc * 2;
191727        Fts5HashEntry *pNew;
191728        Fts5HashEntry **pp;
191729        pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
191730        if( pNew==0 ) return SQLITE_NOMEM;
191731        pNew->nAlloc = nNew;
191732        for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
191733        *pp = pNew;
191734        p = pNew;
191735      }
191736      nIncr -= p->nData;
191737    }
191738    assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
191739  
191740    pPtr = (u8*)p;
191741  
191742    /* If this is a new rowid, append the 4-byte size field for the previous
191743    ** entry, and the new rowid for this entry.  */
191744    if( iRowid!=p->iRowid ){
191745      fts5HashAddPoslistSize(pHash, p);
191746      p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
191747      p->iRowid = iRowid;
191748      bNew = 1;
191749      p->iSzPoslist = p->nData;
191750      if( pHash->eDetail!=FTS5_DETAIL_NONE ){
191751        p->nData += 1;
191752        p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
191753        p->iPos = 0;
191754      }
191755    }
191756  
191757    if( iCol>=0 ){
191758      if( pHash->eDetail==FTS5_DETAIL_NONE ){
191759        p->bContent = 1;
191760      }else{
191761        /* Append a new column value, if necessary */
191762        assert( iCol>=p->iCol );
191763        if( iCol!=p->iCol ){
191764          if( pHash->eDetail==FTS5_DETAIL_FULL ){
191765            pPtr[p->nData++] = 0x01;
191766            p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
191767            p->iCol = (i16)iCol;
191768            p->iPos = 0;
191769          }else{
191770            bNew = 1;
191771            p->iCol = (i16)(iPos = iCol);
191772          }
191773        }
191774  
191775        /* Append the new position offset, if necessary */
191776        if( bNew ){
191777          p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
191778          p->iPos = iPos;
191779        }
191780      }
191781    }else{
191782      /* This is a delete. Set the delete flag. */
191783      p->bDel = 1;
191784    }
191785  
191786    nIncr += p->nData;
191787    *pHash->pnByte += nIncr;
191788    return SQLITE_OK;
191789  }
191790  
191791  
191792  /*
191793  ** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
191794  ** each sorted in key order. This function merges the two lists into a
191795  ** single list and returns a pointer to its first element.
191796  */
191797  static Fts5HashEntry *fts5HashEntryMerge(
191798    Fts5HashEntry *pLeft,
191799    Fts5HashEntry *pRight
191800  ){
191801    Fts5HashEntry *p1 = pLeft;
191802    Fts5HashEntry *p2 = pRight;
191803    Fts5HashEntry *pRet = 0;
191804    Fts5HashEntry **ppOut = &pRet;
191805  
191806    while( p1 || p2 ){
191807      if( p1==0 ){
191808        *ppOut = p2;
191809        p2 = 0;
191810      }else if( p2==0 ){
191811        *ppOut = p1;
191812        p1 = 0;
191813      }else{
191814        int i = 0;
191815        char *zKey1 = fts5EntryKey(p1);
191816        char *zKey2 = fts5EntryKey(p2);
191817        while( zKey1[i]==zKey2[i] ) i++;
191818  
191819        if( ((u8)zKey1[i])>((u8)zKey2[i]) ){
191820          /* p2 is smaller */
191821          *ppOut = p2;
191822          ppOut = &p2->pScanNext;
191823          p2 = p2->pScanNext;
191824        }else{
191825          /* p1 is smaller */
191826          *ppOut = p1;
191827          ppOut = &p1->pScanNext;
191828          p1 = p1->pScanNext;
191829        }
191830        *ppOut = 0;
191831      }
191832    }
191833  
191834    return pRet;
191835  }
191836  
191837  /*
191838  ** Extract all tokens from hash table iHash and link them into a list
191839  ** in sorted order. The hash table is cleared before returning. It is
191840  ** the responsibility of the caller to free the elements of the returned
191841  ** list.
191842  */
191843  static int fts5HashEntrySort(
191844    Fts5Hash *pHash, 
191845    const char *pTerm, int nTerm,   /* Query prefix, if any */
191846    Fts5HashEntry **ppSorted
191847  ){
191848    const int nMergeSlot = 32;
191849    Fts5HashEntry **ap;
191850    Fts5HashEntry *pList;
191851    int iSlot;
191852    int i;
191853  
191854    *ppSorted = 0;
191855    ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
191856    if( !ap ) return SQLITE_NOMEM;
191857    memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
191858  
191859    for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
191860      Fts5HashEntry *pIter;
191861      for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
191862        if( pTerm==0 || 0==memcmp(fts5EntryKey(pIter), pTerm, nTerm) ){
191863          Fts5HashEntry *pEntry = pIter;
191864          pEntry->pScanNext = 0;
191865          for(i=0; ap[i]; i++){
191866            pEntry = fts5HashEntryMerge(pEntry, ap[i]);
191867            ap[i] = 0;
191868          }
191869          ap[i] = pEntry;
191870        }
191871      }
191872    }
191873  
191874    pList = 0;
191875    for(i=0; i<nMergeSlot; i++){
191876      pList = fts5HashEntryMerge(pList, ap[i]);
191877    }
191878  
191879    pHash->nEntry = 0;
191880    sqlite3_free(ap);
191881    *ppSorted = pList;
191882    return SQLITE_OK;
191883  }
191884  
191885  /*
191886  ** Query the hash table for a doclist associated with term pTerm/nTerm.
191887  */
191888  static int sqlite3Fts5HashQuery(
191889    Fts5Hash *pHash,                /* Hash table to query */
191890    const char *pTerm, int nTerm,   /* Query term */
191891    const u8 **ppDoclist,           /* OUT: Pointer to doclist for pTerm */
191892    int *pnDoclist                  /* OUT: Size of doclist in bytes */
191893  ){
191894    unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
191895    char *zKey = 0;
191896    Fts5HashEntry *p;
191897  
191898    for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
191899      zKey = fts5EntryKey(p);
191900      if( memcmp(zKey, pTerm, nTerm)==0 && zKey[nTerm]==0 ) break;
191901    }
191902  
191903    if( p ){
191904      fts5HashAddPoslistSize(pHash, p);
191905      *ppDoclist = (const u8*)&zKey[nTerm+1];
191906      *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
191907    }else{
191908      *ppDoclist = 0;
191909      *pnDoclist = 0;
191910    }
191911  
191912    return SQLITE_OK;
191913  }
191914  
191915  static int sqlite3Fts5HashScanInit(
191916    Fts5Hash *p,                    /* Hash table to query */
191917    const char *pTerm, int nTerm    /* Query prefix */
191918  ){
191919    return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
191920  }
191921  
191922  static void sqlite3Fts5HashScanNext(Fts5Hash *p){
191923    assert( !sqlite3Fts5HashScanEof(p) );
191924    p->pScan = p->pScan->pScanNext;
191925  }
191926  
191927  static int sqlite3Fts5HashScanEof(Fts5Hash *p){
191928    return (p->pScan==0);
191929  }
191930  
191931  static void sqlite3Fts5HashScanEntry(
191932    Fts5Hash *pHash,
191933    const char **pzTerm,            /* OUT: term (nul-terminated) */
191934    const u8 **ppDoclist,           /* OUT: pointer to doclist */
191935    int *pnDoclist                  /* OUT: size of doclist in bytes */
191936  ){
191937    Fts5HashEntry *p;
191938    if( (p = pHash->pScan) ){
191939      char *zKey = fts5EntryKey(p);
191940      int nTerm = (int)strlen(zKey);
191941      fts5HashAddPoslistSize(pHash, p);
191942      *pzTerm = zKey;
191943      *ppDoclist = (const u8*)&zKey[nTerm+1];
191944      *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
191945    }else{
191946      *pzTerm = 0;
191947      *ppDoclist = 0;
191948      *pnDoclist = 0;
191949    }
191950  }
191951  
191952  
191953  /*
191954  ** 2014 May 31
191955  **
191956  ** The author disclaims copyright to this source code.  In place of
191957  ** a legal notice, here is a blessing:
191958  **
191959  **    May you do good and not evil.
191960  **    May you find forgiveness for yourself and forgive others.
191961  **    May you share freely, never taking more than you give.
191962  **
191963  ******************************************************************************
191964  **
191965  ** Low level access to the FTS index stored in the database file. The 
191966  ** routines in this file file implement all read and write access to the
191967  ** %_data table. Other parts of the system access this functionality via
191968  ** the interface defined in fts5Int.h.
191969  */
191970  
191971  
191972  /* #include "fts5Int.h" */
191973  
191974  /*
191975  ** Overview:
191976  **
191977  ** The %_data table contains all the FTS indexes for an FTS5 virtual table.
191978  ** As well as the main term index, there may be up to 31 prefix indexes.
191979  ** The format is similar to FTS3/4, except that:
191980  **
191981  **   * all segment b-tree leaf data is stored in fixed size page records 
191982  **     (e.g. 1000 bytes). A single doclist may span multiple pages. Care is 
191983  **     taken to ensure it is possible to iterate in either direction through 
191984  **     the entries in a doclist, or to seek to a specific entry within a 
191985  **     doclist, without loading it into memory.
191986  **
191987  **   * large doclists that span many pages have associated "doclist index"
191988  **     records that contain a copy of the first rowid on each page spanned by
191989  **     the doclist. This is used to speed up seek operations, and merges of
191990  **     large doclists with very small doclists.
191991  **
191992  **   * extra fields in the "structure record" record the state of ongoing
191993  **     incremental merge operations.
191994  **
191995  */
191996  
191997  
191998  #define FTS5_OPT_WORK_UNIT  1000  /* Number of leaf pages per optimize step */
191999  #define FTS5_WORK_UNIT      64    /* Number of leaf pages in unit of work */
192000  
192001  #define FTS5_MIN_DLIDX_SIZE 4     /* Add dlidx if this many empty pages */
192002  
192003  #define FTS5_MAIN_PREFIX '0'
192004  
192005  #if FTS5_MAX_PREFIX_INDEXES > 31
192006  # error "FTS5_MAX_PREFIX_INDEXES is too large"
192007  #endif
192008  
192009  /*
192010  ** Details:
192011  **
192012  ** The %_data table managed by this module,
192013  **
192014  **     CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
192015  **
192016  ** , contains the following 5 types of records. See the comments surrounding
192017  ** the FTS5_*_ROWID macros below for a description of how %_data rowids are 
192018  ** assigned to each fo them.
192019  **
192020  ** 1. Structure Records:
192021  **
192022  **   The set of segments that make up an index - the index structure - are
192023  **   recorded in a single record within the %_data table. The record consists
192024  **   of a single 32-bit configuration cookie value followed by a list of 
192025  **   SQLite varints. If the FTS table features more than one index (because
192026  **   there are one or more prefix indexes), it is guaranteed that all share
192027  **   the same cookie value.
192028  **
192029  **   Immediately following the configuration cookie, the record begins with
192030  **   three varints:
192031  **
192032  **     + number of levels,
192033  **     + total number of segments on all levels,
192034  **     + value of write counter.
192035  **
192036  **   Then, for each level from 0 to nMax:
192037  **
192038  **     + number of input segments in ongoing merge.
192039  **     + total number of segments in level.
192040  **     + for each segment from oldest to newest:
192041  **         + segment id (always > 0)
192042  **         + first leaf page number (often 1, always greater than 0)
192043  **         + final leaf page number
192044  **
192045  ** 2. The Averages Record:
192046  **
192047  **   A single record within the %_data table. The data is a list of varints.
192048  **   The first value is the number of rows in the index. Then, for each column
192049  **   from left to right, the total number of tokens in the column for all
192050  **   rows of the table.
192051  **
192052  ** 3. Segment leaves:
192053  **
192054  **   TERM/DOCLIST FORMAT:
192055  **
192056  **     Most of each segment leaf is taken up by term/doclist data. The 
192057  **     general format of term/doclist, starting with the first term
192058  **     on the leaf page, is:
192059  **
192060  **         varint : size of first term
192061  **         blob:    first term data
192062  **         doclist: first doclist
192063  **         zero-or-more {
192064  **           varint:  number of bytes in common with previous term
192065  **           varint:  number of bytes of new term data (nNew)
192066  **           blob:    nNew bytes of new term data
192067  **           doclist: next doclist
192068  **         }
192069  **
192070  **     doclist format:
192071  **
192072  **         varint:  first rowid
192073  **         poslist: first poslist
192074  **         zero-or-more {
192075  **           varint:  rowid delta (always > 0)
192076  **           poslist: next poslist
192077  **         }
192078  **
192079  **     poslist format:
192080  **
192081  **         varint: size of poslist in bytes multiplied by 2, not including
192082  **                 this field. Plus 1 if this entry carries the "delete" flag.
192083  **         collist: collist for column 0
192084  **         zero-or-more {
192085  **           0x01 byte
192086  **           varint: column number (I)
192087  **           collist: collist for column I
192088  **         }
192089  **
192090  **     collist format:
192091  **
192092  **         varint: first offset + 2
192093  **         zero-or-more {
192094  **           varint: offset delta + 2
192095  **         }
192096  **
192097  **   PAGE FORMAT
192098  **
192099  **     Each leaf page begins with a 4-byte header containing 2 16-bit 
192100  **     unsigned integer fields in big-endian format. They are:
192101  **
192102  **       * The byte offset of the first rowid on the page, if it exists
192103  **         and occurs before the first term (otherwise 0).
192104  **
192105  **       * The byte offset of the start of the page footer. If the page
192106  **         footer is 0 bytes in size, then this field is the same as the
192107  **         size of the leaf page in bytes.
192108  **
192109  **     The page footer consists of a single varint for each term located
192110  **     on the page. Each varint is the byte offset of the current term
192111  **     within the page, delta-compressed against the previous value. In
192112  **     other words, the first varint in the footer is the byte offset of
192113  **     the first term, the second is the byte offset of the second less that
192114  **     of the first, and so on.
192115  **
192116  **     The term/doclist format described above is accurate if the entire
192117  **     term/doclist data fits on a single leaf page. If this is not the case,
192118  **     the format is changed in two ways:
192119  **
192120  **       + if the first rowid on a page occurs before the first term, it
192121  **         is stored as a literal value:
192122  **
192123  **             varint:  first rowid
192124  **
192125  **       + the first term on each page is stored in the same way as the
192126  **         very first term of the segment:
192127  **
192128  **             varint : size of first term
192129  **             blob:    first term data
192130  **
192131  ** 5. Segment doclist indexes:
192132  **
192133  **   Doclist indexes are themselves b-trees, however they usually consist of
192134  **   a single leaf record only. The format of each doclist index leaf page 
192135  **   is:
192136  **
192137  **     * Flags byte. Bits are:
192138  **         0x01: Clear if leaf is also the root page, otherwise set.
192139  **
192140  **     * Page number of fts index leaf page. As a varint.
192141  **
192142  **     * First rowid on page indicated by previous field. As a varint.
192143  **
192144  **     * A list of varints, one for each subsequent termless page. A 
192145  **       positive delta if the termless page contains at least one rowid, 
192146  **       or an 0x00 byte otherwise.
192147  **
192148  **   Internal doclist index nodes are:
192149  **
192150  **     * Flags byte. Bits are:
192151  **         0x01: Clear for root page, otherwise set.
192152  **
192153  **     * Page number of first child page. As a varint.
192154  **
192155  **     * Copy of first rowid on page indicated by previous field. As a varint.
192156  **
192157  **     * A list of delta-encoded varints - the first rowid on each subsequent
192158  **       child page. 
192159  **
192160  */
192161  
192162  /*
192163  ** Rowids for the averages and structure records in the %_data table.
192164  */
192165  #define FTS5_AVERAGES_ROWID     1    /* Rowid used for the averages record */
192166  #define FTS5_STRUCTURE_ROWID   10    /* The structure record */
192167  
192168  /*
192169  ** Macros determining the rowids used by segment leaves and dlidx leaves
192170  ** and nodes. All nodes and leaves are stored in the %_data table with large
192171  ** positive rowids.
192172  **
192173  ** Each segment has a unique non-zero 16-bit id.
192174  **
192175  ** The rowid for each segment leaf is found by passing the segment id and 
192176  ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
192177  ** sequentially starting from 1.
192178  */
192179  #define FTS5_DATA_ID_B     16     /* Max seg id number 65535 */
192180  #define FTS5_DATA_DLI_B     1     /* Doclist-index flag (1 bit) */
192181  #define FTS5_DATA_HEIGHT_B  5     /* Max dlidx tree height of 32 */
192182  #define FTS5_DATA_PAGE_B   31     /* Max page number of 2147483648 */
192183  
192184  #define fts5_dri(segid, dlidx, height, pgno) (                                 \
192185   ((i64)(segid)  << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) +    \
192186   ((i64)(dlidx)  << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) +                  \
192187   ((i64)(height) << (FTS5_DATA_PAGE_B)) +                                       \
192188   ((i64)(pgno))                                                                 \
192189  )
192190  
192191  #define FTS5_SEGMENT_ROWID(segid, pgno)       fts5_dri(segid, 0, 0, pgno)
192192  #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
192193  
192194  /*
192195  ** Maximum segments permitted in a single index 
192196  */
192197  #define FTS5_MAX_SEGMENT 2000
192198  
192199  #ifdef SQLITE_DEBUG
192200  static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
192201  #endif
192202  
192203  
192204  /*
192205  ** Each time a blob is read from the %_data table, it is padded with this
192206  ** many zero bytes. This makes it easier to decode the various record formats
192207  ** without overreading if the records are corrupt.
192208  */
192209  #define FTS5_DATA_ZERO_PADDING 8
192210  #define FTS5_DATA_PADDING 20
192211  
192212  typedef struct Fts5Data Fts5Data;
192213  typedef struct Fts5DlidxIter Fts5DlidxIter;
192214  typedef struct Fts5DlidxLvl Fts5DlidxLvl;
192215  typedef struct Fts5DlidxWriter Fts5DlidxWriter;
192216  typedef struct Fts5Iter Fts5Iter;
192217  typedef struct Fts5PageWriter Fts5PageWriter;
192218  typedef struct Fts5SegIter Fts5SegIter;
192219  typedef struct Fts5DoclistIter Fts5DoclistIter;
192220  typedef struct Fts5SegWriter Fts5SegWriter;
192221  typedef struct Fts5Structure Fts5Structure;
192222  typedef struct Fts5StructureLevel Fts5StructureLevel;
192223  typedef struct Fts5StructureSegment Fts5StructureSegment;
192224  
192225  struct Fts5Data {
192226    u8 *p;                          /* Pointer to buffer containing record */
192227    int nn;                         /* Size of record in bytes */
192228    int szLeaf;                     /* Size of leaf without page-index */
192229  };
192230  
192231  /*
192232  ** One object per %_data table.
192233  */
192234  struct Fts5Index {
192235    Fts5Config *pConfig;            /* Virtual table configuration */
192236    char *zDataTbl;                 /* Name of %_data table */
192237    int nWorkUnit;                  /* Leaf pages in a "unit" of work */
192238  
192239    /*
192240    ** Variables related to the accumulation of tokens and doclists within the
192241    ** in-memory hash tables before they are flushed to disk.
192242    */
192243    Fts5Hash *pHash;                /* Hash table for in-memory data */
192244    int nPendingData;               /* Current bytes of pending data */
192245    i64 iWriteRowid;                /* Rowid for current doc being written */
192246    int bDelete;                    /* Current write is a delete */
192247  
192248    /* Error state. */
192249    int rc;                         /* Current error code */
192250  
192251    /* State used by the fts5DataXXX() functions. */
192252    sqlite3_blob *pReader;          /* RO incr-blob open on %_data table */
192253    sqlite3_stmt *pWriter;          /* "INSERT ... %_data VALUES(?,?)" */
192254    sqlite3_stmt *pDeleter;         /* "DELETE FROM %_data ... id>=? AND id<=?" */
192255    sqlite3_stmt *pIdxWriter;       /* "INSERT ... %_idx VALUES(?,?,?,?)" */
192256    sqlite3_stmt *pIdxDeleter;      /* "DELETE FROM %_idx WHERE segid=? */
192257    sqlite3_stmt *pIdxSelect;
192258    int nRead;                      /* Total number of blocks read */
192259  
192260    sqlite3_stmt *pDataVersion;
192261    i64 iStructVersion;             /* data_version when pStruct read */
192262    Fts5Structure *pStruct;         /* Current db structure (or NULL) */
192263  };
192264  
192265  struct Fts5DoclistIter {
192266    u8 *aEof;                       /* Pointer to 1 byte past end of doclist */
192267  
192268    /* Output variables. aPoslist==0 at EOF */
192269    i64 iRowid;
192270    u8 *aPoslist;
192271    int nPoslist;
192272    int nSize;
192273  };
192274  
192275  /*
192276  ** The contents of the "structure" record for each index are represented
192277  ** using an Fts5Structure record in memory. Which uses instances of the 
192278  ** other Fts5StructureXXX types as components.
192279  */
192280  struct Fts5StructureSegment {
192281    int iSegid;                     /* Segment id */
192282    int pgnoFirst;                  /* First leaf page number in segment */
192283    int pgnoLast;                   /* Last leaf page number in segment */
192284  };
192285  struct Fts5StructureLevel {
192286    int nMerge;                     /* Number of segments in incr-merge */
192287    int nSeg;                       /* Total number of segments on level */
192288    Fts5StructureSegment *aSeg;     /* Array of segments. aSeg[0] is oldest. */
192289  };
192290  struct Fts5Structure {
192291    int nRef;                       /* Object reference count */
192292    u64 nWriteCounter;              /* Total leaves written to level 0 */
192293    int nSegment;                   /* Total segments in this structure */
192294    int nLevel;                     /* Number of levels in this index */
192295    Fts5StructureLevel aLevel[1];   /* Array of nLevel level objects */
192296  };
192297  
192298  /*
192299  ** An object of type Fts5SegWriter is used to write to segments.
192300  */
192301  struct Fts5PageWriter {
192302    int pgno;                       /* Page number for this page */
192303    int iPrevPgidx;                 /* Previous value written into pgidx */
192304    Fts5Buffer buf;                 /* Buffer containing leaf data */
192305    Fts5Buffer pgidx;               /* Buffer containing page-index */
192306    Fts5Buffer term;                /* Buffer containing previous term on page */
192307  };
192308  struct Fts5DlidxWriter {
192309    int pgno;                       /* Page number for this page */
192310    int bPrevValid;                 /* True if iPrev is valid */
192311    i64 iPrev;                      /* Previous rowid value written to page */
192312    Fts5Buffer buf;                 /* Buffer containing page data */
192313  };
192314  struct Fts5SegWriter {
192315    int iSegid;                     /* Segid to write to */
192316    Fts5PageWriter writer;          /* PageWriter object */
192317    i64 iPrevRowid;                 /* Previous rowid written to current leaf */
192318    u8 bFirstRowidInDoclist;        /* True if next rowid is first in doclist */
192319    u8 bFirstRowidInPage;           /* True if next rowid is first in page */
192320    /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
192321    u8 bFirstTermInPage;            /* True if next term will be first in leaf */
192322    int nLeafWritten;               /* Number of leaf pages written */
192323    int nEmpty;                     /* Number of contiguous term-less nodes */
192324  
192325    int nDlidx;                     /* Allocated size of aDlidx[] array */
192326    Fts5DlidxWriter *aDlidx;        /* Array of Fts5DlidxWriter objects */
192327  
192328    /* Values to insert into the %_idx table */
192329    Fts5Buffer btterm;              /* Next term to insert into %_idx table */
192330    int iBtPage;                    /* Page number corresponding to btterm */
192331  };
192332  
192333  typedef struct Fts5CResult Fts5CResult;
192334  struct Fts5CResult {
192335    u16 iFirst;                     /* aSeg[] index of firstest iterator */
192336    u8 bTermEq;                     /* True if the terms are equal */
192337  };
192338  
192339  /*
192340  ** Object for iterating through a single segment, visiting each term/rowid
192341  ** pair in the segment.
192342  **
192343  ** pSeg:
192344  **   The segment to iterate through.
192345  **
192346  ** iLeafPgno:
192347  **   Current leaf page number within segment.
192348  **
192349  ** iLeafOffset:
192350  **   Byte offset within the current leaf that is the first byte of the 
192351  **   position list data (one byte passed the position-list size field).
192352  **   rowid field of the current entry. Usually this is the size field of the
192353  **   position list data. The exception is if the rowid for the current entry 
192354  **   is the last thing on the leaf page.
192355  **
192356  ** pLeaf:
192357  **   Buffer containing current leaf page data. Set to NULL at EOF.
192358  **
192359  ** iTermLeafPgno, iTermLeafOffset:
192360  **   Leaf page number containing the last term read from the segment. And
192361  **   the offset immediately following the term data.
192362  **
192363  ** flags:
192364  **   Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
192365  **
192366  **   FTS5_SEGITER_ONETERM:
192367  **     If set, set the iterator to point to EOF after the current doclist 
192368  **     has been exhausted. Do not proceed to the next term in the segment.
192369  **
192370  **   FTS5_SEGITER_REVERSE:
192371  **     This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
192372  **     it is set, iterate through rowid in descending order instead of the
192373  **     default ascending order.
192374  **
192375  ** iRowidOffset/nRowidOffset/aRowidOffset:
192376  **     These are used if the FTS5_SEGITER_REVERSE flag is set.
192377  **
192378  **     For each rowid on the page corresponding to the current term, the
192379  **     corresponding aRowidOffset[] entry is set to the byte offset of the
192380  **     start of the "position-list-size" field within the page.
192381  **
192382  ** iTermIdx:
192383  **     Index of current term on iTermLeafPgno.
192384  */
192385  struct Fts5SegIter {
192386    Fts5StructureSegment *pSeg;     /* Segment to iterate through */
192387    int flags;                      /* Mask of configuration flags */
192388    int iLeafPgno;                  /* Current leaf page number */
192389    Fts5Data *pLeaf;                /* Current leaf data */
192390    Fts5Data *pNextLeaf;            /* Leaf page (iLeafPgno+1) */
192391    int iLeafOffset;                /* Byte offset within current leaf */
192392  
192393    /* Next method */
192394    void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
192395  
192396    /* The page and offset from which the current term was read. The offset 
192397    ** is the offset of the first rowid in the current doclist.  */
192398    int iTermLeafPgno;
192399    int iTermLeafOffset;
192400  
192401    int iPgidxOff;                  /* Next offset in pgidx */
192402    int iEndofDoclist;
192403  
192404    /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
192405    int iRowidOffset;               /* Current entry in aRowidOffset[] */
192406    int nRowidOffset;               /* Allocated size of aRowidOffset[] array */
192407    int *aRowidOffset;              /* Array of offset to rowid fields */
192408  
192409    Fts5DlidxIter *pDlidx;          /* If there is a doclist-index */
192410  
192411    /* Variables populated based on current entry. */
192412    Fts5Buffer term;                /* Current term */
192413    i64 iRowid;                     /* Current rowid */
192414    int nPos;                       /* Number of bytes in current position list */
192415    u8 bDel;                        /* True if the delete flag is set */
192416  };
192417  
192418  /*
192419  ** Argument is a pointer to an Fts5Data structure that contains a 
192420  ** leaf page.
192421  */
192422  #define ASSERT_SZLEAF_OK(x) assert( \
192423      (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
192424  )
192425  
192426  #define FTS5_SEGITER_ONETERM 0x01
192427  #define FTS5_SEGITER_REVERSE 0x02
192428  
192429  /* 
192430  ** Argument is a pointer to an Fts5Data structure that contains a leaf
192431  ** page. This macro evaluates to true if the leaf contains no terms, or
192432  ** false if it contains at least one term.
192433  */
192434  #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
192435  
192436  #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
192437  
192438  #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
192439  
192440  /*
192441  ** Object for iterating through the merged results of one or more segments,
192442  ** visiting each term/rowid pair in the merged data.
192443  **
192444  ** nSeg is always a power of two greater than or equal to the number of
192445  ** segments that this object is merging data from. Both the aSeg[] and
192446  ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
192447  ** with zeroed objects - these are handled as if they were iterators opened
192448  ** on empty segments.
192449  **
192450  ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
192451  ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the 
192452  ** comparison in this context is the index of the iterator that currently
192453  ** points to the smaller term/rowid combination. Iterators at EOF are
192454  ** considered to be greater than all other iterators.
192455  **
192456  ** aFirst[1] contains the index in aSeg[] of the iterator that points to
192457  ** the smallest key overall. aFirst[0] is unused. 
192458  **
192459  ** poslist:
192460  **   Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
192461  **   There is no way to tell if this is populated or not.
192462  */
192463  struct Fts5Iter {
192464    Fts5IndexIter base;             /* Base class containing output vars */
192465  
192466    Fts5Index *pIndex;              /* Index that owns this iterator */
192467    Fts5Structure *pStruct;         /* Database structure for this iterator */
192468    Fts5Buffer poslist;             /* Buffer containing current poslist */
192469    Fts5Colset *pColset;            /* Restrict matches to these columns */
192470  
192471    /* Invoked to set output variables. */
192472    void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
192473  
192474    int nSeg;                       /* Size of aSeg[] array */
192475    int bRev;                       /* True to iterate in reverse order */
192476    u8 bSkipEmpty;                  /* True to skip deleted entries */
192477  
192478    i64 iSwitchRowid;               /* Firstest rowid of other than aFirst[1] */
192479    Fts5CResult *aFirst;            /* Current merge state (see above) */
192480    Fts5SegIter aSeg[1];            /* Array of segment iterators */
192481  };
192482  
192483  
192484  /*
192485  ** An instance of the following type is used to iterate through the contents
192486  ** of a doclist-index record.
192487  **
192488  ** pData:
192489  **   Record containing the doclist-index data.
192490  **
192491  ** bEof:
192492  **   Set to true once iterator has reached EOF.
192493  **
192494  ** iOff:
192495  **   Set to the current offset within record pData.
192496  */
192497  struct Fts5DlidxLvl {
192498    Fts5Data *pData;              /* Data for current page of this level */
192499    int iOff;                     /* Current offset into pData */
192500    int bEof;                     /* At EOF already */
192501    int iFirstOff;                /* Used by reverse iterators */
192502  
192503    /* Output variables */
192504    int iLeafPgno;                /* Page number of current leaf page */
192505    i64 iRowid;                   /* First rowid on leaf iLeafPgno */
192506  };
192507  struct Fts5DlidxIter {
192508    int nLvl;
192509    int iSegid;
192510    Fts5DlidxLvl aLvl[1];
192511  };
192512  
192513  static void fts5PutU16(u8 *aOut, u16 iVal){
192514    aOut[0] = (iVal>>8);
192515    aOut[1] = (iVal&0xFF);
192516  }
192517  
192518  static u16 fts5GetU16(const u8 *aIn){
192519    return ((u16)aIn[0] << 8) + aIn[1];
192520  } 
192521  
192522  /*
192523  ** Allocate and return a buffer at least nByte bytes in size.
192524  **
192525  ** If an OOM error is encountered, return NULL and set the error code in
192526  ** the Fts5Index handle passed as the first argument.
192527  */
192528  static void *fts5IdxMalloc(Fts5Index *p, int nByte){
192529    return sqlite3Fts5MallocZero(&p->rc, nByte);
192530  }
192531  
192532  /*
192533  ** Compare the contents of the pLeft buffer with the pRight/nRight blob.
192534  **
192535  ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
192536  ** +ve if pRight is smaller than pLeft. In other words:
192537  **
192538  **     res = *pLeft - *pRight
192539  */
192540  #ifdef SQLITE_DEBUG
192541  static int fts5BufferCompareBlob(
192542    Fts5Buffer *pLeft,              /* Left hand side of comparison */
192543    const u8 *pRight, int nRight    /* Right hand side of comparison */
192544  ){
192545    int nCmp = MIN(pLeft->n, nRight);
192546    int res = memcmp(pLeft->p, pRight, nCmp);
192547    return (res==0 ? (pLeft->n - nRight) : res);
192548  }
192549  #endif
192550  
192551  /*
192552  ** Compare the contents of the two buffers using memcmp(). If one buffer
192553  ** is a prefix of the other, it is considered the lesser.
192554  **
192555  ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
192556  ** +ve if pRight is smaller than pLeft. In other words:
192557  **
192558  **     res = *pLeft - *pRight
192559  */
192560  static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
192561    int nCmp = MIN(pLeft->n, pRight->n);
192562    int res = memcmp(pLeft->p, pRight->p, nCmp);
192563    return (res==0 ? (pLeft->n - pRight->n) : res);
192564  }
192565  
192566  static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
192567    int ret;
192568    fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
192569    return ret;
192570  }
192571  
192572  /*
192573  ** Close the read-only blob handle, if it is open.
192574  */
192575  static void fts5CloseReader(Fts5Index *p){
192576    if( p->pReader ){
192577      sqlite3_blob *pReader = p->pReader;
192578      p->pReader = 0;
192579      sqlite3_blob_close(pReader);
192580    }
192581  }
192582  
192583  /*
192584  ** Retrieve a record from the %_data table.
192585  **
192586  ** If an error occurs, NULL is returned and an error left in the 
192587  ** Fts5Index object.
192588  */
192589  static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
192590    Fts5Data *pRet = 0;
192591    if( p->rc==SQLITE_OK ){
192592      int rc = SQLITE_OK;
192593  
192594      if( p->pReader ){
192595        /* This call may return SQLITE_ABORT if there has been a savepoint
192596        ** rollback since it was last used. In this case a new blob handle
192597        ** is required.  */
192598        sqlite3_blob *pBlob = p->pReader;
192599        p->pReader = 0;
192600        rc = sqlite3_blob_reopen(pBlob, iRowid);
192601        assert( p->pReader==0 );
192602        p->pReader = pBlob;
192603        if( rc!=SQLITE_OK ){
192604          fts5CloseReader(p);
192605        }
192606        if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
192607      }
192608  
192609      /* If the blob handle is not open at this point, open it and seek 
192610      ** to the requested entry.  */
192611      if( p->pReader==0 && rc==SQLITE_OK ){
192612        Fts5Config *pConfig = p->pConfig;
192613        rc = sqlite3_blob_open(pConfig->db, 
192614            pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
192615        );
192616      }
192617  
192618      /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
192619      ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
192620      ** All the reasons those functions might return SQLITE_ERROR - missing
192621      ** table, missing row, non-blob/text in block column - indicate 
192622      ** backing store corruption.  */
192623      if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
192624  
192625      if( rc==SQLITE_OK ){
192626        u8 *aOut = 0;               /* Read blob data into this buffer */
192627        int nByte = sqlite3_blob_bytes(p->pReader);
192628        int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
192629        pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
192630        if( pRet ){
192631          pRet->nn = nByte;
192632          aOut = pRet->p = (u8*)&pRet[1];
192633        }else{
192634          rc = SQLITE_NOMEM;
192635        }
192636  
192637        if( rc==SQLITE_OK ){
192638          rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
192639        }
192640        if( rc!=SQLITE_OK ){
192641          sqlite3_free(pRet);
192642          pRet = 0;
192643        }else{
192644          /* TODO1: Fix this */
192645          pRet->szLeaf = fts5GetU16(&pRet->p[2]);
192646        }
192647      }
192648      p->rc = rc;
192649      p->nRead++;
192650    }
192651  
192652    assert( (pRet==0)==(p->rc!=SQLITE_OK) );
192653    return pRet;
192654  }
192655  
192656  /*
192657  ** Release a reference to data record returned by an earlier call to
192658  ** fts5DataRead().
192659  */
192660  static void fts5DataRelease(Fts5Data *pData){
192661    sqlite3_free(pData);
192662  }
192663  
192664  static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
192665    Fts5Data *pRet = fts5DataRead(p, iRowid);
192666    if( pRet ){
192667      if( pRet->szLeaf>pRet->nn ){
192668        p->rc = FTS5_CORRUPT;
192669        fts5DataRelease(pRet);
192670        pRet = 0;
192671      }
192672    }
192673    return pRet;
192674  }
192675  
192676  static int fts5IndexPrepareStmt(
192677    Fts5Index *p,
192678    sqlite3_stmt **ppStmt,
192679    char *zSql
192680  ){
192681    if( p->rc==SQLITE_OK ){
192682      if( zSql ){
192683        p->rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1,
192684                                   SQLITE_PREPARE_PERSISTENT, ppStmt, 0);
192685      }else{
192686        p->rc = SQLITE_NOMEM;
192687      }
192688    }
192689    sqlite3_free(zSql);
192690    return p->rc;
192691  }
192692  
192693  
192694  /*
192695  ** INSERT OR REPLACE a record into the %_data table.
192696  */
192697  static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
192698    if( p->rc!=SQLITE_OK ) return;
192699  
192700    if( p->pWriter==0 ){
192701      Fts5Config *pConfig = p->pConfig;
192702      fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
192703            "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)", 
192704            pConfig->zDb, pConfig->zName
192705      ));
192706      if( p->rc ) return;
192707    }
192708  
192709    sqlite3_bind_int64(p->pWriter, 1, iRowid);
192710    sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
192711    sqlite3_step(p->pWriter);
192712    p->rc = sqlite3_reset(p->pWriter);
192713  }
192714  
192715  /*
192716  ** Execute the following SQL:
192717  **
192718  **     DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
192719  */
192720  static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
192721    if( p->rc!=SQLITE_OK ) return;
192722  
192723    if( p->pDeleter==0 ){
192724      int rc;
192725      Fts5Config *pConfig = p->pConfig;
192726      char *zSql = sqlite3_mprintf(
192727          "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?", 
192728            pConfig->zDb, pConfig->zName
192729      );
192730      if( zSql==0 ){
192731        rc = SQLITE_NOMEM;
192732      }else{
192733        rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
192734                                SQLITE_PREPARE_PERSISTENT, &p->pDeleter, 0);
192735        sqlite3_free(zSql);
192736      }
192737      if( rc!=SQLITE_OK ){
192738        p->rc = rc;
192739        return;
192740      }
192741    }
192742  
192743    sqlite3_bind_int64(p->pDeleter, 1, iFirst);
192744    sqlite3_bind_int64(p->pDeleter, 2, iLast);
192745    sqlite3_step(p->pDeleter);
192746    p->rc = sqlite3_reset(p->pDeleter);
192747  }
192748  
192749  /*
192750  ** Remove all records associated with segment iSegid.
192751  */
192752  static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
192753    i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
192754    i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
192755    fts5DataDelete(p, iFirst, iLast);
192756    if( p->pIdxDeleter==0 ){
192757      Fts5Config *pConfig = p->pConfig;
192758      fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
192759            "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
192760            pConfig->zDb, pConfig->zName
192761      ));
192762    }
192763    if( p->rc==SQLITE_OK ){
192764      sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
192765      sqlite3_step(p->pIdxDeleter);
192766      p->rc = sqlite3_reset(p->pIdxDeleter);
192767    }
192768  }
192769  
192770  /*
192771  ** Release a reference to an Fts5Structure object returned by an earlier 
192772  ** call to fts5StructureRead() or fts5StructureDecode().
192773  */
192774  static void fts5StructureRelease(Fts5Structure *pStruct){
192775    if( pStruct && 0>=(--pStruct->nRef) ){
192776      int i;
192777      assert( pStruct->nRef==0 );
192778      for(i=0; i<pStruct->nLevel; i++){
192779        sqlite3_free(pStruct->aLevel[i].aSeg);
192780      }
192781      sqlite3_free(pStruct);
192782    }
192783  }
192784  
192785  static void fts5StructureRef(Fts5Structure *pStruct){
192786    pStruct->nRef++;
192787  }
192788  
192789  /*
192790  ** Deserialize and return the structure record currently stored in serialized
192791  ** form within buffer pData/nData.
192792  **
192793  ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
192794  ** are over-allocated by one slot. This allows the structure contents
192795  ** to be more easily edited.
192796  **
192797  ** If an error occurs, *ppOut is set to NULL and an SQLite error code
192798  ** returned. Otherwise, *ppOut is set to point to the new object and
192799  ** SQLITE_OK returned.
192800  */
192801  static int fts5StructureDecode(
192802    const u8 *pData,                /* Buffer containing serialized structure */
192803    int nData,                      /* Size of buffer pData in bytes */
192804    int *piCookie,                  /* Configuration cookie value */
192805    Fts5Structure **ppOut           /* OUT: Deserialized object */
192806  ){
192807    int rc = SQLITE_OK;
192808    int i = 0;
192809    int iLvl;
192810    int nLevel = 0;
192811    int nSegment = 0;
192812    int nByte;                      /* Bytes of space to allocate at pRet */
192813    Fts5Structure *pRet = 0;        /* Structure object to return */
192814  
192815    /* Grab the cookie value */
192816    if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
192817    i = 4;
192818  
192819    /* Read the total number of levels and segments from the start of the
192820    ** structure record.  */
192821    i += fts5GetVarint32(&pData[i], nLevel);
192822    i += fts5GetVarint32(&pData[i], nSegment);
192823    nByte = (
192824        sizeof(Fts5Structure) +                    /* Main structure */
192825        sizeof(Fts5StructureLevel) * (nLevel-1)    /* aLevel[] array */
192826    );
192827    pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
192828  
192829    if( pRet ){
192830      pRet->nRef = 1;
192831      pRet->nLevel = nLevel;
192832      pRet->nSegment = nSegment;
192833      i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
192834  
192835      for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
192836        Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
192837        int nTotal = 0;
192838        int iSeg;
192839  
192840        if( i>=nData ){
192841          rc = FTS5_CORRUPT;
192842        }else{
192843          i += fts5GetVarint32(&pData[i], pLvl->nMerge);
192844          i += fts5GetVarint32(&pData[i], nTotal);
192845          assert( nTotal>=pLvl->nMerge );
192846          pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc, 
192847              nTotal * sizeof(Fts5StructureSegment)
192848          );
192849        }
192850  
192851        if( rc==SQLITE_OK ){
192852          pLvl->nSeg = nTotal;
192853          for(iSeg=0; iSeg<nTotal; iSeg++){
192854            if( i>=nData ){
192855              rc = FTS5_CORRUPT;
192856              break;
192857            }
192858            i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
192859            i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
192860            i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
192861          }
192862        }
192863      }
192864      if( rc!=SQLITE_OK ){
192865        fts5StructureRelease(pRet);
192866        pRet = 0;
192867      }
192868    }
192869  
192870    *ppOut = pRet;
192871    return rc;
192872  }
192873  
192874  /*
192875  **
192876  */
192877  static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
192878    if( *pRc==SQLITE_OK ){
192879      Fts5Structure *pStruct = *ppStruct;
192880      int nLevel = pStruct->nLevel;
192881      int nByte = (
192882          sizeof(Fts5Structure) +                  /* Main structure */
192883          sizeof(Fts5StructureLevel) * (nLevel+1)  /* aLevel[] array */
192884      );
192885  
192886      pStruct = sqlite3_realloc(pStruct, nByte);
192887      if( pStruct ){
192888        memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
192889        pStruct->nLevel++;
192890        *ppStruct = pStruct;
192891      }else{
192892        *pRc = SQLITE_NOMEM;
192893      }
192894    }
192895  }
192896  
192897  /*
192898  ** Extend level iLvl so that there is room for at least nExtra more
192899  ** segments.
192900  */
192901  static void fts5StructureExtendLevel(
192902    int *pRc, 
192903    Fts5Structure *pStruct, 
192904    int iLvl, 
192905    int nExtra, 
192906    int bInsert
192907  ){
192908    if( *pRc==SQLITE_OK ){
192909      Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
192910      Fts5StructureSegment *aNew;
192911      int nByte;
192912  
192913      nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
192914      aNew = sqlite3_realloc(pLvl->aSeg, nByte);
192915      if( aNew ){
192916        if( bInsert==0 ){
192917          memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
192918        }else{
192919          int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
192920          memmove(&aNew[nExtra], aNew, nMove);
192921          memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
192922        }
192923        pLvl->aSeg = aNew;
192924      }else{
192925        *pRc = SQLITE_NOMEM;
192926      }
192927    }
192928  }
192929  
192930  static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
192931    Fts5Structure *pRet = 0;
192932    Fts5Config *pConfig = p->pConfig;
192933    int iCookie;                    /* Configuration cookie */
192934    Fts5Data *pData;
192935  
192936    pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
192937    if( p->rc==SQLITE_OK ){
192938      /* TODO: Do we need this if the leaf-index is appended? Probably... */
192939      memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
192940      p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
192941      if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
192942        p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
192943      }
192944      fts5DataRelease(pData);
192945      if( p->rc!=SQLITE_OK ){
192946        fts5StructureRelease(pRet);
192947        pRet = 0;
192948      }
192949    }
192950  
192951    return pRet;
192952  }
192953  
192954  static i64 fts5IndexDataVersion(Fts5Index *p){
192955    i64 iVersion = 0;
192956  
192957    if( p->rc==SQLITE_OK ){
192958      if( p->pDataVersion==0 ){
192959        p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion, 
192960            sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
192961            );
192962        if( p->rc ) return 0;
192963      }
192964  
192965      if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
192966        iVersion = sqlite3_column_int64(p->pDataVersion, 0);
192967      }
192968      p->rc = sqlite3_reset(p->pDataVersion);
192969    }
192970  
192971    return iVersion;
192972  }
192973  
192974  /*
192975  ** Read, deserialize and return the structure record.
192976  **
192977  ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
192978  ** are over-allocated as described for function fts5StructureDecode() 
192979  ** above.
192980  **
192981  ** If an error occurs, NULL is returned and an error code left in the
192982  ** Fts5Index handle. If an error has already occurred when this function
192983  ** is called, it is a no-op.
192984  */
192985  static Fts5Structure *fts5StructureRead(Fts5Index *p){
192986  
192987    if( p->pStruct==0 ){
192988      p->iStructVersion = fts5IndexDataVersion(p);
192989      if( p->rc==SQLITE_OK ){
192990        p->pStruct = fts5StructureReadUncached(p);
192991      }
192992    }
192993  
192994  #if 0
192995    else{
192996      Fts5Structure *pTest = fts5StructureReadUncached(p);
192997      if( pTest ){
192998        int i, j;
192999        assert_nc( p->pStruct->nSegment==pTest->nSegment );
193000        assert_nc( p->pStruct->nLevel==pTest->nLevel );
193001        for(i=0; i<pTest->nLevel; i++){
193002          assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
193003          assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
193004          for(j=0; j<pTest->aLevel[i].nSeg; j++){
193005            Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
193006            Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
193007            assert_nc( p1->iSegid==p2->iSegid );
193008            assert_nc( p1->pgnoFirst==p2->pgnoFirst );
193009            assert_nc( p1->pgnoLast==p2->pgnoLast );
193010          }
193011        }
193012        fts5StructureRelease(pTest);
193013      }
193014    }
193015  #endif
193016  
193017    if( p->rc!=SQLITE_OK ) return 0;
193018    assert( p->iStructVersion!=0 );
193019    assert( p->pStruct!=0 );
193020    fts5StructureRef(p->pStruct);
193021    return p->pStruct;
193022  }
193023  
193024  static void fts5StructureInvalidate(Fts5Index *p){
193025    if( p->pStruct ){
193026      fts5StructureRelease(p->pStruct);
193027      p->pStruct = 0;
193028    }
193029  }
193030  
193031  /*
193032  ** Return the total number of segments in index structure pStruct. This
193033  ** function is only ever used as part of assert() conditions.
193034  */
193035  #ifdef SQLITE_DEBUG
193036  static int fts5StructureCountSegments(Fts5Structure *pStruct){
193037    int nSegment = 0;               /* Total number of segments */
193038    if( pStruct ){
193039      int iLvl;                     /* Used to iterate through levels */
193040      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
193041        nSegment += pStruct->aLevel[iLvl].nSeg;
193042      }
193043    }
193044  
193045    return nSegment;
193046  }
193047  #endif
193048  
193049  #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) {     \
193050    assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) );             \
193051    memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob);             \
193052    (pBuf)->n += nBlob;                                      \
193053  }
193054  
193055  #define fts5BufferSafeAppendVarint(pBuf, iVal) {                \
193056    (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal));  \
193057    assert( (pBuf)->nSpace>=(pBuf)->n );                          \
193058  }
193059  
193060  
193061  /*
193062  ** Serialize and store the "structure" record.
193063  **
193064  ** If an error occurs, leave an error code in the Fts5Index object. If an
193065  ** error has already occurred, this function is a no-op.
193066  */
193067  static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
193068    if( p->rc==SQLITE_OK ){
193069      Fts5Buffer buf;               /* Buffer to serialize record into */
193070      int iLvl;                     /* Used to iterate through levels */
193071      int iCookie;                  /* Cookie value to store */
193072  
193073      assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
193074      memset(&buf, 0, sizeof(Fts5Buffer));
193075  
193076      /* Append the current configuration cookie */
193077      iCookie = p->pConfig->iCookie;
193078      if( iCookie<0 ) iCookie = 0;
193079  
193080      if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
193081        sqlite3Fts5Put32(buf.p, iCookie);
193082        buf.n = 4;
193083        fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
193084        fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
193085        fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
193086      }
193087  
193088      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
193089        int iSeg;                     /* Used to iterate through segments */
193090        Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
193091        fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
193092        fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
193093        assert( pLvl->nMerge<=pLvl->nSeg );
193094  
193095        for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
193096          fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
193097          fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
193098          fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
193099        }
193100      }
193101  
193102      fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
193103      fts5BufferFree(&buf);
193104    }
193105  }
193106  
193107  #if 0
193108  static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
193109  static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
193110    int rc = SQLITE_OK;
193111    Fts5Buffer buf;
193112    memset(&buf, 0, sizeof(buf));
193113    fts5DebugStructure(&rc, &buf, pStruct);
193114    fprintf(stdout, "%s: %s\n", zCaption, buf.p);
193115    fflush(stdout);
193116    fts5BufferFree(&buf);
193117  }
193118  #else
193119  # define fts5PrintStructure(x,y)
193120  #endif
193121  
193122  static int fts5SegmentSize(Fts5StructureSegment *pSeg){
193123    return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
193124  }
193125  
193126  /*
193127  ** Return a copy of index structure pStruct. Except, promote as many 
193128  ** segments as possible to level iPromote. If an OOM occurs, NULL is 
193129  ** returned.
193130  */
193131  static void fts5StructurePromoteTo(
193132    Fts5Index *p,
193133    int iPromote,
193134    int szPromote,
193135    Fts5Structure *pStruct
193136  ){
193137    int il, is;
193138    Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
193139  
193140    if( pOut->nMerge==0 ){
193141      for(il=iPromote+1; il<pStruct->nLevel; il++){
193142        Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
193143        if( pLvl->nMerge ) return;
193144        for(is=pLvl->nSeg-1; is>=0; is--){
193145          int sz = fts5SegmentSize(&pLvl->aSeg[is]);
193146          if( sz>szPromote ) return;
193147          fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
193148          if( p->rc ) return;
193149          memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
193150          pOut->nSeg++;
193151          pLvl->nSeg--;
193152        }
193153      }
193154    }
193155  }
193156  
193157  /*
193158  ** A new segment has just been written to level iLvl of index structure
193159  ** pStruct. This function determines if any segments should be promoted
193160  ** as a result. Segments are promoted in two scenarios:
193161  **
193162  **   a) If the segment just written is smaller than one or more segments
193163  **      within the previous populated level, it is promoted to the previous
193164  **      populated level.
193165  **
193166  **   b) If the segment just written is larger than the newest segment on
193167  **      the next populated level, then that segment, and any other adjacent
193168  **      segments that are also smaller than the one just written, are 
193169  **      promoted. 
193170  **
193171  ** If one or more segments are promoted, the structure object is updated
193172  ** to reflect this.
193173  */
193174  static void fts5StructurePromote(
193175    Fts5Index *p,                   /* FTS5 backend object */
193176    int iLvl,                       /* Index level just updated */
193177    Fts5Structure *pStruct          /* Index structure */
193178  ){
193179    if( p->rc==SQLITE_OK ){
193180      int iTst;
193181      int iPromote = -1;
193182      int szPromote = 0;            /* Promote anything this size or smaller */
193183      Fts5StructureSegment *pSeg;   /* Segment just written */
193184      int szSeg;                    /* Size of segment just written */
193185      int nSeg = pStruct->aLevel[iLvl].nSeg;
193186  
193187      if( nSeg==0 ) return;
193188      pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
193189      szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
193190  
193191      /* Check for condition (a) */
193192      for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
193193      if( iTst>=0 ){
193194        int i;
193195        int szMax = 0;
193196        Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
193197        assert( pTst->nMerge==0 );
193198        for(i=0; i<pTst->nSeg; i++){
193199          int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
193200          if( sz>szMax ) szMax = sz;
193201        }
193202        if( szMax>=szSeg ){
193203          /* Condition (a) is true. Promote the newest segment on level 
193204          ** iLvl to level iTst.  */
193205          iPromote = iTst;
193206          szPromote = szMax;
193207        }
193208      }
193209  
193210      /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
193211      ** is a no-op if it is not.  */
193212      if( iPromote<0 ){
193213        iPromote = iLvl;
193214        szPromote = szSeg;
193215      }
193216      fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
193217    }
193218  }
193219  
193220  
193221  /*
193222  ** Advance the iterator passed as the only argument. If the end of the 
193223  ** doclist-index page is reached, return non-zero.
193224  */
193225  static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
193226    Fts5Data *pData = pLvl->pData;
193227  
193228    if( pLvl->iOff==0 ){
193229      assert( pLvl->bEof==0 );
193230      pLvl->iOff = 1;
193231      pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
193232      pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
193233      pLvl->iFirstOff = pLvl->iOff;
193234    }else{
193235      int iOff;
193236      for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
193237        if( pData->p[iOff] ) break; 
193238      }
193239  
193240      if( iOff<pData->nn ){
193241        i64 iVal;
193242        pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
193243        iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
193244        pLvl->iRowid += iVal;
193245        pLvl->iOff = iOff;
193246      }else{
193247        pLvl->bEof = 1;
193248      }
193249    }
193250  
193251    return pLvl->bEof;
193252  }
193253  
193254  /*
193255  ** Advance the iterator passed as the only argument.
193256  */
193257  static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
193258    Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
193259  
193260    assert( iLvl<pIter->nLvl );
193261    if( fts5DlidxLvlNext(pLvl) ){
193262      if( (iLvl+1) < pIter->nLvl ){
193263        fts5DlidxIterNextR(p, pIter, iLvl+1);
193264        if( pLvl[1].bEof==0 ){
193265          fts5DataRelease(pLvl->pData);
193266          memset(pLvl, 0, sizeof(Fts5DlidxLvl));
193267          pLvl->pData = fts5DataRead(p, 
193268              FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
193269          );
193270          if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
193271        }
193272      }
193273    }
193274  
193275    return pIter->aLvl[0].bEof;
193276  }
193277  static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
193278    return fts5DlidxIterNextR(p, pIter, 0);
193279  }
193280  
193281  /*
193282  ** The iterator passed as the first argument has the following fields set
193283  ** as follows. This function sets up the rest of the iterator so that it
193284  ** points to the first rowid in the doclist-index.
193285  **
193286  **   pData:
193287  **     pointer to doclist-index record, 
193288  **
193289  ** When this function is called pIter->iLeafPgno is the page number the
193290  ** doclist is associated with (the one featuring the term).
193291  */
193292  static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
193293    int i;
193294    for(i=0; i<pIter->nLvl; i++){
193295      fts5DlidxLvlNext(&pIter->aLvl[i]);
193296    }
193297    return pIter->aLvl[0].bEof;
193298  }
193299  
193300  
193301  static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
193302    return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
193303  }
193304  
193305  static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
193306    int i;
193307  
193308    /* Advance each level to the last entry on the last page */
193309    for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
193310      Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
193311      while( fts5DlidxLvlNext(pLvl)==0 );
193312      pLvl->bEof = 0;
193313  
193314      if( i>0 ){
193315        Fts5DlidxLvl *pChild = &pLvl[-1];
193316        fts5DataRelease(pChild->pData);
193317        memset(pChild, 0, sizeof(Fts5DlidxLvl));
193318        pChild->pData = fts5DataRead(p, 
193319            FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
193320        );
193321      }
193322    }
193323  }
193324  
193325  /*
193326  ** Move the iterator passed as the only argument to the previous entry.
193327  */
193328  static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
193329    int iOff = pLvl->iOff;
193330  
193331    assert( pLvl->bEof==0 );
193332    if( iOff<=pLvl->iFirstOff ){
193333      pLvl->bEof = 1;
193334    }else{
193335      u8 *a = pLvl->pData->p;
193336      i64 iVal;
193337      int iLimit;
193338      int ii;
193339      int nZero = 0;
193340  
193341      /* Currently iOff points to the first byte of a varint. This block 
193342      ** decrements iOff until it points to the first byte of the previous 
193343      ** varint. Taking care not to read any memory locations that occur
193344      ** before the buffer in memory.  */
193345      iLimit = (iOff>9 ? iOff-9 : 0);
193346      for(iOff--; iOff>iLimit; iOff--){
193347        if( (a[iOff-1] & 0x80)==0 ) break;
193348      }
193349  
193350      fts5GetVarint(&a[iOff], (u64*)&iVal);
193351      pLvl->iRowid -= iVal;
193352      pLvl->iLeafPgno--;
193353  
193354      /* Skip backwards past any 0x00 varints. */
193355      for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
193356        nZero++;
193357      }
193358      if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
193359        /* The byte immediately before the last 0x00 byte has the 0x80 bit
193360        ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
193361        ** bytes before a[ii]. */
193362        int bZero = 0;              /* True if last 0x00 counts */
193363        if( (ii-8)>=pLvl->iFirstOff ){
193364          int j;
193365          for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
193366          bZero = (j>8);
193367        }
193368        if( bZero==0 ) nZero--;
193369      }
193370      pLvl->iLeafPgno -= nZero;
193371      pLvl->iOff = iOff - nZero;
193372    }
193373  
193374    return pLvl->bEof;
193375  }
193376  
193377  static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
193378    Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
193379  
193380    assert( iLvl<pIter->nLvl );
193381    if( fts5DlidxLvlPrev(pLvl) ){
193382      if( (iLvl+1) < pIter->nLvl ){
193383        fts5DlidxIterPrevR(p, pIter, iLvl+1);
193384        if( pLvl[1].bEof==0 ){
193385          fts5DataRelease(pLvl->pData);
193386          memset(pLvl, 0, sizeof(Fts5DlidxLvl));
193387          pLvl->pData = fts5DataRead(p, 
193388              FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
193389          );
193390          if( pLvl->pData ){
193391            while( fts5DlidxLvlNext(pLvl)==0 );
193392            pLvl->bEof = 0;
193393          }
193394        }
193395      }
193396    }
193397  
193398    return pIter->aLvl[0].bEof;
193399  }
193400  static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
193401    return fts5DlidxIterPrevR(p, pIter, 0);
193402  }
193403  
193404  /*
193405  ** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
193406  */
193407  static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
193408    if( pIter ){
193409      int i;
193410      for(i=0; i<pIter->nLvl; i++){
193411        fts5DataRelease(pIter->aLvl[i].pData);
193412      }
193413      sqlite3_free(pIter);
193414    }
193415  }
193416  
193417  static Fts5DlidxIter *fts5DlidxIterInit(
193418    Fts5Index *p,                   /* Fts5 Backend to iterate within */
193419    int bRev,                       /* True for ORDER BY ASC */
193420    int iSegid,                     /* Segment id */
193421    int iLeafPg                     /* Leaf page number to load dlidx for */
193422  ){
193423    Fts5DlidxIter *pIter = 0;
193424    int i;
193425    int bDone = 0;
193426  
193427    for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
193428      int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
193429      Fts5DlidxIter *pNew;
193430  
193431      pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
193432      if( pNew==0 ){
193433        p->rc = SQLITE_NOMEM;
193434      }else{
193435        i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
193436        Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
193437        pIter = pNew;
193438        memset(pLvl, 0, sizeof(Fts5DlidxLvl));
193439        pLvl->pData = fts5DataRead(p, iRowid);
193440        if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
193441          bDone = 1;
193442        }
193443        pIter->nLvl = i+1;
193444      }
193445    }
193446  
193447    if( p->rc==SQLITE_OK ){
193448      pIter->iSegid = iSegid;
193449      if( bRev==0 ){
193450        fts5DlidxIterFirst(pIter);
193451      }else{
193452        fts5DlidxIterLast(p, pIter);
193453      }
193454    }
193455  
193456    if( p->rc!=SQLITE_OK ){
193457      fts5DlidxIterFree(pIter);
193458      pIter = 0;
193459    }
193460  
193461    return pIter;
193462  }
193463  
193464  static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
193465    return pIter->aLvl[0].iRowid;
193466  }
193467  static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
193468    return pIter->aLvl[0].iLeafPgno;
193469  }
193470  
193471  /*
193472  ** Load the next leaf page into the segment iterator.
193473  */
193474  static void fts5SegIterNextPage(
193475    Fts5Index *p,                   /* FTS5 backend object */
193476    Fts5SegIter *pIter              /* Iterator to advance to next page */
193477  ){
193478    Fts5Data *pLeaf;
193479    Fts5StructureSegment *pSeg = pIter->pSeg;
193480    fts5DataRelease(pIter->pLeaf);
193481    pIter->iLeafPgno++;
193482    if( pIter->pNextLeaf ){
193483      pIter->pLeaf = pIter->pNextLeaf;
193484      pIter->pNextLeaf = 0;
193485    }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
193486      pIter->pLeaf = fts5LeafRead(p, 
193487          FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
193488      );
193489    }else{
193490      pIter->pLeaf = 0;
193491    }
193492    pLeaf = pIter->pLeaf;
193493  
193494    if( pLeaf ){
193495      pIter->iPgidxOff = pLeaf->szLeaf;
193496      if( fts5LeafIsTermless(pLeaf) ){
193497        pIter->iEndofDoclist = pLeaf->nn+1;
193498      }else{
193499        pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
193500            pIter->iEndofDoclist
193501        );
193502      }
193503    }
193504  }
193505  
193506  /*
193507  ** Argument p points to a buffer containing a varint to be interpreted as a
193508  ** position list size field. Read the varint and return the number of bytes
193509  ** read. Before returning, set *pnSz to the number of bytes in the position
193510  ** list, and *pbDel to true if the delete flag is set, or false otherwise.
193511  */
193512  static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
193513    int nSz;
193514    int n = 0;
193515    fts5FastGetVarint32(p, n, nSz);
193516    assert_nc( nSz>=0 );
193517    *pnSz = nSz/2;
193518    *pbDel = nSz & 0x0001;
193519    return n;
193520  }
193521  
193522  /*
193523  ** Fts5SegIter.iLeafOffset currently points to the first byte of a
193524  ** position-list size field. Read the value of the field and store it
193525  ** in the following variables:
193526  **
193527  **   Fts5SegIter.nPos
193528  **   Fts5SegIter.bDel
193529  **
193530  ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the 
193531  ** position list content (if any).
193532  */
193533  static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
193534    if( p->rc==SQLITE_OK ){
193535      int iOff = pIter->iLeafOffset;  /* Offset to read at */
193536      ASSERT_SZLEAF_OK(pIter->pLeaf);
193537      if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
193538        int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
193539        pIter->bDel = 0;
193540        pIter->nPos = 1;
193541        if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
193542          pIter->bDel = 1;
193543          iOff++;
193544          if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
193545            pIter->nPos = 1;
193546            iOff++;
193547          }else{
193548            pIter->nPos = 0;
193549          }
193550        }
193551      }else{
193552        int nSz;
193553        fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
193554        pIter->bDel = (nSz & 0x0001);
193555        pIter->nPos = nSz>>1;
193556        assert_nc( pIter->nPos>=0 );
193557      }
193558      pIter->iLeafOffset = iOff;
193559    }
193560  }
193561  
193562  static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
193563    u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
193564    int iOff = pIter->iLeafOffset;
193565  
193566    ASSERT_SZLEAF_OK(pIter->pLeaf);
193567    if( iOff>=pIter->pLeaf->szLeaf ){
193568      fts5SegIterNextPage(p, pIter);
193569      if( pIter->pLeaf==0 ){
193570        if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
193571        return;
193572      }
193573      iOff = 4;
193574      a = pIter->pLeaf->p;
193575    }
193576    iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
193577    pIter->iLeafOffset = iOff;
193578  }
193579  
193580  /*
193581  ** Fts5SegIter.iLeafOffset currently points to the first byte of the 
193582  ** "nSuffix" field of a term. Function parameter nKeep contains the value
193583  ** of the "nPrefix" field (if there was one - it is passed 0 if this is
193584  ** the first term in the segment).
193585  **
193586  ** This function populates:
193587  **
193588  **   Fts5SegIter.term
193589  **   Fts5SegIter.rowid
193590  **
193591  ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
193592  ** the first position list. The position list belonging to document 
193593  ** (Fts5SegIter.iRowid).
193594  */
193595  static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
193596    u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
193597    int iOff = pIter->iLeafOffset;  /* Offset to read at */
193598    int nNew;                       /* Bytes of new data */
193599  
193600    iOff += fts5GetVarint32(&a[iOff], nNew);
193601    if( iOff+nNew>pIter->pLeaf->nn ){
193602      p->rc = FTS5_CORRUPT;
193603      return;
193604    }
193605    pIter->term.n = nKeep;
193606    fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
193607    iOff += nNew;
193608    pIter->iTermLeafOffset = iOff;
193609    pIter->iTermLeafPgno = pIter->iLeafPgno;
193610    pIter->iLeafOffset = iOff;
193611  
193612    if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
193613      pIter->iEndofDoclist = pIter->pLeaf->nn+1;
193614    }else{
193615      int nExtra;
193616      pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
193617      pIter->iEndofDoclist += nExtra;
193618    }
193619  
193620    fts5SegIterLoadRowid(p, pIter);
193621  }
193622  
193623  static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
193624  static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
193625  static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
193626  
193627  static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
193628    if( pIter->flags & FTS5_SEGITER_REVERSE ){
193629      pIter->xNext = fts5SegIterNext_Reverse;
193630    }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
193631      pIter->xNext = fts5SegIterNext_None;
193632    }else{
193633      pIter->xNext = fts5SegIterNext;
193634    }
193635  }
193636  
193637  /*
193638  ** Initialize the iterator object pIter to iterate through the entries in
193639  ** segment pSeg. The iterator is left pointing to the first entry when 
193640  ** this function returns.
193641  **
193642  ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If 
193643  ** an error has already occurred when this function is called, it is a no-op.
193644  */
193645  static void fts5SegIterInit(
193646    Fts5Index *p,                   /* FTS index object */
193647    Fts5StructureSegment *pSeg,     /* Description of segment */
193648    Fts5SegIter *pIter              /* Object to populate */
193649  ){
193650    if( pSeg->pgnoFirst==0 ){
193651      /* This happens if the segment is being used as an input to an incremental
193652      ** merge and all data has already been "trimmed". See function
193653      ** fts5TrimSegments() for details. In this case leave the iterator empty.
193654      ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
193655      ** at EOF already. */
193656      assert( pIter->pLeaf==0 );
193657      return;
193658    }
193659  
193660    if( p->rc==SQLITE_OK ){
193661      memset(pIter, 0, sizeof(*pIter));
193662      fts5SegIterSetNext(p, pIter);
193663      pIter->pSeg = pSeg;
193664      pIter->iLeafPgno = pSeg->pgnoFirst-1;
193665      fts5SegIterNextPage(p, pIter);
193666    }
193667  
193668    if( p->rc==SQLITE_OK ){
193669      pIter->iLeafOffset = 4;
193670      assert_nc( pIter->pLeaf->nn>4 );
193671      assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
193672      pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
193673      fts5SegIterLoadTerm(p, pIter, 0);
193674      fts5SegIterLoadNPos(p, pIter);
193675    }
193676  }
193677  
193678  /*
193679  ** This function is only ever called on iterators created by calls to
193680  ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
193681  **
193682  ** The iterator is in an unusual state when this function is called: the
193683  ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
193684  ** the position-list size field for the first relevant rowid on the page.
193685  ** Fts5SegIter.rowid is set, but nPos and bDel are not.
193686  **
193687  ** This function advances the iterator so that it points to the last 
193688  ** relevant rowid on the page and, if necessary, initializes the 
193689  ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
193690  ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
193691  ** byte of the position list content associated with said rowid.
193692  */
193693  static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
193694    int eDetail = p->pConfig->eDetail;
193695    int n = pIter->pLeaf->szLeaf;
193696    int i = pIter->iLeafOffset;
193697    u8 *a = pIter->pLeaf->p;
193698    int iRowidOffset = 0;
193699  
193700    if( n>pIter->iEndofDoclist ){
193701      n = pIter->iEndofDoclist;
193702    }
193703  
193704    ASSERT_SZLEAF_OK(pIter->pLeaf);
193705    while( 1 ){
193706      i64 iDelta = 0;
193707  
193708      if( eDetail==FTS5_DETAIL_NONE ){
193709        /* todo */
193710        if( i<n && a[i]==0 ){
193711          i++;
193712          if( i<n && a[i]==0 ) i++;
193713        }
193714      }else{
193715        int nPos;
193716        int bDummy;
193717        i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
193718        i += nPos;
193719      }
193720      if( i>=n ) break;
193721      i += fts5GetVarint(&a[i], (u64*)&iDelta);
193722      pIter->iRowid += iDelta;
193723  
193724      /* If necessary, grow the pIter->aRowidOffset[] array. */
193725      if( iRowidOffset>=pIter->nRowidOffset ){
193726        int nNew = pIter->nRowidOffset + 8;
193727        int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
193728        if( aNew==0 ){
193729          p->rc = SQLITE_NOMEM;
193730          break;
193731        }
193732        pIter->aRowidOffset = aNew;
193733        pIter->nRowidOffset = nNew;
193734      }
193735  
193736      pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
193737      pIter->iLeafOffset = i;
193738    }
193739    pIter->iRowidOffset = iRowidOffset;
193740    fts5SegIterLoadNPos(p, pIter);
193741  }
193742  
193743  /*
193744  **
193745  */
193746  static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
193747    assert( pIter->flags & FTS5_SEGITER_REVERSE );
193748    assert( pIter->flags & FTS5_SEGITER_ONETERM );
193749  
193750    fts5DataRelease(pIter->pLeaf);
193751    pIter->pLeaf = 0;
193752    while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
193753      Fts5Data *pNew;
193754      pIter->iLeafPgno--;
193755      pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
193756            pIter->pSeg->iSegid, pIter->iLeafPgno
193757      ));
193758      if( pNew ){
193759        /* iTermLeafOffset may be equal to szLeaf if the term is the last
193760        ** thing on the page - i.e. the first rowid is on the following page.
193761        ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
193762        if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
193763          assert( pIter->pLeaf==0 );
193764          if( pIter->iTermLeafOffset<pNew->szLeaf ){
193765            pIter->pLeaf = pNew;
193766            pIter->iLeafOffset = pIter->iTermLeafOffset;
193767          }
193768        }else{
193769          int iRowidOff;
193770          iRowidOff = fts5LeafFirstRowidOff(pNew);
193771          if( iRowidOff ){
193772            pIter->pLeaf = pNew;
193773            pIter->iLeafOffset = iRowidOff;
193774          }
193775        }
193776  
193777        if( pIter->pLeaf ){
193778          u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
193779          pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
193780          break;
193781        }else{
193782          fts5DataRelease(pNew);
193783        }
193784      }
193785    }
193786  
193787    if( pIter->pLeaf ){
193788      pIter->iEndofDoclist = pIter->pLeaf->nn+1;
193789      fts5SegIterReverseInitPage(p, pIter);
193790    }
193791  }
193792  
193793  /*
193794  ** Return true if the iterator passed as the second argument currently
193795  ** points to a delete marker. A delete marker is an entry with a 0 byte
193796  ** position-list.
193797  */
193798  static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
193799    Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
193800    return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
193801  }
193802  
193803  /*
193804  ** Advance iterator pIter to the next entry.
193805  **
193806  ** This version of fts5SegIterNext() is only used by reverse iterators.
193807  */
193808  static void fts5SegIterNext_Reverse(
193809    Fts5Index *p,                   /* FTS5 backend object */
193810    Fts5SegIter *pIter,             /* Iterator to advance */
193811    int *pbUnused                   /* Unused */
193812  ){
193813    assert( pIter->flags & FTS5_SEGITER_REVERSE );
193814    assert( pIter->pNextLeaf==0 );
193815    UNUSED_PARAM(pbUnused);
193816  
193817    if( pIter->iRowidOffset>0 ){
193818      u8 *a = pIter->pLeaf->p;
193819      int iOff;
193820      i64 iDelta;
193821  
193822      pIter->iRowidOffset--;
193823      pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
193824      fts5SegIterLoadNPos(p, pIter);
193825      iOff = pIter->iLeafOffset;
193826      if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
193827        iOff += pIter->nPos;
193828      }
193829      fts5GetVarint(&a[iOff], (u64*)&iDelta);
193830      pIter->iRowid -= iDelta;
193831    }else{
193832      fts5SegIterReverseNewPage(p, pIter);
193833    }
193834  }
193835  
193836  /*
193837  ** Advance iterator pIter to the next entry.
193838  **
193839  ** This version of fts5SegIterNext() is only used if detail=none and the
193840  ** iterator is not a reverse direction iterator.
193841  */
193842  static void fts5SegIterNext_None(
193843    Fts5Index *p,                   /* FTS5 backend object */
193844    Fts5SegIter *pIter,             /* Iterator to advance */
193845    int *pbNewTerm                  /* OUT: Set for new term */
193846  ){
193847    int iOff;
193848  
193849    assert( p->rc==SQLITE_OK );
193850    assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
193851    assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
193852  
193853    ASSERT_SZLEAF_OK(pIter->pLeaf);
193854    iOff = pIter->iLeafOffset;
193855  
193856    /* Next entry is on the next page */
193857    if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
193858      fts5SegIterNextPage(p, pIter);
193859      if( p->rc || pIter->pLeaf==0 ) return;
193860      pIter->iRowid = 0;
193861      iOff = 4;
193862    }
193863  
193864    if( iOff<pIter->iEndofDoclist ){
193865      /* Next entry is on the current page */
193866      i64 iDelta;
193867      iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
193868      pIter->iLeafOffset = iOff;
193869      pIter->iRowid += iDelta;
193870    }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
193871      if( pIter->pSeg ){
193872        int nKeep = 0;
193873        if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
193874          iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
193875        }
193876        pIter->iLeafOffset = iOff;
193877        fts5SegIterLoadTerm(p, pIter, nKeep);
193878      }else{
193879        const u8 *pList = 0;
193880        const char *zTerm = 0;
193881        int nList;
193882        sqlite3Fts5HashScanNext(p->pHash);
193883        sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
193884        if( pList==0 ) goto next_none_eof;
193885        pIter->pLeaf->p = (u8*)pList;
193886        pIter->pLeaf->nn = nList;
193887        pIter->pLeaf->szLeaf = nList;
193888        pIter->iEndofDoclist = nList;
193889        sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
193890        pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
193891      }
193892  
193893      if( pbNewTerm ) *pbNewTerm = 1;
193894    }else{
193895      goto next_none_eof;
193896    }
193897  
193898    fts5SegIterLoadNPos(p, pIter);
193899  
193900    return;
193901   next_none_eof:
193902    fts5DataRelease(pIter->pLeaf);
193903    pIter->pLeaf = 0;
193904  }
193905  
193906  
193907  /*
193908  ** Advance iterator pIter to the next entry. 
193909  **
193910  ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It 
193911  ** is not considered an error if the iterator reaches EOF. If an error has 
193912  ** already occurred when this function is called, it is a no-op.
193913  */
193914  static void fts5SegIterNext(
193915    Fts5Index *p,                   /* FTS5 backend object */
193916    Fts5SegIter *pIter,             /* Iterator to advance */
193917    int *pbNewTerm                  /* OUT: Set for new term */
193918  ){
193919    Fts5Data *pLeaf = pIter->pLeaf;
193920    int iOff;
193921    int bNewTerm = 0;
193922    int nKeep = 0;
193923    u8 *a;
193924    int n;
193925  
193926    assert( pbNewTerm==0 || *pbNewTerm==0 );
193927    assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
193928  
193929    /* Search for the end of the position list within the current page. */
193930    a = pLeaf->p;
193931    n = pLeaf->szLeaf;
193932  
193933    ASSERT_SZLEAF_OK(pLeaf);
193934    iOff = pIter->iLeafOffset + pIter->nPos;
193935  
193936    if( iOff<n ){
193937      /* The next entry is on the current page. */
193938      assert_nc( iOff<=pIter->iEndofDoclist );
193939      if( iOff>=pIter->iEndofDoclist ){
193940        bNewTerm = 1;
193941        if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
193942          iOff += fts5GetVarint32(&a[iOff], nKeep);
193943        }
193944      }else{
193945        u64 iDelta;
193946        iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
193947        pIter->iRowid += iDelta;
193948        assert_nc( iDelta>0 );
193949      }
193950      pIter->iLeafOffset = iOff;
193951  
193952    }else if( pIter->pSeg==0 ){
193953      const u8 *pList = 0;
193954      const char *zTerm = 0;
193955      int nList = 0;
193956      assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
193957      if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
193958        sqlite3Fts5HashScanNext(p->pHash);
193959        sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
193960      }
193961      if( pList==0 ){
193962        fts5DataRelease(pIter->pLeaf);
193963        pIter->pLeaf = 0;
193964      }else{
193965        pIter->pLeaf->p = (u8*)pList;
193966        pIter->pLeaf->nn = nList;
193967        pIter->pLeaf->szLeaf = nList;
193968        pIter->iEndofDoclist = nList+1;
193969        sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
193970            (u8*)zTerm);
193971        pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
193972        *pbNewTerm = 1;
193973      }
193974    }else{
193975      iOff = 0;
193976      /* Next entry is not on the current page */
193977      while( iOff==0 ){
193978        fts5SegIterNextPage(p, pIter);
193979        pLeaf = pIter->pLeaf;
193980        if( pLeaf==0 ) break;
193981        ASSERT_SZLEAF_OK(pLeaf);
193982        if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
193983          iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
193984          pIter->iLeafOffset = iOff;
193985  
193986          if( pLeaf->nn>pLeaf->szLeaf ){
193987            pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
193988                &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
193989            );
193990          }
193991        }
193992        else if( pLeaf->nn>pLeaf->szLeaf ){
193993          pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
193994              &pLeaf->p[pLeaf->szLeaf], iOff
193995          );
193996          pIter->iLeafOffset = iOff;
193997          pIter->iEndofDoclist = iOff;
193998          bNewTerm = 1;
193999        }
194000        assert_nc( iOff<pLeaf->szLeaf );
194001        if( iOff>pLeaf->szLeaf ){
194002          p->rc = FTS5_CORRUPT;
194003          return;
194004        }
194005      }
194006    }
194007  
194008    /* Check if the iterator is now at EOF. If so, return early. */
194009    if( pIter->pLeaf ){
194010      if( bNewTerm ){
194011        if( pIter->flags & FTS5_SEGITER_ONETERM ){
194012          fts5DataRelease(pIter->pLeaf);
194013          pIter->pLeaf = 0;
194014        }else{
194015          fts5SegIterLoadTerm(p, pIter, nKeep);
194016          fts5SegIterLoadNPos(p, pIter);
194017          if( pbNewTerm ) *pbNewTerm = 1;
194018        }
194019      }else{
194020        /* The following could be done by calling fts5SegIterLoadNPos(). But
194021        ** this block is particularly performance critical, so equivalent
194022        ** code is inlined. 
194023        **
194024        ** Later: Switched back to fts5SegIterLoadNPos() because it supports
194025        ** detail=none mode. Not ideal.
194026        */
194027        int nSz;
194028        assert( p->rc==SQLITE_OK );
194029        assert( pIter->iLeafOffset<=pIter->pLeaf->nn );
194030        fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
194031        pIter->bDel = (nSz & 0x0001);
194032        pIter->nPos = nSz>>1;
194033        assert_nc( pIter->nPos>=0 );
194034      }
194035    }
194036  }
194037  
194038  #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
194039  
194040  #define fts5IndexSkipVarint(a, iOff) {            \
194041    int iEnd = iOff+9;                              \
194042    while( (a[iOff++] & 0x80) && iOff<iEnd );       \
194043  }
194044  
194045  /*
194046  ** Iterator pIter currently points to the first rowid in a doclist. This
194047  ** function sets the iterator up so that iterates in reverse order through
194048  ** the doclist.
194049  */
194050  static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
194051    Fts5DlidxIter *pDlidx = pIter->pDlidx;
194052    Fts5Data *pLast = 0;
194053    int pgnoLast = 0;
194054  
194055    if( pDlidx ){
194056      int iSegid = pIter->pSeg->iSegid;
194057      pgnoLast = fts5DlidxIterPgno(pDlidx);
194058      pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
194059    }else{
194060      Fts5Data *pLeaf = pIter->pLeaf;         /* Current leaf data */
194061  
194062      /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
194063      ** position-list content for the current rowid. Back it up so that it
194064      ** points to the start of the position-list size field. */
194065      int iPoslist;
194066      if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
194067        iPoslist = pIter->iTermLeafOffset;
194068      }else{
194069        iPoslist = 4;
194070      }
194071      fts5IndexSkipVarint(pLeaf->p, iPoslist);
194072      pIter->iLeafOffset = iPoslist;
194073  
194074      /* If this condition is true then the largest rowid for the current
194075      ** term may not be stored on the current page. So search forward to
194076      ** see where said rowid really is.  */
194077      if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
194078        int pgno;
194079        Fts5StructureSegment *pSeg = pIter->pSeg;
194080  
194081        /* The last rowid in the doclist may not be on the current page. Search
194082        ** forward to find the page containing the last rowid.  */
194083        for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
194084          i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
194085          Fts5Data *pNew = fts5DataRead(p, iAbs);
194086          if( pNew ){
194087            int iRowid, bTermless;
194088            iRowid = fts5LeafFirstRowidOff(pNew);
194089            bTermless = fts5LeafIsTermless(pNew);
194090            if( iRowid ){
194091              SWAPVAL(Fts5Data*, pNew, pLast);
194092              pgnoLast = pgno;
194093            }
194094            fts5DataRelease(pNew);
194095            if( bTermless==0 ) break;
194096          }
194097        }
194098      }
194099    }
194100  
194101    /* If pLast is NULL at this point, then the last rowid for this doclist
194102    ** lies on the page currently indicated by the iterator. In this case 
194103    ** pIter->iLeafOffset is already set to point to the position-list size
194104    ** field associated with the first relevant rowid on the page.
194105    **
194106    ** Or, if pLast is non-NULL, then it is the page that contains the last
194107    ** rowid. In this case configure the iterator so that it points to the
194108    ** first rowid on this page.
194109    */
194110    if( pLast ){
194111      int iOff;
194112      fts5DataRelease(pIter->pLeaf);
194113      pIter->pLeaf = pLast;
194114      pIter->iLeafPgno = pgnoLast;
194115      iOff = fts5LeafFirstRowidOff(pLast);
194116      iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
194117      pIter->iLeafOffset = iOff;
194118  
194119      if( fts5LeafIsTermless(pLast) ){
194120        pIter->iEndofDoclist = pLast->nn+1;
194121      }else{
194122        pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
194123      }
194124  
194125    }
194126  
194127    fts5SegIterReverseInitPage(p, pIter);
194128  }
194129  
194130  /*
194131  ** Iterator pIter currently points to the first rowid of a doclist.
194132  ** There is a doclist-index associated with the final term on the current 
194133  ** page. If the current term is the last term on the page, load the 
194134  ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
194135  */
194136  static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
194137    int iSeg = pIter->pSeg->iSegid;
194138    int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
194139    Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
194140  
194141    assert( pIter->flags & FTS5_SEGITER_ONETERM );
194142    assert( pIter->pDlidx==0 );
194143  
194144    /* Check if the current doclist ends on this page. If it does, return
194145    ** early without loading the doclist-index (as it belongs to a different
194146    ** term. */
194147    if( pIter->iTermLeafPgno==pIter->iLeafPgno 
194148     && pIter->iEndofDoclist<pLeaf->szLeaf 
194149    ){
194150      return;
194151    }
194152  
194153    pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
194154  }
194155  
194156  /*
194157  ** The iterator object passed as the second argument currently contains
194158  ** no valid values except for the Fts5SegIter.pLeaf member variable. This
194159  ** function searches the leaf page for a term matching (pTerm/nTerm).
194160  **
194161  ** If the specified term is found on the page, then the iterator is left
194162  ** pointing to it. If argument bGe is zero and the term is not found,
194163  ** the iterator is left pointing at EOF.
194164  **
194165  ** If bGe is non-zero and the specified term is not found, then the
194166  ** iterator is left pointing to the smallest term in the segment that
194167  ** is larger than the specified term, even if this term is not on the
194168  ** current page.
194169  */
194170  static void fts5LeafSeek(
194171    Fts5Index *p,                   /* Leave any error code here */
194172    int bGe,                        /* True for a >= search */
194173    Fts5SegIter *pIter,             /* Iterator to seek */
194174    const u8 *pTerm, int nTerm      /* Term to search for */
194175  ){
194176    int iOff;
194177    const u8 *a = pIter->pLeaf->p;
194178    int szLeaf = pIter->pLeaf->szLeaf;
194179    int n = pIter->pLeaf->nn;
194180  
194181    int nMatch = 0;
194182    int nKeep = 0;
194183    int nNew = 0;
194184    int iTermOff;
194185    int iPgidx;                     /* Current offset in pgidx */
194186    int bEndOfPage = 0;
194187  
194188    assert( p->rc==SQLITE_OK );
194189  
194190    iPgidx = szLeaf;
194191    iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
194192    iOff = iTermOff;
194193    if( iOff>n ){
194194      p->rc = FTS5_CORRUPT;
194195      return;
194196    }
194197  
194198    while( 1 ){
194199  
194200      /* Figure out how many new bytes are in this term */
194201      fts5FastGetVarint32(a, iOff, nNew);
194202      if( nKeep<nMatch ){
194203        goto search_failed;
194204      }
194205  
194206      assert( nKeep>=nMatch );
194207      if( nKeep==nMatch ){
194208        int nCmp;
194209        int i;
194210        nCmp = MIN(nNew, nTerm-nMatch);
194211        for(i=0; i<nCmp; i++){
194212          if( a[iOff+i]!=pTerm[nMatch+i] ) break;
194213        }
194214        nMatch += i;
194215  
194216        if( nTerm==nMatch ){
194217          if( i==nNew ){
194218            goto search_success;
194219          }else{
194220            goto search_failed;
194221          }
194222        }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
194223          goto search_failed;
194224        }
194225      }
194226  
194227      if( iPgidx>=n ){
194228        bEndOfPage = 1;
194229        break;
194230      }
194231  
194232      iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
194233      iTermOff += nKeep;
194234      iOff = iTermOff;
194235  
194236      if( iOff>=n ){
194237        p->rc = FTS5_CORRUPT;
194238        return;
194239      }
194240  
194241      /* Read the nKeep field of the next term. */
194242      fts5FastGetVarint32(a, iOff, nKeep);
194243    }
194244  
194245   search_failed:
194246    if( bGe==0 ){
194247      fts5DataRelease(pIter->pLeaf);
194248      pIter->pLeaf = 0;
194249      return;
194250    }else if( bEndOfPage ){
194251      do {
194252        fts5SegIterNextPage(p, pIter);
194253        if( pIter->pLeaf==0 ) return;
194254        a = pIter->pLeaf->p;
194255        if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
194256          iPgidx = pIter->pLeaf->szLeaf;
194257          iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
194258          if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
194259            p->rc = FTS5_CORRUPT;
194260          }else{
194261            nKeep = 0;
194262            iTermOff = iOff;
194263            n = pIter->pLeaf->nn;
194264            iOff += fts5GetVarint32(&a[iOff], nNew);
194265            break;
194266          }
194267        }
194268      }while( 1 );
194269    }
194270  
194271   search_success:
194272  
194273    pIter->iLeafOffset = iOff + nNew;
194274    pIter->iTermLeafOffset = pIter->iLeafOffset;
194275    pIter->iTermLeafPgno = pIter->iLeafPgno;
194276  
194277    fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
194278    fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
194279  
194280    if( iPgidx>=n ){
194281      pIter->iEndofDoclist = pIter->pLeaf->nn+1;
194282    }else{
194283      int nExtra;
194284      iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
194285      pIter->iEndofDoclist = iTermOff + nExtra;
194286    }
194287    pIter->iPgidxOff = iPgidx;
194288  
194289    fts5SegIterLoadRowid(p, pIter);
194290    fts5SegIterLoadNPos(p, pIter);
194291  }
194292  
194293  static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
194294    if( p->pIdxSelect==0 ){
194295      Fts5Config *pConfig = p->pConfig;
194296      fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
194297            "SELECT pgno FROM '%q'.'%q_idx' WHERE "
194298            "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
194299            pConfig->zDb, pConfig->zName
194300      ));
194301    }
194302    return p->pIdxSelect;
194303  }
194304  
194305  /*
194306  ** Initialize the object pIter to point to term pTerm/nTerm within segment
194307  ** pSeg. If there is no such term in the index, the iterator is set to EOF.
194308  **
194309  ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If 
194310  ** an error has already occurred when this function is called, it is a no-op.
194311  */
194312  static void fts5SegIterSeekInit(
194313    Fts5Index *p,                   /* FTS5 backend */
194314    const u8 *pTerm, int nTerm,     /* Term to seek to */
194315    int flags,                      /* Mask of FTS5INDEX_XXX flags */
194316    Fts5StructureSegment *pSeg,     /* Description of segment */
194317    Fts5SegIter *pIter              /* Object to populate */
194318  ){
194319    int iPg = 1;
194320    int bGe = (flags & FTS5INDEX_QUERY_SCAN);
194321    int bDlidx = 0;                 /* True if there is a doclist-index */
194322    sqlite3_stmt *pIdxSelect = 0;
194323  
194324    assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
194325    assert( pTerm && nTerm );
194326    memset(pIter, 0, sizeof(*pIter));
194327    pIter->pSeg = pSeg;
194328  
194329    /* This block sets stack variable iPg to the leaf page number that may
194330    ** contain term (pTerm/nTerm), if it is present in the segment. */
194331    pIdxSelect = fts5IdxSelectStmt(p);
194332    if( p->rc ) return;
194333    sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
194334    sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
194335    if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
194336      i64 val = sqlite3_column_int(pIdxSelect, 0);
194337      iPg = (int)(val>>1);
194338      bDlidx = (val & 0x0001);
194339    }
194340    p->rc = sqlite3_reset(pIdxSelect);
194341  
194342    if( iPg<pSeg->pgnoFirst ){
194343      iPg = pSeg->pgnoFirst;
194344      bDlidx = 0;
194345    }
194346  
194347    pIter->iLeafPgno = iPg - 1;
194348    fts5SegIterNextPage(p, pIter);
194349  
194350    if( pIter->pLeaf ){
194351      fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
194352    }
194353  
194354    if( p->rc==SQLITE_OK && bGe==0 ){
194355      pIter->flags |= FTS5_SEGITER_ONETERM;
194356      if( pIter->pLeaf ){
194357        if( flags & FTS5INDEX_QUERY_DESC ){
194358          pIter->flags |= FTS5_SEGITER_REVERSE;
194359        }
194360        if( bDlidx ){
194361          fts5SegIterLoadDlidx(p, pIter);
194362        }
194363        if( flags & FTS5INDEX_QUERY_DESC ){
194364          fts5SegIterReverse(p, pIter);
194365        }
194366      }
194367    }
194368  
194369    fts5SegIterSetNext(p, pIter);
194370  
194371    /* Either:
194372    **
194373    **   1) an error has occurred, or
194374    **   2) the iterator points to EOF, or
194375    **   3) the iterator points to an entry with term (pTerm/nTerm), or
194376    **   4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
194377    **      to an entry with a term greater than or equal to (pTerm/nTerm).
194378    */
194379    assert( p->rc!=SQLITE_OK                                          /* 1 */
194380     || pIter->pLeaf==0                                               /* 2 */
194381     || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0          /* 3 */
194382     || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0)  /* 4 */
194383    );
194384  }
194385  
194386  /*
194387  ** Initialize the object pIter to point to term pTerm/nTerm within the
194388  ** in-memory hash table. If there is no such term in the hash-table, the 
194389  ** iterator is set to EOF.
194390  **
194391  ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If 
194392  ** an error has already occurred when this function is called, it is a no-op.
194393  */
194394  static void fts5SegIterHashInit(
194395    Fts5Index *p,                   /* FTS5 backend */
194396    const u8 *pTerm, int nTerm,     /* Term to seek to */
194397    int flags,                      /* Mask of FTS5INDEX_XXX flags */
194398    Fts5SegIter *pIter              /* Object to populate */
194399  ){
194400    const u8 *pList = 0;
194401    int nList = 0;
194402    const u8 *z = 0;
194403    int n = 0;
194404  
194405    assert( p->pHash );
194406    assert( p->rc==SQLITE_OK );
194407  
194408    if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
194409      p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
194410      sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
194411      n = (z ? (int)strlen((const char*)z) : 0);
194412    }else{
194413      pIter->flags |= FTS5_SEGITER_ONETERM;
194414      sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
194415      z = pTerm;
194416      n = nTerm;
194417    }
194418  
194419    if( pList ){
194420      Fts5Data *pLeaf;
194421      sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
194422      pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
194423      if( pLeaf==0 ) return;
194424      pLeaf->p = (u8*)pList;
194425      pLeaf->nn = pLeaf->szLeaf = nList;
194426      pIter->pLeaf = pLeaf;
194427      pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
194428      pIter->iEndofDoclist = pLeaf->nn;
194429  
194430      if( flags & FTS5INDEX_QUERY_DESC ){
194431        pIter->flags |= FTS5_SEGITER_REVERSE;
194432        fts5SegIterReverseInitPage(p, pIter);
194433      }else{
194434        fts5SegIterLoadNPos(p, pIter);
194435      }
194436    }
194437  
194438    fts5SegIterSetNext(p, pIter);
194439  }
194440  
194441  /*
194442  ** Zero the iterator passed as the only argument.
194443  */
194444  static void fts5SegIterClear(Fts5SegIter *pIter){
194445    fts5BufferFree(&pIter->term);
194446    fts5DataRelease(pIter->pLeaf);
194447    fts5DataRelease(pIter->pNextLeaf);
194448    fts5DlidxIterFree(pIter->pDlidx);
194449    sqlite3_free(pIter->aRowidOffset);
194450    memset(pIter, 0, sizeof(Fts5SegIter));
194451  }
194452  
194453  #ifdef SQLITE_DEBUG
194454  
194455  /*
194456  ** This function is used as part of the big assert() procedure implemented by
194457  ** fts5AssertMultiIterSetup(). It ensures that the result currently stored
194458  ** in *pRes is the correct result of comparing the current positions of the
194459  ** two iterators.
194460  */
194461  static void fts5AssertComparisonResult(
194462    Fts5Iter *pIter, 
194463    Fts5SegIter *p1,
194464    Fts5SegIter *p2,
194465    Fts5CResult *pRes
194466  ){
194467    int i1 = p1 - pIter->aSeg;
194468    int i2 = p2 - pIter->aSeg;
194469  
194470    if( p1->pLeaf || p2->pLeaf ){
194471      if( p1->pLeaf==0 ){
194472        assert( pRes->iFirst==i2 );
194473      }else if( p2->pLeaf==0 ){
194474        assert( pRes->iFirst==i1 );
194475      }else{
194476        int nMin = MIN(p1->term.n, p2->term.n);
194477        int res = memcmp(p1->term.p, p2->term.p, nMin);
194478        if( res==0 ) res = p1->term.n - p2->term.n;
194479  
194480        if( res==0 ){
194481          assert( pRes->bTermEq==1 );
194482          assert( p1->iRowid!=p2->iRowid );
194483          res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
194484        }else{
194485          assert( pRes->bTermEq==0 );
194486        }
194487  
194488        if( res<0 ){
194489          assert( pRes->iFirst==i1 );
194490        }else{
194491          assert( pRes->iFirst==i2 );
194492        }
194493      }
194494    }
194495  }
194496  
194497  /*
194498  ** This function is a no-op unless SQLITE_DEBUG is defined when this module
194499  ** is compiled. In that case, this function is essentially an assert() 
194500  ** statement used to verify that the contents of the pIter->aFirst[] array
194501  ** are correct.
194502  */
194503  static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
194504    if( p->rc==SQLITE_OK ){
194505      Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
194506      int i;
194507  
194508      assert( (pFirst->pLeaf==0)==pIter->base.bEof );
194509  
194510      /* Check that pIter->iSwitchRowid is set correctly. */
194511      for(i=0; i<pIter->nSeg; i++){
194512        Fts5SegIter *p1 = &pIter->aSeg[i];
194513        assert( p1==pFirst 
194514             || p1->pLeaf==0 
194515             || fts5BufferCompare(&pFirst->term, &p1->term) 
194516             || p1->iRowid==pIter->iSwitchRowid
194517             || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
194518        );
194519      }
194520  
194521      for(i=0; i<pIter->nSeg; i+=2){
194522        Fts5SegIter *p1 = &pIter->aSeg[i];
194523        Fts5SegIter *p2 = &pIter->aSeg[i+1];
194524        Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
194525        fts5AssertComparisonResult(pIter, p1, p2, pRes);
194526      }
194527  
194528      for(i=1; i<(pIter->nSeg / 2); i+=2){
194529        Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
194530        Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
194531        Fts5CResult *pRes = &pIter->aFirst[i];
194532        fts5AssertComparisonResult(pIter, p1, p2, pRes);
194533      }
194534    }
194535  }
194536  #else
194537  # define fts5AssertMultiIterSetup(x,y)
194538  #endif
194539  
194540  /*
194541  ** Do the comparison necessary to populate pIter->aFirst[iOut].
194542  **
194543  ** If the returned value is non-zero, then it is the index of an entry
194544  ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
194545  ** to a key that is a duplicate of another, higher priority, 
194546  ** segment-iterator in the pSeg->aSeg[] array.
194547  */
194548  static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
194549    int i1;                         /* Index of left-hand Fts5SegIter */
194550    int i2;                         /* Index of right-hand Fts5SegIter */
194551    int iRes;
194552    Fts5SegIter *p1;                /* Left-hand Fts5SegIter */
194553    Fts5SegIter *p2;                /* Right-hand Fts5SegIter */
194554    Fts5CResult *pRes = &pIter->aFirst[iOut];
194555  
194556    assert( iOut<pIter->nSeg && iOut>0 );
194557    assert( pIter->bRev==0 || pIter->bRev==1 );
194558  
194559    if( iOut>=(pIter->nSeg/2) ){
194560      i1 = (iOut - pIter->nSeg/2) * 2;
194561      i2 = i1 + 1;
194562    }else{
194563      i1 = pIter->aFirst[iOut*2].iFirst;
194564      i2 = pIter->aFirst[iOut*2+1].iFirst;
194565    }
194566    p1 = &pIter->aSeg[i1];
194567    p2 = &pIter->aSeg[i2];
194568  
194569    pRes->bTermEq = 0;
194570    if( p1->pLeaf==0 ){           /* If p1 is at EOF */
194571      iRes = i2;
194572    }else if( p2->pLeaf==0 ){     /* If p2 is at EOF */
194573      iRes = i1;
194574    }else{
194575      int res = fts5BufferCompare(&p1->term, &p2->term);
194576      if( res==0 ){
194577        assert( i2>i1 );
194578        assert( i2!=0 );
194579        pRes->bTermEq = 1;
194580        if( p1->iRowid==p2->iRowid ){
194581          p1->bDel = p2->bDel;
194582          return i2;
194583        }
194584        res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
194585      }
194586      assert( res!=0 );
194587      if( res<0 ){
194588        iRes = i1;
194589      }else{
194590        iRes = i2;
194591      }
194592    }
194593  
194594    pRes->iFirst = (u16)iRes;
194595    return 0;
194596  }
194597  
194598  /*
194599  ** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
194600  ** It is an error if leaf iLeafPgno does not exist or contains no rowids.
194601  */
194602  static void fts5SegIterGotoPage(
194603    Fts5Index *p,                   /* FTS5 backend object */
194604    Fts5SegIter *pIter,             /* Iterator to advance */
194605    int iLeafPgno
194606  ){
194607    assert( iLeafPgno>pIter->iLeafPgno );
194608  
194609    if( iLeafPgno>pIter->pSeg->pgnoLast ){
194610      p->rc = FTS5_CORRUPT;
194611    }else{
194612      fts5DataRelease(pIter->pNextLeaf);
194613      pIter->pNextLeaf = 0;
194614      pIter->iLeafPgno = iLeafPgno-1;
194615      fts5SegIterNextPage(p, pIter);
194616      assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
194617  
194618      if( p->rc==SQLITE_OK ){
194619        int iOff;
194620        u8 *a = pIter->pLeaf->p;
194621        int n = pIter->pLeaf->szLeaf;
194622  
194623        iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
194624        if( iOff<4 || iOff>=n ){
194625          p->rc = FTS5_CORRUPT;
194626        }else{
194627          iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
194628          pIter->iLeafOffset = iOff;
194629          fts5SegIterLoadNPos(p, pIter);
194630        }
194631      }
194632    }
194633  }
194634  
194635  /*
194636  ** Advance the iterator passed as the second argument until it is at or 
194637  ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
194638  ** always advanced at least once.
194639  */
194640  static void fts5SegIterNextFrom(
194641    Fts5Index *p,                   /* FTS5 backend object */
194642    Fts5SegIter *pIter,             /* Iterator to advance */
194643    i64 iMatch                      /* Advance iterator at least this far */
194644  ){
194645    int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
194646    Fts5DlidxIter *pDlidx = pIter->pDlidx;
194647    int iLeafPgno = pIter->iLeafPgno;
194648    int bMove = 1;
194649  
194650    assert( pIter->flags & FTS5_SEGITER_ONETERM );
194651    assert( pIter->pDlidx );
194652    assert( pIter->pLeaf );
194653  
194654    if( bRev==0 ){
194655      while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
194656        iLeafPgno = fts5DlidxIterPgno(pDlidx);
194657        fts5DlidxIterNext(p, pDlidx);
194658      }
194659      assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
194660      if( iLeafPgno>pIter->iLeafPgno ){
194661        fts5SegIterGotoPage(p, pIter, iLeafPgno);
194662        bMove = 0;
194663      }
194664    }else{
194665      assert( pIter->pNextLeaf==0 );
194666      assert( iMatch<pIter->iRowid );
194667      while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
194668        fts5DlidxIterPrev(p, pDlidx);
194669      }
194670      iLeafPgno = fts5DlidxIterPgno(pDlidx);
194671  
194672      assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
194673  
194674      if( iLeafPgno<pIter->iLeafPgno ){
194675        pIter->iLeafPgno = iLeafPgno+1;
194676        fts5SegIterReverseNewPage(p, pIter);
194677        bMove = 0;
194678      }
194679    }
194680  
194681    do{
194682      if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
194683      if( pIter->pLeaf==0 ) break;
194684      if( bRev==0 && pIter->iRowid>=iMatch ) break;
194685      if( bRev!=0 && pIter->iRowid<=iMatch ) break;
194686      bMove = 1;
194687    }while( p->rc==SQLITE_OK );
194688  }
194689  
194690  
194691  /*
194692  ** Free the iterator object passed as the second argument.
194693  */
194694  static void fts5MultiIterFree(Fts5Iter *pIter){
194695    if( pIter ){
194696      int i;
194697      for(i=0; i<pIter->nSeg; i++){
194698        fts5SegIterClear(&pIter->aSeg[i]);
194699      }
194700      fts5StructureRelease(pIter->pStruct);
194701      fts5BufferFree(&pIter->poslist);
194702      sqlite3_free(pIter);
194703    }
194704  }
194705  
194706  static void fts5MultiIterAdvanced(
194707    Fts5Index *p,                   /* FTS5 backend to iterate within */
194708    Fts5Iter *pIter,                /* Iterator to update aFirst[] array for */
194709    int iChanged,                   /* Index of sub-iterator just advanced */
194710    int iMinset                     /* Minimum entry in aFirst[] to set */
194711  ){
194712    int i;
194713    for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
194714      int iEq;
194715      if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
194716        Fts5SegIter *pSeg = &pIter->aSeg[iEq];
194717        assert( p->rc==SQLITE_OK );
194718        pSeg->xNext(p, pSeg, 0);
194719        i = pIter->nSeg + iEq;
194720      }
194721    }
194722  }
194723  
194724  /*
194725  ** Sub-iterator iChanged of iterator pIter has just been advanced. It still
194726  ** points to the same term though - just a different rowid. This function
194727  ** attempts to update the contents of the pIter->aFirst[] accordingly.
194728  ** If it does so successfully, 0 is returned. Otherwise 1.
194729  **
194730  ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
194731  ** on the iterator instead. That function does the same as this one, except
194732  ** that it deals with more complicated cases as well.
194733  */ 
194734  static int fts5MultiIterAdvanceRowid(
194735    Fts5Iter *pIter,                /* Iterator to update aFirst[] array for */
194736    int iChanged,                   /* Index of sub-iterator just advanced */
194737    Fts5SegIter **ppFirst
194738  ){
194739    Fts5SegIter *pNew = &pIter->aSeg[iChanged];
194740  
194741    if( pNew->iRowid==pIter->iSwitchRowid
194742     || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
194743    ){
194744      int i;
194745      Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
194746      pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
194747      for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
194748        Fts5CResult *pRes = &pIter->aFirst[i];
194749  
194750        assert( pNew->pLeaf );
194751        assert( pRes->bTermEq==0 || pOther->pLeaf );
194752  
194753        if( pRes->bTermEq ){
194754          if( pNew->iRowid==pOther->iRowid ){
194755            return 1;
194756          }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
194757            pIter->iSwitchRowid = pOther->iRowid;
194758            pNew = pOther;
194759          }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
194760            pIter->iSwitchRowid = pOther->iRowid;
194761          }
194762        }
194763        pRes->iFirst = (u16)(pNew - pIter->aSeg);
194764        if( i==1 ) break;
194765  
194766        pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
194767      }
194768    }
194769  
194770    *ppFirst = pNew;
194771    return 0;
194772  }
194773  
194774  /*
194775  ** Set the pIter->bEof variable based on the state of the sub-iterators.
194776  */
194777  static void fts5MultiIterSetEof(Fts5Iter *pIter){
194778    Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
194779    pIter->base.bEof = pSeg->pLeaf==0;
194780    pIter->iSwitchRowid = pSeg->iRowid;
194781  }
194782  
194783  /*
194784  ** Move the iterator to the next entry. 
194785  **
194786  ** If an error occurs, an error code is left in Fts5Index.rc. It is not 
194787  ** considered an error if the iterator reaches EOF, or if it is already at 
194788  ** EOF when this function is called.
194789  */
194790  static void fts5MultiIterNext(
194791    Fts5Index *p, 
194792    Fts5Iter *pIter,
194793    int bFrom,                      /* True if argument iFrom is valid */
194794    i64 iFrom                       /* Advance at least as far as this */
194795  ){
194796    int bUseFrom = bFrom;
194797    assert( pIter->base.bEof==0 );
194798    while( p->rc==SQLITE_OK ){
194799      int iFirst = pIter->aFirst[1].iFirst;
194800      int bNewTerm = 0;
194801      Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
194802      assert( p->rc==SQLITE_OK );
194803      if( bUseFrom && pSeg->pDlidx ){
194804        fts5SegIterNextFrom(p, pSeg, iFrom);
194805      }else{
194806        pSeg->xNext(p, pSeg, &bNewTerm);
194807      }
194808  
194809      if( pSeg->pLeaf==0 || bNewTerm 
194810       || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
194811      ){
194812        fts5MultiIterAdvanced(p, pIter, iFirst, 1);
194813        fts5MultiIterSetEof(pIter);
194814        pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
194815        if( pSeg->pLeaf==0 ) return;
194816      }
194817  
194818      fts5AssertMultiIterSetup(p, pIter);
194819      assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
194820      if( pIter->bSkipEmpty==0 || pSeg->nPos ){
194821        pIter->xSetOutputs(pIter, pSeg);
194822        return;
194823      }
194824      bUseFrom = 0;
194825    }
194826  }
194827  
194828  static void fts5MultiIterNext2(
194829    Fts5Index *p, 
194830    Fts5Iter *pIter,
194831    int *pbNewTerm                  /* OUT: True if *might* be new term */
194832  ){
194833    assert( pIter->bSkipEmpty );
194834    if( p->rc==SQLITE_OK ){
194835      *pbNewTerm = 0;
194836      do{
194837        int iFirst = pIter->aFirst[1].iFirst;
194838        Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
194839        int bNewTerm = 0;
194840  
194841        assert( p->rc==SQLITE_OK );
194842        pSeg->xNext(p, pSeg, &bNewTerm);
194843        if( pSeg->pLeaf==0 || bNewTerm 
194844         || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
194845        ){
194846          fts5MultiIterAdvanced(p, pIter, iFirst, 1);
194847          fts5MultiIterSetEof(pIter);
194848          *pbNewTerm = 1;
194849        }
194850        fts5AssertMultiIterSetup(p, pIter);
194851  
194852      }while( fts5MultiIterIsEmpty(p, pIter) );
194853    }
194854  }
194855  
194856  static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
194857    UNUSED_PARAM2(pUnused1, pUnused2);
194858  }
194859  
194860  static Fts5Iter *fts5MultiIterAlloc(
194861    Fts5Index *p,                   /* FTS5 backend to iterate within */
194862    int nSeg
194863  ){
194864    Fts5Iter *pNew;
194865    int nSlot;                      /* Power of two >= nSeg */
194866  
194867    for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
194868    pNew = fts5IdxMalloc(p, 
194869        sizeof(Fts5Iter) +                  /* pNew */
194870        sizeof(Fts5SegIter) * (nSlot-1) +   /* pNew->aSeg[] */
194871        sizeof(Fts5CResult) * nSlot         /* pNew->aFirst[] */
194872    );
194873    if( pNew ){
194874      pNew->nSeg = nSlot;
194875      pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
194876      pNew->pIndex = p;
194877      pNew->xSetOutputs = fts5IterSetOutputs_Noop;
194878    }
194879    return pNew;
194880  }
194881  
194882  static void fts5PoslistCallback(
194883    Fts5Index *pUnused, 
194884    void *pContext, 
194885    const u8 *pChunk, int nChunk
194886  ){
194887    UNUSED_PARAM(pUnused);
194888    assert_nc( nChunk>=0 );
194889    if( nChunk>0 ){
194890      fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
194891    }
194892  }
194893  
194894  typedef struct PoslistCallbackCtx PoslistCallbackCtx;
194895  struct PoslistCallbackCtx {
194896    Fts5Buffer *pBuf;               /* Append to this buffer */
194897    Fts5Colset *pColset;            /* Restrict matches to this column */
194898    int eState;                     /* See above */
194899  };
194900  
194901  typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
194902  struct PoslistOffsetsCtx {
194903    Fts5Buffer *pBuf;               /* Append to this buffer */
194904    Fts5Colset *pColset;            /* Restrict matches to this column */
194905    int iRead;
194906    int iWrite;
194907  };
194908  
194909  /*
194910  ** TODO: Make this more efficient!
194911  */
194912  static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
194913    int i;
194914    for(i=0; i<pColset->nCol; i++){
194915      if( pColset->aiCol[i]==iCol ) return 1;
194916    }
194917    return 0;
194918  }
194919  
194920  static void fts5PoslistOffsetsCallback(
194921    Fts5Index *pUnused, 
194922    void *pContext, 
194923    const u8 *pChunk, int nChunk
194924  ){
194925    PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
194926    UNUSED_PARAM(pUnused);
194927    assert_nc( nChunk>=0 );
194928    if( nChunk>0 ){
194929      int i = 0;
194930      while( i<nChunk ){
194931        int iVal;
194932        i += fts5GetVarint32(&pChunk[i], iVal);
194933        iVal += pCtx->iRead - 2;
194934        pCtx->iRead = iVal;
194935        if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
194936          fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
194937          pCtx->iWrite = iVal;
194938        }
194939      }
194940    }
194941  }
194942  
194943  static void fts5PoslistFilterCallback(
194944    Fts5Index *pUnused,
194945    void *pContext, 
194946    const u8 *pChunk, int nChunk
194947  ){
194948    PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
194949    UNUSED_PARAM(pUnused);
194950    assert_nc( nChunk>=0 );
194951    if( nChunk>0 ){
194952      /* Search through to find the first varint with value 1. This is the
194953      ** start of the next columns hits. */
194954      int i = 0;
194955      int iStart = 0;
194956  
194957      if( pCtx->eState==2 ){
194958        int iCol;
194959        fts5FastGetVarint32(pChunk, i, iCol);
194960        if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
194961          pCtx->eState = 1;
194962          fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
194963        }else{
194964          pCtx->eState = 0;
194965        }
194966      }
194967  
194968      do {
194969        while( i<nChunk && pChunk[i]!=0x01 ){
194970          while( pChunk[i] & 0x80 ) i++;
194971          i++;
194972        }
194973        if( pCtx->eState ){
194974          fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
194975        }
194976        if( i<nChunk ){
194977          int iCol;
194978          iStart = i;
194979          i++;
194980          if( i>=nChunk ){
194981            pCtx->eState = 2;
194982          }else{
194983            fts5FastGetVarint32(pChunk, i, iCol);
194984            pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
194985            if( pCtx->eState ){
194986              fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
194987              iStart = i;
194988            }
194989          }
194990        }
194991      }while( i<nChunk );
194992    }
194993  }
194994  
194995  static void fts5ChunkIterate(
194996    Fts5Index *p,                   /* Index object */
194997    Fts5SegIter *pSeg,              /* Poslist of this iterator */
194998    void *pCtx,                     /* Context pointer for xChunk callback */
194999    void (*xChunk)(Fts5Index*, void*, const u8*, int)
195000  ){
195001    int nRem = pSeg->nPos;          /* Number of bytes still to come */
195002    Fts5Data *pData = 0;
195003    u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
195004    int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
195005    int pgno = pSeg->iLeafPgno;
195006    int pgnoSave = 0;
195007  
195008    /* This function does notmwork with detail=none databases. */
195009    assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
195010  
195011    if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
195012      pgnoSave = pgno+1;
195013    }
195014  
195015    while( 1 ){
195016      xChunk(p, pCtx, pChunk, nChunk);
195017      nRem -= nChunk;
195018      fts5DataRelease(pData);
195019      if( nRem<=0 ){
195020        break;
195021      }else{
195022        pgno++;
195023        pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
195024        if( pData==0 ) break;
195025        pChunk = &pData->p[4];
195026        nChunk = MIN(nRem, pData->szLeaf - 4);
195027        if( pgno==pgnoSave ){
195028          assert( pSeg->pNextLeaf==0 );
195029          pSeg->pNextLeaf = pData;
195030          pData = 0;
195031        }
195032      }
195033    }
195034  }
195035  
195036  /*
195037  ** Iterator pIter currently points to a valid entry (not EOF). This
195038  ** function appends the position list data for the current entry to
195039  ** buffer pBuf. It does not make a copy of the position-list size
195040  ** field.
195041  */
195042  static void fts5SegiterPoslist(
195043    Fts5Index *p,
195044    Fts5SegIter *pSeg,
195045    Fts5Colset *pColset,
195046    Fts5Buffer *pBuf
195047  ){
195048    if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
195049      if( pColset==0 ){
195050        fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
195051      }else{
195052        if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
195053          PoslistCallbackCtx sCtx;
195054          sCtx.pBuf = pBuf;
195055          sCtx.pColset = pColset;
195056          sCtx.eState = fts5IndexColsetTest(pColset, 0);
195057          assert( sCtx.eState==0 || sCtx.eState==1 );
195058          fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
195059        }else{
195060          PoslistOffsetsCtx sCtx;
195061          memset(&sCtx, 0, sizeof(sCtx));
195062          sCtx.pBuf = pBuf;
195063          sCtx.pColset = pColset;
195064          fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
195065        }
195066      }
195067    }
195068  }
195069  
195070  /*
195071  ** IN/OUT parameter (*pa) points to a position list n bytes in size. If
195072  ** the position list contains entries for column iCol, then (*pa) is set
195073  ** to point to the sub-position-list for that column and the number of
195074  ** bytes in it returned. Or, if the argument position list does not
195075  ** contain any entries for column iCol, return 0.
195076  */
195077  static int fts5IndexExtractCol(
195078    const u8 **pa,                  /* IN/OUT: Pointer to poslist */
195079    int n,                          /* IN: Size of poslist in bytes */
195080    int iCol                        /* Column to extract from poslist */
195081  ){
195082    int iCurrent = 0;               /* Anything before the first 0x01 is col 0 */
195083    const u8 *p = *pa;
195084    const u8 *pEnd = &p[n];         /* One byte past end of position list */
195085  
195086    while( iCol>iCurrent ){
195087      /* Advance pointer p until it points to pEnd or an 0x01 byte that is
195088      ** not part of a varint. Note that it is not possible for a negative
195089      ** or extremely large varint to occur within an uncorrupted position 
195090      ** list. So the last byte of each varint may be assumed to have a clear
195091      ** 0x80 bit.  */
195092      while( *p!=0x01 ){
195093        while( *p++ & 0x80 );
195094        if( p>=pEnd ) return 0;
195095      }
195096      *pa = p++;
195097      iCurrent = *p++;
195098      if( iCurrent & 0x80 ){
195099        p--;
195100        p += fts5GetVarint32(p, iCurrent);
195101      }
195102    }
195103    if( iCol!=iCurrent ) return 0;
195104  
195105    /* Advance pointer p until it points to pEnd or an 0x01 byte that is
195106    ** not part of a varint */
195107    while( p<pEnd && *p!=0x01 ){
195108      while( *p++ & 0x80 );
195109    }
195110  
195111    return p - (*pa);
195112  }
195113  
195114  static void fts5IndexExtractColset(
195115    int *pRc,
195116    Fts5Colset *pColset,            /* Colset to filter on */
195117    const u8 *pPos, int nPos,       /* Position list */
195118    Fts5Buffer *pBuf                /* Output buffer */
195119  ){
195120    if( *pRc==SQLITE_OK ){
195121      int i;
195122      fts5BufferZero(pBuf);
195123      for(i=0; i<pColset->nCol; i++){
195124        const u8 *pSub = pPos;
195125        int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
195126        if( nSub ){
195127          fts5BufferAppendBlob(pRc, pBuf, nSub, pSub);
195128        }
195129      }
195130    }
195131  }
195132  
195133  /*
195134  ** xSetOutputs callback used by detail=none tables.
195135  */
195136  static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
195137    assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
195138    pIter->base.iRowid = pSeg->iRowid;
195139    pIter->base.nData = pSeg->nPos;
195140  }
195141  
195142  /*
195143  ** xSetOutputs callback used by detail=full and detail=col tables when no
195144  ** column filters are specified.
195145  */
195146  static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
195147    pIter->base.iRowid = pSeg->iRowid;
195148    pIter->base.nData = pSeg->nPos;
195149  
195150    assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
195151    assert( pIter->pColset==0 );
195152  
195153    if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
195154      /* All data is stored on the current page. Populate the output 
195155      ** variables to point into the body of the page object. */
195156      pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
195157    }else{
195158      /* The data is distributed over two or more pages. Copy it into the
195159      ** Fts5Iter.poslist buffer and then set the output pointer to point
195160      ** to this buffer.  */
195161      fts5BufferZero(&pIter->poslist);
195162      fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
195163      pIter->base.pData = pIter->poslist.p;
195164    }
195165  }
195166  
195167  /*
195168  ** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
195169  ** against no columns at all).
195170  */
195171  static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
195172    UNUSED_PARAM(pSeg);
195173    pIter->base.nData = 0;
195174  }
195175  
195176  /*
195177  ** xSetOutputs callback used by detail=col when there is a column filter
195178  ** and there are 100 or more columns. Also called as a fallback from
195179  ** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
195180  */
195181  static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
195182    fts5BufferZero(&pIter->poslist);
195183    fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
195184    pIter->base.iRowid = pSeg->iRowid;
195185    pIter->base.pData = pIter->poslist.p;
195186    pIter->base.nData = pIter->poslist.n;
195187  }
195188  
195189  /*
195190  ** xSetOutputs callback used when: 
195191  **
195192  **   * detail=col,
195193  **   * there is a column filter, and
195194  **   * the table contains 100 or fewer columns. 
195195  **
195196  ** The last point is to ensure all column numbers are stored as 
195197  ** single-byte varints.
195198  */
195199  static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
195200  
195201    assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
195202    assert( pIter->pColset );
195203  
195204    if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
195205      fts5IterSetOutputs_Col(pIter, pSeg);
195206    }else{
195207      u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
195208      u8 *pEnd = (u8*)&a[pSeg->nPos]; 
195209      int iPrev = 0;
195210      int *aiCol = pIter->pColset->aiCol;
195211      int *aiColEnd = &aiCol[pIter->pColset->nCol];
195212  
195213      u8 *aOut = pIter->poslist.p;
195214      int iPrevOut = 0;
195215  
195216      pIter->base.iRowid = pSeg->iRowid;
195217  
195218      while( a<pEnd ){
195219        iPrev += (int)a++[0] - 2;
195220        while( *aiCol<iPrev ){
195221          aiCol++;
195222          if( aiCol==aiColEnd ) goto setoutputs_col_out;
195223        }
195224        if( *aiCol==iPrev ){
195225          *aOut++ = (u8)((iPrev - iPrevOut) + 2);
195226          iPrevOut = iPrev;
195227        }
195228      }
195229  
195230  setoutputs_col_out:
195231      pIter->base.pData = pIter->poslist.p;
195232      pIter->base.nData = aOut - pIter->poslist.p;
195233    }
195234  }
195235  
195236  /*
195237  ** xSetOutputs callback used by detail=full when there is a column filter.
195238  */
195239  static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
195240    Fts5Colset *pColset = pIter->pColset;
195241    pIter->base.iRowid = pSeg->iRowid;
195242  
195243    assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
195244    assert( pColset );
195245  
195246    if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
195247      /* All data is stored on the current page. Populate the output 
195248      ** variables to point into the body of the page object. */
195249      const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
195250      if( pColset->nCol==1 ){
195251        pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
195252        pIter->base.pData = a;
195253      }else{
195254        int *pRc = &pIter->pIndex->rc;
195255        fts5BufferZero(&pIter->poslist);
195256        fts5IndexExtractColset(pRc, pColset, a, pSeg->nPos, &pIter->poslist);
195257        pIter->base.pData = pIter->poslist.p;
195258        pIter->base.nData = pIter->poslist.n;
195259      }
195260    }else{
195261      /* The data is distributed over two or more pages. Copy it into the
195262      ** Fts5Iter.poslist buffer and then set the output pointer to point
195263      ** to this buffer.  */
195264      fts5BufferZero(&pIter->poslist);
195265      fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
195266      pIter->base.pData = pIter->poslist.p;
195267      pIter->base.nData = pIter->poslist.n;
195268    }
195269  }
195270  
195271  static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
195272    if( *pRc==SQLITE_OK ){
195273      Fts5Config *pConfig = pIter->pIndex->pConfig;
195274      if( pConfig->eDetail==FTS5_DETAIL_NONE ){
195275        pIter->xSetOutputs = fts5IterSetOutputs_None;
195276      }
195277  
195278      else if( pIter->pColset==0 ){
195279        pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
195280      }
195281  
195282      else if( pIter->pColset->nCol==0 ){
195283        pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
195284      }
195285  
195286      else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
195287        pIter->xSetOutputs = fts5IterSetOutputs_Full;
195288      }
195289  
195290      else{
195291        assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
195292        if( pConfig->nCol<=100 ){
195293          pIter->xSetOutputs = fts5IterSetOutputs_Col100;
195294          sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
195295        }else{
195296          pIter->xSetOutputs = fts5IterSetOutputs_Col;
195297        }
195298      }
195299    }
195300  }
195301  
195302  
195303  /*
195304  ** Allocate a new Fts5Iter object.
195305  **
195306  ** The new object will be used to iterate through data in structure pStruct.
195307  ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
195308  ** is zero or greater, data from the first nSegment segments on level iLevel
195309  ** is merged.
195310  **
195311  ** The iterator initially points to the first term/rowid entry in the 
195312  ** iterated data.
195313  */
195314  static void fts5MultiIterNew(
195315    Fts5Index *p,                   /* FTS5 backend to iterate within */
195316    Fts5Structure *pStruct,         /* Structure of specific index */
195317    int flags,                      /* FTS5INDEX_QUERY_XXX flags */
195318    Fts5Colset *pColset,            /* Colset to filter on (or NULL) */
195319    const u8 *pTerm, int nTerm,     /* Term to seek to (or NULL/0) */
195320    int iLevel,                     /* Level to iterate (-1 for all) */
195321    int nSegment,                   /* Number of segments to merge (iLevel>=0) */
195322    Fts5Iter **ppOut                /* New object */
195323  ){
195324    int nSeg = 0;                   /* Number of segment-iters in use */
195325    int iIter = 0;                  /* */
195326    int iSeg;                       /* Used to iterate through segments */
195327    Fts5StructureLevel *pLvl;
195328    Fts5Iter *pNew;
195329  
195330    assert( (pTerm==0 && nTerm==0) || iLevel<0 );
195331  
195332    /* Allocate space for the new multi-seg-iterator. */
195333    if( p->rc==SQLITE_OK ){
195334      if( iLevel<0 ){
195335        assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
195336        nSeg = pStruct->nSegment;
195337        nSeg += (p->pHash ? 1 : 0);
195338      }else{
195339        nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
195340      }
195341    }
195342    *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
195343    if( pNew==0 ) return;
195344    pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
195345    pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
195346    pNew->pStruct = pStruct;
195347    pNew->pColset = pColset;
195348    fts5StructureRef(pStruct);
195349    if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
195350      fts5IterSetOutputCb(&p->rc, pNew);
195351    }
195352  
195353    /* Initialize each of the component segment iterators. */
195354    if( p->rc==SQLITE_OK ){
195355      if( iLevel<0 ){
195356        Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
195357        if( p->pHash ){
195358          /* Add a segment iterator for the current contents of the hash table. */
195359          Fts5SegIter *pIter = &pNew->aSeg[iIter++];
195360          fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
195361        }
195362        for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
195363          for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
195364            Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
195365            Fts5SegIter *pIter = &pNew->aSeg[iIter++];
195366            if( pTerm==0 ){
195367              fts5SegIterInit(p, pSeg, pIter);
195368            }else{
195369              fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
195370            }
195371          }
195372        }
195373      }else{
195374        pLvl = &pStruct->aLevel[iLevel];
195375        for(iSeg=nSeg-1; iSeg>=0; iSeg--){
195376          fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
195377        }
195378      }
195379      assert( iIter==nSeg );
195380    }
195381  
195382    /* If the above was successful, each component iterators now points 
195383    ** to the first entry in its segment. In this case initialize the 
195384    ** aFirst[] array. Or, if an error has occurred, free the iterator
195385    ** object and set the output variable to NULL.  */
195386    if( p->rc==SQLITE_OK ){
195387      for(iIter=pNew->nSeg-1; iIter>0; iIter--){
195388        int iEq;
195389        if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
195390          Fts5SegIter *pSeg = &pNew->aSeg[iEq];
195391          if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
195392          fts5MultiIterAdvanced(p, pNew, iEq, iIter);
195393        }
195394      }
195395      fts5MultiIterSetEof(pNew);
195396      fts5AssertMultiIterSetup(p, pNew);
195397  
195398      if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
195399        fts5MultiIterNext(p, pNew, 0, 0);
195400      }else if( pNew->base.bEof==0 ){
195401        Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
195402        pNew->xSetOutputs(pNew, pSeg);
195403      }
195404  
195405    }else{
195406      fts5MultiIterFree(pNew);
195407      *ppOut = 0;
195408    }
195409  }
195410  
195411  /*
195412  ** Create an Fts5Iter that iterates through the doclist provided
195413  ** as the second argument.
195414  */
195415  static void fts5MultiIterNew2(
195416    Fts5Index *p,                   /* FTS5 backend to iterate within */
195417    Fts5Data *pData,                /* Doclist to iterate through */
195418    int bDesc,                      /* True for descending rowid order */
195419    Fts5Iter **ppOut                /* New object */
195420  ){
195421    Fts5Iter *pNew;
195422    pNew = fts5MultiIterAlloc(p, 2);
195423    if( pNew ){
195424      Fts5SegIter *pIter = &pNew->aSeg[1];
195425  
195426      pIter->flags = FTS5_SEGITER_ONETERM;
195427      if( pData->szLeaf>0 ){
195428        pIter->pLeaf = pData;
195429        pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
195430        pIter->iEndofDoclist = pData->nn;
195431        pNew->aFirst[1].iFirst = 1;
195432        if( bDesc ){
195433          pNew->bRev = 1;
195434          pIter->flags |= FTS5_SEGITER_REVERSE;
195435          fts5SegIterReverseInitPage(p, pIter);
195436        }else{
195437          fts5SegIterLoadNPos(p, pIter);
195438        }
195439        pData = 0;
195440      }else{
195441        pNew->base.bEof = 1;
195442      }
195443      fts5SegIterSetNext(p, pIter);
195444  
195445      *ppOut = pNew;
195446    }
195447  
195448    fts5DataRelease(pData);
195449  }
195450  
195451  /*
195452  ** Return true if the iterator is at EOF or if an error has occurred. 
195453  ** False otherwise.
195454  */
195455  static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
195456    assert( p->rc 
195457        || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof 
195458    );
195459    return (p->rc || pIter->base.bEof);
195460  }
195461  
195462  /*
195463  ** Return the rowid of the entry that the iterator currently points
195464  ** to. If the iterator points to EOF when this function is called the
195465  ** results are undefined.
195466  */
195467  static i64 fts5MultiIterRowid(Fts5Iter *pIter){
195468    assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
195469    return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
195470  }
195471  
195472  /*
195473  ** Move the iterator to the next entry at or following iMatch.
195474  */
195475  static void fts5MultiIterNextFrom(
195476    Fts5Index *p, 
195477    Fts5Iter *pIter, 
195478    i64 iMatch
195479  ){
195480    while( 1 ){
195481      i64 iRowid;
195482      fts5MultiIterNext(p, pIter, 1, iMatch);
195483      if( fts5MultiIterEof(p, pIter) ) break;
195484      iRowid = fts5MultiIterRowid(pIter);
195485      if( pIter->bRev==0 && iRowid>=iMatch ) break;
195486      if( pIter->bRev!=0 && iRowid<=iMatch ) break;
195487    }
195488  }
195489  
195490  /*
195491  ** Return a pointer to a buffer containing the term associated with the 
195492  ** entry that the iterator currently points to.
195493  */
195494  static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
195495    Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
195496    *pn = p->term.n;
195497    return p->term.p;
195498  }
195499  
195500  /*
195501  ** Allocate a new segment-id for the structure pStruct. The new segment
195502  ** id must be between 1 and 65335 inclusive, and must not be used by 
195503  ** any currently existing segment. If a free segment id cannot be found,
195504  ** SQLITE_FULL is returned.
195505  **
195506  ** If an error has already occurred, this function is a no-op. 0 is 
195507  ** returned in this case.
195508  */
195509  static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
195510    int iSegid = 0;
195511  
195512    if( p->rc==SQLITE_OK ){
195513      if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
195514        p->rc = SQLITE_FULL;
195515      }else{
195516        /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
195517        ** array is 63 elements, or 252 bytes, in size.  */
195518        u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
195519        int iLvl, iSeg;
195520        int i;
195521        u32 mask;
195522        memset(aUsed, 0, sizeof(aUsed));
195523        for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
195524          for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
195525            int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
195526            if( iId<=FTS5_MAX_SEGMENT ){
195527              aUsed[(iId-1) / 32] |= 1 << ((iId-1) % 32);
195528            }
195529          }
195530        }
195531  
195532        for(i=0; aUsed[i]==0xFFFFFFFF; i++);
195533        mask = aUsed[i];
195534        for(iSegid=0; mask & (1 << iSegid); iSegid++);
195535        iSegid += 1 + i*32;
195536  
195537  #ifdef SQLITE_DEBUG
195538        for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
195539          for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
195540            assert( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
195541          }
195542        }
195543        assert( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
195544  
195545        {
195546          sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
195547          if( p->rc==SQLITE_OK ){
195548            u8 aBlob[2] = {0xff, 0xff};
195549            sqlite3_bind_int(pIdxSelect, 1, iSegid);
195550            sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
195551            assert( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
195552            p->rc = sqlite3_reset(pIdxSelect);
195553          }
195554        }
195555  #endif
195556      }
195557    }
195558  
195559    return iSegid;
195560  }
195561  
195562  /*
195563  ** Discard all data currently cached in the hash-tables.
195564  */
195565  static void fts5IndexDiscardData(Fts5Index *p){
195566    assert( p->pHash || p->nPendingData==0 );
195567    if( p->pHash ){
195568      sqlite3Fts5HashClear(p->pHash);
195569      p->nPendingData = 0;
195570    }
195571  }
195572  
195573  /*
195574  ** Return the size of the prefix, in bytes, that buffer 
195575  ** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
195576  **
195577  ** Buffer (pNew/<length-unknown>) is guaranteed to be greater 
195578  ** than buffer (pOld/nOld).
195579  */
195580  static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
195581    int i;
195582    for(i=0; i<nOld; i++){
195583      if( pOld[i]!=pNew[i] ) break;
195584    }
195585    return i;
195586  }
195587  
195588  static void fts5WriteDlidxClear(
195589    Fts5Index *p, 
195590    Fts5SegWriter *pWriter,
195591    int bFlush                      /* If true, write dlidx to disk */
195592  ){
195593    int i;
195594    assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
195595    for(i=0; i<pWriter->nDlidx; i++){
195596      Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
195597      if( pDlidx->buf.n==0 ) break;
195598      if( bFlush ){
195599        assert( pDlidx->pgno!=0 );
195600        fts5DataWrite(p, 
195601            FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
195602            pDlidx->buf.p, pDlidx->buf.n
195603        );
195604      }
195605      sqlite3Fts5BufferZero(&pDlidx->buf);
195606      pDlidx->bPrevValid = 0;
195607    }
195608  }
195609  
195610  /*
195611  ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
195612  ** Any new array elements are zeroed before returning.
195613  */
195614  static int fts5WriteDlidxGrow(
195615    Fts5Index *p,
195616    Fts5SegWriter *pWriter,
195617    int nLvl
195618  ){
195619    if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
195620      Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
195621          pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
195622      );
195623      if( aDlidx==0 ){
195624        p->rc = SQLITE_NOMEM;
195625      }else{
195626        int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
195627        memset(&aDlidx[pWriter->nDlidx], 0, nByte);
195628        pWriter->aDlidx = aDlidx;
195629        pWriter->nDlidx = nLvl;
195630      }
195631    }
195632    return p->rc;
195633  }
195634  
195635  /*
195636  ** If the current doclist-index accumulating in pWriter->aDlidx[] is large
195637  ** enough, flush it to disk and return 1. Otherwise discard it and return
195638  ** zero.
195639  */
195640  static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
195641    int bFlag = 0;
195642  
195643    /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
195644    ** to the database, also write the doclist-index to disk.  */
195645    if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
195646      bFlag = 1;
195647    }
195648    fts5WriteDlidxClear(p, pWriter, bFlag);
195649    pWriter->nEmpty = 0;
195650    return bFlag;
195651  }
195652  
195653  /*
195654  ** This function is called whenever processing of the doclist for the 
195655  ** last term on leaf page (pWriter->iBtPage) is completed. 
195656  **
195657  ** The doclist-index for that term is currently stored in-memory within the
195658  ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
195659  ** writes it out to disk. Or, if it is too small to bother with, discards
195660  ** it.
195661  **
195662  ** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
195663  */
195664  static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
195665    int bFlag;
195666  
195667    assert( pWriter->iBtPage || pWriter->nEmpty==0 );
195668    if( pWriter->iBtPage==0 ) return;
195669    bFlag = fts5WriteFlushDlidx(p, pWriter);
195670  
195671    if( p->rc==SQLITE_OK ){
195672      const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
195673      /* The following was already done in fts5WriteInit(): */
195674      /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
195675      sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
195676      sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
195677      sqlite3_step(p->pIdxWriter);
195678      p->rc = sqlite3_reset(p->pIdxWriter);
195679    }
195680    pWriter->iBtPage = 0;
195681  }
195682  
195683  /*
195684  ** This is called once for each leaf page except the first that contains
195685  ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
195686  ** is larger than all terms written to earlier leaves, and equal to or
195687  ** smaller than the first term on the new leaf.
195688  **
195689  ** If an error occurs, an error code is left in Fts5Index.rc. If an error
195690  ** has already occurred when this function is called, it is a no-op.
195691  */
195692  static void fts5WriteBtreeTerm(
195693    Fts5Index *p,                   /* FTS5 backend object */
195694    Fts5SegWriter *pWriter,         /* Writer object */
195695    int nTerm, const u8 *pTerm      /* First term on new page */
195696  ){
195697    fts5WriteFlushBtree(p, pWriter);
195698    fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
195699    pWriter->iBtPage = pWriter->writer.pgno;
195700  }
195701  
195702  /*
195703  ** This function is called when flushing a leaf page that contains no
195704  ** terms at all to disk.
195705  */
195706  static void fts5WriteBtreeNoTerm(
195707    Fts5Index *p,                   /* FTS5 backend object */
195708    Fts5SegWriter *pWriter          /* Writer object */
195709  ){
195710    /* If there were no rowids on the leaf page either and the doclist-index
195711    ** has already been started, append an 0x00 byte to it.  */
195712    if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
195713      Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
195714      assert( pDlidx->bPrevValid );
195715      sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
195716    }
195717  
195718    /* Increment the "number of sequential leaves without a term" counter. */
195719    pWriter->nEmpty++;
195720  }
195721  
195722  static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
195723    i64 iRowid;
195724    int iOff;
195725  
195726    iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
195727    fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
195728    return iRowid;
195729  }
195730  
195731  /*
195732  ** Rowid iRowid has just been appended to the current leaf page. It is the
195733  ** first on the page. This function appends an appropriate entry to the current
195734  ** doclist-index.
195735  */
195736  static void fts5WriteDlidxAppend(
195737    Fts5Index *p, 
195738    Fts5SegWriter *pWriter, 
195739    i64 iRowid
195740  ){
195741    int i;
195742    int bDone = 0;
195743  
195744    for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
195745      i64 iVal;
195746      Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
195747  
195748      if( pDlidx->buf.n>=p->pConfig->pgsz ){
195749        /* The current doclist-index page is full. Write it to disk and push
195750        ** a copy of iRowid (which will become the first rowid on the next
195751        ** doclist-index leaf page) up into the next level of the b-tree 
195752        ** hierarchy. If the node being flushed is currently the root node,
195753        ** also push its first rowid upwards. */
195754        pDlidx->buf.p[0] = 0x01;    /* Not the root node */
195755        fts5DataWrite(p, 
195756            FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
195757            pDlidx->buf.p, pDlidx->buf.n
195758        );
195759        fts5WriteDlidxGrow(p, pWriter, i+2);
195760        pDlidx = &pWriter->aDlidx[i];
195761        if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
195762          i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
195763  
195764          /* This was the root node. Push its first rowid up to the new root. */
195765          pDlidx[1].pgno = pDlidx->pgno;
195766          sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
195767          sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
195768          sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
195769          pDlidx[1].bPrevValid = 1;
195770          pDlidx[1].iPrev = iFirst;
195771        }
195772  
195773        sqlite3Fts5BufferZero(&pDlidx->buf);
195774        pDlidx->bPrevValid = 0;
195775        pDlidx->pgno++;
195776      }else{
195777        bDone = 1;
195778      }
195779  
195780      if( pDlidx->bPrevValid ){
195781        iVal = iRowid - pDlidx->iPrev;
195782      }else{
195783        i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
195784        assert( pDlidx->buf.n==0 );
195785        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
195786        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
195787        iVal = iRowid;
195788      }
195789  
195790      sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
195791      pDlidx->bPrevValid = 1;
195792      pDlidx->iPrev = iRowid;
195793    }
195794  }
195795  
195796  static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
195797    static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
195798    Fts5PageWriter *pPage = &pWriter->writer;
195799    i64 iRowid;
195800  
195801    assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
195802  
195803    /* Set the szLeaf header field. */
195804    assert( 0==fts5GetU16(&pPage->buf.p[2]) );
195805    fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
195806  
195807    if( pWriter->bFirstTermInPage ){
195808      /* No term was written to this page. */
195809      assert( pPage->pgidx.n==0 );
195810      fts5WriteBtreeNoTerm(p, pWriter);
195811    }else{
195812      /* Append the pgidx to the page buffer. Set the szLeaf header field. */
195813      fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
195814    }
195815  
195816    /* Write the page out to disk */
195817    iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
195818    fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
195819  
195820    /* Initialize the next page. */
195821    fts5BufferZero(&pPage->buf);
195822    fts5BufferZero(&pPage->pgidx);
195823    fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
195824    pPage->iPrevPgidx = 0;
195825    pPage->pgno++;
195826  
195827    /* Increase the leaves written counter */
195828    pWriter->nLeafWritten++;
195829  
195830    /* The new leaf holds no terms or rowids */
195831    pWriter->bFirstTermInPage = 1;
195832    pWriter->bFirstRowidInPage = 1;
195833  }
195834  
195835  /*
195836  ** Append term pTerm/nTerm to the segment being written by the writer passed
195837  ** as the second argument.
195838  **
195839  ** If an error occurs, set the Fts5Index.rc error code. If an error has 
195840  ** already occurred, this function is a no-op.
195841  */
195842  static void fts5WriteAppendTerm(
195843    Fts5Index *p, 
195844    Fts5SegWriter *pWriter,
195845    int nTerm, const u8 *pTerm 
195846  ){
195847    int nPrefix;                    /* Bytes of prefix compression for term */
195848    Fts5PageWriter *pPage = &pWriter->writer;
195849    Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
195850  
195851    assert( p->rc==SQLITE_OK );
195852    assert( pPage->buf.n>=4 );
195853    assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
195854  
195855    /* If the current leaf page is full, flush it to disk. */
195856    if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
195857      if( pPage->buf.n>4 ){
195858        fts5WriteFlushLeaf(p, pWriter);
195859      }
195860      fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
195861    }
195862    
195863    /* TODO1: Updating pgidx here. */
195864    pPgidx->n += sqlite3Fts5PutVarint(
195865        &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
195866    );
195867    pPage->iPrevPgidx = pPage->buf.n;
195868  #if 0
195869    fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
195870    pPgidx->n += 2;
195871  #endif
195872  
195873    if( pWriter->bFirstTermInPage ){
195874      nPrefix = 0;
195875      if( pPage->pgno!=1 ){
195876        /* This is the first term on a leaf that is not the leftmost leaf in
195877        ** the segment b-tree. In this case it is necessary to add a term to
195878        ** the b-tree hierarchy that is (a) larger than the largest term 
195879        ** already written to the segment and (b) smaller than or equal to
195880        ** this term. In other words, a prefix of (pTerm/nTerm) that is one
195881        ** byte longer than the longest prefix (pTerm/nTerm) shares with the
195882        ** previous term. 
195883        **
195884        ** Usually, the previous term is available in pPage->term. The exception
195885        ** is if this is the first term written in an incremental-merge step.
195886        ** In this case the previous term is not available, so just write a
195887        ** copy of (pTerm/nTerm) into the parent node. This is slightly
195888        ** inefficient, but still correct.  */
195889        int n = nTerm;
195890        if( pPage->term.n ){
195891          n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
195892        }
195893        fts5WriteBtreeTerm(p, pWriter, n, pTerm);
195894        pPage = &pWriter->writer;
195895      }
195896    }else{
195897      nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
195898      fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
195899    }
195900  
195901    /* Append the number of bytes of new data, then the term data itself
195902    ** to the page. */
195903    fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
195904    fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
195905  
195906    /* Update the Fts5PageWriter.term field. */
195907    fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
195908    pWriter->bFirstTermInPage = 0;
195909  
195910    pWriter->bFirstRowidInPage = 0;
195911    pWriter->bFirstRowidInDoclist = 1;
195912  
195913    assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
195914    pWriter->aDlidx[0].pgno = pPage->pgno;
195915  }
195916  
195917  /*
195918  ** Append a rowid and position-list size field to the writers output. 
195919  */
195920  static void fts5WriteAppendRowid(
195921    Fts5Index *p, 
195922    Fts5SegWriter *pWriter,
195923    i64 iRowid
195924  ){
195925    if( p->rc==SQLITE_OK ){
195926      Fts5PageWriter *pPage = &pWriter->writer;
195927  
195928      if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
195929        fts5WriteFlushLeaf(p, pWriter);
195930      }
195931  
195932      /* If this is to be the first rowid written to the page, set the 
195933      ** rowid-pointer in the page-header. Also append a value to the dlidx
195934      ** buffer, in case a doclist-index is required.  */
195935      if( pWriter->bFirstRowidInPage ){
195936        fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
195937        fts5WriteDlidxAppend(p, pWriter, iRowid);
195938      }
195939  
195940      /* Write the rowid. */
195941      if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
195942        fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
195943      }else{
195944        assert( p->rc || iRowid>pWriter->iPrevRowid );
195945        fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
195946      }
195947      pWriter->iPrevRowid = iRowid;
195948      pWriter->bFirstRowidInDoclist = 0;
195949      pWriter->bFirstRowidInPage = 0;
195950    }
195951  }
195952  
195953  static void fts5WriteAppendPoslistData(
195954    Fts5Index *p, 
195955    Fts5SegWriter *pWriter, 
195956    const u8 *aData, 
195957    int nData
195958  ){
195959    Fts5PageWriter *pPage = &pWriter->writer;
195960    const u8 *a = aData;
195961    int n = nData;
195962    
195963    assert( p->pConfig->pgsz>0 );
195964    while( p->rc==SQLITE_OK 
195965       && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz 
195966    ){
195967      int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
195968      int nCopy = 0;
195969      while( nCopy<nReq ){
195970        i64 dummy;
195971        nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
195972      }
195973      fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
195974      a += nCopy;
195975      n -= nCopy;
195976      fts5WriteFlushLeaf(p, pWriter);
195977    }
195978    if( n>0 ){
195979      fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
195980    }
195981  }
195982  
195983  /*
195984  ** Flush any data cached by the writer object to the database. Free any
195985  ** allocations associated with the writer.
195986  */
195987  static void fts5WriteFinish(
195988    Fts5Index *p, 
195989    Fts5SegWriter *pWriter,         /* Writer object */
195990    int *pnLeaf                     /* OUT: Number of leaf pages in b-tree */
195991  ){
195992    int i;
195993    Fts5PageWriter *pLeaf = &pWriter->writer;
195994    if( p->rc==SQLITE_OK ){
195995      assert( pLeaf->pgno>=1 );
195996      if( pLeaf->buf.n>4 ){
195997        fts5WriteFlushLeaf(p, pWriter);
195998      }
195999      *pnLeaf = pLeaf->pgno-1;
196000      if( pLeaf->pgno>1 ){
196001        fts5WriteFlushBtree(p, pWriter);
196002      }
196003    }
196004    fts5BufferFree(&pLeaf->term);
196005    fts5BufferFree(&pLeaf->buf);
196006    fts5BufferFree(&pLeaf->pgidx);
196007    fts5BufferFree(&pWriter->btterm);
196008  
196009    for(i=0; i<pWriter->nDlidx; i++){
196010      sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
196011    }
196012    sqlite3_free(pWriter->aDlidx);
196013  }
196014  
196015  static void fts5WriteInit(
196016    Fts5Index *p, 
196017    Fts5SegWriter *pWriter, 
196018    int iSegid
196019  ){
196020    const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
196021  
196022    memset(pWriter, 0, sizeof(Fts5SegWriter));
196023    pWriter->iSegid = iSegid;
196024  
196025    fts5WriteDlidxGrow(p, pWriter, 1);
196026    pWriter->writer.pgno = 1;
196027    pWriter->bFirstTermInPage = 1;
196028    pWriter->iBtPage = 1;
196029  
196030    assert( pWriter->writer.buf.n==0 );
196031    assert( pWriter->writer.pgidx.n==0 );
196032  
196033    /* Grow the two buffers to pgsz + padding bytes in size. */
196034    sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
196035    sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
196036  
196037    if( p->pIdxWriter==0 ){
196038      Fts5Config *pConfig = p->pConfig;
196039      fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
196040            "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)", 
196041            pConfig->zDb, pConfig->zName
196042      ));
196043    }
196044  
196045    if( p->rc==SQLITE_OK ){
196046      /* Initialize the 4-byte leaf-page header to 0x00. */
196047      memset(pWriter->writer.buf.p, 0, 4);
196048      pWriter->writer.buf.n = 4;
196049  
196050      /* Bind the current output segment id to the index-writer. This is an
196051      ** optimization over binding the same value over and over as rows are
196052      ** inserted into %_idx by the current writer.  */
196053      sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
196054    }
196055  }
196056  
196057  /*
196058  ** Iterator pIter was used to iterate through the input segments of on an
196059  ** incremental merge operation. This function is called if the incremental
196060  ** merge step has finished but the input has not been completely exhausted.
196061  */
196062  static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
196063    int i;
196064    Fts5Buffer buf;
196065    memset(&buf, 0, sizeof(Fts5Buffer));
196066    for(i=0; i<pIter->nSeg; i++){
196067      Fts5SegIter *pSeg = &pIter->aSeg[i];
196068      if( pSeg->pSeg==0 ){
196069        /* no-op */
196070      }else if( pSeg->pLeaf==0 ){
196071        /* All keys from this input segment have been transfered to the output.
196072        ** Set both the first and last page-numbers to 0 to indicate that the
196073        ** segment is now empty. */
196074        pSeg->pSeg->pgnoLast = 0;
196075        pSeg->pSeg->pgnoFirst = 0;
196076      }else{
196077        int iOff = pSeg->iTermLeafOffset;     /* Offset on new first leaf page */
196078        i64 iLeafRowid;
196079        Fts5Data *pData;
196080        int iId = pSeg->pSeg->iSegid;
196081        u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
196082  
196083        iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
196084        pData = fts5DataRead(p, iLeafRowid);
196085        if( pData ){
196086          fts5BufferZero(&buf);
196087          fts5BufferGrow(&p->rc, &buf, pData->nn);
196088          fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
196089          fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
196090          fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
196091          fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
196092          if( p->rc==SQLITE_OK ){
196093            /* Set the szLeaf field */
196094            fts5PutU16(&buf.p[2], (u16)buf.n);
196095          }
196096  
196097          /* Set up the new page-index array */
196098          fts5BufferAppendVarint(&p->rc, &buf, 4);
196099          if( pSeg->iLeafPgno==pSeg->iTermLeafPgno 
196100           && pSeg->iEndofDoclist<pData->szLeaf 
196101          ){
196102            int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
196103            fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
196104            fts5BufferAppendBlob(&p->rc, &buf, 
196105                pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
196106            );
196107          }
196108  
196109          fts5DataRelease(pData);
196110          pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
196111          fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
196112          fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
196113        }
196114      }
196115    }
196116    fts5BufferFree(&buf);
196117  }
196118  
196119  static void fts5MergeChunkCallback(
196120    Fts5Index *p, 
196121    void *pCtx, 
196122    const u8 *pChunk, int nChunk
196123  ){
196124    Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
196125    fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
196126  }
196127  
196128  /*
196129  **
196130  */
196131  static void fts5IndexMergeLevel(
196132    Fts5Index *p,                   /* FTS5 backend object */
196133    Fts5Structure **ppStruct,       /* IN/OUT: Stucture of index */
196134    int iLvl,                       /* Level to read input from */
196135    int *pnRem                      /* Write up to this many output leaves */
196136  ){
196137    Fts5Structure *pStruct = *ppStruct;
196138    Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
196139    Fts5StructureLevel *pLvlOut;
196140    Fts5Iter *pIter = 0;       /* Iterator to read input data */
196141    int nRem = pnRem ? *pnRem : 0;  /* Output leaf pages left to write */
196142    int nInput;                     /* Number of input segments */
196143    Fts5SegWriter writer;           /* Writer object */
196144    Fts5StructureSegment *pSeg;     /* Output segment */
196145    Fts5Buffer term;
196146    int bOldest;                    /* True if the output segment is the oldest */
196147    int eDetail = p->pConfig->eDetail;
196148    const int flags = FTS5INDEX_QUERY_NOOUTPUT;
196149    int bTermWritten = 0;           /* True if current term already output */
196150  
196151    assert( iLvl<pStruct->nLevel );
196152    assert( pLvl->nMerge<=pLvl->nSeg );
196153  
196154    memset(&writer, 0, sizeof(Fts5SegWriter));
196155    memset(&term, 0, sizeof(Fts5Buffer));
196156    if( pLvl->nMerge ){
196157      pLvlOut = &pStruct->aLevel[iLvl+1];
196158      assert( pLvlOut->nSeg>0 );
196159      nInput = pLvl->nMerge;
196160      pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
196161  
196162      fts5WriteInit(p, &writer, pSeg->iSegid);
196163      writer.writer.pgno = pSeg->pgnoLast+1;
196164      writer.iBtPage = 0;
196165    }else{
196166      int iSegid = fts5AllocateSegid(p, pStruct);
196167  
196168      /* Extend the Fts5Structure object as required to ensure the output
196169      ** segment exists. */
196170      if( iLvl==pStruct->nLevel-1 ){
196171        fts5StructureAddLevel(&p->rc, ppStruct);
196172        pStruct = *ppStruct;
196173      }
196174      fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
196175      if( p->rc ) return;
196176      pLvl = &pStruct->aLevel[iLvl];
196177      pLvlOut = &pStruct->aLevel[iLvl+1];
196178  
196179      fts5WriteInit(p, &writer, iSegid);
196180  
196181      /* Add the new segment to the output level */
196182      pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
196183      pLvlOut->nSeg++;
196184      pSeg->pgnoFirst = 1;
196185      pSeg->iSegid = iSegid;
196186      pStruct->nSegment++;
196187  
196188      /* Read input from all segments in the input level */
196189      nInput = pLvl->nSeg;
196190    }
196191    bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
196192  
196193    assert( iLvl>=0 );
196194    for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
196195        fts5MultiIterEof(p, pIter)==0;
196196        fts5MultiIterNext(p, pIter, 0, 0)
196197    ){
196198      Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
196199      int nPos;                     /* position-list size field value */
196200      int nTerm;
196201      const u8 *pTerm;
196202  
196203      pTerm = fts5MultiIterTerm(pIter, &nTerm);
196204      if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
196205        if( pnRem && writer.nLeafWritten>nRem ){
196206          break;
196207        }
196208        fts5BufferSet(&p->rc, &term, nTerm, pTerm);
196209        bTermWritten =0;
196210      }
196211  
196212      /* Check for key annihilation. */
196213      if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
196214  
196215      if( p->rc==SQLITE_OK && bTermWritten==0 ){
196216        /* This is a new term. Append a term to the output segment. */
196217        fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
196218        bTermWritten = 1;
196219      }
196220  
196221      /* Append the rowid to the output */
196222      /* WRITEPOSLISTSIZE */
196223      fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
196224  
196225      if( eDetail==FTS5_DETAIL_NONE ){
196226        if( pSegIter->bDel ){
196227          fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
196228          if( pSegIter->nPos>0 ){
196229            fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
196230          }
196231        }
196232      }else{
196233        /* Append the position-list data to the output */
196234        nPos = pSegIter->nPos*2 + pSegIter->bDel;
196235        fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
196236        fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
196237      }
196238    }
196239  
196240    /* Flush the last leaf page to disk. Set the output segment b-tree height
196241    ** and last leaf page number at the same time.  */
196242    fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
196243  
196244    if( fts5MultiIterEof(p, pIter) ){
196245      int i;
196246  
196247      /* Remove the redundant segments from the %_data table */
196248      for(i=0; i<nInput; i++){
196249        fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
196250      }
196251  
196252      /* Remove the redundant segments from the input level */
196253      if( pLvl->nSeg!=nInput ){
196254        int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
196255        memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
196256      }
196257      pStruct->nSegment -= nInput;
196258      pLvl->nSeg -= nInput;
196259      pLvl->nMerge = 0;
196260      if( pSeg->pgnoLast==0 ){
196261        pLvlOut->nSeg--;
196262        pStruct->nSegment--;
196263      }
196264    }else{
196265      assert( pSeg->pgnoLast>0 );
196266      fts5TrimSegments(p, pIter);
196267      pLvl->nMerge = nInput;
196268    }
196269  
196270    fts5MultiIterFree(pIter);
196271    fts5BufferFree(&term);
196272    if( pnRem ) *pnRem -= writer.nLeafWritten;
196273  }
196274  
196275  /*
196276  ** Do up to nPg pages of automerge work on the index.
196277  **
196278  ** Return true if any changes were actually made, or false otherwise.
196279  */
196280  static int fts5IndexMerge(
196281    Fts5Index *p,                   /* FTS5 backend object */
196282    Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
196283    int nPg,                        /* Pages of work to do */
196284    int nMin                        /* Minimum number of segments to merge */
196285  ){
196286    int nRem = nPg;
196287    int bRet = 0;
196288    Fts5Structure *pStruct = *ppStruct;
196289    while( nRem>0 && p->rc==SQLITE_OK ){
196290      int iLvl;                   /* To iterate through levels */
196291      int iBestLvl = 0;           /* Level offering the most input segments */
196292      int nBest = 0;              /* Number of input segments on best level */
196293  
196294      /* Set iBestLvl to the level to read input segments from. */
196295      assert( pStruct->nLevel>0 );
196296      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
196297        Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
196298        if( pLvl->nMerge ){
196299          if( pLvl->nMerge>nBest ){
196300            iBestLvl = iLvl;
196301            nBest = pLvl->nMerge;
196302          }
196303          break;
196304        }
196305        if( pLvl->nSeg>nBest ){
196306          nBest = pLvl->nSeg;
196307          iBestLvl = iLvl;
196308        }
196309      }
196310  
196311      /* If nBest is still 0, then the index must be empty. */
196312  #ifdef SQLITE_DEBUG
196313      for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
196314        assert( pStruct->aLevel[iLvl].nSeg==0 );
196315      }
196316  #endif
196317  
196318      if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
196319        break;
196320      }
196321      bRet = 1;
196322      fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
196323      if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
196324        fts5StructurePromote(p, iBestLvl+1, pStruct);
196325      }
196326    }
196327    *ppStruct = pStruct;
196328    return bRet;
196329  }
196330  
196331  /*
196332  ** A total of nLeaf leaf pages of data has just been flushed to a level-0
196333  ** segment. This function updates the write-counter accordingly and, if
196334  ** necessary, performs incremental merge work.
196335  **
196336  ** If an error occurs, set the Fts5Index.rc error code. If an error has 
196337  ** already occurred, this function is a no-op.
196338  */
196339  static void fts5IndexAutomerge(
196340    Fts5Index *p,                   /* FTS5 backend object */
196341    Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
196342    int nLeaf                       /* Number of output leaves just written */
196343  ){
196344    if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
196345      Fts5Structure *pStruct = *ppStruct;
196346      u64 nWrite;                   /* Initial value of write-counter */
196347      int nWork;                    /* Number of work-quanta to perform */
196348      int nRem;                     /* Number of leaf pages left to write */
196349  
196350      /* Update the write-counter. While doing so, set nWork. */
196351      nWrite = pStruct->nWriteCounter;
196352      nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
196353      pStruct->nWriteCounter += nLeaf;
196354      nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
196355  
196356      fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
196357    }
196358  }
196359  
196360  static void fts5IndexCrisismerge(
196361    Fts5Index *p,                   /* FTS5 backend object */
196362    Fts5Structure **ppStruct        /* IN/OUT: Current structure of index */
196363  ){
196364    const int nCrisis = p->pConfig->nCrisisMerge;
196365    Fts5Structure *pStruct = *ppStruct;
196366    int iLvl = 0;
196367  
196368    assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
196369    while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
196370      fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
196371      assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
196372      fts5StructurePromote(p, iLvl+1, pStruct);
196373      iLvl++;
196374    }
196375    *ppStruct = pStruct;
196376  }
196377  
196378  static int fts5IndexReturn(Fts5Index *p){
196379    int rc = p->rc;
196380    p->rc = SQLITE_OK;
196381    return rc;
196382  }
196383  
196384  typedef struct Fts5FlushCtx Fts5FlushCtx;
196385  struct Fts5FlushCtx {
196386    Fts5Index *pIdx;
196387    Fts5SegWriter writer; 
196388  };
196389  
196390  /*
196391  ** Buffer aBuf[] contains a list of varints, all small enough to fit
196392  ** in a 32-bit integer. Return the size of the largest prefix of this 
196393  ** list nMax bytes or less in size.
196394  */
196395  static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
196396    int ret;
196397    u32 dummy;
196398    ret = fts5GetVarint32(aBuf, dummy);
196399    if( ret<nMax ){
196400      while( 1 ){
196401        int i = fts5GetVarint32(&aBuf[ret], dummy);
196402        if( (ret + i) > nMax ) break;
196403        ret += i;
196404      }
196405    }
196406    return ret;
196407  }
196408  
196409  /*
196410  ** Flush the contents of in-memory hash table iHash to a new level-0 
196411  ** segment on disk. Also update the corresponding structure record.
196412  **
196413  ** If an error occurs, set the Fts5Index.rc error code. If an error has 
196414  ** already occurred, this function is a no-op.
196415  */
196416  static void fts5FlushOneHash(Fts5Index *p){
196417    Fts5Hash *pHash = p->pHash;
196418    Fts5Structure *pStruct;
196419    int iSegid;
196420    int pgnoLast = 0;                 /* Last leaf page number in segment */
196421  
196422    /* Obtain a reference to the index structure and allocate a new segment-id
196423    ** for the new level-0 segment.  */
196424    pStruct = fts5StructureRead(p);
196425    iSegid = fts5AllocateSegid(p, pStruct);
196426    fts5StructureInvalidate(p);
196427  
196428    if( iSegid ){
196429      const int pgsz = p->pConfig->pgsz;
196430      int eDetail = p->pConfig->eDetail;
196431      Fts5StructureSegment *pSeg;   /* New segment within pStruct */
196432      Fts5Buffer *pBuf;             /* Buffer in which to assemble leaf page */
196433      Fts5Buffer *pPgidx;           /* Buffer in which to assemble pgidx */
196434  
196435      Fts5SegWriter writer;
196436      fts5WriteInit(p, &writer, iSegid);
196437  
196438      pBuf = &writer.writer.buf;
196439      pPgidx = &writer.writer.pgidx;
196440  
196441      /* fts5WriteInit() should have initialized the buffers to (most likely)
196442      ** the maximum space required. */
196443      assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
196444      assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
196445  
196446      /* Begin scanning through hash table entries. This loop runs once for each
196447      ** term/doclist currently stored within the hash table. */
196448      if( p->rc==SQLITE_OK ){
196449        p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
196450      }
196451      while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
196452        const char *zTerm;          /* Buffer containing term */
196453        const u8 *pDoclist;         /* Pointer to doclist for this term */
196454        int nDoclist;               /* Size of doclist in bytes */
196455  
196456        /* Write the term for this entry to disk. */
196457        sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
196458        fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
196459  
196460        assert( writer.bFirstRowidInPage==0 );
196461        if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
196462          /* The entire doclist will fit on the current leaf. */
196463          fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
196464        }else{
196465          i64 iRowid = 0;
196466          i64 iDelta = 0;
196467          int iOff = 0;
196468  
196469          /* The entire doclist will not fit on this leaf. The following 
196470          ** loop iterates through the poslists that make up the current 
196471          ** doclist.  */
196472          while( p->rc==SQLITE_OK && iOff<nDoclist ){
196473            iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
196474            iRowid += iDelta;
196475            
196476            if( writer.bFirstRowidInPage ){
196477              fts5PutU16(&pBuf->p[0], (u16)pBuf->n);   /* first rowid on page */
196478              pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
196479              writer.bFirstRowidInPage = 0;
196480              fts5WriteDlidxAppend(p, &writer, iRowid);
196481            }else{
196482              pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
196483            }
196484            assert( pBuf->n<=pBuf->nSpace );
196485  
196486            if( eDetail==FTS5_DETAIL_NONE ){
196487              if( iOff<nDoclist && pDoclist[iOff]==0 ){
196488                pBuf->p[pBuf->n++] = 0;
196489                iOff++;
196490                if( iOff<nDoclist && pDoclist[iOff]==0 ){
196491                  pBuf->p[pBuf->n++] = 0;
196492                  iOff++;
196493                }
196494              }
196495              if( (pBuf->n + pPgidx->n)>=pgsz ){
196496                fts5WriteFlushLeaf(p, &writer);
196497              }
196498            }else{
196499              int bDummy;
196500              int nPos;
196501              int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
196502              nCopy += nPos;
196503              if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
196504                /* The entire poslist will fit on the current leaf. So copy
196505                ** it in one go. */
196506                fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
196507              }else{
196508                /* The entire poslist will not fit on this leaf. So it needs
196509                ** to be broken into sections. The only qualification being
196510                ** that each varint must be stored contiguously.  */
196511                const u8 *pPoslist = &pDoclist[iOff];
196512                int iPos = 0;
196513                while( p->rc==SQLITE_OK ){
196514                  int nSpace = pgsz - pBuf->n - pPgidx->n;
196515                  int n = 0;
196516                  if( (nCopy - iPos)<=nSpace ){
196517                    n = nCopy - iPos;
196518                  }else{
196519                    n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
196520                  }
196521                  assert( n>0 );
196522                  fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
196523                  iPos += n;
196524                  if( (pBuf->n + pPgidx->n)>=pgsz ){
196525                    fts5WriteFlushLeaf(p, &writer);
196526                  }
196527                  if( iPos>=nCopy ) break;
196528                }
196529              }
196530              iOff += nCopy;
196531            }
196532          }
196533        }
196534  
196535        /* TODO2: Doclist terminator written here. */
196536        /* pBuf->p[pBuf->n++] = '\0'; */
196537        assert( pBuf->n<=pBuf->nSpace );
196538        sqlite3Fts5HashScanNext(pHash);
196539      }
196540      sqlite3Fts5HashClear(pHash);
196541      fts5WriteFinish(p, &writer, &pgnoLast);
196542  
196543      /* Update the Fts5Structure. It is written back to the database by the
196544      ** fts5StructureRelease() call below.  */
196545      if( pStruct->nLevel==0 ){
196546        fts5StructureAddLevel(&p->rc, &pStruct);
196547      }
196548      fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
196549      if( p->rc==SQLITE_OK ){
196550        pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
196551        pSeg->iSegid = iSegid;
196552        pSeg->pgnoFirst = 1;
196553        pSeg->pgnoLast = pgnoLast;
196554        pStruct->nSegment++;
196555      }
196556      fts5StructurePromote(p, 0, pStruct);
196557    }
196558  
196559    fts5IndexAutomerge(p, &pStruct, pgnoLast);
196560    fts5IndexCrisismerge(p, &pStruct);
196561    fts5StructureWrite(p, pStruct);
196562    fts5StructureRelease(pStruct);
196563  }
196564  
196565  /*
196566  ** Flush any data stored in the in-memory hash tables to the database.
196567  */
196568  static void fts5IndexFlush(Fts5Index *p){
196569    /* Unless it is empty, flush the hash table to disk */
196570    if( p->nPendingData ){
196571      assert( p->pHash );
196572      p->nPendingData = 0;
196573      fts5FlushOneHash(p);
196574    }
196575  }
196576  
196577  static Fts5Structure *fts5IndexOptimizeStruct(
196578    Fts5Index *p, 
196579    Fts5Structure *pStruct
196580  ){
196581    Fts5Structure *pNew = 0;
196582    int nByte = sizeof(Fts5Structure);
196583    int nSeg = pStruct->nSegment;
196584    int i;
196585  
196586    /* Figure out if this structure requires optimization. A structure does
196587    ** not require optimization if either:
196588    **
196589    **  + it consists of fewer than two segments, or 
196590    **  + all segments are on the same level, or
196591    **  + all segments except one are currently inputs to a merge operation.
196592    **
196593    ** In the first case, return NULL. In the second, increment the ref-count
196594    ** on *pStruct and return a copy of the pointer to it.
196595    */
196596    if( nSeg<2 ) return 0;
196597    for(i=0; i<pStruct->nLevel; i++){
196598      int nThis = pStruct->aLevel[i].nSeg;
196599      if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
196600        fts5StructureRef(pStruct);
196601        return pStruct;
196602      }
196603      assert( pStruct->aLevel[i].nMerge<=nThis );
196604    }
196605  
196606    nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
196607    pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
196608  
196609    if( pNew ){
196610      Fts5StructureLevel *pLvl;
196611      nByte = nSeg * sizeof(Fts5StructureSegment);
196612      pNew->nLevel = pStruct->nLevel+1;
196613      pNew->nRef = 1;
196614      pNew->nWriteCounter = pStruct->nWriteCounter;
196615      pLvl = &pNew->aLevel[pStruct->nLevel];
196616      pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
196617      if( pLvl->aSeg ){
196618        int iLvl, iSeg;
196619        int iSegOut = 0;
196620        /* Iterate through all segments, from oldest to newest. Add them to
196621        ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
196622        ** segment in the data structure.  */
196623        for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
196624          for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
196625            pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
196626            iSegOut++;
196627          }
196628        }
196629        pNew->nSegment = pLvl->nSeg = nSeg;
196630      }else{
196631        sqlite3_free(pNew);
196632        pNew = 0;
196633      }
196634    }
196635  
196636    return pNew;
196637  }
196638  
196639  static int sqlite3Fts5IndexOptimize(Fts5Index *p){
196640    Fts5Structure *pStruct;
196641    Fts5Structure *pNew = 0;
196642  
196643    assert( p->rc==SQLITE_OK );
196644    fts5IndexFlush(p);
196645    pStruct = fts5StructureRead(p);
196646    fts5StructureInvalidate(p);
196647  
196648    if( pStruct ){
196649      pNew = fts5IndexOptimizeStruct(p, pStruct);
196650    }
196651    fts5StructureRelease(pStruct);
196652  
196653    assert( pNew==0 || pNew->nSegment>0 );
196654    if( pNew ){
196655      int iLvl;
196656      for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
196657      while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
196658        int nRem = FTS5_OPT_WORK_UNIT;
196659        fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
196660      }
196661  
196662      fts5StructureWrite(p, pNew);
196663      fts5StructureRelease(pNew);
196664    }
196665  
196666    return fts5IndexReturn(p); 
196667  }
196668  
196669  /*
196670  ** This is called to implement the special "VALUES('merge', $nMerge)"
196671  ** INSERT command.
196672  */
196673  static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
196674    Fts5Structure *pStruct = fts5StructureRead(p);
196675    if( pStruct ){
196676      int nMin = p->pConfig->nUsermerge;
196677      fts5StructureInvalidate(p);
196678      if( nMerge<0 ){
196679        Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
196680        fts5StructureRelease(pStruct);
196681        pStruct = pNew;
196682        nMin = 2;
196683        nMerge = nMerge*-1;
196684      }
196685      if( pStruct && pStruct->nLevel ){
196686        if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
196687          fts5StructureWrite(p, pStruct);
196688        }
196689      }
196690      fts5StructureRelease(pStruct);
196691    }
196692    return fts5IndexReturn(p);
196693  }
196694  
196695  static void fts5AppendRowid(
196696    Fts5Index *p,
196697    i64 iDelta,
196698    Fts5Iter *pUnused,
196699    Fts5Buffer *pBuf
196700  ){
196701    UNUSED_PARAM(pUnused);
196702    fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
196703  }
196704  
196705  static void fts5AppendPoslist(
196706    Fts5Index *p,
196707    i64 iDelta,
196708    Fts5Iter *pMulti,
196709    Fts5Buffer *pBuf
196710  ){
196711    int nData = pMulti->base.nData;
196712    assert( nData>0 );
196713    if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nData+9+9) ){
196714      fts5BufferSafeAppendVarint(pBuf, iDelta);
196715      fts5BufferSafeAppendVarint(pBuf, nData*2);
196716      fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
196717    }
196718  }
196719  
196720  
196721  static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
196722    u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
196723  
196724    assert( pIter->aPoslist );
196725    if( p>=pIter->aEof ){
196726      pIter->aPoslist = 0;
196727    }else{
196728      i64 iDelta;
196729  
196730      p += fts5GetVarint(p, (u64*)&iDelta);
196731      pIter->iRowid += iDelta;
196732  
196733      /* Read position list size */
196734      if( p[0] & 0x80 ){
196735        int nPos;
196736        pIter->nSize = fts5GetVarint32(p, nPos);
196737        pIter->nPoslist = (nPos>>1);
196738      }else{
196739        pIter->nPoslist = ((int)(p[0])) >> 1;
196740        pIter->nSize = 1;
196741      }
196742  
196743      pIter->aPoslist = p;
196744    }
196745  }
196746  
196747  static void fts5DoclistIterInit(
196748    Fts5Buffer *pBuf, 
196749    Fts5DoclistIter *pIter
196750  ){
196751    memset(pIter, 0, sizeof(*pIter));
196752    pIter->aPoslist = pBuf->p;
196753    pIter->aEof = &pBuf->p[pBuf->n];
196754    fts5DoclistIterNext(pIter);
196755  }
196756  
196757  #if 0
196758  /*
196759  ** Append a doclist to buffer pBuf.
196760  **
196761  ** This function assumes that space within the buffer has already been
196762  ** allocated.
196763  */
196764  static void fts5MergeAppendDocid(
196765    Fts5Buffer *pBuf,               /* Buffer to write to */
196766    i64 *piLastRowid,               /* IN/OUT: Previous rowid written (if any) */
196767    i64 iRowid                      /* Rowid to append */
196768  ){
196769    assert( pBuf->n!=0 || (*piLastRowid)==0 );
196770    fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
196771    *piLastRowid = iRowid;
196772  }
196773  #endif
196774  
196775  #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) {       \
196776    assert( (pBuf)->n!=0 || (iLastRowid)==0 );                   \
196777    fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
196778    (iLastRowid) = (iRowid);                                     \
196779  }
196780  
196781  /*
196782  ** Swap the contents of buffer *p1 with that of *p2.
196783  */
196784  static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
196785    Fts5Buffer tmp = *p1;
196786    *p1 = *p2;
196787    *p2 = tmp;
196788  }
196789  
196790  static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
196791    int i = *piOff;
196792    if( i>=pBuf->n ){
196793      *piOff = -1;
196794    }else{
196795      u64 iVal;
196796      *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
196797      *piRowid += iVal;
196798    }
196799  }
196800  
196801  /*
196802  ** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
196803  ** In this case the buffers consist of a delta-encoded list of rowids only.
196804  */
196805  static void fts5MergeRowidLists(
196806    Fts5Index *p,                   /* FTS5 backend object */
196807    Fts5Buffer *p1,                 /* First list to merge */
196808    Fts5Buffer *p2                  /* Second list to merge */
196809  ){
196810    int i1 = 0;
196811    int i2 = 0;
196812    i64 iRowid1 = 0;
196813    i64 iRowid2 = 0;
196814    i64 iOut = 0;
196815  
196816    Fts5Buffer out;
196817    memset(&out, 0, sizeof(out));
196818    sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
196819    if( p->rc ) return;
196820  
196821    fts5NextRowid(p1, &i1, &iRowid1);
196822    fts5NextRowid(p2, &i2, &iRowid2);
196823    while( i1>=0 || i2>=0 ){
196824      if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
196825        assert( iOut==0 || iRowid1>iOut );
196826        fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
196827        iOut = iRowid1;
196828        fts5NextRowid(p1, &i1, &iRowid1);
196829      }else{
196830        assert( iOut==0 || iRowid2>iOut );
196831        fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
196832        iOut = iRowid2;
196833        if( i1>=0 && iRowid1==iRowid2 ){
196834          fts5NextRowid(p1, &i1, &iRowid1);
196835        }
196836        fts5NextRowid(p2, &i2, &iRowid2);
196837      }
196838    }
196839  
196840    fts5BufferSwap(&out, p1);
196841    fts5BufferFree(&out);
196842  }
196843  
196844  /*
196845  ** Buffers p1 and p2 contain doclists. This function merges the content
196846  ** of the two doclists together and sets buffer p1 to the result before
196847  ** returning.
196848  **
196849  ** If an error occurs, an error code is left in p->rc. If an error has
196850  ** already occurred, this function is a no-op.
196851  */
196852  static void fts5MergePrefixLists(
196853    Fts5Index *p,                   /* FTS5 backend object */
196854    Fts5Buffer *p1,                 /* First list to merge */
196855    Fts5Buffer *p2                  /* Second list to merge */
196856  ){
196857    if( p2->n ){
196858      i64 iLastRowid = 0;
196859      Fts5DoclistIter i1;
196860      Fts5DoclistIter i2;
196861      Fts5Buffer out = {0, 0, 0};
196862      Fts5Buffer tmp = {0, 0, 0};
196863  
196864      if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n) ) return;
196865      fts5DoclistIterInit(p1, &i1);
196866      fts5DoclistIterInit(p2, &i2);
196867  
196868      while( 1 ){
196869        if( i1.iRowid<i2.iRowid ){
196870          /* Copy entry from i1 */
196871          fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
196872          fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
196873          fts5DoclistIterNext(&i1);
196874          if( i1.aPoslist==0 ) break;
196875        }
196876        else if( i2.iRowid!=i1.iRowid ){
196877          /* Copy entry from i2 */
196878          fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
196879          fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
196880          fts5DoclistIterNext(&i2);
196881          if( i2.aPoslist==0 ) break;
196882        }
196883        else{
196884          /* Merge the two position lists. */ 
196885          i64 iPos1 = 0;
196886          i64 iPos2 = 0;
196887          int iOff1 = 0;
196888          int iOff2 = 0;
196889          u8 *a1 = &i1.aPoslist[i1.nSize];
196890          u8 *a2 = &i2.aPoslist[i2.nSize];
196891  
196892          i64 iPrev = 0;
196893          Fts5PoslistWriter writer;
196894          memset(&writer, 0, sizeof(writer));
196895  
196896          fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
196897          fts5BufferZero(&tmp);
196898          sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist);
196899          if( p->rc ) break;
196900  
196901          sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
196902          sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
196903          assert( iPos1>=0 && iPos2>=0 );
196904  
196905          if( iPos1<iPos2 ){
196906            sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
196907            sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
196908          }else{
196909            sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
196910            sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
196911          }
196912  
196913          if( iPos1>=0 && iPos2>=0 ){
196914            while( 1 ){
196915              if( iPos1<iPos2 ){
196916                if( iPos1!=iPrev ){
196917                  sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
196918                }
196919                sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
196920                if( iPos1<0 ) break;
196921              }else{
196922                assert( iPos2!=iPrev );
196923                sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
196924                sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
196925                if( iPos2<0 ) break;
196926              }
196927            }
196928          }
196929  
196930          if( iPos1>=0 ){
196931            if( iPos1!=iPrev ){
196932              sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
196933            }
196934            fts5BufferSafeAppendBlob(&tmp, &a1[iOff1], i1.nPoslist-iOff1);
196935          }else{
196936            assert( iPos2>=0 && iPos2!=iPrev );
196937            sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
196938            fts5BufferSafeAppendBlob(&tmp, &a2[iOff2], i2.nPoslist-iOff2);
196939          }
196940  
196941          /* WRITEPOSLISTSIZE */
196942          fts5BufferSafeAppendVarint(&out, tmp.n * 2);
196943          fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
196944          fts5DoclistIterNext(&i1);
196945          fts5DoclistIterNext(&i2);
196946          if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
196947        }
196948      }
196949  
196950      if( i1.aPoslist ){
196951        fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
196952        fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
196953      }
196954      else if( i2.aPoslist ){
196955        fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
196956        fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
196957      }
196958  
196959      fts5BufferSet(&p->rc, p1, out.n, out.p);
196960      fts5BufferFree(&tmp);
196961      fts5BufferFree(&out);
196962    }
196963  }
196964  
196965  static void fts5SetupPrefixIter(
196966    Fts5Index *p,                   /* Index to read from */
196967    int bDesc,                      /* True for "ORDER BY rowid DESC" */
196968    const u8 *pToken,               /* Buffer containing prefix to match */
196969    int nToken,                     /* Size of buffer pToken in bytes */
196970    Fts5Colset *pColset,            /* Restrict matches to these columns */
196971    Fts5Iter **ppIter          /* OUT: New iterator */
196972  ){
196973    Fts5Structure *pStruct;
196974    Fts5Buffer *aBuf;
196975    const int nBuf = 32;
196976  
196977    void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
196978    void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
196979    if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
196980      xMerge = fts5MergeRowidLists;
196981      xAppend = fts5AppendRowid;
196982    }else{
196983      xMerge = fts5MergePrefixLists;
196984      xAppend = fts5AppendPoslist;
196985    }
196986  
196987    aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
196988    pStruct = fts5StructureRead(p);
196989  
196990    if( aBuf && pStruct ){
196991      const int flags = FTS5INDEX_QUERY_SCAN 
196992                      | FTS5INDEX_QUERY_SKIPEMPTY 
196993                      | FTS5INDEX_QUERY_NOOUTPUT;
196994      int i;
196995      i64 iLastRowid = 0;
196996      Fts5Iter *p1 = 0;     /* Iterator used to gather data from index */
196997      Fts5Data *pData;
196998      Fts5Buffer doclist;
196999      int bNewTerm = 1;
197000  
197001      memset(&doclist, 0, sizeof(doclist));
197002      fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
197003      fts5IterSetOutputCb(&p->rc, p1);
197004      for( /* no-op */ ;
197005          fts5MultiIterEof(p, p1)==0;
197006          fts5MultiIterNext2(p, p1, &bNewTerm)
197007      ){
197008        Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
197009        int nTerm = pSeg->term.n;
197010        const u8 *pTerm = pSeg->term.p;
197011        p1->xSetOutputs(p1, pSeg);
197012  
197013        assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
197014        if( bNewTerm ){
197015          if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
197016        }
197017  
197018        if( p1->base.nData==0 ) continue;
197019  
197020        if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
197021          for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
197022            assert( i<nBuf );
197023            if( aBuf[i].n==0 ){
197024              fts5BufferSwap(&doclist, &aBuf[i]);
197025              fts5BufferZero(&doclist);
197026            }else{
197027              xMerge(p, &doclist, &aBuf[i]);
197028              fts5BufferZero(&aBuf[i]);
197029            }
197030          }
197031          iLastRowid = 0;
197032        }
197033  
197034        xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
197035        iLastRowid = p1->base.iRowid;
197036      }
197037  
197038      for(i=0; i<nBuf; i++){
197039        if( p->rc==SQLITE_OK ){
197040          xMerge(p, &doclist, &aBuf[i]);
197041        }
197042        fts5BufferFree(&aBuf[i]);
197043      }
197044      fts5MultiIterFree(p1);
197045  
197046      pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
197047      if( pData ){
197048        pData->p = (u8*)&pData[1];
197049        pData->nn = pData->szLeaf = doclist.n;
197050        if( doclist.n ) memcpy(pData->p, doclist.p, doclist.n);
197051        fts5MultiIterNew2(p, pData, bDesc, ppIter);
197052      }
197053      fts5BufferFree(&doclist);
197054    }
197055  
197056    fts5StructureRelease(pStruct);
197057    sqlite3_free(aBuf);
197058  }
197059  
197060  
197061  /*
197062  ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
197063  ** to the document with rowid iRowid.
197064  */
197065  static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
197066    assert( p->rc==SQLITE_OK );
197067  
197068    /* Allocate the hash table if it has not already been allocated */
197069    if( p->pHash==0 ){
197070      p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
197071    }
197072  
197073    /* Flush the hash table to disk if required */
197074    if( iRowid<p->iWriteRowid 
197075     || (iRowid==p->iWriteRowid && p->bDelete==0)
197076     || (p->nPendingData > p->pConfig->nHashSize) 
197077    ){
197078      fts5IndexFlush(p);
197079    }
197080  
197081    p->iWriteRowid = iRowid;
197082    p->bDelete = bDelete;
197083    return fts5IndexReturn(p);
197084  }
197085  
197086  /*
197087  ** Commit data to disk.
197088  */
197089  static int sqlite3Fts5IndexSync(Fts5Index *p){
197090    assert( p->rc==SQLITE_OK );
197091    fts5IndexFlush(p);
197092    fts5CloseReader(p);
197093    return fts5IndexReturn(p);
197094  }
197095  
197096  /*
197097  ** Discard any data stored in the in-memory hash tables. Do not write it
197098  ** to the database. Additionally, assume that the contents of the %_data
197099  ** table may have changed on disk. So any in-memory caches of %_data 
197100  ** records must be invalidated.
197101  */
197102  static int sqlite3Fts5IndexRollback(Fts5Index *p){
197103    fts5CloseReader(p);
197104    fts5IndexDiscardData(p);
197105    fts5StructureInvalidate(p);
197106    /* assert( p->rc==SQLITE_OK ); */
197107    return SQLITE_OK;
197108  }
197109  
197110  /*
197111  ** The %_data table is completely empty when this function is called. This
197112  ** function populates it with the initial structure objects for each index,
197113  ** and the initial version of the "averages" record (a zero-byte blob).
197114  */
197115  static int sqlite3Fts5IndexReinit(Fts5Index *p){
197116    Fts5Structure s;
197117    fts5StructureInvalidate(p);
197118    memset(&s, 0, sizeof(Fts5Structure));
197119    fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
197120    fts5StructureWrite(p, &s);
197121    return fts5IndexReturn(p);
197122  }
197123  
197124  /*
197125  ** Open a new Fts5Index handle. If the bCreate argument is true, create
197126  ** and initialize the underlying %_data table.
197127  **
197128  ** If successful, set *pp to point to the new object and return SQLITE_OK.
197129  ** Otherwise, set *pp to NULL and return an SQLite error code.
197130  */
197131  static int sqlite3Fts5IndexOpen(
197132    Fts5Config *pConfig, 
197133    int bCreate, 
197134    Fts5Index **pp,
197135    char **pzErr
197136  ){
197137    int rc = SQLITE_OK;
197138    Fts5Index *p;                   /* New object */
197139  
197140    *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
197141    if( rc==SQLITE_OK ){
197142      p->pConfig = pConfig;
197143      p->nWorkUnit = FTS5_WORK_UNIT;
197144      p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
197145      if( p->zDataTbl && bCreate ){
197146        rc = sqlite3Fts5CreateTable(
197147            pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
197148        );
197149        if( rc==SQLITE_OK ){
197150          rc = sqlite3Fts5CreateTable(pConfig, "idx", 
197151              "segid, term, pgno, PRIMARY KEY(segid, term)", 
197152              1, pzErr
197153          );
197154        }
197155        if( rc==SQLITE_OK ){
197156          rc = sqlite3Fts5IndexReinit(p);
197157        }
197158      }
197159    }
197160  
197161    assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
197162    if( rc ){
197163      sqlite3Fts5IndexClose(p);
197164      *pp = 0;
197165    }
197166    return rc;
197167  }
197168  
197169  /*
197170  ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
197171  */
197172  static int sqlite3Fts5IndexClose(Fts5Index *p){
197173    int rc = SQLITE_OK;
197174    if( p ){
197175      assert( p->pReader==0 );
197176      fts5StructureInvalidate(p);
197177      sqlite3_finalize(p->pWriter);
197178      sqlite3_finalize(p->pDeleter);
197179      sqlite3_finalize(p->pIdxWriter);
197180      sqlite3_finalize(p->pIdxDeleter);
197181      sqlite3_finalize(p->pIdxSelect);
197182      sqlite3_finalize(p->pDataVersion);
197183      sqlite3Fts5HashFree(p->pHash);
197184      sqlite3_free(p->zDataTbl);
197185      sqlite3_free(p);
197186    }
197187    return rc;
197188  }
197189  
197190  /*
197191  ** Argument p points to a buffer containing utf-8 text that is n bytes in 
197192  ** size. Return the number of bytes in the nChar character prefix of the
197193  ** buffer, or 0 if there are less than nChar characters in total.
197194  */
197195  static int sqlite3Fts5IndexCharlenToBytelen(
197196    const char *p, 
197197    int nByte, 
197198    int nChar
197199  ){
197200    int n = 0;
197201    int i;
197202    for(i=0; i<nChar; i++){
197203      if( n>=nByte ) return 0;      /* Input contains fewer than nChar chars */
197204      if( (unsigned char)p[n++]>=0xc0 ){
197205        while( (p[n] & 0xc0)==0x80 ) n++;
197206      }
197207    }
197208    return n;
197209  }
197210  
197211  /*
197212  ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
197213  ** unicode characters in the string.
197214  */
197215  static int fts5IndexCharlen(const char *pIn, int nIn){
197216    int nChar = 0;            
197217    int i = 0;
197218    while( i<nIn ){
197219      if( (unsigned char)pIn[i++]>=0xc0 ){
197220        while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
197221      }
197222      nChar++;
197223    }
197224    return nChar;
197225  }
197226  
197227  /*
197228  ** Insert or remove data to or from the index. Each time a document is 
197229  ** added to or removed from the index, this function is called one or more
197230  ** times.
197231  **
197232  ** For an insert, it must be called once for each token in the new document.
197233  ** If the operation is a delete, it must be called (at least) once for each
197234  ** unique token in the document with an iCol value less than zero. The iPos
197235  ** argument is ignored for a delete.
197236  */
197237  static int sqlite3Fts5IndexWrite(
197238    Fts5Index *p,                   /* Index to write to */
197239    int iCol,                       /* Column token appears in (-ve -> delete) */
197240    int iPos,                       /* Position of token within column */
197241    const char *pToken, int nToken  /* Token to add or remove to or from index */
197242  ){
197243    int i;                          /* Used to iterate through indexes */
197244    int rc = SQLITE_OK;             /* Return code */
197245    Fts5Config *pConfig = p->pConfig;
197246  
197247    assert( p->rc==SQLITE_OK );
197248    assert( (iCol<0)==p->bDelete );
197249  
197250    /* Add the entry to the main terms index. */
197251    rc = sqlite3Fts5HashWrite(
197252        p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
197253    );
197254  
197255    for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
197256      const int nChar = pConfig->aPrefix[i];
197257      int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
197258      if( nByte ){
197259        rc = sqlite3Fts5HashWrite(p->pHash, 
197260            p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
197261            nByte
197262        );
197263      }
197264    }
197265  
197266    return rc;
197267  }
197268  
197269  /*
197270  ** Open a new iterator to iterate though all rowid that match the 
197271  ** specified token or token prefix.
197272  */
197273  static int sqlite3Fts5IndexQuery(
197274    Fts5Index *p,                   /* FTS index to query */
197275    const char *pToken, int nToken, /* Token (or prefix) to query for */
197276    int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
197277    Fts5Colset *pColset,            /* Match these columns only */
197278    Fts5IndexIter **ppIter          /* OUT: New iterator object */
197279  ){
197280    Fts5Config *pConfig = p->pConfig;
197281    Fts5Iter *pRet = 0;
197282    Fts5Buffer buf = {0, 0, 0};
197283  
197284    /* If the QUERY_SCAN flag is set, all other flags must be clear. */
197285    assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
197286  
197287    if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
197288      int iIdx = 0;                 /* Index to search */
197289      if( nToken ) memcpy(&buf.p[1], pToken, nToken);
197290  
197291      /* Figure out which index to search and set iIdx accordingly. If this
197292      ** is a prefix query for which there is no prefix index, set iIdx to
197293      ** greater than pConfig->nPrefix to indicate that the query will be
197294      ** satisfied by scanning multiple terms in the main index.
197295      **
197296      ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
197297      ** prefix-query. Instead of using a prefix-index (if one exists), 
197298      ** evaluate the prefix query using the main FTS index. This is used
197299      ** for internal sanity checking by the integrity-check in debug 
197300      ** mode only.  */
197301  #ifdef SQLITE_DEBUG
197302      if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
197303        assert( flags & FTS5INDEX_QUERY_PREFIX );
197304        iIdx = 1+pConfig->nPrefix;
197305      }else
197306  #endif
197307      if( flags & FTS5INDEX_QUERY_PREFIX ){
197308        int nChar = fts5IndexCharlen(pToken, nToken);
197309        for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
197310          if( pConfig->aPrefix[iIdx-1]==nChar ) break;
197311        }
197312      }
197313  
197314      if( iIdx<=pConfig->nPrefix ){
197315        /* Straight index lookup */
197316        Fts5Structure *pStruct = fts5StructureRead(p);
197317        buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
197318        if( pStruct ){
197319          fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY, 
197320              pColset, buf.p, nToken+1, -1, 0, &pRet
197321          );
197322          fts5StructureRelease(pStruct);
197323        }
197324      }else{
197325        /* Scan multiple terms in the main index */
197326        int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
197327        buf.p[0] = FTS5_MAIN_PREFIX;
197328        fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
197329        assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
197330        fts5IterSetOutputCb(&p->rc, pRet);
197331        if( p->rc==SQLITE_OK ){
197332          Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
197333          if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
197334        }
197335      }
197336  
197337      if( p->rc ){
197338        sqlite3Fts5IterClose((Fts5IndexIter*)pRet);
197339        pRet = 0;
197340        fts5CloseReader(p);
197341      }
197342  
197343      *ppIter = &pRet->base;
197344      sqlite3Fts5BufferFree(&buf);
197345    }
197346    return fts5IndexReturn(p);
197347  }
197348  
197349  /*
197350  ** Return true if the iterator passed as the only argument is at EOF.
197351  */
197352  /*
197353  ** Move to the next matching rowid. 
197354  */
197355  static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
197356    Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
197357    assert( pIter->pIndex->rc==SQLITE_OK );
197358    fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
197359    return fts5IndexReturn(pIter->pIndex);
197360  }
197361  
197362  /*
197363  ** Move to the next matching term/rowid. Used by the fts5vocab module.
197364  */
197365  static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
197366    Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
197367    Fts5Index *p = pIter->pIndex;
197368  
197369    assert( pIter->pIndex->rc==SQLITE_OK );
197370  
197371    fts5MultiIterNext(p, pIter, 0, 0);
197372    if( p->rc==SQLITE_OK ){
197373      Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
197374      if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
197375        fts5DataRelease(pSeg->pLeaf);
197376        pSeg->pLeaf = 0;
197377        pIter->base.bEof = 1;
197378      }
197379    }
197380  
197381    return fts5IndexReturn(pIter->pIndex);
197382  }
197383  
197384  /*
197385  ** Move to the next matching rowid that occurs at or after iMatch. The
197386  ** definition of "at or after" depends on whether this iterator iterates
197387  ** in ascending or descending rowid order.
197388  */
197389  static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
197390    Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
197391    fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
197392    return fts5IndexReturn(pIter->pIndex);
197393  }
197394  
197395  /*
197396  ** Return the current term.
197397  */
197398  static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
197399    int n;
197400    const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
197401    *pn = n-1;
197402    return &z[1];
197403  }
197404  
197405  /*
197406  ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
197407  */
197408  static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
197409    if( pIndexIter ){
197410      Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
197411      Fts5Index *pIndex = pIter->pIndex;
197412      fts5MultiIterFree(pIter);
197413      fts5CloseReader(pIndex);
197414    }
197415  }
197416  
197417  /*
197418  ** Read and decode the "averages" record from the database. 
197419  **
197420  ** Parameter anSize must point to an array of size nCol, where nCol is
197421  ** the number of user defined columns in the FTS table.
197422  */
197423  static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
197424    int nCol = p->pConfig->nCol;
197425    Fts5Data *pData;
197426  
197427    *pnRow = 0;
197428    memset(anSize, 0, sizeof(i64) * nCol);
197429    pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
197430    if( p->rc==SQLITE_OK && pData->nn ){
197431      int i = 0;
197432      int iCol;
197433      i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
197434      for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
197435        i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
197436      }
197437    }
197438  
197439    fts5DataRelease(pData);
197440    return fts5IndexReturn(p);
197441  }
197442  
197443  /*
197444  ** Replace the current "averages" record with the contents of the buffer 
197445  ** supplied as the second argument.
197446  */
197447  static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
197448    assert( p->rc==SQLITE_OK );
197449    fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
197450    return fts5IndexReturn(p);
197451  }
197452  
197453  /*
197454  ** Return the total number of blocks this module has read from the %_data
197455  ** table since it was created.
197456  */
197457  static int sqlite3Fts5IndexReads(Fts5Index *p){
197458    return p->nRead;
197459  }
197460  
197461  /*
197462  ** Set the 32-bit cookie value stored at the start of all structure 
197463  ** records to the value passed as the second argument.
197464  **
197465  ** Return SQLITE_OK if successful, or an SQLite error code if an error
197466  ** occurs.
197467  */
197468  static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
197469    int rc;                              /* Return code */
197470    Fts5Config *pConfig = p->pConfig;    /* Configuration object */
197471    u8 aCookie[4];                       /* Binary representation of iNew */
197472    sqlite3_blob *pBlob = 0;
197473  
197474    assert( p->rc==SQLITE_OK );
197475    sqlite3Fts5Put32(aCookie, iNew);
197476  
197477    rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl, 
197478        "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
197479    );
197480    if( rc==SQLITE_OK ){
197481      sqlite3_blob_write(pBlob, aCookie, 4, 0);
197482      rc = sqlite3_blob_close(pBlob);
197483    }
197484  
197485    return rc;
197486  }
197487  
197488  static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
197489    Fts5Structure *pStruct;
197490    pStruct = fts5StructureRead(p);
197491    fts5StructureRelease(pStruct);
197492    return fts5IndexReturn(p);
197493  }
197494  
197495  
197496  /*************************************************************************
197497  **************************************************************************
197498  ** Below this point is the implementation of the integrity-check 
197499  ** functionality.
197500  */
197501  
197502  /*
197503  ** Return a simple checksum value based on the arguments.
197504  */
197505  static u64 sqlite3Fts5IndexEntryCksum(
197506    i64 iRowid, 
197507    int iCol, 
197508    int iPos, 
197509    int iIdx,
197510    const char *pTerm,
197511    int nTerm
197512  ){
197513    int i;
197514    u64 ret = iRowid;
197515    ret += (ret<<3) + iCol;
197516    ret += (ret<<3) + iPos;
197517    if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
197518    for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
197519    return ret;
197520  }
197521  
197522  #ifdef SQLITE_DEBUG
197523  /*
197524  ** This function is purely an internal test. It does not contribute to 
197525  ** FTS functionality, or even the integrity-check, in any way.
197526  **
197527  ** Instead, it tests that the same set of pgno/rowid combinations are 
197528  ** visited regardless of whether the doclist-index identified by parameters
197529  ** iSegid/iLeaf is iterated in forwards or reverse order.
197530  */
197531  static void fts5TestDlidxReverse(
197532    Fts5Index *p, 
197533    int iSegid,                     /* Segment id to load from */
197534    int iLeaf                       /* Load doclist-index for this leaf */
197535  ){
197536    Fts5DlidxIter *pDlidx = 0;
197537    u64 cksum1 = 13;
197538    u64 cksum2 = 13;
197539  
197540    for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
197541        fts5DlidxIterEof(p, pDlidx)==0;
197542        fts5DlidxIterNext(p, pDlidx)
197543    ){
197544      i64 iRowid = fts5DlidxIterRowid(pDlidx);
197545      int pgno = fts5DlidxIterPgno(pDlidx);
197546      assert( pgno>iLeaf );
197547      cksum1 += iRowid + ((i64)pgno<<32);
197548    }
197549    fts5DlidxIterFree(pDlidx);
197550    pDlidx = 0;
197551  
197552    for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
197553        fts5DlidxIterEof(p, pDlidx)==0;
197554        fts5DlidxIterPrev(p, pDlidx)
197555    ){
197556      i64 iRowid = fts5DlidxIterRowid(pDlidx);
197557      int pgno = fts5DlidxIterPgno(pDlidx);
197558      assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
197559      cksum2 += iRowid + ((i64)pgno<<32);
197560    }
197561    fts5DlidxIterFree(pDlidx);
197562    pDlidx = 0;
197563  
197564    if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
197565  }
197566  
197567  static int fts5QueryCksum(
197568    Fts5Index *p,                   /* Fts5 index object */
197569    int iIdx,
197570    const char *z,                  /* Index key to query for */
197571    int n,                          /* Size of index key in bytes */
197572    int flags,                      /* Flags for Fts5IndexQuery */
197573    u64 *pCksum                     /* IN/OUT: Checksum value */
197574  ){
197575    int eDetail = p->pConfig->eDetail;
197576    u64 cksum = *pCksum;
197577    Fts5IndexIter *pIter = 0;
197578    int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
197579  
197580    while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
197581      i64 rowid = pIter->iRowid;
197582  
197583      if( eDetail==FTS5_DETAIL_NONE ){
197584        cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
197585      }else{
197586        Fts5PoslistReader sReader;
197587        for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
197588            sReader.bEof==0;
197589            sqlite3Fts5PoslistReaderNext(&sReader)
197590        ){
197591          int iCol = FTS5_POS2COLUMN(sReader.iPos);
197592          int iOff = FTS5_POS2OFFSET(sReader.iPos);
197593          cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
197594        }
197595      }
197596      if( rc==SQLITE_OK ){
197597        rc = sqlite3Fts5IterNext(pIter);
197598      }
197599    }
197600    sqlite3Fts5IterClose(pIter);
197601  
197602    *pCksum = cksum;
197603    return rc;
197604  }
197605  
197606  
197607  /*
197608  ** This function is also purely an internal test. It does not contribute to 
197609  ** FTS functionality, or even the integrity-check, in any way.
197610  */
197611  static void fts5TestTerm(
197612    Fts5Index *p, 
197613    Fts5Buffer *pPrev,              /* Previous term */
197614    const char *z, int n,           /* Possibly new term to test */
197615    u64 expected,
197616    u64 *pCksum
197617  ){
197618    int rc = p->rc;
197619    if( pPrev->n==0 ){
197620      fts5BufferSet(&rc, pPrev, n, (const u8*)z);
197621    }else
197622    if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
197623      u64 cksum3 = *pCksum;
197624      const char *zTerm = (const char*)&pPrev->p[1];  /* term sans prefix-byte */
197625      int nTerm = pPrev->n-1;            /* Size of zTerm in bytes */
197626      int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
197627      int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
197628      u64 ck1 = 0;
197629      u64 ck2 = 0;
197630  
197631      /* Check that the results returned for ASC and DESC queries are
197632      ** the same. If not, call this corruption.  */
197633      rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
197634      if( rc==SQLITE_OK ){
197635        int f = flags|FTS5INDEX_QUERY_DESC;
197636        rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
197637      }
197638      if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
197639  
197640      /* If this is a prefix query, check that the results returned if the
197641      ** the index is disabled are the same. In both ASC and DESC order. 
197642      **
197643      ** This check may only be performed if the hash table is empty. This
197644      ** is because the hash table only supports a single scan query at
197645      ** a time, and the multi-iter loop from which this function is called
197646      ** is already performing such a scan. */
197647      if( p->nPendingData==0 ){
197648        if( iIdx>0 && rc==SQLITE_OK ){
197649          int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
197650          ck2 = 0;
197651          rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
197652          if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
197653        }
197654        if( iIdx>0 && rc==SQLITE_OK ){
197655          int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
197656          ck2 = 0;
197657          rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
197658          if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
197659        }
197660      }
197661  
197662      cksum3 ^= ck1;
197663      fts5BufferSet(&rc, pPrev, n, (const u8*)z);
197664  
197665      if( rc==SQLITE_OK && cksum3!=expected ){
197666        rc = FTS5_CORRUPT;
197667      }
197668      *pCksum = cksum3;
197669    }
197670    p->rc = rc;
197671  }
197672   
197673  #else
197674  # define fts5TestDlidxReverse(x,y,z)
197675  # define fts5TestTerm(u,v,w,x,y,z)
197676  #endif
197677  
197678  /*
197679  ** Check that:
197680  **
197681  **   1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
197682  **      contain zero terms.
197683  **   2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
197684  **      contain zero rowids.
197685  */
197686  static void fts5IndexIntegrityCheckEmpty(
197687    Fts5Index *p,
197688    Fts5StructureSegment *pSeg,     /* Segment to check internal consistency */
197689    int iFirst,
197690    int iNoRowid,
197691    int iLast
197692  ){
197693    int i;
197694  
197695    /* Now check that the iter.nEmpty leaves following the current leaf
197696    ** (a) exist and (b) contain no terms. */
197697    for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
197698      Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
197699      if( pLeaf ){
197700        if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
197701        if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
197702      }
197703      fts5DataRelease(pLeaf);
197704    }
197705  }
197706  
197707  static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
197708    int iTermOff = 0;
197709    int ii;
197710  
197711    Fts5Buffer buf1 = {0,0,0};
197712    Fts5Buffer buf2 = {0,0,0};
197713  
197714    ii = pLeaf->szLeaf;
197715    while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
197716      int res;
197717      int iOff;
197718      int nIncr;
197719  
197720      ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
197721      iTermOff += nIncr;
197722      iOff = iTermOff;
197723  
197724      if( iOff>=pLeaf->szLeaf ){
197725        p->rc = FTS5_CORRUPT;
197726      }else if( iTermOff==nIncr ){
197727        int nByte;
197728        iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
197729        if( (iOff+nByte)>pLeaf->szLeaf ){
197730          p->rc = FTS5_CORRUPT;
197731        }else{
197732          fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
197733        }
197734      }else{
197735        int nKeep, nByte;
197736        iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
197737        iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
197738        if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
197739          p->rc = FTS5_CORRUPT;
197740        }else{
197741          buf1.n = nKeep;
197742          fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
197743        }
197744  
197745        if( p->rc==SQLITE_OK ){
197746          res = fts5BufferCompare(&buf1, &buf2);
197747          if( res<=0 ) p->rc = FTS5_CORRUPT;
197748        }
197749      }
197750      fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
197751    }
197752  
197753    fts5BufferFree(&buf1);
197754    fts5BufferFree(&buf2);
197755  }
197756  
197757  static void fts5IndexIntegrityCheckSegment(
197758    Fts5Index *p,                   /* FTS5 backend object */
197759    Fts5StructureSegment *pSeg      /* Segment to check internal consistency */
197760  ){
197761    Fts5Config *pConfig = p->pConfig;
197762    sqlite3_stmt *pStmt = 0;
197763    int rc2;
197764    int iIdxPrevLeaf = pSeg->pgnoFirst-1;
197765    int iDlidxPrevLeaf = pSeg->pgnoLast;
197766  
197767    if( pSeg->pgnoFirst==0 ) return;
197768  
197769    fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
197770        "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
197771        pConfig->zDb, pConfig->zName, pSeg->iSegid
197772    ));
197773  
197774    /* Iterate through the b-tree hierarchy.  */
197775    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
197776      i64 iRow;                     /* Rowid for this leaf */
197777      Fts5Data *pLeaf;              /* Data for this leaf */
197778  
197779      int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
197780      const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
197781      int iIdxLeaf = sqlite3_column_int(pStmt, 2);
197782      int bIdxDlidx = sqlite3_column_int(pStmt, 3);
197783  
197784      /* If the leaf in question has already been trimmed from the segment, 
197785      ** ignore this b-tree entry. Otherwise, load it into memory. */
197786      if( iIdxLeaf<pSeg->pgnoFirst ) continue;
197787      iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
197788      pLeaf = fts5LeafRead(p, iRow);
197789      if( pLeaf==0 ) break;
197790  
197791      /* Check that the leaf contains at least one term, and that it is equal
197792      ** to or larger than the split-key in zIdxTerm.  Also check that if there
197793      ** is also a rowid pointer within the leaf page header, it points to a
197794      ** location before the term.  */
197795      if( pLeaf->nn<=pLeaf->szLeaf ){
197796        p->rc = FTS5_CORRUPT;
197797      }else{
197798        int iOff;                   /* Offset of first term on leaf */
197799        int iRowidOff;              /* Offset of first rowid on leaf */
197800        int nTerm;                  /* Size of term on leaf in bytes */
197801        int res;                    /* Comparison of term and split-key */
197802  
197803        iOff = fts5LeafFirstTermOff(pLeaf);
197804        iRowidOff = fts5LeafFirstRowidOff(pLeaf);
197805        if( iRowidOff>=iOff ){
197806          p->rc = FTS5_CORRUPT;
197807        }else{
197808          iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
197809          res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
197810          if( res==0 ) res = nTerm - nIdxTerm;
197811          if( res<0 ) p->rc = FTS5_CORRUPT;
197812        }
197813  
197814        fts5IntegrityCheckPgidx(p, pLeaf);
197815      }
197816      fts5DataRelease(pLeaf);
197817      if( p->rc ) break;
197818  
197819      /* Now check that the iter.nEmpty leaves following the current leaf
197820      ** (a) exist and (b) contain no terms. */
197821      fts5IndexIntegrityCheckEmpty(
197822          p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
197823      );
197824      if( p->rc ) break;
197825  
197826      /* If there is a doclist-index, check that it looks right. */
197827      if( bIdxDlidx ){
197828        Fts5DlidxIter *pDlidx = 0;  /* For iterating through doclist index */
197829        int iPrevLeaf = iIdxLeaf;
197830        int iSegid = pSeg->iSegid;
197831        int iPg = 0;
197832        i64 iKey;
197833  
197834        for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
197835            fts5DlidxIterEof(p, pDlidx)==0;
197836            fts5DlidxIterNext(p, pDlidx)
197837        ){
197838  
197839          /* Check any rowid-less pages that occur before the current leaf. */
197840          for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
197841            iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
197842            pLeaf = fts5DataRead(p, iKey);
197843            if( pLeaf ){
197844              if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
197845              fts5DataRelease(pLeaf);
197846            }
197847          }
197848          iPrevLeaf = fts5DlidxIterPgno(pDlidx);
197849  
197850          /* Check that the leaf page indicated by the iterator really does
197851          ** contain the rowid suggested by the same. */
197852          iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
197853          pLeaf = fts5DataRead(p, iKey);
197854          if( pLeaf ){
197855            i64 iRowid;
197856            int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
197857            ASSERT_SZLEAF_OK(pLeaf);
197858            if( iRowidOff>=pLeaf->szLeaf ){
197859              p->rc = FTS5_CORRUPT;
197860            }else{
197861              fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
197862              if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
197863            }
197864            fts5DataRelease(pLeaf);
197865          }
197866        }
197867  
197868        iDlidxPrevLeaf = iPg;
197869        fts5DlidxIterFree(pDlidx);
197870        fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
197871      }else{
197872        iDlidxPrevLeaf = pSeg->pgnoLast;
197873        /* TODO: Check there is no doclist index */
197874      }
197875  
197876      iIdxPrevLeaf = iIdxLeaf;
197877    }
197878  
197879    rc2 = sqlite3_finalize(pStmt);
197880    if( p->rc==SQLITE_OK ) p->rc = rc2;
197881  
197882    /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
197883  #if 0
197884    if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
197885      p->rc = FTS5_CORRUPT;
197886    }
197887  #endif
197888  }
197889  
197890  
197891  /*
197892  ** Run internal checks to ensure that the FTS index (a) is internally 
197893  ** consistent and (b) contains entries for which the XOR of the checksums
197894  ** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
197895  **
197896  ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
197897  ** checksum does not match. Return SQLITE_OK if all checks pass without
197898  ** error, or some other SQLite error code if another error (e.g. OOM)
197899  ** occurs.
197900  */
197901  static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
197902    int eDetail = p->pConfig->eDetail;
197903    u64 cksum2 = 0;                 /* Checksum based on contents of indexes */
197904    Fts5Buffer poslist = {0,0,0};   /* Buffer used to hold a poslist */
197905    Fts5Iter *pIter;                /* Used to iterate through entire index */
197906    Fts5Structure *pStruct;         /* Index structure */
197907  
197908  #ifdef SQLITE_DEBUG
197909    /* Used by extra internal tests only run if NDEBUG is not defined */
197910    u64 cksum3 = 0;                 /* Checksum based on contents of indexes */
197911    Fts5Buffer term = {0,0,0};      /* Buffer used to hold most recent term */
197912  #endif
197913    const int flags = FTS5INDEX_QUERY_NOOUTPUT;
197914    
197915    /* Load the FTS index structure */
197916    pStruct = fts5StructureRead(p);
197917  
197918    /* Check that the internal nodes of each segment match the leaves */
197919    if( pStruct ){
197920      int iLvl, iSeg;
197921      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
197922        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
197923          Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
197924          fts5IndexIntegrityCheckSegment(p, pSeg);
197925        }
197926      }
197927    }
197928  
197929    /* The cksum argument passed to this function is a checksum calculated
197930    ** based on all expected entries in the FTS index (including prefix index
197931    ** entries). This block checks that a checksum calculated based on the
197932    ** actual contents of FTS index is identical.
197933    **
197934    ** Two versions of the same checksum are calculated. The first (stack
197935    ** variable cksum2) based on entries extracted from the full-text index
197936    ** while doing a linear scan of each individual index in turn. 
197937    **
197938    ** As each term visited by the linear scans, a separate query for the
197939    ** same term is performed. cksum3 is calculated based on the entries
197940    ** extracted by these queries.
197941    */
197942    for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
197943        fts5MultiIterEof(p, pIter)==0;
197944        fts5MultiIterNext(p, pIter, 0, 0)
197945    ){
197946      int n;                      /* Size of term in bytes */
197947      i64 iPos = 0;               /* Position read from poslist */
197948      int iOff = 0;               /* Offset within poslist */
197949      i64 iRowid = fts5MultiIterRowid(pIter);
197950      char *z = (char*)fts5MultiIterTerm(pIter, &n);
197951  
197952      /* If this is a new term, query for it. Update cksum3 with the results. */
197953      fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
197954  
197955      if( eDetail==FTS5_DETAIL_NONE ){
197956        if( 0==fts5MultiIterIsEmpty(p, pIter) ){
197957          cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
197958        }
197959      }else{
197960        poslist.n = 0;
197961        fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
197962        while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
197963          int iCol = FTS5_POS2COLUMN(iPos);
197964          int iTokOff = FTS5_POS2OFFSET(iPos);
197965          cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
197966        }
197967      }
197968    }
197969    fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
197970  
197971    fts5MultiIterFree(pIter);
197972    if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
197973  
197974    fts5StructureRelease(pStruct);
197975  #ifdef SQLITE_DEBUG
197976    fts5BufferFree(&term);
197977  #endif
197978    fts5BufferFree(&poslist);
197979    return fts5IndexReturn(p);
197980  }
197981  
197982  /*************************************************************************
197983  **************************************************************************
197984  ** Below this point is the implementation of the fts5_decode() scalar
197985  ** function only.
197986  */
197987  
197988  /*
197989  ** Decode a segment-data rowid from the %_data table. This function is
197990  ** the opposite of macro FTS5_SEGMENT_ROWID().
197991  */
197992  static void fts5DecodeRowid(
197993    i64 iRowid,                     /* Rowid from %_data table */
197994    int *piSegid,                   /* OUT: Segment id */
197995    int *pbDlidx,                   /* OUT: Dlidx flag */
197996    int *piHeight,                  /* OUT: Height */
197997    int *piPgno                     /* OUT: Page number */
197998  ){
197999    *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
198000    iRowid >>= FTS5_DATA_PAGE_B;
198001  
198002    *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
198003    iRowid >>= FTS5_DATA_HEIGHT_B;
198004  
198005    *pbDlidx = (int)(iRowid & 0x0001);
198006    iRowid >>= FTS5_DATA_DLI_B;
198007  
198008    *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
198009  }
198010  
198011  static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
198012    int iSegid, iHeight, iPgno, bDlidx;       /* Rowid compenents */
198013    fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
198014  
198015    if( iSegid==0 ){
198016      if( iKey==FTS5_AVERAGES_ROWID ){
198017        sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
198018      }else{
198019        sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
198020      }
198021    }
198022    else{
198023      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
198024          bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
198025      );
198026    }
198027  }
198028  
198029  static void fts5DebugStructure(
198030    int *pRc,                       /* IN/OUT: error code */
198031    Fts5Buffer *pBuf,
198032    Fts5Structure *p
198033  ){
198034    int iLvl, iSeg;                 /* Iterate through levels, segments */
198035  
198036    for(iLvl=0; iLvl<p->nLevel; iLvl++){
198037      Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
198038      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, 
198039          " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
198040      );
198041      for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
198042        Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
198043        sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}", 
198044            pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
198045        );
198046      }
198047      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
198048    }
198049  }
198050  
198051  /*
198052  ** This is part of the fts5_decode() debugging aid.
198053  **
198054  ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
198055  ** function appends a human-readable representation of the same object
198056  ** to the buffer passed as the second argument. 
198057  */
198058  static void fts5DecodeStructure(
198059    int *pRc,                       /* IN/OUT: error code */
198060    Fts5Buffer *pBuf,
198061    const u8 *pBlob, int nBlob
198062  ){
198063    int rc;                         /* Return code */
198064    Fts5Structure *p = 0;           /* Decoded structure object */
198065  
198066    rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
198067    if( rc!=SQLITE_OK ){
198068      *pRc = rc;
198069      return;
198070    }
198071  
198072    fts5DebugStructure(pRc, pBuf, p);
198073    fts5StructureRelease(p);
198074  }
198075  
198076  /*
198077  ** This is part of the fts5_decode() debugging aid.
198078  **
198079  ** Arguments pBlob/nBlob contain an "averages" record. This function 
198080  ** appends a human-readable representation of record to the buffer passed 
198081  ** as the second argument. 
198082  */
198083  static void fts5DecodeAverages(
198084    int *pRc,                       /* IN/OUT: error code */
198085    Fts5Buffer *pBuf,
198086    const u8 *pBlob, int nBlob
198087  ){
198088    int i = 0;
198089    const char *zSpace = "";
198090  
198091    while( i<nBlob ){
198092      u64 iVal;
198093      i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
198094      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
198095      zSpace = " ";
198096    }
198097  }
198098  
198099  /*
198100  ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
198101  ** each varint and append its string representation to buffer pBuf. Return
198102  ** after either the input buffer is exhausted or a 0 value is read.
198103  **
198104  ** The return value is the number of bytes read from the input buffer.
198105  */
198106  static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
198107    int iOff = 0;
198108    while( iOff<n ){
198109      int iVal;
198110      iOff += fts5GetVarint32(&a[iOff], iVal);
198111      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
198112    }
198113    return iOff;
198114  }
198115  
198116  /*
198117  ** The start of buffer (a/n) contains the start of a doclist. The doclist
198118  ** may or may not finish within the buffer. This function appends a text
198119  ** representation of the part of the doclist that is present to buffer
198120  ** pBuf. 
198121  **
198122  ** The return value is the number of bytes read from the input buffer.
198123  */
198124  static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
198125    i64 iDocid = 0;
198126    int iOff = 0;
198127  
198128    if( n>0 ){
198129      iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
198130      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
198131    }
198132    while( iOff<n ){
198133      int nPos;
198134      int bDel;
198135      iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
198136      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
198137      iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
198138      if( iOff<n ){
198139        i64 iDelta;
198140        iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
198141        iDocid += iDelta;
198142        sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
198143      }
198144    }
198145  
198146    return iOff;
198147  }
198148  
198149  /*
198150  ** This function is part of the fts5_decode() debugging function. It is 
198151  ** only ever used with detail=none tables.
198152  **
198153  ** Buffer (pData/nData) contains a doclist in the format used by detail=none
198154  ** tables. This function appends a human-readable version of that list to
198155  ** buffer pBuf.
198156  **
198157  ** If *pRc is other than SQLITE_OK when this function is called, it is a
198158  ** no-op. If an OOM or other error occurs within this function, *pRc is
198159  ** set to an SQLite error code before returning. The final state of buffer
198160  ** pBuf is undefined in this case.
198161  */
198162  static void fts5DecodeRowidList(
198163    int *pRc,                       /* IN/OUT: Error code */
198164    Fts5Buffer *pBuf,               /* Buffer to append text to */
198165    const u8 *pData, int nData      /* Data to decode list-of-rowids from */
198166  ){
198167    int i = 0;
198168    i64 iRowid = 0;
198169  
198170    while( i<nData ){
198171      const char *zApp = "";
198172      u64 iVal;
198173      i += sqlite3Fts5GetVarint(&pData[i], &iVal);
198174      iRowid += iVal;
198175  
198176      if( i<nData && pData[i]==0x00 ){
198177        i++;
198178        if( i<nData && pData[i]==0x00 ){
198179          i++;
198180          zApp = "+";
198181        }else{
198182          zApp = "*";
198183        }
198184      }
198185  
198186      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
198187    }
198188  }
198189  
198190  /*
198191  ** The implementation of user-defined scalar function fts5_decode().
198192  */
198193  static void fts5DecodeFunction(
198194    sqlite3_context *pCtx,          /* Function call context */
198195    int nArg,                       /* Number of args (always 2) */
198196    sqlite3_value **apVal           /* Function arguments */
198197  ){
198198    i64 iRowid;                     /* Rowid for record being decoded */
198199    int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
198200    const u8 *aBlob; int n;         /* Record to decode */
198201    u8 *a = 0;
198202    Fts5Buffer s;                   /* Build up text to return here */
198203    int rc = SQLITE_OK;             /* Return code */
198204    int nSpace = 0;
198205    int eDetailNone = (sqlite3_user_data(pCtx)!=0);
198206  
198207    assert( nArg==2 );
198208    UNUSED_PARAM(nArg);
198209    memset(&s, 0, sizeof(Fts5Buffer));
198210    iRowid = sqlite3_value_int64(apVal[0]);
198211  
198212    /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
198213    ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
198214    ** buffer overreads even if the record is corrupt.  */
198215    n = sqlite3_value_bytes(apVal[1]);
198216    aBlob = sqlite3_value_blob(apVal[1]);
198217    nSpace = n + FTS5_DATA_ZERO_PADDING;
198218    a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
198219    if( a==0 ) goto decode_out;
198220    memcpy(a, aBlob, n);
198221  
198222  
198223    fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
198224  
198225    fts5DebugRowid(&rc, &s, iRowid);
198226    if( bDlidx ){
198227      Fts5Data dlidx;
198228      Fts5DlidxLvl lvl;
198229  
198230      dlidx.p = a;
198231      dlidx.nn = n;
198232  
198233      memset(&lvl, 0, sizeof(Fts5DlidxLvl));
198234      lvl.pData = &dlidx;
198235      lvl.iLeafPgno = iPgno;
198236  
198237      for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
198238        sqlite3Fts5BufferAppendPrintf(&rc, &s, 
198239            " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
198240        );
198241      }
198242    }else if( iSegid==0 ){
198243      if( iRowid==FTS5_AVERAGES_ROWID ){
198244        fts5DecodeAverages(&rc, &s, a, n);
198245      }else{
198246        fts5DecodeStructure(&rc, &s, a, n);
198247      }
198248    }else if( eDetailNone ){
198249      Fts5Buffer term;              /* Current term read from page */
198250      int szLeaf;
198251      int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
198252      int iTermOff;
198253      int nKeep = 0;
198254      int iOff;
198255  
198256      memset(&term, 0, sizeof(Fts5Buffer));
198257  
198258      /* Decode any entries that occur before the first term. */
198259      if( szLeaf<n ){
198260        iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
198261      }else{
198262        iTermOff = szLeaf;
198263      }
198264      fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
198265  
198266      iOff = iTermOff;
198267      while( iOff<szLeaf ){
198268        int nAppend;
198269  
198270        /* Read the term data for the next term*/
198271        iOff += fts5GetVarint32(&a[iOff], nAppend);
198272        term.n = nKeep;
198273        fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
198274        sqlite3Fts5BufferAppendPrintf(
198275            &rc, &s, " term=%.*s", term.n, (const char*)term.p
198276        );
198277        iOff += nAppend;
198278  
198279        /* Figure out where the doclist for this term ends */
198280        if( iPgidxOff<n ){
198281          int nIncr;
198282          iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
198283          iTermOff += nIncr;
198284        }else{
198285          iTermOff = szLeaf;
198286        }
198287  
198288        fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
198289        iOff = iTermOff;
198290        if( iOff<szLeaf ){
198291          iOff += fts5GetVarint32(&a[iOff], nKeep);
198292        }
198293      }
198294  
198295      fts5BufferFree(&term);
198296    }else{
198297      Fts5Buffer term;              /* Current term read from page */
198298      int szLeaf;                   /* Offset of pgidx in a[] */
198299      int iPgidxOff;
198300      int iPgidxPrev = 0;           /* Previous value read from pgidx */
198301      int iTermOff = 0;
198302      int iRowidOff = 0;
198303      int iOff;
198304      int nDoclist;
198305  
198306      memset(&term, 0, sizeof(Fts5Buffer));
198307  
198308      if( n<4 ){
198309        sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
198310        goto decode_out;
198311      }else{
198312        iRowidOff = fts5GetU16(&a[0]);
198313        iPgidxOff = szLeaf = fts5GetU16(&a[2]);
198314        if( iPgidxOff<n ){
198315          fts5GetVarint32(&a[iPgidxOff], iTermOff);
198316        }
198317      }
198318  
198319      /* Decode the position list tail at the start of the page */
198320      if( iRowidOff!=0 ){
198321        iOff = iRowidOff;
198322      }else if( iTermOff!=0 ){
198323        iOff = iTermOff;
198324      }else{
198325        iOff = szLeaf;
198326      }
198327      fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
198328  
198329      /* Decode any more doclist data that appears on the page before the
198330      ** first term. */
198331      nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
198332      fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
198333  
198334      while( iPgidxOff<n ){
198335        int bFirst = (iPgidxOff==szLeaf);     /* True for first term on page */
198336        int nByte;                            /* Bytes of data */
198337        int iEnd;
198338        
198339        iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
198340        iPgidxPrev += nByte;
198341        iOff = iPgidxPrev;
198342  
198343        if( iPgidxOff<n ){
198344          fts5GetVarint32(&a[iPgidxOff], nByte);
198345          iEnd = iPgidxPrev + nByte;
198346        }else{
198347          iEnd = szLeaf;
198348        }
198349  
198350        if( bFirst==0 ){
198351          iOff += fts5GetVarint32(&a[iOff], nByte);
198352          term.n = nByte;
198353        }
198354        iOff += fts5GetVarint32(&a[iOff], nByte);
198355        fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
198356        iOff += nByte;
198357  
198358        sqlite3Fts5BufferAppendPrintf(
198359            &rc, &s, " term=%.*s", term.n, (const char*)term.p
198360        );
198361        iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
198362      }
198363  
198364      fts5BufferFree(&term);
198365    }
198366    
198367   decode_out:
198368    sqlite3_free(a);
198369    if( rc==SQLITE_OK ){
198370      sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
198371    }else{
198372      sqlite3_result_error_code(pCtx, rc);
198373    }
198374    fts5BufferFree(&s);
198375  }
198376  
198377  /*
198378  ** The implementation of user-defined scalar function fts5_rowid().
198379  */
198380  static void fts5RowidFunction(
198381    sqlite3_context *pCtx,          /* Function call context */
198382    int nArg,                       /* Number of args (always 2) */
198383    sqlite3_value **apVal           /* Function arguments */
198384  ){
198385    const char *zArg;
198386    if( nArg==0 ){
198387      sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
198388    }else{
198389      zArg = (const char*)sqlite3_value_text(apVal[0]);
198390      if( 0==sqlite3_stricmp(zArg, "segment") ){
198391        i64 iRowid;
198392        int segid, pgno;
198393        if( nArg!=3 ){
198394          sqlite3_result_error(pCtx, 
198395              "should be: fts5_rowid('segment', segid, pgno))", -1
198396          );
198397        }else{
198398          segid = sqlite3_value_int(apVal[1]);
198399          pgno = sqlite3_value_int(apVal[2]);
198400          iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
198401          sqlite3_result_int64(pCtx, iRowid);
198402        }
198403      }else{
198404        sqlite3_result_error(pCtx, 
198405          "first arg to fts5_rowid() must be 'segment'" , -1
198406        );
198407      }
198408    }
198409  }
198410  
198411  /*
198412  ** This is called as part of registering the FTS5 module with database
198413  ** connection db. It registers several user-defined scalar functions useful
198414  ** with FTS5.
198415  **
198416  ** If successful, SQLITE_OK is returned. If an error occurs, some other
198417  ** SQLite error code is returned instead.
198418  */
198419  static int sqlite3Fts5IndexInit(sqlite3 *db){
198420    int rc = sqlite3_create_function(
198421        db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
198422    );
198423  
198424    if( rc==SQLITE_OK ){
198425      rc = sqlite3_create_function(
198426          db, "fts5_decode_none", 2, 
198427          SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
198428      );
198429    }
198430  
198431    if( rc==SQLITE_OK ){
198432      rc = sqlite3_create_function(
198433          db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
198434      );
198435    }
198436    return rc;
198437  }
198438  
198439  
198440  static int sqlite3Fts5IndexReset(Fts5Index *p){
198441    assert( p->pStruct==0 || p->iStructVersion!=0 );
198442    if( fts5IndexDataVersion(p)!=p->iStructVersion ){
198443      fts5StructureInvalidate(p);
198444    }
198445    return fts5IndexReturn(p);
198446  }
198447  
198448  /*
198449  ** 2014 Jun 09
198450  **
198451  ** The author disclaims copyright to this source code.  In place of
198452  ** a legal notice, here is a blessing:
198453  **
198454  **    May you do good and not evil.
198455  **    May you find forgiveness for yourself and forgive others.
198456  **    May you share freely, never taking more than you give.
198457  **
198458  ******************************************************************************
198459  **
198460  ** This is an SQLite module implementing full-text search.
198461  */
198462  
198463  
198464  /* #include "fts5Int.h" */
198465  
198466  /*
198467  ** This variable is set to false when running tests for which the on disk
198468  ** structures should not be corrupt. Otherwise, true. If it is false, extra
198469  ** assert() conditions in the fts5 code are activated - conditions that are
198470  ** only true if it is guaranteed that the fts5 database is not corrupt.
198471  */
198472  SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
198473  
198474  
198475  typedef struct Fts5Auxdata Fts5Auxdata;
198476  typedef struct Fts5Auxiliary Fts5Auxiliary;
198477  typedef struct Fts5Cursor Fts5Cursor;
198478  typedef struct Fts5Sorter Fts5Sorter;
198479  typedef struct Fts5Table Fts5Table;
198480  typedef struct Fts5TokenizerModule Fts5TokenizerModule;
198481  
198482  /*
198483  ** NOTES ON TRANSACTIONS: 
198484  **
198485  ** SQLite invokes the following virtual table methods as transactions are 
198486  ** opened and closed by the user:
198487  **
198488  **     xBegin():    Start of a new transaction.
198489  **     xSync():     Initial part of two-phase commit.
198490  **     xCommit():   Final part of two-phase commit.
198491  **     xRollback(): Rollback the transaction.
198492  **
198493  ** Anything that is required as part of a commit that may fail is performed
198494  ** in the xSync() callback. Current versions of SQLite ignore any errors 
198495  ** returned by xCommit().
198496  **
198497  ** And as sub-transactions are opened/closed:
198498  **
198499  **     xSavepoint(int S):  Open savepoint S.
198500  **     xRelease(int S):    Commit and close savepoint S.
198501  **     xRollbackTo(int S): Rollback to start of savepoint S.
198502  **
198503  ** During a write-transaction the fts5_index.c module may cache some data 
198504  ** in-memory. It is flushed to disk whenever xSync(), xRelease() or
198505  ** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo() 
198506  ** is called.
198507  **
198508  ** Additionally, if SQLITE_DEBUG is defined, an instance of the following
198509  ** structure is used to record the current transaction state. This information
198510  ** is not required, but it is used in the assert() statements executed by
198511  ** function fts5CheckTransactionState() (see below).
198512  */
198513  struct Fts5TransactionState {
198514    int eState;                     /* 0==closed, 1==open, 2==synced */
198515    int iSavepoint;                 /* Number of open savepoints (0 -> none) */
198516  };
198517  
198518  /*
198519  ** A single object of this type is allocated when the FTS5 module is 
198520  ** registered with a database handle. It is used to store pointers to
198521  ** all registered FTS5 extensions - tokenizers and auxiliary functions.
198522  */
198523  struct Fts5Global {
198524    fts5_api api;                   /* User visible part of object (see fts5.h) */
198525    sqlite3 *db;                    /* Associated database connection */ 
198526    i64 iNextId;                    /* Used to allocate unique cursor ids */
198527    Fts5Auxiliary *pAux;            /* First in list of all aux. functions */
198528    Fts5TokenizerModule *pTok;      /* First in list of all tokenizer modules */
198529    Fts5TokenizerModule *pDfltTok;  /* Default tokenizer module */
198530    Fts5Cursor *pCsr;               /* First in list of all open cursors */
198531  };
198532  
198533  /*
198534  ** Each auxiliary function registered with the FTS5 module is represented
198535  ** by an object of the following type. All such objects are stored as part
198536  ** of the Fts5Global.pAux list.
198537  */
198538  struct Fts5Auxiliary {
198539    Fts5Global *pGlobal;            /* Global context for this function */
198540    char *zFunc;                    /* Function name (nul-terminated) */
198541    void *pUserData;                /* User-data pointer */
198542    fts5_extension_function xFunc;  /* Callback function */
198543    void (*xDestroy)(void*);        /* Destructor function */
198544    Fts5Auxiliary *pNext;           /* Next registered auxiliary function */
198545  };
198546  
198547  /*
198548  ** Each tokenizer module registered with the FTS5 module is represented
198549  ** by an object of the following type. All such objects are stored as part
198550  ** of the Fts5Global.pTok list.
198551  */
198552  struct Fts5TokenizerModule {
198553    char *zName;                    /* Name of tokenizer */
198554    void *pUserData;                /* User pointer passed to xCreate() */
198555    fts5_tokenizer x;               /* Tokenizer functions */
198556    void (*xDestroy)(void*);        /* Destructor function */
198557    Fts5TokenizerModule *pNext;     /* Next registered tokenizer module */
198558  };
198559  
198560  /*
198561  ** Virtual-table object.
198562  */
198563  struct Fts5Table {
198564    sqlite3_vtab base;              /* Base class used by SQLite core */
198565    Fts5Config *pConfig;            /* Virtual table configuration */
198566    Fts5Index *pIndex;              /* Full-text index */
198567    Fts5Storage *pStorage;          /* Document store */
198568    Fts5Global *pGlobal;            /* Global (connection wide) data */
198569    Fts5Cursor *pSortCsr;           /* Sort data from this cursor */
198570  #ifdef SQLITE_DEBUG
198571    struct Fts5TransactionState ts;
198572  #endif
198573  };
198574  
198575  struct Fts5MatchPhrase {
198576    Fts5Buffer *pPoslist;           /* Pointer to current poslist */
198577    int nTerm;                      /* Size of phrase in terms */
198578  };
198579  
198580  /*
198581  ** pStmt:
198582  **   SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
198583  **
198584  ** aIdx[]:
198585  **   There is one entry in the aIdx[] array for each phrase in the query,
198586  **   the value of which is the offset within aPoslist[] following the last 
198587  **   byte of the position list for the corresponding phrase.
198588  */
198589  struct Fts5Sorter {
198590    sqlite3_stmt *pStmt;
198591    i64 iRowid;                     /* Current rowid */
198592    const u8 *aPoslist;             /* Position lists for current row */
198593    int nIdx;                       /* Number of entries in aIdx[] */
198594    int aIdx[1];                    /* Offsets into aPoslist for current row */
198595  };
198596  
198597  
198598  /*
198599  ** Virtual-table cursor object.
198600  **
198601  ** iSpecial:
198602  **   If this is a 'special' query (refer to function fts5SpecialMatch()), 
198603  **   then this variable contains the result of the query. 
198604  **
198605  ** iFirstRowid, iLastRowid:
198606  **   These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
198607  **   cursor iterates in ascending order of rowids, iFirstRowid is the lower
198608  **   limit of rowids to return, and iLastRowid the upper. In other words, the
198609  **   WHERE clause in the user's query might have been:
198610  **
198611  **       <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
198612  **
198613  **   If the cursor iterates in descending order of rowid, iFirstRowid
198614  **   is the upper limit (i.e. the "first" rowid visited) and iLastRowid
198615  **   the lower.
198616  */
198617  struct Fts5Cursor {
198618    sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
198619    Fts5Cursor *pNext;              /* Next cursor in Fts5Cursor.pCsr list */
198620    int *aColumnSize;               /* Values for xColumnSize() */
198621    i64 iCsrId;                     /* Cursor id */
198622  
198623    /* Zero from this point onwards on cursor reset */
198624    int ePlan;                      /* FTS5_PLAN_XXX value */
198625    int bDesc;                      /* True for "ORDER BY rowid DESC" queries */
198626    i64 iFirstRowid;                /* Return no rowids earlier than this */
198627    i64 iLastRowid;                 /* Return no rowids later than this */
198628    sqlite3_stmt *pStmt;            /* Statement used to read %_content */
198629    Fts5Expr *pExpr;                /* Expression for MATCH queries */
198630    Fts5Sorter *pSorter;            /* Sorter for "ORDER BY rank" queries */
198631    int csrflags;                   /* Mask of cursor flags (see below) */
198632    i64 iSpecial;                   /* Result of special query */
198633  
198634    /* "rank" function. Populated on demand from vtab.xColumn(). */
198635    char *zRank;                    /* Custom rank function */
198636    char *zRankArgs;                /* Custom rank function args */
198637    Fts5Auxiliary *pRank;           /* Rank callback (or NULL) */
198638    int nRankArg;                   /* Number of trailing arguments for rank() */
198639    sqlite3_value **apRankArg;      /* Array of trailing arguments */
198640    sqlite3_stmt *pRankArgStmt;     /* Origin of objects in apRankArg[] */
198641  
198642    /* Auxiliary data storage */
198643    Fts5Auxiliary *pAux;            /* Currently executing extension function */
198644    Fts5Auxdata *pAuxdata;          /* First in linked list of saved aux-data */
198645  
198646    /* Cache used by auxiliary functions xInst() and xInstCount() */
198647    Fts5PoslistReader *aInstIter;   /* One for each phrase */
198648    int nInstAlloc;                 /* Size of aInst[] array (entries / 3) */
198649    int nInstCount;                 /* Number of phrase instances */
198650    int *aInst;                     /* 3 integers per phrase instance */
198651  };
198652  
198653  /*
198654  ** Bits that make up the "idxNum" parameter passed indirectly by 
198655  ** xBestIndex() to xFilter().
198656  */
198657  #define FTS5_BI_MATCH        0x0001         /* <tbl> MATCH ? */
198658  #define FTS5_BI_RANK         0x0002         /* rank MATCH ? */
198659  #define FTS5_BI_ROWID_EQ     0x0004         /* rowid == ? */
198660  #define FTS5_BI_ROWID_LE     0x0008         /* rowid <= ? */
198661  #define FTS5_BI_ROWID_GE     0x0010         /* rowid >= ? */
198662  
198663  #define FTS5_BI_ORDER_RANK   0x0020
198664  #define FTS5_BI_ORDER_ROWID  0x0040
198665  #define FTS5_BI_ORDER_DESC   0x0080
198666  
198667  /*
198668  ** Values for Fts5Cursor.csrflags
198669  */
198670  #define FTS5CSR_EOF               0x01
198671  #define FTS5CSR_REQUIRE_CONTENT   0x02
198672  #define FTS5CSR_REQUIRE_DOCSIZE   0x04
198673  #define FTS5CSR_REQUIRE_INST      0x08
198674  #define FTS5CSR_FREE_ZRANK        0x10
198675  #define FTS5CSR_REQUIRE_RESEEK    0x20
198676  #define FTS5CSR_REQUIRE_POSLIST   0x40
198677  
198678  #define BitFlagAllTest(x,y) (((x) & (y))==(y))
198679  #define BitFlagTest(x,y)    (((x) & (y))!=0)
198680  
198681  
198682  /*
198683  ** Macros to Set(), Clear() and Test() cursor flags.
198684  */
198685  #define CsrFlagSet(pCsr, flag)   ((pCsr)->csrflags |= (flag))
198686  #define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
198687  #define CsrFlagTest(pCsr, flag)  ((pCsr)->csrflags & (flag))
198688  
198689  struct Fts5Auxdata {
198690    Fts5Auxiliary *pAux;            /* Extension to which this belongs */
198691    void *pPtr;                     /* Pointer value */
198692    void(*xDelete)(void*);          /* Destructor */
198693    Fts5Auxdata *pNext;             /* Next object in linked list */
198694  };
198695  
198696  #ifdef SQLITE_DEBUG
198697  #define FTS5_BEGIN      1
198698  #define FTS5_SYNC       2
198699  #define FTS5_COMMIT     3
198700  #define FTS5_ROLLBACK   4
198701  #define FTS5_SAVEPOINT  5
198702  #define FTS5_RELEASE    6
198703  #define FTS5_ROLLBACKTO 7
198704  static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
198705    switch( op ){
198706      case FTS5_BEGIN:
198707        assert( p->ts.eState==0 );
198708        p->ts.eState = 1;
198709        p->ts.iSavepoint = -1;
198710        break;
198711  
198712      case FTS5_SYNC:
198713        assert( p->ts.eState==1 );
198714        p->ts.eState = 2;
198715        break;
198716  
198717      case FTS5_COMMIT:
198718        assert( p->ts.eState==2 );
198719        p->ts.eState = 0;
198720        break;
198721  
198722      case FTS5_ROLLBACK:
198723        assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
198724        p->ts.eState = 0;
198725        break;
198726  
198727      case FTS5_SAVEPOINT:
198728        assert( p->ts.eState==1 );
198729        assert( iSavepoint>=0 );
198730        assert( iSavepoint>p->ts.iSavepoint );
198731        p->ts.iSavepoint = iSavepoint;
198732        break;
198733        
198734      case FTS5_RELEASE:
198735        assert( p->ts.eState==1 );
198736        assert( iSavepoint>=0 );
198737        assert( iSavepoint<=p->ts.iSavepoint );
198738        p->ts.iSavepoint = iSavepoint-1;
198739        break;
198740  
198741      case FTS5_ROLLBACKTO:
198742        assert( p->ts.eState==1 );
198743        assert( iSavepoint>=0 );
198744        assert( iSavepoint<=p->ts.iSavepoint );
198745        p->ts.iSavepoint = iSavepoint;
198746        break;
198747    }
198748  }
198749  #else
198750  # define fts5CheckTransactionState(x,y,z)
198751  #endif
198752  
198753  /*
198754  ** Return true if pTab is a contentless table.
198755  */
198756  static int fts5IsContentless(Fts5Table *pTab){
198757    return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
198758  }
198759  
198760  /*
198761  ** Delete a virtual table handle allocated by fts5InitVtab(). 
198762  */
198763  static void fts5FreeVtab(Fts5Table *pTab){
198764    if( pTab ){
198765      sqlite3Fts5IndexClose(pTab->pIndex);
198766      sqlite3Fts5StorageClose(pTab->pStorage);
198767      sqlite3Fts5ConfigFree(pTab->pConfig);
198768      sqlite3_free(pTab);
198769    }
198770  }
198771  
198772  /*
198773  ** The xDisconnect() virtual table method.
198774  */
198775  static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
198776    fts5FreeVtab((Fts5Table*)pVtab);
198777    return SQLITE_OK;
198778  }
198779  
198780  /*
198781  ** The xDestroy() virtual table method.
198782  */
198783  static int fts5DestroyMethod(sqlite3_vtab *pVtab){
198784    Fts5Table *pTab = (Fts5Table*)pVtab;
198785    int rc = sqlite3Fts5DropAll(pTab->pConfig);
198786    if( rc==SQLITE_OK ){
198787      fts5FreeVtab((Fts5Table*)pVtab);
198788    }
198789    return rc;
198790  }
198791  
198792  /*
198793  ** This function is the implementation of both the xConnect and xCreate
198794  ** methods of the FTS3 virtual table.
198795  **
198796  ** The argv[] array contains the following:
198797  **
198798  **   argv[0]   -> module name  ("fts5")
198799  **   argv[1]   -> database name
198800  **   argv[2]   -> table name
198801  **   argv[...] -> "column name" and other module argument fields.
198802  */
198803  static int fts5InitVtab(
198804    int bCreate,                    /* True for xCreate, false for xConnect */
198805    sqlite3 *db,                    /* The SQLite database connection */
198806    void *pAux,                     /* Hash table containing tokenizers */
198807    int argc,                       /* Number of elements in argv array */
198808    const char * const *argv,       /* xCreate/xConnect argument array */
198809    sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
198810    char **pzErr                    /* Write any error message here */
198811  ){
198812    Fts5Global *pGlobal = (Fts5Global*)pAux;
198813    const char **azConfig = (const char**)argv;
198814    int rc = SQLITE_OK;             /* Return code */
198815    Fts5Config *pConfig = 0;        /* Results of parsing argc/argv */
198816    Fts5Table *pTab = 0;            /* New virtual table object */
198817  
198818    /* Allocate the new vtab object and parse the configuration */
198819    pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
198820    if( rc==SQLITE_OK ){
198821      rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
198822      assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
198823    }
198824    if( rc==SQLITE_OK ){
198825      pTab->pConfig = pConfig;
198826      pTab->pGlobal = pGlobal;
198827    }
198828  
198829    /* Open the index sub-system */
198830    if( rc==SQLITE_OK ){
198831      rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
198832    }
198833  
198834    /* Open the storage sub-system */
198835    if( rc==SQLITE_OK ){
198836      rc = sqlite3Fts5StorageOpen(
198837          pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
198838      );
198839    }
198840  
198841    /* Call sqlite3_declare_vtab() */
198842    if( rc==SQLITE_OK ){
198843      rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
198844    }
198845  
198846    /* Load the initial configuration */
198847    if( rc==SQLITE_OK ){
198848      assert( pConfig->pzErrmsg==0 );
198849      pConfig->pzErrmsg = pzErr;
198850      rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
198851      sqlite3Fts5IndexRollback(pTab->pIndex);
198852      pConfig->pzErrmsg = 0;
198853    }
198854  
198855    if( rc!=SQLITE_OK ){
198856      fts5FreeVtab(pTab);
198857      pTab = 0;
198858    }else if( bCreate ){
198859      fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
198860    }
198861    *ppVTab = (sqlite3_vtab*)pTab;
198862    return rc;
198863  }
198864  
198865  /*
198866  ** The xConnect() and xCreate() methods for the virtual table. All the
198867  ** work is done in function fts5InitVtab().
198868  */
198869  static int fts5ConnectMethod(
198870    sqlite3 *db,                    /* Database connection */
198871    void *pAux,                     /* Pointer to tokenizer hash table */
198872    int argc,                       /* Number of elements in argv array */
198873    const char * const *argv,       /* xCreate/xConnect argument array */
198874    sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
198875    char **pzErr                    /* OUT: sqlite3_malloc'd error message */
198876  ){
198877    return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
198878  }
198879  static int fts5CreateMethod(
198880    sqlite3 *db,                    /* Database connection */
198881    void *pAux,                     /* Pointer to tokenizer hash table */
198882    int argc,                       /* Number of elements in argv array */
198883    const char * const *argv,       /* xCreate/xConnect argument array */
198884    sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
198885    char **pzErr                    /* OUT: sqlite3_malloc'd error message */
198886  ){
198887    return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
198888  }
198889  
198890  /*
198891  ** The different query plans.
198892  */
198893  #define FTS5_PLAN_MATCH          1       /* (<tbl> MATCH ?) */
198894  #define FTS5_PLAN_SOURCE         2       /* A source cursor for SORTED_MATCH */
198895  #define FTS5_PLAN_SPECIAL        3       /* An internal query */
198896  #define FTS5_PLAN_SORTED_MATCH   4       /* (<tbl> MATCH ? ORDER BY rank) */
198897  #define FTS5_PLAN_SCAN           5       /* No usable constraint */
198898  #define FTS5_PLAN_ROWID          6       /* (rowid = ?) */
198899  
198900  /*
198901  ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
198902  ** extension is currently being used by a version of SQLite too old to
198903  ** support index-info flags. In that case this function is a no-op.
198904  */
198905  static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
198906  #if SQLITE_VERSION_NUMBER>=3008012
198907  #ifndef SQLITE_CORE
198908    if( sqlite3_libversion_number()>=3008012 )
198909  #endif
198910    {
198911      pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
198912    }
198913  #endif
198914  }
198915  
198916  /*
198917  ** Implementation of the xBestIndex method for FTS5 tables. Within the 
198918  ** WHERE constraint, it searches for the following:
198919  **
198920  **   1. A MATCH constraint against the special column.
198921  **   2. A MATCH constraint against the "rank" column.
198922  **   3. An == constraint against the rowid column.
198923  **   4. A < or <= constraint against the rowid column.
198924  **   5. A > or >= constraint against the rowid column.
198925  **
198926  ** Within the ORDER BY, either:
198927  **
198928  **   5. ORDER BY rank [ASC|DESC]
198929  **   6. ORDER BY rowid [ASC|DESC]
198930  **
198931  ** Costs are assigned as follows:
198932  **
198933  **  a) If an unusable MATCH operator is present in the WHERE clause, the
198934  **     cost is unconditionally set to 1e50 (a really big number).
198935  **
198936  **  a) If a MATCH operator is present, the cost depends on the other
198937  **     constraints also present. As follows:
198938  **
198939  **       * No other constraints:         cost=1000.0
198940  **       * One rowid range constraint:   cost=750.0
198941  **       * Both rowid range constraints: cost=500.0
198942  **       * An == rowid constraint:       cost=100.0
198943  **
198944  **  b) Otherwise, if there is no MATCH:
198945  **
198946  **       * No other constraints:         cost=1000000.0
198947  **       * One rowid range constraint:   cost=750000.0
198948  **       * Both rowid range constraints: cost=250000.0
198949  **       * An == rowid constraint:       cost=10.0
198950  **
198951  ** Costs are not modified by the ORDER BY clause.
198952  */
198953  static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
198954    Fts5Table *pTab = (Fts5Table*)pVTab;
198955    Fts5Config *pConfig = pTab->pConfig;
198956    const int nCol = pConfig->nCol;
198957    int idxFlags = 0;               /* Parameter passed through to xFilter() */
198958    int bHasMatch;
198959    int iNext;
198960    int i;
198961  
198962    struct Constraint {
198963      int op;                       /* Mask against sqlite3_index_constraint.op */
198964      int fts5op;                   /* FTS5 mask for idxFlags */
198965      int iCol;                     /* 0==rowid, 1==tbl, 2==rank */
198966      int omit;                     /* True to omit this if found */
198967      int iConsIndex;               /* Index in pInfo->aConstraint[] */
198968    } aConstraint[] = {
198969      {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ, 
198970                                      FTS5_BI_MATCH,    1, 1, -1},
198971      {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ, 
198972                                      FTS5_BI_RANK,     2, 1, -1},
198973      {SQLITE_INDEX_CONSTRAINT_EQ,    FTS5_BI_ROWID_EQ, 0, 0, -1},
198974      {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE, 
198975                                      FTS5_BI_ROWID_LE, 0, 0, -1},
198976      {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE, 
198977                                      FTS5_BI_ROWID_GE, 0, 0, -1},
198978    };
198979  
198980    int aColMap[3];
198981    aColMap[0] = -1;
198982    aColMap[1] = nCol;
198983    aColMap[2] = nCol+1;
198984  
198985    /* Set idxFlags flags for all WHERE clause terms that will be used. */
198986    for(i=0; i<pInfo->nConstraint; i++){
198987      struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
198988      int iCol = p->iColumn;
198989  
198990      if( (p->op==SQLITE_INDEX_CONSTRAINT_MATCH && iCol>=0 && iCol<=nCol)
198991       || (p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol==nCol)
198992      ){
198993        /* A MATCH operator or equivalent */
198994        if( p->usable ){
198995          idxFlags = (idxFlags & 0xFFFF) | FTS5_BI_MATCH | (iCol << 16);
198996          aConstraint[0].iConsIndex = i;
198997        }else{
198998          /* As there exists an unusable MATCH constraint this is an 
198999          ** unusable plan. Set a prohibitively high cost. */
199000          pInfo->estimatedCost = 1e50;
199001          return SQLITE_OK;
199002        }
199003      }else{
199004        int j;
199005        for(j=1; j<ArraySize(aConstraint); j++){
199006          struct Constraint *pC = &aConstraint[j];
199007          if( iCol==aColMap[pC->iCol] && p->op & pC->op && p->usable ){
199008            pC->iConsIndex = i;
199009            idxFlags |= pC->fts5op;
199010          }
199011        }
199012      }
199013    }
199014  
199015    /* Set idxFlags flags for the ORDER BY clause */
199016    if( pInfo->nOrderBy==1 ){
199017      int iSort = pInfo->aOrderBy[0].iColumn;
199018      if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
199019        idxFlags |= FTS5_BI_ORDER_RANK;
199020      }else if( iSort==-1 ){
199021        idxFlags |= FTS5_BI_ORDER_ROWID;
199022      }
199023      if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
199024        pInfo->orderByConsumed = 1;
199025        if( pInfo->aOrderBy[0].desc ){
199026          idxFlags |= FTS5_BI_ORDER_DESC;
199027        }
199028      }
199029    }
199030  
199031    /* Calculate the estimated cost based on the flags set in idxFlags. */
199032    bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
199033    if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
199034      pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
199035      if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
199036    }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
199037      pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
199038    }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
199039      pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
199040    }else{
199041      pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
199042    }
199043  
199044    /* Assign argvIndex values to each constraint in use. */
199045    iNext = 1;
199046    for(i=0; i<ArraySize(aConstraint); i++){
199047      struct Constraint *pC = &aConstraint[i];
199048      if( pC->iConsIndex>=0 ){
199049        pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
199050        pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
199051      }
199052    }
199053  
199054    pInfo->idxNum = idxFlags;
199055    return SQLITE_OK;
199056  }
199057  
199058  static int fts5NewTransaction(Fts5Table *pTab){
199059    Fts5Cursor *pCsr;
199060    for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
199061      if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
199062    }
199063    return sqlite3Fts5StorageReset(pTab->pStorage);
199064  }
199065  
199066  /*
199067  ** Implementation of xOpen method.
199068  */
199069  static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
199070    Fts5Table *pTab = (Fts5Table*)pVTab;
199071    Fts5Config *pConfig = pTab->pConfig;
199072    Fts5Cursor *pCsr = 0;           /* New cursor object */
199073    int nByte;                      /* Bytes of space to allocate */
199074    int rc;                         /* Return code */
199075  
199076    rc = fts5NewTransaction(pTab);
199077    if( rc==SQLITE_OK ){
199078      nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
199079      pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
199080      if( pCsr ){
199081        Fts5Global *pGlobal = pTab->pGlobal;
199082        memset(pCsr, 0, nByte);
199083        pCsr->aColumnSize = (int*)&pCsr[1];
199084        pCsr->pNext = pGlobal->pCsr;
199085        pGlobal->pCsr = pCsr;
199086        pCsr->iCsrId = ++pGlobal->iNextId;
199087      }else{
199088        rc = SQLITE_NOMEM;
199089      }
199090    }
199091    *ppCsr = (sqlite3_vtab_cursor*)pCsr;
199092    return rc;
199093  }
199094  
199095  static int fts5StmtType(Fts5Cursor *pCsr){
199096    if( pCsr->ePlan==FTS5_PLAN_SCAN ){
199097      return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
199098    }
199099    return FTS5_STMT_LOOKUP;
199100  }
199101  
199102  /*
199103  ** This function is called after the cursor passed as the only argument
199104  ** is moved to point at a different row. It clears all cached data 
199105  ** specific to the previous row stored by the cursor object.
199106  */
199107  static void fts5CsrNewrow(Fts5Cursor *pCsr){
199108    CsrFlagSet(pCsr, 
199109        FTS5CSR_REQUIRE_CONTENT 
199110      | FTS5CSR_REQUIRE_DOCSIZE 
199111      | FTS5CSR_REQUIRE_INST 
199112      | FTS5CSR_REQUIRE_POSLIST 
199113    );
199114  }
199115  
199116  static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
199117    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
199118    Fts5Auxdata *pData;
199119    Fts5Auxdata *pNext;
199120  
199121    sqlite3_free(pCsr->aInstIter);
199122    sqlite3_free(pCsr->aInst);
199123    if( pCsr->pStmt ){
199124      int eStmt = fts5StmtType(pCsr);
199125      sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
199126    }
199127    if( pCsr->pSorter ){
199128      Fts5Sorter *pSorter = pCsr->pSorter;
199129      sqlite3_finalize(pSorter->pStmt);
199130      sqlite3_free(pSorter);
199131    }
199132  
199133    if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
199134      sqlite3Fts5ExprFree(pCsr->pExpr);
199135    }
199136  
199137    for(pData=pCsr->pAuxdata; pData; pData=pNext){
199138      pNext = pData->pNext;
199139      if( pData->xDelete ) pData->xDelete(pData->pPtr);
199140      sqlite3_free(pData);
199141    }
199142  
199143    sqlite3_finalize(pCsr->pRankArgStmt);
199144    sqlite3_free(pCsr->apRankArg);
199145  
199146    if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
199147      sqlite3_free(pCsr->zRank);
199148      sqlite3_free(pCsr->zRankArgs);
199149    }
199150  
199151    memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
199152  }
199153  
199154  
199155  /*
199156  ** Close the cursor.  For additional information see the documentation
199157  ** on the xClose method of the virtual table interface.
199158  */
199159  static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
199160    if( pCursor ){
199161      Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
199162      Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
199163      Fts5Cursor **pp;
199164  
199165      fts5FreeCursorComponents(pCsr);
199166      /* Remove the cursor from the Fts5Global.pCsr list */
199167      for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
199168      *pp = pCsr->pNext;
199169  
199170      sqlite3_free(pCsr);
199171    }
199172    return SQLITE_OK;
199173  }
199174  
199175  static int fts5SorterNext(Fts5Cursor *pCsr){
199176    Fts5Sorter *pSorter = pCsr->pSorter;
199177    int rc;
199178  
199179    rc = sqlite3_step(pSorter->pStmt);
199180    if( rc==SQLITE_DONE ){
199181      rc = SQLITE_OK;
199182      CsrFlagSet(pCsr, FTS5CSR_EOF);
199183    }else if( rc==SQLITE_ROW ){
199184      const u8 *a;
199185      const u8 *aBlob;
199186      int nBlob;
199187      int i;
199188      int iOff = 0;
199189      rc = SQLITE_OK;
199190  
199191      pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
199192      nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
199193      aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
199194  
199195      /* nBlob==0 in detail=none mode. */
199196      if( nBlob>0 ){
199197        for(i=0; i<(pSorter->nIdx-1); i++){
199198          int iVal;
199199          a += fts5GetVarint32(a, iVal);
199200          iOff += iVal;
199201          pSorter->aIdx[i] = iOff;
199202        }
199203        pSorter->aIdx[i] = &aBlob[nBlob] - a;
199204        pSorter->aPoslist = a;
199205      }
199206  
199207      fts5CsrNewrow(pCsr);
199208    }
199209  
199210    return rc;
199211  }
199212  
199213  
199214  /*
199215  ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors 
199216  ** open on table pTab.
199217  */
199218  static void fts5TripCursors(Fts5Table *pTab){
199219    Fts5Cursor *pCsr;
199220    for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
199221      if( pCsr->ePlan==FTS5_PLAN_MATCH
199222       && pCsr->base.pVtab==(sqlite3_vtab*)pTab 
199223      ){
199224        CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
199225      }
199226    }
199227  }
199228  
199229  /*
199230  ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
199231  ** argument, close and reopen all Fts5IndexIter iterators that the cursor 
199232  ** is using. Then attempt to move the cursor to a rowid equal to or laster
199233  ** (in the cursors sort order - ASC or DESC) than the current rowid. 
199234  **
199235  ** If the new rowid is not equal to the old, set output parameter *pbSkip
199236  ** to 1 before returning. Otherwise, leave it unchanged.
199237  **
199238  ** Return SQLITE_OK if successful or if no reseek was required, or an 
199239  ** error code if an error occurred.
199240  */
199241  static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
199242    int rc = SQLITE_OK;
199243    assert( *pbSkip==0 );
199244    if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
199245      Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
199246      int bDesc = pCsr->bDesc;
199247      i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
199248  
199249      rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
199250      if( rc==SQLITE_OK &&  iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
199251        *pbSkip = 1;
199252      }
199253  
199254      CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
199255      fts5CsrNewrow(pCsr);
199256      if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
199257        CsrFlagSet(pCsr, FTS5CSR_EOF);
199258        *pbSkip = 1;
199259      }
199260    }
199261    return rc;
199262  }
199263  
199264  
199265  /*
199266  ** Advance the cursor to the next row in the table that matches the 
199267  ** search criteria.
199268  **
199269  ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
199270  ** even if we reach end-of-file.  The fts5EofMethod() will be called
199271  ** subsequently to determine whether or not an EOF was hit.
199272  */
199273  static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
199274    Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
199275    int rc;
199276  
199277    assert( (pCsr->ePlan<3)==
199278            (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE) 
199279    );
199280    assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
199281  
199282    if( pCsr->ePlan<3 ){
199283      int bSkip = 0;
199284      if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
199285      rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
199286      CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
199287      fts5CsrNewrow(pCsr);
199288    }else{
199289      switch( pCsr->ePlan ){
199290        case FTS5_PLAN_SPECIAL: {
199291          CsrFlagSet(pCsr, FTS5CSR_EOF);
199292          rc = SQLITE_OK;
199293          break;
199294        }
199295    
199296        case FTS5_PLAN_SORTED_MATCH: {
199297          rc = fts5SorterNext(pCsr);
199298          break;
199299        }
199300    
199301        default:
199302          rc = sqlite3_step(pCsr->pStmt);
199303          if( rc!=SQLITE_ROW ){
199304            CsrFlagSet(pCsr, FTS5CSR_EOF);
199305            rc = sqlite3_reset(pCsr->pStmt);
199306          }else{
199307            rc = SQLITE_OK;
199308          }
199309          break;
199310      }
199311    }
199312    
199313    return rc;
199314  }
199315  
199316  
199317  static int fts5PrepareStatement(
199318    sqlite3_stmt **ppStmt,
199319    Fts5Config *pConfig, 
199320    const char *zFmt,
199321    ...
199322  ){
199323    sqlite3_stmt *pRet = 0;
199324    int rc;
199325    char *zSql;
199326    va_list ap;
199327  
199328    va_start(ap, zFmt);
199329    zSql = sqlite3_vmprintf(zFmt, ap);
199330    if( zSql==0 ){
199331      rc = SQLITE_NOMEM; 
199332    }else{
199333      rc = sqlite3_prepare_v3(pConfig->db, zSql, -1, 
199334                              SQLITE_PREPARE_PERSISTENT, &pRet, 0);
199335      if( rc!=SQLITE_OK ){
199336        *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
199337      }
199338      sqlite3_free(zSql);
199339    }
199340  
199341    va_end(ap);
199342    *ppStmt = pRet;
199343    return rc;
199344  } 
199345  
199346  static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
199347    Fts5Config *pConfig = pTab->pConfig;
199348    Fts5Sorter *pSorter;
199349    int nPhrase;
199350    int nByte;
199351    int rc;
199352    const char *zRank = pCsr->zRank;
199353    const char *zRankArgs = pCsr->zRankArgs;
199354    
199355    nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
199356    nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
199357    pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
199358    if( pSorter==0 ) return SQLITE_NOMEM;
199359    memset(pSorter, 0, nByte);
199360    pSorter->nIdx = nPhrase;
199361  
199362    /* TODO: It would be better to have some system for reusing statement
199363    ** handles here, rather than preparing a new one for each query. But that
199364    ** is not possible as SQLite reference counts the virtual table objects.
199365    ** And since the statement required here reads from this very virtual 
199366    ** table, saving it creates a circular reference.
199367    **
199368    ** If SQLite a built-in statement cache, this wouldn't be a problem. */
199369    rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
199370        "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
199371        pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
199372        (zRankArgs ? ", " : ""),
199373        (zRankArgs ? zRankArgs : ""),
199374        bDesc ? "DESC" : "ASC"
199375    );
199376  
199377    pCsr->pSorter = pSorter;
199378    if( rc==SQLITE_OK ){
199379      assert( pTab->pSortCsr==0 );
199380      pTab->pSortCsr = pCsr;
199381      rc = fts5SorterNext(pCsr);
199382      pTab->pSortCsr = 0;
199383    }
199384  
199385    if( rc!=SQLITE_OK ){
199386      sqlite3_finalize(pSorter->pStmt);
199387      sqlite3_free(pSorter);
199388      pCsr->pSorter = 0;
199389    }
199390  
199391    return rc;
199392  }
199393  
199394  static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
199395    int rc;
199396    Fts5Expr *pExpr = pCsr->pExpr;
199397    rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
199398    if( sqlite3Fts5ExprEof(pExpr) ){
199399      CsrFlagSet(pCsr, FTS5CSR_EOF);
199400    }
199401    fts5CsrNewrow(pCsr);
199402    return rc;
199403  }
199404  
199405  /*
199406  ** Process a "special" query. A special query is identified as one with a
199407  ** MATCH expression that begins with a '*' character. The remainder of
199408  ** the text passed to the MATCH operator are used as  the special query
199409  ** parameters.
199410  */
199411  static int fts5SpecialMatch(
199412    Fts5Table *pTab, 
199413    Fts5Cursor *pCsr, 
199414    const char *zQuery
199415  ){
199416    int rc = SQLITE_OK;             /* Return code */
199417    const char *z = zQuery;         /* Special query text */
199418    int n;                          /* Number of bytes in text at z */
199419  
199420    while( z[0]==' ' ) z++;
199421    for(n=0; z[n] && z[n]!=' '; n++);
199422  
199423    assert( pTab->base.zErrMsg==0 );
199424    pCsr->ePlan = FTS5_PLAN_SPECIAL;
199425  
199426    if( 0==sqlite3_strnicmp("reads", z, n) ){
199427      pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
199428    }
199429    else if( 0==sqlite3_strnicmp("id", z, n) ){
199430      pCsr->iSpecial = pCsr->iCsrId;
199431    }
199432    else{
199433      /* An unrecognized directive. Return an error message. */
199434      pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
199435      rc = SQLITE_ERROR;
199436    }
199437  
199438    return rc;
199439  }
199440  
199441  /*
199442  ** Search for an auxiliary function named zName that can be used with table
199443  ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
199444  ** structure. Otherwise, if no such function exists, return NULL.
199445  */
199446  static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
199447    Fts5Auxiliary *pAux;
199448  
199449    for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
199450      if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
199451    }
199452  
199453    /* No function of the specified name was found. Return 0. */
199454    return 0;
199455  }
199456  
199457  
199458  static int fts5FindRankFunction(Fts5Cursor *pCsr){
199459    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
199460    Fts5Config *pConfig = pTab->pConfig;
199461    int rc = SQLITE_OK;
199462    Fts5Auxiliary *pAux = 0;
199463    const char *zRank = pCsr->zRank;
199464    const char *zRankArgs = pCsr->zRankArgs;
199465  
199466    if( zRankArgs ){
199467      char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
199468      if( zSql ){
199469        sqlite3_stmt *pStmt = 0;
199470        rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
199471                                SQLITE_PREPARE_PERSISTENT, &pStmt, 0);
199472        sqlite3_free(zSql);
199473        assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
199474        if( rc==SQLITE_OK ){
199475          if( SQLITE_ROW==sqlite3_step(pStmt) ){
199476            int nByte;
199477            pCsr->nRankArg = sqlite3_column_count(pStmt);
199478            nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
199479            pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
199480            if( rc==SQLITE_OK ){
199481              int i;
199482              for(i=0; i<pCsr->nRankArg; i++){
199483                pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
199484              }
199485            }
199486            pCsr->pRankArgStmt = pStmt;
199487          }else{
199488            rc = sqlite3_finalize(pStmt);
199489            assert( rc!=SQLITE_OK );
199490          }
199491        }
199492      }
199493    }
199494  
199495    if( rc==SQLITE_OK ){
199496      pAux = fts5FindAuxiliary(pTab, zRank);
199497      if( pAux==0 ){
199498        assert( pTab->base.zErrMsg==0 );
199499        pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
199500        rc = SQLITE_ERROR;
199501      }
199502    }
199503  
199504    pCsr->pRank = pAux;
199505    return rc;
199506  }
199507  
199508  
199509  static int fts5CursorParseRank(
199510    Fts5Config *pConfig,
199511    Fts5Cursor *pCsr, 
199512    sqlite3_value *pRank
199513  ){
199514    int rc = SQLITE_OK;
199515    if( pRank ){
199516      const char *z = (const char*)sqlite3_value_text(pRank);
199517      char *zRank = 0;
199518      char *zRankArgs = 0;
199519  
199520      if( z==0 ){
199521        if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
199522      }else{
199523        rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
199524      }
199525      if( rc==SQLITE_OK ){
199526        pCsr->zRank = zRank;
199527        pCsr->zRankArgs = zRankArgs;
199528        CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
199529      }else if( rc==SQLITE_ERROR ){
199530        pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
199531            "parse error in rank function: %s", z
199532        );
199533      }
199534    }else{
199535      if( pConfig->zRank ){
199536        pCsr->zRank = (char*)pConfig->zRank;
199537        pCsr->zRankArgs = (char*)pConfig->zRankArgs;
199538      }else{
199539        pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
199540        pCsr->zRankArgs = 0;
199541      }
199542    }
199543    return rc;
199544  }
199545  
199546  static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
199547    if( pVal ){
199548      int eType = sqlite3_value_numeric_type(pVal);
199549      if( eType==SQLITE_INTEGER ){
199550        return sqlite3_value_int64(pVal);
199551      }
199552    }
199553    return iDefault;
199554  }
199555  
199556  /*
199557  ** This is the xFilter interface for the virtual table.  See
199558  ** the virtual table xFilter method documentation for additional
199559  ** information.
199560  ** 
199561  ** There are three possible query strategies:
199562  **
199563  **   1. Full-text search using a MATCH operator.
199564  **   2. A by-rowid lookup.
199565  **   3. A full-table scan.
199566  */
199567  static int fts5FilterMethod(
199568    sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
199569    int idxNum,                     /* Strategy index */
199570    const char *zUnused,            /* Unused */
199571    int nVal,                       /* Number of elements in apVal */
199572    sqlite3_value **apVal           /* Arguments for the indexing scheme */
199573  ){
199574    Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
199575    Fts5Config *pConfig = pTab->pConfig;
199576    Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
199577    int rc = SQLITE_OK;             /* Error code */
199578    int iVal = 0;                   /* Counter for apVal[] */
199579    int bDesc;                      /* True if ORDER BY [rank|rowid] DESC */
199580    int bOrderByRank;               /* True if ORDER BY rank */
199581    sqlite3_value *pMatch = 0;      /* <tbl> MATCH ? expression (or NULL) */
199582    sqlite3_value *pRank = 0;       /* rank MATCH ? expression (or NULL) */
199583    sqlite3_value *pRowidEq = 0;    /* rowid = ? expression (or NULL) */
199584    sqlite3_value *pRowidLe = 0;    /* rowid <= ? expression (or NULL) */
199585    sqlite3_value *pRowidGe = 0;    /* rowid >= ? expression (or NULL) */
199586    int iCol;                       /* Column on LHS of MATCH operator */
199587    char **pzErrmsg = pConfig->pzErrmsg;
199588  
199589    UNUSED_PARAM(zUnused);
199590    UNUSED_PARAM(nVal);
199591  
199592    if( pCsr->ePlan ){
199593      fts5FreeCursorComponents(pCsr);
199594      memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
199595    }
199596  
199597    assert( pCsr->pStmt==0 );
199598    assert( pCsr->pExpr==0 );
199599    assert( pCsr->csrflags==0 );
199600    assert( pCsr->pRank==0 );
199601    assert( pCsr->zRank==0 );
199602    assert( pCsr->zRankArgs==0 );
199603  
199604    assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
199605    pConfig->pzErrmsg = &pTab->base.zErrMsg;
199606  
199607    /* Decode the arguments passed through to this function.
199608    **
199609    ** Note: The following set of if(...) statements must be in the same
199610    ** order as the corresponding entries in the struct at the top of
199611    ** fts5BestIndexMethod().  */
199612    if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
199613    if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
199614    if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
199615    if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
199616    if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
199617    iCol = (idxNum>>16);
199618    assert( iCol>=0 && iCol<=pConfig->nCol );
199619    assert( iVal==nVal );
199620    bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
199621    pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
199622  
199623    /* Set the cursor upper and lower rowid limits. Only some strategies 
199624    ** actually use them. This is ok, as the xBestIndex() method leaves the
199625    ** sqlite3_index_constraint.omit flag clear for range constraints
199626    ** on the rowid field.  */
199627    if( pRowidEq ){
199628      pRowidLe = pRowidGe = pRowidEq;
199629    }
199630    if( bDesc ){
199631      pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
199632      pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
199633    }else{
199634      pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
199635      pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
199636    }
199637  
199638    if( pTab->pSortCsr ){
199639      /* If pSortCsr is non-NULL, then this call is being made as part of 
199640      ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
199641      ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
199642      ** return results to the user for this query. The current cursor 
199643      ** (pCursor) is used to execute the query issued by function 
199644      ** fts5CursorFirstSorted() above.  */
199645      assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
199646      assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
199647      assert( pCsr->iLastRowid==LARGEST_INT64 );
199648      assert( pCsr->iFirstRowid==SMALLEST_INT64 );
199649      pCsr->ePlan = FTS5_PLAN_SOURCE;
199650      pCsr->pExpr = pTab->pSortCsr->pExpr;
199651      rc = fts5CursorFirst(pTab, pCsr, bDesc);
199652    }else if( pMatch ){
199653      const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
199654      if( zExpr==0 ) zExpr = "";
199655  
199656      rc = fts5CursorParseRank(pConfig, pCsr, pRank);
199657      if( rc==SQLITE_OK ){
199658        if( zExpr[0]=='*' ){
199659          /* The user has issued a query of the form "MATCH '*...'". This
199660          ** indicates that the MATCH expression is not a full text query,
199661          ** but a request for an internal parameter.  */
199662          rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
199663        }else{
199664          char **pzErr = &pTab->base.zErrMsg;
199665          rc = sqlite3Fts5ExprNew(pConfig, iCol, zExpr, &pCsr->pExpr, pzErr);
199666          if( rc==SQLITE_OK ){
199667            if( bOrderByRank ){
199668              pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
199669              rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
199670            }else{
199671              pCsr->ePlan = FTS5_PLAN_MATCH;
199672              rc = fts5CursorFirst(pTab, pCsr, bDesc);
199673            }
199674          }
199675        }
199676      }
199677    }else if( pConfig->zContent==0 ){
199678      *pConfig->pzErrmsg = sqlite3_mprintf(
199679          "%s: table does not support scanning", pConfig->zName
199680      );
199681      rc = SQLITE_ERROR;
199682    }else{
199683      /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
199684      ** by rowid (ePlan==FTS5_PLAN_ROWID).  */
199685      pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
199686      rc = sqlite3Fts5StorageStmt(
199687          pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
199688      );
199689      if( rc==SQLITE_OK ){
199690        if( pCsr->ePlan==FTS5_PLAN_ROWID ){
199691          sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
199692        }else{
199693          sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
199694          sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
199695        }
199696        rc = fts5NextMethod(pCursor);
199697      }
199698    }
199699  
199700    pConfig->pzErrmsg = pzErrmsg;
199701    return rc;
199702  }
199703  
199704  /* 
199705  ** This is the xEof method of the virtual table. SQLite calls this 
199706  ** routine to find out if it has reached the end of a result set.
199707  */
199708  static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
199709    Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
199710    return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
199711  }
199712  
199713  /*
199714  ** Return the rowid that the cursor currently points to.
199715  */
199716  static i64 fts5CursorRowid(Fts5Cursor *pCsr){
199717    assert( pCsr->ePlan==FTS5_PLAN_MATCH 
199718         || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH 
199719         || pCsr->ePlan==FTS5_PLAN_SOURCE 
199720    );
199721    if( pCsr->pSorter ){
199722      return pCsr->pSorter->iRowid;
199723    }else{
199724      return sqlite3Fts5ExprRowid(pCsr->pExpr);
199725    }
199726  }
199727  
199728  /* 
199729  ** This is the xRowid method. The SQLite core calls this routine to
199730  ** retrieve the rowid for the current row of the result set. fts5
199731  ** exposes %_content.rowid as the rowid for the virtual table. The
199732  ** rowid should be written to *pRowid.
199733  */
199734  static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
199735    Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
199736    int ePlan = pCsr->ePlan;
199737    
199738    assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
199739    switch( ePlan ){
199740      case FTS5_PLAN_SPECIAL:
199741        *pRowid = 0;
199742        break;
199743  
199744      case FTS5_PLAN_SOURCE:
199745      case FTS5_PLAN_MATCH:
199746      case FTS5_PLAN_SORTED_MATCH:
199747        *pRowid = fts5CursorRowid(pCsr);
199748        break;
199749  
199750      default:
199751        *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
199752        break;
199753    }
199754  
199755    return SQLITE_OK;
199756  }
199757  
199758  /*
199759  ** If the cursor requires seeking (bSeekRequired flag is set), seek it.
199760  ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
199761  **
199762  ** If argument bErrormsg is true and an error occurs, an error message may
199763  ** be left in sqlite3_vtab.zErrMsg.
199764  */
199765  static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
199766    int rc = SQLITE_OK;
199767  
199768    /* If the cursor does not yet have a statement handle, obtain one now. */ 
199769    if( pCsr->pStmt==0 ){
199770      Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
199771      int eStmt = fts5StmtType(pCsr);
199772      rc = sqlite3Fts5StorageStmt(
199773          pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
199774      );
199775      assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
199776      assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
199777    }
199778  
199779    if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
199780      assert( pCsr->pExpr );
199781      sqlite3_reset(pCsr->pStmt);
199782      sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
199783      rc = sqlite3_step(pCsr->pStmt);
199784      if( rc==SQLITE_ROW ){
199785        rc = SQLITE_OK;
199786        CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
199787      }else{
199788        rc = sqlite3_reset(pCsr->pStmt);
199789        if( rc==SQLITE_OK ){
199790          rc = FTS5_CORRUPT;
199791        }
199792      }
199793    }
199794    return rc;
199795  }
199796  
199797  static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
199798    va_list ap;                     /* ... printf arguments */
199799    va_start(ap, zFormat);
199800    assert( p->base.zErrMsg==0 );
199801    p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
199802    va_end(ap);
199803  }
199804  
199805  /*
199806  ** This function is called to handle an FTS INSERT command. In other words,
199807  ** an INSERT statement of the form:
199808  **
199809  **     INSERT INTO fts(fts) VALUES($pCmd)
199810  **     INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
199811  **
199812  ** Argument pVal is the value assigned to column "fts" by the INSERT 
199813  ** statement. This function returns SQLITE_OK if successful, or an SQLite
199814  ** error code if an error occurs.
199815  **
199816  ** The commands implemented by this function are documented in the "Special
199817  ** INSERT Directives" section of the documentation. It should be updated if
199818  ** more commands are added to this function.
199819  */
199820  static int fts5SpecialInsert(
199821    Fts5Table *pTab,                /* Fts5 table object */
199822    const char *zCmd,               /* Text inserted into table-name column */
199823    sqlite3_value *pVal             /* Value inserted into rank column */
199824  ){
199825    Fts5Config *pConfig = pTab->pConfig;
199826    int rc = SQLITE_OK;
199827    int bError = 0;
199828  
199829    if( 0==sqlite3_stricmp("delete-all", zCmd) ){
199830      if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
199831        fts5SetVtabError(pTab, 
199832            "'delete-all' may only be used with a "
199833            "contentless or external content fts5 table"
199834        );
199835        rc = SQLITE_ERROR;
199836      }else{
199837        rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
199838      }
199839    }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
199840      if( pConfig->eContent==FTS5_CONTENT_NONE ){
199841        fts5SetVtabError(pTab, 
199842            "'rebuild' may not be used with a contentless fts5 table"
199843        );
199844        rc = SQLITE_ERROR;
199845      }else{
199846        rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
199847      }
199848    }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
199849      rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
199850    }else if( 0==sqlite3_stricmp("merge", zCmd) ){
199851      int nMerge = sqlite3_value_int(pVal);
199852      rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
199853    }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
199854      rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
199855  #ifdef SQLITE_DEBUG
199856    }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
199857      pConfig->bPrefixIndex = sqlite3_value_int(pVal);
199858  #endif
199859    }else{
199860      rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
199861      if( rc==SQLITE_OK ){
199862        rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
199863      }
199864      if( rc==SQLITE_OK ){
199865        if( bError ){
199866          rc = SQLITE_ERROR;
199867        }else{
199868          rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
199869        }
199870      }
199871    }
199872    return rc;
199873  }
199874  
199875  static int fts5SpecialDelete(
199876    Fts5Table *pTab, 
199877    sqlite3_value **apVal
199878  ){
199879    int rc = SQLITE_OK;
199880    int eType1 = sqlite3_value_type(apVal[1]);
199881    if( eType1==SQLITE_INTEGER ){
199882      sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
199883      rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
199884    }
199885    return rc;
199886  }
199887  
199888  static void fts5StorageInsert(
199889    int *pRc, 
199890    Fts5Table *pTab, 
199891    sqlite3_value **apVal, 
199892    i64 *piRowid
199893  ){
199894    int rc = *pRc;
199895    if( rc==SQLITE_OK ){
199896      rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
199897    }
199898    if( rc==SQLITE_OK ){
199899      rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
199900    }
199901    *pRc = rc;
199902  }
199903  
199904  /* 
199905  ** This function is the implementation of the xUpdate callback used by 
199906  ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
199907  ** inserted, updated or deleted.
199908  **
199909  ** A delete specifies a single argument - the rowid of the row to remove.
199910  ** 
199911  ** Update and insert operations pass:
199912  **
199913  **   1. The "old" rowid, or NULL.
199914  **   2. The "new" rowid.
199915  **   3. Values for each of the nCol matchable columns.
199916  **   4. Values for the two hidden columns (<tablename> and "rank").
199917  */
199918  static int fts5UpdateMethod(
199919    sqlite3_vtab *pVtab,            /* Virtual table handle */
199920    int nArg,                       /* Size of argument array */
199921    sqlite3_value **apVal,          /* Array of arguments */
199922    sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
199923  ){
199924    Fts5Table *pTab = (Fts5Table*)pVtab;
199925    Fts5Config *pConfig = pTab->pConfig;
199926    int eType0;                     /* value_type() of apVal[0] */
199927    int rc = SQLITE_OK;             /* Return code */
199928  
199929    /* A transaction must be open when this is called. */
199930    assert( pTab->ts.eState==1 );
199931  
199932    assert( pVtab->zErrMsg==0 );
199933    assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
199934    assert( nArg==1 
199935        || sqlite3_value_type(apVal[1])==SQLITE_INTEGER 
199936        || sqlite3_value_type(apVal[1])==SQLITE_NULL 
199937    );
199938    assert( pTab->pConfig->pzErrmsg==0 );
199939    pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
199940  
199941    /* Put any active cursors into REQUIRE_SEEK state. */
199942    fts5TripCursors(pTab);
199943  
199944    eType0 = sqlite3_value_type(apVal[0]);
199945    if( eType0==SQLITE_NULL 
199946     && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL 
199947    ){
199948      /* A "special" INSERT op. These are handled separately. */
199949      const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
199950      if( pConfig->eContent!=FTS5_CONTENT_NORMAL 
199951        && 0==sqlite3_stricmp("delete", z) 
199952      ){
199953        rc = fts5SpecialDelete(pTab, apVal);
199954      }else{
199955        rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
199956      }
199957    }else{
199958      /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
199959      ** any conflict on the rowid value must be detected before any 
199960      ** modifications are made to the database file. There are 4 cases:
199961      **
199962      **   1) DELETE
199963      **   2) UPDATE (rowid not modified)
199964      **   3) UPDATE (rowid modified)
199965      **   4) INSERT
199966      **
199967      ** Cases 3 and 4 may violate the rowid constraint.
199968      */
199969      int eConflict = SQLITE_ABORT;
199970      if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
199971        eConflict = sqlite3_vtab_on_conflict(pConfig->db);
199972      }
199973  
199974      assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
199975      assert( nArg!=1 || eType0==SQLITE_INTEGER );
199976  
199977      /* Filter out attempts to run UPDATE or DELETE on contentless tables.
199978      ** This is not suported.  */
199979      if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
199980        pTab->base.zErrMsg = sqlite3_mprintf(
199981            "cannot %s contentless fts5 table: %s", 
199982            (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
199983        );
199984        rc = SQLITE_ERROR;
199985      }
199986  
199987      /* DELETE */
199988      else if( nArg==1 ){
199989        i64 iDel = sqlite3_value_int64(apVal[0]);  /* Rowid to delete */
199990        rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
199991      }
199992  
199993      /* INSERT */
199994      else if( eType0!=SQLITE_INTEGER ){     
199995        /* If this is a REPLACE, first remove the current entry (if any) */
199996        if( eConflict==SQLITE_REPLACE 
199997         && sqlite3_value_type(apVal[1])==SQLITE_INTEGER 
199998        ){
199999          i64 iNew = sqlite3_value_int64(apVal[1]);  /* Rowid to delete */
200000          rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
200001        }
200002        fts5StorageInsert(&rc, pTab, apVal, pRowid);
200003      }
200004  
200005      /* UPDATE */
200006      else{
200007        i64 iOld = sqlite3_value_int64(apVal[0]);  /* Old rowid */
200008        i64 iNew = sqlite3_value_int64(apVal[1]);  /* New rowid */
200009        if( iOld!=iNew ){
200010          if( eConflict==SQLITE_REPLACE ){
200011            rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
200012            if( rc==SQLITE_OK ){
200013              rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
200014            }
200015            fts5StorageInsert(&rc, pTab, apVal, pRowid);
200016          }else{
200017            rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
200018            if( rc==SQLITE_OK ){
200019              rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
200020            }
200021            if( rc==SQLITE_OK ){
200022              rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
200023            }
200024          }
200025        }else{
200026          rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
200027          fts5StorageInsert(&rc, pTab, apVal, pRowid);
200028        }
200029      }
200030    }
200031  
200032    pTab->pConfig->pzErrmsg = 0;
200033    return rc;
200034  }
200035  
200036  /*
200037  ** Implementation of xSync() method. 
200038  */
200039  static int fts5SyncMethod(sqlite3_vtab *pVtab){
200040    int rc;
200041    Fts5Table *pTab = (Fts5Table*)pVtab;
200042    fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
200043    pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
200044    fts5TripCursors(pTab);
200045    rc = sqlite3Fts5StorageSync(pTab->pStorage);
200046    pTab->pConfig->pzErrmsg = 0;
200047    return rc;
200048  }
200049  
200050  /*
200051  ** Implementation of xBegin() method. 
200052  */
200053  static int fts5BeginMethod(sqlite3_vtab *pVtab){
200054    fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
200055    fts5NewTransaction((Fts5Table*)pVtab);
200056    return SQLITE_OK;
200057  }
200058  
200059  /*
200060  ** Implementation of xCommit() method. This is a no-op. The contents of
200061  ** the pending-terms hash-table have already been flushed into the database
200062  ** by fts5SyncMethod().
200063  */
200064  static int fts5CommitMethod(sqlite3_vtab *pVtab){
200065    UNUSED_PARAM(pVtab);  /* Call below is a no-op for NDEBUG builds */
200066    fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
200067    return SQLITE_OK;
200068  }
200069  
200070  /*
200071  ** Implementation of xRollback(). Discard the contents of the pending-terms
200072  ** hash-table. Any changes made to the database are reverted by SQLite.
200073  */
200074  static int fts5RollbackMethod(sqlite3_vtab *pVtab){
200075    int rc;
200076    Fts5Table *pTab = (Fts5Table*)pVtab;
200077    fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
200078    rc = sqlite3Fts5StorageRollback(pTab->pStorage);
200079    return rc;
200080  }
200081  
200082  static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
200083  
200084  static void *fts5ApiUserData(Fts5Context *pCtx){
200085    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200086    return pCsr->pAux->pUserData;
200087  }
200088  
200089  static int fts5ApiColumnCount(Fts5Context *pCtx){
200090    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200091    return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
200092  }
200093  
200094  static int fts5ApiColumnTotalSize(
200095    Fts5Context *pCtx, 
200096    int iCol, 
200097    sqlite3_int64 *pnToken
200098  ){
200099    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200100    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
200101    return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
200102  }
200103  
200104  static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
200105    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200106    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
200107    return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
200108  }
200109  
200110  static int fts5ApiTokenize(
200111    Fts5Context *pCtx, 
200112    const char *pText, int nText, 
200113    void *pUserData,
200114    int (*xToken)(void*, int, const char*, int, int, int)
200115  ){
200116    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200117    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
200118    return sqlite3Fts5Tokenize(
200119        pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
200120    );
200121  }
200122  
200123  static int fts5ApiPhraseCount(Fts5Context *pCtx){
200124    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200125    return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
200126  }
200127  
200128  static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
200129    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200130    return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
200131  }
200132  
200133  static int fts5ApiColumnText(
200134    Fts5Context *pCtx, 
200135    int iCol, 
200136    const char **pz, 
200137    int *pn
200138  ){
200139    int rc = SQLITE_OK;
200140    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200141    if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
200142      *pz = 0;
200143      *pn = 0;
200144    }else{
200145      rc = fts5SeekCursor(pCsr, 0);
200146      if( rc==SQLITE_OK ){
200147        *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
200148        *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
200149      }
200150    }
200151    return rc;
200152  }
200153  
200154  static int fts5CsrPoslist(
200155    Fts5Cursor *pCsr, 
200156    int iPhrase, 
200157    const u8 **pa,
200158    int *pn
200159  ){
200160    Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
200161    int rc = SQLITE_OK;
200162    int bLive = (pCsr->pSorter==0);
200163  
200164    if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
200165  
200166      if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
200167        Fts5PoslistPopulator *aPopulator;
200168        int i;
200169        aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
200170        if( aPopulator==0 ) rc = SQLITE_NOMEM;
200171        for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
200172          int n; const char *z;
200173          rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
200174          if( rc==SQLITE_OK ){
200175            rc = sqlite3Fts5ExprPopulatePoslists(
200176                pConfig, pCsr->pExpr, aPopulator, i, z, n
200177            );
200178          }
200179        }
200180        sqlite3_free(aPopulator);
200181  
200182        if( pCsr->pSorter ){
200183          sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
200184        }
200185      }
200186      CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
200187    }
200188  
200189    if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
200190      Fts5Sorter *pSorter = pCsr->pSorter;
200191      int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
200192      *pn = pSorter->aIdx[iPhrase] - i1;
200193      *pa = &pSorter->aPoslist[i1];
200194    }else{
200195      *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
200196    }
200197  
200198    return rc;
200199  }
200200  
200201  /*
200202  ** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
200203  ** correctly for the current view. Return SQLITE_OK if successful, or an
200204  ** SQLite error code otherwise.
200205  */
200206  static int fts5CacheInstArray(Fts5Cursor *pCsr){
200207    int rc = SQLITE_OK;
200208    Fts5PoslistReader *aIter;       /* One iterator for each phrase */
200209    int nIter;                      /* Number of iterators/phrases */
200210    
200211    nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
200212    if( pCsr->aInstIter==0 ){
200213      int nByte = sizeof(Fts5PoslistReader) * nIter;
200214      pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
200215    }
200216    aIter = pCsr->aInstIter;
200217  
200218    if( aIter ){
200219      int nInst = 0;                /* Number instances seen so far */
200220      int i;
200221  
200222      /* Initialize all iterators */
200223      for(i=0; i<nIter && rc==SQLITE_OK; i++){
200224        const u8 *a;
200225        int n; 
200226        rc = fts5CsrPoslist(pCsr, i, &a, &n);
200227        if( rc==SQLITE_OK ){
200228          sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
200229        }
200230      }
200231  
200232      if( rc==SQLITE_OK ){
200233        while( 1 ){
200234          int *aInst;
200235          int iBest = -1;
200236          for(i=0; i<nIter; i++){
200237            if( (aIter[i].bEof==0) 
200238                && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos) 
200239              ){
200240              iBest = i;
200241            }
200242          }
200243          if( iBest<0 ) break;
200244  
200245          nInst++;
200246          if( nInst>=pCsr->nInstAlloc ){
200247            pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
200248            aInst = (int*)sqlite3_realloc(
200249                pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
200250                );
200251            if( aInst ){
200252              pCsr->aInst = aInst;
200253            }else{
200254              rc = SQLITE_NOMEM;
200255              break;
200256            }
200257          }
200258  
200259          aInst = &pCsr->aInst[3 * (nInst-1)];
200260          aInst[0] = iBest;
200261          aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
200262          aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
200263          sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
200264        }
200265      }
200266  
200267      pCsr->nInstCount = nInst;
200268      CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
200269    }
200270    return rc;
200271  }
200272  
200273  static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
200274    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200275    int rc = SQLITE_OK;
200276    if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0 
200277     || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
200278      *pnInst = pCsr->nInstCount;
200279    }
200280    return rc;
200281  }
200282  
200283  static int fts5ApiInst(
200284    Fts5Context *pCtx, 
200285    int iIdx, 
200286    int *piPhrase, 
200287    int *piCol, 
200288    int *piOff
200289  ){
200290    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200291    int rc = SQLITE_OK;
200292    if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0 
200293     || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) 
200294    ){
200295      if( iIdx<0 || iIdx>=pCsr->nInstCount ){
200296        rc = SQLITE_RANGE;
200297  #if 0
200298      }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
200299        *piPhrase = pCsr->aInst[iIdx*3];
200300        *piCol = pCsr->aInst[iIdx*3 + 2];
200301        *piOff = -1;
200302  #endif
200303      }else{
200304        *piPhrase = pCsr->aInst[iIdx*3];
200305        *piCol = pCsr->aInst[iIdx*3 + 1];
200306        *piOff = pCsr->aInst[iIdx*3 + 2];
200307      }
200308    }
200309    return rc;
200310  }
200311  
200312  static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
200313    return fts5CursorRowid((Fts5Cursor*)pCtx);
200314  }
200315  
200316  static int fts5ColumnSizeCb(
200317    void *pContext,                 /* Pointer to int */
200318    int tflags,
200319    const char *pUnused,            /* Buffer containing token */
200320    int nUnused,                    /* Size of token in bytes */
200321    int iUnused1,                   /* Start offset of token */
200322    int iUnused2                    /* End offset of token */
200323  ){
200324    int *pCnt = (int*)pContext;
200325    UNUSED_PARAM2(pUnused, nUnused);
200326    UNUSED_PARAM2(iUnused1, iUnused2);
200327    if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
200328      (*pCnt)++;
200329    }
200330    return SQLITE_OK;
200331  }
200332  
200333  static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
200334    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200335    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
200336    Fts5Config *pConfig = pTab->pConfig;
200337    int rc = SQLITE_OK;
200338  
200339    if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
200340      if( pConfig->bColumnsize ){
200341        i64 iRowid = fts5CursorRowid(pCsr);
200342        rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
200343      }else if( pConfig->zContent==0 ){
200344        int i;
200345        for(i=0; i<pConfig->nCol; i++){
200346          if( pConfig->abUnindexed[i]==0 ){
200347            pCsr->aColumnSize[i] = -1;
200348          }
200349        }
200350      }else{
200351        int i;
200352        for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
200353          if( pConfig->abUnindexed[i]==0 ){
200354            const char *z; int n;
200355            void *p = (void*)(&pCsr->aColumnSize[i]);
200356            pCsr->aColumnSize[i] = 0;
200357            rc = fts5ApiColumnText(pCtx, i, &z, &n);
200358            if( rc==SQLITE_OK ){
200359              rc = sqlite3Fts5Tokenize(
200360                  pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
200361              );
200362            }
200363          }
200364        }
200365      }
200366      CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
200367    }
200368    if( iCol<0 ){
200369      int i;
200370      *pnToken = 0;
200371      for(i=0; i<pConfig->nCol; i++){
200372        *pnToken += pCsr->aColumnSize[i];
200373      }
200374    }else if( iCol<pConfig->nCol ){
200375      *pnToken = pCsr->aColumnSize[iCol];
200376    }else{
200377      *pnToken = 0;
200378      rc = SQLITE_RANGE;
200379    }
200380    return rc;
200381  }
200382  
200383  /*
200384  ** Implementation of the xSetAuxdata() method.
200385  */
200386  static int fts5ApiSetAuxdata(
200387    Fts5Context *pCtx,              /* Fts5 context */
200388    void *pPtr,                     /* Pointer to save as auxdata */
200389    void(*xDelete)(void*)           /* Destructor for pPtr (or NULL) */
200390  ){
200391    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200392    Fts5Auxdata *pData;
200393  
200394    /* Search through the cursors list of Fts5Auxdata objects for one that
200395    ** corresponds to the currently executing auxiliary function.  */
200396    for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
200397      if( pData->pAux==pCsr->pAux ) break;
200398    }
200399  
200400    if( pData ){
200401      if( pData->xDelete ){
200402        pData->xDelete(pData->pPtr);
200403      }
200404    }else{
200405      int rc = SQLITE_OK;
200406      pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
200407      if( pData==0 ){
200408        if( xDelete ) xDelete(pPtr);
200409        return rc;
200410      }
200411      pData->pAux = pCsr->pAux;
200412      pData->pNext = pCsr->pAuxdata;
200413      pCsr->pAuxdata = pData;
200414    }
200415  
200416    pData->xDelete = xDelete;
200417    pData->pPtr = pPtr;
200418    return SQLITE_OK;
200419  }
200420  
200421  static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
200422    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200423    Fts5Auxdata *pData;
200424    void *pRet = 0;
200425  
200426    for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
200427      if( pData->pAux==pCsr->pAux ) break;
200428    }
200429  
200430    if( pData ){
200431      pRet = pData->pPtr;
200432      if( bClear ){
200433        pData->pPtr = 0;
200434        pData->xDelete = 0;
200435      }
200436    }
200437  
200438    return pRet;
200439  }
200440  
200441  static void fts5ApiPhraseNext(
200442    Fts5Context *pUnused, 
200443    Fts5PhraseIter *pIter, 
200444    int *piCol, int *piOff
200445  ){
200446    UNUSED_PARAM(pUnused);
200447    if( pIter->a>=pIter->b ){
200448      *piCol = -1;
200449      *piOff = -1;
200450    }else{
200451      int iVal;
200452      pIter->a += fts5GetVarint32(pIter->a, iVal);
200453      if( iVal==1 ){
200454        pIter->a += fts5GetVarint32(pIter->a, iVal);
200455        *piCol = iVal;
200456        *piOff = 0;
200457        pIter->a += fts5GetVarint32(pIter->a, iVal);
200458      }
200459      *piOff += (iVal-2);
200460    }
200461  }
200462  
200463  static int fts5ApiPhraseFirst(
200464    Fts5Context *pCtx, 
200465    int iPhrase, 
200466    Fts5PhraseIter *pIter, 
200467    int *piCol, int *piOff
200468  ){
200469    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200470    int n;
200471    int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
200472    if( rc==SQLITE_OK ){
200473      pIter->b = &pIter->a[n];
200474      *piCol = 0;
200475      *piOff = 0;
200476      fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
200477    }
200478    return rc;
200479  }
200480  
200481  static void fts5ApiPhraseNextColumn(
200482    Fts5Context *pCtx, 
200483    Fts5PhraseIter *pIter, 
200484    int *piCol
200485  ){
200486    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200487    Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
200488  
200489    if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
200490      if( pIter->a>=pIter->b ){
200491        *piCol = -1;
200492      }else{
200493        int iIncr;
200494        pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
200495        *piCol += (iIncr-2);
200496      }
200497    }else{
200498      while( 1 ){
200499        int dummy;
200500        if( pIter->a>=pIter->b ){
200501          *piCol = -1;
200502          return;
200503        }
200504        if( pIter->a[0]==0x01 ) break;
200505        pIter->a += fts5GetVarint32(pIter->a, dummy);
200506      }
200507      pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
200508    }
200509  }
200510  
200511  static int fts5ApiPhraseFirstColumn(
200512    Fts5Context *pCtx, 
200513    int iPhrase, 
200514    Fts5PhraseIter *pIter, 
200515    int *piCol
200516  ){
200517    int rc = SQLITE_OK;
200518    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200519    Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
200520  
200521    if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
200522      Fts5Sorter *pSorter = pCsr->pSorter;
200523      int n;
200524      if( pSorter ){
200525        int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
200526        n = pSorter->aIdx[iPhrase] - i1;
200527        pIter->a = &pSorter->aPoslist[i1];
200528      }else{
200529        rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
200530      }
200531      if( rc==SQLITE_OK ){
200532        pIter->b = &pIter->a[n];
200533        *piCol = 0;
200534        fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
200535      }
200536    }else{
200537      int n;
200538      rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
200539      if( rc==SQLITE_OK ){
200540        pIter->b = &pIter->a[n];
200541        if( n<=0 ){
200542          *piCol = -1;
200543        }else if( pIter->a[0]==0x01 ){
200544          pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
200545        }else{
200546          *piCol = 0;
200547        }
200548      }
200549    }
200550  
200551    return rc;
200552  }
200553  
200554  
200555  static int fts5ApiQueryPhrase(Fts5Context*, int, void*, 
200556      int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
200557  );
200558  
200559  static const Fts5ExtensionApi sFts5Api = {
200560    2,                            /* iVersion */
200561    fts5ApiUserData,
200562    fts5ApiColumnCount,
200563    fts5ApiRowCount,
200564    fts5ApiColumnTotalSize,
200565    fts5ApiTokenize,
200566    fts5ApiPhraseCount,
200567    fts5ApiPhraseSize,
200568    fts5ApiInstCount,
200569    fts5ApiInst,
200570    fts5ApiRowid,
200571    fts5ApiColumnText,
200572    fts5ApiColumnSize,
200573    fts5ApiQueryPhrase,
200574    fts5ApiSetAuxdata,
200575    fts5ApiGetAuxdata,
200576    fts5ApiPhraseFirst,
200577    fts5ApiPhraseNext,
200578    fts5ApiPhraseFirstColumn,
200579    fts5ApiPhraseNextColumn,
200580  };
200581  
200582  /*
200583  ** Implementation of API function xQueryPhrase().
200584  */
200585  static int fts5ApiQueryPhrase(
200586    Fts5Context *pCtx, 
200587    int iPhrase, 
200588    void *pUserData,
200589    int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
200590  ){
200591    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200592    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
200593    int rc;
200594    Fts5Cursor *pNew = 0;
200595  
200596    rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
200597    if( rc==SQLITE_OK ){
200598      pNew->ePlan = FTS5_PLAN_MATCH;
200599      pNew->iFirstRowid = SMALLEST_INT64;
200600      pNew->iLastRowid = LARGEST_INT64;
200601      pNew->base.pVtab = (sqlite3_vtab*)pTab;
200602      rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
200603    }
200604  
200605    if( rc==SQLITE_OK ){
200606      for(rc = fts5CursorFirst(pTab, pNew, 0);
200607          rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
200608          rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
200609      ){
200610        rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
200611        if( rc!=SQLITE_OK ){
200612          if( rc==SQLITE_DONE ) rc = SQLITE_OK;
200613          break;
200614        }
200615      }
200616    }
200617  
200618    fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
200619    return rc;
200620  }
200621  
200622  static void fts5ApiInvoke(
200623    Fts5Auxiliary *pAux,
200624    Fts5Cursor *pCsr,
200625    sqlite3_context *context,
200626    int argc,
200627    sqlite3_value **argv
200628  ){
200629    assert( pCsr->pAux==0 );
200630    pCsr->pAux = pAux;
200631    pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
200632    pCsr->pAux = 0;
200633  }
200634  
200635  static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
200636    Fts5Cursor *pCsr;
200637    for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
200638      if( pCsr->iCsrId==iCsrId ) break;
200639    }
200640    return pCsr;
200641  }
200642  
200643  static void fts5ApiCallback(
200644    sqlite3_context *context,
200645    int argc,
200646    sqlite3_value **argv
200647  ){
200648  
200649    Fts5Auxiliary *pAux;
200650    Fts5Cursor *pCsr;
200651    i64 iCsrId;
200652  
200653    assert( argc>=1 );
200654    pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
200655    iCsrId = sqlite3_value_int64(argv[0]);
200656  
200657    pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
200658    if( pCsr==0 ){
200659      char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
200660      sqlite3_result_error(context, zErr, -1);
200661      sqlite3_free(zErr);
200662    }else{
200663      fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
200664    }
200665  }
200666  
200667  
200668  /*
200669  ** Given cursor id iId, return a pointer to the corresponding Fts5Index 
200670  ** object. Or NULL If the cursor id does not exist.
200671  **
200672  ** If successful, set *ppConfig to point to the associated config object 
200673  ** before returning.
200674  */
200675  static Fts5Index *sqlite3Fts5IndexFromCsrid(
200676    Fts5Global *pGlobal,            /* FTS5 global context for db handle */
200677    i64 iCsrId,                     /* Id of cursor to find */
200678    Fts5Config **ppConfig           /* OUT: Configuration object */
200679  ){
200680    Fts5Cursor *pCsr;
200681    Fts5Table *pTab;
200682  
200683    pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
200684    pTab = (Fts5Table*)pCsr->base.pVtab;
200685    *ppConfig = pTab->pConfig;
200686  
200687    return pTab->pIndex;
200688  }
200689  
200690  /*
200691  ** Return a "position-list blob" corresponding to the current position of
200692  ** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
200693  ** the current position-list for each phrase in the query associated with
200694  ** cursor pCsr.
200695  **
200696  ** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
200697  ** the number of phrases in the query. Following the varints are the
200698  ** concatenated position lists for each phrase, in order.
200699  **
200700  ** The first varint (if it exists) contains the size of the position list
200701  ** for phrase 0. The second (same disclaimer) contains the size of position
200702  ** list 1. And so on. There is no size field for the final position list,
200703  ** as it can be derived from the total size of the blob.
200704  */
200705  static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
200706    int i;
200707    int rc = SQLITE_OK;
200708    int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
200709    Fts5Buffer val;
200710  
200711    memset(&val, 0, sizeof(Fts5Buffer));
200712    switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
200713      case FTS5_DETAIL_FULL:
200714  
200715        /* Append the varints */
200716        for(i=0; i<(nPhrase-1); i++){
200717          const u8 *dummy;
200718          int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
200719          sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
200720        }
200721  
200722        /* Append the position lists */
200723        for(i=0; i<nPhrase; i++){
200724          const u8 *pPoslist;
200725          int nPoslist;
200726          nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
200727          sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
200728        }
200729        break;
200730  
200731      case FTS5_DETAIL_COLUMNS:
200732  
200733        /* Append the varints */
200734        for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
200735          const u8 *dummy;
200736          int nByte;
200737          rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
200738          sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
200739        }
200740  
200741        /* Append the position lists */
200742        for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
200743          const u8 *pPoslist;
200744          int nPoslist;
200745          rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
200746          sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
200747        }
200748        break;
200749  
200750      default:
200751        break;
200752    }
200753  
200754    sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
200755    return rc;
200756  }
200757  
200758  /* 
200759  ** This is the xColumn method, called by SQLite to request a value from
200760  ** the row that the supplied cursor currently points to.
200761  */
200762  static int fts5ColumnMethod(
200763    sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
200764    sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
200765    int iCol                        /* Index of column to read value from */
200766  ){
200767    Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
200768    Fts5Config *pConfig = pTab->pConfig;
200769    Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
200770    int rc = SQLITE_OK;
200771    
200772    assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
200773  
200774    if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
200775      if( iCol==pConfig->nCol ){
200776        sqlite3_result_int64(pCtx, pCsr->iSpecial);
200777      }
200778    }else
200779  
200780    if( iCol==pConfig->nCol ){
200781      /* User is requesting the value of the special column with the same name
200782      ** as the table. Return the cursor integer id number. This value is only
200783      ** useful in that it may be passed as the first argument to an FTS5
200784      ** auxiliary function.  */
200785      sqlite3_result_int64(pCtx, pCsr->iCsrId);
200786    }else if( iCol==pConfig->nCol+1 ){
200787  
200788      /* The value of the "rank" column. */
200789      if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
200790        fts5PoslistBlob(pCtx, pCsr);
200791      }else if( 
200792          pCsr->ePlan==FTS5_PLAN_MATCH
200793       || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
200794      ){
200795        if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
200796          fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
200797        }
200798      }
200799    }else if( !fts5IsContentless(pTab) ){
200800      rc = fts5SeekCursor(pCsr, 1);
200801      if( rc==SQLITE_OK ){
200802        sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
200803      }
200804    }
200805    return rc;
200806  }
200807  
200808  
200809  /*
200810  ** This routine implements the xFindFunction method for the FTS3
200811  ** virtual table.
200812  */
200813  static int fts5FindFunctionMethod(
200814    sqlite3_vtab *pVtab,            /* Virtual table handle */
200815    int nUnused,                    /* Number of SQL function arguments */
200816    const char *zName,              /* Name of SQL function */
200817    void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
200818    void **ppArg                    /* OUT: User data for *pxFunc */
200819  ){
200820    Fts5Table *pTab = (Fts5Table*)pVtab;
200821    Fts5Auxiliary *pAux;
200822  
200823    UNUSED_PARAM(nUnused);
200824    pAux = fts5FindAuxiliary(pTab, zName);
200825    if( pAux ){
200826      *pxFunc = fts5ApiCallback;
200827      *ppArg = (void*)pAux;
200828      return 1;
200829    }
200830  
200831    /* No function of the specified name was found. Return 0. */
200832    return 0;
200833  }
200834  
200835  /*
200836  ** Implementation of FTS5 xRename method. Rename an fts5 table.
200837  */
200838  static int fts5RenameMethod(
200839    sqlite3_vtab *pVtab,            /* Virtual table handle */
200840    const char *zName               /* New name of table */
200841  ){
200842    Fts5Table *pTab = (Fts5Table*)pVtab;
200843    return sqlite3Fts5StorageRename(pTab->pStorage, zName);
200844  }
200845  
200846  /*
200847  ** The xSavepoint() method.
200848  **
200849  ** Flush the contents of the pending-terms table to disk.
200850  */
200851  static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
200852    Fts5Table *pTab = (Fts5Table*)pVtab;
200853    UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
200854    fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
200855    fts5TripCursors(pTab);
200856    return sqlite3Fts5StorageSync(pTab->pStorage);
200857  }
200858  
200859  /*
200860  ** The xRelease() method.
200861  **
200862  ** This is a no-op.
200863  */
200864  static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
200865    Fts5Table *pTab = (Fts5Table*)pVtab;
200866    UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
200867    fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
200868    fts5TripCursors(pTab);
200869    return sqlite3Fts5StorageSync(pTab->pStorage);
200870  }
200871  
200872  /*
200873  ** The xRollbackTo() method.
200874  **
200875  ** Discard the contents of the pending terms table.
200876  */
200877  static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
200878    Fts5Table *pTab = (Fts5Table*)pVtab;
200879    UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
200880    fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
200881    fts5TripCursors(pTab);
200882    return sqlite3Fts5StorageRollback(pTab->pStorage);
200883  }
200884  
200885  /*
200886  ** Register a new auxiliary function with global context pGlobal.
200887  */
200888  static int fts5CreateAux(
200889    fts5_api *pApi,                 /* Global context (one per db handle) */
200890    const char *zName,              /* Name of new function */
200891    void *pUserData,                /* User data for aux. function */
200892    fts5_extension_function xFunc,  /* Aux. function implementation */
200893    void(*xDestroy)(void*)          /* Destructor for pUserData */
200894  ){
200895    Fts5Global *pGlobal = (Fts5Global*)pApi;
200896    int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
200897    if( rc==SQLITE_OK ){
200898      Fts5Auxiliary *pAux;
200899      int nName;                      /* Size of zName in bytes, including \0 */
200900      int nByte;                      /* Bytes of space to allocate */
200901  
200902      nName = (int)strlen(zName) + 1;
200903      nByte = sizeof(Fts5Auxiliary) + nName;
200904      pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
200905      if( pAux ){
200906        memset(pAux, 0, nByte);
200907        pAux->zFunc = (char*)&pAux[1];
200908        memcpy(pAux->zFunc, zName, nName);
200909        pAux->pGlobal = pGlobal;
200910        pAux->pUserData = pUserData;
200911        pAux->xFunc = xFunc;
200912        pAux->xDestroy = xDestroy;
200913        pAux->pNext = pGlobal->pAux;
200914        pGlobal->pAux = pAux;
200915      }else{
200916        rc = SQLITE_NOMEM;
200917      }
200918    }
200919  
200920    return rc;
200921  }
200922  
200923  /*
200924  ** Register a new tokenizer. This is the implementation of the 
200925  ** fts5_api.xCreateTokenizer() method.
200926  */
200927  static int fts5CreateTokenizer(
200928    fts5_api *pApi,                 /* Global context (one per db handle) */
200929    const char *zName,              /* Name of new function */
200930    void *pUserData,                /* User data for aux. function */
200931    fts5_tokenizer *pTokenizer,     /* Tokenizer implementation */
200932    void(*xDestroy)(void*)          /* Destructor for pUserData */
200933  ){
200934    Fts5Global *pGlobal = (Fts5Global*)pApi;
200935    Fts5TokenizerModule *pNew;
200936    int nName;                      /* Size of zName and its \0 terminator */
200937    int nByte;                      /* Bytes of space to allocate */
200938    int rc = SQLITE_OK;
200939  
200940    nName = (int)strlen(zName) + 1;
200941    nByte = sizeof(Fts5TokenizerModule) + nName;
200942    pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
200943    if( pNew ){
200944      memset(pNew, 0, nByte);
200945      pNew->zName = (char*)&pNew[1];
200946      memcpy(pNew->zName, zName, nName);
200947      pNew->pUserData = pUserData;
200948      pNew->x = *pTokenizer;
200949      pNew->xDestroy = xDestroy;
200950      pNew->pNext = pGlobal->pTok;
200951      pGlobal->pTok = pNew;
200952      if( pNew->pNext==0 ){
200953        pGlobal->pDfltTok = pNew;
200954      }
200955    }else{
200956      rc = SQLITE_NOMEM;
200957    }
200958  
200959    return rc;
200960  }
200961  
200962  static Fts5TokenizerModule *fts5LocateTokenizer(
200963    Fts5Global *pGlobal, 
200964    const char *zName
200965  ){
200966    Fts5TokenizerModule *pMod = 0;
200967  
200968    if( zName==0 ){
200969      pMod = pGlobal->pDfltTok;
200970    }else{
200971      for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
200972        if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
200973      }
200974    }
200975  
200976    return pMod;
200977  }
200978  
200979  /*
200980  ** Find a tokenizer. This is the implementation of the 
200981  ** fts5_api.xFindTokenizer() method.
200982  */
200983  static int fts5FindTokenizer(
200984    fts5_api *pApi,                 /* Global context (one per db handle) */
200985    const char *zName,              /* Name of new function */
200986    void **ppUserData,
200987    fts5_tokenizer *pTokenizer      /* Populate this object */
200988  ){
200989    int rc = SQLITE_OK;
200990    Fts5TokenizerModule *pMod;
200991  
200992    pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
200993    if( pMod ){
200994      *pTokenizer = pMod->x;
200995      *ppUserData = pMod->pUserData;
200996    }else{
200997      memset(pTokenizer, 0, sizeof(fts5_tokenizer));
200998      rc = SQLITE_ERROR;
200999    }
201000  
201001    return rc;
201002  }
201003  
201004  static int sqlite3Fts5GetTokenizer(
201005    Fts5Global *pGlobal, 
201006    const char **azArg,
201007    int nArg,
201008    Fts5Tokenizer **ppTok,
201009    fts5_tokenizer **ppTokApi,
201010    char **pzErr
201011  ){
201012    Fts5TokenizerModule *pMod;
201013    int rc = SQLITE_OK;
201014  
201015    pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
201016    if( pMod==0 ){
201017      assert( nArg>0 );
201018      rc = SQLITE_ERROR;
201019      *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
201020    }else{
201021      rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
201022      *ppTokApi = &pMod->x;
201023      if( rc!=SQLITE_OK && pzErr ){
201024        *pzErr = sqlite3_mprintf("error in tokenizer constructor");
201025      }
201026    }
201027  
201028    if( rc!=SQLITE_OK ){
201029      *ppTokApi = 0;
201030      *ppTok = 0;
201031    }
201032  
201033    return rc;
201034  }
201035  
201036  static void fts5ModuleDestroy(void *pCtx){
201037    Fts5TokenizerModule *pTok, *pNextTok;
201038    Fts5Auxiliary *pAux, *pNextAux;
201039    Fts5Global *pGlobal = (Fts5Global*)pCtx;
201040  
201041    for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
201042      pNextAux = pAux->pNext;
201043      if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
201044      sqlite3_free(pAux);
201045    }
201046  
201047    for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
201048      pNextTok = pTok->pNext;
201049      if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
201050      sqlite3_free(pTok);
201051    }
201052  
201053    sqlite3_free(pGlobal);
201054  }
201055  
201056  static void fts5Fts5Func(
201057    sqlite3_context *pCtx,          /* Function call context */
201058    int nArg,                       /* Number of args */
201059    sqlite3_value **apArg           /* Function arguments */
201060  ){
201061    Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
201062    fts5_api **ppApi;
201063    UNUSED_PARAM(nArg);
201064    assert( nArg==1 );
201065    ppApi = (fts5_api**)sqlite3_value_pointer(apArg[0], "fts5_api_ptr");
201066    if( ppApi ) *ppApi = &pGlobal->api;
201067  }
201068  
201069  /*
201070  ** Implementation of fts5_source_id() function.
201071  */
201072  static void fts5SourceIdFunc(
201073    sqlite3_context *pCtx,          /* Function call context */
201074    int nArg,                       /* Number of args */
201075    sqlite3_value **apUnused        /* Function arguments */
201076  ){
201077    assert( nArg==0 );
201078    UNUSED_PARAM2(nArg, apUnused);
201079    sqlite3_result_text(pCtx, "fts5: 2017-10-24 18:55:49 1a584e499906b5c87ec7d43d4abce641fdf017c42125b083109bc77c4de48827", -1, SQLITE_TRANSIENT);
201080  }
201081  
201082  static int fts5Init(sqlite3 *db){
201083    static const sqlite3_module fts5Mod = {
201084      /* iVersion      */ 2,
201085      /* xCreate       */ fts5CreateMethod,
201086      /* xConnect      */ fts5ConnectMethod,
201087      /* xBestIndex    */ fts5BestIndexMethod,
201088      /* xDisconnect   */ fts5DisconnectMethod,
201089      /* xDestroy      */ fts5DestroyMethod,
201090      /* xOpen         */ fts5OpenMethod,
201091      /* xClose        */ fts5CloseMethod,
201092      /* xFilter       */ fts5FilterMethod,
201093      /* xNext         */ fts5NextMethod,
201094      /* xEof          */ fts5EofMethod,
201095      /* xColumn       */ fts5ColumnMethod,
201096      /* xRowid        */ fts5RowidMethod,
201097      /* xUpdate       */ fts5UpdateMethod,
201098      /* xBegin        */ fts5BeginMethod,
201099      /* xSync         */ fts5SyncMethod,
201100      /* xCommit       */ fts5CommitMethod,
201101      /* xRollback     */ fts5RollbackMethod,
201102      /* xFindFunction */ fts5FindFunctionMethod,
201103      /* xRename       */ fts5RenameMethod,
201104      /* xSavepoint    */ fts5SavepointMethod,
201105      /* xRelease      */ fts5ReleaseMethod,
201106      /* xRollbackTo   */ fts5RollbackToMethod,
201107    };
201108  
201109    int rc;
201110    Fts5Global *pGlobal = 0;
201111  
201112    pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
201113    if( pGlobal==0 ){
201114      rc = SQLITE_NOMEM;
201115    }else{
201116      void *p = (void*)pGlobal;
201117      memset(pGlobal, 0, sizeof(Fts5Global));
201118      pGlobal->db = db;
201119      pGlobal->api.iVersion = 2;
201120      pGlobal->api.xCreateFunction = fts5CreateAux;
201121      pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
201122      pGlobal->api.xFindTokenizer = fts5FindTokenizer;
201123      rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
201124      if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
201125      if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
201126      if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
201127      if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
201128      if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
201129      if( rc==SQLITE_OK ){
201130        rc = sqlite3_create_function(
201131            db, "fts5", 1, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
201132        );
201133      }
201134      if( rc==SQLITE_OK ){
201135        rc = sqlite3_create_function(
201136            db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
201137        );
201138      }
201139    }
201140  
201141    /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
201142    ** fts5_test_mi.c is compiled and linked into the executable. And call
201143    ** its entry point to enable the matchinfo() demo.  */
201144  #ifdef SQLITE_FTS5_ENABLE_TEST_MI
201145    if( rc==SQLITE_OK ){
201146      extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
201147      rc = sqlite3Fts5TestRegisterMatchinfo(db);
201148    }
201149  #endif
201150  
201151    return rc;
201152  }
201153  
201154  /*
201155  ** The following functions are used to register the module with SQLite. If
201156  ** this module is being built as part of the SQLite core (SQLITE_CORE is
201157  ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
201158  **
201159  ** Or, if this module is being built as a loadable extension, 
201160  ** sqlite3Fts5Init() is omitted and the two standard entry points
201161  ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
201162  */
201163  #ifndef SQLITE_CORE
201164  #ifdef _WIN32
201165  __declspec(dllexport)
201166  #endif
201167  SQLITE_API int sqlite3_fts_init(
201168    sqlite3 *db,
201169    char **pzErrMsg,
201170    const sqlite3_api_routines *pApi
201171  ){
201172    SQLITE_EXTENSION_INIT2(pApi);
201173    (void)pzErrMsg;  /* Unused parameter */
201174    return fts5Init(db);
201175  }
201176  
201177  #ifdef _WIN32
201178  __declspec(dllexport)
201179  #endif
201180  SQLITE_API int sqlite3_fts5_init(
201181    sqlite3 *db,
201182    char **pzErrMsg,
201183    const sqlite3_api_routines *pApi
201184  ){
201185    SQLITE_EXTENSION_INIT2(pApi);
201186    (void)pzErrMsg;  /* Unused parameter */
201187    return fts5Init(db);
201188  }
201189  #else
201190  SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
201191    return fts5Init(db);
201192  }
201193  #endif
201194  
201195  /*
201196  ** 2014 May 31
201197  **
201198  ** The author disclaims copyright to this source code.  In place of
201199  ** a legal notice, here is a blessing:
201200  **
201201  **    May you do good and not evil.
201202  **    May you find forgiveness for yourself and forgive others.
201203  **    May you share freely, never taking more than you give.
201204  **
201205  ******************************************************************************
201206  **
201207  */
201208  
201209  
201210  
201211  /* #include "fts5Int.h" */
201212  
201213  struct Fts5Storage {
201214    Fts5Config *pConfig;
201215    Fts5Index *pIndex;
201216    int bTotalsValid;               /* True if nTotalRow/aTotalSize[] are valid */
201217    i64 nTotalRow;                  /* Total number of rows in FTS table */
201218    i64 *aTotalSize;                /* Total sizes of each column */ 
201219    sqlite3_stmt *aStmt[11];
201220  };
201221  
201222  
201223  #if FTS5_STMT_SCAN_ASC!=0 
201224  # error "FTS5_STMT_SCAN_ASC mismatch" 
201225  #endif
201226  #if FTS5_STMT_SCAN_DESC!=1 
201227  # error "FTS5_STMT_SCAN_DESC mismatch" 
201228  #endif
201229  #if FTS5_STMT_LOOKUP!=2
201230  # error "FTS5_STMT_LOOKUP mismatch" 
201231  #endif
201232  
201233  #define FTS5_STMT_INSERT_CONTENT  3
201234  #define FTS5_STMT_REPLACE_CONTENT 4
201235  #define FTS5_STMT_DELETE_CONTENT  5
201236  #define FTS5_STMT_REPLACE_DOCSIZE  6
201237  #define FTS5_STMT_DELETE_DOCSIZE  7
201238  #define FTS5_STMT_LOOKUP_DOCSIZE  8
201239  #define FTS5_STMT_REPLACE_CONFIG 9
201240  #define FTS5_STMT_SCAN 10
201241  
201242  /*
201243  ** Prepare the two insert statements - Fts5Storage.pInsertContent and
201244  ** Fts5Storage.pInsertDocsize - if they have not already been prepared.
201245  ** Return SQLITE_OK if successful, or an SQLite error code if an error
201246  ** occurs.
201247  */
201248  static int fts5StorageGetStmt(
201249    Fts5Storage *p,                 /* Storage handle */
201250    int eStmt,                      /* FTS5_STMT_XXX constant */
201251    sqlite3_stmt **ppStmt,          /* OUT: Prepared statement handle */
201252    char **pzErrMsg                 /* OUT: Error message (if any) */
201253  ){
201254    int rc = SQLITE_OK;
201255  
201256    /* If there is no %_docsize table, there should be no requests for 
201257    ** statements to operate on it.  */
201258    assert( p->pConfig->bColumnsize || (
201259          eStmt!=FTS5_STMT_REPLACE_DOCSIZE 
201260       && eStmt!=FTS5_STMT_DELETE_DOCSIZE 
201261       && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE 
201262    ));
201263  
201264    assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
201265    if( p->aStmt[eStmt]==0 ){
201266      const char *azStmt[] = {
201267        "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
201268        "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
201269        "SELECT %s FROM %s T WHERE T.%Q=?",               /* LOOKUP  */
201270  
201271        "INSERT INTO %Q.'%q_content' VALUES(%s)",         /* INSERT_CONTENT  */
201272        "REPLACE INTO %Q.'%q_content' VALUES(%s)",        /* REPLACE_CONTENT */
201273        "DELETE FROM %Q.'%q_content' WHERE id=?",         /* DELETE_CONTENT  */
201274        "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",       /* REPLACE_DOCSIZE  */
201275        "DELETE FROM %Q.'%q_docsize' WHERE id=?",         /* DELETE_DOCSIZE  */
201276  
201277        "SELECT sz FROM %Q.'%q_docsize' WHERE id=?",      /* LOOKUP_DOCSIZE  */
201278  
201279        "REPLACE INTO %Q.'%q_config' VALUES(?,?)",        /* REPLACE_CONFIG */
201280        "SELECT %s FROM %s AS T",                         /* SCAN */
201281      };
201282      Fts5Config *pC = p->pConfig;
201283      char *zSql = 0;
201284  
201285      switch( eStmt ){
201286        case FTS5_STMT_SCAN:
201287          zSql = sqlite3_mprintf(azStmt[eStmt], 
201288              pC->zContentExprlist, pC->zContent
201289          );
201290          break;
201291  
201292        case FTS5_STMT_SCAN_ASC:
201293        case FTS5_STMT_SCAN_DESC:
201294          zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist, 
201295              pC->zContent, pC->zContentRowid, pC->zContentRowid,
201296              pC->zContentRowid
201297          );
201298          break;
201299  
201300        case FTS5_STMT_LOOKUP:
201301          zSql = sqlite3_mprintf(azStmt[eStmt], 
201302              pC->zContentExprlist, pC->zContent, pC->zContentRowid
201303          );
201304          break;
201305  
201306        case FTS5_STMT_INSERT_CONTENT: 
201307        case FTS5_STMT_REPLACE_CONTENT: {
201308          int nCol = pC->nCol + 1;
201309          char *zBind;
201310          int i;
201311  
201312          zBind = sqlite3_malloc(1 + nCol*2);
201313          if( zBind ){
201314            for(i=0; i<nCol; i++){
201315              zBind[i*2] = '?';
201316              zBind[i*2 + 1] = ',';
201317            }
201318            zBind[i*2-1] = '\0';
201319            zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
201320            sqlite3_free(zBind);
201321          }
201322          break;
201323        }
201324  
201325        default:
201326          zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
201327          break;
201328      }
201329  
201330      if( zSql==0 ){
201331        rc = SQLITE_NOMEM;
201332      }else{
201333        rc = sqlite3_prepare_v3(pC->db, zSql, -1,
201334                                SQLITE_PREPARE_PERSISTENT, &p->aStmt[eStmt], 0);
201335        sqlite3_free(zSql);
201336        if( rc!=SQLITE_OK && pzErrMsg ){
201337          *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
201338        }
201339      }
201340    }
201341  
201342    *ppStmt = p->aStmt[eStmt];
201343    sqlite3_reset(*ppStmt);
201344    return rc;
201345  }
201346  
201347  
201348  static int fts5ExecPrintf(
201349    sqlite3 *db,
201350    char **pzErr,
201351    const char *zFormat,
201352    ...
201353  ){
201354    int rc;
201355    va_list ap;                     /* ... printf arguments */
201356    char *zSql;
201357  
201358    va_start(ap, zFormat);
201359    zSql = sqlite3_vmprintf(zFormat, ap);
201360  
201361    if( zSql==0 ){
201362      rc = SQLITE_NOMEM;
201363    }else{
201364      rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
201365      sqlite3_free(zSql);
201366    }
201367  
201368    va_end(ap);
201369    return rc;
201370  }
201371  
201372  /*
201373  ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
201374  ** code otherwise.
201375  */
201376  static int sqlite3Fts5DropAll(Fts5Config *pConfig){
201377    int rc = fts5ExecPrintf(pConfig->db, 0, 
201378        "DROP TABLE IF EXISTS %Q.'%q_data';"
201379        "DROP TABLE IF EXISTS %Q.'%q_idx';"
201380        "DROP TABLE IF EXISTS %Q.'%q_config';",
201381        pConfig->zDb, pConfig->zName,
201382        pConfig->zDb, pConfig->zName,
201383        pConfig->zDb, pConfig->zName
201384    );
201385    if( rc==SQLITE_OK && pConfig->bColumnsize ){
201386      rc = fts5ExecPrintf(pConfig->db, 0, 
201387          "DROP TABLE IF EXISTS %Q.'%q_docsize';",
201388          pConfig->zDb, pConfig->zName
201389      );
201390    }
201391    if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
201392      rc = fts5ExecPrintf(pConfig->db, 0, 
201393          "DROP TABLE IF EXISTS %Q.'%q_content';",
201394          pConfig->zDb, pConfig->zName
201395      );
201396    }
201397    return rc;
201398  }
201399  
201400  static void fts5StorageRenameOne(
201401    Fts5Config *pConfig,            /* Current FTS5 configuration */
201402    int *pRc,                       /* IN/OUT: Error code */
201403    const char *zTail,              /* Tail of table name e.g. "data", "config" */
201404    const char *zName               /* New name of FTS5 table */
201405  ){
201406    if( *pRc==SQLITE_OK ){
201407      *pRc = fts5ExecPrintf(pConfig->db, 0, 
201408          "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
201409          pConfig->zDb, pConfig->zName, zTail, zName, zTail
201410      );
201411    }
201412  }
201413  
201414  static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
201415    Fts5Config *pConfig = pStorage->pConfig;
201416    int rc = sqlite3Fts5StorageSync(pStorage);
201417  
201418    fts5StorageRenameOne(pConfig, &rc, "data", zName);
201419    fts5StorageRenameOne(pConfig, &rc, "idx", zName);
201420    fts5StorageRenameOne(pConfig, &rc, "config", zName);
201421    if( pConfig->bColumnsize ){
201422      fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
201423    }
201424    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
201425      fts5StorageRenameOne(pConfig, &rc, "content", zName);
201426    }
201427    return rc;
201428  }
201429  
201430  /*
201431  ** Create the shadow table named zPost, with definition zDefn. Return
201432  ** SQLITE_OK if successful, or an SQLite error code otherwise.
201433  */
201434  static int sqlite3Fts5CreateTable(
201435    Fts5Config *pConfig,            /* FTS5 configuration */
201436    const char *zPost,              /* Shadow table to create (e.g. "content") */
201437    const char *zDefn,              /* Columns etc. for shadow table */
201438    int bWithout,                   /* True for without rowid */
201439    char **pzErr                    /* OUT: Error message */
201440  ){
201441    int rc;
201442    char *zErr = 0;
201443  
201444    rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
201445        pConfig->zDb, pConfig->zName, zPost, zDefn, 
201446  #ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
201447        bWithout?" WITHOUT ROWID":
201448  #endif
201449        ""
201450    );
201451    if( zErr ){
201452      *pzErr = sqlite3_mprintf(
201453          "fts5: error creating shadow table %q_%s: %s", 
201454          pConfig->zName, zPost, zErr
201455      );
201456      sqlite3_free(zErr);
201457    }
201458  
201459    return rc;
201460  }
201461  
201462  /*
201463  ** Open a new Fts5Index handle. If the bCreate argument is true, create
201464  ** and initialize the underlying tables 
201465  **
201466  ** If successful, set *pp to point to the new object and return SQLITE_OK.
201467  ** Otherwise, set *pp to NULL and return an SQLite error code.
201468  */
201469  static int sqlite3Fts5StorageOpen(
201470    Fts5Config *pConfig, 
201471    Fts5Index *pIndex, 
201472    int bCreate, 
201473    Fts5Storage **pp,
201474    char **pzErr                    /* OUT: Error message */
201475  ){
201476    int rc = SQLITE_OK;
201477    Fts5Storage *p;                 /* New object */
201478    int nByte;                      /* Bytes of space to allocate */
201479  
201480    nByte = sizeof(Fts5Storage)               /* Fts5Storage object */
201481          + pConfig->nCol * sizeof(i64);      /* Fts5Storage.aTotalSize[] */
201482    *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
201483    if( !p ) return SQLITE_NOMEM;
201484  
201485    memset(p, 0, nByte);
201486    p->aTotalSize = (i64*)&p[1];
201487    p->pConfig = pConfig;
201488    p->pIndex = pIndex;
201489  
201490    if( bCreate ){
201491      if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
201492        int nDefn = 32 + pConfig->nCol*10;
201493        char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
201494        if( zDefn==0 ){
201495          rc = SQLITE_NOMEM;
201496        }else{
201497          int i;
201498          int iOff;
201499          sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
201500          iOff = (int)strlen(zDefn);
201501          for(i=0; i<pConfig->nCol; i++){
201502            sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
201503            iOff += (int)strlen(&zDefn[iOff]);
201504          }
201505          rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
201506        }
201507        sqlite3_free(zDefn);
201508      }
201509  
201510      if( rc==SQLITE_OK && pConfig->bColumnsize ){
201511        rc = sqlite3Fts5CreateTable(
201512            pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
201513        );
201514      }
201515      if( rc==SQLITE_OK ){
201516        rc = sqlite3Fts5CreateTable(
201517            pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
201518        );
201519      }
201520      if( rc==SQLITE_OK ){
201521        rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
201522      }
201523    }
201524  
201525    if( rc ){
201526      sqlite3Fts5StorageClose(p);
201527      *pp = 0;
201528    }
201529    return rc;
201530  }
201531  
201532  /*
201533  ** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
201534  */
201535  static int sqlite3Fts5StorageClose(Fts5Storage *p){
201536    int rc = SQLITE_OK;
201537    if( p ){
201538      int i;
201539  
201540      /* Finalize all SQL statements */
201541      for(i=0; i<ArraySize(p->aStmt); i++){
201542        sqlite3_finalize(p->aStmt[i]);
201543      }
201544  
201545      sqlite3_free(p);
201546    }
201547    return rc;
201548  }
201549  
201550  typedef struct Fts5InsertCtx Fts5InsertCtx;
201551  struct Fts5InsertCtx {
201552    Fts5Storage *pStorage;
201553    int iCol;
201554    int szCol;                      /* Size of column value in tokens */
201555  };
201556  
201557  /*
201558  ** Tokenization callback used when inserting tokens into the FTS index.
201559  */
201560  static int fts5StorageInsertCallback(
201561    void *pContext,                 /* Pointer to Fts5InsertCtx object */
201562    int tflags,
201563    const char *pToken,             /* Buffer containing token */
201564    int nToken,                     /* Size of token in bytes */
201565    int iUnused1,                   /* Start offset of token */
201566    int iUnused2                    /* End offset of token */
201567  ){
201568    Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
201569    Fts5Index *pIdx = pCtx->pStorage->pIndex;
201570    UNUSED_PARAM2(iUnused1, iUnused2);
201571    if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
201572    if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
201573      pCtx->szCol++;
201574    }
201575    return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
201576  }
201577  
201578  /*
201579  ** If a row with rowid iDel is present in the %_content table, add the
201580  ** delete-markers to the FTS index necessary to delete it. Do not actually
201581  ** remove the %_content row at this time though.
201582  */
201583  static int fts5StorageDeleteFromIndex(
201584    Fts5Storage *p, 
201585    i64 iDel, 
201586    sqlite3_value **apVal
201587  ){
201588    Fts5Config *pConfig = p->pConfig;
201589    sqlite3_stmt *pSeek = 0;        /* SELECT to read row iDel from %_data */
201590    int rc;                         /* Return code */
201591    int rc2;                        /* sqlite3_reset() return code */
201592    int iCol;
201593    Fts5InsertCtx ctx;
201594  
201595    if( apVal==0 ){
201596      rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
201597      if( rc!=SQLITE_OK ) return rc;
201598      sqlite3_bind_int64(pSeek, 1, iDel);
201599      if( sqlite3_step(pSeek)!=SQLITE_ROW ){
201600        return sqlite3_reset(pSeek);
201601      }
201602    }
201603  
201604    ctx.pStorage = p;
201605    ctx.iCol = -1;
201606    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
201607    for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
201608      if( pConfig->abUnindexed[iCol-1]==0 ){
201609        const char *zText;
201610        int nText;
201611        if( pSeek ){
201612          zText = (const char*)sqlite3_column_text(pSeek, iCol);
201613          nText = sqlite3_column_bytes(pSeek, iCol);
201614        }else{
201615          zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
201616          nText = sqlite3_value_bytes(apVal[iCol-1]);
201617        }
201618        ctx.szCol = 0;
201619        rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT, 
201620            zText, nText, (void*)&ctx, fts5StorageInsertCallback
201621        );
201622        p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
201623      }
201624    }
201625    p->nTotalRow--;
201626  
201627    rc2 = sqlite3_reset(pSeek);
201628    if( rc==SQLITE_OK ) rc = rc2;
201629    return rc;
201630  }
201631  
201632  
201633  /*
201634  ** Insert a record into the %_docsize table. Specifically, do:
201635  **
201636  **   INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
201637  **
201638  ** If there is no %_docsize table (as happens if the columnsize=0 option
201639  ** is specified when the FTS5 table is created), this function is a no-op.
201640  */
201641  static int fts5StorageInsertDocsize(
201642    Fts5Storage *p,                 /* Storage module to write to */
201643    i64 iRowid,                     /* id value */
201644    Fts5Buffer *pBuf                /* sz value */
201645  ){
201646    int rc = SQLITE_OK;
201647    if( p->pConfig->bColumnsize ){
201648      sqlite3_stmt *pReplace = 0;
201649      rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
201650      if( rc==SQLITE_OK ){
201651        sqlite3_bind_int64(pReplace, 1, iRowid);
201652        sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
201653        sqlite3_step(pReplace);
201654        rc = sqlite3_reset(pReplace);
201655      }
201656    }
201657    return rc;
201658  }
201659  
201660  /*
201661  ** Load the contents of the "averages" record from disk into the 
201662  ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
201663  ** argument bCache is true, set the p->bTotalsValid flag to indicate
201664  ** that the contents of aTotalSize[] and nTotalRow are valid until
201665  ** further notice.
201666  **
201667  ** Return SQLITE_OK if successful, or an SQLite error code if an error
201668  ** occurs.
201669  */
201670  static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
201671    int rc = SQLITE_OK;
201672    if( p->bTotalsValid==0 ){
201673      rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
201674      p->bTotalsValid = bCache;
201675    }
201676    return rc;
201677  }
201678  
201679  /*
201680  ** Store the current contents of the p->nTotalRow and p->aTotalSize[] 
201681  ** variables in the "averages" record on disk.
201682  **
201683  ** Return SQLITE_OK if successful, or an SQLite error code if an error
201684  ** occurs.
201685  */
201686  static int fts5StorageSaveTotals(Fts5Storage *p){
201687    int nCol = p->pConfig->nCol;
201688    int i;
201689    Fts5Buffer buf;
201690    int rc = SQLITE_OK;
201691    memset(&buf, 0, sizeof(buf));
201692  
201693    sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
201694    for(i=0; i<nCol; i++){
201695      sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
201696    }
201697    if( rc==SQLITE_OK ){
201698      rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
201699    }
201700    sqlite3_free(buf.p);
201701  
201702    return rc;
201703  }
201704  
201705  /*
201706  ** Remove a row from the FTS table.
201707  */
201708  static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
201709    Fts5Config *pConfig = p->pConfig;
201710    int rc;
201711    sqlite3_stmt *pDel = 0;
201712  
201713    assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
201714    rc = fts5StorageLoadTotals(p, 1);
201715  
201716    /* Delete the index records */
201717    if( rc==SQLITE_OK ){
201718      rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
201719    }
201720  
201721    /* Delete the %_docsize record */
201722    if( rc==SQLITE_OK && pConfig->bColumnsize ){
201723      rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
201724      if( rc==SQLITE_OK ){
201725        sqlite3_bind_int64(pDel, 1, iDel);
201726        sqlite3_step(pDel);
201727        rc = sqlite3_reset(pDel);
201728      }
201729    }
201730  
201731    /* Delete the %_content record */
201732    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
201733      if( rc==SQLITE_OK ){
201734        rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
201735      }
201736      if( rc==SQLITE_OK ){
201737        sqlite3_bind_int64(pDel, 1, iDel);
201738        sqlite3_step(pDel);
201739        rc = sqlite3_reset(pDel);
201740      }
201741    }
201742  
201743    return rc;
201744  }
201745  
201746  /*
201747  ** Delete all entries in the FTS5 index.
201748  */
201749  static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
201750    Fts5Config *pConfig = p->pConfig;
201751    int rc;
201752  
201753    /* Delete the contents of the %_data and %_docsize tables. */
201754    rc = fts5ExecPrintf(pConfig->db, 0,
201755        "DELETE FROM %Q.'%q_data';" 
201756        "DELETE FROM %Q.'%q_idx';",
201757        pConfig->zDb, pConfig->zName,
201758        pConfig->zDb, pConfig->zName
201759    );
201760    if( rc==SQLITE_OK && pConfig->bColumnsize ){
201761      rc = fts5ExecPrintf(pConfig->db, 0,
201762          "DELETE FROM %Q.'%q_docsize';",
201763          pConfig->zDb, pConfig->zName
201764      );
201765    }
201766  
201767    /* Reinitialize the %_data table. This call creates the initial structure
201768    ** and averages records.  */
201769    if( rc==SQLITE_OK ){
201770      rc = sqlite3Fts5IndexReinit(p->pIndex);
201771    }
201772    if( rc==SQLITE_OK ){
201773      rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
201774    }
201775    return rc;
201776  }
201777  
201778  static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
201779    Fts5Buffer buf = {0,0,0};
201780    Fts5Config *pConfig = p->pConfig;
201781    sqlite3_stmt *pScan = 0;
201782    Fts5InsertCtx ctx;
201783    int rc;
201784  
201785    memset(&ctx, 0, sizeof(Fts5InsertCtx));
201786    ctx.pStorage = p;
201787    rc = sqlite3Fts5StorageDeleteAll(p);
201788    if( rc==SQLITE_OK ){
201789      rc = fts5StorageLoadTotals(p, 1);
201790    }
201791  
201792    if( rc==SQLITE_OK ){
201793      rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
201794    }
201795  
201796    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
201797      i64 iRowid = sqlite3_column_int64(pScan, 0);
201798  
201799      sqlite3Fts5BufferZero(&buf);
201800      rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
201801      for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
201802        ctx.szCol = 0;
201803        if( pConfig->abUnindexed[ctx.iCol]==0 ){
201804          rc = sqlite3Fts5Tokenize(pConfig, 
201805              FTS5_TOKENIZE_DOCUMENT,
201806              (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
201807              sqlite3_column_bytes(pScan, ctx.iCol+1),
201808              (void*)&ctx,
201809              fts5StorageInsertCallback
201810          );
201811        }
201812        sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
201813        p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
201814      }
201815      p->nTotalRow++;
201816  
201817      if( rc==SQLITE_OK ){
201818        rc = fts5StorageInsertDocsize(p, iRowid, &buf);
201819      }
201820    }
201821    sqlite3_free(buf.p);
201822  
201823    /* Write the averages record */
201824    if( rc==SQLITE_OK ){
201825      rc = fts5StorageSaveTotals(p);
201826    }
201827    return rc;
201828  }
201829  
201830  static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
201831    return sqlite3Fts5IndexOptimize(p->pIndex);
201832  }
201833  
201834  static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
201835    return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
201836  }
201837  
201838  static int sqlite3Fts5StorageReset(Fts5Storage *p){
201839    return sqlite3Fts5IndexReset(p->pIndex);
201840  }
201841  
201842  /*
201843  ** Allocate a new rowid. This is used for "external content" tables when
201844  ** a NULL value is inserted into the rowid column. The new rowid is allocated
201845  ** by inserting a dummy row into the %_docsize table. The dummy will be
201846  ** overwritten later.
201847  **
201848  ** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
201849  ** this case the user is required to provide a rowid explicitly.
201850  */
201851  static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
201852    int rc = SQLITE_MISMATCH;
201853    if( p->pConfig->bColumnsize ){
201854      sqlite3_stmt *pReplace = 0;
201855      rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
201856      if( rc==SQLITE_OK ){
201857        sqlite3_bind_null(pReplace, 1);
201858        sqlite3_bind_null(pReplace, 2);
201859        sqlite3_step(pReplace);
201860        rc = sqlite3_reset(pReplace);
201861      }
201862      if( rc==SQLITE_OK ){
201863        *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
201864      }
201865    }
201866    return rc;
201867  }
201868  
201869  /*
201870  ** Insert a new row into the FTS content table.
201871  */
201872  static int sqlite3Fts5StorageContentInsert(
201873    Fts5Storage *p, 
201874    sqlite3_value **apVal, 
201875    i64 *piRowid
201876  ){
201877    Fts5Config *pConfig = p->pConfig;
201878    int rc = SQLITE_OK;
201879  
201880    /* Insert the new row into the %_content table. */
201881    if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
201882      if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
201883        *piRowid = sqlite3_value_int64(apVal[1]);
201884      }else{
201885        rc = fts5StorageNewRowid(p, piRowid);
201886      }
201887    }else{
201888      sqlite3_stmt *pInsert = 0;    /* Statement to write %_content table */
201889      int i;                        /* Counter variable */
201890      rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
201891      for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
201892        rc = sqlite3_bind_value(pInsert, i, apVal[i]);
201893      }
201894      if( rc==SQLITE_OK ){
201895        sqlite3_step(pInsert);
201896        rc = sqlite3_reset(pInsert);
201897      }
201898      *piRowid = sqlite3_last_insert_rowid(pConfig->db);
201899    }
201900  
201901    return rc;
201902  }
201903  
201904  /*
201905  ** Insert new entries into the FTS index and %_docsize table.
201906  */
201907  static int sqlite3Fts5StorageIndexInsert(
201908    Fts5Storage *p, 
201909    sqlite3_value **apVal, 
201910    i64 iRowid
201911  ){
201912    Fts5Config *pConfig = p->pConfig;
201913    int rc = SQLITE_OK;             /* Return code */
201914    Fts5InsertCtx ctx;              /* Tokenization callback context object */
201915    Fts5Buffer buf;                 /* Buffer used to build up %_docsize blob */
201916  
201917    memset(&buf, 0, sizeof(Fts5Buffer));
201918    ctx.pStorage = p;
201919    rc = fts5StorageLoadTotals(p, 1);
201920  
201921    if( rc==SQLITE_OK ){
201922      rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
201923    }
201924    for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
201925      ctx.szCol = 0;
201926      if( pConfig->abUnindexed[ctx.iCol]==0 ){
201927        rc = sqlite3Fts5Tokenize(pConfig, 
201928            FTS5_TOKENIZE_DOCUMENT,
201929            (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
201930            sqlite3_value_bytes(apVal[ctx.iCol+2]),
201931            (void*)&ctx,
201932            fts5StorageInsertCallback
201933        );
201934      }
201935      sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
201936      p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
201937    }
201938    p->nTotalRow++;
201939  
201940    /* Write the %_docsize record */
201941    if( rc==SQLITE_OK ){
201942      rc = fts5StorageInsertDocsize(p, iRowid, &buf);
201943    }
201944    sqlite3_free(buf.p);
201945  
201946    return rc;
201947  }
201948  
201949  static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
201950    Fts5Config *pConfig = p->pConfig;
201951    char *zSql;
201952    int rc;
201953  
201954    zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'", 
201955        pConfig->zDb, pConfig->zName, zSuffix
201956    );
201957    if( zSql==0 ){
201958      rc = SQLITE_NOMEM;
201959    }else{
201960      sqlite3_stmt *pCnt = 0;
201961      rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
201962      if( rc==SQLITE_OK ){
201963        if( SQLITE_ROW==sqlite3_step(pCnt) ){
201964          *pnRow = sqlite3_column_int64(pCnt, 0);
201965        }
201966        rc = sqlite3_finalize(pCnt);
201967      }
201968    }
201969  
201970    sqlite3_free(zSql);
201971    return rc;
201972  }
201973  
201974  /*
201975  ** Context object used by sqlite3Fts5StorageIntegrity().
201976  */
201977  typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
201978  struct Fts5IntegrityCtx {
201979    i64 iRowid;
201980    int iCol;
201981    int szCol;
201982    u64 cksum;
201983    Fts5Termset *pTermset;
201984    Fts5Config *pConfig;
201985  };
201986  
201987  
201988  /*
201989  ** Tokenization callback used by integrity check.
201990  */
201991  static int fts5StorageIntegrityCallback(
201992    void *pContext,                 /* Pointer to Fts5IntegrityCtx object */
201993    int tflags,
201994    const char *pToken,             /* Buffer containing token */
201995    int nToken,                     /* Size of token in bytes */
201996    int iUnused1,                   /* Start offset of token */
201997    int iUnused2                    /* End offset of token */
201998  ){
201999    Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
202000    Fts5Termset *pTermset = pCtx->pTermset;
202001    int bPresent;
202002    int ii;
202003    int rc = SQLITE_OK;
202004    int iPos;
202005    int iCol;
202006  
202007    UNUSED_PARAM2(iUnused1, iUnused2);
202008    if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
202009  
202010    if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
202011      pCtx->szCol++;
202012    }
202013  
202014    switch( pCtx->pConfig->eDetail ){
202015      case FTS5_DETAIL_FULL:
202016        iPos = pCtx->szCol-1;
202017        iCol = pCtx->iCol;
202018        break;
202019  
202020      case FTS5_DETAIL_COLUMNS:
202021        iPos = pCtx->iCol;
202022        iCol = 0;
202023        break;
202024  
202025      default:
202026        assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
202027        iPos = 0;
202028        iCol = 0;
202029        break;
202030    }
202031  
202032    rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
202033    if( rc==SQLITE_OK && bPresent==0 ){
202034      pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
202035          pCtx->iRowid, iCol, iPos, 0, pToken, nToken
202036      );
202037    }
202038  
202039    for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
202040      const int nChar = pCtx->pConfig->aPrefix[ii];
202041      int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
202042      if( nByte ){
202043        rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
202044        if( bPresent==0 ){
202045          pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
202046              pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
202047          );
202048        }
202049      }
202050    }
202051  
202052    return rc;
202053  }
202054  
202055  /*
202056  ** Check that the contents of the FTS index match that of the %_content
202057  ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
202058  ** some other SQLite error code if an error occurs while attempting to
202059  ** determine this.
202060  */
202061  static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
202062    Fts5Config *pConfig = p->pConfig;
202063    int rc;                         /* Return code */
202064    int *aColSize;                  /* Array of size pConfig->nCol */
202065    i64 *aTotalSize;                /* Array of size pConfig->nCol */
202066    Fts5IntegrityCtx ctx;
202067    sqlite3_stmt *pScan;
202068  
202069    memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
202070    ctx.pConfig = p->pConfig;
202071    aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
202072    if( !aTotalSize ) return SQLITE_NOMEM;
202073    aColSize = (int*)&aTotalSize[pConfig->nCol];
202074    memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
202075  
202076    /* Generate the expected index checksum based on the contents of the
202077    ** %_content table. This block stores the checksum in ctx.cksum. */
202078    rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
202079    if( rc==SQLITE_OK ){
202080      int rc2;
202081      while( SQLITE_ROW==sqlite3_step(pScan) ){
202082        int i;
202083        ctx.iRowid = sqlite3_column_int64(pScan, 0);
202084        ctx.szCol = 0;
202085        if( pConfig->bColumnsize ){
202086          rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
202087        }
202088        if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
202089          rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
202090        }
202091        for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
202092          if( pConfig->abUnindexed[i] ) continue;
202093          ctx.iCol = i;
202094          ctx.szCol = 0;
202095          if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
202096            rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
202097          }
202098          if( rc==SQLITE_OK ){
202099            rc = sqlite3Fts5Tokenize(pConfig, 
202100                FTS5_TOKENIZE_DOCUMENT,
202101                (const char*)sqlite3_column_text(pScan, i+1),
202102                sqlite3_column_bytes(pScan, i+1),
202103                (void*)&ctx,
202104                fts5StorageIntegrityCallback
202105            );
202106          }
202107          if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
202108            rc = FTS5_CORRUPT;
202109          }
202110          aTotalSize[i] += ctx.szCol;
202111          if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
202112            sqlite3Fts5TermsetFree(ctx.pTermset);
202113            ctx.pTermset = 0;
202114          }
202115        }
202116        sqlite3Fts5TermsetFree(ctx.pTermset);
202117        ctx.pTermset = 0;
202118  
202119        if( rc!=SQLITE_OK ) break;
202120      }
202121      rc2 = sqlite3_reset(pScan);
202122      if( rc==SQLITE_OK ) rc = rc2;
202123    }
202124  
202125    /* Test that the "totals" (sometimes called "averages") record looks Ok */
202126    if( rc==SQLITE_OK ){
202127      int i;
202128      rc = fts5StorageLoadTotals(p, 0);
202129      for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
202130        if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
202131      }
202132    }
202133  
202134    /* Check that the %_docsize and %_content tables contain the expected
202135    ** number of rows.  */
202136    if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
202137      i64 nRow = 0;
202138      rc = fts5StorageCount(p, "content", &nRow);
202139      if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
202140    }
202141    if( rc==SQLITE_OK && pConfig->bColumnsize ){
202142      i64 nRow = 0;
202143      rc = fts5StorageCount(p, "docsize", &nRow);
202144      if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
202145    }
202146  
202147    /* Pass the expected checksum down to the FTS index module. It will
202148    ** verify, amongst other things, that it matches the checksum generated by
202149    ** inspecting the index itself.  */
202150    if( rc==SQLITE_OK ){
202151      rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
202152    }
202153  
202154    sqlite3_free(aTotalSize);
202155    return rc;
202156  }
202157  
202158  /*
202159  ** Obtain an SQLite statement handle that may be used to read data from the
202160  ** %_content table.
202161  */
202162  static int sqlite3Fts5StorageStmt(
202163    Fts5Storage *p, 
202164    int eStmt, 
202165    sqlite3_stmt **pp, 
202166    char **pzErrMsg
202167  ){
202168    int rc;
202169    assert( eStmt==FTS5_STMT_SCAN_ASC 
202170         || eStmt==FTS5_STMT_SCAN_DESC
202171         || eStmt==FTS5_STMT_LOOKUP
202172    );
202173    rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
202174    if( rc==SQLITE_OK ){
202175      assert( p->aStmt[eStmt]==*pp );
202176      p->aStmt[eStmt] = 0;
202177    }
202178    return rc;
202179  }
202180  
202181  /*
202182  ** Release an SQLite statement handle obtained via an earlier call to
202183  ** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
202184  ** must match that passed to the sqlite3Fts5StorageStmt() call.
202185  */
202186  static void sqlite3Fts5StorageStmtRelease(
202187    Fts5Storage *p, 
202188    int eStmt, 
202189    sqlite3_stmt *pStmt
202190  ){
202191    assert( eStmt==FTS5_STMT_SCAN_ASC
202192         || eStmt==FTS5_STMT_SCAN_DESC
202193         || eStmt==FTS5_STMT_LOOKUP
202194    );
202195    if( p->aStmt[eStmt]==0 ){
202196      sqlite3_reset(pStmt);
202197      p->aStmt[eStmt] = pStmt;
202198    }else{
202199      sqlite3_finalize(pStmt);
202200    }
202201  }
202202  
202203  static int fts5StorageDecodeSizeArray(
202204    int *aCol, int nCol,            /* Array to populate */
202205    const u8 *aBlob, int nBlob      /* Record to read varints from */
202206  ){
202207    int i;
202208    int iOff = 0;
202209    for(i=0; i<nCol; i++){
202210      if( iOff>=nBlob ) return 1;
202211      iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
202212    }
202213    return (iOff!=nBlob);
202214  }
202215  
202216  /*
202217  ** Argument aCol points to an array of integers containing one entry for
202218  ** each table column. This function reads the %_docsize record for the
202219  ** specified rowid and populates aCol[] with the results.
202220  **
202221  ** An SQLite error code is returned if an error occurs, or SQLITE_OK
202222  ** otherwise.
202223  */
202224  static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
202225    int nCol = p->pConfig->nCol;    /* Number of user columns in table */
202226    sqlite3_stmt *pLookup = 0;      /* Statement to query %_docsize */
202227    int rc;                         /* Return Code */
202228  
202229    assert( p->pConfig->bColumnsize );
202230    rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
202231    if( rc==SQLITE_OK ){
202232      int bCorrupt = 1;
202233      sqlite3_bind_int64(pLookup, 1, iRowid);
202234      if( SQLITE_ROW==sqlite3_step(pLookup) ){
202235        const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
202236        int nBlob = sqlite3_column_bytes(pLookup, 0);
202237        if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
202238          bCorrupt = 0;
202239        }
202240      }
202241      rc = sqlite3_reset(pLookup);
202242      if( bCorrupt && rc==SQLITE_OK ){
202243        rc = FTS5_CORRUPT;
202244      }
202245    }
202246  
202247    return rc;
202248  }
202249  
202250  static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
202251    int rc = fts5StorageLoadTotals(p, 0);
202252    if( rc==SQLITE_OK ){
202253      *pnToken = 0;
202254      if( iCol<0 ){
202255        int i;
202256        for(i=0; i<p->pConfig->nCol; i++){
202257          *pnToken += p->aTotalSize[i];
202258        }
202259      }else if( iCol<p->pConfig->nCol ){
202260        *pnToken = p->aTotalSize[iCol];
202261      }else{
202262        rc = SQLITE_RANGE;
202263      }
202264    }
202265    return rc;
202266  }
202267  
202268  static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
202269    int rc = fts5StorageLoadTotals(p, 0);
202270    if( rc==SQLITE_OK ){
202271      *pnRow = p->nTotalRow;
202272    }
202273    return rc;
202274  }
202275  
202276  /*
202277  ** Flush any data currently held in-memory to disk.
202278  */
202279  static int sqlite3Fts5StorageSync(Fts5Storage *p){
202280    int rc = SQLITE_OK;
202281    i64 iLastRowid = sqlite3_last_insert_rowid(p->pConfig->db);
202282    if( p->bTotalsValid ){
202283      rc = fts5StorageSaveTotals(p);
202284      p->bTotalsValid = 0;
202285    }
202286    if( rc==SQLITE_OK ){
202287      rc = sqlite3Fts5IndexSync(p->pIndex);
202288    }
202289    sqlite3_set_last_insert_rowid(p->pConfig->db, iLastRowid);
202290    return rc;
202291  }
202292  
202293  static int sqlite3Fts5StorageRollback(Fts5Storage *p){
202294    p->bTotalsValid = 0;
202295    return sqlite3Fts5IndexRollback(p->pIndex);
202296  }
202297  
202298  static int sqlite3Fts5StorageConfigValue(
202299    Fts5Storage *p, 
202300    const char *z,
202301    sqlite3_value *pVal,
202302    int iVal
202303  ){
202304    sqlite3_stmt *pReplace = 0;
202305    int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
202306    if( rc==SQLITE_OK ){
202307      sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
202308      if( pVal ){
202309        sqlite3_bind_value(pReplace, 2, pVal);
202310      }else{
202311        sqlite3_bind_int(pReplace, 2, iVal);
202312      }
202313      sqlite3_step(pReplace);
202314      rc = sqlite3_reset(pReplace);
202315    }
202316    if( rc==SQLITE_OK && pVal ){
202317      int iNew = p->pConfig->iCookie + 1;
202318      rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
202319      if( rc==SQLITE_OK ){
202320        p->pConfig->iCookie = iNew;
202321      }
202322    }
202323    return rc;
202324  }
202325  
202326  /*
202327  ** 2014 May 31
202328  **
202329  ** The author disclaims copyright to this source code.  In place of
202330  ** a legal notice, here is a blessing:
202331  **
202332  **    May you do good and not evil.
202333  **    May you find forgiveness for yourself and forgive others.
202334  **    May you share freely, never taking more than you give.
202335  **
202336  ******************************************************************************
202337  */
202338  
202339  
202340  /* #include "fts5Int.h" */
202341  
202342  /**************************************************************************
202343  ** Start of ascii tokenizer implementation.
202344  */
202345  
202346  /*
202347  ** For tokenizers with no "unicode" modifier, the set of token characters
202348  ** is the same as the set of ASCII range alphanumeric characters. 
202349  */
202350  static unsigned char aAsciiTokenChar[128] = {
202351    0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00..0x0F */
202352    0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x10..0x1F */
202353    0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20..0x2F */
202354    1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30..0x3F */
202355    0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40..0x4F */
202356    1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x50..0x5F */
202357    0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60..0x6F */
202358    1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x70..0x7F */
202359  };
202360  
202361  typedef struct AsciiTokenizer AsciiTokenizer;
202362  struct AsciiTokenizer {
202363    unsigned char aTokenChar[128];
202364  };
202365  
202366  static void fts5AsciiAddExceptions(
202367    AsciiTokenizer *p, 
202368    const char *zArg, 
202369    int bTokenChars
202370  ){
202371    int i;
202372    for(i=0; zArg[i]; i++){
202373      if( (zArg[i] & 0x80)==0 ){
202374        p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
202375      }
202376    }
202377  }
202378  
202379  /*
202380  ** Delete a "ascii" tokenizer.
202381  */
202382  static void fts5AsciiDelete(Fts5Tokenizer *p){
202383    sqlite3_free(p);
202384  }
202385  
202386  /*
202387  ** Create an "ascii" tokenizer.
202388  */
202389  static int fts5AsciiCreate(
202390    void *pUnused, 
202391    const char **azArg, int nArg,
202392    Fts5Tokenizer **ppOut
202393  ){
202394    int rc = SQLITE_OK;
202395    AsciiTokenizer *p = 0;
202396    UNUSED_PARAM(pUnused);
202397    if( nArg%2 ){
202398      rc = SQLITE_ERROR;
202399    }else{
202400      p = sqlite3_malloc(sizeof(AsciiTokenizer));
202401      if( p==0 ){
202402        rc = SQLITE_NOMEM;
202403      }else{
202404        int i;
202405        memset(p, 0, sizeof(AsciiTokenizer));
202406        memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
202407        for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
202408          const char *zArg = azArg[i+1];
202409          if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
202410            fts5AsciiAddExceptions(p, zArg, 1);
202411          }else
202412          if( 0==sqlite3_stricmp(azArg[i], "separators") ){
202413            fts5AsciiAddExceptions(p, zArg, 0);
202414          }else{
202415            rc = SQLITE_ERROR;
202416          }
202417        }
202418        if( rc!=SQLITE_OK ){
202419          fts5AsciiDelete((Fts5Tokenizer*)p);
202420          p = 0;
202421        }
202422      }
202423    }
202424  
202425    *ppOut = (Fts5Tokenizer*)p;
202426    return rc;
202427  }
202428  
202429  
202430  static void asciiFold(char *aOut, const char *aIn, int nByte){
202431    int i;
202432    for(i=0; i<nByte; i++){
202433      char c = aIn[i];
202434      if( c>='A' && c<='Z' ) c += 32;
202435      aOut[i] = c;
202436    }
202437  }
202438  
202439  /*
202440  ** Tokenize some text using the ascii tokenizer.
202441  */
202442  static int fts5AsciiTokenize(
202443    Fts5Tokenizer *pTokenizer,
202444    void *pCtx,
202445    int iUnused,
202446    const char *pText, int nText,
202447    int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
202448  ){
202449    AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
202450    int rc = SQLITE_OK;
202451    int ie;
202452    int is = 0;
202453  
202454    char aFold[64];
202455    int nFold = sizeof(aFold);
202456    char *pFold = aFold;
202457    unsigned char *a = p->aTokenChar;
202458  
202459    UNUSED_PARAM(iUnused);
202460  
202461    while( is<nText && rc==SQLITE_OK ){
202462      int nByte;
202463  
202464      /* Skip any leading divider characters. */
202465      while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
202466        is++;
202467      }
202468      if( is==nText ) break;
202469  
202470      /* Count the token characters */
202471      ie = is+1;
202472      while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
202473        ie++;
202474      }
202475  
202476      /* Fold to lower case */
202477      nByte = ie-is;
202478      if( nByte>nFold ){
202479        if( pFold!=aFold ) sqlite3_free(pFold);
202480        pFold = sqlite3_malloc(nByte*2);
202481        if( pFold==0 ){
202482          rc = SQLITE_NOMEM;
202483          break;
202484        }
202485        nFold = nByte*2;
202486      }
202487      asciiFold(pFold, &pText[is], nByte);
202488  
202489      /* Invoke the token callback */
202490      rc = xToken(pCtx, 0, pFold, nByte, is, ie);
202491      is = ie+1;
202492    }
202493    
202494    if( pFold!=aFold ) sqlite3_free(pFold);
202495    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
202496    return rc;
202497  }
202498  
202499  /**************************************************************************
202500  ** Start of unicode61 tokenizer implementation.
202501  */
202502  
202503  
202504  /*
202505  ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
202506  ** from the sqlite3 source file utf.c. If this file is compiled as part
202507  ** of the amalgamation, they are not required.
202508  */
202509  #ifndef SQLITE_AMALGAMATION
202510  
202511  static const unsigned char sqlite3Utf8Trans1[] = {
202512    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
202513    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
202514    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
202515    0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
202516    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
202517    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
202518    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
202519    0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
202520  };
202521  
202522  #define READ_UTF8(zIn, zTerm, c)                           \
202523    c = *(zIn++);                                            \
202524    if( c>=0xc0 ){                                           \
202525      c = sqlite3Utf8Trans1[c-0xc0];                         \
202526      while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
202527        c = (c<<6) + (0x3f & *(zIn++));                      \
202528      }                                                      \
202529      if( c<0x80                                             \
202530          || (c&0xFFFFF800)==0xD800                          \
202531          || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
202532    }
202533  
202534  
202535  #define WRITE_UTF8(zOut, c) {                          \
202536    if( c<0x00080 ){                                     \
202537      *zOut++ = (unsigned char)(c&0xFF);                 \
202538    }                                                    \
202539    else if( c<0x00800 ){                                \
202540      *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F);     \
202541      *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
202542    }                                                    \
202543    else if( c<0x10000 ){                                \
202544      *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F);    \
202545      *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
202546      *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
202547    }else{                                               \
202548      *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07);  \
202549      *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F);  \
202550      *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
202551      *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
202552    }                                                    \
202553  }
202554  
202555  #endif /* ifndef SQLITE_AMALGAMATION */
202556  
202557  typedef struct Unicode61Tokenizer Unicode61Tokenizer;
202558  struct Unicode61Tokenizer {
202559    unsigned char aTokenChar[128];  /* ASCII range token characters */
202560    char *aFold;                    /* Buffer to fold text into */
202561    int nFold;                      /* Size of aFold[] in bytes */
202562    int bRemoveDiacritic;           /* True if remove_diacritics=1 is set */
202563    int nException;
202564    int *aiException;
202565  };
202566  
202567  static int fts5UnicodeAddExceptions(
202568    Unicode61Tokenizer *p,          /* Tokenizer object */
202569    const char *z,                  /* Characters to treat as exceptions */
202570    int bTokenChars                 /* 1 for 'tokenchars', 0 for 'separators' */
202571  ){
202572    int rc = SQLITE_OK;
202573    int n = (int)strlen(z);
202574    int *aNew;
202575  
202576    if( n>0 ){
202577      aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
202578      if( aNew ){
202579        int nNew = p->nException;
202580        const unsigned char *zCsr = (const unsigned char*)z;
202581        const unsigned char *zTerm = (const unsigned char*)&z[n];
202582        while( zCsr<zTerm ){
202583          int iCode;
202584          int bToken;
202585          READ_UTF8(zCsr, zTerm, iCode);
202586          if( iCode<128 ){
202587            p->aTokenChar[iCode] = (unsigned char)bTokenChars;
202588          }else{
202589            bToken = sqlite3Fts5UnicodeIsalnum(iCode);
202590            assert( (bToken==0 || bToken==1) ); 
202591            assert( (bTokenChars==0 || bTokenChars==1) );
202592            if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
202593              int i;
202594              for(i=0; i<nNew; i++){
202595                if( aNew[i]>iCode ) break;
202596              }
202597              memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
202598              aNew[i] = iCode;
202599              nNew++;
202600            }
202601          }
202602        }
202603        p->aiException = aNew;
202604        p->nException = nNew;
202605      }else{
202606        rc = SQLITE_NOMEM;
202607      }
202608    }
202609  
202610    return rc;
202611  }
202612  
202613  /*
202614  ** Return true if the p->aiException[] array contains the value iCode.
202615  */
202616  static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
202617    if( p->nException>0 ){
202618      int *a = p->aiException;
202619      int iLo = 0;
202620      int iHi = p->nException-1;
202621  
202622      while( iHi>=iLo ){
202623        int iTest = (iHi + iLo) / 2;
202624        if( iCode==a[iTest] ){
202625          return 1;
202626        }else if( iCode>a[iTest] ){
202627          iLo = iTest+1;
202628        }else{
202629          iHi = iTest-1;
202630        }
202631      }
202632    }
202633  
202634    return 0;
202635  }
202636  
202637  /*
202638  ** Delete a "unicode61" tokenizer.
202639  */
202640  static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
202641    if( pTok ){
202642      Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
202643      sqlite3_free(p->aiException);
202644      sqlite3_free(p->aFold);
202645      sqlite3_free(p);
202646    }
202647    return;
202648  }
202649  
202650  /*
202651  ** Create a "unicode61" tokenizer.
202652  */
202653  static int fts5UnicodeCreate(
202654    void *pUnused, 
202655    const char **azArg, int nArg,
202656    Fts5Tokenizer **ppOut
202657  ){
202658    int rc = SQLITE_OK;             /* Return code */
202659    Unicode61Tokenizer *p = 0;      /* New tokenizer object */ 
202660  
202661    UNUSED_PARAM(pUnused);
202662  
202663    if( nArg%2 ){
202664      rc = SQLITE_ERROR;
202665    }else{
202666      p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
202667      if( p ){
202668        int i;
202669        memset(p, 0, sizeof(Unicode61Tokenizer));
202670        memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
202671        p->bRemoveDiacritic = 1;
202672        p->nFold = 64;
202673        p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
202674        if( p->aFold==0 ){
202675          rc = SQLITE_NOMEM;
202676        }
202677        for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
202678          const char *zArg = azArg[i+1];
202679          if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
202680            if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
202681              rc = SQLITE_ERROR;
202682            }
202683            p->bRemoveDiacritic = (zArg[0]=='1');
202684          }else
202685          if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
202686            rc = fts5UnicodeAddExceptions(p, zArg, 1);
202687          }else
202688          if( 0==sqlite3_stricmp(azArg[i], "separators") ){
202689            rc = fts5UnicodeAddExceptions(p, zArg, 0);
202690          }else{
202691            rc = SQLITE_ERROR;
202692          }
202693        }
202694      }else{
202695        rc = SQLITE_NOMEM;
202696      }
202697      if( rc!=SQLITE_OK ){
202698        fts5UnicodeDelete((Fts5Tokenizer*)p);
202699        p = 0;
202700      }
202701      *ppOut = (Fts5Tokenizer*)p;
202702    }
202703    return rc;
202704  }
202705  
202706  /*
202707  ** Return true if, for the purposes of tokenizing with the tokenizer
202708  ** passed as the first argument, codepoint iCode is considered a token 
202709  ** character (not a separator).
202710  */
202711  static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
202712    assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
202713    return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode);
202714  }
202715  
202716  static int fts5UnicodeTokenize(
202717    Fts5Tokenizer *pTokenizer,
202718    void *pCtx,
202719    int iUnused,
202720    const char *pText, int nText,
202721    int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
202722  ){
202723    Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
202724    int rc = SQLITE_OK;
202725    unsigned char *a = p->aTokenChar;
202726  
202727    unsigned char *zTerm = (unsigned char*)&pText[nText];
202728    unsigned char *zCsr = (unsigned char *)pText;
202729  
202730    /* Output buffer */
202731    char *aFold = p->aFold;
202732    int nFold = p->nFold;
202733    const char *pEnd = &aFold[nFold-6];
202734  
202735    UNUSED_PARAM(iUnused);
202736  
202737    /* Each iteration of this loop gobbles up a contiguous run of separators,
202738    ** then the next token.  */
202739    while( rc==SQLITE_OK ){
202740      int iCode;                    /* non-ASCII codepoint read from input */
202741      char *zOut = aFold;
202742      int is;
202743      int ie;
202744  
202745      /* Skip any separator characters. */
202746      while( 1 ){
202747        if( zCsr>=zTerm ) goto tokenize_done;
202748        if( *zCsr & 0x80 ) {
202749          /* A character outside of the ascii range. Skip past it if it is
202750          ** a separator character. Or break out of the loop if it is not. */
202751          is = zCsr - (unsigned char*)pText;
202752          READ_UTF8(zCsr, zTerm, iCode);
202753          if( fts5UnicodeIsAlnum(p, iCode) ){
202754            goto non_ascii_tokenchar;
202755          }
202756        }else{
202757          if( a[*zCsr] ){
202758            is = zCsr - (unsigned char*)pText;
202759            goto ascii_tokenchar;
202760          }
202761          zCsr++;
202762        }
202763      }
202764  
202765      /* Run through the tokenchars. Fold them into the output buffer along
202766      ** the way.  */
202767      while( zCsr<zTerm ){
202768  
202769        /* Grow the output buffer so that there is sufficient space to fit the
202770        ** largest possible utf-8 character.  */
202771        if( zOut>pEnd ){
202772          aFold = sqlite3_malloc(nFold*2);
202773          if( aFold==0 ){
202774            rc = SQLITE_NOMEM;
202775            goto tokenize_done;
202776          }
202777          zOut = &aFold[zOut - p->aFold];
202778          memcpy(aFold, p->aFold, nFold);
202779          sqlite3_free(p->aFold);
202780          p->aFold = aFold;
202781          p->nFold = nFold = nFold*2;
202782          pEnd = &aFold[nFold-6];
202783        }
202784  
202785        if( *zCsr & 0x80 ){
202786          /* An non-ascii-range character. Fold it into the output buffer if
202787          ** it is a token character, or break out of the loop if it is not. */
202788          READ_UTF8(zCsr, zTerm, iCode);
202789          if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
202790   non_ascii_tokenchar:
202791            iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
202792            if( iCode ) WRITE_UTF8(zOut, iCode);
202793          }else{
202794            break;
202795          }
202796        }else if( a[*zCsr]==0 ){
202797          /* An ascii-range separator character. End of token. */
202798          break; 
202799        }else{
202800   ascii_tokenchar:
202801          if( *zCsr>='A' && *zCsr<='Z' ){
202802            *zOut++ = *zCsr + 32;
202803          }else{
202804            *zOut++ = *zCsr;
202805          }
202806          zCsr++;
202807        }
202808        ie = zCsr - (unsigned char*)pText;
202809      }
202810  
202811      /* Invoke the token callback */
202812      rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie); 
202813    }
202814    
202815   tokenize_done:
202816    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
202817    return rc;
202818  }
202819  
202820  /**************************************************************************
202821  ** Start of porter stemmer implementation.
202822  */
202823  
202824  /* Any tokens larger than this (in bytes) are passed through without
202825  ** stemming. */
202826  #define FTS5_PORTER_MAX_TOKEN 64
202827  
202828  typedef struct PorterTokenizer PorterTokenizer;
202829  struct PorterTokenizer {
202830    fts5_tokenizer tokenizer;       /* Parent tokenizer module */
202831    Fts5Tokenizer *pTokenizer;      /* Parent tokenizer instance */
202832    char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
202833  };
202834  
202835  /*
202836  ** Delete a "porter" tokenizer.
202837  */
202838  static void fts5PorterDelete(Fts5Tokenizer *pTok){
202839    if( pTok ){
202840      PorterTokenizer *p = (PorterTokenizer*)pTok;
202841      if( p->pTokenizer ){
202842        p->tokenizer.xDelete(p->pTokenizer);
202843      }
202844      sqlite3_free(p);
202845    }
202846  }
202847  
202848  /*
202849  ** Create a "porter" tokenizer.
202850  */
202851  static int fts5PorterCreate(
202852    void *pCtx, 
202853    const char **azArg, int nArg,
202854    Fts5Tokenizer **ppOut
202855  ){
202856    fts5_api *pApi = (fts5_api*)pCtx;
202857    int rc = SQLITE_OK;
202858    PorterTokenizer *pRet;
202859    void *pUserdata = 0;
202860    const char *zBase = "unicode61";
202861  
202862    if( nArg>0 ){
202863      zBase = azArg[0];
202864    }
202865  
202866    pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
202867    if( pRet ){
202868      memset(pRet, 0, sizeof(PorterTokenizer));
202869      rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
202870    }else{
202871      rc = SQLITE_NOMEM;
202872    }
202873    if( rc==SQLITE_OK ){
202874      int nArg2 = (nArg>0 ? nArg-1 : 0);
202875      const char **azArg2 = (nArg2 ? &azArg[1] : 0);
202876      rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
202877    }
202878  
202879    if( rc!=SQLITE_OK ){
202880      fts5PorterDelete((Fts5Tokenizer*)pRet);
202881      pRet = 0;
202882    }
202883    *ppOut = (Fts5Tokenizer*)pRet;
202884    return rc;
202885  }
202886  
202887  typedef struct PorterContext PorterContext;
202888  struct PorterContext {
202889    void *pCtx;
202890    int (*xToken)(void*, int, const char*, int, int, int);
202891    char *aBuf;
202892  };
202893  
202894  typedef struct PorterRule PorterRule;
202895  struct PorterRule {
202896    const char *zSuffix;
202897    int nSuffix;
202898    int (*xCond)(char *zStem, int nStem);
202899    const char *zOutput;
202900    int nOutput;
202901  };
202902  
202903  #if 0
202904  static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
202905    int ret = -1;
202906    int nBuf = *pnBuf;
202907    PorterRule *p;
202908  
202909    for(p=aRule; p->zSuffix; p++){
202910      assert( strlen(p->zSuffix)==p->nSuffix );
202911      assert( strlen(p->zOutput)==p->nOutput );
202912      if( nBuf<p->nSuffix ) continue;
202913      if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
202914    }
202915  
202916    if( p->zSuffix ){
202917      int nStem = nBuf - p->nSuffix;
202918      if( p->xCond==0 || p->xCond(aBuf, nStem) ){
202919        memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
202920        *pnBuf = nStem + p->nOutput;
202921        ret = p - aRule;
202922      }
202923    }
202924  
202925    return ret;
202926  }
202927  #endif
202928  
202929  static int fts5PorterIsVowel(char c, int bYIsVowel){
202930    return (
202931        c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
202932    );
202933  }
202934  
202935  static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
202936    int i;
202937    int bCons = bPrevCons;
202938  
202939    /* Scan for a vowel */
202940    for(i=0; i<nStem; i++){
202941      if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
202942    }
202943  
202944    /* Scan for a consonent */
202945    for(i++; i<nStem; i++){
202946      if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
202947    }
202948    return 0;
202949  }
202950  
202951  /* porter rule condition: (m > 0) */
202952  static int fts5Porter_MGt0(char *zStem, int nStem){
202953    return !!fts5PorterGobbleVC(zStem, nStem, 0);
202954  }
202955  
202956  /* porter rule condition: (m > 1) */
202957  static int fts5Porter_MGt1(char *zStem, int nStem){
202958    int n;
202959    n = fts5PorterGobbleVC(zStem, nStem, 0);
202960    if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
202961      return 1;
202962    }
202963    return 0;
202964  }
202965  
202966  /* porter rule condition: (m = 1) */
202967  static int fts5Porter_MEq1(char *zStem, int nStem){
202968    int n;
202969    n = fts5PorterGobbleVC(zStem, nStem, 0);
202970    if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
202971      return 1;
202972    }
202973    return 0;
202974  }
202975  
202976  /* porter rule condition: (*o) */
202977  static int fts5Porter_Ostar(char *zStem, int nStem){
202978    if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
202979      return 0;
202980    }else{
202981      int i;
202982      int mask = 0;
202983      int bCons = 0;
202984      for(i=0; i<nStem; i++){
202985        bCons = !fts5PorterIsVowel(zStem[i], bCons);
202986        assert( bCons==0 || bCons==1 );
202987        mask = (mask << 1) + bCons;
202988      }
202989      return ((mask & 0x0007)==0x0005);
202990    }
202991  }
202992  
202993  /* porter rule condition: (m > 1 and (*S or *T)) */
202994  static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
202995    assert( nStem>0 );
202996    return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t') 
202997        && fts5Porter_MGt1(zStem, nStem);
202998  }
202999  
203000  /* porter rule condition: (*v*) */
203001  static int fts5Porter_Vowel(char *zStem, int nStem){
203002    int i;
203003    for(i=0; i<nStem; i++){
203004      if( fts5PorterIsVowel(zStem[i], i>0) ){
203005        return 1;
203006      }
203007    }
203008    return 0;
203009  }
203010  
203011  
203012  /**************************************************************************
203013  ***************************************************************************
203014  ** GENERATED CODE STARTS HERE (mkportersteps.tcl)
203015  */
203016  
203017  static int fts5PorterStep4(char *aBuf, int *pnBuf){
203018    int ret = 0;
203019    int nBuf = *pnBuf;
203020    switch( aBuf[nBuf-2] ){
203021      
203022      case 'a': 
203023        if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
203024          if( fts5Porter_MGt1(aBuf, nBuf-2) ){
203025            *pnBuf = nBuf - 2;
203026          }
203027        }
203028        break;
203029    
203030      case 'c': 
203031        if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
203032          if( fts5Porter_MGt1(aBuf, nBuf-4) ){
203033            *pnBuf = nBuf - 4;
203034          }
203035        }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
203036          if( fts5Porter_MGt1(aBuf, nBuf-4) ){
203037            *pnBuf = nBuf - 4;
203038          }
203039        }
203040        break;
203041    
203042      case 'e': 
203043        if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
203044          if( fts5Porter_MGt1(aBuf, nBuf-2) ){
203045            *pnBuf = nBuf - 2;
203046          }
203047        }
203048        break;
203049    
203050      case 'i': 
203051        if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
203052          if( fts5Porter_MGt1(aBuf, nBuf-2) ){
203053            *pnBuf = nBuf - 2;
203054          }
203055        }
203056        break;
203057    
203058      case 'l': 
203059        if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
203060          if( fts5Porter_MGt1(aBuf, nBuf-4) ){
203061            *pnBuf = nBuf - 4;
203062          }
203063        }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
203064          if( fts5Porter_MGt1(aBuf, nBuf-4) ){
203065            *pnBuf = nBuf - 4;
203066          }
203067        }
203068        break;
203069    
203070      case 'n': 
203071        if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
203072          if( fts5Porter_MGt1(aBuf, nBuf-3) ){
203073            *pnBuf = nBuf - 3;
203074          }
203075        }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
203076          if( fts5Porter_MGt1(aBuf, nBuf-5) ){
203077            *pnBuf = nBuf - 5;
203078          }
203079        }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
203080          if( fts5Porter_MGt1(aBuf, nBuf-4) ){
203081            *pnBuf = nBuf - 4;
203082          }
203083        }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
203084          if( fts5Porter_MGt1(aBuf, nBuf-3) ){
203085            *pnBuf = nBuf - 3;
203086          }
203087        }
203088        break;
203089    
203090      case 'o': 
203091        if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
203092          if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
203093            *pnBuf = nBuf - 3;
203094          }
203095        }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
203096          if( fts5Porter_MGt1(aBuf, nBuf-2) ){
203097            *pnBuf = nBuf - 2;
203098          }
203099        }
203100        break;
203101    
203102      case 's': 
203103        if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
203104          if( fts5Porter_MGt1(aBuf, nBuf-3) ){
203105            *pnBuf = nBuf - 3;
203106          }
203107        }
203108        break;
203109    
203110      case 't': 
203111        if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
203112          if( fts5Porter_MGt1(aBuf, nBuf-3) ){
203113            *pnBuf = nBuf - 3;
203114          }
203115        }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
203116          if( fts5Porter_MGt1(aBuf, nBuf-3) ){
203117            *pnBuf = nBuf - 3;
203118          }
203119        }
203120        break;
203121    
203122      case 'u': 
203123        if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
203124          if( fts5Porter_MGt1(aBuf, nBuf-3) ){
203125            *pnBuf = nBuf - 3;
203126          }
203127        }
203128        break;
203129    
203130      case 'v': 
203131        if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
203132          if( fts5Porter_MGt1(aBuf, nBuf-3) ){
203133            *pnBuf = nBuf - 3;
203134          }
203135        }
203136        break;
203137    
203138      case 'z': 
203139        if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
203140          if( fts5Porter_MGt1(aBuf, nBuf-3) ){
203141            *pnBuf = nBuf - 3;
203142          }
203143        }
203144        break;
203145    
203146    }
203147    return ret;
203148  }
203149    
203150  
203151  static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
203152    int ret = 0;
203153    int nBuf = *pnBuf;
203154    switch( aBuf[nBuf-2] ){
203155      
203156      case 'a': 
203157        if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
203158          memcpy(&aBuf[nBuf-2], "ate", 3);
203159          *pnBuf = nBuf - 2 + 3;
203160          ret = 1;
203161        }
203162        break;
203163    
203164      case 'b': 
203165        if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
203166          memcpy(&aBuf[nBuf-2], "ble", 3);
203167          *pnBuf = nBuf - 2 + 3;
203168          ret = 1;
203169        }
203170        break;
203171    
203172      case 'i': 
203173        if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
203174          memcpy(&aBuf[nBuf-2], "ize", 3);
203175          *pnBuf = nBuf - 2 + 3;
203176          ret = 1;
203177        }
203178        break;
203179    
203180    }
203181    return ret;
203182  }
203183    
203184  
203185  static int fts5PorterStep2(char *aBuf, int *pnBuf){
203186    int ret = 0;
203187    int nBuf = *pnBuf;
203188    switch( aBuf[nBuf-2] ){
203189      
203190      case 'a': 
203191        if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
203192          if( fts5Porter_MGt0(aBuf, nBuf-7) ){
203193            memcpy(&aBuf[nBuf-7], "ate", 3);
203194            *pnBuf = nBuf - 7 + 3;
203195          }
203196        }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
203197          if( fts5Porter_MGt0(aBuf, nBuf-6) ){
203198            memcpy(&aBuf[nBuf-6], "tion", 4);
203199            *pnBuf = nBuf - 6 + 4;
203200          }
203201        }
203202        break;
203203    
203204      case 'c': 
203205        if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
203206          if( fts5Porter_MGt0(aBuf, nBuf-4) ){
203207            memcpy(&aBuf[nBuf-4], "ence", 4);
203208            *pnBuf = nBuf - 4 + 4;
203209          }
203210        }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
203211          if( fts5Porter_MGt0(aBuf, nBuf-4) ){
203212            memcpy(&aBuf[nBuf-4], "ance", 4);
203213            *pnBuf = nBuf - 4 + 4;
203214          }
203215        }
203216        break;
203217    
203218      case 'e': 
203219        if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
203220          if( fts5Porter_MGt0(aBuf, nBuf-4) ){
203221            memcpy(&aBuf[nBuf-4], "ize", 3);
203222            *pnBuf = nBuf - 4 + 3;
203223          }
203224        }
203225        break;
203226    
203227      case 'g': 
203228        if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
203229          if( fts5Porter_MGt0(aBuf, nBuf-4) ){
203230            memcpy(&aBuf[nBuf-4], "log", 3);
203231            *pnBuf = nBuf - 4 + 3;
203232          }
203233        }
203234        break;
203235    
203236      case 'l': 
203237        if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
203238          if( fts5Porter_MGt0(aBuf, nBuf-3) ){
203239            memcpy(&aBuf[nBuf-3], "ble", 3);
203240            *pnBuf = nBuf - 3 + 3;
203241          }
203242        }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
203243          if( fts5Porter_MGt0(aBuf, nBuf-4) ){
203244            memcpy(&aBuf[nBuf-4], "al", 2);
203245            *pnBuf = nBuf - 4 + 2;
203246          }
203247        }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
203248          if( fts5Porter_MGt0(aBuf, nBuf-5) ){
203249            memcpy(&aBuf[nBuf-5], "ent", 3);
203250            *pnBuf = nBuf - 5 + 3;
203251          }
203252        }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
203253          if( fts5Porter_MGt0(aBuf, nBuf-3) ){
203254            memcpy(&aBuf[nBuf-3], "e", 1);
203255            *pnBuf = nBuf - 3 + 1;
203256          }
203257        }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
203258          if( fts5Porter_MGt0(aBuf, nBuf-5) ){
203259            memcpy(&aBuf[nBuf-5], "ous", 3);
203260            *pnBuf = nBuf - 5 + 3;
203261          }
203262        }
203263        break;
203264    
203265      case 'o': 
203266        if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
203267          if( fts5Porter_MGt0(aBuf, nBuf-7) ){
203268            memcpy(&aBuf[nBuf-7], "ize", 3);
203269            *pnBuf = nBuf - 7 + 3;
203270          }
203271        }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
203272          if( fts5Porter_MGt0(aBuf, nBuf-5) ){
203273            memcpy(&aBuf[nBuf-5], "ate", 3);
203274            *pnBuf = nBuf - 5 + 3;
203275          }
203276        }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
203277          if( fts5Porter_MGt0(aBuf, nBuf-4) ){
203278            memcpy(&aBuf[nBuf-4], "ate", 3);
203279            *pnBuf = nBuf - 4 + 3;
203280          }
203281        }
203282        break;
203283    
203284      case 's': 
203285        if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
203286          if( fts5Porter_MGt0(aBuf, nBuf-5) ){
203287            memcpy(&aBuf[nBuf-5], "al", 2);
203288            *pnBuf = nBuf - 5 + 2;
203289          }
203290        }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
203291          if( fts5Porter_MGt0(aBuf, nBuf-7) ){
203292            memcpy(&aBuf[nBuf-7], "ive", 3);
203293            *pnBuf = nBuf - 7 + 3;
203294          }
203295        }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
203296          if( fts5Porter_MGt0(aBuf, nBuf-7) ){
203297            memcpy(&aBuf[nBuf-7], "ful", 3);
203298            *pnBuf = nBuf - 7 + 3;
203299          }
203300        }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
203301          if( fts5Porter_MGt0(aBuf, nBuf-7) ){
203302            memcpy(&aBuf[nBuf-7], "ous", 3);
203303            *pnBuf = nBuf - 7 + 3;
203304          }
203305        }
203306        break;
203307    
203308      case 't': 
203309        if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
203310          if( fts5Porter_MGt0(aBuf, nBuf-5) ){
203311            memcpy(&aBuf[nBuf-5], "al", 2);
203312            *pnBuf = nBuf - 5 + 2;
203313          }
203314        }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
203315          if( fts5Porter_MGt0(aBuf, nBuf-5) ){
203316            memcpy(&aBuf[nBuf-5], "ive", 3);
203317            *pnBuf = nBuf - 5 + 3;
203318          }
203319        }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
203320          if( fts5Porter_MGt0(aBuf, nBuf-6) ){
203321            memcpy(&aBuf[nBuf-6], "ble", 3);
203322            *pnBuf = nBuf - 6 + 3;
203323          }
203324        }
203325        break;
203326    
203327    }
203328    return ret;
203329  }
203330    
203331  
203332  static int fts5PorterStep3(char *aBuf, int *pnBuf){
203333    int ret = 0;
203334    int nBuf = *pnBuf;
203335    switch( aBuf[nBuf-2] ){
203336      
203337      case 'a': 
203338        if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
203339          if( fts5Porter_MGt0(aBuf, nBuf-4) ){
203340            memcpy(&aBuf[nBuf-4], "ic", 2);
203341            *pnBuf = nBuf - 4 + 2;
203342          }
203343        }
203344        break;
203345    
203346      case 's': 
203347        if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
203348          if( fts5Porter_MGt0(aBuf, nBuf-4) ){
203349            *pnBuf = nBuf - 4;
203350          }
203351        }
203352        break;
203353    
203354      case 't': 
203355        if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
203356          if( fts5Porter_MGt0(aBuf, nBuf-5) ){
203357            memcpy(&aBuf[nBuf-5], "ic", 2);
203358            *pnBuf = nBuf - 5 + 2;
203359          }
203360        }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
203361          if( fts5Porter_MGt0(aBuf, nBuf-5) ){
203362            memcpy(&aBuf[nBuf-5], "ic", 2);
203363            *pnBuf = nBuf - 5 + 2;
203364          }
203365        }
203366        break;
203367    
203368      case 'u': 
203369        if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
203370          if( fts5Porter_MGt0(aBuf, nBuf-3) ){
203371            *pnBuf = nBuf - 3;
203372          }
203373        }
203374        break;
203375    
203376      case 'v': 
203377        if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
203378          if( fts5Porter_MGt0(aBuf, nBuf-5) ){
203379            *pnBuf = nBuf - 5;
203380          }
203381        }
203382        break;
203383    
203384      case 'z': 
203385        if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
203386          if( fts5Porter_MGt0(aBuf, nBuf-5) ){
203387            memcpy(&aBuf[nBuf-5], "al", 2);
203388            *pnBuf = nBuf - 5 + 2;
203389          }
203390        }
203391        break;
203392    
203393    }
203394    return ret;
203395  }
203396    
203397  
203398  static int fts5PorterStep1B(char *aBuf, int *pnBuf){
203399    int ret = 0;
203400    int nBuf = *pnBuf;
203401    switch( aBuf[nBuf-2] ){
203402      
203403      case 'e': 
203404        if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
203405          if( fts5Porter_MGt0(aBuf, nBuf-3) ){
203406            memcpy(&aBuf[nBuf-3], "ee", 2);
203407            *pnBuf = nBuf - 3 + 2;
203408          }
203409        }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
203410          if( fts5Porter_Vowel(aBuf, nBuf-2) ){
203411            *pnBuf = nBuf - 2;
203412            ret = 1;
203413          }
203414        }
203415        break;
203416    
203417      case 'n': 
203418        if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
203419          if( fts5Porter_Vowel(aBuf, nBuf-3) ){
203420            *pnBuf = nBuf - 3;
203421            ret = 1;
203422          }
203423        }
203424        break;
203425    
203426    }
203427    return ret;
203428  }
203429    
203430  /* 
203431  ** GENERATED CODE ENDS HERE (mkportersteps.tcl)
203432  ***************************************************************************
203433  **************************************************************************/
203434  
203435  static void fts5PorterStep1A(char *aBuf, int *pnBuf){
203436    int nBuf = *pnBuf;
203437    if( aBuf[nBuf-1]=='s' ){
203438      if( aBuf[nBuf-2]=='e' ){
203439        if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s') 
203440         || (nBuf>3 && aBuf[nBuf-3]=='i' )
203441        ){
203442          *pnBuf = nBuf-2;
203443        }else{
203444          *pnBuf = nBuf-1;
203445        }
203446      }
203447      else if( aBuf[nBuf-2]!='s' ){
203448        *pnBuf = nBuf-1;
203449      }
203450    }
203451  }
203452  
203453  static int fts5PorterCb(
203454    void *pCtx, 
203455    int tflags,
203456    const char *pToken, 
203457    int nToken, 
203458    int iStart, 
203459    int iEnd
203460  ){
203461    PorterContext *p = (PorterContext*)pCtx;
203462  
203463    char *aBuf;
203464    int nBuf;
203465  
203466    if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
203467    aBuf = p->aBuf;
203468    nBuf = nToken;
203469    memcpy(aBuf, pToken, nBuf);
203470  
203471    /* Step 1. */
203472    fts5PorterStep1A(aBuf, &nBuf);
203473    if( fts5PorterStep1B(aBuf, &nBuf) ){
203474      if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
203475        char c = aBuf[nBuf-1];
203476        if( fts5PorterIsVowel(c, 0)==0 
203477         && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2] 
203478        ){
203479          nBuf--;
203480        }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
203481          aBuf[nBuf++] = 'e';
203482        }
203483      }
203484    }
203485  
203486    /* Step 1C. */
203487    if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
203488      aBuf[nBuf-1] = 'i';
203489    }
203490  
203491    /* Steps 2 through 4. */
203492    fts5PorterStep2(aBuf, &nBuf);
203493    fts5PorterStep3(aBuf, &nBuf);
203494    fts5PorterStep4(aBuf, &nBuf);
203495  
203496    /* Step 5a. */
203497    assert( nBuf>0 );
203498    if( aBuf[nBuf-1]=='e' ){
203499      if( fts5Porter_MGt1(aBuf, nBuf-1) 
203500       || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
203501      ){
203502        nBuf--;
203503      }
203504    }
203505  
203506    /* Step 5b. */
203507    if( nBuf>1 && aBuf[nBuf-1]=='l' 
203508     && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1) 
203509    ){
203510      nBuf--;
203511    }
203512  
203513    return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
203514  
203515   pass_through:
203516    return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
203517  }
203518  
203519  /*
203520  ** Tokenize using the porter tokenizer.
203521  */
203522  static int fts5PorterTokenize(
203523    Fts5Tokenizer *pTokenizer,
203524    void *pCtx,
203525    int flags,
203526    const char *pText, int nText,
203527    int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
203528  ){
203529    PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
203530    PorterContext sCtx;
203531    sCtx.xToken = xToken;
203532    sCtx.pCtx = pCtx;
203533    sCtx.aBuf = p->aBuf;
203534    return p->tokenizer.xTokenize(
203535        p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
203536    );
203537  }
203538  
203539  /*
203540  ** Register all built-in tokenizers with FTS5.
203541  */
203542  static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
203543    struct BuiltinTokenizer {
203544      const char *zName;
203545      fts5_tokenizer x;
203546    } aBuiltin[] = {
203547      { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
203548      { "ascii",     {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
203549      { "porter",    {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
203550    };
203551    
203552    int rc = SQLITE_OK;             /* Return code */
203553    int i;                          /* To iterate through builtin functions */
203554  
203555    for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
203556      rc = pApi->xCreateTokenizer(pApi,
203557          aBuiltin[i].zName,
203558          (void*)pApi,
203559          &aBuiltin[i].x,
203560          0
203561      );
203562    }
203563  
203564    return rc;
203565  }
203566  
203567  
203568  
203569  /*
203570  ** 2012 May 25
203571  **
203572  ** The author disclaims copyright to this source code.  In place of
203573  ** a legal notice, here is a blessing:
203574  **
203575  **    May you do good and not evil.
203576  **    May you find forgiveness for yourself and forgive others.
203577  **    May you share freely, never taking more than you give.
203578  **
203579  ******************************************************************************
203580  */
203581  
203582  /*
203583  ** DO NOT EDIT THIS MACHINE GENERATED FILE.
203584  */
203585  
203586  
203587  /* #include <assert.h> */
203588  
203589  /*
203590  ** Return true if the argument corresponds to a unicode codepoint
203591  ** classified as either a letter or a number. Otherwise false.
203592  **
203593  ** The results are undefined if the value passed to this function
203594  ** is less than zero.
203595  */
203596  static int sqlite3Fts5UnicodeIsalnum(int c){
203597    /* Each unsigned integer in the following array corresponds to a contiguous
203598    ** range of unicode codepoints that are not either letters or numbers (i.e.
203599    ** codepoints for which this function should return 0).
203600    **
203601    ** The most significant 22 bits in each 32-bit value contain the first 
203602    ** codepoint in the range. The least significant 10 bits are used to store
203603    ** the size of the range (always at least 1). In other words, the value 
203604    ** ((C<<22) + N) represents a range of N codepoints starting with codepoint 
203605    ** C. It is not possible to represent a range larger than 1023 codepoints 
203606    ** using this format.
203607    */
203608    static const unsigned int aEntry[] = {
203609      0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
203610      0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
203611      0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
203612      0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
203613      0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
203614      0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
203615      0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
203616      0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
203617      0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
203618      0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
203619      0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
203620      0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
203621      0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
203622      0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
203623      0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
203624      0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
203625      0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
203626      0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
203627      0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
203628      0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
203629      0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
203630      0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
203631      0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
203632      0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
203633      0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
203634      0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
203635      0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
203636      0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
203637      0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
203638      0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
203639      0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
203640      0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
203641      0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
203642      0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
203643      0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
203644      0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
203645      0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
203646      0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
203647      0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
203648      0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
203649      0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
203650      0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
203651      0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
203652      0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
203653      0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
203654      0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
203655      0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
203656      0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
203657      0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
203658      0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
203659      0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
203660      0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
203661      0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
203662      0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
203663      0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
203664      0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
203665      0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
203666      0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
203667      0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
203668      0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
203669      0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
203670      0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
203671      0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
203672      0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
203673      0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
203674      0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
203675      0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
203676      0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
203677      0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
203678      0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
203679      0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
203680      0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
203681      0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
203682      0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
203683      0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
203684      0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
203685      0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
203686      0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
203687      0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
203688      0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
203689      0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
203690      0x380400F0,
203691    };
203692    static const unsigned int aAscii[4] = {
203693      0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
203694    };
203695  
203696    if( (unsigned int)c<128 ){
203697      return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
203698    }else if( (unsigned int)c<(1<<22) ){
203699      unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
203700      int iRes = 0;
203701      int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
203702      int iLo = 0;
203703      while( iHi>=iLo ){
203704        int iTest = (iHi + iLo) / 2;
203705        if( key >= aEntry[iTest] ){
203706          iRes = iTest;
203707          iLo = iTest+1;
203708        }else{
203709          iHi = iTest-1;
203710        }
203711      }
203712      assert( aEntry[0]<key );
203713      assert( key>=aEntry[iRes] );
203714      return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
203715    }
203716    return 1;
203717  }
203718  
203719  
203720  /*
203721  ** If the argument is a codepoint corresponding to a lowercase letter
203722  ** in the ASCII range with a diacritic added, return the codepoint
203723  ** of the ASCII letter only. For example, if passed 235 - "LATIN
203724  ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
203725  ** E"). The resuls of passing a codepoint that corresponds to an
203726  ** uppercase letter are undefined.
203727  */
203728  static int fts5_remove_diacritic(int c){
203729    unsigned short aDia[] = {
203730          0,  1797,  1848,  1859,  1891,  1928,  1940,  1995, 
203731       2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286, 
203732       2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732, 
203733       2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336, 
203734       3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928, 
203735       3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234, 
203736       4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504, 
203737       6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529, 
203738      61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726, 
203739      61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122, 
203740      62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536, 
203741      62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730, 
203742      62924, 63050, 63082, 63274, 63390, 
203743    };
203744    char aChar[] = {
203745      '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',  
203746      'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',  
203747      's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',  
203748      'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',  
203749      'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0', 
203750      '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',  
203751      'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',  
203752      'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',  
203753      'e',  'i',  'o',  'u',  'y',  
203754    };
203755  
203756    unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
203757    int iRes = 0;
203758    int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
203759    int iLo = 0;
203760    while( iHi>=iLo ){
203761      int iTest = (iHi + iLo) / 2;
203762      if( key >= aDia[iTest] ){
203763        iRes = iTest;
203764        iLo = iTest+1;
203765      }else{
203766        iHi = iTest-1;
203767      }
203768    }
203769    assert( key>=aDia[iRes] );
203770    return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
203771  }
203772  
203773  
203774  /*
203775  ** Return true if the argument interpreted as a unicode codepoint
203776  ** is a diacritical modifier character.
203777  */
203778  static int sqlite3Fts5UnicodeIsdiacritic(int c){
203779    unsigned int mask0 = 0x08029FDF;
203780    unsigned int mask1 = 0x000361F8;
203781    if( c<768 || c>817 ) return 0;
203782    return (c < 768+32) ?
203783        (mask0 & (1 << (c-768))) :
203784        (mask1 & (1 << (c-768-32)));
203785  }
203786  
203787  
203788  /*
203789  ** Interpret the argument as a unicode codepoint. If the codepoint
203790  ** is an upper case character that has a lower case equivalent,
203791  ** return the codepoint corresponding to the lower case version.
203792  ** Otherwise, return a copy of the argument.
203793  **
203794  ** The results are undefined if the value passed to this function
203795  ** is less than zero.
203796  */
203797  static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
203798    /* Each entry in the following array defines a rule for folding a range
203799    ** of codepoints to lower case. The rule applies to a range of nRange
203800    ** codepoints starting at codepoint iCode.
203801    **
203802    ** If the least significant bit in flags is clear, then the rule applies
203803    ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
203804    ** need to be folded). Or, if it is set, then the rule only applies to
203805    ** every second codepoint in the range, starting with codepoint C.
203806    **
203807    ** The 7 most significant bits in flags are an index into the aiOff[]
203808    ** array. If a specific codepoint C does require folding, then its lower
203809    ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
203810    **
203811    ** The contents of this array are generated by parsing the CaseFolding.txt
203812    ** file distributed as part of the "Unicode Character Database". See
203813    ** http://www.unicode.org for details.
203814    */
203815    static const struct TableEntry {
203816      unsigned short iCode;
203817      unsigned char flags;
203818      unsigned char nRange;
203819    } aEntry[] = {
203820      {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
203821      {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
203822      {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
203823      {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
203824      {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
203825      {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
203826      {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
203827      {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
203828      {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
203829      {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
203830      {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
203831      {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
203832      {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
203833      {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
203834      {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
203835      {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
203836      {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
203837      {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
203838      {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
203839      {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
203840      {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
203841      {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
203842      {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
203843      {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
203844      {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
203845      {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
203846      {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
203847      {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
203848      {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
203849      {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
203850      {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
203851      {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
203852      {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
203853      {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
203854      {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
203855      {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
203856      {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
203857      {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
203858      {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
203859      {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
203860      {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
203861      {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
203862      {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
203863      {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
203864      {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
203865      {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
203866      {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
203867      {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
203868      {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
203869      {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
203870      {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
203871      {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
203872      {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
203873      {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
203874      {65313, 14, 26},       
203875    };
203876    static const unsigned short aiOff[] = {
203877     1,     2,     8,     15,    16,    26,    28,    32,    
203878     37,    38,    40,    48,    63,    64,    69,    71,    
203879     79,    80,    116,   202,   203,   205,   206,   207,   
203880     209,   210,   211,   213,   214,   217,   218,   219,   
203881     775,   7264,  10792, 10795, 23228, 23256, 30204, 54721, 
203882     54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, 
203883     57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, 
203884     65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, 
203885     65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, 
203886     65514, 65521, 65527, 65528, 65529, 
203887    };
203888  
203889    int ret = c;
203890  
203891    assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
203892  
203893    if( c<128 ){
203894      if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
203895    }else if( c<65536 ){
203896      const struct TableEntry *p;
203897      int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
203898      int iLo = 0;
203899      int iRes = -1;
203900  
203901      assert( c>aEntry[0].iCode );
203902      while( iHi>=iLo ){
203903        int iTest = (iHi + iLo) / 2;
203904        int cmp = (c - aEntry[iTest].iCode);
203905        if( cmp>=0 ){
203906          iRes = iTest;
203907          iLo = iTest+1;
203908        }else{
203909          iHi = iTest-1;
203910        }
203911      }
203912  
203913      assert( iRes>=0 && c>=aEntry[iRes].iCode );
203914      p = &aEntry[iRes];
203915      if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
203916        ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
203917        assert( ret>0 );
203918      }
203919  
203920      if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
203921    }
203922    
203923    else if( c>=66560 && c<66600 ){
203924      ret = c + 40;
203925    }
203926  
203927    return ret;
203928  }
203929  
203930  /*
203931  ** 2015 May 30
203932  **
203933  ** The author disclaims copyright to this source code.  In place of
203934  ** a legal notice, here is a blessing:
203935  **
203936  **    May you do good and not evil.
203937  **    May you find forgiveness for yourself and forgive others.
203938  **    May you share freely, never taking more than you give.
203939  **
203940  ******************************************************************************
203941  **
203942  ** Routines for varint serialization and deserialization.
203943  */
203944  
203945  
203946  /* #include "fts5Int.h" */
203947  
203948  /*
203949  ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
203950  ** Except, this version does handle the single byte case that the core
203951  ** version depends on being handled before its function is called.
203952  */
203953  static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
203954    u32 a,b;
203955  
203956    /* The 1-byte case. Overwhelmingly the most common. */
203957    a = *p;
203958    /* a: p0 (unmasked) */
203959    if (!(a&0x80))
203960    {
203961      /* Values between 0 and 127 */
203962      *v = a;
203963      return 1;
203964    }
203965  
203966    /* The 2-byte case */
203967    p++;
203968    b = *p;
203969    /* b: p1 (unmasked) */
203970    if (!(b&0x80))
203971    {
203972      /* Values between 128 and 16383 */
203973      a &= 0x7f;
203974      a = a<<7;
203975      *v = a | b;
203976      return 2;
203977    }
203978  
203979    /* The 3-byte case */
203980    p++;
203981    a = a<<14;
203982    a |= *p;
203983    /* a: p0<<14 | p2 (unmasked) */
203984    if (!(a&0x80))
203985    {
203986      /* Values between 16384 and 2097151 */
203987      a &= (0x7f<<14)|(0x7f);
203988      b &= 0x7f;
203989      b = b<<7;
203990      *v = a | b;
203991      return 3;
203992    }
203993  
203994    /* A 32-bit varint is used to store size information in btrees.
203995    ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
203996    ** A 3-byte varint is sufficient, for example, to record the size
203997    ** of a 1048569-byte BLOB or string.
203998    **
203999    ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
204000    ** rare larger cases can be handled by the slower 64-bit varint
204001    ** routine.
204002    */
204003    {
204004      u64 v64;
204005      u8 n;
204006      p -= 2;
204007      n = sqlite3Fts5GetVarint(p, &v64);
204008      *v = (u32)v64;
204009      assert( n>3 && n<=9 );
204010      return n;
204011    }
204012  }
204013  
204014  
204015  /*
204016  ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
204017  ** are defined here rather than simply putting the constant expressions
204018  ** inline in order to work around bugs in the RVT compiler.
204019  **
204020  ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
204021  **
204022  ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
204023  */
204024  #define SLOT_2_0     0x001fc07f
204025  #define SLOT_4_2_0   0xf01fc07f
204026  
204027  /*
204028  ** Read a 64-bit variable-length integer from memory starting at p[0].
204029  ** Return the number of bytes read.  The value is stored in *v.
204030  */
204031  static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
204032    u32 a,b,s;
204033  
204034    a = *p;
204035    /* a: p0 (unmasked) */
204036    if (!(a&0x80))
204037    {
204038      *v = a;
204039      return 1;
204040    }
204041  
204042    p++;
204043    b = *p;
204044    /* b: p1 (unmasked) */
204045    if (!(b&0x80))
204046    {
204047      a &= 0x7f;
204048      a = a<<7;
204049      a |= b;
204050      *v = a;
204051      return 2;
204052    }
204053  
204054    /* Verify that constants are precomputed correctly */
204055    assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
204056    assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
204057  
204058    p++;
204059    a = a<<14;
204060    a |= *p;
204061    /* a: p0<<14 | p2 (unmasked) */
204062    if (!(a&0x80))
204063    {
204064      a &= SLOT_2_0;
204065      b &= 0x7f;
204066      b = b<<7;
204067      a |= b;
204068      *v = a;
204069      return 3;
204070    }
204071  
204072    /* CSE1 from below */
204073    a &= SLOT_2_0;
204074    p++;
204075    b = b<<14;
204076    b |= *p;
204077    /* b: p1<<14 | p3 (unmasked) */
204078    if (!(b&0x80))
204079    {
204080      b &= SLOT_2_0;
204081      /* moved CSE1 up */
204082      /* a &= (0x7f<<14)|(0x7f); */
204083      a = a<<7;
204084      a |= b;
204085      *v = a;
204086      return 4;
204087    }
204088  
204089    /* a: p0<<14 | p2 (masked) */
204090    /* b: p1<<14 | p3 (unmasked) */
204091    /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
204092    /* moved CSE1 up */
204093    /* a &= (0x7f<<14)|(0x7f); */
204094    b &= SLOT_2_0;
204095    s = a;
204096    /* s: p0<<14 | p2 (masked) */
204097  
204098    p++;
204099    a = a<<14;
204100    a |= *p;
204101    /* a: p0<<28 | p2<<14 | p4 (unmasked) */
204102    if (!(a&0x80))
204103    {
204104      /* we can skip these cause they were (effectively) done above in calc'ing s */
204105      /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
204106      /* b &= (0x7f<<14)|(0x7f); */
204107      b = b<<7;
204108      a |= b;
204109      s = s>>18;
204110      *v = ((u64)s)<<32 | a;
204111      return 5;
204112    }
204113  
204114    /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
204115    s = s<<7;
204116    s |= b;
204117    /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
204118  
204119    p++;
204120    b = b<<14;
204121    b |= *p;
204122    /* b: p1<<28 | p3<<14 | p5 (unmasked) */
204123    if (!(b&0x80))
204124    {
204125      /* we can skip this cause it was (effectively) done above in calc'ing s */
204126      /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
204127      a &= SLOT_2_0;
204128      a = a<<7;
204129      a |= b;
204130      s = s>>18;
204131      *v = ((u64)s)<<32 | a;
204132      return 6;
204133    }
204134  
204135    p++;
204136    a = a<<14;
204137    a |= *p;
204138    /* a: p2<<28 | p4<<14 | p6 (unmasked) */
204139    if (!(a&0x80))
204140    {
204141      a &= SLOT_4_2_0;
204142      b &= SLOT_2_0;
204143      b = b<<7;
204144      a |= b;
204145      s = s>>11;
204146      *v = ((u64)s)<<32 | a;
204147      return 7;
204148    }
204149  
204150    /* CSE2 from below */
204151    a &= SLOT_2_0;
204152    p++;
204153    b = b<<14;
204154    b |= *p;
204155    /* b: p3<<28 | p5<<14 | p7 (unmasked) */
204156    if (!(b&0x80))
204157    {
204158      b &= SLOT_4_2_0;
204159      /* moved CSE2 up */
204160      /* a &= (0x7f<<14)|(0x7f); */
204161      a = a<<7;
204162      a |= b;
204163      s = s>>4;
204164      *v = ((u64)s)<<32 | a;
204165      return 8;
204166    }
204167  
204168    p++;
204169    a = a<<15;
204170    a |= *p;
204171    /* a: p4<<29 | p6<<15 | p8 (unmasked) */
204172  
204173    /* moved CSE2 up */
204174    /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
204175    b &= SLOT_2_0;
204176    b = b<<8;
204177    a |= b;
204178  
204179    s = s<<4;
204180    b = p[-4];
204181    b &= 0x7f;
204182    b = b>>3;
204183    s |= b;
204184  
204185    *v = ((u64)s)<<32 | a;
204186  
204187    return 9;
204188  }
204189  
204190  /*
204191  ** The variable-length integer encoding is as follows:
204192  **
204193  ** KEY:
204194  **         A = 0xxxxxxx    7 bits of data and one flag bit
204195  **         B = 1xxxxxxx    7 bits of data and one flag bit
204196  **         C = xxxxxxxx    8 bits of data
204197  **
204198  **  7 bits - A
204199  ** 14 bits - BA
204200  ** 21 bits - BBA
204201  ** 28 bits - BBBA
204202  ** 35 bits - BBBBA
204203  ** 42 bits - BBBBBA
204204  ** 49 bits - BBBBBBA
204205  ** 56 bits - BBBBBBBA
204206  ** 64 bits - BBBBBBBBC
204207  */
204208  
204209  #ifdef SQLITE_NOINLINE
204210  # define FTS5_NOINLINE SQLITE_NOINLINE
204211  #else
204212  # define FTS5_NOINLINE
204213  #endif
204214  
204215  /*
204216  ** Write a 64-bit variable-length integer to memory starting at p[0].
204217  ** The length of data write will be between 1 and 9 bytes.  The number
204218  ** of bytes written is returned.
204219  **
204220  ** A variable-length integer consists of the lower 7 bits of each byte
204221  ** for all bytes that have the 8th bit set and one byte with the 8th
204222  ** bit clear.  Except, if we get to the 9th byte, it stores the full
204223  ** 8 bits and is the last byte.
204224  */
204225  static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
204226    int i, j, n;
204227    u8 buf[10];
204228    if( v & (((u64)0xff000000)<<32) ){
204229      p[8] = (u8)v;
204230      v >>= 8;
204231      for(i=7; i>=0; i--){
204232        p[i] = (u8)((v & 0x7f) | 0x80);
204233        v >>= 7;
204234      }
204235      return 9;
204236    }    
204237    n = 0;
204238    do{
204239      buf[n++] = (u8)((v & 0x7f) | 0x80);
204240      v >>= 7;
204241    }while( v!=0 );
204242    buf[0] &= 0x7f;
204243    assert( n<=9 );
204244    for(i=0, j=n-1; j>=0; j--, i++){
204245      p[i] = buf[j];
204246    }
204247    return n;
204248  }
204249  
204250  static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
204251    if( v<=0x7f ){
204252      p[0] = v&0x7f;
204253      return 1;
204254    }
204255    if( v<=0x3fff ){
204256      p[0] = ((v>>7)&0x7f)|0x80;
204257      p[1] = v&0x7f;
204258      return 2;
204259    }
204260    return fts5PutVarint64(p,v);
204261  }
204262  
204263  
204264  static int sqlite3Fts5GetVarintLen(u32 iVal){
204265  #if 0
204266    if( iVal<(1 << 7 ) ) return 1;
204267  #endif
204268    assert( iVal>=(1 << 7) );
204269    if( iVal<(1 << 14) ) return 2;
204270    if( iVal<(1 << 21) ) return 3;
204271    if( iVal<(1 << 28) ) return 4;
204272    return 5;
204273  }
204274  
204275  
204276  /*
204277  ** 2015 May 08
204278  **
204279  ** The author disclaims copyright to this source code.  In place of
204280  ** a legal notice, here is a blessing:
204281  **
204282  **    May you do good and not evil.
204283  **    May you find forgiveness for yourself and forgive others.
204284  **    May you share freely, never taking more than you give.
204285  **
204286  ******************************************************************************
204287  **
204288  ** This is an SQLite virtual table module implementing direct access to an
204289  ** existing FTS5 index. The module may create several different types of 
204290  ** tables:
204291  **
204292  ** col:
204293  **     CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
204294  **
204295  **   One row for each term/column combination. The value of $doc is set to
204296  **   the number of fts5 rows that contain at least one instance of term
204297  **   $term within column $col. Field $cnt is set to the total number of 
204298  **   instances of term $term in column $col (in any row of the fts5 table). 
204299  **
204300  ** row:
204301  **     CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
204302  **
204303  **   One row for each term in the database. The value of $doc is set to
204304  **   the number of fts5 rows that contain at least one instance of term
204305  **   $term. Field $cnt is set to the total number of instances of term 
204306  **   $term in the database.
204307  **
204308  ** instance:
204309  **     CREATE TABLE vocab(term, doc, col, offset, PRIMARY KEY(<all-fields>));
204310  **
204311  **   One row for each term instance in the database. 
204312  */
204313  
204314  
204315  /* #include "fts5Int.h" */
204316  
204317  
204318  typedef struct Fts5VocabTable Fts5VocabTable;
204319  typedef struct Fts5VocabCursor Fts5VocabCursor;
204320  
204321  struct Fts5VocabTable {
204322    sqlite3_vtab base;
204323    char *zFts5Tbl;                 /* Name of fts5 table */
204324    char *zFts5Db;                  /* Db containing fts5 table */
204325    sqlite3 *db;                    /* Database handle */
204326    Fts5Global *pGlobal;            /* FTS5 global object for this database */
204327    int eType;                      /* FTS5_VOCAB_COL, ROW or INSTANCE */
204328  };
204329  
204330  struct Fts5VocabCursor {
204331    sqlite3_vtab_cursor base;
204332    sqlite3_stmt *pStmt;            /* Statement holding lock on pIndex */
204333    Fts5Index *pIndex;              /* Associated FTS5 index */
204334  
204335    int bEof;                       /* True if this cursor is at EOF */
204336    Fts5IndexIter *pIter;           /* Term/rowid iterator object */
204337  
204338    int nLeTerm;                    /* Size of zLeTerm in bytes */
204339    char *zLeTerm;                  /* (term <= $zLeTerm) paramater, or NULL */
204340  
204341    /* These are used by 'col' tables only */
204342    Fts5Config *pConfig;            /* Fts5 table configuration */
204343    int iCol;
204344    i64 *aCnt;
204345    i64 *aDoc;
204346  
204347    /* Output values used by all tables. */
204348    i64 rowid;                      /* This table's current rowid value */
204349    Fts5Buffer term;                /* Current value of 'term' column */
204350  
204351    /* Output values Used by 'instance' tables only */
204352    i64 iInstPos;
204353    int iInstOff;
204354  };
204355  
204356  #define FTS5_VOCAB_COL      0
204357  #define FTS5_VOCAB_ROW      1
204358  #define FTS5_VOCAB_INSTANCE 2
204359  
204360  #define FTS5_VOCAB_COL_SCHEMA  "term, col, doc, cnt"
204361  #define FTS5_VOCAB_ROW_SCHEMA  "term, doc, cnt"
204362  #define FTS5_VOCAB_INST_SCHEMA "term, doc, col, offset"
204363  
204364  /*
204365  ** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
204366  */
204367  #define FTS5_VOCAB_TERM_EQ 0x01
204368  #define FTS5_VOCAB_TERM_GE 0x02
204369  #define FTS5_VOCAB_TERM_LE 0x04
204370  
204371  
204372  /*
204373  ** Translate a string containing an fts5vocab table type to an 
204374  ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
204375  ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
204376  ** and return SQLITE_ERROR.
204377  */
204378  static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
204379    int rc = SQLITE_OK;
204380    char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
204381    if( rc==SQLITE_OK ){
204382      sqlite3Fts5Dequote(zCopy);
204383      if( sqlite3_stricmp(zCopy, "col")==0 ){
204384        *peType = FTS5_VOCAB_COL;
204385      }else
204386  
204387      if( sqlite3_stricmp(zCopy, "row")==0 ){
204388        *peType = FTS5_VOCAB_ROW;
204389      }else
204390      if( sqlite3_stricmp(zCopy, "instance")==0 ){
204391        *peType = FTS5_VOCAB_INSTANCE;
204392      }else
204393      {
204394        *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
204395        rc = SQLITE_ERROR;
204396      }
204397      sqlite3_free(zCopy);
204398    }
204399  
204400    return rc;
204401  }
204402  
204403  
204404  /*
204405  ** The xDisconnect() virtual table method.
204406  */
204407  static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
204408    Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
204409    sqlite3_free(pTab);
204410    return SQLITE_OK;
204411  }
204412  
204413  /*
204414  ** The xDestroy() virtual table method.
204415  */
204416  static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
204417    Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
204418    sqlite3_free(pTab);
204419    return SQLITE_OK;
204420  }
204421  
204422  /*
204423  ** This function is the implementation of both the xConnect and xCreate
204424  ** methods of the FTS3 virtual table.
204425  **
204426  ** The argv[] array contains the following:
204427  **
204428  **   argv[0]   -> module name  ("fts5vocab")
204429  **   argv[1]   -> database name
204430  **   argv[2]   -> table name
204431  **
204432  ** then:
204433  **
204434  **   argv[3]   -> name of fts5 table
204435  **   argv[4]   -> type of fts5vocab table
204436  **
204437  ** or, for tables in the TEMP schema only.
204438  **
204439  **   argv[3]   -> name of fts5 tables database
204440  **   argv[4]   -> name of fts5 table
204441  **   argv[5]   -> type of fts5vocab table
204442  */
204443  static int fts5VocabInitVtab(
204444    sqlite3 *db,                    /* The SQLite database connection */
204445    void *pAux,                     /* Pointer to Fts5Global object */
204446    int argc,                       /* Number of elements in argv array */
204447    const char * const *argv,       /* xCreate/xConnect argument array */
204448    sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
204449    char **pzErr                    /* Write any error message here */
204450  ){
204451    const char *azSchema[] = { 
204452      "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA  ")", 
204453      "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA  ")",
204454      "CREATE TABlE vocab(" FTS5_VOCAB_INST_SCHEMA ")"
204455    };
204456  
204457    Fts5VocabTable *pRet = 0;
204458    int rc = SQLITE_OK;             /* Return code */
204459    int bDb;
204460  
204461    bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
204462  
204463    if( argc!=5 && bDb==0 ){
204464      *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
204465      rc = SQLITE_ERROR;
204466    }else{
204467      int nByte;                      /* Bytes of space to allocate */
204468      const char *zDb = bDb ? argv[3] : argv[1];
204469      const char *zTab = bDb ? argv[4] : argv[3];
204470      const char *zType = bDb ? argv[5] : argv[4];
204471      int nDb = (int)strlen(zDb)+1; 
204472      int nTab = (int)strlen(zTab)+1;
204473      int eType = 0;
204474      
204475      rc = fts5VocabTableType(zType, pzErr, &eType);
204476      if( rc==SQLITE_OK ){
204477        assert( eType>=0 && eType<ArraySize(azSchema) );
204478        rc = sqlite3_declare_vtab(db, azSchema[eType]);
204479      }
204480  
204481      nByte = sizeof(Fts5VocabTable) + nDb + nTab;
204482      pRet = sqlite3Fts5MallocZero(&rc, nByte);
204483      if( pRet ){
204484        pRet->pGlobal = (Fts5Global*)pAux;
204485        pRet->eType = eType;
204486        pRet->db = db;
204487        pRet->zFts5Tbl = (char*)&pRet[1];
204488        pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
204489        memcpy(pRet->zFts5Tbl, zTab, nTab);
204490        memcpy(pRet->zFts5Db, zDb, nDb);
204491        sqlite3Fts5Dequote(pRet->zFts5Tbl);
204492        sqlite3Fts5Dequote(pRet->zFts5Db);
204493      }
204494    }
204495  
204496    *ppVTab = (sqlite3_vtab*)pRet;
204497    return rc;
204498  }
204499  
204500  
204501  /*
204502  ** The xConnect() and xCreate() methods for the virtual table. All the
204503  ** work is done in function fts5VocabInitVtab().
204504  */
204505  static int fts5VocabConnectMethod(
204506    sqlite3 *db,                    /* Database connection */
204507    void *pAux,                     /* Pointer to tokenizer hash table */
204508    int argc,                       /* Number of elements in argv array */
204509    const char * const *argv,       /* xCreate/xConnect argument array */
204510    sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
204511    char **pzErr                    /* OUT: sqlite3_malloc'd error message */
204512  ){
204513    return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
204514  }
204515  static int fts5VocabCreateMethod(
204516    sqlite3 *db,                    /* Database connection */
204517    void *pAux,                     /* Pointer to tokenizer hash table */
204518    int argc,                       /* Number of elements in argv array */
204519    const char * const *argv,       /* xCreate/xConnect argument array */
204520    sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
204521    char **pzErr                    /* OUT: sqlite3_malloc'd error message */
204522  ){
204523    return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
204524  }
204525  
204526  /* 
204527  ** Implementation of the xBestIndex method.
204528  **
204529  ** Only constraints of the form:
204530  **
204531  **     term <= ?
204532  **     term == ?
204533  **     term >= ?
204534  **
204535  ** are interpreted. Less-than and less-than-or-equal are treated 
204536  ** identically, as are greater-than and greater-than-or-equal.
204537  */
204538  static int fts5VocabBestIndexMethod(
204539    sqlite3_vtab *pUnused,
204540    sqlite3_index_info *pInfo
204541  ){
204542    int i;
204543    int iTermEq = -1;
204544    int iTermGe = -1;
204545    int iTermLe = -1;
204546    int idxNum = 0;
204547    int nArg = 0;
204548  
204549    UNUSED_PARAM(pUnused);
204550  
204551    for(i=0; i<pInfo->nConstraint; i++){
204552      struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
204553      if( p->usable==0 ) continue;
204554      if( p->iColumn==0 ){          /* term column */
204555        if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
204556        if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
204557        if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
204558        if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
204559        if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
204560      }
204561    }
204562  
204563    if( iTermEq>=0 ){
204564      idxNum |= FTS5_VOCAB_TERM_EQ;
204565      pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
204566      pInfo->estimatedCost = 100;
204567    }else{
204568      pInfo->estimatedCost = 1000000;
204569      if( iTermGe>=0 ){
204570        idxNum |= FTS5_VOCAB_TERM_GE;
204571        pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
204572        pInfo->estimatedCost = pInfo->estimatedCost / 2;
204573      }
204574      if( iTermLe>=0 ){
204575        idxNum |= FTS5_VOCAB_TERM_LE;
204576        pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
204577        pInfo->estimatedCost = pInfo->estimatedCost / 2;
204578      }
204579    }
204580  
204581    /* This virtual table always delivers results in ascending order of
204582    ** the "term" column (column 0). So if the user has requested this
204583    ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the
204584    ** sqlite3_index_info.orderByConsumed flag to tell the core the results
204585    ** are already in sorted order.  */
204586    if( pInfo->nOrderBy==1 
204587     && pInfo->aOrderBy[0].iColumn==0 
204588     && pInfo->aOrderBy[0].desc==0
204589    ){
204590      pInfo->orderByConsumed = 1;
204591    }
204592  
204593    pInfo->idxNum = idxNum;
204594    return SQLITE_OK;
204595  }
204596  
204597  /*
204598  ** Implementation of xOpen method.
204599  */
204600  static int fts5VocabOpenMethod(
204601    sqlite3_vtab *pVTab, 
204602    sqlite3_vtab_cursor **ppCsr
204603  ){
204604    Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
204605    Fts5Index *pIndex = 0;
204606    Fts5Config *pConfig = 0;
204607    Fts5VocabCursor *pCsr = 0;
204608    int rc = SQLITE_OK;
204609    sqlite3_stmt *pStmt = 0;
204610    char *zSql = 0;
204611  
204612    zSql = sqlite3Fts5Mprintf(&rc,
204613        "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
204614        pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
204615    );
204616    if( zSql ){
204617      rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
204618    }
204619    sqlite3_free(zSql);
204620    assert( rc==SQLITE_OK || pStmt==0 );
204621    if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
204622  
204623    if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
204624      i64 iId = sqlite3_column_int64(pStmt, 0);
204625      pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &pConfig);
204626    }
204627  
204628    if( rc==SQLITE_OK && pIndex==0 ){
204629      rc = sqlite3_finalize(pStmt);
204630      pStmt = 0;
204631      if( rc==SQLITE_OK ){
204632        pVTab->zErrMsg = sqlite3_mprintf(
204633            "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
204634        );
204635        rc = SQLITE_ERROR;
204636      }
204637    }
204638  
204639    if( rc==SQLITE_OK ){
204640      int nByte = pConfig->nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
204641      pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
204642    }
204643  
204644    if( pCsr ){
204645      pCsr->pIndex = pIndex;
204646      pCsr->pStmt = pStmt;
204647      pCsr->pConfig = pConfig;
204648      pCsr->aCnt = (i64*)&pCsr[1];
204649      pCsr->aDoc = &pCsr->aCnt[pConfig->nCol];
204650    }else{
204651      sqlite3_finalize(pStmt);
204652    }
204653  
204654    *ppCsr = (sqlite3_vtab_cursor*)pCsr;
204655    return rc;
204656  }
204657  
204658  static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
204659    pCsr->rowid = 0;
204660    sqlite3Fts5IterClose(pCsr->pIter);
204661    pCsr->pIter = 0;
204662    sqlite3_free(pCsr->zLeTerm);
204663    pCsr->nLeTerm = -1;
204664    pCsr->zLeTerm = 0;
204665  }
204666  
204667  /*
204668  ** Close the cursor.  For additional information see the documentation
204669  ** on the xClose method of the virtual table interface.
204670  */
204671  static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
204672    Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
204673    fts5VocabResetCursor(pCsr);
204674    sqlite3Fts5BufferFree(&pCsr->term);
204675    sqlite3_finalize(pCsr->pStmt);
204676    sqlite3_free(pCsr);
204677    return SQLITE_OK;
204678  }
204679  
204680  static int fts5VocabInstanceNewTerm(Fts5VocabCursor *pCsr){
204681    int rc = SQLITE_OK;
204682    
204683    if( sqlite3Fts5IterEof(pCsr->pIter) ){
204684      pCsr->bEof = 1;
204685    }else{
204686      const char *zTerm;
204687      int nTerm;
204688      zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
204689      if( pCsr->nLeTerm>=0 ){
204690        int nCmp = MIN(nTerm, pCsr->nLeTerm);
204691        int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
204692        if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
204693          pCsr->bEof = 1;
204694        }
204695      }
204696  
204697      sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
204698    }
204699    return rc;
204700  }
204701  
204702  static int fts5VocabInstanceNext(Fts5VocabCursor *pCsr){
204703    int eDetail = pCsr->pConfig->eDetail;
204704    int rc = SQLITE_OK;
204705    Fts5IndexIter *pIter = pCsr->pIter;
204706    i64 *pp = &pCsr->iInstPos;
204707    int *po = &pCsr->iInstOff;
204708    
204709    while( eDetail==FTS5_DETAIL_NONE
204710        || sqlite3Fts5PoslistNext64(pIter->pData, pIter->nData, po, pp) 
204711    ){
204712      pCsr->iInstPos = 0;
204713      pCsr->iInstOff = 0;
204714  
204715      rc = sqlite3Fts5IterNextScan(pCsr->pIter);
204716      if( rc==SQLITE_OK ){
204717        rc = fts5VocabInstanceNewTerm(pCsr);
204718        if( eDetail==FTS5_DETAIL_NONE ) break;
204719      }
204720      if( rc ){
204721        pCsr->bEof = 1;
204722        break;
204723      }
204724    }
204725  
204726    return rc;
204727  }
204728  
204729  /*
204730  ** Advance the cursor to the next row in the table.
204731  */
204732  static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
204733    Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
204734    Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
204735    int rc = SQLITE_OK;
204736    int nCol = pCsr->pConfig->nCol;
204737  
204738    pCsr->rowid++;
204739  
204740    if( pTab->eType==FTS5_VOCAB_INSTANCE ){
204741      return fts5VocabInstanceNext(pCsr);
204742    }
204743  
204744    if( pTab->eType==FTS5_VOCAB_COL ){
204745      for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
204746        if( pCsr->aDoc[pCsr->iCol] ) break;
204747      }
204748    }
204749  
204750    if( pTab->eType!=FTS5_VOCAB_COL || pCsr->iCol>=nCol ){
204751      if( sqlite3Fts5IterEof(pCsr->pIter) ){
204752        pCsr->bEof = 1;
204753      }else{
204754        const char *zTerm;
204755        int nTerm;
204756  
204757        zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
204758        if( pCsr->nLeTerm>=0 ){
204759          int nCmp = MIN(nTerm, pCsr->nLeTerm);
204760          int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
204761          if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
204762            pCsr->bEof = 1;
204763            return SQLITE_OK;
204764          }
204765        }
204766  
204767        sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
204768        memset(pCsr->aCnt, 0, nCol * sizeof(i64));
204769        memset(pCsr->aDoc, 0, nCol * sizeof(i64));
204770        pCsr->iCol = 0;
204771  
204772        assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
204773        while( rc==SQLITE_OK ){
204774          int eDetail = pCsr->pConfig->eDetail;
204775          const u8 *pPos; int nPos;   /* Position list */
204776          i64 iPos = 0;               /* 64-bit position read from poslist */
204777          int iOff = 0;               /* Current offset within position list */
204778  
204779          pPos = pCsr->pIter->pData;
204780          nPos = pCsr->pIter->nData;
204781  
204782          switch( pTab->eType ){
204783            case FTS5_VOCAB_ROW:
204784              if( eDetail==FTS5_DETAIL_FULL ){
204785                while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
204786                  pCsr->aCnt[0]++;
204787                }
204788              }
204789              pCsr->aDoc[0]++;
204790              break;
204791  
204792            case FTS5_VOCAB_COL:
204793              if( eDetail==FTS5_DETAIL_FULL ){
204794                int iCol = -1;
204795                while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
204796                  int ii = FTS5_POS2COLUMN(iPos);
204797                  pCsr->aCnt[ii]++;
204798                  if( iCol!=ii ){
204799                    if( ii>=nCol ){
204800                      rc = FTS5_CORRUPT;
204801                      break;
204802                    }
204803                    pCsr->aDoc[ii]++;
204804                    iCol = ii;
204805                  }
204806                }
204807              }else if( eDetail==FTS5_DETAIL_COLUMNS ){
204808                while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
204809                  assert_nc( iPos>=0 && iPos<nCol );
204810                  if( iPos>=nCol ){
204811                    rc = FTS5_CORRUPT;
204812                    break;
204813                  }
204814                  pCsr->aDoc[iPos]++;
204815                }
204816              }else{
204817                assert( eDetail==FTS5_DETAIL_NONE );
204818                pCsr->aDoc[0]++;
204819              }
204820              break;
204821  
204822            default:
204823              assert( pTab->eType==FTS5_VOCAB_INSTANCE );
204824              break;
204825          }
204826  
204827          if( rc==SQLITE_OK ){
204828            rc = sqlite3Fts5IterNextScan(pCsr->pIter);
204829          }
204830          if( pTab->eType==FTS5_VOCAB_INSTANCE ) break;
204831  
204832          if( rc==SQLITE_OK ){
204833            zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
204834            if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ){
204835              break;
204836            }
204837            if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
204838          }
204839        }
204840      }
204841    }
204842  
204843    if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
204844      while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++;
204845      assert( pCsr->iCol<pCsr->pConfig->nCol );
204846    }
204847    return rc;
204848  }
204849  
204850  /*
204851  ** This is the xFilter implementation for the virtual table.
204852  */
204853  static int fts5VocabFilterMethod(
204854    sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
204855    int idxNum,                     /* Strategy index */
204856    const char *zUnused,            /* Unused */
204857    int nUnused,                    /* Number of elements in apVal */
204858    sqlite3_value **apVal           /* Arguments for the indexing scheme */
204859  ){
204860    Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
204861    Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
204862    int eType = pTab->eType;
204863    int rc = SQLITE_OK;
204864  
204865    int iVal = 0;
204866    int f = FTS5INDEX_QUERY_SCAN;
204867    const char *zTerm = 0;
204868    int nTerm = 0;
204869  
204870    sqlite3_value *pEq = 0;
204871    sqlite3_value *pGe = 0;
204872    sqlite3_value *pLe = 0;
204873  
204874    UNUSED_PARAM2(zUnused, nUnused);
204875  
204876    fts5VocabResetCursor(pCsr);
204877    if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
204878    if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
204879    if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
204880  
204881    if( pEq ){
204882      zTerm = (const char *)sqlite3_value_text(pEq);
204883      nTerm = sqlite3_value_bytes(pEq);
204884      f = 0;
204885    }else{
204886      if( pGe ){
204887        zTerm = (const char *)sqlite3_value_text(pGe);
204888        nTerm = sqlite3_value_bytes(pGe);
204889      }
204890      if( pLe ){
204891        const char *zCopy = (const char *)sqlite3_value_text(pLe);
204892        pCsr->nLeTerm = sqlite3_value_bytes(pLe);
204893        pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
204894        if( pCsr->zLeTerm==0 ){
204895          rc = SQLITE_NOMEM;
204896        }else{
204897          memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
204898        }
204899      }
204900    }
204901  
204902    if( rc==SQLITE_OK ){
204903      rc = sqlite3Fts5IndexQuery(pCsr->pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
204904    }
204905    if( rc==SQLITE_OK && eType==FTS5_VOCAB_INSTANCE ){
204906      rc = fts5VocabInstanceNewTerm(pCsr);
204907    }
204908    if( rc==SQLITE_OK 
204909     && !pCsr->bEof 
204910     && (eType!=FTS5_VOCAB_INSTANCE || pCsr->pConfig->eDetail!=FTS5_DETAIL_NONE)
204911    ){
204912      rc = fts5VocabNextMethod(pCursor);
204913    }
204914  
204915    return rc;
204916  }
204917  
204918  /* 
204919  ** This is the xEof method of the virtual table. SQLite calls this 
204920  ** routine to find out if it has reached the end of a result set.
204921  */
204922  static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
204923    Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
204924    return pCsr->bEof;
204925  }
204926  
204927  static int fts5VocabColumnMethod(
204928    sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
204929    sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
204930    int iCol                        /* Index of column to read value from */
204931  ){
204932    Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
204933    int eDetail = pCsr->pConfig->eDetail;
204934    int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
204935    i64 iVal = 0;
204936  
204937    if( iCol==0 ){
204938      sqlite3_result_text(
204939          pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
204940      );
204941    }else if( eType==FTS5_VOCAB_COL ){
204942      assert( iCol==1 || iCol==2 || iCol==3 );
204943      if( iCol==1 ){
204944        if( eDetail!=FTS5_DETAIL_NONE ){
204945          const char *z = pCsr->pConfig->azCol[pCsr->iCol];
204946          sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
204947        }
204948      }else if( iCol==2 ){
204949        iVal = pCsr->aDoc[pCsr->iCol];
204950      }else{
204951        iVal = pCsr->aCnt[pCsr->iCol];
204952      }
204953    }else if( eType==FTS5_VOCAB_ROW ){
204954      assert( iCol==1 || iCol==2 );
204955      if( iCol==1 ){
204956        iVal = pCsr->aDoc[0];
204957      }else{
204958        iVal = pCsr->aCnt[0];
204959      }
204960    }else{
204961      assert( eType==FTS5_VOCAB_INSTANCE );
204962      switch( iCol ){
204963        case 1:
204964          sqlite3_result_int64(pCtx, pCsr->pIter->iRowid);
204965          break;
204966        case 2: {
204967          int ii = -1;
204968          if( eDetail==FTS5_DETAIL_FULL ){
204969            ii = FTS5_POS2COLUMN(pCsr->iInstPos);
204970          }else if( eDetail==FTS5_DETAIL_COLUMNS ){
204971            ii = (int)pCsr->iInstPos;
204972          }
204973          if( ii>=0 && ii<pCsr->pConfig->nCol ){
204974            const char *z = pCsr->pConfig->azCol[ii];
204975            sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
204976          }
204977          break;
204978        }
204979        default: {
204980          assert( iCol==3 );
204981          if( eDetail==FTS5_DETAIL_FULL ){
204982            int ii = FTS5_POS2OFFSET(pCsr->iInstPos);
204983            sqlite3_result_int(pCtx, ii);
204984          }
204985          break;
204986        }
204987      }
204988    }
204989  
204990    if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
204991    return SQLITE_OK;
204992  }
204993  
204994  /* 
204995  ** This is the xRowid method. The SQLite core calls this routine to
204996  ** retrieve the rowid for the current row of the result set. The
204997  ** rowid should be written to *pRowid.
204998  */
204999  static int fts5VocabRowidMethod(
205000    sqlite3_vtab_cursor *pCursor, 
205001    sqlite_int64 *pRowid
205002  ){
205003    Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
205004    *pRowid = pCsr->rowid;
205005    return SQLITE_OK;
205006  }
205007  
205008  static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
205009    static const sqlite3_module fts5Vocab = {
205010      /* iVersion      */ 2,
205011      /* xCreate       */ fts5VocabCreateMethod,
205012      /* xConnect      */ fts5VocabConnectMethod,
205013      /* xBestIndex    */ fts5VocabBestIndexMethod,
205014      /* xDisconnect   */ fts5VocabDisconnectMethod,
205015      /* xDestroy      */ fts5VocabDestroyMethod,
205016      /* xOpen         */ fts5VocabOpenMethod,
205017      /* xClose        */ fts5VocabCloseMethod,
205018      /* xFilter       */ fts5VocabFilterMethod,
205019      /* xNext         */ fts5VocabNextMethod,
205020      /* xEof          */ fts5VocabEofMethod,
205021      /* xColumn       */ fts5VocabColumnMethod,
205022      /* xRowid        */ fts5VocabRowidMethod,
205023      /* xUpdate       */ 0,
205024      /* xBegin        */ 0,
205025      /* xSync         */ 0,
205026      /* xCommit       */ 0,
205027      /* xRollback     */ 0,
205028      /* xFindFunction */ 0,
205029      /* xRename       */ 0,
205030      /* xSavepoint    */ 0,
205031      /* xRelease      */ 0,
205032      /* xRollbackTo   */ 0,
205033    };
205034    void *p = (void*)pGlobal;
205035  
205036    return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
205037  }
205038  
205039  
205040  
205041  
205042      
205043  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
205044  
205045  /************** End of fts5.c ************************************************/
205046  /************** Begin file stmt.c ********************************************/
205047  /*
205048  ** 2017-05-31
205049  **
205050  ** The author disclaims copyright to this source code.  In place of
205051  ** a legal notice, here is a blessing:
205052  **
205053  **    May you do good and not evil.
205054  **    May you find forgiveness for yourself and forgive others.
205055  **    May you share freely, never taking more than you give.
205056  **
205057  *************************************************************************
205058  **
205059  ** This file demonstrates an eponymous virtual table that returns information
205060  ** about all prepared statements for the database connection.
205061  **
205062  ** Usage example:
205063  **
205064  **     .load ./stmt
205065  **     .mode line
205066  **     .header on
205067  **     SELECT * FROM stmt;
205068  */
205069  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB)
205070  #if !defined(SQLITEINT_H)
205071  /* #include "sqlite3ext.h" */
205072  #endif
205073  SQLITE_EXTENSION_INIT1
205074  /* #include <assert.h> */
205075  /* #include <string.h> */
205076  
205077  #ifndef SQLITE_OMIT_VIRTUALTABLE
205078  
205079  /* stmt_vtab is a subclass of sqlite3_vtab which will
205080  ** serve as the underlying representation of a stmt virtual table
205081  */
205082  typedef struct stmt_vtab stmt_vtab;
205083  struct stmt_vtab {
205084    sqlite3_vtab base;  /* Base class - must be first */
205085    sqlite3 *db;        /* Database connection for this stmt vtab */
205086  };
205087  
205088  /* stmt_cursor is a subclass of sqlite3_vtab_cursor which will
205089  ** serve as the underlying representation of a cursor that scans
205090  ** over rows of the result
205091  */
205092  typedef struct stmt_cursor stmt_cursor;
205093  struct stmt_cursor {
205094    sqlite3_vtab_cursor base;  /* Base class - must be first */
205095    sqlite3 *db;               /* Database connection for this cursor */
205096    sqlite3_stmt *pStmt;       /* Statement cursor is currently pointing at */
205097    sqlite3_int64 iRowid;      /* The rowid */
205098  };
205099  
205100  /*
205101  ** The stmtConnect() method is invoked to create a new
205102  ** stmt_vtab that describes the stmt virtual table.
205103  **
205104  ** Think of this routine as the constructor for stmt_vtab objects.
205105  **
205106  ** All this routine needs to do is:
205107  **
205108  **    (1) Allocate the stmt_vtab object and initialize all fields.
205109  **
205110  **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
205111  **        result set of queries against stmt will look like.
205112  */
205113  static int stmtConnect(
205114    sqlite3 *db,
205115    void *pAux,
205116    int argc, const char *const*argv,
205117    sqlite3_vtab **ppVtab,
205118    char **pzErr
205119  ){
205120    stmt_vtab *pNew;
205121    int rc;
205122  
205123  /* Column numbers */
205124  #define STMT_COLUMN_SQL     0   /* SQL for the statement */
205125  #define STMT_COLUMN_NCOL    1   /* Number of result columns */
205126  #define STMT_COLUMN_RO      2   /* True if read-only */
205127  #define STMT_COLUMN_BUSY    3   /* True if currently busy */
205128  #define STMT_COLUMN_NSCAN   4   /* SQLITE_STMTSTATUS_FULLSCAN_STEP */
205129  #define STMT_COLUMN_NSORT   5   /* SQLITE_STMTSTATUS_SORT */
205130  #define STMT_COLUMN_NAIDX   6   /* SQLITE_STMTSTATUS_AUTOINDEX */
205131  #define STMT_COLUMN_NSTEP   7   /* SQLITE_STMTSTATUS_VM_STEP */
205132  #define STMT_COLUMN_REPREP  8   /* SQLITE_STMTSTATUS_REPREPARE */
205133  #define STMT_COLUMN_RUN     9   /* SQLITE_STMTSTATUS_RUN */
205134  #define STMT_COLUMN_MEM    10   /* SQLITE_STMTSTATUS_MEMUSED */
205135  
205136  
205137    rc = sqlite3_declare_vtab(db,
205138       "CREATE TABLE x(sql,ncol,ro,busy,nscan,nsort,naidx,nstep,"
205139                      "reprep,run,mem)");
205140    if( rc==SQLITE_OK ){
205141      pNew = sqlite3_malloc( sizeof(*pNew) );
205142      *ppVtab = (sqlite3_vtab*)pNew;
205143      if( pNew==0 ) return SQLITE_NOMEM;
205144      memset(pNew, 0, sizeof(*pNew));
205145      pNew->db = db;
205146    }
205147    return rc;
205148  }
205149  
205150  /*
205151  ** This method is the destructor for stmt_cursor objects.
205152  */
205153  static int stmtDisconnect(sqlite3_vtab *pVtab){
205154    sqlite3_free(pVtab);
205155    return SQLITE_OK;
205156  }
205157  
205158  /*
205159  ** Constructor for a new stmt_cursor object.
205160  */
205161  static int stmtOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
205162    stmt_cursor *pCur;
205163    pCur = sqlite3_malloc( sizeof(*pCur) );
205164    if( pCur==0 ) return SQLITE_NOMEM;
205165    memset(pCur, 0, sizeof(*pCur));
205166    pCur->db = ((stmt_vtab*)p)->db;
205167    *ppCursor = &pCur->base;
205168    return SQLITE_OK;
205169  }
205170  
205171  /*
205172  ** Destructor for a stmt_cursor.
205173  */
205174  static int stmtClose(sqlite3_vtab_cursor *cur){
205175    sqlite3_free(cur);
205176    return SQLITE_OK;
205177  }
205178  
205179  
205180  /*
205181  ** Advance a stmt_cursor to its next row of output.
205182  */
205183  static int stmtNext(sqlite3_vtab_cursor *cur){
205184    stmt_cursor *pCur = (stmt_cursor*)cur;
205185    pCur->iRowid++;
205186    pCur->pStmt = sqlite3_next_stmt(pCur->db, pCur->pStmt);
205187    return SQLITE_OK;
205188  }
205189  
205190  /*
205191  ** Return values of columns for the row at which the stmt_cursor
205192  ** is currently pointing.
205193  */
205194  static int stmtColumn(
205195    sqlite3_vtab_cursor *cur,   /* The cursor */
205196    sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
205197    int i                       /* Which column to return */
205198  ){
205199    stmt_cursor *pCur = (stmt_cursor*)cur;
205200    switch( i ){
205201      case STMT_COLUMN_SQL: {
205202        sqlite3_result_text(ctx, sqlite3_sql(pCur->pStmt), -1, SQLITE_TRANSIENT);
205203        break;
205204      }
205205      case STMT_COLUMN_NCOL: {
205206        sqlite3_result_int(ctx, sqlite3_column_count(pCur->pStmt));
205207        break;
205208      }
205209      case STMT_COLUMN_RO: {
205210        sqlite3_result_int(ctx, sqlite3_stmt_readonly(pCur->pStmt));
205211        break;
205212      }
205213      case STMT_COLUMN_BUSY: {
205214        sqlite3_result_int(ctx, sqlite3_stmt_busy(pCur->pStmt));
205215        break;
205216      }
205217      case STMT_COLUMN_MEM: {
205218        i = SQLITE_STMTSTATUS_MEMUSED + 
205219              STMT_COLUMN_NSCAN - SQLITE_STMTSTATUS_FULLSCAN_STEP;
205220        /* Fall thru */
205221      }
205222      case STMT_COLUMN_NSCAN:
205223      case STMT_COLUMN_NSORT:
205224      case STMT_COLUMN_NAIDX:
205225      case STMT_COLUMN_NSTEP:
205226      case STMT_COLUMN_REPREP:
205227      case STMT_COLUMN_RUN: {
205228        sqlite3_result_int(ctx, sqlite3_stmt_status(pCur->pStmt,
205229                        i-STMT_COLUMN_NSCAN+SQLITE_STMTSTATUS_FULLSCAN_STEP, 0));
205230        break;
205231      }
205232    }
205233    return SQLITE_OK;
205234  }
205235  
205236  /*
205237  ** Return the rowid for the current row.  In this implementation, the
205238  ** rowid is the same as the output value.
205239  */
205240  static int stmtRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
205241    stmt_cursor *pCur = (stmt_cursor*)cur;
205242    *pRowid = pCur->iRowid;
205243    return SQLITE_OK;
205244  }
205245  
205246  /*
205247  ** Return TRUE if the cursor has been moved off of the last
205248  ** row of output.
205249  */
205250  static int stmtEof(sqlite3_vtab_cursor *cur){
205251    stmt_cursor *pCur = (stmt_cursor*)cur;
205252    return pCur->pStmt==0;
205253  }
205254  
205255  /*
205256  ** This method is called to "rewind" the stmt_cursor object back
205257  ** to the first row of output.  This method is always called at least
205258  ** once prior to any call to stmtColumn() or stmtRowid() or 
205259  ** stmtEof().
205260  */
205261  static int stmtFilter(
205262    sqlite3_vtab_cursor *pVtabCursor, 
205263    int idxNum, const char *idxStr,
205264    int argc, sqlite3_value **argv
205265  ){
205266    stmt_cursor *pCur = (stmt_cursor *)pVtabCursor;
205267    pCur->pStmt = 0;
205268    pCur->iRowid = 0;
205269    return stmtNext(pVtabCursor);
205270  }
205271  
205272  /*
205273  ** SQLite will invoke this method one or more times while planning a query
205274  ** that uses the stmt virtual table.  This routine needs to create
205275  ** a query plan for each invocation and compute an estimated cost for that
205276  ** plan.
205277  */
205278  static int stmtBestIndex(
205279    sqlite3_vtab *tab,
205280    sqlite3_index_info *pIdxInfo
205281  ){
205282    pIdxInfo->estimatedCost = (double)500;
205283    pIdxInfo->estimatedRows = 500;
205284    return SQLITE_OK;
205285  }
205286  
205287  /*
205288  ** This following structure defines all the methods for the 
205289  ** stmt virtual table.
205290  */
205291  static sqlite3_module stmtModule = {
205292    0,                         /* iVersion */
205293    0,                         /* xCreate */
205294    stmtConnect,               /* xConnect */
205295    stmtBestIndex,             /* xBestIndex */
205296    stmtDisconnect,            /* xDisconnect */
205297    0,                         /* xDestroy */
205298    stmtOpen,                  /* xOpen - open a cursor */
205299    stmtClose,                 /* xClose - close a cursor */
205300    stmtFilter,                /* xFilter - configure scan constraints */
205301    stmtNext,                  /* xNext - advance a cursor */
205302    stmtEof,                   /* xEof - check for end of scan */
205303    stmtColumn,                /* xColumn - read data */
205304    stmtRowid,                 /* xRowid - read data */
205305    0,                         /* xUpdate */
205306    0,                         /* xBegin */
205307    0,                         /* xSync */
205308    0,                         /* xCommit */
205309    0,                         /* xRollback */
205310    0,                         /* xFindMethod */
205311    0,                         /* xRename */
205312    0,                         /* xSavepoint */
205313    0,                         /* xRelease */
205314    0,                         /* xRollbackTo */
205315  };
205316  
205317  #endif /* SQLITE_OMIT_VIRTUALTABLE */
205318  
205319  SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3 *db){
205320    int rc = SQLITE_OK;
205321  #ifndef SQLITE_OMIT_VIRTUALTABLE
205322    rc = sqlite3_create_module(db, "sqlite_stmt", &stmtModule, 0);
205323  #endif
205324    return rc;
205325  }
205326  
205327  #ifndef SQLITE_CORE
205328  #ifdef _WIN32
205329  __declspec(dllexport)
205330  #endif
205331  SQLITE_API int sqlite3_stmt_init(
205332    sqlite3 *db, 
205333    char **pzErrMsg, 
205334    const sqlite3_api_routines *pApi
205335  ){
205336    int rc = SQLITE_OK;
205337    SQLITE_EXTENSION_INIT2(pApi);
205338  #ifndef SQLITE_OMIT_VIRTUALTABLE
205339    rc = sqlite3StmtVtabInit(db);
205340  #endif
205341    return rc;
205342  }
205343  #endif /* SQLITE_CORE */
205344  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) */
205345  
205346  /************** End of stmt.c ************************************************/
205347  #if __LINE__!=205346
205348  #undef SQLITE_SOURCE_ID
205349  #define SQLITE_SOURCE_ID      "2017-10-24 18:55:49 1a584e499906b5c87ec7d43d4abce641fdf017c42125b083109bc77c4de4alt2"
205350  #endif
205351  /* Return the source-id for this library */
205352  SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
205353  /************************** End of sqlite3.c ******************************/
205354  #else // USE_LIBSQLITE3
205355   // If users really want to link against the system sqlite3 we
205356  // need to make this file a noop.
205357   #endif